4
** The author disclaims copyright to this source code. In place of
5
** a legal notice, here is a blessing:
7
** May you do good and not evil.
8
** May you find forgiveness for yourself and forgive others.
9
** May you share freely, never taking more than you give.
11
*************************************************************************
12
** This file contains C code routines that are called by the parser
13
** to handle SELECT statements in SQLite.
15
** $Id: select.c,v 1.243 2005/03/28 03:39:56 drh Exp $
17
#include "sqliteInt.h"
21
** Allocate a new Select structure and return a pointer to that
24
Select *sqlite3SelectNew(
25
ExprList *pEList, /* which columns to include in the result */
26
SrcList *pSrc, /* the FROM clause -- which tables to scan */
27
Expr *pWhere, /* the WHERE clause */
28
ExprList *pGroupBy, /* the GROUP BY clause */
29
Expr *pHaving, /* the HAVING clause */
30
ExprList *pOrderBy, /* the ORDER BY clause */
31
int isDistinct, /* true if the DISTINCT keyword is present */
32
Expr *pLimit, /* LIMIT value. NULL means not used */
33
Expr *pOffset /* OFFSET value. NULL means no offset */
36
pNew = sqliteMalloc( sizeof(*pNew) );
37
assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */
39
sqlite3ExprListDelete(pEList);
40
sqlite3SrcListDelete(pSrc);
41
sqlite3ExprDelete(pWhere);
42
sqlite3ExprListDelete(pGroupBy);
43
sqlite3ExprDelete(pHaving);
44
sqlite3ExprListDelete(pOrderBy);
45
sqlite3ExprDelete(pLimit);
46
sqlite3ExprDelete(pOffset);
49
pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
51
pNew->pEList = pEList;
53
pNew->pWhere = pWhere;
54
pNew->pGroupBy = pGroupBy;
55
pNew->pHaving = pHaving;
56
pNew->pOrderBy = pOrderBy;
57
pNew->isDistinct = isDistinct;
59
pNew->pLimit = pLimit;
60
pNew->pOffset = pOffset;
68
** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
69
** type of join. Return an integer constant that expresses that type
70
** in terms of the following bit values:
78
** A full outer join is the combination of JT_LEFT and JT_RIGHT.
80
** If an illegal or unsupported join type is seen, then still return
81
** a join type, but put an error in the pParse structure.
83
int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
92
{ "natural", 7, JT_NATURAL },
93
{ "left", 4, JT_LEFT|JT_OUTER },
94
{ "right", 5, JT_RIGHT|JT_OUTER },
95
{ "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
96
{ "outer", 5, JT_OUTER },
97
{ "inner", 5, JT_INNER },
98
{ "cross", 5, JT_INNER },
104
for(i=0; i<3 && apAll[i]; i++){
106
for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
107
if( p->n==keywords[j].nChar
108
&& sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
109
jointype |= keywords[j].code;
113
if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
114
jointype |= JT_ERROR;
119
(jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
120
(jointype & JT_ERROR)!=0
122
const char *zSp1 = " ";
123
const char *zSp2 = " ";
124
if( pB==0 ){ zSp1++; }
125
if( pC==0 ){ zSp2++; }
126
sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
127
"%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
129
}else if( jointype & JT_RIGHT ){
130
sqlite3ErrorMsg(pParse,
131
"RIGHT and FULL OUTER JOINs are not currently supported");
138
** Return the index of a column in a table. Return -1 if the column
139
** is not contained in the table.
141
static int columnIndex(Table *pTab, const char *zCol){
143
for(i=0; i<pTab->nCol; i++){
144
if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
150
** Set the value of a token to a '\000'-terminated string.
152
static void setToken(Token *p, const char *z){
160
** Add a term to the WHERE expression in *ppExpr that requires the
161
** zCol column to be equal in the two tables pTab1 and pTab2.
163
static void addWhereTerm(
164
const char *zCol, /* Name of the column */
165
const Table *pTab1, /* First table */
166
const char *zAlias1, /* Alias for first table. May be NULL */
167
const Table *pTab2, /* Second table */
168
const char *zAlias2, /* Alias for second table. May be NULL */
169
Expr **ppExpr /* Add the equality term to this expression */
172
Expr *pE1a, *pE1b, *pE1c;
173
Expr *pE2a, *pE2b, *pE2c;
176
setToken(&dummy, zCol);
177
pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy);
178
pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy);
180
zAlias1 = pTab1->zName;
182
setToken(&dummy, zAlias1);
183
pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy);
185
zAlias2 = pTab2->zName;
187
setToken(&dummy, zAlias2);
188
pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy);
189
pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
190
pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
191
pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
192
ExprSetProperty(pE, EP_FromJoin);
193
*ppExpr = sqlite3ExprAnd(*ppExpr, pE);
197
** Set the EP_FromJoin property on all terms of the given expression.
199
** The EP_FromJoin property is used on terms of an expression to tell
200
** the LEFT OUTER JOIN processing logic that this term is part of the
201
** join restriction specified in the ON or USING clause and not a part
202
** of the more general WHERE clause. These terms are moved over to the
203
** WHERE clause during join processing but we need to remember that they
204
** originated in the ON or USING clause.
206
static void setJoinExpr(Expr *p){
208
ExprSetProperty(p, EP_FromJoin);
209
setJoinExpr(p->pLeft);
215
** This routine processes the join information for a SELECT statement.
216
** ON and USING clauses are converted into extra terms of the WHERE clause.
217
** NATURAL joins also create extra WHERE clause terms.
219
** The terms of a FROM clause are contained in the Select.pSrc structure.
220
** The left most table is the first entry in Select.pSrc. The right-most
221
** table is the last entry. The join operator is held in the entry to
222
** the left. Thus entry 0 contains the join operator for the join between
223
** entries 0 and 1. Any ON or USING clauses associated with the join are
224
** also attached to the left entry.
226
** This routine returns the number of errors encountered.
228
static int sqliteProcessJoin(Parse *pParse, Select *p){
229
SrcList *pSrc; /* All tables in the FROM clause */
230
int i, j; /* Loop counters */
231
struct SrcList_item *pLeft; /* Left table being joined */
232
struct SrcList_item *pRight; /* Right table being joined */
237
for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
238
Table *pLeftTab = pLeft->pTab;
239
Table *pRightTab = pRight->pTab;
241
if( pLeftTab==0 || pRightTab==0 ) continue;
243
/* When the NATURAL keyword is present, add WHERE clause terms for
244
** every column that the two tables have in common.
246
if( pLeft->jointype & JT_NATURAL ){
247
if( pLeft->pOn || pLeft->pUsing ){
248
sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
249
"an ON or USING clause", 0);
252
for(j=0; j<pLeftTab->nCol; j++){
253
char *zName = pLeftTab->aCol[j].zName;
254
if( columnIndex(pRightTab, zName)>=0 ){
255
addWhereTerm(zName, pLeftTab, pLeft->zAlias,
256
pRightTab, pRight->zAlias, &p->pWhere);
261
/* Disallow both ON and USING clauses in the same join
263
if( pLeft->pOn && pLeft->pUsing ){
264
sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
265
"clauses in the same join");
269
/* Add the ON clause to the end of the WHERE clause, connected by
273
setJoinExpr(pLeft->pOn);
274
p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn);
278
/* Create extra terms on the WHERE clause for each column named
279
** in the USING clause. Example: If the two tables to be joined are
280
** A and B and the USING clause names X, Y, and Z, then add this
281
** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
282
** Report an error if any column mentioned in the USING clause is
283
** not contained in both tables to be joined.
286
IdList *pList = pLeft->pUsing;
287
for(j=0; j<pList->nId; j++){
288
char *zName = pList->a[j].zName;
289
if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
290
sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
291
"not present in both tables", zName);
294
addWhereTerm(zName, pLeftTab, pLeft->zAlias,
295
pRightTab, pRight->zAlias, &p->pWhere);
303
** Delete the given Select structure and all of its substructures.
305
void sqlite3SelectDelete(Select *p){
307
sqlite3ExprListDelete(p->pEList);
308
sqlite3SrcListDelete(p->pSrc);
309
sqlite3ExprDelete(p->pWhere);
310
sqlite3ExprListDelete(p->pGroupBy);
311
sqlite3ExprDelete(p->pHaving);
312
sqlite3ExprListDelete(p->pOrderBy);
313
sqlite3SelectDelete(p->pPrior);
314
sqlite3ExprDelete(p->pLimit);
315
sqlite3ExprDelete(p->pOffset);
320
** Insert code into "v" that will push the record on the top of the
321
** stack into the sorter.
323
static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
325
for(i=0; i<pOrderBy->nExpr; i++){
326
sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
328
sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr, 0);
329
sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
333
** Add code to implement the OFFSET and LIMIT
335
static void codeLimiter(
336
Vdbe *v, /* Generate code into this VM */
337
Select *p, /* The SELECT statement being coded */
338
int iContinue, /* Jump here to skip the current record */
339
int iBreak, /* Jump here to end the loop */
340
int nPop /* Number of times to pop stack when jumping */
343
int addr = sqlite3VdbeCurrentAddr(v) + 3;
345
sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, 0);
346
sqlite3VdbeAddOp(v, OP_IfMemPos, p->iOffset, addr);
348
sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
350
sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
351
VdbeComment((v, "# skip OFFSET records"));
354
sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
355
VdbeComment((v, "# exit when LIMIT reached"));
360
** This routine generates the code for the inside of the inner loop
363
** If srcTab and nColumn are both zero, then the pEList expressions
364
** are evaluated in order to get the data for this row. If nColumn>0
365
** then data is pulled from srcTab and pEList is used only to get the
366
** datatypes for each column.
368
static int selectInnerLoop(
369
Parse *pParse, /* The parser context */
370
Select *p, /* The complete select statement being coded */
371
ExprList *pEList, /* List of values being extracted */
372
int srcTab, /* Pull data from this table */
373
int nColumn, /* Number of columns in the source table */
374
ExprList *pOrderBy, /* If not NULL, sort results using this key */
375
int distinct, /* If >=0, make sure results are distinct */
376
int eDest, /* How to dispose of the results */
377
int iParm, /* An argument to the disposal method */
378
int iContinue, /* Jump here to continue with next row */
379
int iBreak, /* Jump here to break out of the inner loop */
380
char *aff /* affinity string if eDest is SRT_Union */
382
Vdbe *v = pParse->pVdbe;
384
int hasDistinct; /* True if the DISTINCT keyword is present */
389
/* If there was a LIMIT clause on the SELECT statement, then do the check
390
** to see if this row should be output.
392
hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
393
if( pOrderBy==0 && !hasDistinct ){
394
codeLimiter(v, p, iContinue, iBreak, 0);
397
/* Pull the requested columns.
400
for(i=0; i<nColumn; i++){
401
sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
404
nColumn = pEList->nExpr;
405
for(i=0; i<pEList->nExpr; i++){
406
sqlite3ExprCode(pParse, pEList->a[i].pExpr);
410
/* If the DISTINCT keyword was present on the SELECT statement
411
** and this row has been seen before, then do not make this row
412
** part of the result.
415
#if NULL_ALWAYS_DISTINCT
416
sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
418
/* Deliberately leave the affinity string off of the following
420
sqlite3VdbeAddOp(v, OP_MakeRecord, pEList->nExpr * -1, 0);
421
sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
422
sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
423
sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
424
VdbeComment((v, "# skip indistinct records"));
425
sqlite3VdbeAddOp(v, OP_String8, 0, 0);
426
sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
428
codeLimiter(v, p, iContinue, iBreak, nColumn);
433
#ifndef SQLITE_OMIT_COMPOUND_SELECT
434
/* In this mode, write each query result to the key of the temporary
438
sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
439
sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
440
sqlite3VdbeAddOp(v, OP_String8, 0, 0);
441
sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
445
/* Construct a record from the query result, but instead of
446
** saving that record, use it as a key to delete elements from
447
** the temporary table iParm.
451
addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
452
sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
453
sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
454
sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
459
/* Store the result as data using a unique key.
462
case SRT_TempTable: {
463
sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
465
pushOntoSorter(pParse, v, pOrderBy);
467
sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
468
sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
469
sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
474
#ifndef SQLITE_OMIT_SUBQUERY
475
/* If we are creating a set for an "expr IN (SELECT ...)" construct,
476
** then there should be a single item on the stack. Write this
477
** item into the set table with bogus data.
480
int addr1 = sqlite3VdbeCurrentAddr(v);
483
assert( nColumn==1 );
484
sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
485
sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
486
addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
488
pushOntoSorter(pParse, v, pOrderBy);
490
char aff = (iParm>>16)&0xFF;
491
aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
492
sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1);
493
sqlite3VdbeAddOp(v, OP_String8, 0, 0);
494
sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
496
sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
500
/* If this is a scalar select that is part of an expression, then
501
** store the results in the appropriate memory cell and break out
506
assert( nColumn==1 );
508
pushOntoSorter(pParse, v, pOrderBy);
510
sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
511
sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
515
#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
517
/* Send the data to the callback function.
522
sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
523
pushOntoSorter(pParse, v, pOrderBy);
525
assert( eDest==SRT_Callback );
526
sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
531
/* Invoke a subroutine to handle the results. The subroutine itself
532
** is responsible for popping the results off of the stack.
534
case SRT_Subroutine: {
536
sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
537
pushOntoSorter(pParse, v, pOrderBy);
539
sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
544
#if !defined(SQLITE_OMIT_TRIGGER)
545
/* Discard the results. This is used for SELECT statements inside
546
** the body of a TRIGGER. The purpose of such selects is to call
547
** user-defined functions that have side effects. We do not care
548
** about the actual results of the select.
551
assert( eDest==SRT_Discard );
552
sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
561
** If the inner loop was generated using a non-null pOrderBy argument,
562
** then the results were placed in a sorter. After the loop is terminated
563
** we need to run the sorter and output the results. The following
564
** routine generates the code needed to do that.
566
static void generateSortTail(
567
Parse *pParse, /* The parsing context */
568
Select *p, /* The SELECT statement */
569
Vdbe *v, /* Generate code into this VDBE */
570
int nColumn, /* Number of columns of data */
571
int eDest, /* Write the sorted results here */
572
int iParm /* Optional parameter associated with eDest */
574
int end1 = sqlite3VdbeMakeLabel(v);
575
int end2 = sqlite3VdbeMakeLabel(v);
580
sqlite3 *db = pParse->db;
582
if( eDest==SRT_Sorter ) return;
583
pOrderBy = p->pOrderBy;
584
nCol = pOrderBy->nExpr;
585
pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
586
if( pInfo==0 ) return;
587
pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
588
pInfo->nField = nCol;
589
for(i=0; i<nCol; i++){
590
/* If a collation sequence was specified explicity, then it
591
** is stored in pOrderBy->a[i].zName. Otherwise, use the default
592
** collation type for the expression.
594
pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr);
595
if( !pInfo->aColl[i] ){
596
pInfo->aColl[i] = db->pDfltColl;
598
pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
600
sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
601
addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
602
codeLimiter(v, p, addr, end2, 1);
605
case SRT_TempTable: {
606
sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
607
sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
608
sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
611
#ifndef SQLITE_OMIT_SUBQUERY
613
assert( nColumn==1 );
614
sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
615
sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
616
sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
617
sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
618
sqlite3VdbeAddOp(v, OP_String8, 0, 0);
619
sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
624
assert( nColumn==1 );
625
sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
626
sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
631
case SRT_Subroutine: {
633
sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
634
sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
635
for(i=0; i<nColumn; i++){
636
sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
638
if( eDest==SRT_Callback ){
639
sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
641
sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
643
sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
651
sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
652
sqlite3VdbeResolveLabel(v, end2);
653
sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
654
sqlite3VdbeResolveLabel(v, end1);
655
sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
659
** Return a pointer to a string containing the 'declaration type' of the
660
** expression pExpr. The string may be treated as static by the caller.
662
** If the declaration type is the exact datatype definition extracted from
663
** the original CREATE TABLE statement if the expression is a column.
665
** The declaration type for an expression is either TEXT, NUMERIC or ANY.
666
** The declaration type for a ROWID field is INTEGER.
668
static const char *columnType(NameContext *pNC, Expr *pExpr){
671
if( pExpr==0 || pNC->pSrcList==0 ) return 0;
673
/* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING,
674
** and LIMIT clauses. But pExpr originates in the result set of a
675
** SELECT. So pExpr can never contain an AS operator.
677
assert( pExpr->op!=TK_AS );
682
int iCol = pExpr->iColumn;
683
while( pNC && !pTab ){
684
SrcList *pTabList = pNC->pSrcList;
685
for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
686
if( j<pTabList->nSrc ){
687
pTab = pTabList->a[j].pTab;
693
if( iCol<0 ) iCol = pTab->iPKey;
694
assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
698
zType = pTab->aCol[iCol].zType;
702
#ifndef SQLITE_OMIT_SUBQUERY
705
Select *pS = pExpr->pSelect;
706
sNC.pSrcList = pExpr->pSelect->pSrc;
708
zType = columnType(&sNC, pS->pEList->a[0].pExpr);
720
** Generate code that will tell the VDBE the declaration types of columns
721
** in the result set.
723
static void generateColumnTypes(
724
Parse *pParse, /* Parser context */
725
SrcList *pTabList, /* List of tables */
726
ExprList *pEList /* Expressions defining the result set */
728
Vdbe *v = pParse->pVdbe;
731
sNC.pSrcList = pTabList;
732
for(i=0; i<pEList->nExpr; i++){
733
Expr *p = pEList->a[i].pExpr;
734
const char *zType = columnType(&sNC, p);
735
if( zType==0 ) continue;
736
/* The vdbe must make it's own copy of the column-type, in case the
737
** schema is reset before this virtual machine is deleted.
739
sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
744
** Generate code that will tell the VDBE the names of columns
745
** in the result set. This information is used to provide the
746
** azCol[] values in the callback.
748
static void generateColumnNames(
749
Parse *pParse, /* Parser context */
750
SrcList *pTabList, /* List of tables */
751
ExprList *pEList /* Expressions defining the result set */
753
Vdbe *v = pParse->pVdbe;
755
sqlite3 *db = pParse->db;
756
int fullNames, shortNames;
758
#ifndef SQLITE_OMIT_EXPLAIN
759
/* If this is an EXPLAIN, skip this step */
760
if( pParse->explain ){
766
if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
767
pParse->colNamesSet = 1;
768
fullNames = (db->flags & SQLITE_FullColNames)!=0;
769
shortNames = (db->flags & SQLITE_ShortColNames)!=0;
770
sqlite3VdbeSetNumCols(v, pEList->nExpr);
771
for(i=0; i<pEList->nExpr; i++){
773
p = pEList->a[i].pExpr;
775
if( pEList->a[i].zName ){
776
char *zName = pEList->a[i].zName;
777
sqlite3VdbeSetColName(v, i, zName, strlen(zName));
780
if( p->op==TK_COLUMN && pTabList ){
783
int iCol = p->iColumn;
784
for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
785
assert( j<pTabList->nSrc );
786
pTab = pTabList->a[j].pTab;
787
if( iCol<0 ) iCol = pTab->iPKey;
788
assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
792
zCol = pTab->aCol[iCol].zName;
794
if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
795
sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
796
}else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
800
zTab = pTabList->a[j].zAlias;
801
if( fullNames || zTab==0 ) zTab = pTab->zName;
802
sqlite3SetString(&zName, zTab, ".", zCol, 0);
803
sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
805
sqlite3VdbeSetColName(v, i, zCol, strlen(zCol));
807
}else if( p->span.z && p->span.z[0] ){
808
sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
809
/* sqlite3VdbeCompressSpace(v, addr); */
812
assert( p->op!=TK_COLUMN || pTabList==0 );
813
sprintf(zName, "column%d", i+1);
814
sqlite3VdbeSetColName(v, i, zName, 0);
817
generateColumnTypes(pParse, pTabList, pEList);
820
#ifndef SQLITE_OMIT_COMPOUND_SELECT
822
** Name of the connection operator, used for error messages.
824
static const char *selectOpName(int id){
827
case TK_ALL: z = "UNION ALL"; break;
828
case TK_INTERSECT: z = "INTERSECT"; break;
829
case TK_EXCEPT: z = "EXCEPT"; break;
830
default: z = "UNION"; break;
834
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
837
** Forward declaration
839
static int prepSelectStmt(Parse*, Select*);
842
** Given a SELECT statement, generate a Table structure that describes
843
** the result set of that SELECT.
845
Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
851
if( prepSelectStmt(pParse, pSelect) ){
854
if( sqlite3SelectResolve(pParse, pSelect, 0) ){
857
pTab = sqliteMalloc( sizeof(Table) );
861
pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
862
pEList = pSelect->pEList;
863
pTab->nCol = pEList->nExpr;
864
assert( pTab->nCol>0 );
865
pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
866
for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
874
/* Get an appropriate name for the column
876
p = pEList->a[i].pExpr;
877
assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
878
if( (zName = pEList->a[i].zName)!=0 ){
879
/* If the column contains an "AS <name>" phrase, use <name> as the name */
880
zName = sqliteStrDup(zName);
881
}else if( p->op==TK_DOT
882
&& (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
883
/* For columns of the from A.B use B as the name */
884
zName = sqlite3MPrintf("%T", &pR->token);
885
}else if( p->span.z && p->span.z[0] ){
886
/* Use the original text of the column expression as its name */
887
zName = sqlite3MPrintf("%T", &p->span);
889
/* If all else fails, make up a name */
890
zName = sqlite3MPrintf("column%d", i+1);
892
sqlite3Dequote(zName);
893
if( sqlite3_malloc_failed ){
895
sqlite3DeleteTable(0, pTab);
899
/* Make sure the column name is unique. If the name is not unique,
900
** append a integer to the name so that it becomes unique.
903
for(j=cnt=0; j<i; j++){
904
if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
905
zName = sqlite3MPrintf("%s:%d", zBasename, ++cnt);
907
if( zName==0 ) break;
910
if( zBasename!=zName ){
911
sqliteFree(zBasename);
915
/* Get the typename, type affinity, and collating sequence for the
918
sNC.pSrcList = pSelect->pSrc;
919
zType = sqliteStrDup(columnType(&sNC, p));
921
pCol->affinity = sqlite3ExprAffinity(p);
922
pCol->pColl = sqlite3ExprCollSeq(pParse, p);
924
pCol->pColl = pParse->db->pDfltColl;
932
** Prepare a SELECT statement for processing by doing the following
935
** (1) Make sure VDBE cursor numbers have been assigned to every
936
** element of the FROM clause.
938
** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
939
** defines FROM clause. When views appear in the FROM clause,
940
** fill pTabList->a[].pSelect with a copy of the SELECT statement
941
** that implements the view. A copy is made of the view's SELECT
942
** statement so that we can freely modify or delete that statement
943
** without worrying about messing up the presistent representation
946
** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
947
** on joins and the ON and USING clause of joins.
949
** (4) Scan the list of columns in the result set (pEList) looking
950
** for instances of the "*" operator or the TABLE.* operator.
951
** If found, expand each "*" to be every column in every table
952
** and TABLE.* to be every column in TABLE.
954
** Return 0 on success. If there are problems, leave an error message
955
** in pParse and return non-zero.
957
static int prepSelectStmt(Parse *pParse, Select *p){
962
struct SrcList_item *pFrom;
964
if( p==0 || p->pSrc==0 || sqlite3_malloc_failed ) return 1;
968
/* Make sure cursor numbers have been assigned to all entries in
969
** the FROM clause of the SELECT statement.
971
sqlite3SrcListAssignCursors(pParse, p->pSrc);
973
/* Look up every table named in the FROM clause of the select. If
974
** an entry of the FROM clause is a subquery instead of a table or view,
975
** then create a transient table structure to describe the subquery.
977
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
978
if( pFrom->pTab!=0 ){
979
/* This statement has already been prepared. There is no need
984
if( pFrom->zName==0 ){
985
#ifndef SQLITE_OMIT_SUBQUERY
986
/* A sub-query in the FROM clause of a SELECT */
987
assert( pFrom->pSelect!=0 );
988
if( pFrom->zAlias==0 ){
990
sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
993
sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
997
/* The isTransient flag indicates that the Table structure has been
998
** dynamically allocated and may be freed at any time. In other words,
999
** pTab is not pointing to a persistent table structure that defines
1000
** part of the schema. */
1001
pTab->isTransient = 1;
1004
/* An ordinary table or view name in the FROM clause */
1005
pFrom->pTab = pTab =
1006
sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
1010
#ifndef SQLITE_OMIT_VIEW
1011
if( pTab->pSelect ){
1012
/* We reach here if the named table is a really a view */
1013
if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1016
/* If pFrom->pSelect!=0 it means we are dealing with a
1017
** view within a view. The SELECT structure has already been
1018
** copied by the outer view so we can skip the copy step here
1019
** in the inner view.
1021
if( pFrom->pSelect==0 ){
1022
pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
1029
/* Process NATURAL keywords, and ON and USING clauses of joins.
1031
if( sqliteProcessJoin(pParse, p) ) return 1;
1033
/* For every "*" that occurs in the column list, insert the names of
1034
** all columns in all tables. And for every TABLE.* insert the names
1035
** of all columns in TABLE. The parser inserted a special expression
1036
** with the TK_ALL operator for each "*" that it found in the column list.
1037
** The following code just has to locate the TK_ALL expressions and expand
1038
** each one to the list of all columns in all tables.
1040
** The first loop just checks to see if there are any "*" operators
1041
** that need expanding.
1043
for(k=0; k<pEList->nExpr; k++){
1044
Expr *pE = pEList->a[k].pExpr;
1045
if( pE->op==TK_ALL ) break;
1046
if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
1047
&& pE->pLeft && pE->pLeft->op==TK_ID ) break;
1050
if( k<pEList->nExpr ){
1052
** If we get here it means the result set contains one or more "*"
1053
** operators that need to be expanded. Loop through each expression
1054
** in the result set and expand them one by one.
1056
struct ExprList_item *a = pEList->a;
1058
for(k=0; k<pEList->nExpr; k++){
1059
Expr *pE = a[k].pExpr;
1060
if( pE->op!=TK_ALL &&
1061
(pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
1062
/* This particular expression does not need to be expanded.
1064
pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
1065
pNew->a[pNew->nExpr-1].zName = a[k].zName;
1069
/* This expression is a "*" or a "TABLE.*" and needs to be
1071
int tableSeen = 0; /* Set to 1 when TABLE matches */
1072
char *zTName; /* text of name of TABLE */
1073
if( pE->op==TK_DOT && pE->pLeft ){
1074
zTName = sqlite3NameFromToken(&pE->pLeft->token);
1078
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1079
Table *pTab = pFrom->pTab;
1080
char *zTabName = pFrom->zAlias;
1081
if( zTabName==0 || zTabName[0]==0 ){
1082
zTabName = pTab->zName;
1084
if( zTName && (zTabName==0 || zTabName[0]==0 ||
1085
sqlite3StrICmp(zTName, zTabName)!=0) ){
1089
for(j=0; j<pTab->nCol; j++){
1090
Expr *pExpr, *pLeft, *pRight;
1091
char *zName = pTab->aCol[j].zName;
1094
struct SrcList_item *pLeft = &pTabList->a[i-1];
1095
if( (pLeft->jointype & JT_NATURAL)!=0 &&
1096
columnIndex(pLeft->pTab, zName)>=0 ){
1097
/* In a NATURAL join, omit the join columns from the
1098
** table on the right */
1101
if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1102
/* In a join with a USING clause, omit columns in the
1103
** using clause from the table on the right. */
1107
pRight = sqlite3Expr(TK_ID, 0, 0, 0);
1108
if( pRight==0 ) break;
1109
setToken(&pRight->token, zName);
1110
if( zTabName && pTabList->nSrc>1 ){
1111
pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1112
pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
1113
if( pExpr==0 ) break;
1114
setToken(&pLeft->token, zTabName);
1115
setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
1116
pExpr->span.dyn = 1;
1119
pExpr->token.dyn = 0;
1122
pExpr->span = pExpr->token;
1124
pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
1129
sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
1131
sqlite3ErrorMsg(pParse, "no tables specified");
1138
sqlite3ExprListDelete(pEList);
1145
** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1146
** in a select structure. It just sets the pointers to NULL. This
1147
** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1148
** pointer is not NULL, this routine is called recursively on that pointer.
1150
** This routine is called on the Select structure that defines a
1151
** VIEW in order to undo any bindings to tables. This is necessary
1152
** because those tables might be DROPed by a subsequent SQL command.
1153
** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1154
** will be left pointing to a deallocated Table structure after the
1155
** DROP and a coredump will occur the next time the VIEW is used.
1158
void sqlite3SelectUnbind(Select *p){
1160
SrcList *pSrc = p->pSrc;
1161
struct SrcList_item *pItem;
1164
for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
1165
if( (pTab = pItem->pTab)!=0 ){
1166
if( pTab->isTransient ){
1167
sqlite3DeleteTable(0, pTab);
1170
if( pItem->pSelect ){
1171
sqlite3SelectUnbind(pItem->pSelect);
1178
#ifndef SQLITE_OMIT_COMPOUND_SELECT
1180
** This routine associates entries in an ORDER BY expression list with
1181
** columns in a result. For each ORDER BY expression, the opcode of
1182
** the top-level node is changed to TK_COLUMN and the iColumn value of
1183
** the top-level node is filled in with column number and the iTable
1184
** value of the top-level node is filled with iTable parameter.
1186
** If there are prior SELECT clauses, they are processed first. A match
1187
** in an earlier SELECT takes precedence over a later SELECT.
1189
** Any entry that does not match is flagged as an error. The number
1190
** of errors is returned.
1192
static int matchOrderbyToColumn(
1193
Parse *pParse, /* A place to leave error messages */
1194
Select *pSelect, /* Match to result columns of this SELECT */
1195
ExprList *pOrderBy, /* The ORDER BY values to match against columns */
1196
int iTable, /* Insert this value in iTable */
1197
int mustComplete /* If TRUE all ORDER BYs must match */
1203
if( pSelect==0 || pOrderBy==0 ) return 1;
1205
for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1207
if( prepSelectStmt(pParse, pSelect) ){
1210
if( pSelect->pPrior ){
1211
if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1215
pEList = pSelect->pEList;
1216
for(i=0; i<pOrderBy->nExpr; i++){
1217
Expr *pE = pOrderBy->a[i].pExpr;
1219
if( pOrderBy->a[i].done ) continue;
1220
if( sqlite3ExprIsInteger(pE, &iCol) ){
1221
if( iCol<=0 || iCol>pEList->nExpr ){
1222
sqlite3ErrorMsg(pParse,
1223
"ORDER BY position %d should be between 1 and %d",
1224
iCol, pEList->nExpr);
1228
if( !mustComplete ) continue;
1231
for(j=0; iCol<0 && j<pEList->nExpr; j++){
1232
if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
1233
char *zName, *zLabel;
1234
zName = pEList->a[j].zName;
1235
zLabel = sqlite3NameFromToken(&pE->token);
1236
assert( zLabel!=0 );
1237
if( sqlite3StrICmp(zName, zLabel)==0 ){
1242
if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
1249
pE->iTable = iTable;
1251
pOrderBy->a[i].done = 1;
1253
if( iCol<0 && mustComplete ){
1254
sqlite3ErrorMsg(pParse,
1255
"ORDER BY term number %d does not match any result column", i+1);
1262
#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
1265
** Get a VDBE for the given parser context. Create a new one if necessary.
1266
** If an error occurs, return NULL and leave a message in pParse.
1268
Vdbe *sqlite3GetVdbe(Parse *pParse){
1269
Vdbe *v = pParse->pVdbe;
1271
v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1277
** Compute the iLimit and iOffset fields of the SELECT based on the
1278
** pLimit and pOffset expressions. nLimit and nOffset hold the expressions
1279
** that appear in the original SQL statement after the LIMIT and OFFSET
1280
** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
1281
** are the integer memory register numbers for counters used to compute
1282
** the limit and offset. If there is no limit and/or offset, then
1283
** iLimit and iOffset are negative.
1285
** This routine changes the values if iLimit and iOffset only if
1286
** a limit or offset is defined by nLimit and nOffset. iLimit and
1287
** iOffset should have been preset to appropriate default values
1288
** (usually but not always -1) prior to calling this routine.
1289
** Only if nLimit>=0 or nOffset>0 do the limit registers get
1290
** redefined. The UNION ALL operator uses this property to force
1291
** the reuse of the same limit and offset registers across multiple
1292
** SELECT statements.
1294
static void computeLimitRegisters(Parse *pParse, Select *p){
1296
** "LIMIT -1" always shows all rows. There is some
1297
** contraversy about what the correct behavior should be.
1298
** The current implementation interprets "LIMIT 0" to mean
1302
int iMem = pParse->nMem++;
1303
Vdbe *v = sqlite3GetVdbe(pParse);
1305
sqlite3ExprCode(pParse, p->pLimit);
1306
sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1307
sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
1308
sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
1309
VdbeComment((v, "# LIMIT counter"));
1313
int iMem = pParse->nMem++;
1314
Vdbe *v = sqlite3GetVdbe(pParse);
1316
sqlite3ExprCode(pParse, p->pOffset);
1317
sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1318
sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
1319
sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
1320
VdbeComment((v, "# OFFSET counter"));
1326
** Generate VDBE instructions that will open a transient table that
1327
** will be used for an index or to store keyed results for a compound
1328
** select. In other words, open a transient table that needs a
1329
** KeyInfo structure. The number of columns in the KeyInfo is determined
1330
** by the result set of the SELECT statement in the second argument.
1332
** Specifically, this routine is called to open an index table for
1333
** DISTINCT, UNION, INTERSECT and EXCEPT select statements (but not
1336
** Make the new table a KeyAsData table if keyAsData is true.
1338
** The value returned is the address of the OP_OpenTemp instruction.
1340
static int openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
1343
sqlite3 *db = pParse->db;
1345
Vdbe *v = pParse->pVdbe;
1348
if( prepSelectStmt(pParse, p) ){
1351
nColumn = p->pEList->nExpr;
1352
pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
1353
if( pKeyInfo==0 ) return 0;
1354
pKeyInfo->enc = db->enc;
1355
pKeyInfo->nField = nColumn;
1356
for(i=0; i<nColumn; i++){
1357
pKeyInfo->aColl[i] = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
1358
if( !pKeyInfo->aColl[i] ){
1359
pKeyInfo->aColl[i] = db->pDfltColl;
1362
addr = sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0,
1363
(char*)pKeyInfo, P3_KEYINFO_HANDOFF);
1365
sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1370
#ifndef SQLITE_OMIT_COMPOUND_SELECT
1372
** Add the address "addr" to the set of all OpenTemp opcode addresses
1373
** that are being accumulated in p->ppOpenTemp.
1375
static int multiSelectOpenTempAddr(Select *p, int addr){
1376
IdList *pList = *p->ppOpenTemp = sqlite3IdListAppend(*p->ppOpenTemp, 0);
1378
return SQLITE_NOMEM;
1380
pList->a[pList->nId-1].idx = addr;
1383
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
1385
#ifndef SQLITE_OMIT_COMPOUND_SELECT
1387
** Return the appropriate collating sequence for the iCol-th column of
1388
** the result set for the compound-select statement "p". Return NULL if
1389
** the column has no default collating sequence.
1391
** The collating sequence for the compound select is taken from the
1392
** left-most term of the select that has a collating sequence.
1394
static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1397
pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1402
pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1406
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
1408
#ifndef SQLITE_OMIT_COMPOUND_SELECT
1410
** This routine is called to process a query that is really the union
1411
** or intersection of two or more separate queries.
1413
** "p" points to the right-most of the two queries. the query on the
1414
** left is p->pPrior. The left query could also be a compound query
1415
** in which case this routine will be called recursively.
1417
** The results of the total query are to be written into a destination
1418
** of type eDest with parameter iParm.
1420
** Example 1: Consider a three-way compound SQL statement.
1422
** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1424
** This statement is parsed up as follows:
1428
** `-----> SELECT b FROM t2
1430
** `------> SELECT a FROM t1
1432
** The arrows in the diagram above represent the Select.pPrior pointer.
1433
** So if this routine is called with p equal to the t3 query, then
1434
** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1436
** Notice that because of the way SQLite parses compound SELECTs, the
1437
** individual selects always group from left to right.
1439
static int multiSelect(
1440
Parse *pParse, /* Parsing context */
1441
Select *p, /* The right-most of SELECTs to be coded */
1442
int eDest, /* \___ Store query results as specified */
1443
int iParm, /* / by these two parameters. */
1444
char *aff /* If eDest is SRT_Union, the affinity string */
1446
int rc = SQLITE_OK; /* Success code from a subroutine */
1447
Select *pPrior; /* Another SELECT immediately to our left */
1448
Vdbe *v; /* Generate code to this VDBE */
1449
IdList *pOpenTemp = 0;/* OP_OpenTemp opcodes that need a KeyInfo */
1450
int aAddr[5]; /* Addresses of SetNumColumns operators */
1451
int nAddr = 0; /* Number used */
1452
int nCol; /* Number of columns in the result set */
1454
/* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
1455
** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
1457
if( p==0 || p->pPrior==0 ){
1459
goto multi_select_end;
1462
if( pPrior->pOrderBy ){
1463
sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1464
selectOpName(p->op));
1466
goto multi_select_end;
1468
if( pPrior->pLimit ){
1469
sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
1470
selectOpName(p->op));
1472
goto multi_select_end;
1475
/* Make sure we have a valid query engine. If not, create a new one.
1477
v = sqlite3GetVdbe(pParse);
1480
goto multi_select_end;
1483
/* If *p this is the right-most select statement, then initialize
1484
** p->ppOpenTemp to point to pOpenTemp. If *p is not the right most
1485
** statement then p->ppOpenTemp will have already been initialized
1486
** by a prior call to this same procedure. Pass along the pOpenTemp
1487
** pointer to pPrior, the next statement to our left.
1489
if( p->ppOpenTemp==0 ){
1490
p->ppOpenTemp = &pOpenTemp;
1492
pPrior->ppOpenTemp = p->ppOpenTemp;
1494
/* Create the destination temporary table if necessary
1496
if( eDest==SRT_TempTable ){
1497
assert( p->pEList );
1498
sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
1500
aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 0);
1504
/* Generate code for the left and right SELECT statements.
1508
if( p->pOrderBy==0 ){
1509
assert( !pPrior->pLimit );
1510
pPrior->pLimit = p->pLimit;
1511
pPrior->pOffset = p->pOffset;
1512
rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1514
goto multi_select_end;
1517
p->iLimit = pPrior->iLimit;
1518
p->iOffset = pPrior->iOffset;
1521
rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
1524
goto multi_select_end;
1528
/* For UNION ALL ... ORDER BY fall through to the next case */
1532
int unionTab; /* Cursor number of the temporary table holding result */
1533
int op = 0; /* One of the SRT_ operations to apply to self */
1534
int priorOp; /* The SRT_ operation to apply to prior selects */
1535
Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1536
ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
1539
priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
1540
if( eDest==priorOp && p->pOrderBy==0 && !p->pLimit && !p->pOffset ){
1541
/* We can reuse a temporary table generated by a SELECT to our
1546
/* We will need to create our own temporary table to hold the
1547
** intermediate results.
1549
unionTab = pParse->nTab++;
1551
&& matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1553
goto multi_select_end;
1555
addr = sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
1556
if( p->op!=TK_ALL ){
1557
rc = multiSelectOpenTempAddr(p, addr);
1558
if( rc!=SQLITE_OK ){
1559
goto multi_select_end;
1561
sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
1563
assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1564
aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, 0);
1565
assert( p->pEList );
1568
/* Code the SELECT statements to our left
1570
assert( !pPrior->pOrderBy );
1571
rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
1573
goto multi_select_end;
1576
/* Code the current SELECT statement
1579
case TK_EXCEPT: op = SRT_Except; break;
1580
case TK_UNION: op = SRT_Union; break;
1581
case TK_ALL: op = SRT_Table; break;
1584
pOrderBy = p->pOrderBy;
1588
pOffset = p->pOffset;
1590
rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
1592
p->pOrderBy = pOrderBy;
1593
sqlite3ExprDelete(p->pLimit);
1595
p->pOffset = pOffset;
1599
goto multi_select_end;
1603
/* Convert the data in the temporary table into whatever form
1604
** it is that we currently need.
1606
if( eDest!=priorOp || unionTab!=iParm ){
1607
int iCont, iBreak, iStart;
1608
assert( p->pEList );
1609
if( eDest==SRT_Callback ){
1610
generateColumnNames(pParse, 0, p->pEList);
1612
iBreak = sqlite3VdbeMakeLabel(v);
1613
iCont = sqlite3VdbeMakeLabel(v);
1614
sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
1615
computeLimitRegisters(pParse, p);
1616
iStart = sqlite3VdbeCurrentAddr(v);
1617
rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1618
p->pOrderBy, -1, eDest, iParm,
1622
goto multi_select_end;
1624
sqlite3VdbeResolveLabel(v, iCont);
1625
sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1626
sqlite3VdbeResolveLabel(v, iBreak);
1627
sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
1631
case TK_INTERSECT: {
1633
int iCont, iBreak, iStart;
1634
Expr *pLimit, *pOffset;
1637
/* INTERSECT is different from the others since it requires
1638
** two temporary tables. Hence it has its own case. Begin
1639
** by allocating the tables we will need.
1641
tab1 = pParse->nTab++;
1642
tab2 = pParse->nTab++;
1643
if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1645
goto multi_select_end;
1648
addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 0);
1649
rc = multiSelectOpenTempAddr(p, addr);
1650
if( rc!=SQLITE_OK ){
1651
goto multi_select_end;
1653
sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
1654
assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1655
aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab1, 0);
1656
assert( p->pEList );
1658
/* Code the SELECTs to our left into temporary table "tab1".
1660
rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
1662
goto multi_select_end;
1665
/* Code the current SELECT into temporary table "tab2"
1667
addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0);
1668
rc = multiSelectOpenTempAddr(p, addr);
1669
if( rc!=SQLITE_OK ){
1670
goto multi_select_end;
1672
sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
1673
assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1674
aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab2, 0);
1678
pOffset = p->pOffset;
1680
rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
1682
sqlite3ExprDelete(p->pLimit);
1684
p->pOffset = pOffset;
1686
goto multi_select_end;
1689
/* Generate code to take the intersection of the two temporary
1692
assert( p->pEList );
1693
if( eDest==SRT_Callback ){
1694
generateColumnNames(pParse, 0, p->pEList);
1696
iBreak = sqlite3VdbeMakeLabel(v);
1697
iCont = sqlite3VdbeMakeLabel(v);
1698
sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
1699
computeLimitRegisters(pParse, p);
1700
iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
1701
sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
1702
rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1703
p->pOrderBy, -1, eDest, iParm,
1707
goto multi_select_end;
1709
sqlite3VdbeResolveLabel(v, iCont);
1710
sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1711
sqlite3VdbeResolveLabel(v, iBreak);
1712
sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1713
sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
1718
/* Make sure all SELECTs in the statement have the same number of elements
1719
** in their result sets.
1721
assert( p->pEList && pPrior->pEList );
1722
if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
1723
sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1724
" do not have the same number of result columns", selectOpName(p->op));
1726
goto multi_select_end;
1729
/* Set the number of columns in temporary tables
1731
nCol = p->pEList->nExpr;
1734
sqlite3VdbeChangeP2(v, aAddr[nAddr], nCol);
1737
/* Compute collating sequences used by either the ORDER BY clause or
1738
** by any temporary tables needed to implement the compound select.
1739
** Attach the KeyInfo structure to all temporary tables. Invoke the
1740
** ORDER BY processing if there is an ORDER BY clause.
1742
** This section is run by the right-most SELECT statement only.
1743
** SELECT statements to the left always skip this part. The right-most
1744
** SELECT might also skip this part if it has no ORDER BY clause and
1745
** no temp tables are required.
1747
if( p->pOrderBy || (pOpenTemp && pOpenTemp->nId>0) ){
1748
int i; /* Loop counter */
1749
KeyInfo *pKeyInfo; /* Collating sequence for the result set */
1751
assert( p->ppOpenTemp == &pOpenTemp );
1752
pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*sizeof(CollSeq*));
1755
goto multi_select_end;
1758
pKeyInfo->enc = pParse->db->enc;
1759
pKeyInfo->nField = nCol;
1761
for(i=0; i<nCol; i++){
1762
pKeyInfo->aColl[i] = multiSelectCollSeq(pParse, p, i);
1763
if( !pKeyInfo->aColl[i] ){
1764
pKeyInfo->aColl[i] = pParse->db->pDfltColl;
1768
for(i=0; pOpenTemp && i<pOpenTemp->nId; i++){
1769
int p3type = (i==0?P3_KEYINFO_HANDOFF:P3_KEYINFO);
1770
int addr = pOpenTemp->a[i].idx;
1771
sqlite3VdbeChangeP3(v, addr, (char *)pKeyInfo, p3type);
1775
struct ExprList_item *pOrderByTerm = p->pOrderBy->a;
1776
for(i=0; i<p->pOrderBy->nExpr; i++, pOrderByTerm++){
1777
Expr *pExpr = pOrderByTerm->pExpr;
1778
char *zName = pOrderByTerm->zName;
1779
assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
1780
/* assert( !pExpr->pColl ); */
1782
pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1);
1784
pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn];
1787
generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1791
/* This happens for UNION ALL ... ORDER BY */
1792
sqliteFree(pKeyInfo);
1798
sqlite3IdListDelete(pOpenTemp);
1803
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
1805
#ifndef SQLITE_OMIT_VIEW
1807
** Scan through the expression pExpr. Replace every reference to
1808
** a column in table number iTable with a copy of the iColumn-th
1809
** entry in pEList. (But leave references to the ROWID column
1812
** This routine is part of the flattening procedure. A subquery
1813
** whose result set is defined by pEList appears as entry in the
1814
** FROM clause of a SELECT such that the VDBE cursor assigned to that
1815
** FORM clause entry is iTable. This routine make the necessary
1816
** changes to pExpr so that it refers directly to the source table
1817
** of the subquery rather the result set of the subquery.
1819
static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1820
static void substSelect(Select *, int, ExprList *); /* Forward Decl */
1821
static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
1822
if( pExpr==0 ) return;
1823
if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1824
if( pExpr->iColumn<0 ){
1825
pExpr->op = TK_NULL;
1828
assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1829
assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1830
pNew = pEList->a[pExpr->iColumn].pExpr;
1832
pExpr->op = pNew->op;
1833
assert( pExpr->pLeft==0 );
1834
pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
1835
assert( pExpr->pRight==0 );
1836
pExpr->pRight = sqlite3ExprDup(pNew->pRight);
1837
assert( pExpr->pList==0 );
1838
pExpr->pList = sqlite3ExprListDup(pNew->pList);
1839
pExpr->iTable = pNew->iTable;
1840
pExpr->iColumn = pNew->iColumn;
1841
pExpr->iAgg = pNew->iAgg;
1842
sqlite3TokenCopy(&pExpr->token, &pNew->token);
1843
sqlite3TokenCopy(&pExpr->span, &pNew->span);
1844
pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
1845
pExpr->flags = pNew->flags;
1848
substExpr(pExpr->pLeft, iTable, pEList);
1849
substExpr(pExpr->pRight, iTable, pEList);
1850
substSelect(pExpr->pSelect, iTable, pEList);
1851
substExprList(pExpr->pList, iTable, pEList);
1854
static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
1856
if( pList==0 ) return;
1857
for(i=0; i<pList->nExpr; i++){
1858
substExpr(pList->a[i].pExpr, iTable, pEList);
1861
static void substSelect(Select *p, int iTable, ExprList *pEList){
1863
substExprList(p->pEList, iTable, pEList);
1864
substExprList(p->pGroupBy, iTable, pEList);
1865
substExprList(p->pOrderBy, iTable, pEList);
1866
substExpr(p->pHaving, iTable, pEList);
1867
substExpr(p->pWhere, iTable, pEList);
1869
#endif /* !defined(SQLITE_OMIT_VIEW) */
1871
#ifndef SQLITE_OMIT_VIEW
1873
** This routine attempts to flatten subqueries in order to speed
1874
** execution. It returns 1 if it makes changes and 0 if no flattening
1877
** To understand the concept of flattening, consider the following
1880
** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1882
** The default way of implementing this query is to execute the
1883
** subquery first and store the results in a temporary table, then
1884
** run the outer query on that temporary table. This requires two
1885
** passes over the data. Furthermore, because the temporary table
1886
** has no indices, the WHERE clause on the outer query cannot be
1889
** This routine attempts to rewrite queries such as the above into
1890
** a single flat select, like this:
1892
** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1894
** The code generated for this simpification gives the same result
1895
** but only has to scan the data once. And because indices might
1896
** exist on the table t1, a complete scan of the data might be
1899
** Flattening is only attempted if all of the following are true:
1901
** (1) The subquery and the outer query do not both use aggregates.
1903
** (2) The subquery is not an aggregate or the outer query is not a join.
1905
** (3) The subquery is not the right operand of a left outer join, or
1906
** the subquery is not itself a join. (Ticket #306)
1908
** (4) The subquery is not DISTINCT or the outer query is not a join.
1910
** (5) The subquery is not DISTINCT or the outer query does not use
1913
** (6) The subquery does not use aggregates or the outer query is not
1916
** (7) The subquery has a FROM clause.
1918
** (8) The subquery does not use LIMIT or the outer query is not a join.
1920
** (9) The subquery does not use LIMIT or the outer query does not use
1923
** (10) The subquery does not use aggregates or the outer query does not
1926
** (11) The subquery and the outer query do not both have ORDER BY clauses.
1928
** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1929
** subquery has no WHERE clause. (added by ticket #350)
1931
** In this routine, the "p" parameter is a pointer to the outer query.
1932
** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1933
** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1935
** If flattening is not attempted, this routine is a no-op and returns 0.
1936
** If flattening is attempted this routine returns 1.
1938
** All of the expression analysis must occur on both the outer query and
1939
** the subquery before this routine runs.
1941
static int flattenSubquery(
1942
Parse *pParse, /* The parsing context */
1943
Select *p, /* The parent or outer SELECT statement */
1944
int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1945
int isAgg, /* True if outer SELECT uses aggregate functions */
1946
int subqueryIsAgg /* True if the subquery uses aggregate functions */
1948
Select *pSub; /* The inner query or "subquery" */
1949
SrcList *pSrc; /* The FROM clause of the outer query */
1950
SrcList *pSubSrc; /* The FROM clause of the subquery */
1951
ExprList *pList; /* The result set of the outer query */
1952
int iParent; /* VDBE cursor number of the pSub result set temp table */
1953
int i; /* Loop counter */
1954
Expr *pWhere; /* The WHERE clause */
1955
struct SrcList_item *pSubitem; /* The subquery */
1957
/* Check to see if flattening is permitted. Return 0 if not.
1959
if( p==0 ) return 0;
1961
assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
1962
pSubitem = &pSrc->a[iFrom];
1963
pSub = pSubitem->pSelect;
1965
if( isAgg && subqueryIsAgg ) return 0;
1966
if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
1967
pSubSrc = pSub->pSrc;
1969
if( (pSub->pLimit && p->pLimit) || pSub->pOffset ||
1970
(pSub->pLimit && isAgg) ) return 0;
1971
if( pSubSrc->nSrc==0 ) return 0;
1972
if( pSub->isDistinct && (pSrc->nSrc>1 || isAgg) ){
1975
if( p->isDistinct && subqueryIsAgg ) return 0;
1976
if( p->pOrderBy && pSub->pOrderBy ) return 0;
1978
/* Restriction 3: If the subquery is a join, make sure the subquery is
1979
** not used as the right operand of an outer join. Examples of why this
1982
** t1 LEFT OUTER JOIN (t2 JOIN t3)
1984
** If we flatten the above, we would get
1986
** (t1 LEFT OUTER JOIN t2) JOIN t3
1988
** which is not at all the same thing.
1990
if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1994
/* Restriction 12: If the subquery is the right operand of a left outer
1995
** join, make sure the subquery has no WHERE clause.
1996
** An examples of why this is not allowed:
1998
** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
2000
** If we flatten the above, we would get
2002
** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
2004
** But the t2.x>0 test will always fail on a NULL row of t2, which
2005
** effectively converts the OUTER JOIN into an INNER JOIN.
2007
if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
2008
&& pSub->pWhere!=0 ){
2012
/* If we reach this point, it means flattening is permitted for the
2013
** iFrom-th entry of the FROM clause in the outer query.
2016
/* Move all of the FROM elements of the subquery into the
2017
** the FROM clause of the outer query. Before doing this, remember
2018
** the cursor number for the original outer query FROM element in
2019
** iParent. The iParent cursor will never be used. Subsequent code
2020
** will scan expressions looking for iParent references and replace
2021
** those references with expressions that resolve to the subquery FROM
2022
** elements we are now copying in.
2024
iParent = pSubitem->iCursor;
2026
int nSubSrc = pSubSrc->nSrc;
2027
int jointype = pSubitem->jointype;
2028
Table *pTab = pSubitem->pTab;
2030
if( pTab && pTab->isTransient ){
2031
sqlite3DeleteTable(0, pSubitem->pTab);
2033
sqliteFree(pSubitem->zDatabase);
2034
sqliteFree(pSubitem->zName);
2035
sqliteFree(pSubitem->zAlias);
2037
int extra = nSubSrc - 1;
2038
for(i=1; i<nSubSrc; i++){
2039
pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
2042
for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2043
pSrc->a[i] = pSrc->a[i-extra];
2046
for(i=0; i<nSubSrc; i++){
2047
pSrc->a[i+iFrom] = pSubSrc->a[i];
2048
memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2050
pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
2053
/* Now begin substituting subquery result set expressions for
2054
** references to the iParent in the outer query.
2058
** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2059
** \ \_____________ subquery __________/ /
2060
** \_____________________ outer query ______________________________/
2062
** We look at every expression in the outer query and every place we see
2063
** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2065
substExprList(p->pEList, iParent, pSub->pEList);
2067
for(i=0; i<pList->nExpr; i++){
2069
if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
2070
pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
2074
substExprList(p->pGroupBy, iParent, pSub->pEList);
2075
substExpr(p->pHaving, iParent, pSub->pEList);
2077
if( pSub->pOrderBy ){
2078
assert( p->pOrderBy==0 );
2079
p->pOrderBy = pSub->pOrderBy;
2081
}else if( p->pOrderBy ){
2082
substExprList(p->pOrderBy, iParent, pSub->pEList);
2085
pWhere = sqlite3ExprDup(pSub->pWhere);
2089
if( subqueryIsAgg ){
2090
assert( p->pHaving==0 );
2091
p->pHaving = p->pWhere;
2093
substExpr(p->pHaving, iParent, pSub->pEList);
2094
p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
2095
assert( p->pGroupBy==0 );
2096
p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
2098
substExpr(p->pWhere, iParent, pSub->pEList);
2099
p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
2102
/* The flattened query is distinct if either the inner or the
2103
** outer query is distinct.
2105
p->isDistinct = p->isDistinct || pSub->isDistinct;
2108
** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2111
p->pLimit = pSub->pLimit;
2115
/* Finially, delete what is left of the subquery and return
2118
sqlite3SelectDelete(pSub);
2121
#endif /* SQLITE_OMIT_VIEW */
2124
** Analyze the SELECT statement passed in as an argument to see if it
2125
** is a simple min() or max() query. If it is and this query can be
2126
** satisfied using a single seek to the beginning or end of an index,
2127
** then generate the code for this SELECT and return 1. If this is not a
2128
** simple min() or max() query, then return 0;
2130
** A simply min() or max() query looks like this:
2132
** SELECT min(a) FROM table;
2133
** SELECT max(a) FROM table;
2135
** The query may have only a single table in its FROM argument. There
2136
** can be no GROUP BY or HAVING or WHERE clauses. The result set must
2137
** be the min() or max() of a single column of the table. The column
2138
** in the min() or max() function must be indexed.
2140
** The parameters to this routine are the same as for sqlite3Select().
2141
** See the header comment on that routine for additional information.
2143
static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2152
ExprList *pEList, *pList, eList;
2153
struct ExprList_item eListItem;
2156
/* Check to see if this query is a simple min() or max() query. Return
2157
** zero if it is not.
2159
if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
2161
if( pSrc->nSrc!=1 ) return 0;
2163
if( pEList->nExpr!=1 ) return 0;
2164
pExpr = pEList->a[0].pExpr;
2165
if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
2166
pList = pExpr->pList;
2167
if( pList==0 || pList->nExpr!=1 ) return 0;
2168
if( pExpr->token.n!=3 ) return 0;
2169
if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
2171
}else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
2176
pExpr = pList->a[0].pExpr;
2177
if( pExpr->op!=TK_COLUMN ) return 0;
2178
iCol = pExpr->iColumn;
2179
pTab = pSrc->a[0].pTab;
2181
/* If we get to here, it means the query is of the correct form.
2182
** Check to make sure we have an index and make pIdx point to the
2183
** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2184
** key column, no index is necessary so set pIdx to NULL. If no
2185
** usable index is found, return 0.
2190
CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
2191
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2192
assert( pIdx->nColumn>=1 );
2193
if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
2195
if( pIdx==0 ) return 0;
2198
/* Identify column types if we will be using the callback. This
2199
** step is skipped if the output is going to a table or a memory cell.
2200
** The column names have already been generated in the calling function.
2202
v = sqlite3GetVdbe(pParse);
2203
if( v==0 ) return 0;
2205
/* If the output is destined for a temporary table, open that table.
2207
if( eDest==SRT_TempTable ){
2208
sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
2209
sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
2212
/* Generating code to find the min or the max. Basically all we have
2213
** to do is find the first or the last entry in the chosen index. If
2214
** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2215
** or last entry in the main table.
2217
sqlite3CodeVerifySchema(pParse, pTab->iDb);
2218
base = pSrc->a[0].iCursor;
2219
computeLimitRegisters(pParse, p);
2220
if( pSrc->a[0].pSelect==0 ){
2221
sqlite3OpenTableForReading(v, base, pTab);
2223
cont = sqlite3VdbeMakeLabel(v);
2225
sqlite3VdbeAddOp(v, seekOp, base, 0);
2227
/* Even though the cursor used to open the index here is closed
2228
** as soon as a single value has been read from it, allocate it
2229
** using (pParse->nTab++) to prevent the cursor id from being
2230
** reused. This is important for statements of the form
2231
** "INSERT INTO x SELECT max() FROM x".
2234
iIdx = pParse->nTab++;
2235
sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
2236
sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
2237
(char*)&pIdx->keyInfo, P3_KEYINFO);
2238
if( seekOp==OP_Rewind ){
2239
sqlite3VdbeAddOp(v, OP_String, 0, 0);
2240
sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2243
sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
2244
sqlite3VdbeAddOp(v, OP_IdxRecno, iIdx, 0);
2245
sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
2246
sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
2249
memset(&eListItem, 0, sizeof(eListItem));
2250
eList.a = &eListItem;
2251
eList.a[0].pExpr = pExpr;
2252
selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
2253
sqlite3VdbeResolveLabel(v, cont);
2254
sqlite3VdbeAddOp(v, OP_Close, base, 0);
2260
** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
2261
** the number of errors seen.
2263
** An ORDER BY or GROUP BY is a list of expressions. If any expression
2264
** is an integer constant, then that expression is replaced by the
2265
** corresponding entry in the result set.
2267
static int processOrderGroupBy(
2268
NameContext *pNC, /* Name context of the SELECT statement. */
2269
ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
2270
const char *zType /* Either "ORDER" or "GROUP", as appropriate */
2273
ExprList *pEList = pNC->pEList; /* The result set of the SELECT */
2274
Parse *pParse = pNC->pParse; /* The result set of the SELECT */
2277
if( pOrderBy==0 ) return 0;
2278
for(i=0; i<pOrderBy->nExpr; i++){
2280
Expr *pE = pOrderBy->a[i].pExpr;
2281
if( sqlite3ExprIsInteger(pE, &iCol) ){
2282
if( iCol>0 && iCol<=pEList->nExpr ){
2283
sqlite3ExprDelete(pE);
2284
pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2286
sqlite3ErrorMsg(pParse,
2287
"%s BY column number %d out of range - should be "
2288
"between 1 and %d", zType, iCol, pEList->nExpr);
2292
if( sqlite3ExprResolveNames(pNC, pE) ){
2295
if( sqlite3ExprIsConstant(pE) ){
2296
sqlite3ErrorMsg(pParse,
2297
"%s BY terms must not be non-integer constants", zType);
2305
** This routine resolves any names used in the result set of the
2306
** supplied SELECT statement. If the SELECT statement being resolved
2307
** is a sub-select, then pOuterNC is a pointer to the NameContext
2308
** of the parent SELECT.
2310
int sqlite3SelectResolve(
2311
Parse *pParse, /* The parser context */
2312
Select *p, /* The SELECT statement being coded. */
2313
NameContext *pOuterNC /* The outer name context. May be NULL. */
2315
ExprList *pEList; /* Result set. */
2316
int i; /* For-loop variable used in multiple places */
2317
NameContext sNC; /* Local name-context */
2319
/* If this routine has run before, return immediately. */
2320
if( p->isResolved ){
2321
assert( !pOuterNC );
2326
/* If there have already been errors, do nothing. */
2327
if( pParse->nErr>0 ){
2328
return SQLITE_ERROR;
2331
/* Prepare the select statement. This call will allocate all cursors
2332
** required to handle the tables and subqueries in the FROM clause.
2334
if( prepSelectStmt(pParse, p) ){
2335
return SQLITE_ERROR;
2338
/* Resolve the expressions in the LIMIT and OFFSET clauses. These
2339
** are not allowed to refer to any names, so pass an empty NameContext.
2341
sNC.pParse = pParse;
2349
if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2350
sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2351
return SQLITE_ERROR;
2354
/* Set up the local name-context to pass to ExprResolveNames() to
2355
** resolve the expression-list.
2358
sNC.pSrcList = p->pSrc;
2359
sNC.pNext = pOuterNC;
2361
/* NameContext.nDepth stores the depth of recursion for this query. For
2362
** an outer query (e.g. SELECT * FROM sqlite_master) this is 1. For
2363
** a subquery it is 2. For a subquery of a subquery, 3. And so on.
2364
** Parse.nMaxDepth is the maximum depth for any subquery resolved so
2365
** far. This is used to determine the number of aggregate contexts
2366
** required at runtime.
2368
sNC.nDepth = (pOuterNC?pOuterNC->nDepth+1:1);
2369
if( sNC.nDepth>pParse->nMaxDepth ){
2370
pParse->nMaxDepth = sNC.nDepth;
2373
/* Resolve names in the result set. */
2375
if( !pEList ) return SQLITE_ERROR;
2376
for(i=0; i<pEList->nExpr; i++){
2377
Expr *pX = pEList->a[i].pExpr;
2378
if( sqlite3ExprResolveNames(&sNC, pX) ){
2379
return SQLITE_ERROR;
2383
/* If there are no aggregate functions in the result-set, and no GROUP BY
2384
** expression, do not allow aggregates in any of the other expressions.
2386
assert( !p->isAgg );
2387
if( p->pGroupBy || sNC.hasAgg ){
2393
/* If a HAVING clause is present, then there must be a GROUP BY clause.
2395
if( p->pHaving && !p->pGroupBy ){
2396
sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2397
return SQLITE_ERROR;
2400
/* Add the expression list to the name-context before parsing the
2401
** other expressions in the SELECT statement. This is so that
2402
** expressions in the WHERE clause (etc.) can refer to expressions by
2403
** aliases in the result set.
2405
** Minor point: If this is the case, then the expression will be
2406
** re-evaluated for each reference to it.
2408
sNC.pEList = p->pEList;
2409
if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2410
sqlite3ExprResolveNames(&sNC, p->pHaving) ||
2411
processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
2412
processOrderGroupBy(&sNC, p->pGroupBy, "GROUP")
2414
return SQLITE_ERROR;
2421
** An instance of the following struct is used by sqlite3Select()
2422
** to save aggregate related information from the Parse object
2423
** at the start of each call and to restore it at the end. See
2424
** saveAggregateInfo() and restoreAggregateInfo().
2426
struct AggregateInfo {
2430
typedef struct AggregateInfo AggregateInfo;
2433
** Copy aggregate related information from the Parse structure
2434
** into the AggregateInfo structure. Zero the aggregate related
2435
** values in the Parse struct.
2437
static void saveAggregateInfo(Parse *pParse, AggregateInfo *pInfo){
2438
pInfo->aAgg = pParse->aAgg;
2439
pInfo->nAgg = pParse->nAgg;
2445
** Copy aggregate related information from the AggregateInfo struct
2446
** back into the Parse structure. The aggregate related information
2447
** currently stored in the Parse structure is deleted.
2449
static void restoreAggregateInfo(Parse *pParse, AggregateInfo *pInfo){
2450
sqliteFree(pParse->aAgg);
2451
pParse->aAgg = pInfo->aAgg;
2452
pParse->nAgg = pInfo->nAgg;
2456
** Generate code for the given SELECT statement.
2458
** The results are distributed in various ways depending on the
2459
** value of eDest and iParm.
2461
** eDest Value Result
2462
** ------------ -------------------------------------------
2463
** SRT_Callback Invoke the callback for each row of the result.
2465
** SRT_Mem Store first result in memory cell iParm
2467
** SRT_Set Store results as keys of table iParm.
2469
** SRT_Union Store results as a key in a temporary table iParm
2471
** SRT_Except Remove results from the temporary table iParm.
2473
** SRT_Table Store results in temporary table iParm
2475
** The table above is incomplete. Additional eDist value have be added
2476
** since this comment was written. See the selectInnerLoop() function for
2477
** a complete listing of the allowed values of eDest and their meanings.
2479
** This routine returns the number of errors. If any errors are
2480
** encountered, then an appropriate error message is left in
2483
** This routine does NOT free the Select structure passed in. The
2484
** calling function needs to do that.
2486
** The pParent, parentTab, and *pParentAgg fields are filled in if this
2487
** SELECT is a subquery. This routine may try to combine this SELECT
2488
** with its parent to form a single flat query. In so doing, it might
2489
** change the parent query from a non-aggregate to an aggregate query.
2490
** For that reason, the pParentAgg flag is passed as a pointer, so it
2493
** Example 1: The meaning of the pParent parameter.
2495
** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2496
** \ \_______ subquery _______/ /
2498
** \____________________ outer query ___________________/
2500
** This routine is called for the outer query first. For that call,
2501
** pParent will be NULL. During the processing of the outer query, this
2502
** routine is called recursively to handle the subquery. For the recursive
2503
** call, pParent will point to the outer query. Because the subquery is
2504
** the second element in a three-way join, the parentTab parameter will
2505
** be 1 (the 2nd value of a 0-indexed array.)
2508
Parse *pParse, /* The parser context */
2509
Select *p, /* The SELECT statement being coded. */
2510
int eDest, /* How to dispose of the results */
2511
int iParm, /* A parameter used by the eDest disposal method */
2512
Select *pParent, /* Another SELECT for which this is a sub-query */
2513
int parentTab, /* Index in pParent->pSrc of this query */
2514
int *pParentAgg, /* True if pParent uses aggregate functions */
2515
char *aff /* If eDest is SRT_Union, the affinity string */
2520
int isAgg; /* True for select lists like "count(*)" */
2521
ExprList *pEList; /* List of columns to extract. */
2522
SrcList *pTabList; /* List of tables to select from */
2523
Expr *pWhere; /* The WHERE clause. May be NULL */
2524
ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
2525
ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2526
Expr *pHaving; /* The HAVING clause. May be NULL */
2527
int isDistinct; /* True if the DISTINCT keyword is present */
2528
int distinct; /* Table to use for the distinct set */
2529
int rc = 1; /* Value to return from this function */
2530
AggregateInfo sAggInfo;
2532
if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
2533
if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
2535
#ifndef SQLITE_OMIT_COMPOUND_SELECT
2536
/* If there is are a sequence of queries, do the earlier ones first.
2539
return multiSelect(pParse, p, eDest, iParm, aff);
2543
saveAggregateInfo(pParse, &sAggInfo);
2544
pOrderBy = p->pOrderBy;
2545
if( eDest==SRT_Union || eDest==SRT_Except || eDest==SRT_Discard ){
2548
if( sqlite3SelectResolve(pParse, p, 0) ){
2551
p->pOrderBy = pOrderBy;
2553
/* Make local copies of the parameters for this query.
2557
pGroupBy = p->pGroupBy;
2558
pHaving = p->pHaving;
2560
isDistinct = p->isDistinct;
2562
if( pEList==0 ) goto select_end;
2565
** Do not even attempt to generate any code if we have already seen
2566
** errors before this routine starts.
2568
if( pParse->nErr>0 ) goto select_end;
2570
/* If writing to memory or generating a set
2571
** only a single column may be output.
2573
assert( eDest!=SRT_Exists || pEList->nExpr==1 );
2574
#ifndef SQLITE_OMIT_SUBQUERY
2575
if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
2576
sqlite3ErrorMsg(pParse, "only a single result allowed for "
2577
"a SELECT that is part of an expression");
2582
/* ORDER BY is ignored for some destinations.
2594
/* Begin generating code.
2596
v = sqlite3GetVdbe(pParse);
2597
if( v==0 ) goto select_end;
2599
/* Identify column names if we will be using them in a callback. This
2600
** step is skipped if the output is going to some other destination.
2602
if( eDest==SRT_Callback ){
2603
generateColumnNames(pParse, pTabList, pEList);
2606
/* Generate code for all sub-queries in the FROM clause
2608
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2609
for(i=0; i<pTabList->nSrc; i++){
2610
const char *zSavedAuthContext = 0;
2611
int needRestoreContext;
2613
if( pTabList->a[i].pSelect==0 ) continue;
2614
if( pTabList->a[i].zName!=0 ){
2615
zSavedAuthContext = pParse->zAuthContext;
2616
pParse->zAuthContext = pTabList->a[i].zName;
2617
needRestoreContext = 1;
2619
needRestoreContext = 0;
2621
sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
2622
pTabList->a[i].iCursor, p, i, &isAgg, 0);
2623
if( needRestoreContext ){
2624
pParse->zAuthContext = zSavedAuthContext;
2628
if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
2629
pOrderBy = p->pOrderBy;
2631
pGroupBy = p->pGroupBy;
2632
pHaving = p->pHaving;
2633
isDistinct = p->isDistinct;
2637
/* Check for the special case of a min() or max() function by itself
2638
** in the result set.
2640
if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2645
/* Check to see if this is a subquery that can be "flattened" into its parent.
2646
** If flattening is a possiblity, do so and return immediately.
2648
#ifndef SQLITE_OMIT_VIEW
2649
if( pParent && pParentAgg &&
2650
flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
2651
if( isAgg ) *pParentAgg = 1;
2656
/* If there is an ORDER BY clause, resolve any collation sequences
2657
** names that have been explicitly specified.
2660
for(i=0; i<pOrderBy->nExpr; i++){
2661
if( pOrderBy->a[i].zName ){
2662
pOrderBy->a[i].pExpr->pColl =
2663
sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1);
2673
computeLimitRegisters(pParse, p);
2675
/* If the output is destined for a temporary table, open that table.
2677
if( eDest==SRT_TempTable ){
2678
sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
2679
sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
2682
/* Do an analysis of aggregate expressions.
2684
if( isAgg || pGroupBy ){
2686
memset(&sNC, 0, sizeof(sNC));
2687
sNC.pParse = pParse;
2688
sNC.pSrcList = pTabList;
2690
assert( pParse->nAgg==0 );
2692
for(i=0; i<pEList->nExpr; i++){
2693
if( sqlite3ExprAnalyzeAggregates(&sNC, pEList->a[i].pExpr) ){
2698
for(i=0; i<pGroupBy->nExpr; i++){
2699
if( sqlite3ExprAnalyzeAggregates(&sNC, pGroupBy->a[i].pExpr) ){
2704
if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
2708
for(i=0; i<pOrderBy->nExpr; i++){
2709
if( sqlite3ExprAnalyzeAggregates(&sNC, pOrderBy->a[i].pExpr) ){
2716
/* Reset the aggregator
2719
int addr = sqlite3VdbeAddOp(v, OP_AggReset, (pGroupBy?0:1), pParse->nAgg);
2720
for(i=0; i<pParse->nAgg; i++){
2722
if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
2723
sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_FUNCDEF);
2727
int sz = sizeof(KeyInfo) + pGroupBy->nExpr*sizeof(CollSeq*);
2728
KeyInfo *pKey = (KeyInfo *)sqliteMalloc(sz);
2732
pKey->enc = pParse->db->enc;
2733
pKey->nField = pGroupBy->nExpr;
2734
for(i=0; i<pGroupBy->nExpr; i++){
2735
pKey->aColl[i] = sqlite3ExprCollSeq(pParse, pGroupBy->a[i].pExpr);
2736
if( !pKey->aColl[i] ){
2737
pKey->aColl[i] = pParse->db->pDfltColl;
2740
sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF);
2744
/* Initialize the memory cell to NULL for SRT_Mem or 0 for SRT_Exists
2746
if( eDest==SRT_Mem || eDest==SRT_Exists ){
2747
sqlite3VdbeAddOp(v, eDest==SRT_Mem ? OP_String8 : OP_Integer, 0, 0);
2748
sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
2751
/* Open a temporary table to use for the distinct set.
2754
distinct = pParse->nTab++;
2755
openTempIndex(pParse, p, distinct, 0);
2760
/* Begin the database scan
2762
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,
2763
pGroupBy ? 0 : &pOrderBy, p->pFetch);
2764
if( pWInfo==0 ) goto select_end;
2766
/* Use the standard inner loop if we are not dealing with
2770
if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2771
iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
2776
/* If we are dealing with aggregates, then do the special aggregate
2782
pParse->fillAgg = 1;
2784
for(i=0; i<pGroupBy->nExpr; i++){
2785
sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
2787
/* No affinity string is attached to the following OP_MakeRecord
2788
** because we do not need to do any coercion of datatypes. */
2789
sqlite3VdbeAddOp(v, OP_MakeRecord, pGroupBy->nExpr, 0);
2790
lbl1 = sqlite3VdbeMakeLabel(v);
2791
sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
2793
for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2794
if( pAgg->isAgg ) continue;
2795
sqlite3ExprCode(pParse, pAgg->pExpr);
2796
sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
2798
pParse->fillAgg = 0;
2800
sqlite3VdbeResolveLabel(v, lbl1);
2802
for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2806
if( !pAgg->isAgg ) continue;
2807
assert( pAgg->pFunc!=0 );
2808
assert( pAgg->pFunc->xStep!=0 );
2812
assert( pE->op==TK_AGG_FUNCTION );
2813
nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
2814
sqlite3VdbeAddOp(v, OP_Integer, i, 0);
2815
if( pDef->needCollSeq ){
2818
for(j=0; !pColl && j<nExpr; j++){
2819
pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr);
2821
if( !pColl ) pColl = pParse->db->pDfltColl;
2822
sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2824
sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
2828
/* End the database scan loop.
2830
sqlite3WhereEnd(pWInfo);
2832
/* If we are processing aggregates, we need to set up a second loop
2833
** over all of the aggregate values and process them.
2836
int endagg = sqlite3VdbeMakeLabel(v);
2838
startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
2840
sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
2842
if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2843
iParm, startagg, endagg, aff) ){
2846
sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2847
sqlite3VdbeResolveLabel(v, endagg);
2848
sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
2851
/* If there is an ORDER BY clause, then we need to sort the results
2852
** and send them to the callback one by one.
2855
generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
2858
#ifndef SQLITE_OMIT_SUBQUERY
2859
/* If this was a subquery, we have now converted the subquery into a
2860
** temporary table. So delete the subquery structure from the parent
2861
** to prevent this subquery from being evaluated again and to force the
2862
** the use of the temporary table.
2865
assert( pParent->pSrc->nSrc>parentTab );
2866
assert( pParent->pSrc->a[parentTab].pSelect==p );
2867
sqlite3SelectDelete(p);
2868
pParent->pSrc->a[parentTab].pSelect = 0;
2872
/* The SELECT was successfully coded. Set the return code to 0
2873
** to indicate no errors.
2877
/* Control jumps to here if an error is encountered above, or upon
2878
** successful coding of the SELECT.
2881
restoreAggregateInfo(pParse, &sAggInfo);