Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(235)

Side by Side Diff: third_party/sqlite/sqlite-src-3100200/src/select.c

Issue 1610543003: [sql] Import reference version of SQLite 3.10.2. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 4 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* 1 /*
2 ** 2001 September 15 2 ** 2001 September 15
3 ** 3 **
4 ** The author disclaims copyright to this source code. In place of 4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing: 5 ** a legal notice, here is a blessing:
6 ** 6 **
7 ** May you do good and not evil. 7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others. 8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give. 9 ** May you share freely, never taking more than you give.
10 ** 10 **
11 ************************************************************************* 11 *************************************************************************
12 ** This file contains C code routines that are called by the parser 12 ** This file contains C code routines that are called by the parser
13 ** to handle SELECT statements in SQLite. 13 ** to handle SELECT statements in SQLite.
14 */ 14 */
15 #include "sqliteInt.h" 15 #include "sqliteInt.h"
16 16
17 /* 17 /*
18 ** Trace output macros 18 ** Trace output macros
19 */ 19 */
20 #if SELECTTRACE_ENABLED 20 #if SELECTTRACE_ENABLED
21 /***/ int sqlite3SelectTrace = 0; 21 /***/ int sqlite3SelectTrace = 0;
22 # define SELECTTRACE(K,P,S,X) \ 22 # define SELECTTRACE(K,P,S,X) \
23 if(sqlite3SelectTrace&(K)) \ 23 if(sqlite3SelectTrace&(K)) \
24 sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",(S)->zSelName,(S)) ,\ 24 sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
25 (S)->zSelName,(S)),\
25 sqlite3DebugPrintf X 26 sqlite3DebugPrintf X
26 #else 27 #else
27 # define SELECTTRACE(K,P,S,X) 28 # define SELECTTRACE(K,P,S,X)
28 #endif 29 #endif
29 30
30 31
31 /* 32 /*
32 ** An instance of the following object is used to record information about 33 ** An instance of the following object is used to record information about
33 ** how to process the DISTINCT keyword, to simplify passing that information 34 ** how to process the DISTINCT keyword, to simplify passing that information
34 ** into the selectInnerLoop() routine. 35 ** into the selectInnerLoop() routine.
(...skipping 11 matching lines...) Expand all
46 ** the ORDER BY (or GROUP BY) clause of query is being coded. 47 ** the ORDER BY (or GROUP BY) clause of query is being coded.
47 */ 48 */
48 typedef struct SortCtx SortCtx; 49 typedef struct SortCtx SortCtx;
49 struct SortCtx { 50 struct SortCtx {
50 ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */ 51 ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
51 int nOBSat; /* Number of ORDER BY terms satisfied by indices */ 52 int nOBSat; /* Number of ORDER BY terms satisfied by indices */
52 int iECursor; /* Cursor number for the sorter */ 53 int iECursor; /* Cursor number for the sorter */
53 int regReturn; /* Register holding block-output return address */ 54 int regReturn; /* Register holding block-output return address */
54 int labelBkOut; /* Start label for the block-output subroutine */ 55 int labelBkOut; /* Start label for the block-output subroutine */
55 int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */ 56 int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
57 int labelDone; /* Jump here when done, ex: LIMIT reached */
56 u8 sortFlags; /* Zero or more SORTFLAG_* bits */ 58 u8 sortFlags; /* Zero or more SORTFLAG_* bits */
57 }; 59 };
58 #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */ 60 #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
59 61
60 /* 62 /*
61 ** Delete all the content of a Select structure but do not deallocate 63 ** Delete all the content of a Select structure. Deallocate the structure
62 ** the select structure itself. 64 ** itself only if bFree is true.
63 */ 65 */
64 static void clearSelect(sqlite3 *db, Select *p){ 66 static void clearSelect(sqlite3 *db, Select *p, int bFree){
65 sqlite3ExprListDelete(db, p->pEList); 67 while( p ){
66 sqlite3SrcListDelete(db, p->pSrc); 68 Select *pPrior = p->pPrior;
67 sqlite3ExprDelete(db, p->pWhere); 69 sqlite3ExprListDelete(db, p->pEList);
68 sqlite3ExprListDelete(db, p->pGroupBy); 70 sqlite3SrcListDelete(db, p->pSrc);
69 sqlite3ExprDelete(db, p->pHaving); 71 sqlite3ExprDelete(db, p->pWhere);
70 sqlite3ExprListDelete(db, p->pOrderBy); 72 sqlite3ExprListDelete(db, p->pGroupBy);
71 sqlite3SelectDelete(db, p->pPrior); 73 sqlite3ExprDelete(db, p->pHaving);
72 sqlite3ExprDelete(db, p->pLimit); 74 sqlite3ExprListDelete(db, p->pOrderBy);
73 sqlite3ExprDelete(db, p->pOffset); 75 sqlite3ExprDelete(db, p->pLimit);
74 sqlite3WithDelete(db, p->pWith); 76 sqlite3ExprDelete(db, p->pOffset);
77 sqlite3WithDelete(db, p->pWith);
78 if( bFree ) sqlite3DbFree(db, p);
79 p = pPrior;
80 bFree = 1;
81 }
75 } 82 }
76 83
77 /* 84 /*
78 ** Initialize a SelectDest structure. 85 ** Initialize a SelectDest structure.
79 */ 86 */
80 void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ 87 void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
81 pDest->eDest = (u8)eDest; 88 pDest->eDest = (u8)eDest;
82 pDest->iSDParm = iParm; 89 pDest->iSDParm = iParm;
83 pDest->affSdst = 0; 90 pDest->affSdst = 0;
84 pDest->iSdst = 0; 91 pDest->iSdst = 0;
(...skipping 14 matching lines...) Expand all
99 Expr *pHaving, /* the HAVING clause */ 106 Expr *pHaving, /* the HAVING clause */
100 ExprList *pOrderBy, /* the ORDER BY clause */ 107 ExprList *pOrderBy, /* the ORDER BY clause */
101 u16 selFlags, /* Flag parameters, such as SF_Distinct */ 108 u16 selFlags, /* Flag parameters, such as SF_Distinct */
102 Expr *pLimit, /* LIMIT value. NULL means not used */ 109 Expr *pLimit, /* LIMIT value. NULL means not used */
103 Expr *pOffset /* OFFSET value. NULL means no offset */ 110 Expr *pOffset /* OFFSET value. NULL means no offset */
104 ){ 111 ){
105 Select *pNew; 112 Select *pNew;
106 Select standin; 113 Select standin;
107 sqlite3 *db = pParse->db; 114 sqlite3 *db = pParse->db;
108 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 115 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
109 assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
110 if( pNew==0 ){ 116 if( pNew==0 ){
111 assert( db->mallocFailed ); 117 assert( db->mallocFailed );
112 pNew = &standin; 118 pNew = &standin;
113 memset(pNew, 0, sizeof(*pNew)); 119 memset(pNew, 0, sizeof(*pNew));
114 } 120 }
115 if( pEList==0 ){ 121 if( pEList==0 ){
116 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0)); 122 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
117 } 123 }
118 pNew->pEList = pEList; 124 pNew->pEList = pEList;
119 if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc)); 125 if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
120 pNew->pSrc = pSrc; 126 pNew->pSrc = pSrc;
121 pNew->pWhere = pWhere; 127 pNew->pWhere = pWhere;
122 pNew->pGroupBy = pGroupBy; 128 pNew->pGroupBy = pGroupBy;
123 pNew->pHaving = pHaving; 129 pNew->pHaving = pHaving;
124 pNew->pOrderBy = pOrderBy; 130 pNew->pOrderBy = pOrderBy;
125 pNew->selFlags = selFlags; 131 pNew->selFlags = selFlags;
126 pNew->op = TK_SELECT; 132 pNew->op = TK_SELECT;
127 pNew->pLimit = pLimit; 133 pNew->pLimit = pLimit;
128 pNew->pOffset = pOffset; 134 pNew->pOffset = pOffset;
129 assert( pOffset==0 || pLimit!=0 ); 135 assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
130 pNew->addrOpenEphm[0] = -1; 136 pNew->addrOpenEphm[0] = -1;
131 pNew->addrOpenEphm[1] = -1; 137 pNew->addrOpenEphm[1] = -1;
132 if( db->mallocFailed ) { 138 if( db->mallocFailed ) {
133 clearSelect(db, pNew); 139 clearSelect(db, pNew, pNew!=&standin);
134 if( pNew!=&standin ) sqlite3DbFree(db, pNew);
135 pNew = 0; 140 pNew = 0;
136 }else{ 141 }else{
137 assert( pNew->pSrc!=0 || pParse->nErr>0 ); 142 assert( pNew->pSrc!=0 || pParse->nErr>0 );
138 } 143 }
139 assert( pNew!=&standin ); 144 assert( pNew!=&standin );
140 return pNew; 145 return pNew;
141 } 146 }
142 147
143 #if SELECTTRACE_ENABLED 148 #if SELECTTRACE_ENABLED
144 /* 149 /*
145 ** Set the name of a Select object 150 ** Set the name of a Select object
146 */ 151 */
147 void sqlite3SelectSetName(Select *p, const char *zName){ 152 void sqlite3SelectSetName(Select *p, const char *zName){
148 if( p && zName ){ 153 if( p && zName ){
149 sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName); 154 sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
150 } 155 }
151 } 156 }
152 #endif 157 #endif
153 158
154 159
155 /* 160 /*
156 ** Delete the given Select structure and all of its substructures. 161 ** Delete the given Select structure and all of its substructures.
157 */ 162 */
158 void sqlite3SelectDelete(sqlite3 *db, Select *p){ 163 void sqlite3SelectDelete(sqlite3 *db, Select *p){
159 if( p ){ 164 clearSelect(db, p, 1);
160 clearSelect(db, p);
161 sqlite3DbFree(db, p);
162 }
163 } 165 }
164 166
165 /* 167 /*
166 ** Return a pointer to the right-most SELECT statement in a compound. 168 ** Return a pointer to the right-most SELECT statement in a compound.
167 */ 169 */
168 static Select *findRightmost(Select *p){ 170 static Select *findRightmost(Select *p){
169 while( p->pNext ) p = p->pNext; 171 while( p->pNext ) p = p->pNext;
170 return p; 172 return p;
171 } 173 }
172 174
(...skipping 185 matching lines...) Expand 10 before | Expand all | Expand 10 after
358 ** defer the handling of t1.x=5, it will be processed immediately 360 ** defer the handling of t1.x=5, it will be processed immediately
359 ** after the t1 loop and rows with t1.x!=5 will never appear in 361 ** after the t1 loop and rows with t1.x!=5 will never appear in
360 ** the output, which is incorrect. 362 ** the output, which is incorrect.
361 */ 363 */
362 static void setJoinExpr(Expr *p, int iTable){ 364 static void setJoinExpr(Expr *p, int iTable){
363 while( p ){ 365 while( p ){
364 ExprSetProperty(p, EP_FromJoin); 366 ExprSetProperty(p, EP_FromJoin);
365 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); 367 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
366 ExprSetVVAProperty(p, EP_NoReduce); 368 ExprSetVVAProperty(p, EP_NoReduce);
367 p->iRightJoinTable = (i16)iTable; 369 p->iRightJoinTable = (i16)iTable;
370 if( p->op==TK_FUNCTION && p->x.pList ){
371 int i;
372 for(i=0; i<p->x.pList->nExpr; i++){
373 setJoinExpr(p->x.pList->a[i].pExpr, iTable);
374 }
375 }
368 setJoinExpr(p->pLeft, iTable); 376 setJoinExpr(p->pLeft, iTable);
369 p = p->pRight; 377 p = p->pRight;
370 } 378 }
371 } 379 }
372 380
373 /* 381 /*
374 ** This routine processes the join information for a SELECT statement. 382 ** This routine processes the join information for a SELECT statement.
375 ** ON and USING clauses are converted into extra terms of the WHERE clause. 383 ** ON and USING clauses are converted into extra terms of the WHERE clause.
376 ** NATURAL joins also create extra WHERE clause terms. 384 ** NATURAL joins also create extra WHERE clause terms.
377 ** 385 **
(...skipping 14 matching lines...) Expand all
392 400
393 pSrc = p->pSrc; 401 pSrc = p->pSrc;
394 pLeft = &pSrc->a[0]; 402 pLeft = &pSrc->a[0];
395 pRight = &pLeft[1]; 403 pRight = &pLeft[1];
396 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 404 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
397 Table *pLeftTab = pLeft->pTab; 405 Table *pLeftTab = pLeft->pTab;
398 Table *pRightTab = pRight->pTab; 406 Table *pRightTab = pRight->pTab;
399 int isOuter; 407 int isOuter;
400 408
401 if( NEVER(pLeftTab==0 || pRightTab==0) ) continue; 409 if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
402 isOuter = (pRight->jointype & JT_OUTER)!=0; 410 isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
403 411
404 /* When the NATURAL keyword is present, add WHERE clause terms for 412 /* When the NATURAL keyword is present, add WHERE clause terms for
405 ** every column that the two tables have in common. 413 ** every column that the two tables have in common.
406 */ 414 */
407 if( pRight->jointype & JT_NATURAL ){ 415 if( pRight->fg.jointype & JT_NATURAL ){
408 if( pRight->pOn || pRight->pUsing ){ 416 if( pRight->pOn || pRight->pUsing ){
409 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 417 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
410 "an ON or USING clause", 0); 418 "an ON or USING clause", 0);
411 return 1; 419 return 1;
412 } 420 }
413 for(j=0; j<pRightTab->nCol; j++){ 421 for(j=0; j<pRightTab->nCol; j++){
414 char *zName; /* Name of column in the right table */ 422 char *zName; /* Name of column in the right table */
415 int iLeft; /* Matching left table */ 423 int iLeft; /* Matching left table */
416 int iLeftCol; /* Matching column in the left table */ 424 int iLeftCol; /* Matching column in the left table */
417 425
(...skipping 64 matching lines...) Expand 10 before | Expand all | Expand 10 after
482 490
483 /* 491 /*
484 ** Generate code that will push the record in registers regData 492 ** Generate code that will push the record in registers regData
485 ** through regData+nData-1 onto the sorter. 493 ** through regData+nData-1 onto the sorter.
486 */ 494 */
487 static void pushOntoSorter( 495 static void pushOntoSorter(
488 Parse *pParse, /* Parser context */ 496 Parse *pParse, /* Parser context */
489 SortCtx *pSort, /* Information about the ORDER BY clause */ 497 SortCtx *pSort, /* Information about the ORDER BY clause */
490 Select *pSelect, /* The whole SELECT statement */ 498 Select *pSelect, /* The whole SELECT statement */
491 int regData, /* First register holding data to be sorted */ 499 int regData, /* First register holding data to be sorted */
500 int regOrigData, /* First register holding data before packing */
492 int nData, /* Number of elements in the data array */ 501 int nData, /* Number of elements in the data array */
493 int nPrefixReg /* No. of reg prior to regData available for use */ 502 int nPrefixReg /* No. of reg prior to regData available for use */
494 ){ 503 ){
495 Vdbe *v = pParse->pVdbe; /* Stmt under construction */ 504 Vdbe *v = pParse->pVdbe; /* Stmt under construction */
496 int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0); 505 int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
497 int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ 506 int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
498 int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ 507 int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
499 int regBase; /* Regs for sorter record */ 508 int regBase; /* Regs for sorter record */
500 int regRecord = ++pParse->nMem; /* Assembled sorter record */ 509 int regRecord = ++pParse->nMem; /* Assembled sorter record */
501 int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ 510 int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
502 int op; /* Opcode to add sorter record to sorter */ 511 int op; /* Opcode to add sorter record to sorter */
512 int iLimit; /* LIMIT counter */
503 513
504 assert( bSeq==0 || bSeq==1 ); 514 assert( bSeq==0 || bSeq==1 );
515 assert( nData==1 || regData==regOrigData );
505 if( nPrefixReg ){ 516 if( nPrefixReg ){
506 assert( nPrefixReg==nExpr+bSeq ); 517 assert( nPrefixReg==nExpr+bSeq );
507 regBase = regData - nExpr - bSeq; 518 regBase = regData - nExpr - bSeq;
508 }else{ 519 }else{
509 regBase = pParse->nMem + 1; 520 regBase = pParse->nMem + 1;
510 pParse->nMem += nBase; 521 pParse->nMem += nBase;
511 } 522 }
512 sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, SQLITE_ECEL_DUP); 523 assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
524 iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
525 pSort->labelDone = sqlite3VdbeMakeLabel(v);
526 sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
527 SQLITE_ECEL_DUP|SQLITE_ECEL_REF);
513 if( bSeq ){ 528 if( bSeq ){
514 sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); 529 sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
515 } 530 }
516 if( nPrefixReg==0 ){ 531 if( nPrefixReg==0 ){
517 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); 532 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
518 } 533 }
519
520 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord); 534 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
521 if( nOBSat>0 ){ 535 if( nOBSat>0 ){
522 int regPrevKey; /* The first nOBSat columns of the previous row */ 536 int regPrevKey; /* The first nOBSat columns of the previous row */
523 int addrFirst; /* Address of the OP_IfNot opcode */ 537 int addrFirst; /* Address of the OP_IfNot opcode */
524 int addrJmp; /* Address of the OP_Jump opcode */ 538 int addrJmp; /* Address of the OP_Jump opcode */
525 VdbeOp *pOp; /* Opcode that opens the sorter */ 539 VdbeOp *pOp; /* Opcode that opens the sorter */
526 int nKey; /* Number of sorting key columns, including OP_Sequence */ 540 int nKey; /* Number of sorting key columns, including OP_Sequence */
527 KeyInfo *pKI; /* Original KeyInfo on the sorter table */ 541 KeyInfo *pKI; /* Original KeyInfo on the sorter table */
528 542
529 regPrevKey = pParse->nMem+1; 543 regPrevKey = pParse->nMem+1;
530 pParse->nMem += pSort->nOBSat; 544 pParse->nMem += pSort->nOBSat;
531 nKey = nExpr - pSort->nOBSat + bSeq; 545 nKey = nExpr - pSort->nOBSat + bSeq;
532 if( bSeq ){ 546 if( bSeq ){
533 addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 547 addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
534 }else{ 548 }else{
535 addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); 549 addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
536 } 550 }
537 VdbeCoverage(v); 551 VdbeCoverage(v);
538 sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); 552 sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
539 pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 553 pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
540 if( pParse->db->mallocFailed ) return; 554 if( pParse->db->mallocFailed ) return;
541 pOp->p2 = nKey + nData; 555 pOp->p2 = nKey + nData;
542 pKI = pOp->p4.pKeyInfo; 556 pKI = pOp->p4.pKeyInfo;
543 memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */ 557 memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
544 sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); 558 sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
545 pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, 1); 559 testcase( pKI->nXField>2 );
560 pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
561 pKI->nXField-1);
546 addrJmp = sqlite3VdbeCurrentAddr(v); 562 addrJmp = sqlite3VdbeCurrentAddr(v);
547 sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); 563 sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
548 pSort->labelBkOut = sqlite3VdbeMakeLabel(v); 564 pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
549 pSort->regReturn = ++pParse->nMem; 565 pSort->regReturn = ++pParse->nMem;
550 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 566 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
551 sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); 567 sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
568 if( iLimit ){
569 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
570 VdbeCoverage(v);
571 }
552 sqlite3VdbeJumpHere(v, addrFirst); 572 sqlite3VdbeJumpHere(v, addrFirst);
553 sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); 573 sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
554 sqlite3VdbeJumpHere(v, addrJmp); 574 sqlite3VdbeJumpHere(v, addrJmp);
555 } 575 }
556 if( pSort->sortFlags & SORTFLAG_UseSorter ){ 576 if( pSort->sortFlags & SORTFLAG_UseSorter ){
557 op = OP_SorterInsert; 577 op = OP_SorterInsert;
558 }else{ 578 }else{
559 op = OP_IdxInsert; 579 op = OP_IdxInsert;
560 } 580 }
561 sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord); 581 sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
562 if( pSelect->iLimit ){ 582 if( iLimit ){
563 int addr1, addr2; 583 int addr;
564 int iLimit; 584 addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
565 if( pSelect->iOffset ){
566 iLimit = pSelect->iOffset+1;
567 }else{
568 iLimit = pSelect->iLimit;
569 }
570 addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); VdbeCoverage(v);
571 sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
572 addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
573 sqlite3VdbeJumpHere(v, addr1);
574 sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor); 585 sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
575 sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor); 586 sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
576 sqlite3VdbeJumpHere(v, addr2); 587 sqlite3VdbeJumpHere(v, addr);
577 } 588 }
578 } 589 }
579 590
580 /* 591 /*
581 ** Add code to implement the OFFSET 592 ** Add code to implement the OFFSET
582 */ 593 */
583 static void codeOffset( 594 static void codeOffset(
584 Vdbe *v, /* Generate code into this VM */ 595 Vdbe *v, /* Generate code into this VM */
585 int iOffset, /* Register holding the offset counter */ 596 int iOffset, /* Register holding the offset counter */
586 int iContinue /* Jump here to skip the current record */ 597 int iContinue /* Jump here to skip the current record */
587 ){ 598 ){
588 if( iOffset>0 ){ 599 if( iOffset>0 ){
589 int addr; 600 sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
590 addr = sqlite3VdbeAddOp3(v, OP_IfNeg, iOffset, 0, -1); VdbeCoverage(v); 601 VdbeComment((v, "OFFSET"));
591 sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
592 VdbeComment((v, "skip OFFSET records"));
593 sqlite3VdbeJumpHere(v, addr);
594 } 602 }
595 } 603 }
596 604
597 /* 605 /*
598 ** Add code that will check to make sure the N registers starting at iMem 606 ** Add code that will check to make sure the N registers starting at iMem
599 ** form a distinct entry. iTab is a sorting index that holds previously 607 ** form a distinct entry. iTab is a sorting index that holds previously
600 ** seen combinations of the N values. A new entry is made in iTab 608 ** seen combinations of the N values. A new entry is made in iTab
601 ** if the current N values are new. 609 ** if the current N values are new.
602 ** 610 **
603 ** A jump to addrRepeat is made and the N+1 values are popped from the 611 ** A jump to addrRepeat is made and the N+1 values are popped from the
(...skipping 103 matching lines...) Expand 10 before | Expand all | Expand 10 after
707 regResult = pDest->iSdst; 715 regResult = pDest->iSdst;
708 if( srcTab>=0 ){ 716 if( srcTab>=0 ){
709 for(i=0; i<nResultCol; i++){ 717 for(i=0; i<nResultCol; i++){
710 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 718 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
711 VdbeComment((v, "%s", pEList->a[i].zName)); 719 VdbeComment((v, "%s", pEList->a[i].zName));
712 } 720 }
713 }else if( eDest!=SRT_Exists ){ 721 }else if( eDest!=SRT_Exists ){
714 /* If the destination is an EXISTS(...) expression, the actual 722 /* If the destination is an EXISTS(...) expression, the actual
715 ** values returned by the SELECT are not required. 723 ** values returned by the SELECT are not required.
716 */ 724 */
717 sqlite3ExprCodeExprList(pParse, pEList, regResult, 725 u8 ecelFlags;
718 (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0); 726 if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
727 ecelFlags = SQLITE_ECEL_DUP;
728 }else{
729 ecelFlags = 0;
730 }
731 sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
719 } 732 }
720 733
721 /* If the DISTINCT keyword was present on the SELECT statement 734 /* If the DISTINCT keyword was present on the SELECT statement
722 ** and this row has been seen before, then do not make this row 735 ** and this row has been seen before, then do not make this row
723 ** part of the result. 736 ** part of the result.
724 */ 737 */
725 if( hasDistinct ){ 738 if( hasDistinct ){
726 switch( pDistinct->eTnctType ){ 739 switch( pDistinct->eTnctType ){
727 case WHERE_DISTINCT_ORDERED: { 740 case WHERE_DISTINCT_ORDERED: {
728 VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ 741 VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
763 break; 776 break;
764 } 777 }
765 778
766 case WHERE_DISTINCT_UNIQUE: { 779 case WHERE_DISTINCT_UNIQUE: {
767 sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 780 sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
768 break; 781 break;
769 } 782 }
770 783
771 default: { 784 default: {
772 assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); 785 assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
773 codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResul t); 786 codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
787 regResult);
774 break; 788 break;
775 } 789 }
776 } 790 }
777 if( pSort==0 ){ 791 if( pSort==0 ){
778 codeOffset(v, p->iOffset, iContinue); 792 codeOffset(v, p->iOffset, iContinue);
779 } 793 }
780 } 794 }
781 795
782 switch( eDest ){ 796 switch( eDest ){
783 /* In this mode, write each query result to the key of the temporary 797 /* In this mode, write each query result to the key of the temporary
(...skipping 21 matching lines...) Expand all
805 819
806 /* Store the result as data using a unique key. 820 /* Store the result as data using a unique key.
807 */ 821 */
808 case SRT_Fifo: 822 case SRT_Fifo:
809 case SRT_DistFifo: 823 case SRT_DistFifo:
810 case SRT_Table: 824 case SRT_Table:
811 case SRT_EphemTab: { 825 case SRT_EphemTab: {
812 int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); 826 int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
813 testcase( eDest==SRT_Table ); 827 testcase( eDest==SRT_Table );
814 testcase( eDest==SRT_EphemTab ); 828 testcase( eDest==SRT_EphemTab );
829 testcase( eDest==SRT_Fifo );
830 testcase( eDest==SRT_DistFifo );
815 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); 831 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
816 #ifndef SQLITE_OMIT_CTE 832 #ifndef SQLITE_OMIT_CTE
817 if( eDest==SRT_DistFifo ){ 833 if( eDest==SRT_DistFifo ){
818 /* If the destination is DistFifo, then cursor (iParm+1) is open 834 /* If the destination is DistFifo, then cursor (iParm+1) is open
819 ** on an ephemeral index. If the current row is already present 835 ** on an ephemeral index. If the current row is already present
820 ** in the index, do not write it to the output. If not, add the 836 ** in the index, do not write it to the output. If not, add the
821 ** current row to the index and proceed with writing it to the 837 ** current row to the index and proceed with writing it to the
822 ** output table as well. */ 838 ** output table as well. */
823 int addr = sqlite3VdbeCurrentAddr(v) + 4; 839 int addr = sqlite3VdbeCurrentAddr(v) + 4;
824 sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v) ; 840 sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
841 VdbeCoverage(v);
825 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1); 842 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
826 assert( pSort==0 ); 843 assert( pSort==0 );
827 } 844 }
828 #endif 845 #endif
829 if( pSort ){ 846 if( pSort ){
830 pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, 1, nPrefixReg); 847 pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
831 }else{ 848 }else{
832 int r2 = sqlite3GetTempReg(pParse); 849 int r2 = sqlite3GetTempReg(pParse);
833 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 850 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
834 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 851 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
835 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 852 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
836 sqlite3ReleaseTempReg(pParse, r2); 853 sqlite3ReleaseTempReg(pParse, r2);
837 } 854 }
838 sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); 855 sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
839 break; 856 break;
840 } 857 }
841 858
842 #ifndef SQLITE_OMIT_SUBQUERY 859 #ifndef SQLITE_OMIT_SUBQUERY
843 /* If we are creating a set for an "expr IN (SELECT ...)" construct, 860 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
844 ** then there should be a single item on the stack. Write this 861 ** then there should be a single item on the stack. Write this
845 ** item into the set table with bogus data. 862 ** item into the set table with bogus data.
846 */ 863 */
847 case SRT_Set: { 864 case SRT_Set: {
848 assert( nResultCol==1 ); 865 assert( nResultCol==1 );
849 pDest->affSdst = 866 pDest->affSdst =
850 sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst); 867 sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
851 if( pSort ){ 868 if( pSort ){
852 /* At first glance you would think we could optimize out the 869 /* At first glance you would think we could optimize out the
853 ** ORDER BY in this case since the order of entries in the set 870 ** ORDER BY in this case since the order of entries in the set
854 ** does not matter. But there might be a LIMIT clause, in which 871 ** does not matter. But there might be a LIMIT clause, in which
855 ** case the order does matter */ 872 ** case the order does matter */
856 pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg); 873 pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
857 }else{ 874 }else{
858 int r1 = sqlite3GetTempReg(pParse); 875 int r1 = sqlite3GetTempReg(pParse);
859 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1); 876 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
860 sqlite3ExprCacheAffinityChange(pParse, regResult, 1); 877 sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
861 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 878 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
862 sqlite3ReleaseTempReg(pParse, r1); 879 sqlite3ReleaseTempReg(pParse, r1);
863 } 880 }
864 break; 881 break;
865 } 882 }
866 883
867 /* If any row exist in the result set, record that fact and abort. 884 /* If any row exist in the result set, record that fact and abort.
868 */ 885 */
869 case SRT_Exists: { 886 case SRT_Exists: {
870 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 887 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
871 /* The LIMIT clause will terminate the loop for us */ 888 /* The LIMIT clause will terminate the loop for us */
872 break; 889 break;
873 } 890 }
874 891
875 /* If this is a scalar select that is part of an expression, then 892 /* If this is a scalar select that is part of an expression, then
876 ** store the results in the appropriate memory cell and break out 893 ** store the results in the appropriate memory cell and break out
877 ** of the scan loop. 894 ** of the scan loop.
878 */ 895 */
879 case SRT_Mem: { 896 case SRT_Mem: {
880 assert( nResultCol==1 ); 897 assert( nResultCol==1 );
881 if( pSort ){ 898 if( pSort ){
882 pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg); 899 pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
883 }else{ 900 }else{
884 assert( regResult==iParm ); 901 assert( regResult==iParm );
885 /* The LIMIT clause will jump out of the loop for us */ 902 /* The LIMIT clause will jump out of the loop for us */
886 } 903 }
887 break; 904 break;
888 } 905 }
889 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 906 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
890 907
891 case SRT_Coroutine: /* Send data to a co-routine */ 908 case SRT_Coroutine: /* Send data to a co-routine */
892 case SRT_Output: { /* Return the results */ 909 case SRT_Output: { /* Return the results */
893 testcase( eDest==SRT_Coroutine ); 910 testcase( eDest==SRT_Coroutine );
894 testcase( eDest==SRT_Output ); 911 testcase( eDest==SRT_Output );
895 if( pSort ){ 912 if( pSort ){
896 pushOntoSorter(pParse, pSort, p, regResult, nResultCol, nPrefixReg); 913 pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
914 nPrefixReg);
897 }else if( eDest==SRT_Coroutine ){ 915 }else if( eDest==SRT_Coroutine ){
898 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 916 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
899 }else{ 917 }else{
900 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); 918 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
901 sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); 919 sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
902 } 920 }
903 break; 921 break;
904 } 922 }
905 923
906 #ifndef SQLITE_OMIT_CTE 924 #ifndef SQLITE_OMIT_CTE
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
963 break; 981 break;
964 } 982 }
965 #endif 983 #endif
966 } 984 }
967 985
968 /* Jump to the end of the loop if the LIMIT is reached. Except, if 986 /* Jump to the end of the loop if the LIMIT is reached. Except, if
969 ** there is a sorter, in which case the sorter has already limited 987 ** there is a sorter, in which case the sorter has already limited
970 ** the output for us. 988 ** the output for us.
971 */ 989 */
972 if( pSort==0 && p->iLimit ){ 990 if( pSort==0 && p->iLimit ){
973 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v); 991 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
974 } 992 }
975 } 993 }
976 994
977 /* 995 /*
978 ** Allocate a KeyInfo object sufficient for an index of N key columns and 996 ** Allocate a KeyInfo object sufficient for an index of N key columns and
979 ** X extra columns. 997 ** X extra columns.
980 */ 998 */
981 KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ 999 KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
982 KeyInfo *p = sqlite3DbMallocZero(0, 1000 KeyInfo *p = sqlite3DbMallocZero(0,
983 sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1)); 1001 sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
(...skipping 62 matching lines...) Expand 10 before | Expand all | Expand 10 after
1046 int iStart, /* Begin with this column of pList */ 1064 int iStart, /* Begin with this column of pList */
1047 int nExtra /* Add this many extra columns to the end */ 1065 int nExtra /* Add this many extra columns to the end */
1048 ){ 1066 ){
1049 int nExpr; 1067 int nExpr;
1050 KeyInfo *pInfo; 1068 KeyInfo *pInfo;
1051 struct ExprList_item *pItem; 1069 struct ExprList_item *pItem;
1052 sqlite3 *db = pParse->db; 1070 sqlite3 *db = pParse->db;
1053 int i; 1071 int i;
1054 1072
1055 nExpr = pList->nExpr; 1073 nExpr = pList->nExpr;
1056 pInfo = sqlite3KeyInfoAlloc(db, nExpr+nExtra-iStart, 1); 1074 pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
1057 if( pInfo ){ 1075 if( pInfo ){
1058 assert( sqlite3KeyInfoIsWriteable(pInfo) ); 1076 assert( sqlite3KeyInfoIsWriteable(pInfo) );
1059 for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){ 1077 for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
1060 CollSeq *pColl; 1078 CollSeq *pColl;
1061 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 1079 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
1062 if( !pColl ) pColl = db->pDfltColl; 1080 if( !pColl ) pColl = db->pDfltColl;
1063 pInfo->aColl[i-iStart] = pColl; 1081 pInfo->aColl[i-iStart] = pColl;
1064 pInfo->aSortOrder[i-iStart] = pItem->sortOrder; 1082 pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
1065 } 1083 }
1066 } 1084 }
1067 return pInfo; 1085 return pInfo;
1068 } 1086 }
1069 1087
1070 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1071 /* 1088 /*
1072 ** Name of the connection operator, used for error messages. 1089 ** Name of the connection operator, used for error messages.
1073 */ 1090 */
1074 static const char *selectOpName(int id){ 1091 static const char *selectOpName(int id){
1075 char *z; 1092 char *z;
1076 switch( id ){ 1093 switch( id ){
1077 case TK_ALL: z = "UNION ALL"; break; 1094 case TK_ALL: z = "UNION ALL"; break;
1078 case TK_INTERSECT: z = "INTERSECT"; break; 1095 case TK_INTERSECT: z = "INTERSECT"; break;
1079 case TK_EXCEPT: z = "EXCEPT"; break; 1096 case TK_EXCEPT: z = "EXCEPT"; break;
1080 default: z = "UNION"; break; 1097 default: z = "UNION"; break;
1081 } 1098 }
1082 return z; 1099 return z;
1083 } 1100 }
1084 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1085 1101
1086 #ifndef SQLITE_OMIT_EXPLAIN 1102 #ifndef SQLITE_OMIT_EXPLAIN
1087 /* 1103 /*
1088 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 1104 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
1089 ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 1105 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
1090 ** where the caption is of the form: 1106 ** where the caption is of the form:
1091 ** 1107 **
1092 ** "USE TEMP B-TREE FOR xxx" 1108 ** "USE TEMP B-TREE FOR xxx"
1093 ** 1109 **
1094 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which 1110 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after
1161 ** routine generates the code needed to do that. 1177 ** routine generates the code needed to do that.
1162 */ 1178 */
1163 static void generateSortTail( 1179 static void generateSortTail(
1164 Parse *pParse, /* Parsing context */ 1180 Parse *pParse, /* Parsing context */
1165 Select *p, /* The SELECT statement */ 1181 Select *p, /* The SELECT statement */
1166 SortCtx *pSort, /* Information on the ORDER BY clause */ 1182 SortCtx *pSort, /* Information on the ORDER BY clause */
1167 int nColumn, /* Number of columns of data */ 1183 int nColumn, /* Number of columns of data */
1168 SelectDest *pDest /* Write the sorted results here */ 1184 SelectDest *pDest /* Write the sorted results here */
1169 ){ 1185 ){
1170 Vdbe *v = pParse->pVdbe; /* The prepared statement */ 1186 Vdbe *v = pParse->pVdbe; /* The prepared statement */
1171 int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */ 1187 int addrBreak = pSort->labelDone; /* Jump here to exit loop */
1172 int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ 1188 int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
1173 int addr; 1189 int addr;
1174 int addrOnce = 0; 1190 int addrOnce = 0;
1175 int iTab; 1191 int iTab;
1176 ExprList *pOrderBy = pSort->pOrderBy; 1192 ExprList *pOrderBy = pSort->pOrderBy;
1177 int eDest = pDest->eDest; 1193 int eDest = pDest->eDest;
1178 int iParm = pDest->iSDParm; 1194 int iParm = pDest->iSDParm;
1179 int regRow; 1195 int regRow;
1180 int regRowid; 1196 int regRowid;
1181 int nKey; 1197 int nKey;
1182 int iSortTab; /* Sorter cursor to read from */ 1198 int iSortTab; /* Sorter cursor to read from */
1183 int nSortData; /* Trailing values to read from sorter */ 1199 int nSortData; /* Trailing values to read from sorter */
1184 int i; 1200 int i;
1185 int bSeq; /* True if sorter record includes seq. no. */ 1201 int bSeq; /* True if sorter record includes seq. no. */
1186 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS 1202 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1187 struct ExprList_item *aOutEx = p->pEList->a; 1203 struct ExprList_item *aOutEx = p->pEList->a;
1188 #endif 1204 #endif
1189 1205
1206 assert( addrBreak<0 );
1190 if( pSort->labelBkOut ){ 1207 if( pSort->labelBkOut ){
1191 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 1208 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
1192 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak); 1209 sqlite3VdbeGoto(v, addrBreak);
1193 sqlite3VdbeResolveLabel(v, pSort->labelBkOut); 1210 sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
1194 } 1211 }
1195 iTab = pSort->iECursor; 1212 iTab = pSort->iECursor;
1196 if( eDest==SRT_Output || eDest==SRT_Coroutine ){ 1213 if( eDest==SRT_Output || eDest==SRT_Coroutine ){
1197 regRowid = 0; 1214 regRowid = 0;
1198 regRow = pDest->iSdst; 1215 regRow = pDest->iSdst;
1199 nSortData = nColumn; 1216 nSortData = nColumn;
1200 }else{ 1217 }else{
1201 regRowid = sqlite3GetTempReg(pParse); 1218 regRowid = sqlite3GetTempReg(pParse);
1202 regRow = sqlite3GetTempReg(pParse); 1219 regRow = sqlite3GetTempReg(pParse);
(...skipping 17 matching lines...) Expand all
1220 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); 1237 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
1221 codeOffset(v, p->iOffset, addrContinue); 1238 codeOffset(v, p->iOffset, addrContinue);
1222 iSortTab = iTab; 1239 iSortTab = iTab;
1223 bSeq = 1; 1240 bSeq = 1;
1224 } 1241 }
1225 for(i=0; i<nSortData; i++){ 1242 for(i=0; i<nSortData; i++){
1226 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i); 1243 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
1227 VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan)); 1244 VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
1228 } 1245 }
1229 switch( eDest ){ 1246 switch( eDest ){
1230 case SRT_Table:
1231 case SRT_EphemTab: { 1247 case SRT_EphemTab: {
1232 testcase( eDest==SRT_Table );
1233 testcase( eDest==SRT_EphemTab );
1234 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 1248 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
1235 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 1249 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
1236 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1250 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1237 break; 1251 break;
1238 } 1252 }
1239 #ifndef SQLITE_OMIT_SUBQUERY 1253 #ifndef SQLITE_OMIT_SUBQUERY
1240 case SRT_Set: { 1254 case SRT_Set: {
1241 assert( nColumn==1 ); 1255 assert( nColumn==1 );
1242 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, 1256 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
1243 &pDest->affSdst, 1); 1257 &pDest->affSdst, 1);
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
1300 ** SELECT (SELECT col FROM tbl); 1314 ** SELECT (SELECT col FROM tbl);
1301 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 1315 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
1302 ** 1316 **
1303 ** The declaration type for any expression other than a column is NULL. 1317 ** The declaration type for any expression other than a column is NULL.
1304 ** 1318 **
1305 ** This routine has either 3 or 6 parameters depending on whether or not 1319 ** This routine has either 3 or 6 parameters depending on whether or not
1306 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. 1320 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
1307 */ 1321 */
1308 #ifdef SQLITE_ENABLE_COLUMN_METADATA 1322 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1309 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F) 1323 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
1324 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1325 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
1326 #endif
1310 static const char *columnTypeImpl( 1327 static const char *columnTypeImpl(
1311 NameContext *pNC, 1328 NameContext *pNC,
1312 Expr *pExpr, 1329 Expr *pExpr,
1330 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1313 const char **pzOrigDb, 1331 const char **pzOrigDb,
1314 const char **pzOrigTab, 1332 const char **pzOrigTab,
1315 const char **pzOrigCol, 1333 const char **pzOrigCol,
1334 #endif
1316 u8 *pEstWidth 1335 u8 *pEstWidth
1317 ){ 1336 ){
1337 char const *zType = 0;
1338 int j;
1339 u8 estWidth = 1;
1340 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1318 char const *zOrigDb = 0; 1341 char const *zOrigDb = 0;
1319 char const *zOrigTab = 0; 1342 char const *zOrigTab = 0;
1320 char const *zOrigCol = 0; 1343 char const *zOrigCol = 0;
1321 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ 1344 #endif
1322 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
1323 static const char *columnTypeImpl(
1324 NameContext *pNC,
1325 Expr *pExpr,
1326 u8 *pEstWidth
1327 ){
1328 #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1329 char const *zType = 0;
1330 int j;
1331 u8 estWidth = 1;
1332 1345
1333 if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0; 1346 assert( pExpr!=0 );
1347 assert( pNC->pSrcList!=0 );
1334 switch( pExpr->op ){ 1348 switch( pExpr->op ){
1335 case TK_AGG_COLUMN: 1349 case TK_AGG_COLUMN:
1336 case TK_COLUMN: { 1350 case TK_COLUMN: {
1337 /* The expression is a column. Locate the table the column is being 1351 /* The expression is a column. Locate the table the column is being
1338 ** extracted from in NameContext.pSrcList. This table may be real 1352 ** extracted from in NameContext.pSrcList. This table may be real
1339 ** database table or a subquery. 1353 ** database table or a subquery.
1340 */ 1354 */
1341 Table *pTab = 0; /* Table structure column is extracted from */ 1355 Table *pTab = 0; /* Table structure column is extracted from */
1342 Select *pS = 0; /* Select the column is extracted from */ 1356 Select *pS = 0; /* Select the column is extracted from */
1343 int iCol = pExpr->iColumn; /* Index of column in pTab */ 1357 int iCol = pExpr->iColumn; /* Index of column in pTab */
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
1378 assert( pTab && pExpr->pTab==pTab ); 1392 assert( pTab && pExpr->pTab==pTab );
1379 if( pS ){ 1393 if( pS ){
1380 /* The "table" is actually a sub-select or a view in the FROM clause 1394 /* The "table" is actually a sub-select or a view in the FROM clause
1381 ** of the SELECT statement. Return the declaration type and origin 1395 ** of the SELECT statement. Return the declaration type and origin
1382 ** data for the result-set column of the sub-select. 1396 ** data for the result-set column of the sub-select.
1383 */ 1397 */
1384 if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){ 1398 if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
1385 /* If iCol is less than zero, then the expression requests the 1399 /* If iCol is less than zero, then the expression requests the
1386 ** rowid of the sub-select or view. This expression is legal (see 1400 ** rowid of the sub-select or view. This expression is legal (see
1387 ** test case misc2.2.2) - it always evaluates to NULL. 1401 ** test case misc2.2.2) - it always evaluates to NULL.
1402 **
1403 ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
1404 ** caught already by name resolution.
1388 */ 1405 */
1389 NameContext sNC; 1406 NameContext sNC;
1390 Expr *p = pS->pEList->a[iCol].pExpr; 1407 Expr *p = pS->pEList->a[iCol].pExpr;
1391 sNC.pSrcList = pS->pSrc; 1408 sNC.pSrcList = pS->pSrc;
1392 sNC.pNext = pNC; 1409 sNC.pNext = pNC;
1393 sNC.pParse = pNC->pParse; 1410 sNC.pParse = pNC->pParse;
1394 zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth); 1411 zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
1395 } 1412 }
1396 }else if( pTab->pSchema ){ 1413 }else if( pTab->pSchema ){
1397 /* A real table */ 1414 /* A real table */
(...skipping 110 matching lines...) Expand 10 before | Expand all | Expand 10 after
1508 sqlite3 *db = pParse->db; 1525 sqlite3 *db = pParse->db;
1509 int fullNames, shortNames; 1526 int fullNames, shortNames;
1510 1527
1511 #ifndef SQLITE_OMIT_EXPLAIN 1528 #ifndef SQLITE_OMIT_EXPLAIN
1512 /* If this is an EXPLAIN, skip this step */ 1529 /* If this is an EXPLAIN, skip this step */
1513 if( pParse->explain ){ 1530 if( pParse->explain ){
1514 return; 1531 return;
1515 } 1532 }
1516 #endif 1533 #endif
1517 1534
1518 if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return; 1535 if( pParse->colNamesSet || db->mallocFailed ) return;
1536 assert( v!=0 );
1537 assert( pTabList!=0 );
1519 pParse->colNamesSet = 1; 1538 pParse->colNamesSet = 1;
1520 fullNames = (db->flags & SQLITE_FullColNames)!=0; 1539 fullNames = (db->flags & SQLITE_FullColNames)!=0;
1521 shortNames = (db->flags & SQLITE_ShortColNames)!=0; 1540 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
1522 sqlite3VdbeSetNumCols(v, pEList->nExpr); 1541 sqlite3VdbeSetNumCols(v, pEList->nExpr);
1523 for(i=0; i<pEList->nExpr; i++){ 1542 for(i=0; i<pEList->nExpr; i++){
1524 Expr *p; 1543 Expr *p;
1525 p = pEList->a[i].pExpr; 1544 p = pEList->a[i].pExpr;
1526 if( NEVER(p==0) ) continue; 1545 if( NEVER(p==0) ) continue;
1527 if( pEList->a[i].zName ){ 1546 if( pEList->a[i].zName ){
1528 char *zName = pEList->a[i].zName; 1547 char *zName = pEList->a[i].zName;
1529 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); 1548 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
1530 }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){ 1549 }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){
1531 Table *pTab; 1550 Table *pTab;
1532 char *zCol; 1551 char *zCol;
1533 int iCol = p->iColumn; 1552 int iCol = p->iColumn;
1534 for(j=0; ALWAYS(j<pTabList->nSrc); j++){ 1553 for(j=0; ALWAYS(j<pTabList->nSrc); j++){
1535 if( pTabList->a[j].iCursor==p->iTable ) break; 1554 if( pTabList->a[j].iCursor==p->iTable ) break;
1536 } 1555 }
1537 assert( j<pTabList->nSrc ); 1556 assert( j<pTabList->nSrc );
1538 pTab = pTabList->a[j].pTab; 1557 pTab = pTabList->a[j].pTab;
1539 if( iCol<0 ) iCol = pTab->iPKey; 1558 if( iCol<0 ) iCol = pTab->iPKey;
1540 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1559 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
(...skipping 27 matching lines...) Expand all
1568 ** column names for a table that would hold the expression list. 1587 ** column names for a table that would hold the expression list.
1569 ** 1588 **
1570 ** All column names will be unique. 1589 ** All column names will be unique.
1571 ** 1590 **
1572 ** Only the column names are computed. Column.zType, Column.zColl, 1591 ** Only the column names are computed. Column.zType, Column.zColl,
1573 ** and other fields of Column are zeroed. 1592 ** and other fields of Column are zeroed.
1574 ** 1593 **
1575 ** Return SQLITE_OK on success. If a memory allocation error occurs, 1594 ** Return SQLITE_OK on success. If a memory allocation error occurs,
1576 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. 1595 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
1577 */ 1596 */
1578 static int selectColumnsFromExprList( 1597 int sqlite3ColumnsFromExprList(
1579 Parse *pParse, /* Parsing context */ 1598 Parse *pParse, /* Parsing context */
1580 ExprList *pEList, /* Expr list from which to derive column names */ 1599 ExprList *pEList, /* Expr list from which to derive column names */
1581 i16 *pnCol, /* Write the number of columns here */ 1600 i16 *pnCol, /* Write the number of columns here */
1582 Column **paCol /* Write the new column list here */ 1601 Column **paCol /* Write the new column list here */
1583 ){ 1602 ){
1584 sqlite3 *db = pParse->db; /* Database connection */ 1603 sqlite3 *db = pParse->db; /* Database connection */
1585 int i, j; /* Loop counters */ 1604 int i, j; /* Loop counters */
1586 int cnt; /* Index added to make the name unique */ 1605 u32 cnt; /* Index added to make the name unique */
1587 Column *aCol, *pCol; /* For looping over result columns */ 1606 Column *aCol, *pCol; /* For looping over result columns */
1588 int nCol; /* Number of columns in the result set */ 1607 int nCol; /* Number of columns in the result set */
1589 Expr *p; /* Expression for a single result column */ 1608 Expr *p; /* Expression for a single result column */
1590 char *zName; /* Column name */ 1609 char *zName; /* Column name */
1591 int nName; /* Size of name in zName[] */ 1610 int nName; /* Size of name in zName[] */
1611 Hash ht; /* Hash table of column names */
1592 1612
1613 sqlite3HashInit(&ht);
1593 if( pEList ){ 1614 if( pEList ){
1594 nCol = pEList->nExpr; 1615 nCol = pEList->nExpr;
1595 aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); 1616 aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
1596 testcase( aCol==0 ); 1617 testcase( aCol==0 );
1597 }else{ 1618 }else{
1598 nCol = 0; 1619 nCol = 0;
1599 aCol = 0; 1620 aCol = 0;
1600 } 1621 }
1622 assert( nCol==(i16)nCol );
1601 *pnCol = nCol; 1623 *pnCol = nCol;
1602 *paCol = aCol; 1624 *paCol = aCol;
1603 1625
1604 for(i=0, pCol=aCol; i<nCol; i++, pCol++){ 1626 for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
1605 /* Get an appropriate name for the column 1627 /* Get an appropriate name for the column
1606 */ 1628 */
1607 p = sqlite3ExprSkipCollate(pEList->a[i].pExpr); 1629 p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
1608 if( (zName = pEList->a[i].zName)!=0 ){ 1630 if( (zName = pEList->a[i].zName)!=0 ){
1609 /* If the column contains an "AS <name>" phrase, use <name> as the name */ 1631 /* If the column contains an "AS <name>" phrase, use <name> as the name */
1610 zName = sqlite3DbStrDup(db, zName);
1611 }else{ 1632 }else{
1612 Expr *pColExpr = p; /* The expression that is the result column name */ 1633 Expr *pColExpr = p; /* The expression that is the result column name */
1613 Table *pTab; /* Table associated with this expression */ 1634 Table *pTab; /* Table associated with this expression */
1614 while( pColExpr->op==TK_DOT ){ 1635 while( pColExpr->op==TK_DOT ){
1615 pColExpr = pColExpr->pRight; 1636 pColExpr = pColExpr->pRight;
1616 assert( pColExpr!=0 ); 1637 assert( pColExpr!=0 );
1617 } 1638 }
1618 if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){ 1639 if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
1619 /* For columns use the column name name */ 1640 /* For columns use the column name name */
1620 int iCol = pColExpr->iColumn; 1641 int iCol = pColExpr->iColumn;
1621 pTab = pColExpr->pTab; 1642 pTab = pColExpr->pTab;
1622 if( iCol<0 ) iCol = pTab->iPKey; 1643 if( iCol<0 ) iCol = pTab->iPKey;
1623 zName = sqlite3MPrintf(db, "%s", 1644 zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
1624 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
1625 }else if( pColExpr->op==TK_ID ){ 1645 }else if( pColExpr->op==TK_ID ){
1626 assert( !ExprHasProperty(pColExpr, EP_IntValue) ); 1646 assert( !ExprHasProperty(pColExpr, EP_IntValue) );
1627 zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken); 1647 zName = pColExpr->u.zToken;
1628 }else{ 1648 }else{
1629 /* Use the original text of the column expression as its name */ 1649 /* Use the original text of the column expression as its name */
1630 zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan); 1650 zName = pEList->a[i].zSpan;
1631 } 1651 }
1632 } 1652 }
1633 if( db->mallocFailed ){ 1653 zName = sqlite3MPrintf(db, "%s", zName);
1634 sqlite3DbFree(db, zName);
1635 break;
1636 }
1637 1654
1638 /* Make sure the column name is unique. If the name is not unique, 1655 /* Make sure the column name is unique. If the name is not unique,
1639 ** append an integer to the name so that it becomes unique. 1656 ** append an integer to the name so that it becomes unique.
1640 */ 1657 */
1641 nName = sqlite3Strlen30(zName); 1658 cnt = 0;
1642 for(j=cnt=0; j<i; j++){ 1659 while( zName && sqlite3HashFind(&ht, zName)!=0 ){
1643 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 1660 nName = sqlite3Strlen30(zName);
1644 char *zNewName; 1661 if( nName>0 ){
1645 int k; 1662 for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
1646 for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){} 1663 if( zName[j]==':' ) nName = j;
1647 if( k>=0 && zName[k]==':' ) nName = k;
1648 zName[nName] = 0;
1649 zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
1650 sqlite3DbFree(db, zName);
1651 zName = zNewName;
1652 j = -1;
1653 if( zName==0 ) break;
1654 } 1664 }
1665 zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
1666 if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
1655 } 1667 }
1656 pCol->zName = zName; 1668 pCol->zName = zName;
1669 sqlite3ColumnPropertiesFromName(0, pCol);
1670 if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
1671 db->mallocFailed = 1;
1672 }
1657 } 1673 }
1674 sqlite3HashClear(&ht);
1658 if( db->mallocFailed ){ 1675 if( db->mallocFailed ){
1659 for(j=0; j<i; j++){ 1676 for(j=0; j<i; j++){
1660 sqlite3DbFree(db, aCol[j].zName); 1677 sqlite3DbFree(db, aCol[j].zName);
1661 } 1678 }
1662 sqlite3DbFree(db, aCol); 1679 sqlite3DbFree(db, aCol);
1663 *paCol = 0; 1680 *paCol = 0;
1664 *pnCol = 0; 1681 *pnCol = 0;
1665 return SQLITE_NOMEM; 1682 return SQLITE_NOMEM;
1666 } 1683 }
1667 return SQLITE_OK; 1684 return SQLITE_OK;
(...skipping 26 matching lines...) Expand all
1694 1711
1695 assert( pSelect!=0 ); 1712 assert( pSelect!=0 );
1696 assert( (pSelect->selFlags & SF_Resolved)!=0 ); 1713 assert( (pSelect->selFlags & SF_Resolved)!=0 );
1697 assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); 1714 assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
1698 if( db->mallocFailed ) return; 1715 if( db->mallocFailed ) return;
1699 memset(&sNC, 0, sizeof(sNC)); 1716 memset(&sNC, 0, sizeof(sNC));
1700 sNC.pSrcList = pSelect->pSrc; 1717 sNC.pSrcList = pSelect->pSrc;
1701 a = pSelect->pEList->a; 1718 a = pSelect->pEList->a;
1702 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ 1719 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
1703 p = a[i].pExpr; 1720 p = a[i].pExpr;
1704 pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst)); 1721 if( pCol->zType==0 ){
1722 pCol->zType = sqlite3DbStrDup(db,
1723 columnType(&sNC, p,0,0,0, &pCol->szEst));
1724 }
1705 szAll += pCol->szEst; 1725 szAll += pCol->szEst;
1706 pCol->affinity = sqlite3ExprAffinity(p); 1726 pCol->affinity = sqlite3ExprAffinity(p);
1707 if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE; 1727 if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
1708 pColl = sqlite3ExprCollSeq(pParse, p); 1728 pColl = sqlite3ExprCollSeq(pParse, p);
1709 if( pColl ){ 1729 if( pColl && pCol->zColl==0 ){
1710 pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 1730 pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
1711 } 1731 }
1712 } 1732 }
1713 pTab->szTabRow = sqlite3LogEst(szAll*4); 1733 pTab->szTabRow = sqlite3LogEst(szAll*4);
1714 } 1734 }
1715 1735
1716 /* 1736 /*
1717 ** Given a SELECT statement, generate a Table structure that describes 1737 ** Given a SELECT statement, generate a Table structure that describes
1718 ** the result set of that SELECT. 1738 ** the result set of that SELECT.
1719 */ 1739 */
(...skipping 12 matching lines...) Expand all
1732 pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 1752 pTab = sqlite3DbMallocZero(db, sizeof(Table) );
1733 if( pTab==0 ){ 1753 if( pTab==0 ){
1734 return 0; 1754 return 0;
1735 } 1755 }
1736 /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside 1756 /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
1737 ** is disabled */ 1757 ** is disabled */
1738 assert( db->lookaside.bEnabled==0 ); 1758 assert( db->lookaside.bEnabled==0 );
1739 pTab->nRef = 1; 1759 pTab->nRef = 1;
1740 pTab->zName = 0; 1760 pTab->zName = 0;
1741 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 1761 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
1742 selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); 1762 sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
1743 selectAddColumnTypeAndCollation(pParse, pTab, pSelect); 1763 selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
1744 pTab->iPKey = -1; 1764 pTab->iPKey = -1;
1745 if( db->mallocFailed ){ 1765 if( db->mallocFailed ){
1746 sqlite3DeleteTable(db, pTab); 1766 sqlite3DeleteTable(db, pTab);
1747 return 0; 1767 return 0;
1748 } 1768 }
1749 return pTab; 1769 return pTab;
1750 } 1770 }
1751 1771
1752 /* 1772 /*
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
1789 ** 1809 **
1790 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 1810 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
1791 ** redefined. The UNION ALL operator uses this property to force 1811 ** redefined. The UNION ALL operator uses this property to force
1792 ** the reuse of the same limit and offset registers across multiple 1812 ** the reuse of the same limit and offset registers across multiple
1793 ** SELECT statements. 1813 ** SELECT statements.
1794 */ 1814 */
1795 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 1815 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
1796 Vdbe *v = 0; 1816 Vdbe *v = 0;
1797 int iLimit = 0; 1817 int iLimit = 0;
1798 int iOffset; 1818 int iOffset;
1799 int addr1, n; 1819 int n;
1800 if( p->iLimit ) return; 1820 if( p->iLimit ) return;
1801 1821
1802 /* 1822 /*
1803 ** "LIMIT -1" always shows all rows. There is some 1823 ** "LIMIT -1" always shows all rows. There is some
1804 ** controversy about what the correct behavior should be. 1824 ** controversy about what the correct behavior should be.
1805 ** The current implementation interprets "LIMIT 0" to mean 1825 ** The current implementation interprets "LIMIT 0" to mean
1806 ** no rows. 1826 ** no rows.
1807 */ 1827 */
1808 sqlite3ExprCacheClear(pParse); 1828 sqlite3ExprCacheClear(pParse);
1809 assert( p->pOffset==0 || p->pLimit!=0 ); 1829 assert( p->pOffset==0 || p->pLimit!=0 );
1810 if( p->pLimit ){ 1830 if( p->pLimit ){
1811 p->iLimit = iLimit = ++pParse->nMem; 1831 p->iLimit = iLimit = ++pParse->nMem;
1812 v = sqlite3GetVdbe(pParse); 1832 v = sqlite3GetVdbe(pParse);
1813 assert( v!=0 ); 1833 assert( v!=0 );
1814 if( sqlite3ExprIsInteger(p->pLimit, &n) ){ 1834 if( sqlite3ExprIsInteger(p->pLimit, &n) ){
1815 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); 1835 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
1816 VdbeComment((v, "LIMIT counter")); 1836 VdbeComment((v, "LIMIT counter"));
1817 if( n==0 ){ 1837 if( n==0 ){
1818 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); 1838 sqlite3VdbeGoto(v, iBreak);
1819 }else if( n>=0 && p->nSelectRow>(u64)n ){ 1839 }else if( n>=0 && p->nSelectRow>(u64)n ){
1820 p->nSelectRow = n; 1840 p->nSelectRow = n;
1821 } 1841 }
1822 }else{ 1842 }else{
1823 sqlite3ExprCode(pParse, p->pLimit, iLimit); 1843 sqlite3ExprCode(pParse, p->pLimit, iLimit);
1824 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); 1844 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
1825 VdbeComment((v, "LIMIT counter")); 1845 VdbeComment((v, "LIMIT counter"));
1826 sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); VdbeCoverage(v); 1846 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
1827 } 1847 }
1828 if( p->pOffset ){ 1848 if( p->pOffset ){
1829 p->iOffset = iOffset = ++pParse->nMem; 1849 p->iOffset = iOffset = ++pParse->nMem;
1830 pParse->nMem++; /* Allocate an extra register for limit+offset */ 1850 pParse->nMem++; /* Allocate an extra register for limit+offset */
1831 sqlite3ExprCode(pParse, p->pOffset, iOffset); 1851 sqlite3ExprCode(pParse, p->pOffset, iOffset);
1832 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); 1852 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
1833 VdbeComment((v, "OFFSET counter")); 1853 VdbeComment((v, "OFFSET counter"));
1834 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v); 1854 sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iOffset, iOffset, 0);
1835 sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
1836 sqlite3VdbeJumpHere(v, addr1);
1837 sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1); 1855 sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
1838 VdbeComment((v, "LIMIT+OFFSET")); 1856 VdbeComment((v, "LIMIT+OFFSET"));
1839 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v); 1857 sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iLimit, iOffset+1, -1);
1840 sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
1841 sqlite3VdbeJumpHere(v, addr1);
1842 } 1858 }
1843 } 1859 }
1844 } 1860 }
1845 1861
1846 #ifndef SQLITE_OMIT_COMPOUND_SELECT 1862 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1847 /* 1863 /*
1848 ** Return the appropriate collating sequence for the iCol-th column of 1864 ** Return the appropriate collating sequence for the iCol-th column of
1849 ** the result set for the compound-select statement "p". Return NULL if 1865 ** the result set for the compound-select statement "p". Return NULL if
1850 ** the column has no default collating sequence. 1866 ** the column has no default collating sequence.
1851 ** 1867 **
1852 ** The collating sequence for the compound select is taken from the 1868 ** The collating sequence for the compound select is taken from the
1853 ** left-most term of the select that has a collating sequence. 1869 ** left-most term of the select that has a collating sequence.
1854 */ 1870 */
1855 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1871 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1856 CollSeq *pRet; 1872 CollSeq *pRet;
1857 if( p->pPrior ){ 1873 if( p->pPrior ){
1858 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1874 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1859 }else{ 1875 }else{
1860 pRet = 0; 1876 pRet = 0;
1861 } 1877 }
1862 assert( iCol>=0 ); 1878 assert( iCol>=0 );
1863 if( pRet==0 && iCol<p->pEList->nExpr ){ 1879 /* iCol must be less than p->pEList->nExpr. Otherwise an error would
1880 ** have been thrown during name resolution and we would not have gotten
1881 ** this far */
1882 if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
1864 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1883 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1865 } 1884 }
1866 return pRet; 1885 return pRet;
1867 } 1886 }
1868 1887
1869 /* 1888 /*
1870 ** The select statement passed as the second parameter is a compound SELECT 1889 ** The select statement passed as the second parameter is a compound SELECT
1871 ** with an ORDER BY clause. This function allocates and returns a KeyInfo 1890 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
1872 ** structure suitable for implementing the ORDER BY. 1891 ** structure suitable for implementing the ORDER BY.
1873 ** 1892 **
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
1908 /* 1927 /*
1909 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE 1928 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
1910 ** query of the form: 1929 ** query of the form:
1911 ** 1930 **
1912 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>) 1931 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
1913 ** \___________/ \_______________/ 1932 ** \___________/ \_______________/
1914 ** p->pPrior p 1933 ** p->pPrior p
1915 ** 1934 **
1916 ** 1935 **
1917 ** There is exactly one reference to the recursive-table in the FROM clause 1936 ** There is exactly one reference to the recursive-table in the FROM clause
1918 ** of recursive-query, marked with the SrcList->a[].isRecursive flag. 1937 ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
1919 ** 1938 **
1920 ** The setup-query runs once to generate an initial set of rows that go 1939 ** The setup-query runs once to generate an initial set of rows that go
1921 ** into a Queue table. Rows are extracted from the Queue table one by 1940 ** into a Queue table. Rows are extracted from the Queue table one by
1922 ** one. Each row extracted from Queue is output to pDest. Then the single 1941 ** one. Each row extracted from Queue is output to pDest. Then the single
1923 ** extracted row (now in the iCurrent table) becomes the content of the 1942 ** extracted row (now in the iCurrent table) becomes the content of the
1924 ** recursive-table for a recursive-query run. The output of the recursive-query 1943 ** recursive-table for a recursive-query run. The output of the recursive-query
1925 ** is added back into the Queue table. Then another row is extracted from Queue 1944 ** is added back into the Queue table. Then another row is extracted from Queue
1926 ** and the iteration continues until the Queue table is empty. 1945 ** and the iteration continues until the Queue table is empty.
1927 ** 1946 **
1928 ** If the compound query operator is UNION then no duplicate rows are ever 1947 ** If the compound query operator is UNION then no duplicate rows are ever
(...skipping 44 matching lines...) Expand 10 before | Expand all | Expand 10 after
1973 pLimit = p->pLimit; 1992 pLimit = p->pLimit;
1974 pOffset = p->pOffset; 1993 pOffset = p->pOffset;
1975 regLimit = p->iLimit; 1994 regLimit = p->iLimit;
1976 regOffset = p->iOffset; 1995 regOffset = p->iOffset;
1977 p->pLimit = p->pOffset = 0; 1996 p->pLimit = p->pOffset = 0;
1978 p->iLimit = p->iOffset = 0; 1997 p->iLimit = p->iOffset = 0;
1979 pOrderBy = p->pOrderBy; 1998 pOrderBy = p->pOrderBy;
1980 1999
1981 /* Locate the cursor number of the Current table */ 2000 /* Locate the cursor number of the Current table */
1982 for(i=0; ALWAYS(i<pSrc->nSrc); i++){ 2001 for(i=0; ALWAYS(i<pSrc->nSrc); i++){
1983 if( pSrc->a[i].isRecursive ){ 2002 if( pSrc->a[i].fg.isRecursive ){
1984 iCurrent = pSrc->a[i].iCursor; 2003 iCurrent = pSrc->a[i].iCursor;
1985 break; 2004 break;
1986 } 2005 }
1987 } 2006 }
1988 2007
1989 /* Allocate cursors numbers for Queue and Distinct. The cursor number for 2008 /* Allocate cursors numbers for Queue and Distinct. The cursor number for
1990 ** the Distinct table must be exactly one greater than Queue in order 2009 ** the Distinct table must be exactly one greater than Queue in order
1991 ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */ 2010 ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
1992 iQueue = pParse->nTab++; 2011 iQueue = pParse->nTab++;
1993 if( p->op==TK_UNION ){ 2012 if( p->op==TK_UNION ){
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
2035 sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); 2054 sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
2036 } 2055 }
2037 sqlite3VdbeAddOp1(v, OP_Delete, iQueue); 2056 sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
2038 2057
2039 /* Output the single row in Current */ 2058 /* Output the single row in Current */
2040 addrCont = sqlite3VdbeMakeLabel(v); 2059 addrCont = sqlite3VdbeMakeLabel(v);
2041 codeOffset(v, regOffset, addrCont); 2060 codeOffset(v, regOffset, addrCont);
2042 selectInnerLoop(pParse, p, p->pEList, iCurrent, 2061 selectInnerLoop(pParse, p, p->pEList, iCurrent,
2043 0, 0, pDest, addrCont, addrBreak); 2062 0, 0, pDest, addrCont, addrBreak);
2044 if( regLimit ){ 2063 if( regLimit ){
2045 sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1); 2064 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
2046 VdbeCoverage(v); 2065 VdbeCoverage(v);
2047 } 2066 }
2048 sqlite3VdbeResolveLabel(v, addrCont); 2067 sqlite3VdbeResolveLabel(v, addrCont);
2049 2068
2050 /* Execute the recursive SELECT taking the single row in Current as 2069 /* Execute the recursive SELECT taking the single row in Current as
2051 ** the value for the recursive-table. Store the results in the Queue. 2070 ** the value for the recursive-table. Store the results in the Queue.
2052 */ 2071 */
2053 p->pPrior = 0; 2072 if( p->selFlags & SF_Aggregate ){
2054 sqlite3Select(pParse, p, &destQueue); 2073 sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
2055 assert( p->pPrior==0 ); 2074 }else{
2056 p->pPrior = pSetup; 2075 p->pPrior = 0;
2076 sqlite3Select(pParse, p, &destQueue);
2077 assert( p->pPrior==0 );
2078 p->pPrior = pSetup;
2079 }
2057 2080
2058 /* Keep running the loop until the Queue is empty */ 2081 /* Keep running the loop until the Queue is empty */
2059 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop); 2082 sqlite3VdbeGoto(v, addrTop);
2060 sqlite3VdbeResolveLabel(v, addrBreak); 2083 sqlite3VdbeResolveLabel(v, addrBreak);
2061 2084
2062 end_of_recursive_query: 2085 end_of_recursive_query:
2063 sqlite3ExprListDelete(pParse->db, p->pOrderBy); 2086 sqlite3ExprListDelete(pParse->db, p->pOrderBy);
2064 p->pOrderBy = pOrderBy; 2087 p->pOrderBy = pOrderBy;
2065 p->pLimit = pLimit; 2088 p->pLimit = pLimit;
2066 p->pOffset = pOffset; 2089 p->pOffset = pOffset;
2067 return; 2090 return;
2068 } 2091 }
2069 #endif /* SQLITE_OMIT_CTE */ 2092 #endif /* SQLITE_OMIT_CTE */
2070 2093
2071 /* Forward references */ 2094 /* Forward references */
2072 static int multiSelectOrderBy( 2095 static int multiSelectOrderBy(
2073 Parse *pParse, /* Parsing context */ 2096 Parse *pParse, /* Parsing context */
2074 Select *p, /* The right-most of SELECTs to be coded */ 2097 Select *p, /* The right-most of SELECTs to be coded */
2075 SelectDest *pDest /* What to do with query results */ 2098 SelectDest *pDest /* What to do with query results */
2076 ); 2099 );
2077 2100
2101 /*
2102 ** Handle the special case of a compound-select that originates from a
2103 ** VALUES clause. By handling this as a special case, we avoid deep
2104 ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
2105 ** on a VALUES clause.
2106 **
2107 ** Because the Select object originates from a VALUES clause:
2108 ** (1) It has no LIMIT or OFFSET
2109 ** (2) All terms are UNION ALL
2110 ** (3) There is no ORDER BY clause
2111 */
2112 static int multiSelectValues(
2113 Parse *pParse, /* Parsing context */
2114 Select *p, /* The right-most of SELECTs to be coded */
2115 SelectDest *pDest /* What to do with query results */
2116 ){
2117 Select *pPrior;
2118 int nRow = 1;
2119 int rc = 0;
2120 assert( p->selFlags & SF_MultiValue );
2121 do{
2122 assert( p->selFlags & SF_Values );
2123 assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
2124 assert( p->pLimit==0 );
2125 assert( p->pOffset==0 );
2126 assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
2127 if( p->pPrior==0 ) break;
2128 assert( p->pPrior->pNext==p );
2129 p = p->pPrior;
2130 nRow++;
2131 }while(1);
2132 while( p ){
2133 pPrior = p->pPrior;
2134 p->pPrior = 0;
2135 rc = sqlite3Select(pParse, p, pDest);
2136 p->pPrior = pPrior;
2137 if( rc ) break;
2138 p->nSelectRow = nRow;
2139 p = p->pNext;
2140 }
2141 return rc;
2142 }
2078 2143
2079 /* 2144 /*
2080 ** This routine is called to process a compound query form from 2145 ** This routine is called to process a compound query form from
2081 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or 2146 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
2082 ** INTERSECT 2147 ** INTERSECT
2083 ** 2148 **
2084 ** "p" points to the right-most of the two queries. the query on the 2149 ** "p" points to the right-most of the two queries. the query on the
2085 ** left is p->pPrior. The left query could also be a compound query 2150 ** left is p->pPrior. The left query could also be a compound query
2086 ** in which case this routine will be called recursively. 2151 ** in which case this routine will be called recursively.
2087 ** 2152 **
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after
2149 2214
2150 /* Create the destination temporary table if necessary 2215 /* Create the destination temporary table if necessary
2151 */ 2216 */
2152 if( dest.eDest==SRT_EphemTab ){ 2217 if( dest.eDest==SRT_EphemTab ){
2153 assert( p->pEList ); 2218 assert( p->pEList );
2154 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); 2219 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
2155 sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 2220 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
2156 dest.eDest = SRT_Table; 2221 dest.eDest = SRT_Table;
2157 } 2222 }
2158 2223
2224 /* Special handling for a compound-select that originates as a VALUES clause.
2225 */
2226 if( p->selFlags & SF_MultiValue ){
2227 rc = multiSelectValues(pParse, p, &dest);
2228 goto multi_select_end;
2229 }
2230
2159 /* Make sure all SELECTs in the statement have the same number of elements 2231 /* Make sure all SELECTs in the statement have the same number of elements
2160 ** in their result sets. 2232 ** in their result sets.
2161 */ 2233 */
2162 assert( p->pEList && pPrior->pEList ); 2234 assert( p->pEList && pPrior->pEList );
2163 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 2235 assert( p->pEList->nExpr==pPrior->pEList->nExpr );
2164 if( p->selFlags & SF_Values ){
2165 sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
2166 }else{
2167 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
2168 " do not have the same number of result columns", selectOpName(p->op));
2169 }
2170 rc = 1;
2171 goto multi_select_end;
2172 }
2173 2236
2174 #ifndef SQLITE_OMIT_CTE 2237 #ifndef SQLITE_OMIT_CTE
2175 if( p->selFlags & SF_Recursive ){ 2238 if( p->selFlags & SF_Recursive ){
2176 generateWithRecursiveQuery(pParse, p, &dest); 2239 generateWithRecursiveQuery(pParse, p, &dest);
2177 }else 2240 }else
2178 #endif 2241 #endif
2179 2242
2180 /* Compound SELECTs that have an ORDER BY clause are handled separately. 2243 /* Compound SELECTs that have an ORDER BY clause are handled separately.
2181 */ 2244 */
2182 if( p->pOrderBy ){ 2245 if( p->pOrderBy ){
(...skipping 15 matching lines...) Expand all
2198 rc = sqlite3Select(pParse, pPrior, &dest); 2261 rc = sqlite3Select(pParse, pPrior, &dest);
2199 p->pLimit = 0; 2262 p->pLimit = 0;
2200 p->pOffset = 0; 2263 p->pOffset = 0;
2201 if( rc ){ 2264 if( rc ){
2202 goto multi_select_end; 2265 goto multi_select_end;
2203 } 2266 }
2204 p->pPrior = 0; 2267 p->pPrior = 0;
2205 p->iLimit = pPrior->iLimit; 2268 p->iLimit = pPrior->iLimit;
2206 p->iOffset = pPrior->iOffset; 2269 p->iOffset = pPrior->iOffset;
2207 if( p->iLimit ){ 2270 if( p->iLimit ){
2208 addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); VdbeCoverage(v); 2271 addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
2209 VdbeComment((v, "Jump ahead if LIMIT reached")); 2272 VdbeComment((v, "Jump ahead if LIMIT reached"));
2273 if( p->iOffset ){
2274 sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iOffset, p->iOffset, 0);
2275 sqlite3VdbeAddOp3(v, OP_Add, p->iLimit, p->iOffset, p->iOffset+1);
2276 sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iLimit, p->iOffset+1, -1);
2277 }
2210 } 2278 }
2211 explainSetInteger(iSub2, pParse->iNextSelectId); 2279 explainSetInteger(iSub2, pParse->iNextSelectId);
2212 rc = sqlite3Select(pParse, p, &dest); 2280 rc = sqlite3Select(pParse, p, &dest);
2213 testcase( rc!=SQLITE_OK ); 2281 testcase( rc!=SQLITE_OK );
2214 pDelete = p->pPrior; 2282 pDelete = p->pPrior;
2215 p->pPrior = pPrior; 2283 p->pPrior = pPrior;
2216 p->nSelectRow += pPrior->nSelectRow; 2284 p->nSelectRow += pPrior->nSelectRow;
2217 if( pPrior->pLimit 2285 if( pPrior->pLimit
2218 && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit) 2286 && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
2219 && nLimit>0 && p->nSelectRow > (u64)nLimit 2287 && nLimit>0 && p->nSelectRow > (u64)nLimit
(...skipping 80 matching lines...) Expand 10 before | Expand all | Expand 10 after
2300 /* Convert the data in the temporary table into whatever form 2368 /* Convert the data in the temporary table into whatever form
2301 ** it is that we currently need. 2369 ** it is that we currently need.
2302 */ 2370 */
2303 assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); 2371 assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
2304 if( dest.eDest!=priorOp ){ 2372 if( dest.eDest!=priorOp ){
2305 int iCont, iBreak, iStart; 2373 int iCont, iBreak, iStart;
2306 assert( p->pEList ); 2374 assert( p->pEList );
2307 if( dest.eDest==SRT_Output ){ 2375 if( dest.eDest==SRT_Output ){
2308 Select *pFirst = p; 2376 Select *pFirst = p;
2309 while( pFirst->pPrior ) pFirst = pFirst->pPrior; 2377 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
2310 generateColumnNames(pParse, 0, pFirst->pEList); 2378 generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
2311 } 2379 }
2312 iBreak = sqlite3VdbeMakeLabel(v); 2380 iBreak = sqlite3VdbeMakeLabel(v);
2313 iCont = sqlite3VdbeMakeLabel(v); 2381 iCont = sqlite3VdbeMakeLabel(v);
2314 computeLimitRegisters(pParse, p, iBreak); 2382 computeLimitRegisters(pParse, p, iBreak);
2315 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); 2383 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
2316 iStart = sqlite3VdbeCurrentAddr(v); 2384 iStart = sqlite3VdbeCurrentAddr(v);
2317 selectInnerLoop(pParse, p, p->pEList, unionTab, 2385 selectInnerLoop(pParse, p, p->pEList, unionTab,
2318 0, 0, &dest, iCont, iBreak); 2386 0, 0, &dest, iCont, iBreak);
2319 sqlite3VdbeResolveLabel(v, iCont); 2387 sqlite3VdbeResolveLabel(v, iCont);
2320 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); 2388 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
2375 p->pLimit = pLimit; 2443 p->pLimit = pLimit;
2376 p->pOffset = pOffset; 2444 p->pOffset = pOffset;
2377 2445
2378 /* Generate code to take the intersection of the two temporary 2446 /* Generate code to take the intersection of the two temporary
2379 ** tables. 2447 ** tables.
2380 */ 2448 */
2381 assert( p->pEList ); 2449 assert( p->pEList );
2382 if( dest.eDest==SRT_Output ){ 2450 if( dest.eDest==SRT_Output ){
2383 Select *pFirst = p; 2451 Select *pFirst = p;
2384 while( pFirst->pPrior ) pFirst = pFirst->pPrior; 2452 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
2385 generateColumnNames(pParse, 0, pFirst->pEList); 2453 generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
2386 } 2454 }
2387 iBreak = sqlite3VdbeMakeLabel(v); 2455 iBreak = sqlite3VdbeMakeLabel(v);
2388 iCont = sqlite3VdbeMakeLabel(v); 2456 iCont = sqlite3VdbeMakeLabel(v);
2389 computeLimitRegisters(pParse, p, iBreak); 2457 computeLimitRegisters(pParse, p, iBreak);
2390 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); 2458 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
2391 r1 = sqlite3GetTempReg(pParse); 2459 r1 = sqlite3GetTempReg(pParse);
2392 iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); 2460 iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
2393 sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v); 2461 sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
2394 sqlite3ReleaseTempReg(pParse, r1); 2462 sqlite3ReleaseTempReg(pParse, r1);
2395 selectInnerLoop(pParse, p, p->pEList, tab1, 2463 selectInnerLoop(pParse, p, p->pEList, tab1,
(...skipping 59 matching lines...) Expand 10 before | Expand all | Expand 10 after
2455 2523
2456 multi_select_end: 2524 multi_select_end:
2457 pDest->iSdst = dest.iSdst; 2525 pDest->iSdst = dest.iSdst;
2458 pDest->nSdst = dest.nSdst; 2526 pDest->nSdst = dest.nSdst;
2459 sqlite3SelectDelete(db, pDelete); 2527 sqlite3SelectDelete(db, pDelete);
2460 return rc; 2528 return rc;
2461 } 2529 }
2462 #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 2530 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
2463 2531
2464 /* 2532 /*
2533 ** Error message for when two or more terms of a compound select have different
2534 ** size result sets.
2535 */
2536 void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
2537 if( p->selFlags & SF_Values ){
2538 sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
2539 }else{
2540 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
2541 " do not have the same number of result columns", selectOpName(p->op));
2542 }
2543 }
2544
2545 /*
2465 ** Code an output subroutine for a coroutine implementation of a 2546 ** Code an output subroutine for a coroutine implementation of a
2466 ** SELECT statment. 2547 ** SELECT statment.
2467 ** 2548 **
2468 ** The data to be output is contained in pIn->iSdst. There are 2549 ** The data to be output is contained in pIn->iSdst. There are
2469 ** pIn->nSdst columns to be output. pDest is where the output should 2550 ** pIn->nSdst columns to be output. pDest is where the output should
2470 ** be sent. 2551 ** be sent.
2471 ** 2552 **
2472 ** regReturn is the number of the register holding the subroutine 2553 ** regReturn is the number of the register holding the subroutine
2473 ** return address. 2554 ** return address.
2474 ** 2555 **
(...skipping 19 matching lines...) Expand all
2494 Vdbe *v = pParse->pVdbe; 2575 Vdbe *v = pParse->pVdbe;
2495 int iContinue; 2576 int iContinue;
2496 int addr; 2577 int addr;
2497 2578
2498 addr = sqlite3VdbeCurrentAddr(v); 2579 addr = sqlite3VdbeCurrentAddr(v);
2499 iContinue = sqlite3VdbeMakeLabel(v); 2580 iContinue = sqlite3VdbeMakeLabel(v);
2500 2581
2501 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 2582 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
2502 */ 2583 */
2503 if( regPrev ){ 2584 if( regPrev ){
2504 int j1, j2; 2585 int addr1, addr2;
2505 j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); 2586 addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
2506 j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, 2587 addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
2507 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 2588 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
2508 sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v); 2589 sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
2509 sqlite3VdbeJumpHere(v, j1); 2590 sqlite3VdbeJumpHere(v, addr1);
2510 sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); 2591 sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
2511 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); 2592 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
2512 } 2593 }
2513 if( pParse->db->mallocFailed ) return 0; 2594 if( pParse->db->mallocFailed ) return 0;
2514 2595
2515 /* Suppress the first OFFSET entries if there is an OFFSET clause 2596 /* Suppress the first OFFSET entries if there is an OFFSET clause
2516 */ 2597 */
2517 codeOffset(v, p->iOffset, iContinue); 2598 codeOffset(v, p->iOffset, iContinue);
2518 2599
2600 assert( pDest->eDest!=SRT_Exists );
2601 assert( pDest->eDest!=SRT_Table );
2519 switch( pDest->eDest ){ 2602 switch( pDest->eDest ){
2520 /* Store the result as data using a unique key. 2603 /* Store the result as data using a unique key.
2521 */ 2604 */
2522 case SRT_Table:
2523 case SRT_EphemTab: { 2605 case SRT_EphemTab: {
2524 int r1 = sqlite3GetTempReg(pParse); 2606 int r1 = sqlite3GetTempReg(pParse);
2525 int r2 = sqlite3GetTempReg(pParse); 2607 int r2 = sqlite3GetTempReg(pParse);
2526 testcase( pDest->eDest==SRT_Table );
2527 testcase( pDest->eDest==SRT_EphemTab );
2528 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); 2608 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
2529 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); 2609 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
2530 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); 2610 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
2531 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 2611 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
2532 sqlite3ReleaseTempReg(pParse, r2); 2612 sqlite3ReleaseTempReg(pParse, r2);
2533 sqlite3ReleaseTempReg(pParse, r1); 2613 sqlite3ReleaseTempReg(pParse, r1);
2534 break; 2614 break;
2535 } 2615 }
2536 2616
2537 #ifndef SQLITE_OMIT_SUBQUERY 2617 #ifndef SQLITE_OMIT_SUBQUERY
2538 /* If we are creating a set for an "expr IN (SELECT ...)" construct, 2618 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
2539 ** then there should be a single item on the stack. Write this 2619 ** then there should be a single item on the stack. Write this
2540 ** item into the set table with bogus data. 2620 ** item into the set table with bogus data.
2541 */ 2621 */
2542 case SRT_Set: { 2622 case SRT_Set: {
2543 int r1; 2623 int r1;
2544 assert( pIn->nSdst==1 ); 2624 assert( pIn->nSdst==1 || pParse->nErr>0 );
2545 pDest->affSdst = 2625 pDest->affSdst =
2546 sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst); 2626 sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
2547 r1 = sqlite3GetTempReg(pParse); 2627 r1 = sqlite3GetTempReg(pParse);
2548 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1); 2628 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
2549 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1); 2629 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
2550 sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1); 2630 sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
2551 sqlite3ReleaseTempReg(pParse, r1); 2631 sqlite3ReleaseTempReg(pParse, r1);
2552 break; 2632 break;
2553 } 2633 }
2554 2634
2555 #if 0 /* Never occurs on an ORDER BY query */
2556 /* If any row exist in the result set, record that fact and abort.
2557 */
2558 case SRT_Exists: {
2559 sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
2560 /* The LIMIT clause will terminate the loop for us */
2561 break;
2562 }
2563 #endif
2564
2565 /* If this is a scalar select that is part of an expression, then 2635 /* If this is a scalar select that is part of an expression, then
2566 ** store the results in the appropriate memory cell and break out 2636 ** store the results in the appropriate memory cell and break out
2567 ** of the scan loop. 2637 ** of the scan loop.
2568 */ 2638 */
2569 case SRT_Mem: { 2639 case SRT_Mem: {
2570 assert( pIn->nSdst==1 ); 2640 assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
2571 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1); 2641 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
2572 /* The LIMIT clause will jump out of the loop for us */ 2642 /* The LIMIT clause will jump out of the loop for us */
2573 break; 2643 break;
2574 } 2644 }
2575 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 2645 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
2576 2646
2577 /* The results are stored in a sequence of registers 2647 /* The results are stored in a sequence of registers
2578 ** starting at pDest->iSdst. Then the co-routine yields. 2648 ** starting at pDest->iSdst. Then the co-routine yields.
2579 */ 2649 */
2580 case SRT_Coroutine: { 2650 case SRT_Coroutine: {
2581 if( pDest->iSdst==0 ){ 2651 if( pDest->iSdst==0 ){
2582 pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); 2652 pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
2583 pDest->nSdst = pIn->nSdst; 2653 pDest->nSdst = pIn->nSdst;
2584 } 2654 }
2585 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst); 2655 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
2586 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 2656 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
2587 break; 2657 break;
2588 } 2658 }
2589 2659
2590 /* If none of the above, then the result destination must be 2660 /* If none of the above, then the result destination must be
2591 ** SRT_Output. This routine is never called with any other 2661 ** SRT_Output. This routine is never called with any other
2592 ** destination other than the ones handled above or SRT_Output. 2662 ** destination other than the ones handled above or SRT_Output.
2593 ** 2663 **
2594 ** For SRT_Output, results are stored in a sequence of registers. 2664 ** For SRT_Output, results are stored in a sequence of registers.
2595 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to 2665 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
2596 ** return the next row of result. 2666 ** return the next row of result.
2597 */ 2667 */
2598 default: { 2668 default: {
2599 assert( pDest->eDest==SRT_Output ); 2669 assert( pDest->eDest==SRT_Output );
2600 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); 2670 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
2601 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); 2671 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
2602 break; 2672 break;
2603 } 2673 }
2604 } 2674 }
2605 2675
2606 /* Jump to the end of the loop if the LIMIT is reached. 2676 /* Jump to the end of the loop if the LIMIT is reached.
2607 */ 2677 */
2608 if( p->iLimit ){ 2678 if( p->iLimit ){
2609 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v); 2679 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
2610 } 2680 }
2611 2681
2612 /* Generate the subroutine return 2682 /* Generate the subroutine return
2613 */ 2683 */
2614 sqlite3VdbeResolveLabel(v, iContinue); 2684 sqlite3VdbeResolveLabel(v, iContinue);
2615 sqlite3VdbeAddOp1(v, OP_Return, regReturn); 2685 sqlite3VdbeAddOp1(v, OP_Return, regReturn);
2616 2686
2617 return addr; 2687 return addr;
2618 } 2688 }
2619 2689
(...skipping 107 matching lines...) Expand 10 before | Expand all | Expand 10 after
2727 int addrAltB; /* Address of the A<B subroutine */ 2797 int addrAltB; /* Address of the A<B subroutine */
2728 int addrAeqB; /* Address of the A==B subroutine */ 2798 int addrAeqB; /* Address of the A==B subroutine */
2729 int addrAgtB; /* Address of the A>B subroutine */ 2799 int addrAgtB; /* Address of the A>B subroutine */
2730 int regLimitA; /* Limit register for select-A */ 2800 int regLimitA; /* Limit register for select-A */
2731 int regLimitB; /* Limit register for select-A */ 2801 int regLimitB; /* Limit register for select-A */
2732 int regPrev; /* A range of registers to hold previous output */ 2802 int regPrev; /* A range of registers to hold previous output */
2733 int savedLimit; /* Saved value of p->iLimit */ 2803 int savedLimit; /* Saved value of p->iLimit */
2734 int savedOffset; /* Saved value of p->iOffset */ 2804 int savedOffset; /* Saved value of p->iOffset */
2735 int labelCmpr; /* Label for the start of the merge algorithm */ 2805 int labelCmpr; /* Label for the start of the merge algorithm */
2736 int labelEnd; /* Label for the end of the overall SELECT stmt */ 2806 int labelEnd; /* Label for the end of the overall SELECT stmt */
2737 int j1; /* Jump instructions that get retargetted */ 2807 int addr1; /* Jump instructions that get retargetted */
2738 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ 2808 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
2739 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ 2809 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
2740 KeyInfo *pKeyMerge; /* Comparison information for merging rows */ 2810 KeyInfo *pKeyMerge; /* Comparison information for merging rows */
2741 sqlite3 *db; /* Database connection */ 2811 sqlite3 *db; /* Database connection */
2742 ExprList *pOrderBy; /* The ORDER BY clause */ 2812 ExprList *pOrderBy; /* The ORDER BY clause */
2743 int nOrderBy; /* Number of terms in the ORDER BY clause */ 2813 int nOrderBy; /* Number of terms in the ORDER BY clause */
2744 int *aPermute; /* Mapping from ORDER BY terms to result set columns */ 2814 int *aPermute; /* Mapping from ORDER BY terms to result set columns */
2745 #ifndef SQLITE_OMIT_EXPLAIN 2815 #ifndef SQLITE_OMIT_EXPLAIN
2746 int iSub1; /* EQP id of left-hand query */ 2816 int iSub1; /* EQP id of left-hand query */
2747 int iSub2; /* EQP id of right-hand query */ 2817 int iSub2; /* EQP id of right-hand query */
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
2791 ** the permutation used to determine if the next 2861 ** the permutation used to determine if the next
2792 ** row of results comes from selectA or selectB. Also add explicit 2862 ** row of results comes from selectA or selectB. Also add explicit
2793 ** collations to the ORDER BY clause terms so that when the subqueries 2863 ** collations to the ORDER BY clause terms so that when the subqueries
2794 ** to the right and the left are evaluated, they use the correct 2864 ** to the right and the left are evaluated, they use the correct
2795 ** collation. 2865 ** collation.
2796 */ 2866 */
2797 aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy); 2867 aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
2798 if( aPermute ){ 2868 if( aPermute ){
2799 struct ExprList_item *pItem; 2869 struct ExprList_item *pItem;
2800 for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){ 2870 for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
2801 assert( pItem->u.x.iOrderByCol>0 2871 assert( pItem->u.x.iOrderByCol>0 );
2802 && pItem->u.x.iOrderByCol<=p->pEList->nExpr ); 2872 assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
2803 aPermute[i] = pItem->u.x.iOrderByCol - 1; 2873 aPermute[i] = pItem->u.x.iOrderByCol - 1;
2804 } 2874 }
2805 pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1); 2875 pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
2806 }else{ 2876 }else{
2807 pKeyMerge = 0; 2877 pKeyMerge = 0;
2808 } 2878 }
2809 2879
2810 /* Reattach the ORDER BY clause to the query. 2880 /* Reattach the ORDER BY clause to the query.
2811 */ 2881 */
2812 p->pOrderBy = pOrderBy; 2882 p->pOrderBy = pOrderBy;
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after
2863 regAddrB = ++pParse->nMem; 2933 regAddrB = ++pParse->nMem;
2864 regOutA = ++pParse->nMem; 2934 regOutA = ++pParse->nMem;
2865 regOutB = ++pParse->nMem; 2935 regOutB = ++pParse->nMem;
2866 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); 2936 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
2867 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); 2937 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
2868 2938
2869 /* Generate a coroutine to evaluate the SELECT statement to the 2939 /* Generate a coroutine to evaluate the SELECT statement to the
2870 ** left of the compound operator - the "A" select. 2940 ** left of the compound operator - the "A" select.
2871 */ 2941 */
2872 addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; 2942 addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
2873 j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); 2943 addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
2874 VdbeComment((v, "left SELECT")); 2944 VdbeComment((v, "left SELECT"));
2875 pPrior->iLimit = regLimitA; 2945 pPrior->iLimit = regLimitA;
2876 explainSetInteger(iSub1, pParse->iNextSelectId); 2946 explainSetInteger(iSub1, pParse->iNextSelectId);
2877 sqlite3Select(pParse, pPrior, &destA); 2947 sqlite3Select(pParse, pPrior, &destA);
2878 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA); 2948 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
2879 sqlite3VdbeJumpHere(v, j1); 2949 sqlite3VdbeJumpHere(v, addr1);
2880 2950
2881 /* Generate a coroutine to evaluate the SELECT statement on 2951 /* Generate a coroutine to evaluate the SELECT statement on
2882 ** the right - the "B" select 2952 ** the right - the "B" select
2883 */ 2953 */
2884 addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; 2954 addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
2885 j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); 2955 addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
2886 VdbeComment((v, "right SELECT")); 2956 VdbeComment((v, "right SELECT"));
2887 savedLimit = p->iLimit; 2957 savedLimit = p->iLimit;
2888 savedOffset = p->iOffset; 2958 savedOffset = p->iOffset;
2889 p->iLimit = regLimitB; 2959 p->iLimit = regLimitB;
2890 p->iOffset = 0; 2960 p->iOffset = 0;
2891 explainSetInteger(iSub2, pParse->iNextSelectId); 2961 explainSetInteger(iSub2, pParse->iNextSelectId);
2892 sqlite3Select(pParse, p, &destB); 2962 sqlite3Select(pParse, p, &destB);
2893 p->iLimit = savedLimit; 2963 p->iLimit = savedLimit;
2894 p->iOffset = savedOffset; 2964 p->iOffset = savedOffset;
2895 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB); 2965 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
(...skipping 20 matching lines...) Expand all
2916 /* Generate a subroutine to run when the results from select A 2986 /* Generate a subroutine to run when the results from select A
2917 ** are exhausted and only data in select B remains. 2987 ** are exhausted and only data in select B remains.
2918 */ 2988 */
2919 if( op==TK_EXCEPT || op==TK_INTERSECT ){ 2989 if( op==TK_EXCEPT || op==TK_INTERSECT ){
2920 addrEofA_noB = addrEofA = labelEnd; 2990 addrEofA_noB = addrEofA = labelEnd;
2921 }else{ 2991 }else{
2922 VdbeNoopComment((v, "eof-A subroutine")); 2992 VdbeNoopComment((v, "eof-A subroutine"));
2923 addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 2993 addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
2924 addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); 2994 addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
2925 VdbeCoverage(v); 2995 VdbeCoverage(v);
2926 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA); 2996 sqlite3VdbeGoto(v, addrEofA);
2927 p->nSelectRow += pPrior->nSelectRow; 2997 p->nSelectRow += pPrior->nSelectRow;
2928 } 2998 }
2929 2999
2930 /* Generate a subroutine to run when the results from select B 3000 /* Generate a subroutine to run when the results from select B
2931 ** are exhausted and only data in select A remains. 3001 ** are exhausted and only data in select A remains.
2932 */ 3002 */
2933 if( op==TK_INTERSECT ){ 3003 if( op==TK_INTERSECT ){
2934 addrEofB = addrEofA; 3004 addrEofB = addrEofA;
2935 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 3005 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
2936 }else{ 3006 }else{
2937 VdbeNoopComment((v, "eof-B subroutine")); 3007 VdbeNoopComment((v, "eof-B subroutine"));
2938 addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3008 addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
2939 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); 3009 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
2940 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB); 3010 sqlite3VdbeGoto(v, addrEofB);
2941 } 3011 }
2942 3012
2943 /* Generate code to handle the case of A<B 3013 /* Generate code to handle the case of A<B
2944 */ 3014 */
2945 VdbeNoopComment((v, "A-lt-B subroutine")); 3015 VdbeNoopComment((v, "A-lt-B subroutine"));
2946 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3016 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
2947 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3017 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
2948 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 3018 sqlite3VdbeGoto(v, labelCmpr);
2949 3019
2950 /* Generate code to handle the case of A==B 3020 /* Generate code to handle the case of A==B
2951 */ 3021 */
2952 if( op==TK_ALL ){ 3022 if( op==TK_ALL ){
2953 addrAeqB = addrAltB; 3023 addrAeqB = addrAltB;
2954 }else if( op==TK_INTERSECT ){ 3024 }else if( op==TK_INTERSECT ){
2955 addrAeqB = addrAltB; 3025 addrAeqB = addrAltB;
2956 addrAltB++; 3026 addrAltB++;
2957 }else{ 3027 }else{
2958 VdbeNoopComment((v, "A-eq-B subroutine")); 3028 VdbeNoopComment((v, "A-eq-B subroutine"));
2959 addrAeqB = 3029 addrAeqB =
2960 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3030 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
2961 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 3031 sqlite3VdbeGoto(v, labelCmpr);
2962 } 3032 }
2963 3033
2964 /* Generate code to handle the case of A>B 3034 /* Generate code to handle the case of A>B
2965 */ 3035 */
2966 VdbeNoopComment((v, "A-gt-B subroutine")); 3036 VdbeNoopComment((v, "A-gt-B subroutine"));
2967 addrAgtB = sqlite3VdbeCurrentAddr(v); 3037 addrAgtB = sqlite3VdbeCurrentAddr(v);
2968 if( op==TK_ALL || op==TK_UNION ){ 3038 if( op==TK_ALL || op==TK_UNION ){
2969 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 3039 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
2970 } 3040 }
2971 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 3041 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
2972 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 3042 sqlite3VdbeGoto(v, labelCmpr);
2973 3043
2974 /* This code runs once to initialize everything. 3044 /* This code runs once to initialize everything.
2975 */ 3045 */
2976 sqlite3VdbeJumpHere(v, j1); 3046 sqlite3VdbeJumpHere(v, addr1);
2977 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); 3047 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
2978 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 3048 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
2979 3049
2980 /* Implement the main merge loop 3050 /* Implement the main merge loop
2981 */ 3051 */
2982 sqlite3VdbeResolveLabel(v, labelCmpr); 3052 sqlite3VdbeResolveLabel(v, labelCmpr);
2983 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); 3053 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
2984 sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, 3054 sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
2985 (char*)pKeyMerge, P4_KEYINFO); 3055 (char*)pKeyMerge, P4_KEYINFO);
2986 sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); 3056 sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
2987 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); 3057 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
2988 3058
2989 /* Jump to the this point in order to terminate the query. 3059 /* Jump to the this point in order to terminate the query.
2990 */ 3060 */
2991 sqlite3VdbeResolveLabel(v, labelEnd); 3061 sqlite3VdbeResolveLabel(v, labelEnd);
2992 3062
2993 /* Set the number of output columns 3063 /* Set the number of output columns
2994 */ 3064 */
2995 if( pDest->eDest==SRT_Output ){ 3065 if( pDest->eDest==SRT_Output ){
2996 Select *pFirst = pPrior; 3066 Select *pFirst = pPrior;
2997 while( pFirst->pPrior ) pFirst = pFirst->pPrior; 3067 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
2998 generateColumnNames(pParse, 0, pFirst->pEList); 3068 generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
2999 } 3069 }
3000 3070
3001 /* Reassembly the compound query so that it will be freed correctly 3071 /* Reassembly the compound query so that it will be freed correctly
3002 ** by the calling function */ 3072 ** by the calling function */
3003 if( p->pPrior ){ 3073 if( p->pPrior ){
3004 sqlite3SelectDelete(db, p->pPrior); 3074 sqlite3SelectDelete(db, p->pPrior);
3005 } 3075 }
3006 p->pPrior = pPrior; 3076 p->pPrior = pPrior;
3007 pPrior->pNext = p; 3077 pPrior->pNext = p;
3008 3078
3009 /*** TBD: Insert subroutine calls to close cursors on incomplete 3079 /*** TBD: Insert subroutine calls to close cursors on incomplete
3010 **** subqueries ****/ 3080 **** subqueries ****/
3011 explainComposite(pParse, p->op, iSub1, iSub2, 0); 3081 explainComposite(pParse, p->op, iSub1, iSub2, 0);
3012 return SQLITE_OK; 3082 return pParse->nErr!=0;
3013 } 3083 }
3014 #endif 3084 #endif
3015 3085
3016 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3086 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3017 /* Forward Declarations */ 3087 /* Forward Declarations */
3018 static void substExprList(sqlite3*, ExprList*, int, ExprList*); 3088 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
3019 static void substSelect(sqlite3*, Select *, int, ExprList *); 3089 static void substSelect(sqlite3*, Select *, int, ExprList*, int);
3020 3090
3021 /* 3091 /*
3022 ** Scan through the expression pExpr. Replace every reference to 3092 ** Scan through the expression pExpr. Replace every reference to
3023 ** a column in table number iTable with a copy of the iColumn-th 3093 ** a column in table number iTable with a copy of the iColumn-th
3024 ** entry in pEList. (But leave references to the ROWID column 3094 ** entry in pEList. (But leave references to the ROWID column
3025 ** unchanged.) 3095 ** unchanged.)
3026 ** 3096 **
3027 ** This routine is part of the flattening procedure. A subquery 3097 ** This routine is part of the flattening procedure. A subquery
3028 ** whose result set is defined by pEList appears as entry in the 3098 ** whose result set is defined by pEList appears as entry in the
3029 ** FROM clause of a SELECT such that the VDBE cursor assigned to that 3099 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
(...skipping 16 matching lines...) Expand all
3046 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 3116 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
3047 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 3117 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
3048 pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0); 3118 pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
3049 sqlite3ExprDelete(db, pExpr); 3119 sqlite3ExprDelete(db, pExpr);
3050 pExpr = pNew; 3120 pExpr = pNew;
3051 } 3121 }
3052 }else{ 3122 }else{
3053 pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList); 3123 pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
3054 pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList); 3124 pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
3055 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 3125 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
3056 substSelect(db, pExpr->x.pSelect, iTable, pEList); 3126 substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
3057 }else{ 3127 }else{
3058 substExprList(db, pExpr->x.pList, iTable, pEList); 3128 substExprList(db, pExpr->x.pList, iTable, pEList);
3059 } 3129 }
3060 } 3130 }
3061 return pExpr; 3131 return pExpr;
3062 } 3132 }
3063 static void substExprList( 3133 static void substExprList(
3064 sqlite3 *db, /* Report malloc errors here */ 3134 sqlite3 *db, /* Report malloc errors here */
3065 ExprList *pList, /* List to scan and in which to make substitutes */ 3135 ExprList *pList, /* List to scan and in which to make substitutes */
3066 int iTable, /* Table to be substituted */ 3136 int iTable, /* Table to be substituted */
3067 ExprList *pEList /* Substitute values */ 3137 ExprList *pEList /* Substitute values */
3068 ){ 3138 ){
3069 int i; 3139 int i;
3070 if( pList==0 ) return; 3140 if( pList==0 ) return;
3071 for(i=0; i<pList->nExpr; i++){ 3141 for(i=0; i<pList->nExpr; i++){
3072 pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList); 3142 pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
3073 } 3143 }
3074 } 3144 }
3075 static void substSelect( 3145 static void substSelect(
3076 sqlite3 *db, /* Report malloc errors here */ 3146 sqlite3 *db, /* Report malloc errors here */
3077 Select *p, /* SELECT statement in which to make substitutions */ 3147 Select *p, /* SELECT statement in which to make substitutions */
3078 int iTable, /* Table to be replaced */ 3148 int iTable, /* Table to be replaced */
3079 ExprList *pEList /* Substitute values */ 3149 ExprList *pEList, /* Substitute values */
3150 int doPrior /* Do substitutes on p->pPrior too */
3080 ){ 3151 ){
3081 SrcList *pSrc; 3152 SrcList *pSrc;
3082 struct SrcList_item *pItem; 3153 struct SrcList_item *pItem;
3083 int i; 3154 int i;
3084 if( !p ) return; 3155 if( !p ) return;
3085 substExprList(db, p->pEList, iTable, pEList); 3156 do{
3086 substExprList(db, p->pGroupBy, iTable, pEList); 3157 substExprList(db, p->pEList, iTable, pEList);
3087 substExprList(db, p->pOrderBy, iTable, pEList); 3158 substExprList(db, p->pGroupBy, iTable, pEList);
3088 p->pHaving = substExpr(db, p->pHaving, iTable, pEList); 3159 substExprList(db, p->pOrderBy, iTable, pEList);
3089 p->pWhere = substExpr(db, p->pWhere, iTable, pEList); 3160 p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
3090 substSelect(db, p->pPrior, iTable, pEList); 3161 p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
3091 pSrc = p->pSrc; 3162 pSrc = p->pSrc;
3092 assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */ 3163 assert( pSrc!=0 );
3093 if( ALWAYS(pSrc) ){
3094 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ 3164 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
3095 substSelect(db, pItem->pSelect, iTable, pEList); 3165 substSelect(db, pItem->pSelect, iTable, pEList, 1);
3166 if( pItem->fg.isTabFunc ){
3167 substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
3168 }
3096 } 3169 }
3097 } 3170 }while( doPrior && (p = p->pPrior)!=0 );
3098 } 3171 }
3099 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 3172 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
3100 3173
3101 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3174 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3102 /* 3175 /*
3103 ** This routine attempts to flatten subqueries as a performance optimization. 3176 ** This routine attempts to flatten subqueries as a performance optimization.
3104 ** This routine returns 1 if it makes changes and 0 if no flattening occurs. 3177 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
3105 ** 3178 **
3106 ** To understand the concept of flattening, consider the following 3179 ** To understand the concept of flattening, consider the following
3107 ** query: 3180 ** query:
(...skipping 14 matching lines...) Expand all
3122 ** 3195 **
3123 ** The code generated for this simplification gives the same result 3196 ** The code generated for this simplification gives the same result
3124 ** but only has to scan the data once. And because indices might 3197 ** but only has to scan the data once. And because indices might
3125 ** exist on the table t1, a complete scan of the data might be 3198 ** exist on the table t1, a complete scan of the data might be
3126 ** avoided. 3199 ** avoided.
3127 ** 3200 **
3128 ** Flattening is only attempted if all of the following are true: 3201 ** Flattening is only attempted if all of the following are true:
3129 ** 3202 **
3130 ** (1) The subquery and the outer query do not both use aggregates. 3203 ** (1) The subquery and the outer query do not both use aggregates.
3131 ** 3204 **
3132 ** (2) The subquery is not an aggregate or the outer query is not a join. 3205 ** (2) The subquery is not an aggregate or (2a) the outer query is not a join
3206 ** and (2b) the outer query does not use subqueries other than the one
3207 ** FROM-clause subquery that is a candidate for flattening. (2b is
3208 ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
3133 ** 3209 **
3134 ** (3) The subquery is not the right operand of a left outer join 3210 ** (3) The subquery is not the right operand of a left outer join
3135 ** (Originally ticket #306. Strengthened by ticket #3300) 3211 ** (Originally ticket #306. Strengthened by ticket #3300)
3136 ** 3212 **
3137 ** (4) The subquery is not DISTINCT. 3213 ** (4) The subquery is not DISTINCT.
3138 ** 3214 **
3139 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT 3215 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
3140 ** sub-queries that were excluded from this optimization. Restriction 3216 ** sub-queries that were excluded from this optimization. Restriction
3141 ** (4) has since been expanded to exclude all DISTINCT subqueries. 3217 ** (4) has since been expanded to exclude all DISTINCT subqueries.
3142 ** 3218 **
3143 ** (6) The subquery does not use aggregates or the outer query is not 3219 ** (6) The subquery does not use aggregates or the outer query is not
3144 ** DISTINCT. 3220 ** DISTINCT.
3145 ** 3221 **
3146 ** (7) The subquery has a FROM clause. TODO: For subqueries without 3222 ** (7) The subquery has a FROM clause. TODO: For subqueries without
3147 ** A FROM clause, consider adding a FROM close with the special 3223 ** A FROM clause, consider adding a FROM close with the special
3148 ** table sqlite_once that consists of a single row containing a 3224 ** table sqlite_once that consists of a single row containing a
3149 ** single NULL. 3225 ** single NULL.
3150 ** 3226 **
3151 ** (8) The subquery does not use LIMIT or the outer query is not a join. 3227 ** (8) The subquery does not use LIMIT or the outer query is not a join.
3152 ** 3228 **
3153 ** (9) The subquery does not use LIMIT or the outer query does not use 3229 ** (9) The subquery does not use LIMIT or the outer query does not use
3154 ** aggregates. 3230 ** aggregates.
3155 ** 3231 **
3156 ** (**) Restriction (10) was removed from the code on 2005-02-05 but we 3232 ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
3157 ** accidently carried the comment forward until 2014-09-15. Original 3233 ** accidently carried the comment forward until 2014-09-15. Original
3158 ** text: "The subquery does not use aggregates or the outer query does no t 3234 ** text: "The subquery does not use aggregates or the outer query
3159 ** use LIMIT." 3235 ** does not use LIMIT."
3160 ** 3236 **
3161 ** (11) The subquery and the outer query do not both have ORDER BY clauses. 3237 ** (11) The subquery and the outer query do not both have ORDER BY clauses.
3162 ** 3238 **
3163 ** (**) Not implemented. Subsumed into restriction (3). Was previously 3239 ** (**) Not implemented. Subsumed into restriction (3). Was previously
3164 ** a separate restriction deriving from ticket #350. 3240 ** a separate restriction deriving from ticket #350.
3165 ** 3241 **
3166 ** (13) The subquery and outer query do not both use LIMIT. 3242 ** (13) The subquery and outer query do not both use LIMIT.
3167 ** 3243 **
3168 ** (14) The subquery does not use OFFSET. 3244 ** (14) The subquery does not use OFFSET.
3169 ** 3245 **
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after
3236 ** the subquery before this routine runs. 3312 ** the subquery before this routine runs.
3237 */ 3313 */
3238 static int flattenSubquery( 3314 static int flattenSubquery(
3239 Parse *pParse, /* Parsing context */ 3315 Parse *pParse, /* Parsing context */
3240 Select *p, /* The parent or outer SELECT statement */ 3316 Select *p, /* The parent or outer SELECT statement */
3241 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 3317 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
3242 int isAgg, /* True if outer SELECT uses aggregate functions */ 3318 int isAgg, /* True if outer SELECT uses aggregate functions */
3243 int subqueryIsAgg /* True if the subquery uses aggregate functions */ 3319 int subqueryIsAgg /* True if the subquery uses aggregate functions */
3244 ){ 3320 ){
3245 const char *zSavedAuthContext = pParse->zAuthContext; 3321 const char *zSavedAuthContext = pParse->zAuthContext;
3246 Select *pParent; 3322 Select *pParent; /* Current UNION ALL term of the other query */
3247 Select *pSub; /* The inner query or "subquery" */ 3323 Select *pSub; /* The inner query or "subquery" */
3248 Select *pSub1; /* Pointer to the rightmost select in sub-query */ 3324 Select *pSub1; /* Pointer to the rightmost select in sub-query */
3249 SrcList *pSrc; /* The FROM clause of the outer query */ 3325 SrcList *pSrc; /* The FROM clause of the outer query */
3250 SrcList *pSubSrc; /* The FROM clause of the subquery */ 3326 SrcList *pSubSrc; /* The FROM clause of the subquery */
3251 ExprList *pList; /* The result set of the outer query */ 3327 ExprList *pList; /* The result set of the outer query */
3252 int iParent; /* VDBE cursor number of the pSub result set temp table */ 3328 int iParent; /* VDBE cursor number of the pSub result set temp table */
3253 int i; /* Loop counter */ 3329 int i; /* Loop counter */
3254 Expr *pWhere; /* The WHERE clause */ 3330 Expr *pWhere; /* The WHERE clause */
3255 struct SrcList_item *pSubitem; /* The subquery */ 3331 struct SrcList_item *pSubitem; /* The subquery */
3256 sqlite3 *db = pParse->db; 3332 sqlite3 *db = pParse->db;
3257 3333
3258 /* Check to see if flattening is permitted. Return 0 if not. 3334 /* Check to see if flattening is permitted. Return 0 if not.
3259 */ 3335 */
3260 assert( p!=0 ); 3336 assert( p!=0 );
3261 assert( p->pPrior==0 ); /* Unable to flatten compound queries */ 3337 assert( p->pPrior==0 ); /* Unable to flatten compound queries */
3262 if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; 3338 if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
3263 pSrc = p->pSrc; 3339 pSrc = p->pSrc;
3264 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 3340 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
3265 pSubitem = &pSrc->a[iFrom]; 3341 pSubitem = &pSrc->a[iFrom];
3266 iParent = pSubitem->iCursor; 3342 iParent = pSubitem->iCursor;
3267 pSub = pSubitem->pSelect; 3343 pSub = pSubitem->pSelect;
3268 assert( pSub!=0 ); 3344 assert( pSub!=0 );
3269 if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ 3345 if( subqueryIsAgg ){
3270 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ 3346 if( isAgg ) return 0; /* Restriction (1) */
3347 if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */
3348 if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
3349 || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
3350 || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
3351 ){
3352 return 0; /* Restriction (2b) */
3353 }
3354 }
3355
3271 pSubSrc = pSub->pSrc; 3356 pSubSrc = pSub->pSrc;
3272 assert( pSubSrc ); 3357 assert( pSubSrc );
3273 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 3358 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
3274 ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET 3359 ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
3275 ** because they could be computed at compile-time. But when LIMIT and OFFSET 3360 ** because they could be computed at compile-time. But when LIMIT and OFFSET
3276 ** became arbitrary expressions, we were forced to add restrictions (13) 3361 ** became arbitrary expressions, we were forced to add restrictions (13)
3277 ** and (14). */ 3362 ** and (14). */
3278 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 3363 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
3279 if( pSub->pOffset ) return 0; /* Restriction (14) */ 3364 if( pSub->pOffset ) return 0; /* Restriction (14) */
3280 if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ 3365 if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after
3330 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 3415 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
3331 ** 3416 **
3332 ** But the t2.x>0 test will always fail on a NULL row of t2, which 3417 ** But the t2.x>0 test will always fail on a NULL row of t2, which
3333 ** effectively converts the OUTER JOIN into an INNER JOIN. 3418 ** effectively converts the OUTER JOIN into an INNER JOIN.
3334 ** 3419 **
3335 ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: 3420 ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
3336 ** Ticket #3300 shows that flattening the right term of a LEFT JOIN 3421 ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
3337 ** is fraught with danger. Best to avoid the whole thing. If the 3422 ** is fraught with danger. Best to avoid the whole thing. If the
3338 ** subquery is the right term of a LEFT JOIN, then do not flatten. 3423 ** subquery is the right term of a LEFT JOIN, then do not flatten.
3339 */ 3424 */
3340 if( (pSubitem->jointype & JT_OUTER)!=0 ){ 3425 if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
3341 return 0; 3426 return 0;
3342 } 3427 }
3343 3428
3344 /* Restriction 17: If the sub-query is a compound SELECT, then it must 3429 /* Restriction 17: If the sub-query is a compound SELECT, then it must
3345 ** use only the UNION ALL operator. And none of the simple select queries 3430 ** use only the UNION ALL operator. And none of the simple select queries
3346 ** that make up the compound SELECT are allowed to be aggregate or distinct 3431 ** that make up the compound SELECT are allowed to be aggregate or distinct
3347 ** queries. 3432 ** queries.
3348 */ 3433 */
3349 if( pSub->pPrior ){ 3434 if( pSub->pPrior ){
3350 if( pSub->pOrderBy ){ 3435 if( pSub->pOrderBy ){
3351 return 0; /* Restriction 20 */ 3436 return 0; /* Restriction 20 */
3352 } 3437 }
3353 if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ 3438 if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
3354 return 0; 3439 return 0;
3355 } 3440 }
3356 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ 3441 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
3357 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 3442 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
3358 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 3443 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
3359 assert( pSub->pSrc!=0 ); 3444 assert( pSub->pSrc!=0 );
3445 assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
3360 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 3446 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
3361 || (pSub1->pPrior && pSub1->op!=TK_ALL) 3447 || (pSub1->pPrior && pSub1->op!=TK_ALL)
3362 || pSub1->pSrc->nSrc<1 3448 || pSub1->pSrc->nSrc<1
3363 || pSub->pEList->nExpr!=pSub1->pEList->nExpr
3364 ){ 3449 ){
3365 return 0; 3450 return 0;
3366 } 3451 }
3367 testcase( pSub1->pSrc->nSrc>1 ); 3452 testcase( pSub1->pSrc->nSrc>1 );
3368 } 3453 }
3369 3454
3370 /* Restriction 18. */ 3455 /* Restriction 18. */
3371 if( p->pOrderBy ){ 3456 if( p->pOrderBy ){
3372 int ii; 3457 int ii;
3373 for(ii=0; ii<p->pOrderBy->nExpr; ii++){ 3458 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
(...skipping 127 matching lines...) Expand 10 before | Expand all | Expand 10 after
3501 */ 3586 */
3502 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ 3587 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
3503 int nSubSrc; 3588 int nSubSrc;
3504 u8 jointype = 0; 3589 u8 jointype = 0;
3505 pSubSrc = pSub->pSrc; /* FROM clause of subquery */ 3590 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
3506 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ 3591 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
3507 pSrc = pParent->pSrc; /* FROM clause of the outer query */ 3592 pSrc = pParent->pSrc; /* FROM clause of the outer query */
3508 3593
3509 if( pSrc ){ 3594 if( pSrc ){
3510 assert( pParent==p ); /* First time through the loop */ 3595 assert( pParent==p ); /* First time through the loop */
3511 jointype = pSubitem->jointype; 3596 jointype = pSubitem->fg.jointype;
3512 }else{ 3597 }else{
3513 assert( pParent!=p ); /* 2nd and subsequent times through the loop */ 3598 assert( pParent!=p ); /* 2nd and subsequent times through the loop */
3514 pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); 3599 pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
3515 if( pSrc==0 ){ 3600 if( pSrc==0 ){
3516 assert( db->mallocFailed ); 3601 assert( db->mallocFailed );
3517 break; 3602 break;
3518 } 3603 }
3519 } 3604 }
3520 3605
3521 /* The subquery uses a single slot of the FROM clause of the outer 3606 /* The subquery uses a single slot of the FROM clause of the outer
3522 ** query. If the subquery has more than one element in its FROM clause, 3607 ** query. If the subquery has more than one element in its FROM clause,
3523 ** then expand the outer query to make space for it to hold all elements 3608 ** then expand the outer query to make space for it to hold all elements
3524 ** of the subquery. 3609 ** of the subquery.
3525 ** 3610 **
3526 ** Example: 3611 ** Example:
3527 ** 3612 **
3528 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; 3613 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
3529 ** 3614 **
3530 ** The outer query has 3 slots in its FROM clause. One slot of the 3615 ** The outer query has 3 slots in its FROM clause. One slot of the
3531 ** outer query (the middle slot) is used by the subquery. The next 3616 ** outer query (the middle slot) is used by the subquery. The next
3532 ** block of code will expand the out query to 4 slots. The middle 3617 ** block of code will expand the outer query FROM clause to 4 slots.
3533 ** slot is expanded to two slots in order to make space for the 3618 ** The middle slot is expanded to two slots in order to make space
3534 ** two elements in the FROM clause of the subquery. 3619 ** for the two elements in the FROM clause of the subquery.
3535 */ 3620 */
3536 if( nSubSrc>1 ){ 3621 if( nSubSrc>1 ){
3537 pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); 3622 pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
3538 if( db->mallocFailed ){ 3623 if( db->mallocFailed ){
3539 break; 3624 break;
3540 } 3625 }
3541 } 3626 }
3542 3627
3543 /* Transfer the FROM clause terms from the subquery into the 3628 /* Transfer the FROM clause terms from the subquery into the
3544 ** outer query. 3629 ** outer query.
3545 */ 3630 */
3546 for(i=0; i<nSubSrc; i++){ 3631 for(i=0; i<nSubSrc; i++){
3547 sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); 3632 sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
3633 assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
3548 pSrc->a[i+iFrom] = pSubSrc->a[i]; 3634 pSrc->a[i+iFrom] = pSubSrc->a[i];
3549 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 3635 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
3550 } 3636 }
3551 pSrc->a[iFrom].jointype = jointype; 3637 pSrc->a[iFrom].fg.jointype = jointype;
3552 3638
3553 /* Now begin substituting subquery result set expressions for 3639 /* Now begin substituting subquery result set expressions for
3554 ** references to the iParent in the outer query. 3640 ** references to the iParent in the outer query.
3555 ** 3641 **
3556 ** Example: 3642 ** Example:
3557 ** 3643 **
3558 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 3644 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
3559 ** \ \_____________ subquery __________/ / 3645 ** \ \_____________ subquery __________/ /
3560 ** \_____________________ outer query ______________________________/ 3646 ** \_____________________ outer query ______________________________/
3561 ** 3647 **
3562 ** We look at every expression in the outer query and every place we see 3648 ** We look at every expression in the outer query and every place we see
3563 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 3649 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
3564 */ 3650 */
3565 pList = pParent->pEList; 3651 pList = pParent->pEList;
3566 for(i=0; i<pList->nExpr; i++){ 3652 for(i=0; i<pList->nExpr; i++){
3567 if( pList->a[i].zName==0 ){ 3653 if( pList->a[i].zName==0 ){
3568 char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan); 3654 char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
3569 sqlite3Dequote(zName); 3655 sqlite3Dequote(zName);
3570 pList->a[i].zName = zName; 3656 pList->a[i].zName = zName;
3571 } 3657 }
3572 } 3658 }
3573 substExprList(db, pParent->pEList, iParent, pSub->pEList);
3574 if( isAgg ){
3575 substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
3576 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
3577 }
3578 if( pSub->pOrderBy ){ 3659 if( pSub->pOrderBy ){
3579 /* At this point, any non-zero iOrderByCol values indicate that the 3660 /* At this point, any non-zero iOrderByCol values indicate that the
3580 ** ORDER BY column expression is identical to the iOrderByCol'th 3661 ** ORDER BY column expression is identical to the iOrderByCol'th
3581 ** expression returned by SELECT statement pSub. Since these values 3662 ** expression returned by SELECT statement pSub. Since these values
3582 ** do not necessarily correspond to columns in SELECT statement pParent, 3663 ** do not necessarily correspond to columns in SELECT statement pParent,
3583 ** zero them before transfering the ORDER BY clause. 3664 ** zero them before transfering the ORDER BY clause.
3584 ** 3665 **
3585 ** Not doing this may cause an error if a subsequent call to this 3666 ** Not doing this may cause an error if a subsequent call to this
3586 ** function attempts to flatten a compound sub-query into pParent 3667 ** function attempts to flatten a compound sub-query into pParent
3587 ** (the only way this can happen is if the compound sub-query is 3668 ** (the only way this can happen is if the compound sub-query is
3588 ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ 3669 ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
3589 ExprList *pOrderBy = pSub->pOrderBy; 3670 ExprList *pOrderBy = pSub->pOrderBy;
3590 for(i=0; i<pOrderBy->nExpr; i++){ 3671 for(i=0; i<pOrderBy->nExpr; i++){
3591 pOrderBy->a[i].u.x.iOrderByCol = 0; 3672 pOrderBy->a[i].u.x.iOrderByCol = 0;
3592 } 3673 }
3593 assert( pParent->pOrderBy==0 ); 3674 assert( pParent->pOrderBy==0 );
3594 assert( pSub->pPrior==0 ); 3675 assert( pSub->pPrior==0 );
3595 pParent->pOrderBy = pOrderBy; 3676 pParent->pOrderBy = pOrderBy;
3596 pSub->pOrderBy = 0; 3677 pSub->pOrderBy = 0;
3597 }else if( pParent->pOrderBy ){
3598 substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
3599 } 3678 }
3600 if( pSub->pWhere ){ 3679 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
3601 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
3602 }else{
3603 pWhere = 0;
3604 }
3605 if( subqueryIsAgg ){ 3680 if( subqueryIsAgg ){
3606 assert( pParent->pHaving==0 ); 3681 assert( pParent->pHaving==0 );
3607 pParent->pHaving = pParent->pWhere; 3682 pParent->pHaving = pParent->pWhere;
3608 pParent->pWhere = pWhere; 3683 pParent->pWhere = pWhere;
3609 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
3610 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 3684 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
3611 sqlite3ExprDup(db, pSub->pHaving, 0)); 3685 sqlite3ExprDup(db, pSub->pHaving, 0));
3612 assert( pParent->pGroupBy==0 ); 3686 assert( pParent->pGroupBy==0 );
3613 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0); 3687 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
3614 }else{ 3688 }else{
3615 pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
3616 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere); 3689 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
3617 } 3690 }
3691 substSelect(db, pParent, iParent, pSub->pEList, 0);
3618 3692
3619 /* The flattened query is distinct if either the inner or the 3693 /* The flattened query is distinct if either the inner or the
3620 ** outer query is distinct. 3694 ** outer query is distinct.
3621 */ 3695 */
3622 pParent->selFlags |= pSub->selFlags & SF_Distinct; 3696 pParent->selFlags |= pSub->selFlags & SF_Distinct;
3623 3697
3624 /* 3698 /*
3625 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 3699 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
3626 ** 3700 **
3627 ** One is tempted to try to add a and b to combine the limits. But this 3701 ** One is tempted to try to add a and b to combine the limits. But this
3628 ** does not work if either limit is negative. 3702 ** does not work if either limit is negative.
3629 */ 3703 */
3630 if( pSub->pLimit ){ 3704 if( pSub->pLimit ){
3631 pParent->pLimit = pSub->pLimit; 3705 pParent->pLimit = pSub->pLimit;
3632 pSub->pLimit = 0; 3706 pSub->pLimit = 0;
3633 } 3707 }
3634 } 3708 }
3635 3709
3636 /* Finially, delete what is left of the subquery and return 3710 /* Finially, delete what is left of the subquery and return
3637 ** success. 3711 ** success.
3638 */ 3712 */
3639 sqlite3SelectDelete(db, pSub1); 3713 sqlite3SelectDelete(db, pSub1);
3640 3714
3641 #if SELECTTRACE_ENABLED 3715 #if SELECTTRACE_ENABLED
3642 if( sqlite3SelectTrace & 0x100 ){ 3716 if( sqlite3SelectTrace & 0x100 ){
3643 sqlite3DebugPrintf("After flattening:\n"); 3717 SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
3644 sqlite3TreeViewSelect(0, p, 0); 3718 sqlite3TreeViewSelect(0, p, 0);
3645 } 3719 }
3646 #endif 3720 #endif
3647 3721
3648 return 1; 3722 return 1;
3649 } 3723 }
3650 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 3724 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
3651 3725
3726
3727
3728 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3729 /*
3730 ** Make copies of relevant WHERE clause terms of the outer query into
3731 ** the WHERE clause of subquery. Example:
3732 **
3733 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
3734 **
3735 ** Transformed into:
3736 **
3737 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
3738 ** WHERE x=5 AND y=10;
3739 **
3740 ** The hope is that the terms added to the inner query will make it more
3741 ** efficient.
3742 **
3743 ** Do not attempt this optimization if:
3744 **
3745 ** (1) The inner query is an aggregate. (In that case, we'd really want
3746 ** to copy the outer WHERE-clause terms onto the HAVING clause of the
3747 ** inner query. But they probably won't help there so do not bother.)
3748 **
3749 ** (2) The inner query is the recursive part of a common table expression.
3750 **
3751 ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
3752 ** close would change the meaning of the LIMIT).
3753 **
3754 ** (4) The inner query is the right operand of a LEFT JOIN. (The caller
3755 ** enforces this restriction since this routine does not have enough
3756 ** information to know.)
3757 **
3758 ** (5) The WHERE clause expression originates in the ON or USING clause
3759 ** of a LEFT JOIN.
3760 **
3761 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
3762 ** terms are duplicated into the subquery.
3763 */
3764 static int pushDownWhereTerms(
3765 sqlite3 *db, /* The database connection (for malloc()) */
3766 Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
3767 Expr *pWhere, /* The WHERE clause of the outer query */
3768 int iCursor /* Cursor number of the subquery */
3769 ){
3770 Expr *pNew;
3771 int nChng = 0;
3772 if( pWhere==0 ) return 0;
3773 if( (pSubq->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
3774 return 0; /* restrictions (1) and (2) */
3775 }
3776 if( pSubq->pLimit!=0 ){
3777 return 0; /* restriction (3) */
3778 }
3779 while( pWhere->op==TK_AND ){
3780 nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
3781 pWhere = pWhere->pLeft;
3782 }
3783 if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
3784 if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
3785 nChng++;
3786 while( pSubq ){
3787 pNew = sqlite3ExprDup(db, pWhere, 0);
3788 pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
3789 pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
3790 pSubq = pSubq->pPrior;
3791 }
3792 }
3793 return nChng;
3794 }
3795 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
3796
3652 /* 3797 /*
3653 ** Based on the contents of the AggInfo structure indicated by the first 3798 ** Based on the contents of the AggInfo structure indicated by the first
3654 ** argument, this function checks if the following are true: 3799 ** argument, this function checks if the following are true:
3655 ** 3800 **
3656 ** * the query contains just a single aggregate function, 3801 ** * the query contains just a single aggregate function,
3657 ** * the aggregate function is either min() or max(), and 3802 ** * the aggregate function is either min() or max(), and
3658 ** * the argument to the aggregate function is a column value. 3803 ** * the argument to the aggregate function is a column value.
3659 ** 3804 **
3660 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX 3805 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
3661 ** is returned as appropriate. Also, *ppMinMax is set to point to the 3806 ** is returned as appropriate. Also, *ppMinMax is set to point to the
(...skipping 63 matching lines...) Expand 10 before | Expand all | Expand 10 after
3725 } 3870 }
3726 3871
3727 /* 3872 /*
3728 ** If the source-list item passed as an argument was augmented with an 3873 ** If the source-list item passed as an argument was augmented with an
3729 ** INDEXED BY clause, then try to locate the specified index. If there 3874 ** INDEXED BY clause, then try to locate the specified index. If there
3730 ** was such a clause and the named index cannot be found, return 3875 ** was such a clause and the named index cannot be found, return
3731 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 3876 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
3732 ** pFrom->pIndex and return SQLITE_OK. 3877 ** pFrom->pIndex and return SQLITE_OK.
3733 */ 3878 */
3734 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ 3879 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
3735 if( pFrom->pTab && pFrom->zIndex ){ 3880 if( pFrom->pTab && pFrom->fg.isIndexedBy ){
3736 Table *pTab = pFrom->pTab; 3881 Table *pTab = pFrom->pTab;
3737 char *zIndex = pFrom->zIndex; 3882 char *zIndexedBy = pFrom->u1.zIndexedBy;
3738 Index *pIdx; 3883 Index *pIdx;
3739 for(pIdx=pTab->pIndex; 3884 for(pIdx=pTab->pIndex;
3740 pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 3885 pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
3741 pIdx=pIdx->pNext 3886 pIdx=pIdx->pNext
3742 ); 3887 );
3743 if( !pIdx ){ 3888 if( !pIdx ){
3744 sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0); 3889 sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
3745 pParse->checkSchema = 1; 3890 pParse->checkSchema = 1;
3746 return SQLITE_ERROR; 3891 return SQLITE_ERROR;
3747 } 3892 }
3748 pFrom->pIndex = pIdx; 3893 pFrom->pIBIndex = pIdx;
3749 } 3894 }
3750 return SQLITE_OK; 3895 return SQLITE_OK;
3751 } 3896 }
3752 /* 3897 /*
3753 ** Detect compound SELECT statements that use an ORDER BY clause with 3898 ** Detect compound SELECT statements that use an ORDER BY clause with
3754 ** an alternative collating sequence. 3899 ** an alternative collating sequence.
3755 ** 3900 **
3756 ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... 3901 ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
3757 ** 3902 **
3758 ** These are rewritten as a subquery: 3903 ** These are rewritten as a subquery:
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
3794 3939
3795 pParse = pWalker->pParse; 3940 pParse = pWalker->pParse;
3796 db = pParse->db; 3941 db = pParse->db;
3797 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 3942 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
3798 if( pNew==0 ) return WRC_Abort; 3943 if( pNew==0 ) return WRC_Abort;
3799 memset(&dummy, 0, sizeof(dummy)); 3944 memset(&dummy, 0, sizeof(dummy));
3800 pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); 3945 pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
3801 if( pNewSrc==0 ) return WRC_Abort; 3946 if( pNewSrc==0 ) return WRC_Abort;
3802 *pNew = *p; 3947 *pNew = *p;
3803 p->pSrc = pNewSrc; 3948 p->pSrc = pNewSrc;
3804 p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0)); 3949 p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
3805 p->op = TK_SELECT; 3950 p->op = TK_SELECT;
3806 p->pWhere = 0; 3951 p->pWhere = 0;
3807 pNew->pGroupBy = 0; 3952 pNew->pGroupBy = 0;
3808 pNew->pHaving = 0; 3953 pNew->pHaving = 0;
3809 pNew->pOrderBy = 0; 3954 pNew->pOrderBy = 0;
3810 p->pPrior = 0; 3955 p->pPrior = 0;
3811 p->pNext = 0; 3956 p->pNext = 0;
3957 p->pWith = 0;
3812 p->selFlags &= ~SF_Compound; 3958 p->selFlags &= ~SF_Compound;
3959 assert( (p->selFlags & SF_Converted)==0 );
3960 p->selFlags |= SF_Converted;
3813 assert( pNew->pPrior!=0 ); 3961 assert( pNew->pPrior!=0 );
3814 pNew->pPrior->pNext = pNew; 3962 pNew->pPrior->pNext = pNew;
3815 pNew->pLimit = 0; 3963 pNew->pLimit = 0;
3816 pNew->pOffset = 0; 3964 pNew->pOffset = 0;
3817 return WRC_Continue; 3965 return WRC_Continue;
3818 } 3966 }
3819 3967
3968 /*
3969 ** Check to see if the FROM clause term pFrom has table-valued function
3970 ** arguments. If it does, leave an error message in pParse and return
3971 ** non-zero, since pFrom is not allowed to be a table-valued function.
3972 */
3973 static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
3974 if( pFrom->fg.isTabFunc ){
3975 sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
3976 return 1;
3977 }
3978 return 0;
3979 }
3980
3820 #ifndef SQLITE_OMIT_CTE 3981 #ifndef SQLITE_OMIT_CTE
3821 /* 3982 /*
3822 ** Argument pWith (which may be NULL) points to a linked list of nested 3983 ** Argument pWith (which may be NULL) points to a linked list of nested
3823 ** WITH contexts, from inner to outermost. If the table identified by 3984 ** WITH contexts, from inner to outermost. If the table identified by
3824 ** FROM clause element pItem is really a common-table-expression (CTE) 3985 ** FROM clause element pItem is really a common-table-expression (CTE)
3825 ** then return a pointer to the CTE definition for that table. Otherwise 3986 ** then return a pointer to the CTE definition for that table. Otherwise
3826 ** return NULL. 3987 ** return NULL.
3827 ** 3988 **
3828 ** If a non-NULL value is returned, set *ppContext to point to the With 3989 ** If a non-NULL value is returned, set *ppContext to point to the With
3829 ** object that the returned CTE belongs to. 3990 ** object that the returned CTE belongs to.
3830 */ 3991 */
3831 static struct Cte *searchWith( 3992 static struct Cte *searchWith(
3832 With *pWith, /* Current outermost WITH clause */ 3993 With *pWith, /* Current innermost WITH clause */
3833 struct SrcList_item *pItem, /* FROM clause element to resolve */ 3994 struct SrcList_item *pItem, /* FROM clause element to resolve */
3834 With **ppContext /* OUT: WITH clause return value belongs to */ 3995 With **ppContext /* OUT: WITH clause return value belongs to */
3835 ){ 3996 ){
3836 const char *zName; 3997 const char *zName;
3837 if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){ 3998 if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
3838 With *p; 3999 With *p;
3839 for(p=pWith; p; p=p->pOuter){ 4000 for(p=pWith; p; p=p->pOuter){
3840 int i; 4001 int i;
3841 for(i=0; i<p->nCte; i++){ 4002 for(i=0; i<p->nCte; i++){
3842 if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ 4003 if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
(...skipping 10 matching lines...) Expand all
3853 ** with the inner-most WITH clause being at the top of the stack. 4014 ** with the inner-most WITH clause being at the top of the stack.
3854 ** 4015 **
3855 ** This routine pushes the WITH clause passed as the second argument 4016 ** This routine pushes the WITH clause passed as the second argument
3856 ** onto the top of the stack. If argument bFree is true, then this 4017 ** onto the top of the stack. If argument bFree is true, then this
3857 ** WITH clause will never be popped from the stack. In this case it 4018 ** WITH clause will never be popped from the stack. In this case it
3858 ** should be freed along with the Parse object. In other cases, when 4019 ** should be freed along with the Parse object. In other cases, when
3859 ** bFree==0, the With object will be freed along with the SELECT 4020 ** bFree==0, the With object will be freed along with the SELECT
3860 ** statement with which it is associated. 4021 ** statement with which it is associated.
3861 */ 4022 */
3862 void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ 4023 void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
3863 assert( bFree==0 || pParse->pWith==0 ); 4024 assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
3864 if( pWith ){ 4025 if( pWith ){
4026 assert( pParse->pWith!=pWith );
3865 pWith->pOuter = pParse->pWith; 4027 pWith->pOuter = pParse->pWith;
3866 pParse->pWith = pWith; 4028 pParse->pWith = pWith;
3867 pParse->bFreeWith = bFree; 4029 if( bFree ) pParse->pWithToFree = pWith;
3868 } 4030 }
3869 } 4031 }
3870 4032
3871 /* 4033 /*
3872 ** This function checks if argument pFrom refers to a CTE declared by 4034 ** This function checks if argument pFrom refers to a CTE declared by
3873 ** a WITH clause on the stack currently maintained by the parser. And, 4035 ** a WITH clause on the stack currently maintained by the parser. And,
3874 ** if currently processing a CTE expression, if it is a recursive 4036 ** if currently processing a CTE expression, if it is a recursive
3875 ** reference to the current CTE. 4037 ** reference to the current CTE.
3876 ** 4038 **
3877 ** If pFrom falls into either of the two categories above, pFrom->pTab 4039 ** If pFrom falls into either of the two categories above, pFrom->pTab
(...skipping 18 matching lines...) Expand all
3896 4058
3897 pCte = searchWith(pParse->pWith, pFrom, &pWith); 4059 pCte = searchWith(pParse->pWith, pFrom, &pWith);
3898 if( pCte ){ 4060 if( pCte ){
3899 Table *pTab; 4061 Table *pTab;
3900 ExprList *pEList; 4062 ExprList *pEList;
3901 Select *pSel; 4063 Select *pSel;
3902 Select *pLeft; /* Left-most SELECT statement */ 4064 Select *pLeft; /* Left-most SELECT statement */
3903 int bMayRecursive; /* True if compound joined by UNION [ALL] */ 4065 int bMayRecursive; /* True if compound joined by UNION [ALL] */
3904 With *pSavedWith; /* Initial value of pParse->pWith */ 4066 With *pSavedWith; /* Initial value of pParse->pWith */
3905 4067
3906 /* If pCte->zErr is non-NULL at this point, then this is an illegal 4068 /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
3907 ** recursive reference to CTE pCte. Leave an error in pParse and return 4069 ** recursive reference to CTE pCte. Leave an error in pParse and return
3908 ** early. If pCte->zErr is NULL, then this is not a recursive reference. 4070 ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
3909 ** In this case, proceed. */ 4071 ** In this case, proceed. */
3910 if( pCte->zErr ){ 4072 if( pCte->zCteErr ){
3911 sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName); 4073 sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
3912 return SQLITE_ERROR; 4074 return SQLITE_ERROR;
3913 } 4075 }
4076 if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
3914 4077
3915 assert( pFrom->pTab==0 ); 4078 assert( pFrom->pTab==0 );
3916 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 4079 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
3917 if( pTab==0 ) return WRC_Abort; 4080 if( pTab==0 ) return WRC_Abort;
3918 pTab->nRef = 1; 4081 pTab->nRef = 1;
3919 pTab->zName = sqlite3DbStrDup(db, pCte->zName); 4082 pTab->zName = sqlite3DbStrDup(db, pCte->zName);
3920 pTab->iPKey = -1; 4083 pTab->iPKey = -1;
3921 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 4084 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
3922 pTab->tabFlags |= TF_Ephemeral; 4085 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
3923 pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); 4086 pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
3924 if( db->mallocFailed ) return SQLITE_NOMEM; 4087 if( db->mallocFailed ) return SQLITE_NOMEM;
3925 assert( pFrom->pSelect ); 4088 assert( pFrom->pSelect );
3926 4089
3927 /* Check if this is a recursive CTE. */ 4090 /* Check if this is a recursive CTE. */
3928 pSel = pFrom->pSelect; 4091 pSel = pFrom->pSelect;
3929 bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION ); 4092 bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
3930 if( bMayRecursive ){ 4093 if( bMayRecursive ){
3931 int i; 4094 int i;
3932 SrcList *pSrc = pFrom->pSelect->pSrc; 4095 SrcList *pSrc = pFrom->pSelect->pSrc;
3933 for(i=0; i<pSrc->nSrc; i++){ 4096 for(i=0; i<pSrc->nSrc; i++){
3934 struct SrcList_item *pItem = &pSrc->a[i]; 4097 struct SrcList_item *pItem = &pSrc->a[i];
3935 if( pItem->zDatabase==0 4098 if( pItem->zDatabase==0
3936 && pItem->zName!=0 4099 && pItem->zName!=0
3937 && 0==sqlite3StrICmp(pItem->zName, pCte->zName) 4100 && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
3938 ){ 4101 ){
3939 pItem->pTab = pTab; 4102 pItem->pTab = pTab;
3940 pItem->isRecursive = 1; 4103 pItem->fg.isRecursive = 1;
3941 pTab->nRef++; 4104 pTab->nRef++;
3942 pSel->selFlags |= SF_Recursive; 4105 pSel->selFlags |= SF_Recursive;
3943 } 4106 }
3944 } 4107 }
3945 } 4108 }
3946 4109
3947 /* Only one recursive reference is permitted. */ 4110 /* Only one recursive reference is permitted. */
3948 if( pTab->nRef>2 ){ 4111 if( pTab->nRef>2 ){
3949 sqlite3ErrorMsg( 4112 sqlite3ErrorMsg(
3950 pParse, "multiple references to recursive table: %s", pCte->zName 4113 pParse, "multiple references to recursive table: %s", pCte->zName
3951 ); 4114 );
3952 return SQLITE_ERROR; 4115 return SQLITE_ERROR;
3953 } 4116 }
3954 assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 )); 4117 assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
3955 4118
3956 pCte->zErr = "circular reference: %s"; 4119 pCte->zCteErr = "circular reference: %s";
3957 pSavedWith = pParse->pWith; 4120 pSavedWith = pParse->pWith;
3958 pParse->pWith = pWith; 4121 pParse->pWith = pWith;
3959 sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel); 4122 sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
4123 pParse->pWith = pWith;
3960 4124
3961 for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); 4125 for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
3962 pEList = pLeft->pEList; 4126 pEList = pLeft->pEList;
3963 if( pCte->pCols ){ 4127 if( pCte->pCols ){
3964 if( pEList->nExpr!=pCte->pCols->nExpr ){ 4128 if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
3965 sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", 4129 sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
3966 pCte->zName, pEList->nExpr, pCte->pCols->nExpr 4130 pCte->zName, pEList->nExpr, pCte->pCols->nExpr
3967 ); 4131 );
3968 pParse->pWith = pSavedWith; 4132 pParse->pWith = pSavedWith;
3969 return SQLITE_ERROR; 4133 return SQLITE_ERROR;
3970 } 4134 }
3971 pEList = pCte->pCols; 4135 pEList = pCte->pCols;
3972 } 4136 }
3973 4137
3974 selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); 4138 sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
3975 if( bMayRecursive ){ 4139 if( bMayRecursive ){
3976 if( pSel->selFlags & SF_Recursive ){ 4140 if( pSel->selFlags & SF_Recursive ){
3977 pCte->zErr = "multiple recursive references: %s"; 4141 pCte->zCteErr = "multiple recursive references: %s";
3978 }else{ 4142 }else{
3979 pCte->zErr = "recursive reference in a subquery: %s"; 4143 pCte->zCteErr = "recursive reference in a subquery: %s";
3980 } 4144 }
3981 sqlite3WalkSelect(pWalker, pSel); 4145 sqlite3WalkSelect(pWalker, pSel);
3982 } 4146 }
3983 pCte->zErr = 0; 4147 pCte->zCteErr = 0;
3984 pParse->pWith = pSavedWith; 4148 pParse->pWith = pSavedWith;
3985 } 4149 }
3986 4150
3987 return SQLITE_OK; 4151 return SQLITE_OK;
3988 } 4152 }
3989 #endif 4153 #endif
3990 4154
3991 #ifndef SQLITE_OMIT_CTE 4155 #ifndef SQLITE_OMIT_CTE
3992 /* 4156 /*
3993 ** If the SELECT passed as the second argument has an associated WITH 4157 ** If the SELECT passed as the second argument has an associated WITH
(...skipping 51 matching lines...) Expand 10 before | Expand all | Expand 10 after
4045 4209
4046 p->selFlags |= SF_Expanded; 4210 p->selFlags |= SF_Expanded;
4047 if( db->mallocFailed ){ 4211 if( db->mallocFailed ){
4048 return WRC_Abort; 4212 return WRC_Abort;
4049 } 4213 }
4050 if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){ 4214 if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
4051 return WRC_Prune; 4215 return WRC_Prune;
4052 } 4216 }
4053 pTabList = p->pSrc; 4217 pTabList = p->pSrc;
4054 pEList = p->pEList; 4218 pEList = p->pEList;
4055 sqlite3WithPush(pParse, findRightmost(p)->pWith, 0); 4219 if( pWalker->xSelectCallback2==selectPopWith ){
4220 sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
4221 }
4056 4222
4057 /* Make sure cursor numbers have been assigned to all entries in 4223 /* Make sure cursor numbers have been assigned to all entries in
4058 ** the FROM clause of the SELECT statement. 4224 ** the FROM clause of the SELECT statement.
4059 */ 4225 */
4060 sqlite3SrcListAssignCursors(pParse, pTabList); 4226 sqlite3SrcListAssignCursors(pParse, pTabList);
4061 4227
4062 /* Look up every table named in the FROM clause of the select. If 4228 /* Look up every table named in the FROM clause of the select. If
4063 ** an entry of the FROM clause is a subquery instead of a table or view, 4229 ** an entry of the FROM clause is a subquery instead of a table or view,
4064 ** then create a transient table structure to describe the subquery. 4230 ** then create a transient table structure to describe the subquery.
4065 */ 4231 */
4066 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 4232 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
4067 Table *pTab; 4233 Table *pTab;
4068 assert( pFrom->isRecursive==0 || pFrom->pTab ); 4234 assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
4069 if( pFrom->isRecursive ) continue; 4235 if( pFrom->fg.isRecursive ) continue;
4070 if( pFrom->pTab!=0 ){ 4236 assert( pFrom->pTab==0 );
4071 /* This statement has already been prepared. There is no need
4072 ** to go further. */
4073 assert( i==0 );
4074 #ifndef SQLITE_OMIT_CTE
4075 selectPopWith(pWalker, p);
4076 #endif
4077 return WRC_Prune;
4078 }
4079 #ifndef SQLITE_OMIT_CTE 4237 #ifndef SQLITE_OMIT_CTE
4080 if( withExpand(pWalker, pFrom) ) return WRC_Abort; 4238 if( withExpand(pWalker, pFrom) ) return WRC_Abort;
4081 if( pFrom->pTab ) {} else 4239 if( pFrom->pTab ) {} else
4082 #endif 4240 #endif
4083 if( pFrom->zName==0 ){ 4241 if( pFrom->zName==0 ){
4084 #ifndef SQLITE_OMIT_SUBQUERY 4242 #ifndef SQLITE_OMIT_SUBQUERY
4085 Select *pSel = pFrom->pSelect; 4243 Select *pSel = pFrom->pSelect;
4086 /* A sub-query in the FROM clause of a SELECT */ 4244 /* A sub-query in the FROM clause of a SELECT */
4087 assert( pSel!=0 ); 4245 assert( pSel!=0 );
4088 assert( pFrom->pTab==0 ); 4246 assert( pFrom->pTab==0 );
4089 sqlite3WalkSelect(pWalker, pSel); 4247 if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
4090 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 4248 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
4091 if( pTab==0 ) return WRC_Abort; 4249 if( pTab==0 ) return WRC_Abort;
4092 pTab->nRef = 1; 4250 pTab->nRef = 1;
4093 pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab); 4251 pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
4094 while( pSel->pPrior ){ pSel = pSel->pPrior; } 4252 while( pSel->pPrior ){ pSel = pSel->pPrior; }
4095 selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol); 4253 sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
4096 pTab->iPKey = -1; 4254 pTab->iPKey = -1;
4097 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 4255 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
4098 pTab->tabFlags |= TF_Ephemeral; 4256 pTab->tabFlags |= TF_Ephemeral;
4099 #endif 4257 #endif
4100 }else{ 4258 }else{
4101 /* An ordinary table or view name in the FROM clause */ 4259 /* An ordinary table or view name in the FROM clause */
4102 assert( pFrom->pTab==0 ); 4260 assert( pFrom->pTab==0 );
4103 pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); 4261 pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
4104 if( pTab==0 ) return WRC_Abort; 4262 if( pTab==0 ) return WRC_Abort;
4105 if( pTab->nRef==0xffff ){ 4263 if( pTab->nRef==0xffff ){
4106 sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", 4264 sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
4107 pTab->zName); 4265 pTab->zName);
4108 pFrom->pTab = 0; 4266 pFrom->pTab = 0;
4109 return WRC_Abort; 4267 return WRC_Abort;
4110 } 4268 }
4111 pTab->nRef++; 4269 pTab->nRef++;
4270 if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
4271 return WRC_Abort;
4272 }
4112 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 4273 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
4113 if( pTab->pSelect || IsVirtual(pTab) ){ 4274 if( IsVirtual(pTab) || pTab->pSelect ){
4114 /* We reach here if the named table is a really a view */ 4275 i16 nCol;
4115 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; 4276 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
4116 assert( pFrom->pSelect==0 ); 4277 assert( pFrom->pSelect==0 );
4117 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); 4278 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
4118 sqlite3SelectSetName(pFrom->pSelect, pTab->zName); 4279 sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
4280 nCol = pTab->nCol;
4281 pTab->nCol = -1;
4119 sqlite3WalkSelect(pWalker, pFrom->pSelect); 4282 sqlite3WalkSelect(pWalker, pFrom->pSelect);
4283 pTab->nCol = nCol;
4120 } 4284 }
4121 #endif 4285 #endif
4122 } 4286 }
4123 4287
4124 /* Locate the index named by the INDEXED BY clause, if any. */ 4288 /* Locate the index named by the INDEXED BY clause, if any. */
4125 if( sqlite3IndexedByLookup(pParse, pFrom) ){ 4289 if( sqlite3IndexedByLookup(pParse, pFrom) ){
4126 return WRC_Abort; 4290 return WRC_Abort;
4127 } 4291 }
4128 } 4292 }
4129 4293
4130 /* Process NATURAL keywords, and ON and USING clauses of joins. 4294 /* Process NATURAL keywords, and ON and USING clauses of joins.
4131 */ 4295 */
4132 if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ 4296 if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
4133 return WRC_Abort; 4297 return WRC_Abort;
4134 } 4298 }
4135 4299
4136 /* For every "*" that occurs in the column list, insert the names of 4300 /* For every "*" that occurs in the column list, insert the names of
4137 ** all columns in all tables. And for every TABLE.* insert the names 4301 ** all columns in all tables. And for every TABLE.* insert the names
4138 ** of all columns in TABLE. The parser inserted a special expression 4302 ** of all columns in TABLE. The parser inserted a special expression
4139 ** with the TK_ALL operator for each "*" that it found in the column list. 4303 ** with the TK_ASTERISK operator for each "*" that it found in the column
4140 ** The following code just has to locate the TK_ALL expressions and expand 4304 ** list. The following code just has to locate the TK_ASTERISK
4141 ** each one to the list of all columns in all tables. 4305 ** expressions and expand each one to the list of all columns in
4306 ** all tables.
4142 ** 4307 **
4143 ** The first loop just checks to see if there are any "*" operators 4308 ** The first loop just checks to see if there are any "*" operators
4144 ** that need expanding. 4309 ** that need expanding.
4145 */ 4310 */
4146 for(k=0; k<pEList->nExpr; k++){ 4311 for(k=0; k<pEList->nExpr; k++){
4147 pE = pEList->a[k].pExpr; 4312 pE = pEList->a[k].pExpr;
4148 if( pE->op==TK_ALL ) break; 4313 if( pE->op==TK_ASTERISK ) break;
4149 assert( pE->op!=TK_DOT || pE->pRight!=0 ); 4314 assert( pE->op!=TK_DOT || pE->pRight!=0 );
4150 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); 4315 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
4151 if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break; 4316 if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
4152 } 4317 }
4153 if( k<pEList->nExpr ){ 4318 if( k<pEList->nExpr ){
4154 /* 4319 /*
4155 ** If we get here it means the result set contains one or more "*" 4320 ** If we get here it means the result set contains one or more "*"
4156 ** operators that need to be expanded. Loop through each expression 4321 ** operators that need to be expanded. Loop through each expression
4157 ** in the result set and expand them one by one. 4322 ** in the result set and expand them one by one.
4158 */ 4323 */
4159 struct ExprList_item *a = pEList->a; 4324 struct ExprList_item *a = pEList->a;
4160 ExprList *pNew = 0; 4325 ExprList *pNew = 0;
4161 int flags = pParse->db->flags; 4326 int flags = pParse->db->flags;
4162 int longNames = (flags & SQLITE_FullColNames)!=0 4327 int longNames = (flags & SQLITE_FullColNames)!=0
4163 && (flags & SQLITE_ShortColNames)==0; 4328 && (flags & SQLITE_ShortColNames)==0;
4164 4329
4165 /* When processing FROM-clause subqueries, it is always the case
4166 ** that full_column_names=OFF and short_column_names=ON. The
4167 ** sqlite3ResultSetOfSelect() routine makes it so. */
4168 assert( (p->selFlags & SF_NestedFrom)==0
4169 || ((flags & SQLITE_FullColNames)==0 &&
4170 (flags & SQLITE_ShortColNames)!=0) );
4171
4172 for(k=0; k<pEList->nExpr; k++){ 4330 for(k=0; k<pEList->nExpr; k++){
4173 pE = a[k].pExpr; 4331 pE = a[k].pExpr;
4174 pRight = pE->pRight; 4332 pRight = pE->pRight;
4175 assert( pE->op!=TK_DOT || pRight!=0 ); 4333 assert( pE->op!=TK_DOT || pRight!=0 );
4176 if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){ 4334 if( pE->op!=TK_ASTERISK
4335 && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
4336 ){
4177 /* This particular expression does not need to be expanded. 4337 /* This particular expression does not need to be expanded.
4178 */ 4338 */
4179 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); 4339 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
4180 if( pNew ){ 4340 if( pNew ){
4181 pNew->a[pNew->nExpr-1].zName = a[k].zName; 4341 pNew->a[pNew->nExpr-1].zName = a[k].zName;
4182 pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; 4342 pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
4183 a[k].zName = 0; 4343 a[k].zName = 0;
4184 a[k].zSpan = 0; 4344 a[k].zSpan = 0;
4185 } 4345 }
4186 a[k].pExpr = 0; 4346 a[k].pExpr = 0;
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
4218 char *zToFree; /* Malloced string that needs to be freed */ 4378 char *zToFree; /* Malloced string that needs to be freed */
4219 Token sColname; /* Computed column name as a token */ 4379 Token sColname; /* Computed column name as a token */
4220 4380
4221 assert( zName ); 4381 assert( zName );
4222 if( zTName && pSub 4382 if( zTName && pSub
4223 && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0 4383 && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
4224 ){ 4384 ){
4225 continue; 4385 continue;
4226 } 4386 }
4227 4387
4228 /* If a column is marked as 'hidden' (currently only possible 4388 /* If a column is marked as 'hidden', omit it from the expanded
4229 ** for virtual tables), do not include it in the expanded 4389 ** result-set list unless the SELECT has the SF_IncludeHidden
4230 ** result-set list. 4390 ** bit set.
4231 */ 4391 */
4232 if( IsHiddenColumn(&pTab->aCol[j]) ){ 4392 if( (p->selFlags & SF_IncludeHidden)==0
4233 assert(IsVirtual(pTab)); 4393 && IsHiddenColumn(&pTab->aCol[j])
4394 ){
4234 continue; 4395 continue;
4235 } 4396 }
4236 tableSeen = 1; 4397 tableSeen = 1;
4237 4398
4238 if( i>0 && zTName==0 ){ 4399 if( i>0 && zTName==0 ){
4239 if( (pFrom->jointype & JT_NATURAL)!=0 4400 if( (pFrom->fg.jointype & JT_NATURAL)!=0
4240 && tableAndColumnIndex(pTabList, i, zName, 0, 0) 4401 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
4241 ){ 4402 ){
4242 /* In a NATURAL join, omit the join columns from the 4403 /* In a NATURAL join, omit the join columns from the
4243 ** table to the right of the join */ 4404 ** table to the right of the join */
4244 continue; 4405 continue;
4245 } 4406 }
4246 if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ 4407 if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
4247 /* In a join with a USING clause, omit columns in the 4408 /* In a join with a USING clause, omit columns in the
4248 ** using clause from the table on the right. */ 4409 ** using clause from the table on the right. */
4249 continue; 4410 continue;
(...skipping 44 matching lines...) Expand 10 before | Expand all | Expand 10 after
4294 } 4455 }
4295 } 4456 }
4296 } 4457 }
4297 } 4458 }
4298 sqlite3ExprListDelete(db, pEList); 4459 sqlite3ExprListDelete(db, pEList);
4299 p->pEList = pNew; 4460 p->pEList = pNew;
4300 } 4461 }
4301 #if SQLITE_MAX_COLUMN 4462 #if SQLITE_MAX_COLUMN
4302 if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 4463 if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
4303 sqlite3ErrorMsg(pParse, "too many columns in result set"); 4464 sqlite3ErrorMsg(pParse, "too many columns in result set");
4465 return WRC_Abort;
4304 } 4466 }
4305 #endif 4467 #endif
4306 return WRC_Continue; 4468 return WRC_Continue;
4307 } 4469 }
4308 4470
4309 /* 4471 /*
4310 ** No-op routine for the parse-tree walker. 4472 ** No-op routine for the parse-tree walker.
4311 ** 4473 **
4312 ** When this routine is the Walker.xExprCallback then expression trees 4474 ** When this routine is the Walker.xExprCallback then expression trees
4313 ** are walked without any actions being taken at each node. Presumably, 4475 ** are walked without any actions being taken at each node. Presumably,
4314 ** when this routine is used for Walker.xExprCallback then 4476 ** when this routine is used for Walker.xExprCallback then
4315 ** Walker.xSelectCallback is set to do something useful for every 4477 ** Walker.xSelectCallback is set to do something useful for every
4316 ** subquery in the parser tree. 4478 ** subquery in the parser tree.
4317 */ 4479 */
4318 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ 4480 int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
4319 UNUSED_PARAMETER2(NotUsed, NotUsed2); 4481 UNUSED_PARAMETER2(NotUsed, NotUsed2);
4320 return WRC_Continue; 4482 return WRC_Continue;
4321 } 4483 }
4322 4484
4323 /* 4485 /*
4324 ** This routine "expands" a SELECT statement and all of its subqueries. 4486 ** This routine "expands" a SELECT statement and all of its subqueries.
4325 ** For additional information on what it means to "expand" a SELECT 4487 ** For additional information on what it means to "expand" a SELECT
4326 ** statement, see the comment on the selectExpand worker callback above. 4488 ** statement, see the comment on the selectExpand worker callback above.
4327 ** 4489 **
4328 ** Expanding a SELECT statement is the first step in processing a 4490 ** Expanding a SELECT statement is the first step in processing a
4329 ** SELECT statement. The SELECT statement must be expanded before 4491 ** SELECT statement. The SELECT statement must be expanded before
4330 ** name resolution is performed. 4492 ** name resolution is performed.
4331 ** 4493 **
4332 ** If anything goes wrong, an error message is written into pParse. 4494 ** If anything goes wrong, an error message is written into pParse.
4333 ** The calling function can detect the problem by looking at pParse->nErr 4495 ** The calling function can detect the problem by looking at pParse->nErr
4334 ** and/or pParse->db->mallocFailed. 4496 ** and/or pParse->db->mallocFailed.
4335 */ 4497 */
4336 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ 4498 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
4337 Walker w; 4499 Walker w;
4338 memset(&w, 0, sizeof(w)); 4500 memset(&w, 0, sizeof(w));
4339 w.xExprCallback = exprWalkNoop; 4501 w.xExprCallback = sqlite3ExprWalkNoop;
4340 w.pParse = pParse; 4502 w.pParse = pParse;
4341 if( pParse->hasCompound ){ 4503 if( pParse->hasCompound ){
4342 w.xSelectCallback = convertCompoundSelectToSubquery; 4504 w.xSelectCallback = convertCompoundSelectToSubquery;
4343 sqlite3WalkSelect(&w, pSelect); 4505 sqlite3WalkSelect(&w, pSelect);
4344 } 4506 }
4345 w.xSelectCallback = selectExpander; 4507 w.xSelectCallback = selectExpander;
4346 w.xSelectCallback2 = selectPopWith; 4508 if( (pSelect->selFlags & SF_MultiValue)==0 ){
4509 w.xSelectCallback2 = selectPopWith;
4510 }
4347 sqlite3WalkSelect(&w, pSelect); 4511 sqlite3WalkSelect(&w, pSelect);
4348 } 4512 }
4349 4513
4350 4514
4351 #ifndef SQLITE_OMIT_SUBQUERY 4515 #ifndef SQLITE_OMIT_SUBQUERY
4352 /* 4516 /*
4353 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() 4517 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
4354 ** interface. 4518 ** interface.
4355 ** 4519 **
4356 ** For each FROM-clause subquery, add Column.zType and Column.zColl 4520 ** For each FROM-clause subquery, add Column.zType and Column.zColl
4357 ** information to the Table structure that represents the result set 4521 ** information to the Table structure that represents the result set
4358 ** of that subquery. 4522 ** of that subquery.
4359 ** 4523 **
4360 ** The Table structure that represents the result set was constructed 4524 ** The Table structure that represents the result set was constructed
4361 ** by selectExpander() but the type and collation information was omitted 4525 ** by selectExpander() but the type and collation information was omitted
4362 ** at that point because identifiers had not yet been resolved. This 4526 ** at that point because identifiers had not yet been resolved. This
4363 ** routine is called after identifier resolution. 4527 ** routine is called after identifier resolution.
4364 */ 4528 */
4365 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ 4529 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
4366 Parse *pParse; 4530 Parse *pParse;
4367 int i; 4531 int i;
4368 SrcList *pTabList; 4532 SrcList *pTabList;
4369 struct SrcList_item *pFrom; 4533 struct SrcList_item *pFrom;
4370 4534
4371 assert( p->selFlags & SF_Resolved ); 4535 assert( p->selFlags & SF_Resolved );
4372 if( (p->selFlags & SF_HasTypeInfo)==0 ){ 4536 assert( (p->selFlags & SF_HasTypeInfo)==0 );
4373 p->selFlags |= SF_HasTypeInfo; 4537 p->selFlags |= SF_HasTypeInfo;
4374 pParse = pWalker->pParse; 4538 pParse = pWalker->pParse;
4375 pTabList = p->pSrc; 4539 pTabList = p->pSrc;
4376 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 4540 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
4377 Table *pTab = pFrom->pTab; 4541 Table *pTab = pFrom->pTab;
4378 if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){ 4542 assert( pTab!=0 );
4379 /* A sub-query in the FROM clause of a SELECT */ 4543 if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
4380 Select *pSel = pFrom->pSelect; 4544 /* A sub-query in the FROM clause of a SELECT */
4381 if( pSel ){ 4545 Select *pSel = pFrom->pSelect;
4382 while( pSel->pPrior ) pSel = pSel->pPrior; 4546 if( pSel ){
4383 selectAddColumnTypeAndCollation(pParse, pTab, pSel); 4547 while( pSel->pPrior ) pSel = pSel->pPrior;
4384 } 4548 selectAddColumnTypeAndCollation(pParse, pTab, pSel);
4385 } 4549 }
4386 } 4550 }
4387 } 4551 }
4388 } 4552 }
4389 #endif 4553 #endif
4390 4554
4391 4555
4392 /* 4556 /*
4393 ** This routine adds datatype and collating sequence information to 4557 ** This routine adds datatype and collating sequence information to
4394 ** the Table structures of all FROM-clause subqueries in a 4558 ** the Table structures of all FROM-clause subqueries in a
4395 ** SELECT statement. 4559 ** SELECT statement.
4396 ** 4560 **
4397 ** Use this routine after name resolution. 4561 ** Use this routine after name resolution.
4398 */ 4562 */
4399 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ 4563 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
4400 #ifndef SQLITE_OMIT_SUBQUERY 4564 #ifndef SQLITE_OMIT_SUBQUERY
4401 Walker w; 4565 Walker w;
4402 memset(&w, 0, sizeof(w)); 4566 memset(&w, 0, sizeof(w));
4403 w.xSelectCallback2 = selectAddSubqueryTypeInfo; 4567 w.xSelectCallback2 = selectAddSubqueryTypeInfo;
4404 w.xExprCallback = exprWalkNoop; 4568 w.xExprCallback = sqlite3ExprWalkNoop;
4405 w.pParse = pParse; 4569 w.pParse = pParse;
4406 sqlite3WalkSelect(&w, pSelect); 4570 sqlite3WalkSelect(&w, pSelect);
4407 #endif 4571 #endif
4408 } 4572 }
4409 4573
4410 4574
4411 /* 4575 /*
4412 ** This routine sets up a SELECT statement for processing. The 4576 ** This routine sets up a SELECT statement for processing. The
4413 ** following is accomplished: 4577 ** following is accomplished:
4414 ** 4578 **
(...skipping 98 matching lines...) Expand 10 before | Expand all | Expand 10 after
4513 pAggInfo->directMode = 1; 4677 pAggInfo->directMode = 1;
4514 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 4678 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
4515 int nArg; 4679 int nArg;
4516 int addrNext = 0; 4680 int addrNext = 0;
4517 int regAgg; 4681 int regAgg;
4518 ExprList *pList = pF->pExpr->x.pList; 4682 ExprList *pList = pF->pExpr->x.pList;
4519 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 4683 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
4520 if( pList ){ 4684 if( pList ){
4521 nArg = pList->nExpr; 4685 nArg = pList->nExpr;
4522 regAgg = sqlite3GetTempRange(pParse, nArg); 4686 regAgg = sqlite3GetTempRange(pParse, nArg);
4523 sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP); 4687 sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
4524 }else{ 4688 }else{
4525 nArg = 0; 4689 nArg = 0;
4526 regAgg = 0; 4690 regAgg = 0;
4527 } 4691 }
4528 if( pF->iDistinct>=0 ){ 4692 if( pF->iDistinct>=0 ){
4529 addrNext = sqlite3VdbeMakeLabel(v); 4693 addrNext = sqlite3VdbeMakeLabel(v);
4530 assert( nArg==1 ); 4694 testcase( nArg==0 ); /* Error condition */
4695 testcase( nArg>1 ); /* Also an error */
4531 codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 4696 codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
4532 } 4697 }
4533 if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 4698 if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
4534 CollSeq *pColl = 0; 4699 CollSeq *pColl = 0;
4535 struct ExprList_item *pItem; 4700 struct ExprList_item *pItem;
4536 int j; 4701 int j;
4537 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ 4702 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
4538 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 4703 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
4539 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 4704 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
4540 } 4705 }
4541 if( !pColl ){ 4706 if( !pColl ){
4542 pColl = pParse->db->pDfltColl; 4707 pColl = pParse->db->pDfltColl;
4543 } 4708 }
4544 if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; 4709 if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
4545 sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); 4710 sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
4546 } 4711 }
4547 sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem, 4712 sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
4548 (void*)pF->pFunc, P4_FUNCDEF); 4713 (void*)pF->pFunc, P4_FUNCDEF);
4549 sqlite3VdbeChangeP5(v, (u8)nArg); 4714 sqlite3VdbeChangeP5(v, (u8)nArg);
4550 sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); 4715 sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
4551 sqlite3ReleaseTempRange(pParse, regAgg, nArg); 4716 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
4552 if( addrNext ){ 4717 if( addrNext ){
4553 sqlite3VdbeResolveLabel(v, addrNext); 4718 sqlite3VdbeResolveLabel(v, addrNext);
4554 sqlite3ExprCacheClear(pParse); 4719 sqlite3ExprCacheClear(pParse);
4555 } 4720 }
4556 } 4721 }
4557 4722
(...skipping 62 matching lines...) Expand 10 before | Expand all | Expand 10 after
4620 */ 4785 */
4621 int sqlite3Select( 4786 int sqlite3Select(
4622 Parse *pParse, /* The parser context */ 4787 Parse *pParse, /* The parser context */
4623 Select *p, /* The SELECT statement being coded. */ 4788 Select *p, /* The SELECT statement being coded. */
4624 SelectDest *pDest /* What to do with the query results */ 4789 SelectDest *pDest /* What to do with the query results */
4625 ){ 4790 ){
4626 int i, j; /* Loop counters */ 4791 int i, j; /* Loop counters */
4627 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 4792 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
4628 Vdbe *v; /* The virtual machine under construction */ 4793 Vdbe *v; /* The virtual machine under construction */
4629 int isAgg; /* True for select lists like "count(*)" */ 4794 int isAgg; /* True for select lists like "count(*)" */
4630 ExprList *pEList; /* List of columns to extract. */ 4795 ExprList *pEList = 0; /* List of columns to extract. */
4631 SrcList *pTabList; /* List of tables to select from */ 4796 SrcList *pTabList; /* List of tables to select from */
4632 Expr *pWhere; /* The WHERE clause. May be NULL */ 4797 Expr *pWhere; /* The WHERE clause. May be NULL */
4633 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 4798 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
4634 Expr *pHaving; /* The HAVING clause. May be NULL */ 4799 Expr *pHaving; /* The HAVING clause. May be NULL */
4635 int rc = 1; /* Value to return from this function */ 4800 int rc = 1; /* Value to return from this function */
4636 DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ 4801 DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
4637 SortCtx sSort; /* Info on how to code the ORDER BY clause */ 4802 SortCtx sSort; /* Info on how to code the ORDER BY clause */
4638 AggInfo sAggInfo; /* Information used by aggregate queries */ 4803 AggInfo sAggInfo; /* Information used by aggregate queries */
4639 int iEnd; /* Address of the end of the query */ 4804 int iEnd; /* Address of the end of the query */
4640 sqlite3 *db; /* The database connection */ 4805 sqlite3 *db; /* The database connection */
(...skipping 29 matching lines...) Expand all
4670 /* If ORDER BY makes no difference in the output then neither does 4835 /* If ORDER BY makes no difference in the output then neither does
4671 ** DISTINCT so it can be removed too. */ 4836 ** DISTINCT so it can be removed too. */
4672 sqlite3ExprListDelete(db, p->pOrderBy); 4837 sqlite3ExprListDelete(db, p->pOrderBy);
4673 p->pOrderBy = 0; 4838 p->pOrderBy = 0;
4674 p->selFlags &= ~SF_Distinct; 4839 p->selFlags &= ~SF_Distinct;
4675 } 4840 }
4676 sqlite3SelectPrep(pParse, p, 0); 4841 sqlite3SelectPrep(pParse, p, 0);
4677 memset(&sSort, 0, sizeof(sSort)); 4842 memset(&sSort, 0, sizeof(sSort));
4678 sSort.pOrderBy = p->pOrderBy; 4843 sSort.pOrderBy = p->pOrderBy;
4679 pTabList = p->pSrc; 4844 pTabList = p->pSrc;
4680 pEList = p->pEList;
4681 if( pParse->nErr || db->mallocFailed ){ 4845 if( pParse->nErr || db->mallocFailed ){
4682 goto select_end; 4846 goto select_end;
4683 } 4847 }
4848 assert( p->pEList!=0 );
4684 isAgg = (p->selFlags & SF_Aggregate)!=0; 4849 isAgg = (p->selFlags & SF_Aggregate)!=0;
4685 assert( pEList!=0 ); 4850 #if SELECTTRACE_ENABLED
4851 if( sqlite3SelectTrace & 0x100 ){
4852 SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
4853 sqlite3TreeViewSelect(0, p, 0);
4854 }
4855 #endif
4686 4856
4687 /* Begin generating code.
4688 */
4689 v = sqlite3GetVdbe(pParse);
4690 if( v==0 ) goto select_end;
4691 4857
4692 /* If writing to memory or generating a set 4858 /* If writing to memory or generating a set
4693 ** only a single column may be output. 4859 ** only a single column may be output.
4694 */ 4860 */
4695 #ifndef SQLITE_OMIT_SUBQUERY 4861 #ifndef SQLITE_OMIT_SUBQUERY
4696 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ 4862 if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
4697 goto select_end; 4863 goto select_end;
4698 } 4864 }
4699 #endif 4865 #endif
4700 4866
4867 /* Try to flatten subqueries in the FROM clause up into the main query
4868 */
4869 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4870 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
4871 struct SrcList_item *pItem = &pTabList->a[i];
4872 Select *pSub = pItem->pSelect;
4873 int isAggSub;
4874 Table *pTab = pItem->pTab;
4875 if( pSub==0 ) continue;
4876
4877 /* Catch mismatch in the declared columns of a view and the number of
4878 ** columns in the SELECT on the RHS */
4879 if( pTab->nCol!=pSub->pEList->nExpr ){
4880 sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
4881 pTab->nCol, pTab->zName, pSub->pEList->nExpr);
4882 goto select_end;
4883 }
4884
4885 isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
4886 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
4887 /* This subquery can be absorbed into its parent. */
4888 if( isAggSub ){
4889 isAgg = 1;
4890 p->selFlags |= SF_Aggregate;
4891 }
4892 i = -1;
4893 }
4894 pTabList = p->pSrc;
4895 if( db->mallocFailed ) goto select_end;
4896 if( !IgnorableOrderby(pDest) ){
4897 sSort.pOrderBy = p->pOrderBy;
4898 }
4899 }
4900 #endif
4901
4902 /* Get a pointer the VDBE under construction, allocating a new VDBE if one
4903 ** does not already exist */
4904 v = sqlite3GetVdbe(pParse);
4905 if( v==0 ) goto select_end;
4906
4907 #ifndef SQLITE_OMIT_COMPOUND_SELECT
4908 /* Handle compound SELECT statements using the separate multiSelect()
4909 ** procedure.
4910 */
4911 if( p->pPrior ){
4912 rc = multiSelect(pParse, p, pDest);
4913 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
4914 #if SELECTTRACE_ENABLED
4915 SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
4916 pParse->nSelectIndent--;
4917 #endif
4918 return rc;
4919 }
4920 #endif
4921
4701 /* Generate code for all sub-queries in the FROM clause 4922 /* Generate code for all sub-queries in the FROM clause
4702 */ 4923 */
4703 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 4924 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4704 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ 4925 for(i=0; i<pTabList->nSrc; i++){
4705 struct SrcList_item *pItem = &pTabList->a[i]; 4926 struct SrcList_item *pItem = &pTabList->a[i];
4706 SelectDest dest; 4927 SelectDest dest;
4707 Select *pSub = pItem->pSelect; 4928 Select *pSub = pItem->pSelect;
4708 int isAggSub;
4709
4710 if( pSub==0 ) continue; 4929 if( pSub==0 ) continue;
4711 4930
4712 /* Sometimes the code for a subquery will be generated more than 4931 /* Sometimes the code for a subquery will be generated more than
4713 ** once, if the subquery is part of the WHERE clause in a LEFT JOIN, 4932 ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
4714 ** for example. In that case, do not regenerate the code to manifest 4933 ** for example. In that case, do not regenerate the code to manifest
4715 ** a view or the co-routine to implement a view. The first instance 4934 ** a view or the co-routine to implement a view. The first instance
4716 ** is sufficient, though the subroutine to manifest the view does need 4935 ** is sufficient, though the subroutine to manifest the view does need
4717 ** to be invoked again. */ 4936 ** to be invoked again. */
4718 if( pItem->addrFillSub ){ 4937 if( pItem->addrFillSub ){
4719 if( pItem->viaCoroutine==0 ){ 4938 if( pItem->fg.viaCoroutine==0 ){
4720 sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); 4939 sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
4721 } 4940 }
4722 continue; 4941 continue;
4723 } 4942 }
4724 4943
4725 /* Increment Parse.nHeight by the height of the largest expression 4944 /* Increment Parse.nHeight by the height of the largest expression
4726 ** tree referred to by this, the parent select. The child select 4945 ** tree referred to by this, the parent select. The child select
4727 ** may contain expression trees of at most 4946 ** may contain expression trees of at most
4728 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 4947 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
4729 ** more conservative than necessary, but much easier than enforcing 4948 ** more conservative than necessary, but much easier than enforcing
4730 ** an exact limit. 4949 ** an exact limit.
4731 */ 4950 */
4732 pParse->nHeight += sqlite3SelectExprHeight(p); 4951 pParse->nHeight += sqlite3SelectExprHeight(p);
4733 4952
4734 isAggSub = (pSub->selFlags & SF_Aggregate)!=0; 4953 /* Make copies of constant WHERE-clause terms in the outer query down
4735 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ 4954 ** inside the subquery. This can help the subquery to run more efficiently.
4736 /* This subquery can be absorbed into its parent. */ 4955 */
4737 if( isAggSub ){ 4956 if( (pItem->fg.jointype & JT_OUTER)==0
4738 isAgg = 1; 4957 && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
4739 p->selFlags |= SF_Aggregate; 4958 ){
4959 #if SELECTTRACE_ENABLED
4960 if( sqlite3SelectTrace & 0x100 ){
4961 SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
4962 sqlite3TreeViewSelect(0, p, 0);
4740 } 4963 }
4741 i = -1; 4964 #endif
4742 }else if( pTabList->nSrc==1 4965 }
4743 && OptimizationEnabled(db, SQLITE_SubqCoroutine) 4966
4967 /* Generate code to implement the subquery
4968 */
4969 if( pTabList->nSrc==1
4970 && (p->selFlags & SF_All)==0
4971 && OptimizationEnabled(db, SQLITE_SubqCoroutine)
4744 ){ 4972 ){
4745 /* Implement a co-routine that will return a single row of the result 4973 /* Implement a co-routine that will return a single row of the result
4746 ** set on each invocation. 4974 ** set on each invocation.
4747 */ 4975 */
4748 int addrTop = sqlite3VdbeCurrentAddr(v)+1; 4976 int addrTop = sqlite3VdbeCurrentAddr(v)+1;
4749 pItem->regReturn = ++pParse->nMem; 4977 pItem->regReturn = ++pParse->nMem;
4750 sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); 4978 sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
4751 VdbeComment((v, "%s", pItem->pTab->zName)); 4979 VdbeComment((v, "%s", pItem->pTab->zName));
4752 pItem->addrFillSub = addrTop; 4980 pItem->addrFillSub = addrTop;
4753 sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); 4981 sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
4754 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 4982 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
4755 sqlite3Select(pParse, pSub, &dest); 4983 sqlite3Select(pParse, pSub, &dest);
4756 pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow); 4984 pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
4757 pItem->viaCoroutine = 1; 4985 pItem->fg.viaCoroutine = 1;
4758 pItem->regResult = dest.iSdst; 4986 pItem->regResult = dest.iSdst;
4759 sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn); 4987 sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
4760 sqlite3VdbeJumpHere(v, addrTop-1); 4988 sqlite3VdbeJumpHere(v, addrTop-1);
4761 sqlite3ClearTempRegCache(pParse); 4989 sqlite3ClearTempRegCache(pParse);
4762 }else{ 4990 }else{
4763 /* Generate a subroutine that will fill an ephemeral table with 4991 /* Generate a subroutine that will fill an ephemeral table with
4764 ** the content of this subquery. pItem->addrFillSub will point 4992 ** the content of this subquery. pItem->addrFillSub will point
4765 ** to the address of the generated subroutine. pItem->regReturn 4993 ** to the address of the generated subroutine. pItem->regReturn
4766 ** is a register allocated to hold the subroutine return address 4994 ** is a register allocated to hold the subroutine return address
4767 */ 4995 */
4768 int topAddr; 4996 int topAddr;
4769 int onceAddr = 0; 4997 int onceAddr = 0;
4770 int retAddr; 4998 int retAddr;
4771 assert( pItem->addrFillSub==0 ); 4999 assert( pItem->addrFillSub==0 );
4772 pItem->regReturn = ++pParse->nMem; 5000 pItem->regReturn = ++pParse->nMem;
4773 topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); 5001 topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
4774 pItem->addrFillSub = topAddr+1; 5002 pItem->addrFillSub = topAddr+1;
4775 if( pItem->isCorrelated==0 ){ 5003 if( pItem->fg.isCorrelated==0 ){
4776 /* If the subquery is not correlated and if we are not inside of 5004 /* If the subquery is not correlated and if we are not inside of
4777 ** a trigger, then we only need to compute the value of the subquery 5005 ** a trigger, then we only need to compute the value of the subquery
4778 ** once. */ 5006 ** once. */
4779 onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v); 5007 onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
4780 VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName)); 5008 VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
4781 }else{ 5009 }else{
4782 VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName)); 5010 VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
4783 } 5011 }
4784 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 5012 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
4785 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 5013 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
4786 sqlite3Select(pParse, pSub, &dest); 5014 sqlite3Select(pParse, pSub, &dest);
4787 pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow); 5015 pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
4788 if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); 5016 if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
4789 retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); 5017 retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
4790 VdbeComment((v, "end %s", pItem->pTab->zName)); 5018 VdbeComment((v, "end %s", pItem->pTab->zName));
4791 sqlite3VdbeChangeP1(v, topAddr, retAddr); 5019 sqlite3VdbeChangeP1(v, topAddr, retAddr);
4792 sqlite3ClearTempRegCache(pParse); 5020 sqlite3ClearTempRegCache(pParse);
4793 } 5021 }
4794 if( /*pParse->nErr ||*/ db->mallocFailed ){ 5022 if( db->mallocFailed ) goto select_end;
4795 goto select_end;
4796 }
4797 pParse->nHeight -= sqlite3SelectExprHeight(p); 5023 pParse->nHeight -= sqlite3SelectExprHeight(p);
4798 pTabList = p->pSrc;
4799 if( !IgnorableOrderby(pDest) ){
4800 sSort.pOrderBy = p->pOrderBy;
4801 }
4802 } 5024 }
5025 #endif
5026
5027 /* Various elements of the SELECT copied into local variables for
5028 ** convenience */
4803 pEList = p->pEList; 5029 pEList = p->pEList;
4804 #endif
4805 pWhere = p->pWhere; 5030 pWhere = p->pWhere;
4806 pGroupBy = p->pGroupBy; 5031 pGroupBy = p->pGroupBy;
4807 pHaving = p->pHaving; 5032 pHaving = p->pHaving;
4808 sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; 5033 sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
4809 5034
4810 #ifndef SQLITE_OMIT_COMPOUND_SELECT
4811 /* If there is are a sequence of queries, do the earlier ones first.
4812 */
4813 if( p->pPrior ){
4814 rc = multiSelect(pParse, p, pDest);
4815 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
4816 #if SELECTTRACE_ENABLED 5035 #if SELECTTRACE_ENABLED
4817 SELECTTRACE(1,pParse,p,("end compound-select processing\n")); 5036 if( sqlite3SelectTrace & 0x400 ){
4818 pParse->nSelectIndent--; 5037 SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
4819 #endif 5038 sqlite3TreeViewSelect(0, p, 0);
4820 return rc;
4821 } 5039 }
4822 #endif 5040 #endif
4823 5041
4824 /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 5042 /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
4825 ** if the select-list is the same as the ORDER BY list, then this query 5043 ** if the select-list is the same as the ORDER BY list, then this query
4826 ** can be rewritten as a GROUP BY. In other words, this: 5044 ** can be rewritten as a GROUP BY. In other words, this:
4827 ** 5045 **
4828 ** SELECT DISTINCT xyz FROM ... ORDER BY xyz 5046 ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
4829 ** 5047 **
4830 ** is transformed to: 5048 ** is transformed to:
4831 ** 5049 **
4832 ** SELECT xyz FROM ... GROUP BY xyz 5050 ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
4833 ** 5051 **
4834 ** The second form is preferred as a single index (or temp-table) may be 5052 ** The second form is preferred as a single index (or temp-table) may be
4835 ** used for both the ORDER BY and DISTINCT processing. As originally 5053 ** used for both the ORDER BY and DISTINCT processing. As originally
4836 ** written the query must use a temp-table for at least one of the ORDER 5054 ** written the query must use a temp-table for at least one of the ORDER
4837 ** BY and DISTINCT, and an index or separate temp-table for the other. 5055 ** BY and DISTINCT, and an index or separate temp-table for the other.
4838 */ 5056 */
4839 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 5057 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
4840 && sqlite3ExprListCompare(sSort.pOrderBy, p->pEList, -1)==0 5058 && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
4841 ){ 5059 ){
4842 p->selFlags &= ~SF_Distinct; 5060 p->selFlags &= ~SF_Distinct;
4843 p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0); 5061 pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
4844 pGroupBy = p->pGroupBy;
4845 sSort.pOrderBy = 0;
4846 /* Notice that even thought SF_Distinct has been cleared from p->selFlags, 5062 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
4847 ** the sDistinct.isTnct is still set. Hence, isTnct represents the 5063 ** the sDistinct.isTnct is still set. Hence, isTnct represents the
4848 ** original setting of the SF_Distinct flag, not the current setting */ 5064 ** original setting of the SF_Distinct flag, not the current setting */
4849 assert( sDistinct.isTnct ); 5065 assert( sDistinct.isTnct );
4850 } 5066 }
4851 5067
4852 /* If there is an ORDER BY clause, then this sorting 5068 /* If there is an ORDER BY clause, then create an ephemeral index to
4853 ** index might end up being unused if the data can be 5069 ** do the sorting. But this sorting ephemeral index might end up
4854 ** extracted in pre-sorted order. If that is the case, then the 5070 ** being unused if the data can be extracted in pre-sorted order.
4855 ** OP_OpenEphemeral instruction will be changed to an OP_Noop once 5071 ** If that is the case, then the OP_OpenEphemeral instruction will be
4856 ** we figure out that the sorting index is not needed. The addrSortIndex 5072 ** changed to an OP_Noop once we figure out that the sorting index is
4857 ** variable is used to facilitate that change. 5073 ** not needed. The sSort.addrSortIndex variable is used to facilitate
5074 ** that change.
4858 */ 5075 */
4859 if( sSort.pOrderBy ){ 5076 if( sSort.pOrderBy ){
4860 KeyInfo *pKeyInfo; 5077 KeyInfo *pKeyInfo;
4861 pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, 0); 5078 pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
4862 sSort.iECursor = pParse->nTab++; 5079 sSort.iECursor = pParse->nTab++;
4863 sSort.addrSortIndex = 5080 sSort.addrSortIndex =
4864 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 5081 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
4865 sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, 5082 sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
4866 (char*)pKeyInfo, P4_KEYINFO 5083 (char*)pKeyInfo, P4_KEYINFO
4867 ); 5084 );
4868 }else{ 5085 }else{
4869 sSort.addrSortIndex = -1; 5086 sSort.addrSortIndex = -1;
4870 } 5087 }
4871 5088
4872 /* If the output is destined for a temporary table, open that table. 5089 /* If the output is destined for a temporary table, open that table.
4873 */ 5090 */
4874 if( pDest->eDest==SRT_EphemTab ){ 5091 if( pDest->eDest==SRT_EphemTab ){
4875 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); 5092 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
4876 } 5093 }
4877 5094
4878 /* Set the limiter. 5095 /* Set the limiter.
4879 */ 5096 */
4880 iEnd = sqlite3VdbeMakeLabel(v); 5097 iEnd = sqlite3VdbeMakeLabel(v);
4881 p->nSelectRow = LARGEST_INT64; 5098 p->nSelectRow = LARGEST_INT64;
4882 computeLimitRegisters(pParse, p, iEnd); 5099 computeLimitRegisters(pParse, p, iEnd);
4883 if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ 5100 if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
4884 sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen; 5101 sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
4885 sSort.sortFlags |= SORTFLAG_UseSorter; 5102 sSort.sortFlags |= SORTFLAG_UseSorter;
4886 } 5103 }
4887 5104
4888 /* Open a virtual index to use for the distinct set. 5105 /* Open an ephemeral index to use for the distinct set.
4889 */ 5106 */
4890 if( p->selFlags & SF_Distinct ){ 5107 if( p->selFlags & SF_Distinct ){
4891 sDistinct.tabTnct = pParse->nTab++; 5108 sDistinct.tabTnct = pParse->nTab++;
4892 sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 5109 sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
4893 sDistinct.tabTnct, 0, 0, 5110 sDistinct.tabTnct, 0, 0,
4894 (char*)keyInfoFromExprList(pParse, p->pEList,0,0 ), 5111 (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
4895 P4_KEYINFO); 5112 P4_KEYINFO);
4896 sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 5113 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
4897 sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; 5114 sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
4898 }else{ 5115 }else{
4899 sDistinct.eTnctType = WHERE_DISTINCT_NOOP; 5116 sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
4900 } 5117 }
4901 5118
4902 if( !isAgg && pGroupBy==0 ){ 5119 if( !isAgg && pGroupBy==0 ){
4903 /* No aggregate functions and no GROUP BY clause */ 5120 /* No aggregate functions and no GROUP BY clause */
4904 u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0); 5121 u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
4905 5122
(...skipping 57 matching lines...) Expand 10 before | Expand all | Expand 10 after
4963 pItem->u.x.iAlias = 0; 5180 pItem->u.x.iAlias = 0;
4964 } 5181 }
4965 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ 5182 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
4966 pItem->u.x.iAlias = 0; 5183 pItem->u.x.iAlias = 0;
4967 } 5184 }
4968 if( p->nSelectRow>100 ) p->nSelectRow = 100; 5185 if( p->nSelectRow>100 ) p->nSelectRow = 100;
4969 }else{ 5186 }else{
4970 p->nSelectRow = 1; 5187 p->nSelectRow = 1;
4971 } 5188 }
4972 5189
4973
4974 /* If there is both a GROUP BY and an ORDER BY clause and they are 5190 /* If there is both a GROUP BY and an ORDER BY clause and they are
4975 ** identical, then it may be possible to disable the ORDER BY clause 5191 ** identical, then it may be possible to disable the ORDER BY clause
4976 ** on the grounds that the GROUP BY will cause elements to come out 5192 ** on the grounds that the GROUP BY will cause elements to come out
4977 ** in the correct order. It also may not - the GROUP BY may use a 5193 ** in the correct order. It also may not - the GROUP BY might use a
4978 ** database index that causes rows to be grouped together as required 5194 ** database index that causes rows to be grouped together as required
4979 ** but not actually sorted. Either way, record the fact that the 5195 ** but not actually sorted. Either way, record the fact that the
4980 ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp 5196 ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
4981 ** variable. */ 5197 ** variable. */
4982 if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ 5198 if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
4983 orderByGrp = 1; 5199 orderByGrp = 1;
4984 } 5200 }
4985 5201
4986 /* Create a label to jump to when we want to abort the query */ 5202 /* Create a label to jump to when we want to abort the query */
4987 addrEnd = sqlite3VdbeMakeLabel(v); 5203 addrEnd = sqlite3VdbeMakeLabel(v);
(...skipping 22 matching lines...) Expand all
5010 sNC.ncFlags &= ~NC_InAggFunc; 5226 sNC.ncFlags &= ~NC_InAggFunc;
5011 } 5227 }
5012 sAggInfo.mxReg = pParse->nMem; 5228 sAggInfo.mxReg = pParse->nMem;
5013 if( db->mallocFailed ) goto select_end; 5229 if( db->mallocFailed ) goto select_end;
5014 5230
5015 /* Processing for aggregates with GROUP BY is very different and 5231 /* Processing for aggregates with GROUP BY is very different and
5016 ** much more complex than aggregates without a GROUP BY. 5232 ** much more complex than aggregates without a GROUP BY.
5017 */ 5233 */
5018 if( pGroupBy ){ 5234 if( pGroupBy ){
5019 KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 5235 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
5020 int j1; /* A-vs-B comparision jump */ 5236 int addr1; /* A-vs-B comparision jump */
5021 int addrOutputRow; /* Start of subroutine that outputs a result row */ 5237 int addrOutputRow; /* Start of subroutine that outputs a result row */
5022 int regOutputRow; /* Return address register for output subroutine */ 5238 int regOutputRow; /* Return address register for output subroutine */
5023 int addrSetAbort; /* Set the abort flag and return */ 5239 int addrSetAbort; /* Set the abort flag and return */
5024 int addrTopOfLoop; /* Top of the input loop */ 5240 int addrTopOfLoop; /* Top of the input loop */
5025 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 5241 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
5026 int addrReset; /* Subroutine for resetting the accumulator */ 5242 int addrReset; /* Subroutine for resetting the accumulator */
5027 int regReset; /* Return address register for reset subroutine */ 5243 int regReset; /* Return address register for reset subroutine */
5028 5244
5029 /* If there is a GROUP BY clause we might need a sorting index to 5245 /* If there is a GROUP BY clause we might need a sorting index to
5030 ** implement it. Allocate that sorting index now. If it turns out 5246 ** implement it. Allocate that sorting index now. If it turns out
5031 ** that we do not need it after all, the OP_SorterOpen instruction 5247 ** that we do not need it after all, the OP_SorterOpen instruction
5032 ** will be converted into a Noop. 5248 ** will be converted into a Noop.
5033 */ 5249 */
5034 sAggInfo.sortingIdx = pParse->nTab++; 5250 sAggInfo.sortingIdx = pParse->nTab++;
5035 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, 0); 5251 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
5036 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 5252 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
5037 sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 5253 sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
5038 0, (char*)pKeyInfo, P4_KEYINFO); 5254 0, (char*)pKeyInfo, P4_KEYINFO);
5039 5255
5040 /* Initialize memory locations used by GROUP BY aggregate processing 5256 /* Initialize memory locations used by GROUP BY aggregate processing
5041 */ 5257 */
5042 iUseFlag = ++pParse->nMem; 5258 iUseFlag = ++pParse->nMem;
5043 iAbortFlag = ++pParse->nMem; 5259 iAbortFlag = ++pParse->nMem;
5044 regOutputRow = ++pParse->nMem; 5260 regOutputRow = ++pParse->nMem;
5045 addrOutputRow = sqlite3VdbeMakeLabel(v); 5261 addrOutputRow = sqlite3VdbeMakeLabel(v);
(...skipping 45 matching lines...) Expand 10 before | Expand all | Expand 10 after
5091 nCol = nGroupBy; 5307 nCol = nGroupBy;
5092 j = nGroupBy; 5308 j = nGroupBy;
5093 for(i=0; i<sAggInfo.nColumn; i++){ 5309 for(i=0; i<sAggInfo.nColumn; i++){
5094 if( sAggInfo.aCol[i].iSorterColumn>=j ){ 5310 if( sAggInfo.aCol[i].iSorterColumn>=j ){
5095 nCol++; 5311 nCol++;
5096 j++; 5312 j++;
5097 } 5313 }
5098 } 5314 }
5099 regBase = sqlite3GetTempRange(pParse, nCol); 5315 regBase = sqlite3GetTempRange(pParse, nCol);
5100 sqlite3ExprCacheClear(pParse); 5316 sqlite3ExprCacheClear(pParse);
5101 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0); 5317 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
5102 j = nGroupBy; 5318 j = nGroupBy;
5103 for(i=0; i<sAggInfo.nColumn; i++){ 5319 for(i=0; i<sAggInfo.nColumn; i++){
5104 struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 5320 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
5105 if( pCol->iSorterColumn>=j ){ 5321 if( pCol->iSorterColumn>=j ){
5106 int r1 = j + regBase; 5322 int r1 = j + regBase;
5107 int r2; 5323 sqlite3ExprCodeGetColumnToReg(pParse,
5108 5324 pCol->pTab, pCol->iColumn, pCol->iTable, r1);
5109 r2 = sqlite3ExprCodeGetColumn(pParse,
5110 pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
5111 if( r1!=r2 ){
5112 sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
5113 }
5114 j++; 5325 j++;
5115 } 5326 }
5116 } 5327 }
5117 regRecord = sqlite3GetTempReg(pParse); 5328 regRecord = sqlite3GetTempReg(pParse);
5118 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 5329 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
5119 sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); 5330 sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
5120 sqlite3ReleaseTempReg(pParse, regRecord); 5331 sqlite3ReleaseTempReg(pParse, regRecord);
5121 sqlite3ReleaseTempRange(pParse, regBase, nCol); 5332 sqlite3ReleaseTempRange(pParse, regBase, nCol);
5122 sqlite3WhereEnd(pWInfo); 5333 sqlite3WhereEnd(pWInfo);
5123 sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; 5334 sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
(...skipping 21 matching lines...) Expand all
5145 } 5356 }
5146 5357
5147 /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 5358 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
5148 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 5359 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
5149 ** Then compare the current GROUP BY terms against the GROUP BY terms 5360 ** Then compare the current GROUP BY terms against the GROUP BY terms
5150 ** from the previous row currently stored in a0, a1, a2... 5361 ** from the previous row currently stored in a0, a1, a2...
5151 */ 5362 */
5152 addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 5363 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
5153 sqlite3ExprCacheClear(pParse); 5364 sqlite3ExprCacheClear(pParse);
5154 if( groupBySort ){ 5365 if( groupBySort ){
5155 sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut,sortPTa b); 5366 sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
5367 sortOut, sortPTab);
5156 } 5368 }
5157 for(j=0; j<pGroupBy->nExpr; j++){ 5369 for(j=0; j<pGroupBy->nExpr; j++){
5158 if( groupBySort ){ 5370 if( groupBySort ){
5159 sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); 5371 sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
5160 }else{ 5372 }else{
5161 sAggInfo.directMode = 1; 5373 sAggInfo.directMode = 1;
5162 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 5374 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
5163 } 5375 }
5164 } 5376 }
5165 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, 5377 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
5166 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 5378 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
5167 j1 = sqlite3VdbeCurrentAddr(v); 5379 addr1 = sqlite3VdbeCurrentAddr(v);
5168 sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v); 5380 sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
5169 5381
5170 /* Generate code that runs whenever the GROUP BY changes. 5382 /* Generate code that runs whenever the GROUP BY changes.
5171 ** Changes in the GROUP BY are detected by the previous code 5383 ** Changes in the GROUP BY are detected by the previous code
5172 ** block. If there were no changes, this block is skipped. 5384 ** block. If there were no changes, this block is skipped.
5173 ** 5385 **
5174 ** This code copies current group by terms in b0,b1,b2,... 5386 ** This code copies current group by terms in b0,b1,b2,...
5175 ** over to a0,a1,a2. It then calls the output subroutine 5387 ** over to a0,a1,a2. It then calls the output subroutine
5176 ** and resets the aggregate accumulator registers in preparation 5388 ** and resets the aggregate accumulator registers in preparation
5177 ** for the next GROUP BY batch. 5389 ** for the next GROUP BY batch.
5178 */ 5390 */
5179 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); 5391 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
5180 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 5392 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
5181 VdbeComment((v, "output one row")); 5393 VdbeComment((v, "output one row"));
5182 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); 5394 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
5183 VdbeComment((v, "check abort flag")); 5395 VdbeComment((v, "check abort flag"));
5184 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 5396 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
5185 VdbeComment((v, "reset accumulator")); 5397 VdbeComment((v, "reset accumulator"));
5186 5398
5187 /* Update the aggregate accumulators based on the content of 5399 /* Update the aggregate accumulators based on the content of
5188 ** the current row 5400 ** the current row
5189 */ 5401 */
5190 sqlite3VdbeJumpHere(v, j1); 5402 sqlite3VdbeJumpHere(v, addr1);
5191 updateAccumulator(pParse, &sAggInfo); 5403 updateAccumulator(pParse, &sAggInfo);
5192 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 5404 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
5193 VdbeComment((v, "indicate data in accumulator")); 5405 VdbeComment((v, "indicate data in accumulator"));
5194 5406
5195 /* End of the loop 5407 /* End of the loop
5196 */ 5408 */
5197 if( groupBySort ){ 5409 if( groupBySort ){
5198 sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); 5410 sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
5199 VdbeCoverage(v); 5411 VdbeCoverage(v);
5200 }else{ 5412 }else{
5201 sqlite3WhereEnd(pWInfo); 5413 sqlite3WhereEnd(pWInfo);
5202 sqlite3VdbeChangeToNoop(v, addrSortingIdx); 5414 sqlite3VdbeChangeToNoop(v, addrSortingIdx);
5203 } 5415 }
5204 5416
5205 /* Output the final row of result 5417 /* Output the final row of result
5206 */ 5418 */
5207 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 5419 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
5208 VdbeComment((v, "output final row")); 5420 VdbeComment((v, "output final row"));
5209 5421
5210 /* Jump over the subroutines 5422 /* Jump over the subroutines
5211 */ 5423 */
5212 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd); 5424 sqlite3VdbeGoto(v, addrEnd);
5213 5425
5214 /* Generate a subroutine that outputs a single row of the result 5426 /* Generate a subroutine that outputs a single row of the result
5215 ** set. This subroutine first looks at the iUseFlag. If iUseFlag 5427 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
5216 ** is less than or equal to zero, the subroutine is a no-op. If 5428 ** is less than or equal to zero, the subroutine is a no-op. If
5217 ** the processing calls for the query to abort, this subroutine 5429 ** the processing calls for the query to abort, this subroutine
5218 ** increments the iAbortFlag memory location before returning in 5430 ** increments the iAbortFlag memory location before returning in
5219 ** order to signal the caller to abort. 5431 ** order to signal the caller to abort.
5220 */ 5432 */
5221 addrSetAbort = sqlite3VdbeCurrentAddr(v); 5433 addrSetAbort = sqlite3VdbeCurrentAddr(v);
5222 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 5434 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
5223 VdbeComment((v, "set abort flag")); 5435 VdbeComment((v, "set abort flag"));
5224 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 5436 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5225 sqlite3VdbeResolveLabel(v, addrOutputRow); 5437 sqlite3VdbeResolveLabel(v, addrOutputRow);
5226 addrOutputRow = sqlite3VdbeCurrentAddr(v); 5438 addrOutputRow = sqlite3VdbeCurrentAddr(v);
5227 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v) ; 5439 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
5440 VdbeCoverage(v);
5228 VdbeComment((v, "Groupby result generator entry point")); 5441 VdbeComment((v, "Groupby result generator entry point"));
5229 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 5442 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5230 finalizeAggFunctions(pParse, &sAggInfo); 5443 finalizeAggFunctions(pParse, &sAggInfo);
5231 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 5444 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
5232 selectInnerLoop(pParse, p, p->pEList, -1, &sSort, 5445 selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
5233 &sDistinct, pDest, 5446 &sDistinct, pDest,
5234 addrOutputRow+1, addrSetAbort); 5447 addrOutputRow+1, addrSetAbort);
5235 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 5448 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
5236 VdbeComment((v, "end groupby result generator")); 5449 VdbeComment((v, "end groupby result generator"));
5237 5450
(...skipping 117 matching lines...) Expand 10 before | Expand all | Expand 10 after
5355 */ 5568 */
5356 resetAccumulator(pParse, &sAggInfo); 5569 resetAccumulator(pParse, &sAggInfo);
5357 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0); 5570 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
5358 if( pWInfo==0 ){ 5571 if( pWInfo==0 ){
5359 sqlite3ExprListDelete(db, pDel); 5572 sqlite3ExprListDelete(db, pDel);
5360 goto select_end; 5573 goto select_end;
5361 } 5574 }
5362 updateAccumulator(pParse, &sAggInfo); 5575 updateAccumulator(pParse, &sAggInfo);
5363 assert( pMinMax==0 || pMinMax->nExpr==1 ); 5576 assert( pMinMax==0 || pMinMax->nExpr==1 );
5364 if( sqlite3WhereIsOrdered(pWInfo)>0 ){ 5577 if( sqlite3WhereIsOrdered(pWInfo)>0 ){
5365 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo)); 5578 sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
5366 VdbeComment((v, "%s() by index", 5579 VdbeComment((v, "%s() by index",
5367 (flag==WHERE_ORDERBY_MIN?"min":"max"))); 5580 (flag==WHERE_ORDERBY_MIN?"min":"max")));
5368 } 5581 }
5369 sqlite3WhereEnd(pWInfo); 5582 sqlite3WhereEnd(pWInfo);
5370 finalizeAggFunctions(pParse, &sAggInfo); 5583 finalizeAggFunctions(pParse, &sAggInfo);
5371 } 5584 }
5372 5585
5373 sSort.pOrderBy = 0; 5586 sSort.pOrderBy = 0;
5374 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 5587 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
5375 selectInnerLoop(pParse, p, p->pEList, -1, 0, 0, 5588 selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
5376 pDest, addrEnd, addrEnd); 5589 pDest, addrEnd, addrEnd);
5377 sqlite3ExprListDelete(db, pDel); 5590 sqlite3ExprListDelete(db, pDel);
5378 } 5591 }
5379 sqlite3VdbeResolveLabel(v, addrEnd); 5592 sqlite3VdbeResolveLabel(v, addrEnd);
5380 5593
5381 } /* endif aggregate query */ 5594 } /* endif aggregate query */
5382 5595
5383 if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ 5596 if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
5384 explainTempTable(pParse, "DISTINCT"); 5597 explainTempTable(pParse, "DISTINCT");
5385 } 5598 }
5386 5599
5387 /* If there is an ORDER BY clause, then we need to sort the results 5600 /* If there is an ORDER BY clause, then we need to sort the results
5388 ** and send them to the callback one by one. 5601 ** and send them to the callback one by one.
5389 */ 5602 */
5390 if( sSort.pOrderBy ){ 5603 if( sSort.pOrderBy ){
5391 explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY "); 5604 explainTempTable(pParse,
5605 sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
5392 generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); 5606 generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
5393 } 5607 }
5394 5608
5395 /* Jump here to skip this query 5609 /* Jump here to skip this query
5396 */ 5610 */
5397 sqlite3VdbeResolveLabel(v, iEnd); 5611 sqlite3VdbeResolveLabel(v, iEnd);
5398 5612
5399 /* The SELECT was successfully coded. Set the return code to 0 5613 /* The SELECT has been coded. If there is an error in the Parse structure,
5400 ** to indicate no errors. 5614 ** set the return code to 1. Otherwise 0. */
5401 */ 5615 rc = (pParse->nErr>0);
5402 rc = 0;
5403 5616
5404 /* Control jumps to here if an error is encountered above, or upon 5617 /* Control jumps to here if an error is encountered above, or upon
5405 ** successful coding of the SELECT. 5618 ** successful coding of the SELECT.
5406 */ 5619 */
5407 select_end: 5620 select_end:
5408 explainSetInteger(pParse->iSelectId, iRestoreSelectId); 5621 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
5409 5622
5410 /* Identify column names if results of the SELECT are to be output. 5623 /* Identify column names if results of the SELECT are to be output.
5411 */ 5624 */
5412 if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){ 5625 if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
5413 generateColumnNames(pParse, pTabList, pEList); 5626 generateColumnNames(pParse, pTabList, pEList);
5414 } 5627 }
5415 5628
5416 sqlite3DbFree(db, sAggInfo.aCol); 5629 sqlite3DbFree(db, sAggInfo.aCol);
5417 sqlite3DbFree(db, sAggInfo.aFunc); 5630 sqlite3DbFree(db, sAggInfo.aFunc);
5418 #if SELECTTRACE_ENABLED 5631 #if SELECTTRACE_ENABLED
5419 SELECTTRACE(1,pParse,p,("end processing\n")); 5632 SELECTTRACE(1,pParse,p,("end processing\n"));
5420 pParse->nSelectIndent--; 5633 pParse->nSelectIndent--;
5421 #endif 5634 #endif
5422 return rc; 5635 return rc;
5423 } 5636 }
5424
5425 #ifdef SQLITE_DEBUG
5426 /*
5427 ** Generate a human-readable description of a the Select object.
5428 */
5429 void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
5430 int n = 0;
5431 pView = sqlite3TreeViewPush(pView, moreToFollow);
5432 sqlite3TreeViewLine(pView, "SELECT%s%s",
5433 ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
5434 ((p->selFlags & SF_Aggregate) ? " agg_flag" : "")
5435 );
5436 if( p->pSrc && p->pSrc->nSrc ) n++;
5437 if( p->pWhere ) n++;
5438 if( p->pGroupBy ) n++;
5439 if( p->pHaving ) n++;
5440 if( p->pOrderBy ) n++;
5441 if( p->pLimit ) n++;
5442 if( p->pOffset ) n++;
5443 if( p->pPrior ) n++;
5444 sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
5445 if( p->pSrc && p->pSrc->nSrc ){
5446 int i;
5447 pView = sqlite3TreeViewPush(pView, (n--)>0);
5448 sqlite3TreeViewLine(pView, "FROM");
5449 for(i=0; i<p->pSrc->nSrc; i++){
5450 struct SrcList_item *pItem = &p->pSrc->a[i];
5451 StrAccum x;
5452 char zLine[100];
5453 sqlite3StrAccumInit(&x, zLine, sizeof(zLine), 0);
5454 sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor);
5455 if( pItem->zDatabase ){
5456 sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName);
5457 }else if( pItem->zName ){
5458 sqlite3XPrintf(&x, 0, " %s", pItem->zName);
5459 }
5460 if( pItem->pTab ){
5461 sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName);
5462 }
5463 if( pItem->zAlias ){
5464 sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias);
5465 }
5466 if( pItem->jointype & JT_LEFT ){
5467 sqlite3XPrintf(&x, 0, " LEFT-JOIN");
5468 }
5469 sqlite3StrAccumFinish(&x);
5470 sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
5471 if( pItem->pSelect ){
5472 sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
5473 }
5474 sqlite3TreeViewPop(pView);
5475 }
5476 sqlite3TreeViewPop(pView);
5477 }
5478 if( p->pWhere ){
5479 sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
5480 sqlite3TreeViewExpr(pView, p->pWhere, 0);
5481 sqlite3TreeViewPop(pView);
5482 }
5483 if( p->pGroupBy ){
5484 sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
5485 }
5486 if( p->pHaving ){
5487 sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
5488 sqlite3TreeViewExpr(pView, p->pHaving, 0);
5489 sqlite3TreeViewPop(pView);
5490 }
5491 if( p->pOrderBy ){
5492 sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
5493 }
5494 if( p->pLimit ){
5495 sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
5496 sqlite3TreeViewExpr(pView, p->pLimit, 0);
5497 sqlite3TreeViewPop(pView);
5498 }
5499 if( p->pOffset ){
5500 sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
5501 sqlite3TreeViewExpr(pView, p->pOffset, 0);
5502 sqlite3TreeViewPop(pView);
5503 }
5504 if( p->pPrior ){
5505 const char *zOp = "UNION";
5506 switch( p->op ){
5507 case TK_ALL: zOp = "UNION ALL"; break;
5508 case TK_INTERSECT: zOp = "INTERSECT"; break;
5509 case TK_EXCEPT: zOp = "EXCEPT"; break;
5510 }
5511 sqlite3TreeViewItem(pView, zOp, (n--)>0);
5512 sqlite3TreeViewSelect(pView, p->pPrior, 0);
5513 sqlite3TreeViewPop(pView);
5514 }
5515 sqlite3TreeViewPop(pView);
5516 }
5517 #endif /* SQLITE_DEBUG */
OLDNEW
« no previous file with comments | « third_party/sqlite/sqlite-src-3100200/src/rowset.c ('k') | third_party/sqlite/sqlite-src-3100200/src/shell.c » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698