blob: 856ba881dcaafce078806a910f104a4814a0128a [file] [log] [blame]
drhcce7d172000-05-31 15:34:51 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drhcce7d172000-05-31 15:34:51 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drhcce7d172000-05-31 15:34:51 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** 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.
drhcce7d172000-05-31 15:34:51 +000010**
11*************************************************************************
12** This file contains C code routines that are called by the parser
drhb19a2bc2001-09-16 00:13:26 +000013** to handle SELECT statements in SQLite.
drhcce7d172000-05-31 15:34:51 +000014**
drh4efc0832005-11-16 13:47:50 +000015** $Id: select.c,v 1.280 2005/11/16 13:47:51 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
drh315555c2002-10-20 15:53:03 +000019
drhcce7d172000-05-31 15:34:51 +000020/*
drh9bb61fe2000-06-05 16:01:39 +000021** Allocate a new Select structure and return a pointer to that
22** structure.
drhcce7d172000-05-31 15:34:51 +000023*/
danielk19774adee202004-05-08 08:23:19 +000024Select *sqlite3SelectNew(
drhdaffd0e2001-04-11 14:28:42 +000025 ExprList *pEList, /* which columns to include in the result */
drhad3cab52002-05-24 02:04:32 +000026 SrcList *pSrc, /* the FROM clause -- which tables to scan */
drhdaffd0e2001-04-11 14:28:42 +000027 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 */
drh9bbca4c2001-11-06 04:00:18 +000031 int isDistinct, /* true if the DISTINCT keyword is present */
danielk1977a2dc3b12005-02-05 12:48:48 +000032 Expr *pLimit, /* LIMIT value. NULL means not used */
33 Expr *pOffset /* OFFSET value. NULL means no offset */
drh9bb61fe2000-06-05 16:01:39 +000034){
35 Select *pNew;
36 pNew = sqliteMalloc( sizeof(*pNew) );
danielk1977a2dc3b12005-02-05 12:48:48 +000037 assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */
drhdaffd0e2001-04-11 14:28:42 +000038 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +000039 sqlite3ExprListDelete(pEList);
40 sqlite3SrcListDelete(pSrc);
41 sqlite3ExprDelete(pWhere);
42 sqlite3ExprListDelete(pGroupBy);
43 sqlite3ExprDelete(pHaving);
44 sqlite3ExprListDelete(pOrderBy);
danielk1977a2dc3b12005-02-05 12:48:48 +000045 sqlite3ExprDelete(pLimit);
46 sqlite3ExprDelete(pOffset);
drhdaffd0e2001-04-11 14:28:42 +000047 }else{
drhb733d032004-01-24 20:18:12 +000048 if( pEList==0 ){
danielk19774adee202004-05-08 08:23:19 +000049 pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
drhb733d032004-01-24 20:18:12 +000050 }
drhdaffd0e2001-04-11 14:28:42 +000051 pNew->pEList = pEList;
52 pNew->pSrc = pSrc;
53 pNew->pWhere = pWhere;
54 pNew->pGroupBy = pGroupBy;
55 pNew->pHaving = pHaving;
56 pNew->pOrderBy = pOrderBy;
57 pNew->isDistinct = isDistinct;
58 pNew->op = TK_SELECT;
danielk1977a2dc3b12005-02-05 12:48:48 +000059 pNew->pLimit = pLimit;
60 pNew->pOffset = pOffset;
drh7b58dae2003-07-20 01:16:46 +000061 pNew->iLimit = -1;
62 pNew->iOffset = -1;
drh0342b1f2005-09-01 03:07:44 +000063 pNew->addrOpenVirt[0] = -1;
64 pNew->addrOpenVirt[1] = -1;
65 pNew->addrOpenVirt[2] = -1;
drhdaffd0e2001-04-11 14:28:42 +000066 }
drh9bb61fe2000-06-05 16:01:39 +000067 return pNew;
68}
69
70/*
drh01f3f252002-05-24 16:14:15 +000071** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
72** type of join. Return an integer constant that expresses that type
73** in terms of the following bit values:
74**
75** JT_INNER
drh3dec2232005-09-10 15:28:09 +000076** JT_CROSS
drh01f3f252002-05-24 16:14:15 +000077** JT_OUTER
78** JT_NATURAL
79** JT_LEFT
80** JT_RIGHT
81**
82** A full outer join is the combination of JT_LEFT and JT_RIGHT.
83**
84** If an illegal or unsupported join type is seen, then still return
85** a join type, but put an error in the pParse structure.
86*/
danielk19774adee202004-05-08 08:23:19 +000087int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
drh01f3f252002-05-24 16:14:15 +000088 int jointype = 0;
89 Token *apAll[3];
90 Token *p;
drh57196282004-10-06 15:41:16 +000091 static const struct {
drhc182d162005-08-14 20:47:16 +000092 const char zKeyword[8];
drh290c1942004-08-21 17:54:45 +000093 u8 nChar;
94 u8 code;
drh01f3f252002-05-24 16:14:15 +000095 } keywords[] = {
96 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000097 { "left", 4, JT_LEFT|JT_OUTER },
98 { "right", 5, JT_RIGHT|JT_OUTER },
99 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +0000100 { "outer", 5, JT_OUTER },
101 { "inner", 5, JT_INNER },
drh3dec2232005-09-10 15:28:09 +0000102 { "cross", 5, JT_INNER|JT_CROSS },
drh01f3f252002-05-24 16:14:15 +0000103 };
104 int i, j;
105 apAll[0] = pA;
106 apAll[1] = pB;
107 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +0000108 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +0000109 p = apAll[i];
110 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
111 if( p->n==keywords[j].nChar
danielk19774adee202004-05-08 08:23:19 +0000112 && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
drh01f3f252002-05-24 16:14:15 +0000113 jointype |= keywords[j].code;
114 break;
115 }
116 }
117 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
118 jointype |= JT_ERROR;
119 break;
120 }
121 }
drhad2d8302002-05-24 20:31:36 +0000122 if(
123 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000124 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000125 ){
drhae29ffb2004-09-25 14:39:18 +0000126 const char *zSp1 = " ";
127 const char *zSp2 = " ";
128 if( pB==0 ){ zSp1++; }
129 if( pC==0 ){ zSp2++; }
130 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
131 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
drh01f3f252002-05-24 16:14:15 +0000132 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000133 }else if( jointype & JT_RIGHT ){
danielk19774adee202004-05-08 08:23:19 +0000134 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000135 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000136 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000137 }
138 return jointype;
139}
140
141/*
drhad2d8302002-05-24 20:31:36 +0000142** Return the index of a column in a table. Return -1 if the column
143** is not contained in the table.
144*/
145static int columnIndex(Table *pTab, const char *zCol){
146 int i;
147 for(i=0; i<pTab->nCol; i++){
danielk19774adee202004-05-08 08:23:19 +0000148 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
drhad2d8302002-05-24 20:31:36 +0000149 }
150 return -1;
151}
152
153/*
drh91bb0ee2004-09-01 03:06:34 +0000154** Set the value of a token to a '\000'-terminated string.
155*/
156static void setToken(Token *p, const char *z){
157 p->z = z;
158 p->n = strlen(z);
159 p->dyn = 0;
160}
161
drhc182d162005-08-14 20:47:16 +0000162/*
163** Create an expression node for an identifier with the name of zName
164*/
165static Expr *createIdExpr(const char *zName){
166 Token dummy;
167 setToken(&dummy, zName);
168 return sqlite3Expr(TK_ID, 0, 0, &dummy);
169}
170
drh91bb0ee2004-09-01 03:06:34 +0000171
172/*
drhad2d8302002-05-24 20:31:36 +0000173** Add a term to the WHERE expression in *ppExpr that requires the
174** zCol column to be equal in the two tables pTab1 and pTab2.
175*/
176static void addWhereTerm(
177 const char *zCol, /* Name of the column */
178 const Table *pTab1, /* First table */
drh030530d2005-01-18 17:40:04 +0000179 const char *zAlias1, /* Alias for first table. May be NULL */
drhad2d8302002-05-24 20:31:36 +0000180 const Table *pTab2, /* Second table */
drh030530d2005-01-18 17:40:04 +0000181 const char *zAlias2, /* Alias for second table. May be NULL */
drh22d6a532005-09-19 21:05:48 +0000182 int iRightJoinTable, /* VDBE cursor for the right table */
drhad2d8302002-05-24 20:31:36 +0000183 Expr **ppExpr /* Add the equality term to this expression */
184){
drhad2d8302002-05-24 20:31:36 +0000185 Expr *pE1a, *pE1b, *pE1c;
186 Expr *pE2a, *pE2b, *pE2c;
187 Expr *pE;
188
drhc182d162005-08-14 20:47:16 +0000189 pE1a = createIdExpr(zCol);
190 pE2a = createIdExpr(zCol);
drh030530d2005-01-18 17:40:04 +0000191 if( zAlias1==0 ){
192 zAlias1 = pTab1->zName;
193 }
drhc182d162005-08-14 20:47:16 +0000194 pE1b = createIdExpr(zAlias1);
drh030530d2005-01-18 17:40:04 +0000195 if( zAlias2==0 ){
196 zAlias2 = pTab2->zName;
197 }
drhc182d162005-08-14 20:47:16 +0000198 pE2b = createIdExpr(zAlias2);
danielk19774adee202004-05-08 08:23:19 +0000199 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
200 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
201 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000202 ExprSetProperty(pE, EP_FromJoin);
drh22d6a532005-09-19 21:05:48 +0000203 pE->iRightJoinTable = iRightJoinTable;
drh91bb0ee2004-09-01 03:06:34 +0000204 *ppExpr = sqlite3ExprAnd(*ppExpr, pE);
drhad2d8302002-05-24 20:31:36 +0000205}
206
207/*
drh1f162302002-10-27 19:35:33 +0000208** Set the EP_FromJoin property on all terms of the given expression.
drh22d6a532005-09-19 21:05:48 +0000209** And set the Expr.iRightJoinTable to iTable for every term in the
210** expression.
drh1cc093c2002-06-24 22:01:57 +0000211**
drhe78e8282003-01-19 03:59:45 +0000212** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000213** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000214** join restriction specified in the ON or USING clause and not a part
215** of the more general WHERE clause. These terms are moved over to the
216** WHERE clause during join processing but we need to remember that they
217** originated in the ON or USING clause.
drh22d6a532005-09-19 21:05:48 +0000218**
219** The Expr.iRightJoinTable tells the WHERE clause processing that the
220** expression depends on table iRightJoinTable even if that table is not
221** explicitly mentioned in the expression. That information is needed
222** for cases like this:
223**
224** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
225**
226** The where clause needs to defer the handling of the t1.x=5
227** term until after the t2 loop of the join. In that way, a
228** NULL t2 row will be inserted whenever t1.x!=5. If we do not
229** defer the handling of t1.x=5, it will be processed immediately
230** after the t1 loop and rows with t1.x!=5 will never appear in
231** the output, which is incorrect.
drh1cc093c2002-06-24 22:01:57 +0000232*/
drh22d6a532005-09-19 21:05:48 +0000233static void setJoinExpr(Expr *p, int iTable){
drh1cc093c2002-06-24 22:01:57 +0000234 while( p ){
drh1f162302002-10-27 19:35:33 +0000235 ExprSetProperty(p, EP_FromJoin);
drh22d6a532005-09-19 21:05:48 +0000236 p->iRightJoinTable = iTable;
237 setJoinExpr(p->pLeft, iTable);
drh1cc093c2002-06-24 22:01:57 +0000238 p = p->pRight;
239 }
240}
241
242/*
drhad2d8302002-05-24 20:31:36 +0000243** This routine processes the join information for a SELECT statement.
244** ON and USING clauses are converted into extra terms of the WHERE clause.
245** NATURAL joins also create extra WHERE clause terms.
246**
drh91bb0ee2004-09-01 03:06:34 +0000247** The terms of a FROM clause are contained in the Select.pSrc structure.
248** The left most table is the first entry in Select.pSrc. The right-most
249** table is the last entry. The join operator is held in the entry to
250** the left. Thus entry 0 contains the join operator for the join between
251** entries 0 and 1. Any ON or USING clauses associated with the join are
252** also attached to the left entry.
253**
drhad2d8302002-05-24 20:31:36 +0000254** This routine returns the number of errors encountered.
255*/
256static int sqliteProcessJoin(Parse *pParse, Select *p){
drh91bb0ee2004-09-01 03:06:34 +0000257 SrcList *pSrc; /* All tables in the FROM clause */
258 int i, j; /* Loop counters */
259 struct SrcList_item *pLeft; /* Left table being joined */
260 struct SrcList_item *pRight; /* Right table being joined */
drhad2d8302002-05-24 20:31:36 +0000261
drh91bb0ee2004-09-01 03:06:34 +0000262 pSrc = p->pSrc;
263 pLeft = &pSrc->a[0];
264 pRight = &pLeft[1];
265 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
266 Table *pLeftTab = pLeft->pTab;
267 Table *pRightTab = pRight->pTab;
268
269 if( pLeftTab==0 || pRightTab==0 ) continue;
drhad2d8302002-05-24 20:31:36 +0000270
271 /* When the NATURAL keyword is present, add WHERE clause terms for
272 ** every column that the two tables have in common.
273 */
drh91bb0ee2004-09-01 03:06:34 +0000274 if( pLeft->jointype & JT_NATURAL ){
275 if( pLeft->pOn || pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000276 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000277 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000278 return 1;
279 }
drh91bb0ee2004-09-01 03:06:34 +0000280 for(j=0; j<pLeftTab->nCol; j++){
281 char *zName = pLeftTab->aCol[j].zName;
282 if( columnIndex(pRightTab, zName)>=0 ){
drh030530d2005-01-18 17:40:04 +0000283 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
drh22d6a532005-09-19 21:05:48 +0000284 pRightTab, pRight->zAlias,
285 pRight->iCursor, &p->pWhere);
286
drhad2d8302002-05-24 20:31:36 +0000287 }
288 }
289 }
290
291 /* Disallow both ON and USING clauses in the same join
292 */
drh91bb0ee2004-09-01 03:06:34 +0000293 if( pLeft->pOn && pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000294 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
drhda93d232003-03-31 02:12:46 +0000295 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000296 return 1;
297 }
298
299 /* Add the ON clause to the end of the WHERE clause, connected by
drh91bb0ee2004-09-01 03:06:34 +0000300 ** an AND operator.
drhad2d8302002-05-24 20:31:36 +0000301 */
drh91bb0ee2004-09-01 03:06:34 +0000302 if( pLeft->pOn ){
drh22d6a532005-09-19 21:05:48 +0000303 setJoinExpr(pLeft->pOn, pRight->iCursor);
drh91bb0ee2004-09-01 03:06:34 +0000304 p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn);
305 pLeft->pOn = 0;
drhad2d8302002-05-24 20:31:36 +0000306 }
307
308 /* Create extra terms on the WHERE clause for each column named
309 ** in the USING clause. Example: If the two tables to be joined are
310 ** A and B and the USING clause names X, Y, and Z, then add this
311 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
312 ** Report an error if any column mentioned in the USING clause is
313 ** not contained in both tables to be joined.
314 */
drh91bb0ee2004-09-01 03:06:34 +0000315 if( pLeft->pUsing ){
316 IdList *pList = pLeft->pUsing;
drhad2d8302002-05-24 20:31:36 +0000317 for(j=0; j<pList->nId; j++){
drh91bb0ee2004-09-01 03:06:34 +0000318 char *zName = pList->a[j].zName;
319 if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
danielk19774adee202004-05-08 08:23:19 +0000320 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
drh91bb0ee2004-09-01 03:06:34 +0000321 "not present in both tables", zName);
drhad2d8302002-05-24 20:31:36 +0000322 return 1;
323 }
drh030530d2005-01-18 17:40:04 +0000324 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
drh22d6a532005-09-19 21:05:48 +0000325 pRightTab, pRight->zAlias,
326 pRight->iCursor, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000327 }
328 }
329 }
330 return 0;
331}
332
333/*
drh9bb61fe2000-06-05 16:01:39 +0000334** Delete the given Select structure and all of its substructures.
335*/
danielk19774adee202004-05-08 08:23:19 +0000336void sqlite3SelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000337 if( p==0 ) return;
danielk19774adee202004-05-08 08:23:19 +0000338 sqlite3ExprListDelete(p->pEList);
339 sqlite3SrcListDelete(p->pSrc);
340 sqlite3ExprDelete(p->pWhere);
341 sqlite3ExprListDelete(p->pGroupBy);
342 sqlite3ExprDelete(p->pHaving);
343 sqlite3ExprListDelete(p->pOrderBy);
344 sqlite3SelectDelete(p->pPrior);
danielk1977a2dc3b12005-02-05 12:48:48 +0000345 sqlite3ExprDelete(p->pLimit);
346 sqlite3ExprDelete(p->pOffset);
drh9bb61fe2000-06-05 16:01:39 +0000347 sqliteFree(p);
348}
349
350/*
drhc926afb2002-06-20 03:38:26 +0000351** Insert code into "v" that will push the record on the top of the
352** stack into the sorter.
353*/
354static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
drhc182d162005-08-14 20:47:16 +0000355 sqlite3ExprCodeExprList(pParse, pOrderBy);
drh9d2985c2005-09-08 01:58:42 +0000356 sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0);
drh4db38a72005-09-01 12:16:28 +0000357 sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0);
358 sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0);
drh9d2985c2005-09-08 01:58:42 +0000359 sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0);
drhc926afb2002-06-20 03:38:26 +0000360}
361
362/*
drhec7429a2005-10-06 16:53:14 +0000363** Add code to implement the OFFSET
drhea48eb22004-07-19 23:16:38 +0000364*/
drhec7429a2005-10-06 16:53:14 +0000365static void codeOffset(
drhbab39e12004-07-19 23:38:11 +0000366 Vdbe *v, /* Generate code into this VM */
drhea48eb22004-07-19 23:16:38 +0000367 Select *p, /* The SELECT statement being coded */
368 int iContinue, /* Jump here to skip the current record */
drhea48eb22004-07-19 23:16:38 +0000369 int nPop /* Number of times to pop stack when jumping */
370){
drh13449892005-09-07 21:22:45 +0000371 if( p->iOffset>=0 && iContinue!=0 ){
danielk1977a2dc3b12005-02-05 12:48:48 +0000372 int addr = sqlite3VdbeCurrentAddr(v) + 3;
drhea48eb22004-07-19 23:16:38 +0000373 if( nPop>0 ) addr++;
danielk1977a2dc3b12005-02-05 12:48:48 +0000374 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, 0);
375 sqlite3VdbeAddOp(v, OP_IfMemPos, p->iOffset, addr);
drhea48eb22004-07-19 23:16:38 +0000376 if( nPop>0 ){
377 sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
378 }
379 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000380 VdbeComment((v, "# skip OFFSET records"));
drhea48eb22004-07-19 23:16:38 +0000381 }
drhea48eb22004-07-19 23:16:38 +0000382}
383
384/*
drhc99130f2005-09-11 11:56:27 +0000385** Add code that will check to make sure the top N elements of the
386** stack are distinct. iTab is a sorting index that holds previously
387** seen combinations of the N values. A new entry is made in iTab
388** if the current N values are new.
389**
390** A jump to addrRepeat is made and the K values are popped from the
391** stack if the top N elements are not distinct.
392*/
393static void codeDistinct(
394 Vdbe *v, /* Generate code into this VM */
395 int iTab, /* A sorting index used to test for distinctness */
396 int addrRepeat, /* Jump to here if not distinct */
397 int N, /* The top N elements of the stack must be distinct */
398 int K /* Pop K elements from the stack if indistinct */
399){
400#if NULL_ALWAYS_DISTINCT
401 sqlite3VdbeAddOp(v, OP_IsNull, -N, sqlite3VdbeCurrentAddr(v)+6);
402#endif
403 sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0);
404 sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3);
405 sqlite3VdbeAddOp(v, OP_Pop, K, 0);
406 sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat);
407 VdbeComment((v, "# skip indistinct records"));
408 sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0);
409}
410
411
412/*
drh22827922000-06-06 17:27:05 +0000413** This routine generates the code for the inside of the inner loop
414** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000415**
drh38640e12002-07-05 21:42:36 +0000416** If srcTab and nColumn are both zero, then the pEList expressions
417** are evaluated in order to get the data for this row. If nColumn>0
418** then data is pulled from srcTab and pEList is used only to get the
419** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000420*/
421static int selectInnerLoop(
422 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000423 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000424 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000425 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000426 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000427 ExprList *pOrderBy, /* If not NULL, sort results using this key */
428 int distinct, /* If >=0, make sure results are distinct */
429 int eDest, /* How to dispose of the results */
430 int iParm, /* An argument to the disposal method */
431 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000432 int iBreak, /* Jump here to break out of the inner loop */
433 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000434){
435 Vdbe *v = pParse->pVdbe;
436 int i;
drhea48eb22004-07-19 23:16:38 +0000437 int hasDistinct; /* True if the DISTINCT keyword is present */
drh38640e12002-07-05 21:42:36 +0000438
drhdaffd0e2001-04-11 14:28:42 +0000439 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000440 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000441
drhdf199a22002-06-14 22:38:41 +0000442 /* If there was a LIMIT clause on the SELECT statement, then do the check
443 ** to see if this row should be output.
444 */
drhea48eb22004-07-19 23:16:38 +0000445 hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
446 if( pOrderBy==0 && !hasDistinct ){
drhec7429a2005-10-06 16:53:14 +0000447 codeOffset(v, p, iContinue, 0);
drhdf199a22002-06-14 22:38:41 +0000448 }
449
drh967e8b72000-06-21 13:59:10 +0000450 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000451 */
drh38640e12002-07-05 21:42:36 +0000452 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000453 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000454 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000455 }
drh38640e12002-07-05 21:42:36 +0000456 }else{
457 nColumn = pEList->nExpr;
drhc182d162005-08-14 20:47:16 +0000458 sqlite3ExprCodeExprList(pParse, pEList);
drh22827922000-06-06 17:27:05 +0000459 }
460
drhdaffd0e2001-04-11 14:28:42 +0000461 /* If the DISTINCT keyword was present on the SELECT statement
462 ** and this row has been seen before, then do not make this row
463 ** part of the result.
drh22827922000-06-06 17:27:05 +0000464 */
drhea48eb22004-07-19 23:16:38 +0000465 if( hasDistinct ){
drhc182d162005-08-14 20:47:16 +0000466 int n = pEList->nExpr;
drhc99130f2005-09-11 11:56:27 +0000467 codeDistinct(v, distinct, iContinue, n, n+1);
drhea48eb22004-07-19 23:16:38 +0000468 if( pOrderBy==0 ){
drhec7429a2005-10-06 16:53:14 +0000469 codeOffset(v, p, iContinue, nColumn);
drhea48eb22004-07-19 23:16:38 +0000470 }
drh22827922000-06-06 17:27:05 +0000471 }
drh82c3d632000-06-06 21:56:07 +0000472
drhc926afb2002-06-20 03:38:26 +0000473 switch( eDest ){
474 /* In this mode, write each query result to the key of the temporary
475 ** table iParm.
476 */
drh13449892005-09-07 21:22:45 +0000477#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhc926afb2002-06-20 03:38:26 +0000478 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000479 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
drh13449892005-09-07 21:22:45 +0000480 if( aff ){
481 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
482 }
drhf0863fe2005-06-12 21:35:51 +0000483 sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000484 break;
drh22827922000-06-06 17:27:05 +0000485 }
drh22827922000-06-06 17:27:05 +0000486
drhc926afb2002-06-20 03:38:26 +0000487 /* Construct a record from the query result, but instead of
488 ** saving that record, use it as a key to delete elements from
489 ** the temporary table iParm.
490 */
491 case SRT_Except: {
492 int addr;
danielk19774adee202004-05-08 08:23:19 +0000493 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000494 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000495 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
496 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000497 break;
498 }
danielk19775338a5f2005-01-20 13:03:10 +0000499#endif
500
501 /* Store the result as data using a unique key.
502 */
503 case SRT_Table:
drh9d2985c2005-09-08 01:58:42 +0000504 case SRT_VirtualTab: {
danielk19775338a5f2005-01-20 13:03:10 +0000505 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
506 if( pOrderBy ){
507 pushOntoSorter(pParse, v, pOrderBy);
508 }else{
drhf0863fe2005-06-12 21:35:51 +0000509 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
danielk19775338a5f2005-01-20 13:03:10 +0000510 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhf0863fe2005-06-12 21:35:51 +0000511 sqlite3VdbeAddOp(v, OP_Insert, iParm, 0);
danielk19775338a5f2005-01-20 13:03:10 +0000512 }
513 break;
514 }
drh5974a302000-06-07 14:42:26 +0000515
danielk197793758c82005-01-21 08:13:14 +0000516#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000517 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
518 ** then there should be a single item on the stack. Write this
519 ** item into the set table with bogus data.
520 */
521 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000522 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000523 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000524
drhc926afb2002-06-20 03:38:26 +0000525 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000526 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
527 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
528 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000529 if( pOrderBy ){
drhde941c62005-08-28 01:34:21 +0000530 /* At first glance you would think we could optimize out the
531 ** ORDER BY in this case since the order of entries in the set
532 ** does not matter. But there might be a LIMIT clause, in which
533 ** case the order does matter */
drhc926afb2002-06-20 03:38:26 +0000534 pushOntoSorter(pParse, v, pOrderBy);
535 }else{
danielk1977e014a832004-05-17 10:48:57 +0000536 char aff = (iParm>>16)&0xFF;
537 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
drh94a11212004-09-25 13:12:14 +0000538 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1);
drhf0863fe2005-06-12 21:35:51 +0000539 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000540 }
drhd654be82005-09-20 17:42:23 +0000541 sqlite3VdbeJumpHere(v, addr2);
drhc926afb2002-06-20 03:38:26 +0000542 break;
543 }
drh22827922000-06-06 17:27:05 +0000544
drhec7429a2005-10-06 16:53:14 +0000545 /* If any row exists in the result set, record that fact and abort.
546 */
547 case SRT_Exists: {
548 sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm);
549 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
550 /* The LIMIT clause will terminate the loop for us */
551 break;
552 }
553
drhc926afb2002-06-20 03:38:26 +0000554 /* If this is a scalar select that is part of an expression, then
555 ** store the results in the appropriate memory cell and break out
556 ** of the scan loop.
557 */
558 case SRT_Mem: {
559 assert( nColumn==1 );
560 if( pOrderBy ){
561 pushOntoSorter(pParse, v, pOrderBy);
562 }else{
danielk19774adee202004-05-08 08:23:19 +0000563 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drhec7429a2005-10-06 16:53:14 +0000564 /* The LIMIT clause will jump out of the loop for us */
drhc926afb2002-06-20 03:38:26 +0000565 }
566 break;
567 }
danielk197793758c82005-01-21 08:13:14 +0000568#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
drh22827922000-06-06 17:27:05 +0000569
drhc182d162005-08-14 20:47:16 +0000570 /* Send the data to the callback function or to a subroutine. In the
571 ** case of a subroutine, the subroutine itself is responsible for
572 ** popping the data from the stack.
drhf46f9052002-06-22 02:33:38 +0000573 */
drhc182d162005-08-14 20:47:16 +0000574 case SRT_Subroutine:
drh9d2985c2005-09-08 01:58:42 +0000575 case SRT_Callback: {
drhf46f9052002-06-22 02:33:38 +0000576 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000577 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000578 pushOntoSorter(pParse, v, pOrderBy);
drhc182d162005-08-14 20:47:16 +0000579 }else if( eDest==SRT_Subroutine ){
danielk19774adee202004-05-08 08:23:19 +0000580 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhc182d162005-08-14 20:47:16 +0000581 }else{
drhc182d162005-08-14 20:47:16 +0000582 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000583 }
drh142e30d2002-08-28 03:00:58 +0000584 break;
585 }
586
danielk19776a67fe82005-02-04 04:07:16 +0000587#if !defined(SQLITE_OMIT_TRIGGER)
drhc926afb2002-06-20 03:38:26 +0000588 /* Discard the results. This is used for SELECT statements inside
589 ** the body of a TRIGGER. The purpose of such selects is to call
590 ** user-defined functions that have side effects. We do not care
591 ** about the actual results of the select.
592 */
drhc926afb2002-06-20 03:38:26 +0000593 default: {
drhf46f9052002-06-22 02:33:38 +0000594 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000595 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000596 break;
597 }
danielk197793758c82005-01-21 08:13:14 +0000598#endif
drh82c3d632000-06-06 21:56:07 +0000599 }
drhec7429a2005-10-06 16:53:14 +0000600
601 /* Jump to the end of the loop if the LIMIT is reached.
602 */
603 if( p->iLimit>=0 && pOrderBy==0 ){
604 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, 0);
605 sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak);
606 }
drh82c3d632000-06-06 21:56:07 +0000607 return 0;
608}
609
610/*
drhdece1a82005-08-31 18:20:00 +0000611** Given an expression list, generate a KeyInfo structure that records
612** the collating sequence for each expression in that expression list.
613**
drh0342b1f2005-09-01 03:07:44 +0000614** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
615** KeyInfo structure is appropriate for initializing a virtual index to
616** implement that clause. If the ExprList is the result set of a SELECT
617** then the KeyInfo structure is appropriate for initializing a virtual
618** index to implement a DISTINCT test.
619**
drhdece1a82005-08-31 18:20:00 +0000620** Space to hold the KeyInfo structure is obtain from malloc. The calling
621** function is responsible for seeing that this structure is eventually
622** freed. Add the KeyInfo structure to the P3 field of an opcode using
623** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
624*/
625static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
626 sqlite3 *db = pParse->db;
627 int nExpr;
628 KeyInfo *pInfo;
629 struct ExprList_item *pItem;
630 int i;
631
632 nExpr = pList->nExpr;
633 pInfo = sqliteMalloc( sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
634 if( pInfo ){
635 pInfo->aSortOrder = (char*)&pInfo->aColl[nExpr];
636 pInfo->nField = nExpr;
637 pInfo->enc = db->enc;
638 for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
639 CollSeq *pColl;
640 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
641 if( !pColl ){
642 pColl = db->pDfltColl;
643 }
644 pInfo->aColl[i] = pColl;
645 pInfo->aSortOrder[i] = pItem->sortOrder;
646 }
647 }
648 return pInfo;
649}
650
651
652/*
drhd8bc7082000-06-07 23:51:50 +0000653** If the inner loop was generated using a non-null pOrderBy argument,
654** then the results were placed in a sorter. After the loop is terminated
655** we need to run the sorter and output the results. The following
656** routine generates the code needed to do that.
657*/
drhc926afb2002-06-20 03:38:26 +0000658static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000659 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000660 Select *p, /* The SELECT statement */
661 Vdbe *v, /* Generate code into this VDBE */
662 int nColumn, /* Number of columns of data */
663 int eDest, /* Write the sorted results here */
664 int iParm /* Optional parameter associated with eDest */
665){
drh0342b1f2005-09-01 03:07:44 +0000666 int brk = sqlite3VdbeMakeLabel(v);
667 int cont = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000668 int addr;
drh0342b1f2005-09-01 03:07:44 +0000669 int iTab;
670 ExprList *pOrderBy = p->pOrderBy;
drhffbc3082004-05-21 01:29:06 +0000671
drh9d2985c2005-09-08 01:58:42 +0000672 iTab = pOrderBy->iECursor;
drh0342b1f2005-09-01 03:07:44 +0000673 addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
drhec7429a2005-10-06 16:53:14 +0000674 codeOffset(v, p, cont, 0);
drh4db38a72005-09-01 12:16:28 +0000675 sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1);
drhc926afb2002-06-20 03:38:26 +0000676 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000677 case SRT_Table:
drh9d2985c2005-09-08 01:58:42 +0000678 case SRT_VirtualTab: {
drhf0863fe2005-06-12 21:35:51 +0000679 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
danielk19774adee202004-05-08 08:23:19 +0000680 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhf0863fe2005-06-12 21:35:51 +0000681 sqlite3VdbeAddOp(v, OP_Insert, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000682 break;
683 }
danielk197793758c82005-01-21 08:13:14 +0000684#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000685 case SRT_Set: {
686 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000687 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
688 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
689 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
drh8a512562005-11-14 22:29:05 +0000690 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "c", P3_STATIC);
drhf0863fe2005-06-12 21:35:51 +0000691 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000692 break;
693 }
694 case SRT_Mem: {
695 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000696 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drhec7429a2005-10-06 16:53:14 +0000697 /* The LIMIT clause will terminate the loop for us */
drhc926afb2002-06-20 03:38:26 +0000698 break;
699 }
danielk197793758c82005-01-21 08:13:14 +0000700#endif
drhce665cf2004-05-21 03:01:58 +0000701 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000702 case SRT_Subroutine: {
703 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000704 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
705 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000706 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000707 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000708 }
drhce665cf2004-05-21 03:01:58 +0000709 if( eDest==SRT_Callback ){
710 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
711 }else{
712 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
713 }
danielk197784ac9d02004-05-18 09:58:06 +0000714 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000715 break;
716 }
drhc926afb2002-06-20 03:38:26 +0000717 default: {
drhf46f9052002-06-22 02:33:38 +0000718 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000719 break;
720 }
721 }
drhec7429a2005-10-06 16:53:14 +0000722
723 /* Jump to the end of the loop when the LIMIT is reached
724 */
725 if( p->iLimit>=0 ){
726 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, 0);
727 sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk);
728 }
729
730 /* The bottom of the loop
731 */
drh0342b1f2005-09-01 03:07:44 +0000732 sqlite3VdbeResolveLabel(v, cont);
733 sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
734 sqlite3VdbeResolveLabel(v, brk);
drhd8bc7082000-06-07 23:51:50 +0000735}
736
737/*
danielk1977517eb642004-06-07 10:00:31 +0000738** Return a pointer to a string containing the 'declaration type' of the
739** expression pExpr. The string may be treated as static by the caller.
drhe78e8282003-01-19 03:59:45 +0000740**
danielk1977517eb642004-06-07 10:00:31 +0000741** If the declaration type is the exact datatype definition extracted from
742** the original CREATE TABLE statement if the expression is a column.
743**
744** The declaration type for an expression is either TEXT, NUMERIC or ANY.
745** The declaration type for a ROWID field is INTEGER.
746*/
danielk1977b3bce662005-01-29 08:32:43 +0000747static const char *columnType(NameContext *pNC, Expr *pExpr){
danielk197700e279d2004-06-21 07:36:32 +0000748 char const *zType;
danielk1977517eb642004-06-07 10:00:31 +0000749 int j;
danielk1977b3bce662005-01-29 08:32:43 +0000750 if( pExpr==0 || pNC->pSrcList==0 ) return 0;
danielk19775338a5f2005-01-20 13:03:10 +0000751
752 /* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING,
753 ** and LIMIT clauses. But pExpr originates in the result set of a
754 ** SELECT. So pExpr can never contain an AS operator.
755 */
756 assert( pExpr->op!=TK_AS );
757
danielk197700e279d2004-06-21 07:36:32 +0000758 switch( pExpr->op ){
759 case TK_COLUMN: {
danielk1977b3bce662005-01-29 08:32:43 +0000760 Table *pTab = 0;
danielk197700e279d2004-06-21 07:36:32 +0000761 int iCol = pExpr->iColumn;
danielk1977b3bce662005-01-29 08:32:43 +0000762 while( pNC && !pTab ){
763 SrcList *pTabList = pNC->pSrcList;
764 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
765 if( j<pTabList->nSrc ){
766 pTab = pTabList->a[j].pTab;
767 }else{
768 pNC = pNC->pNext;
769 }
770 }
drh7e627792005-04-29 02:10:00 +0000771 if( pTab==0 ){
772 /* FIX ME:
773 ** This can occurs if you have something like "SELECT new.x;" inside
774 ** a trigger. In other words, if you reference the special "new"
775 ** table in the result set of a select. We do not have a good way
776 ** to find the actual table type, so call it "TEXT". This is really
777 ** something of a bug, but I do not know how to fix it.
778 **
779 ** This code does not produce the correct answer - it just prevents
780 ** a segfault. See ticket #1229.
781 */
782 zType = "TEXT";
783 break;
784 }
danielk1977b3bce662005-01-29 08:32:43 +0000785 assert( pTab );
danielk197700e279d2004-06-21 07:36:32 +0000786 if( iCol<0 ) iCol = pTab->iPKey;
787 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
788 if( iCol<0 ){
789 zType = "INTEGER";
790 }else{
791 zType = pTab->aCol[iCol].zType;
792 }
793 break;
danielk1977517eb642004-06-07 10:00:31 +0000794 }
danielk197793758c82005-01-21 08:13:14 +0000795#ifndef SQLITE_OMIT_SUBQUERY
danielk197700e279d2004-06-21 07:36:32 +0000796 case TK_SELECT: {
danielk1977b3bce662005-01-29 08:32:43 +0000797 NameContext sNC;
danielk197700e279d2004-06-21 07:36:32 +0000798 Select *pS = pExpr->pSelect;
danielk1977b3bce662005-01-29 08:32:43 +0000799 sNC.pSrcList = pExpr->pSelect->pSrc;
800 sNC.pNext = pNC;
801 zType = columnType(&sNC, pS->pEList->a[0].pExpr);
danielk197700e279d2004-06-21 07:36:32 +0000802 break;
danielk1977517eb642004-06-07 10:00:31 +0000803 }
danielk197793758c82005-01-21 08:13:14 +0000804#endif
danielk197700e279d2004-06-21 07:36:32 +0000805 default:
806 zType = 0;
danielk1977517eb642004-06-07 10:00:31 +0000807 }
danielk197700e279d2004-06-21 07:36:32 +0000808
danielk1977517eb642004-06-07 10:00:31 +0000809 return zType;
810}
811
812/*
813** Generate code that will tell the VDBE the declaration types of columns
814** in the result set.
drhfcb78a42003-01-18 20:11:05 +0000815*/
816static void generateColumnTypes(
817 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000818 SrcList *pTabList, /* List of tables */
819 ExprList *pEList /* Expressions defining the result set */
820){
821 Vdbe *v = pParse->pVdbe;
danielk1977517eb642004-06-07 10:00:31 +0000822 int i;
danielk1977b3bce662005-01-29 08:32:43 +0000823 NameContext sNC;
824 sNC.pSrcList = pTabList;
drhfcb78a42003-01-18 20:11:05 +0000825 for(i=0; i<pEList->nExpr; i++){
826 Expr *p = pEList->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +0000827 const char *zType = columnType(&sNC, p);
danielk197700e279d2004-06-21 07:36:32 +0000828 if( zType==0 ) continue;
danielk1977fbcd5852004-06-15 02:44:18 +0000829 /* The vdbe must make it's own copy of the column-type, in case the
830 ** schema is reset before this virtual machine is deleted.
831 */
832 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
drhfcb78a42003-01-18 20:11:05 +0000833 }
834}
835
836/*
837** Generate code that will tell the VDBE the names of columns
838** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000839** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000840*/
drh832508b2002-03-02 17:04:07 +0000841static void generateColumnNames(
842 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000843 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000844 ExprList *pEList /* Expressions defining the result set */
845){
drhd8bc7082000-06-07 23:51:50 +0000846 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000847 int i, j;
drh9bb575f2004-09-06 17:24:11 +0000848 sqlite3 *db = pParse->db;
drhfcabd462004-02-20 14:50:58 +0000849 int fullNames, shortNames;
850
drhfe2093d2005-01-20 22:48:47 +0000851#ifndef SQLITE_OMIT_EXPLAIN
danielk19773cf86062004-05-26 10:11:05 +0000852 /* If this is an EXPLAIN, skip this step */
853 if( pParse->explain ){
danielk197761de0d12004-05-27 23:56:16 +0000854 return;
danielk19773cf86062004-05-26 10:11:05 +0000855 }
danielk19775338a5f2005-01-20 13:03:10 +0000856#endif
danielk19773cf86062004-05-26 10:11:05 +0000857
drhd6502752004-02-16 03:44:01 +0000858 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000859 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000860 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000861 fullNames = (db->flags & SQLITE_FullColNames)!=0;
862 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
danielk197722322fd2004-05-25 23:35:17 +0000863 sqlite3VdbeSetNumCols(v, pEList->nExpr);
drh82c3d632000-06-06 21:56:07 +0000864 for(i=0; i<pEList->nExpr; i++){
865 Expr *p;
drh5a387052003-01-11 14:19:51 +0000866 p = pEList->a[i].pExpr;
867 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000868 if( pEList->a[i].zName ){
869 char *zName = pEList->a[i].zName;
danielk1977d8123362004-06-12 09:25:12 +0000870 sqlite3VdbeSetColName(v, i, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000871 continue;
872 }
drhfa173a72002-07-10 21:26:00 +0000873 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000874 Table *pTab;
drh97665872002-02-13 23:22:53 +0000875 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000876 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000877 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
878 assert( j<pTabList->nSrc );
879 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000880 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000881 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000882 if( iCol<0 ){
drh47a6db22005-01-18 16:02:40 +0000883 zCol = "rowid";
drhb1363202002-06-26 02:45:03 +0000884 }else{
885 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000886 }
drhfcabd462004-02-20 14:50:58 +0000887 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000888 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
drhfcabd462004-02-20 14:50:58 +0000889 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000890 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000891 char *zTab;
892
drh6a3ea0e2003-05-02 14:32:12 +0000893 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000894 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000895 sqlite3SetString(&zName, zTab, ".", zCol, 0);
danielk19773cf86062004-05-26 10:11:05 +0000896 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000897 }else{
drh47a6db22005-01-18 16:02:40 +0000898 sqlite3VdbeSetColName(v, i, zCol, strlen(zCol));
drh82c3d632000-06-06 21:56:07 +0000899 }
drh6977fea2002-10-22 23:38:04 +0000900 }else if( p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000901 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
902 /* sqlite3VdbeCompressSpace(v, addr); */
drh1bee3d72001-10-15 00:44:35 +0000903 }else{
904 char zName[30];
905 assert( p->op!=TK_COLUMN || pTabList==0 );
906 sprintf(zName, "column%d", i+1);
danielk19773cf86062004-05-26 10:11:05 +0000907 sqlite3VdbeSetColName(v, i, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000908 }
909 }
danielk197776d505b2004-05-28 13:13:02 +0000910 generateColumnTypes(pParse, pTabList, pEList);
drh82c3d632000-06-06 21:56:07 +0000911}
912
danielk197793758c82005-01-21 08:13:14 +0000913#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +0000914/*
drhd8bc7082000-06-07 23:51:50 +0000915** Name of the connection operator, used for error messages.
916*/
917static const char *selectOpName(int id){
918 char *z;
919 switch( id ){
920 case TK_ALL: z = "UNION ALL"; break;
921 case TK_INTERSECT: z = "INTERSECT"; break;
922 case TK_EXCEPT: z = "EXCEPT"; break;
923 default: z = "UNION"; break;
924 }
925 return z;
926}
danielk197793758c82005-01-21 08:13:14 +0000927#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +0000928
929/*
drh315555c2002-10-20 15:53:03 +0000930** Forward declaration
931*/
drh9b3187e2005-01-18 14:45:47 +0000932static int prepSelectStmt(Parse*, Select*);
drh315555c2002-10-20 15:53:03 +0000933
934/*
drh22f70c32002-02-18 01:17:00 +0000935** Given a SELECT statement, generate a Table structure that describes
936** the result set of that SELECT.
937*/
danielk19774adee202004-05-08 08:23:19 +0000938Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000939 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000940 int i, j;
drh22f70c32002-02-18 01:17:00 +0000941 ExprList *pEList;
drh290c1942004-08-21 17:54:45 +0000942 Column *aCol, *pCol;
drh22f70c32002-02-18 01:17:00 +0000943
drh9b3187e2005-01-18 14:45:47 +0000944 if( prepSelectStmt(pParse, pSelect) ){
drh22f70c32002-02-18 01:17:00 +0000945 return 0;
946 }
danielk1977142bdf42005-01-30 11:11:44 +0000947 if( sqlite3SelectResolve(pParse, pSelect, 0) ){
948 return 0;
949 }
drh22f70c32002-02-18 01:17:00 +0000950 pTab = sqliteMalloc( sizeof(Table) );
951 if( pTab==0 ){
952 return 0;
953 }
drhed8a3bb2005-06-06 21:19:56 +0000954 pTab->nRef = 1;
drh22f70c32002-02-18 01:17:00 +0000955 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
956 pEList = pSelect->pEList;
957 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000958 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000959 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh290c1942004-08-21 17:54:45 +0000960 for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
drh79d5f632005-01-18 17:20:10 +0000961 Expr *p, *pR;
danielk1977517eb642004-06-07 10:00:31 +0000962 char *zType;
drh91bb0ee2004-09-01 03:06:34 +0000963 char *zName;
drh79d5f632005-01-18 17:20:10 +0000964 char *zBasename;
965 int cnt;
danielk1977b3bce662005-01-29 08:32:43 +0000966 NameContext sNC;
drh79d5f632005-01-18 17:20:10 +0000967
968 /* Get an appropriate name for the column
969 */
970 p = pEList->a[i].pExpr;
drh290c1942004-08-21 17:54:45 +0000971 assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
drh91bb0ee2004-09-01 03:06:34 +0000972 if( (zName = pEList->a[i].zName)!=0 ){
drh79d5f632005-01-18 17:20:10 +0000973 /* If the column contains an "AS <name>" phrase, use <name> as the name */
drh91bb0ee2004-09-01 03:06:34 +0000974 zName = sqliteStrDup(zName);
danielk1977517eb642004-06-07 10:00:31 +0000975 }else if( p->op==TK_DOT
drh79d5f632005-01-18 17:20:10 +0000976 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
977 /* For columns of the from A.B use B as the name */
drh91bb0ee2004-09-01 03:06:34 +0000978 zName = sqlite3MPrintf("%T", &pR->token);
drhb733d032004-01-24 20:18:12 +0000979 }else if( p->span.z && p->span.z[0] ){
drh79d5f632005-01-18 17:20:10 +0000980 /* Use the original text of the column expression as its name */
drh91bb0ee2004-09-01 03:06:34 +0000981 zName = sqlite3MPrintf("%T", &p->span);
drh22f70c32002-02-18 01:17:00 +0000982 }else{
drh79d5f632005-01-18 17:20:10 +0000983 /* If all else fails, make up a name */
drh91bb0ee2004-09-01 03:06:34 +0000984 zName = sqlite3MPrintf("column%d", i+1);
drh22f70c32002-02-18 01:17:00 +0000985 }
drh91bb0ee2004-09-01 03:06:34 +0000986 sqlite3Dequote(zName);
drhdd5b2fa2005-03-28 03:39:55 +0000987 if( sqlite3_malloc_failed ){
988 sqliteFree(zName);
989 sqlite3DeleteTable(0, pTab);
990 return 0;
991 }
drh79d5f632005-01-18 17:20:10 +0000992
993 /* Make sure the column name is unique. If the name is not unique,
994 ** append a integer to the name so that it becomes unique.
995 */
996 zBasename = zName;
997 for(j=cnt=0; j<i; j++){
998 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
999 zName = sqlite3MPrintf("%s:%d", zBasename, ++cnt);
1000 j = -1;
drhdd5b2fa2005-03-28 03:39:55 +00001001 if( zName==0 ) break;
drh79d5f632005-01-18 17:20:10 +00001002 }
1003 }
1004 if( zBasename!=zName ){
1005 sqliteFree(zBasename);
1006 }
drh91bb0ee2004-09-01 03:06:34 +00001007 pCol->zName = zName;
danielk1977517eb642004-06-07 10:00:31 +00001008
drh79d5f632005-01-18 17:20:10 +00001009 /* Get the typename, type affinity, and collating sequence for the
1010 ** column.
1011 */
drhc43e8be2005-05-16 22:37:54 +00001012 memset(&sNC, 0, sizeof(sNC));
danielk1977b3bce662005-01-29 08:32:43 +00001013 sNC.pSrcList = pSelect->pSrc;
1014 zType = sqliteStrDup(columnType(&sNC, p));
drh290c1942004-08-21 17:54:45 +00001015 pCol->zType = zType;
danielk1977c60e9b82005-01-31 12:42:29 +00001016 pCol->affinity = sqlite3ExprAffinity(p);
drh290c1942004-08-21 17:54:45 +00001017 pCol->pColl = sqlite3ExprCollSeq(pParse, p);
1018 if( !pCol->pColl ){
1019 pCol->pColl = pParse->db->pDfltColl;
danielk19770202b292004-06-09 09:55:16 +00001020 }
drh22f70c32002-02-18 01:17:00 +00001021 }
1022 pTab->iPKey = -1;
1023 return pTab;
1024}
1025
1026/*
drh9b3187e2005-01-18 14:45:47 +00001027** Prepare a SELECT statement for processing by doing the following
1028** things:
drhd8bc7082000-06-07 23:51:50 +00001029**
drh9b3187e2005-01-18 14:45:47 +00001030** (1) Make sure VDBE cursor numbers have been assigned to every
1031** element of the FROM clause.
1032**
1033** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
1034** defines FROM clause. When views appear in the FROM clause,
drh63eb5f22003-04-29 16:20:44 +00001035** fill pTabList->a[].pSelect with a copy of the SELECT statement
1036** that implements the view. A copy is made of the view's SELECT
1037** statement so that we can freely modify or delete that statement
1038** without worrying about messing up the presistent representation
1039** of the view.
drhd8bc7082000-06-07 23:51:50 +00001040**
drh9b3187e2005-01-18 14:45:47 +00001041** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
drhad2d8302002-05-24 20:31:36 +00001042** on joins and the ON and USING clause of joins.
1043**
drh9b3187e2005-01-18 14:45:47 +00001044** (4) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +00001045** for instances of the "*" operator or the TABLE.* operator.
1046** If found, expand each "*" to be every column in every table
1047** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +00001048**
1049** Return 0 on success. If there are problems, leave an error message
1050** in pParse and return non-zero.
1051*/
drh9b3187e2005-01-18 14:45:47 +00001052static int prepSelectStmt(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +00001053 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +00001054 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +00001055 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +00001056 Table *pTab;
drh290c1942004-08-21 17:54:45 +00001057 struct SrcList_item *pFrom;
drhdaffd0e2001-04-11 14:28:42 +00001058
danielk1977e94ddc92005-03-21 03:53:38 +00001059 if( p==0 || p->pSrc==0 || sqlite3_malloc_failed ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00001060 pTabList = p->pSrc;
1061 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +00001062
drh9b3187e2005-01-18 14:45:47 +00001063 /* Make sure cursor numbers have been assigned to all entries in
1064 ** the FROM clause of the SELECT statement.
1065 */
1066 sqlite3SrcListAssignCursors(pParse, p->pSrc);
1067
1068 /* Look up every table named in the FROM clause of the select. If
1069 ** an entry of the FROM clause is a subquery instead of a table or view,
1070 ** then create a transient table structure to describe the subquery.
drhd8bc7082000-06-07 23:51:50 +00001071 */
drh290c1942004-08-21 17:54:45 +00001072 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
drh9b3187e2005-01-18 14:45:47 +00001073 if( pFrom->pTab!=0 ){
1074 /* This statement has already been prepared. There is no need
1075 ** to go further. */
1076 assert( i==0 );
drhd8bc7082000-06-07 23:51:50 +00001077 return 0;
1078 }
drh290c1942004-08-21 17:54:45 +00001079 if( pFrom->zName==0 ){
danielk197793758c82005-01-21 08:13:14 +00001080#ifndef SQLITE_OMIT_SUBQUERY
drh22f70c32002-02-18 01:17:00 +00001081 /* A sub-query in the FROM clause of a SELECT */
drh290c1942004-08-21 17:54:45 +00001082 assert( pFrom->pSelect!=0 );
1083 if( pFrom->zAlias==0 ){
drh91bb0ee2004-09-01 03:06:34 +00001084 pFrom->zAlias =
1085 sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
drhad2d8302002-05-24 20:31:36 +00001086 }
drhed8a3bb2005-06-06 21:19:56 +00001087 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001088 pFrom->pTab = pTab =
1089 sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
drh22f70c32002-02-18 01:17:00 +00001090 if( pTab==0 ){
1091 return 1;
1092 }
drh5cf590c2003-04-24 01:45:04 +00001093 /* The isTransient flag indicates that the Table structure has been
1094 ** dynamically allocated and may be freed at any time. In other words,
1095 ** pTab is not pointing to a persistent table structure that defines
1096 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +00001097 pTab->isTransient = 1;
danielk197793758c82005-01-21 08:13:14 +00001098#endif
drh22f70c32002-02-18 01:17:00 +00001099 }else{
drha76b5df2002-02-23 02:32:10 +00001100 /* An ordinary table or view name in the FROM clause */
drhed8a3bb2005-06-06 21:19:56 +00001101 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001102 pFrom->pTab = pTab =
1103 sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
drha76b5df2002-02-23 02:32:10 +00001104 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +00001105 return 1;
1106 }
drhed8a3bb2005-06-06 21:19:56 +00001107 pTab->nRef++;
danielk197793758c82005-01-21 08:13:14 +00001108#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00001109 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +00001110 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +00001111 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +00001112 return 1;
1113 }
drh290c1942004-08-21 17:54:45 +00001114 /* If pFrom->pSelect!=0 it means we are dealing with a
drh63eb5f22003-04-29 16:20:44 +00001115 ** view within a view. The SELECT structure has already been
1116 ** copied by the outer view so we can skip the copy step here
1117 ** in the inner view.
1118 */
drh290c1942004-08-21 17:54:45 +00001119 if( pFrom->pSelect==0 ){
1120 pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +00001121 }
drha76b5df2002-02-23 02:32:10 +00001122 }
danielk197793758c82005-01-21 08:13:14 +00001123#endif
drhd8bc7082000-06-07 23:51:50 +00001124 }
1125 }
1126
drhad2d8302002-05-24 20:31:36 +00001127 /* Process NATURAL keywords, and ON and USING clauses of joins.
1128 */
1129 if( sqliteProcessJoin(pParse, p) ) return 1;
1130
drh7c917d12001-12-16 20:05:05 +00001131 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +00001132 ** all columns in all tables. And for every TABLE.* insert the names
1133 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +00001134 ** with the TK_ALL operator for each "*" that it found in the column list.
1135 ** The following code just has to locate the TK_ALL expressions and expand
1136 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +00001137 **
1138 ** The first loop just checks to see if there are any "*" operators
1139 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +00001140 */
drh7c917d12001-12-16 20:05:05 +00001141 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001142 Expr *pE = pEList->a[k].pExpr;
1143 if( pE->op==TK_ALL ) break;
1144 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
1145 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +00001146 }
drh54473222002-04-04 02:10:55 +00001147 rc = 0;
drh7c917d12001-12-16 20:05:05 +00001148 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +00001149 /*
1150 ** If we get here it means the result set contains one or more "*"
1151 ** operators that need to be expanded. Loop through each expression
1152 ** in the result set and expand them one by one.
1153 */
drh7c917d12001-12-16 20:05:05 +00001154 struct ExprList_item *a = pEList->a;
1155 ExprList *pNew = 0;
drhd70dc522005-06-06 16:34:33 +00001156 int flags = pParse->db->flags;
1157 int longNames = (flags & SQLITE_FullColNames)!=0 &&
1158 (flags & SQLITE_ShortColNames)==0;
1159
drh7c917d12001-12-16 20:05:05 +00001160 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001161 Expr *pE = a[k].pExpr;
1162 if( pE->op!=TK_ALL &&
1163 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
1164 /* This particular expression does not need to be expanded.
1165 */
danielk19774adee202004-05-08 08:23:19 +00001166 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001167 pNew->a[pNew->nExpr-1].zName = a[k].zName;
1168 a[k].pExpr = 0;
1169 a[k].zName = 0;
1170 }else{
drh54473222002-04-04 02:10:55 +00001171 /* This expression is a "*" or a "TABLE.*" and needs to be
1172 ** expanded. */
1173 int tableSeen = 0; /* Set to 1 when TABLE matches */
drhcf55b7a2004-07-20 01:45:19 +00001174 char *zTName; /* text of name of TABLE */
drh54473222002-04-04 02:10:55 +00001175 if( pE->op==TK_DOT && pE->pLeft ){
drhcf55b7a2004-07-20 01:45:19 +00001176 zTName = sqlite3NameFromToken(&pE->pLeft->token);
drh54473222002-04-04 02:10:55 +00001177 }else{
drhcf55b7a2004-07-20 01:45:19 +00001178 zTName = 0;
drh54473222002-04-04 02:10:55 +00001179 }
drh290c1942004-08-21 17:54:45 +00001180 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1181 Table *pTab = pFrom->pTab;
1182 char *zTabName = pFrom->zAlias;
drh54473222002-04-04 02:10:55 +00001183 if( zTabName==0 || zTabName[0]==0 ){
1184 zTabName = pTab->zName;
1185 }
drhcf55b7a2004-07-20 01:45:19 +00001186 if( zTName && (zTabName==0 || zTabName[0]==0 ||
1187 sqlite3StrICmp(zTName, zTabName)!=0) ){
drh54473222002-04-04 02:10:55 +00001188 continue;
1189 }
1190 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001191 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001192 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001193 char *zName = pTab->aCol[j].zName;
1194
drh91bb0ee2004-09-01 03:06:34 +00001195 if( i>0 ){
1196 struct SrcList_item *pLeft = &pTabList->a[i-1];
1197 if( (pLeft->jointype & JT_NATURAL)!=0 &&
1198 columnIndex(pLeft->pTab, zName)>=0 ){
1199 /* In a NATURAL join, omit the join columns from the
1200 ** table on the right */
1201 continue;
1202 }
1203 if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1204 /* In a join with a USING clause, omit columns in the
1205 ** using clause from the table on the right. */
1206 continue;
1207 }
drhad2d8302002-05-24 20:31:36 +00001208 }
danielk19774adee202004-05-08 08:23:19 +00001209 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001210 if( pRight==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001211 setToken(&pRight->token, zName);
drhd70dc522005-06-06 16:34:33 +00001212 if( zTabName && (longNames || pTabList->nSrc>1) ){
danielk19774adee202004-05-08 08:23:19 +00001213 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1214 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001215 if( pExpr==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001216 setToken(&pLeft->token, zTabName);
1217 setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
drh6977fea2002-10-22 23:38:04 +00001218 pExpr->span.dyn = 1;
1219 pExpr->token.z = 0;
1220 pExpr->token.n = 0;
1221 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001222 }else{
drh22f70c32002-02-18 01:17:00 +00001223 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001224 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001225 }
drhd70dc522005-06-06 16:34:33 +00001226 if( longNames ){
1227 pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span);
1228 }else{
1229 pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
1230 }
drh7c917d12001-12-16 20:05:05 +00001231 }
drh17e24df2001-11-06 14:10:41 +00001232 }
drh54473222002-04-04 02:10:55 +00001233 if( !tableSeen ){
drhcf55b7a2004-07-20 01:45:19 +00001234 if( zTName ){
1235 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
drhf5db2d32002-06-06 23:42:27 +00001236 }else{
danielk19774adee202004-05-08 08:23:19 +00001237 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001238 }
drh54473222002-04-04 02:10:55 +00001239 rc = 1;
1240 }
drhcf55b7a2004-07-20 01:45:19 +00001241 sqliteFree(zTName);
drhd8bc7082000-06-07 23:51:50 +00001242 }
1243 }
danielk19774adee202004-05-08 08:23:19 +00001244 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001245 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001246 }
drh54473222002-04-04 02:10:55 +00001247 return rc;
drhd8bc7082000-06-07 23:51:50 +00001248}
1249
danielk197793758c82005-01-21 08:13:14 +00001250#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhff78bd22002-02-27 01:47:11 +00001251/*
drhd8bc7082000-06-07 23:51:50 +00001252** This routine associates entries in an ORDER BY expression list with
1253** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001254** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001255** the top-level node is filled in with column number and the iTable
1256** value of the top-level node is filled with iTable parameter.
1257**
1258** If there are prior SELECT clauses, they are processed first. A match
1259** in an earlier SELECT takes precedence over a later SELECT.
1260**
1261** Any entry that does not match is flagged as an error. The number
1262** of errors is returned.
1263*/
1264static int matchOrderbyToColumn(
1265 Parse *pParse, /* A place to leave error messages */
1266 Select *pSelect, /* Match to result columns of this SELECT */
1267 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001268 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001269 int mustComplete /* If TRUE all ORDER BYs must match */
1270){
1271 int nErr = 0;
1272 int i, j;
1273 ExprList *pEList;
1274
drhdaffd0e2001-04-11 14:28:42 +00001275 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001276 if( mustComplete ){
1277 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1278 }
drh9b3187e2005-01-18 14:45:47 +00001279 if( prepSelectStmt(pParse, pSelect) ){
drhd8bc7082000-06-07 23:51:50 +00001280 return 1;
1281 }
1282 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001283 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1284 return 1;
1285 }
drhd8bc7082000-06-07 23:51:50 +00001286 }
1287 pEList = pSelect->pEList;
1288 for(i=0; i<pOrderBy->nExpr; i++){
1289 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001290 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001291 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001292 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001293 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001294 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001295 "ORDER BY position %d should be between 1 and %d",
1296 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001297 nErr++;
1298 break;
1299 }
drhfcb78a42003-01-18 20:11:05 +00001300 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001301 iCol--;
1302 }
1303 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001304 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001305 char *zName, *zLabel;
1306 zName = pEList->a[j].zName;
drha99db3b2004-06-19 14:49:12 +00001307 zLabel = sqlite3NameFromToken(&pE->token);
1308 assert( zLabel!=0 );
danielk19774adee202004-05-08 08:23:19 +00001309 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001310 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001311 }
drh6e142f52000-06-08 13:36:40 +00001312 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001313 }
danielk19774adee202004-05-08 08:23:19 +00001314 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001315 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001316 }
1317 }
drhe4de1fe2002-06-02 16:09:01 +00001318 if( iCol>=0 ){
1319 pE->op = TK_COLUMN;
1320 pE->iColumn = iCol;
1321 pE->iTable = iTable;
danielk1977a58fdfb2005-02-08 07:50:40 +00001322 pE->iAgg = -1;
drhe4de1fe2002-06-02 16:09:01 +00001323 pOrderBy->a[i].done = 1;
1324 }
1325 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001326 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001327 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001328 nErr++;
1329 break;
1330 }
1331 }
1332 return nErr;
1333}
danielk197793758c82005-01-21 08:13:14 +00001334#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +00001335
1336/*
1337** Get a VDBE for the given parser context. Create a new one if necessary.
1338** If an error occurs, return NULL and leave a message in pParse.
1339*/
danielk19774adee202004-05-08 08:23:19 +00001340Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001341 Vdbe *v = pParse->pVdbe;
1342 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001343 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001344 }
drhd8bc7082000-06-07 23:51:50 +00001345 return v;
1346}
drhfcb78a42003-01-18 20:11:05 +00001347
drhd8bc7082000-06-07 23:51:50 +00001348/*
drh7b58dae2003-07-20 01:16:46 +00001349** Compute the iLimit and iOffset fields of the SELECT based on the
drhec7429a2005-10-06 16:53:14 +00001350** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
drh7b58dae2003-07-20 01:16:46 +00001351** that appear in the original SQL statement after the LIMIT and OFFSET
danielk1977a2dc3b12005-02-05 12:48:48 +00001352** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
1353** are the integer memory register numbers for counters used to compute
1354** the limit and offset. If there is no limit and/or offset, then
1355** iLimit and iOffset are negative.
drh7b58dae2003-07-20 01:16:46 +00001356**
1357** This routine changes the values if iLimit and iOffset only if
drhec7429a2005-10-06 16:53:14 +00001358** a limit or offset is defined by pLimit and pOffset. iLimit and
drh7b58dae2003-07-20 01:16:46 +00001359** iOffset should have been preset to appropriate default values
1360** (usually but not always -1) prior to calling this routine.
drhec7429a2005-10-06 16:53:14 +00001361** Only if pLimit!=0 or pOffset!=0 do the limit registers get
drh7b58dae2003-07-20 01:16:46 +00001362** redefined. The UNION ALL operator uses this property to force
1363** the reuse of the same limit and offset registers across multiple
1364** SELECT statements.
1365*/
drhec7429a2005-10-06 16:53:14 +00001366static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
drh7b58dae2003-07-20 01:16:46 +00001367 /*
drh7b58dae2003-07-20 01:16:46 +00001368 ** "LIMIT -1" always shows all rows. There is some
1369 ** contraversy about what the correct behavior should be.
1370 ** The current implementation interprets "LIMIT 0" to mean
1371 ** no rows.
1372 */
danielk1977a2dc3b12005-02-05 12:48:48 +00001373 if( p->pLimit ){
drh7b58dae2003-07-20 01:16:46 +00001374 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001375 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001376 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001377 sqlite3ExprCode(pParse, p->pLimit);
1378 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1379 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001380 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001381 VdbeComment((v, "# LIMIT counter"));
drhec7429a2005-10-06 16:53:14 +00001382 sqlite3VdbeAddOp(v, OP_IfMemZero, iMem, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001383 p->iLimit = iMem;
1384 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001385 if( p->pOffset ){
drh7b58dae2003-07-20 01:16:46 +00001386 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001387 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001388 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001389 sqlite3ExprCode(pParse, p->pOffset);
1390 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1391 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001392 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001393 VdbeComment((v, "# OFFSET counter"));
drh7b58dae2003-07-20 01:16:46 +00001394 p->iOffset = iMem;
1395 }
1396}
1397
1398/*
drh0342b1f2005-09-01 03:07:44 +00001399** Allocate a virtual index to use for sorting.
drhd3d39e92004-05-20 22:16:29 +00001400*/
drh4db38a72005-09-01 12:16:28 +00001401static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
drh0342b1f2005-09-01 03:07:44 +00001402 if( pOrderBy ){
1403 int addr;
drh9d2985c2005-09-08 01:58:42 +00001404 assert( pOrderBy->iECursor==0 );
1405 pOrderBy->iECursor = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001406 addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenVirtual,
drh9d2985c2005-09-08 01:58:42 +00001407 pOrderBy->iECursor, pOrderBy->nExpr+1);
drh0342b1f2005-09-01 03:07:44 +00001408 assert( p->addrOpenVirt[2] == -1 );
1409 p->addrOpenVirt[2] = addr;
drh736c22b2004-05-21 02:14:24 +00001410 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001411}
1412
drh13449892005-09-07 21:22:45 +00001413/*
1414** The opcode at addr is an OP_OpenVirtual that created a sorting
1415** index tha we ended up not needing. This routine changes that
1416** opcode to OP_Noop.
1417*/
1418static void uncreateSortingIndex(Parse *pParse, int addr){
1419 Vdbe *v = pParse->pVdbe;
1420 VdbeOp *pOp = sqlite3VdbeGetOp(v, addr);
1421 sqlite3VdbeChangeP3(v, addr, 0, 0);
1422 pOp->opcode = OP_Noop;
1423 pOp->p1 = 0;
1424 pOp->p2 = 0;
1425}
1426
drhb7f91642004-10-31 02:22:47 +00001427#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001428/*
drhfbc4ee72004-08-29 01:31:05 +00001429** Return the appropriate collating sequence for the iCol-th column of
1430** the result set for the compound-select statement "p". Return NULL if
1431** the column has no default collating sequence.
1432**
1433** The collating sequence for the compound select is taken from the
1434** left-most term of the select that has a collating sequence.
1435*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001436static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
drhfbc4ee72004-08-29 01:31:05 +00001437 CollSeq *pRet;
danielk1977dc1bdc42004-06-11 10:51:27 +00001438 if( p->pPrior ){
1439 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
drhfbc4ee72004-08-29 01:31:05 +00001440 }else{
1441 pRet = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001442 }
drhfbc4ee72004-08-29 01:31:05 +00001443 if( pRet==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001444 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1445 }
1446 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001447}
drhb7f91642004-10-31 02:22:47 +00001448#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd3d39e92004-05-20 22:16:29 +00001449
drhb7f91642004-10-31 02:22:47 +00001450#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhd3d39e92004-05-20 22:16:29 +00001451/*
drh82c3d632000-06-06 21:56:07 +00001452** This routine is called to process a query that is really the union
1453** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001454**
drhe78e8282003-01-19 03:59:45 +00001455** "p" points to the right-most of the two queries. the query on the
1456** left is p->pPrior. The left query could also be a compound query
1457** in which case this routine will be called recursively.
1458**
1459** The results of the total query are to be written into a destination
1460** of type eDest with parameter iParm.
1461**
1462** Example 1: Consider a three-way compound SQL statement.
1463**
1464** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1465**
1466** This statement is parsed up as follows:
1467**
1468** SELECT c FROM t3
1469** |
1470** `-----> SELECT b FROM t2
1471** |
jplyon4b11c6d2004-01-19 04:57:53 +00001472** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001473**
1474** The arrows in the diagram above represent the Select.pPrior pointer.
1475** So if this routine is called with p equal to the t3 query, then
1476** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1477**
1478** Notice that because of the way SQLite parses compound SELECTs, the
1479** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001480*/
danielk197784ac9d02004-05-18 09:58:06 +00001481static int multiSelect(
drhfbc4ee72004-08-29 01:31:05 +00001482 Parse *pParse, /* Parsing context */
1483 Select *p, /* The right-most of SELECTs to be coded */
1484 int eDest, /* \___ Store query results as specified */
1485 int iParm, /* / by these two parameters. */
1486 char *aff /* If eDest is SRT_Union, the affinity string */
danielk197784ac9d02004-05-18 09:58:06 +00001487){
drhfbc4ee72004-08-29 01:31:05 +00001488 int rc = SQLITE_OK; /* Success code from a subroutine */
1489 Select *pPrior; /* Another SELECT immediately to our left */
1490 Vdbe *v; /* Generate code to this VDBE */
drh8cdbf832004-08-29 16:25:03 +00001491 int nCol; /* Number of columns in the result set */
drh0342b1f2005-09-01 03:07:44 +00001492 ExprList *pOrderBy; /* The ORDER BY clause on p */
1493 int aSetP2[2]; /* Set P2 value of these op to number of columns */
1494 int nSetP2 = 0; /* Number of slots in aSetP2[] used */
drh82c3d632000-06-06 21:56:07 +00001495
drh7b58dae2003-07-20 01:16:46 +00001496 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
drhfbc4ee72004-08-29 01:31:05 +00001497 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001498 */
danielk197784ac9d02004-05-18 09:58:06 +00001499 if( p==0 || p->pPrior==0 ){
1500 rc = 1;
1501 goto multi_select_end;
1502 }
drhd8bc7082000-06-07 23:51:50 +00001503 pPrior = p->pPrior;
drh0342b1f2005-09-01 03:07:44 +00001504 assert( pPrior->pRightmost!=pPrior );
1505 assert( pPrior->pRightmost==p->pRightmost );
drhd8bc7082000-06-07 23:51:50 +00001506 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001507 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001508 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001509 rc = 1;
1510 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001511 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001512 if( pPrior->pLimit ){
danielk19774adee202004-05-08 08:23:19 +00001513 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001514 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001515 rc = 1;
1516 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001517 }
drh82c3d632000-06-06 21:56:07 +00001518
drhd8bc7082000-06-07 23:51:50 +00001519 /* Make sure we have a valid query engine. If not, create a new one.
1520 */
danielk19774adee202004-05-08 08:23:19 +00001521 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001522 if( v==0 ){
1523 rc = 1;
1524 goto multi_select_end;
1525 }
drhd8bc7082000-06-07 23:51:50 +00001526
drh1cc3d752002-03-23 00:31:29 +00001527 /* Create the destination temporary table if necessary
1528 */
drh9d2985c2005-09-08 01:58:42 +00001529 if( eDest==SRT_VirtualTab ){
danielk1977b4964b72004-05-18 01:23:38 +00001530 assert( p->pEList );
drh0342b1f2005-09-01 03:07:44 +00001531 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1532 aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 0);
drh1cc3d752002-03-23 00:31:29 +00001533 eDest = SRT_Table;
1534 }
1535
drhf46f9052002-06-22 02:33:38 +00001536 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001537 */
drh0342b1f2005-09-01 03:07:44 +00001538 pOrderBy = p->pOrderBy;
drh82c3d632000-06-06 21:56:07 +00001539 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001540 case TK_ALL: {
drh0342b1f2005-09-01 03:07:44 +00001541 if( pOrderBy==0 ){
drhec7429a2005-10-06 16:53:14 +00001542 int addr = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001543 assert( !pPrior->pLimit );
1544 pPrior->pLimit = p->pLimit;
1545 pPrior->pOffset = p->pOffset;
danielk1977b3bce662005-01-29 08:32:43 +00001546 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001547 if( rc ){
1548 goto multi_select_end;
1549 }
drhf46f9052002-06-22 02:33:38 +00001550 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001551 p->iLimit = pPrior->iLimit;
1552 p->iOffset = pPrior->iOffset;
danielk1977a2dc3b12005-02-05 12:48:48 +00001553 p->pLimit = 0;
1554 p->pOffset = 0;
drhec7429a2005-10-06 16:53:14 +00001555 if( p->iLimit>=0 ){
1556 addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0);
1557 VdbeComment((v, "# Jump ahead if LIMIT reached"));
1558 }
danielk1977b3bce662005-01-29 08:32:43 +00001559 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001560 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001561 if( rc ){
1562 goto multi_select_end;
1563 }
drhec7429a2005-10-06 16:53:14 +00001564 if( addr ){
1565 sqlite3VdbeJumpHere(v, addr);
1566 }
drhf46f9052002-06-22 02:33:38 +00001567 break;
1568 }
1569 /* For UNION ALL ... ORDER BY fall through to the next case */
1570 }
drh82c3d632000-06-06 21:56:07 +00001571 case TK_EXCEPT:
1572 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001573 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001574 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001575 int priorOp; /* The SRT_ operation to apply to prior selects */
danielk1977a2dc3b12005-02-05 12:48:48 +00001576 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
danielk1977dc1bdc42004-06-11 10:51:27 +00001577 int addr;
drh82c3d632000-06-06 21:56:07 +00001578
drhd8bc7082000-06-07 23:51:50 +00001579 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh0342b1f2005-09-01 03:07:44 +00001580 if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
drhd8bc7082000-06-07 23:51:50 +00001581 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001582 ** right.
drhd8bc7082000-06-07 23:51:50 +00001583 */
drh82c3d632000-06-06 21:56:07 +00001584 unionTab = iParm;
1585 }else{
drhd8bc7082000-06-07 23:51:50 +00001586 /* We will need to create our own temporary table to hold the
1587 ** intermediate results.
1588 */
1589 unionTab = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001590 if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001591 rc = 1;
1592 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001593 }
drh9170dd72005-07-08 17:13:46 +00001594 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, unionTab, 0);
drh0342b1f2005-09-01 03:07:44 +00001595 if( priorOp==SRT_Table ){
1596 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1597 aSetP2[nSetP2++] = addr;
1598 }else{
1599 assert( p->addrOpenVirt[0] == -1 );
1600 p->addrOpenVirt[0] = addr;
1601 p->pRightmost->usesVirt = 1;
drhd8bc7082000-06-07 23:51:50 +00001602 }
drh0342b1f2005-09-01 03:07:44 +00001603 createSortingIndex(pParse, p, pOrderBy);
danielk197784ac9d02004-05-18 09:58:06 +00001604 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001605 }
drhd8bc7082000-06-07 23:51:50 +00001606
1607 /* Code the SELECT statements to our left
1608 */
danielk1977b3bce662005-01-29 08:32:43 +00001609 assert( !pPrior->pOrderBy );
1610 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001611 if( rc ){
1612 goto multi_select_end;
1613 }
drhd8bc7082000-06-07 23:51:50 +00001614
1615 /* Code the current SELECT statement
1616 */
1617 switch( p->op ){
1618 case TK_EXCEPT: op = SRT_Except; break;
1619 case TK_UNION: op = SRT_Union; break;
1620 case TK_ALL: op = SRT_Table; break;
1621 }
drh82c3d632000-06-06 21:56:07 +00001622 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001623 p->pOrderBy = 0;
drh4b14b4d2005-09-19 17:35:53 +00001624 p->disallowOrderBy = pOrderBy!=0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001625 pLimit = p->pLimit;
1626 p->pLimit = 0;
1627 pOffset = p->pOffset;
1628 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001629 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001630 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001631 p->pOrderBy = pOrderBy;
danielk1977a2dc3b12005-02-05 12:48:48 +00001632 sqlite3ExprDelete(p->pLimit);
1633 p->pLimit = pLimit;
1634 p->pOffset = pOffset;
drhbe5fd492004-12-16 21:09:16 +00001635 p->iLimit = -1;
1636 p->iOffset = -1;
danielk197784ac9d02004-05-18 09:58:06 +00001637 if( rc ){
1638 goto multi_select_end;
1639 }
1640
drhd8bc7082000-06-07 23:51:50 +00001641
1642 /* Convert the data in the temporary table into whatever form
1643 ** it is that we currently need.
1644 */
drhc926afb2002-06-20 03:38:26 +00001645 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001646 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001647 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001648 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001649 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001650 }
danielk19774adee202004-05-08 08:23:19 +00001651 iBreak = sqlite3VdbeMakeLabel(v);
1652 iCont = sqlite3VdbeMakeLabel(v);
drhec7429a2005-10-06 16:53:14 +00001653 computeLimitRegisters(pParse, p, iBreak);
danielk19774adee202004-05-08 08:23:19 +00001654 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
danielk19774adee202004-05-08 08:23:19 +00001655 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001656 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001657 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001658 iCont, iBreak, 0);
1659 if( rc ){
1660 rc = 1;
1661 goto multi_select_end;
1662 }
danielk19774adee202004-05-08 08:23:19 +00001663 sqlite3VdbeResolveLabel(v, iCont);
1664 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1665 sqlite3VdbeResolveLabel(v, iBreak);
1666 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001667 }
1668 break;
1669 }
1670 case TK_INTERSECT: {
1671 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001672 int iCont, iBreak, iStart;
danielk1977a2dc3b12005-02-05 12:48:48 +00001673 Expr *pLimit, *pOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001674 int addr;
drh82c3d632000-06-06 21:56:07 +00001675
drhd8bc7082000-06-07 23:51:50 +00001676 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001677 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001678 ** by allocating the tables we will need.
1679 */
drh82c3d632000-06-06 21:56:07 +00001680 tab1 = pParse->nTab++;
1681 tab2 = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001682 if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001683 rc = 1;
1684 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001685 }
drh0342b1f2005-09-01 03:07:44 +00001686 createSortingIndex(pParse, p, pOrderBy);
danielk1977dc1bdc42004-06-11 10:51:27 +00001687
drh9170dd72005-07-08 17:13:46 +00001688 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab1, 0);
drh0342b1f2005-09-01 03:07:44 +00001689 assert( p->addrOpenVirt[0] == -1 );
1690 p->addrOpenVirt[0] = addr;
1691 p->pRightmost->usesVirt = 1;
danielk197784ac9d02004-05-18 09:58:06 +00001692 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001693
1694 /* Code the SELECTs to our left into temporary table "tab1".
1695 */
danielk1977b3bce662005-01-29 08:32:43 +00001696 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001697 if( rc ){
1698 goto multi_select_end;
1699 }
drhd8bc7082000-06-07 23:51:50 +00001700
1701 /* Code the current SELECT into temporary table "tab2"
1702 */
drh9170dd72005-07-08 17:13:46 +00001703 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab2, 0);
drh0342b1f2005-09-01 03:07:44 +00001704 assert( p->addrOpenVirt[1] == -1 );
1705 p->addrOpenVirt[1] = addr;
drh82c3d632000-06-06 21:56:07 +00001706 p->pPrior = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001707 pLimit = p->pLimit;
1708 p->pLimit = 0;
1709 pOffset = p->pOffset;
1710 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001711 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001712 p->pPrior = pPrior;
danielk1977a2dc3b12005-02-05 12:48:48 +00001713 sqlite3ExprDelete(p->pLimit);
1714 p->pLimit = pLimit;
1715 p->pOffset = pOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001716 if( rc ){
1717 goto multi_select_end;
1718 }
drhd8bc7082000-06-07 23:51:50 +00001719
1720 /* Generate code to take the intersection of the two temporary
1721 ** tables.
1722 */
drh82c3d632000-06-06 21:56:07 +00001723 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001724 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001725 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001726 }
danielk19774adee202004-05-08 08:23:19 +00001727 iBreak = sqlite3VdbeMakeLabel(v);
1728 iCont = sqlite3VdbeMakeLabel(v);
drhec7429a2005-10-06 16:53:14 +00001729 computeLimitRegisters(pParse, p, iBreak);
danielk19774adee202004-05-08 08:23:19 +00001730 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh4a9f2412005-06-12 12:01:19 +00001731 iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
danielk19774adee202004-05-08 08:23:19 +00001732 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001733 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001734 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001735 iCont, iBreak, 0);
1736 if( rc ){
1737 rc = 1;
1738 goto multi_select_end;
1739 }
danielk19774adee202004-05-08 08:23:19 +00001740 sqlite3VdbeResolveLabel(v, iCont);
1741 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1742 sqlite3VdbeResolveLabel(v, iBreak);
1743 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1744 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001745 break;
1746 }
1747 }
drh8cdbf832004-08-29 16:25:03 +00001748
1749 /* Make sure all SELECTs in the statement have the same number of elements
1750 ** in their result sets.
1751 */
drh82c3d632000-06-06 21:56:07 +00001752 assert( p->pEList && pPrior->pEList );
1753 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001754 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001755 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001756 rc = 1;
1757 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001758 }
danielk197784ac9d02004-05-18 09:58:06 +00001759
drh8cdbf832004-08-29 16:25:03 +00001760 /* Set the number of columns in temporary tables
1761 */
1762 nCol = p->pEList->nExpr;
drh0342b1f2005-09-01 03:07:44 +00001763 while( nSetP2 ){
1764 sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
drh8cdbf832004-08-29 16:25:03 +00001765 }
1766
drhfbc4ee72004-08-29 01:31:05 +00001767 /* Compute collating sequences used by either the ORDER BY clause or
1768 ** by any temporary tables needed to implement the compound select.
1769 ** Attach the KeyInfo structure to all temporary tables. Invoke the
1770 ** ORDER BY processing if there is an ORDER BY clause.
drh8cdbf832004-08-29 16:25:03 +00001771 **
1772 ** This section is run by the right-most SELECT statement only.
1773 ** SELECT statements to the left always skip this part. The right-most
1774 ** SELECT might also skip this part if it has no ORDER BY clause and
1775 ** no temp tables are required.
drhfbc4ee72004-08-29 01:31:05 +00001776 */
drh0342b1f2005-09-01 03:07:44 +00001777 if( pOrderBy || p->usesVirt ){
drhfbc4ee72004-08-29 01:31:05 +00001778 int i; /* Loop counter */
1779 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
drh0342b1f2005-09-01 03:07:44 +00001780 Select *pLoop; /* For looping through SELECT statements */
1781 CollSeq **apColl;
1782 CollSeq **aCopy;
drhfbc4ee72004-08-29 01:31:05 +00001783
drh0342b1f2005-09-01 03:07:44 +00001784 assert( p->pRightmost==p );
drh4db38a72005-09-01 12:16:28 +00001785 pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*2*sizeof(CollSeq*) + nCol);
danielk1977dc1bdc42004-06-11 10:51:27 +00001786 if( !pKeyInfo ){
1787 rc = SQLITE_NOMEM;
1788 goto multi_select_end;
1789 }
1790
1791 pKeyInfo->enc = pParse->db->enc;
1792 pKeyInfo->nField = nCol;
1793
drh0342b1f2005-09-01 03:07:44 +00001794 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
1795 *apColl = multiSelectCollSeq(pParse, p, i);
1796 if( 0==*apColl ){
1797 *apColl = pParse->db->pDfltColl;
danielk1977dc1bdc42004-06-11 10:51:27 +00001798 }
1799 }
1800
drh0342b1f2005-09-01 03:07:44 +00001801 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
1802 for(i=0; i<2; i++){
1803 int addr = pLoop->addrOpenVirt[i];
1804 if( addr<0 ){
1805 /* If [0] is unused then [1] is also unused. So we can
1806 ** always safely abort as soon as the first unused slot is found */
1807 assert( pLoop->addrOpenVirt[1]<0 );
1808 break;
1809 }
1810 sqlite3VdbeChangeP2(v, addr, nCol);
1811 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
1812 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001813 }
1814
drh0342b1f2005-09-01 03:07:44 +00001815 if( pOrderBy ){
1816 struct ExprList_item *pOTerm = pOrderBy->a;
drh4efc0832005-11-16 13:47:50 +00001817 int nOrderByExpr = pOrderBy->nExpr;
drh0342b1f2005-09-01 03:07:44 +00001818 int addr;
drh4db38a72005-09-01 12:16:28 +00001819 u8 *pSortOrder;
drh0342b1f2005-09-01 03:07:44 +00001820
1821 aCopy = (CollSeq**)&pKeyInfo[1];
drh4efc0832005-11-16 13:47:50 +00001822 pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
drh0342b1f2005-09-01 03:07:44 +00001823 memcpy(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
1824 apColl = pKeyInfo->aColl;
drh4efc0832005-11-16 13:47:50 +00001825 for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
drh0342b1f2005-09-01 03:07:44 +00001826 Expr *pExpr = pOTerm->pExpr;
1827 char *zName = pOTerm->zName;
danielk1977dc1bdc42004-06-11 10:51:27 +00001828 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
danielk1977dc1bdc42004-06-11 10:51:27 +00001829 if( zName ){
drh0342b1f2005-09-01 03:07:44 +00001830 *apColl = sqlite3LocateCollSeq(pParse, zName, -1);
danielk1977dc1bdc42004-06-11 10:51:27 +00001831 }else{
drh0342b1f2005-09-01 03:07:44 +00001832 *apColl = aCopy[pExpr->iColumn];
danielk1977dc1bdc42004-06-11 10:51:27 +00001833 }
drh4db38a72005-09-01 12:16:28 +00001834 *pSortOrder = pOTerm->sortOrder;
danielk1977dc1bdc42004-06-11 10:51:27 +00001835 }
drh0342b1f2005-09-01 03:07:44 +00001836 assert( p->pRightmost==p );
1837 assert( p->addrOpenVirt[2]>=0 );
1838 addr = p->addrOpenVirt[2];
drh4db38a72005-09-01 12:16:28 +00001839 sqlite3VdbeChangeP2(v, addr, p->pEList->nExpr+2);
drh4efc0832005-11-16 13:47:50 +00001840 pKeyInfo->nField = nOrderByExpr;
drh4db38a72005-09-01 12:16:28 +00001841 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
1842 pKeyInfo = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001843 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1844 }
1845
drh0342b1f2005-09-01 03:07:44 +00001846 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001847 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001848
1849multi_select_end:
danielk197784ac9d02004-05-18 09:58:06 +00001850 return rc;
drh22827922000-06-06 17:27:05 +00001851}
drhb7f91642004-10-31 02:22:47 +00001852#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drh22827922000-06-06 17:27:05 +00001853
drhb7f91642004-10-31 02:22:47 +00001854#ifndef SQLITE_OMIT_VIEW
drh22827922000-06-06 17:27:05 +00001855/*
drh832508b2002-03-02 17:04:07 +00001856** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001857** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001858** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001859** unchanged.)
drh832508b2002-03-02 17:04:07 +00001860**
1861** This routine is part of the flattening procedure. A subquery
1862** whose result set is defined by pEList appears as entry in the
1863** FROM clause of a SELECT such that the VDBE cursor assigned to that
1864** FORM clause entry is iTable. This routine make the necessary
1865** changes to pExpr so that it refers directly to the source table
1866** of the subquery rather the result set of the subquery.
1867*/
drh6a3ea0e2003-05-02 14:32:12 +00001868static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
danielk1977b3bce662005-01-29 08:32:43 +00001869static void substSelect(Select *, int, ExprList *); /* Forward Decl */
drh6a3ea0e2003-05-02 14:32:12 +00001870static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001871 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001872 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1873 if( pExpr->iColumn<0 ){
1874 pExpr->op = TK_NULL;
1875 }else{
1876 Expr *pNew;
1877 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1878 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1879 pNew = pEList->a[pExpr->iColumn].pExpr;
1880 assert( pNew!=0 );
1881 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001882 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001883 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001884 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001885 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001886 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001887 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001888 pExpr->iTable = pNew->iTable;
1889 pExpr->iColumn = pNew->iColumn;
1890 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001891 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1892 sqlite3TokenCopy(&pExpr->span, &pNew->span);
danielk1977a1cb1832005-02-12 08:59:55 +00001893 pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
1894 pExpr->flags = pNew->flags;
drh50350a12004-02-13 16:22:22 +00001895 }
drh832508b2002-03-02 17:04:07 +00001896 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001897 substExpr(pExpr->pLeft, iTable, pEList);
1898 substExpr(pExpr->pRight, iTable, pEList);
danielk1977b3bce662005-01-29 08:32:43 +00001899 substSelect(pExpr->pSelect, iTable, pEList);
drh6a3ea0e2003-05-02 14:32:12 +00001900 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001901 }
1902}
danielk1977b3bce662005-01-29 08:32:43 +00001903static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001904 int i;
1905 if( pList==0 ) return;
1906 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001907 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001908 }
1909}
danielk1977b3bce662005-01-29 08:32:43 +00001910static void substSelect(Select *p, int iTable, ExprList *pEList){
1911 if( !p ) return;
1912 substExprList(p->pEList, iTable, pEList);
1913 substExprList(p->pGroupBy, iTable, pEList);
1914 substExprList(p->pOrderBy, iTable, pEList);
1915 substExpr(p->pHaving, iTable, pEList);
1916 substExpr(p->pWhere, iTable, pEList);
1917}
drhb7f91642004-10-31 02:22:47 +00001918#endif /* !defined(SQLITE_OMIT_VIEW) */
drh832508b2002-03-02 17:04:07 +00001919
drhb7f91642004-10-31 02:22:47 +00001920#ifndef SQLITE_OMIT_VIEW
drh832508b2002-03-02 17:04:07 +00001921/*
drh1350b032002-02-27 19:00:20 +00001922** This routine attempts to flatten subqueries in order to speed
1923** execution. It returns 1 if it makes changes and 0 if no flattening
1924** occurs.
1925**
1926** To understand the concept of flattening, consider the following
1927** query:
1928**
1929** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1930**
1931** The default way of implementing this query is to execute the
1932** subquery first and store the results in a temporary table, then
1933** run the outer query on that temporary table. This requires two
1934** passes over the data. Furthermore, because the temporary table
1935** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001936** optimized.
drh1350b032002-02-27 19:00:20 +00001937**
drh832508b2002-03-02 17:04:07 +00001938** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001939** a single flat select, like this:
1940**
1941** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1942**
1943** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001944** but only has to scan the data once. And because indices might
1945** exist on the table t1, a complete scan of the data might be
1946** avoided.
drh1350b032002-02-27 19:00:20 +00001947**
drh832508b2002-03-02 17:04:07 +00001948** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001949**
drh832508b2002-03-02 17:04:07 +00001950** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001951**
drh832508b2002-03-02 17:04:07 +00001952** (2) The subquery is not an aggregate or the outer query is not a join.
1953**
drh8af4d3a2003-05-06 20:35:16 +00001954** (3) The subquery is not the right operand of a left outer join, or
1955** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001956**
1957** (4) The subquery is not DISTINCT or the outer query is not a join.
1958**
1959** (5) The subquery is not DISTINCT or the outer query does not use
1960** aggregates.
1961**
1962** (6) The subquery does not use aggregates or the outer query is not
1963** DISTINCT.
1964**
drh08192d52002-04-30 19:20:28 +00001965** (7) The subquery has a FROM clause.
1966**
drhdf199a22002-06-14 22:38:41 +00001967** (8) The subquery does not use LIMIT or the outer query is not a join.
1968**
1969** (9) The subquery does not use LIMIT or the outer query does not use
1970** aggregates.
1971**
1972** (10) The subquery does not use aggregates or the outer query does not
1973** use LIMIT.
1974**
drh174b6192002-12-03 02:22:52 +00001975** (11) The subquery and the outer query do not both have ORDER BY clauses.
1976**
drh3fc673e2003-06-16 00:40:34 +00001977** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1978** subquery has no WHERE clause. (added by ticket #350)
1979**
drh832508b2002-03-02 17:04:07 +00001980** In this routine, the "p" parameter is a pointer to the outer query.
1981** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1982** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1983**
drh665de472003-03-31 13:36:09 +00001984** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001985** If flattening is attempted this routine returns 1.
1986**
1987** All of the expression analysis must occur on both the outer query and
1988** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001989*/
drh8c74a8c2002-08-25 19:20:40 +00001990static int flattenSubquery(
1991 Parse *pParse, /* The parsing context */
1992 Select *p, /* The parent or outer SELECT statement */
1993 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1994 int isAgg, /* True if outer SELECT uses aggregate functions */
1995 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1996){
drh0bb28102002-05-08 11:54:14 +00001997 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001998 SrcList *pSrc; /* The FROM clause of the outer query */
1999 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00002000 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00002001 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh91bb0ee2004-09-01 03:06:34 +00002002 int i; /* Loop counter */
2003 Expr *pWhere; /* The WHERE clause */
2004 struct SrcList_item *pSubitem; /* The subquery */
drh1350b032002-02-27 19:00:20 +00002005
drh832508b2002-03-02 17:04:07 +00002006 /* Check to see if flattening is permitted. Return 0 if not.
2007 */
2008 if( p==0 ) return 0;
2009 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00002010 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh91bb0ee2004-09-01 03:06:34 +00002011 pSubitem = &pSrc->a[iFrom];
2012 pSub = pSubitem->pSelect;
drh832508b2002-03-02 17:04:07 +00002013 assert( pSub!=0 );
2014 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00002015 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00002016 pSubSrc = pSub->pSrc;
2017 assert( pSubSrc );
danielk1977a2dc3b12005-02-05 12:48:48 +00002018 if( (pSub->pLimit && p->pLimit) || pSub->pOffset ||
2019 (pSub->pLimit && isAgg) ) return 0;
drhc31c2eb2003-05-02 16:04:17 +00002020 if( pSubSrc->nSrc==0 ) return 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00002021 if( pSub->isDistinct && (pSrc->nSrc>1 || isAgg) ){
drhdf199a22002-06-14 22:38:41 +00002022 return 0;
2023 }
danielk1977a2dc3b12005-02-05 12:48:48 +00002024 if( p->isDistinct && subqueryIsAgg ) return 0;
drh4b14b4d2005-09-19 17:35:53 +00002025 if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00002026
drh8af4d3a2003-05-06 20:35:16 +00002027 /* Restriction 3: If the subquery is a join, make sure the subquery is
2028 ** not used as the right operand of an outer join. Examples of why this
2029 ** is not allowed:
2030 **
2031 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
2032 **
2033 ** If we flatten the above, we would get
2034 **
2035 ** (t1 LEFT OUTER JOIN t2) JOIN t3
2036 **
2037 ** which is not at all the same thing.
2038 */
2039 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
2040 return 0;
2041 }
2042
drh3fc673e2003-06-16 00:40:34 +00002043 /* Restriction 12: If the subquery is the right operand of a left outer
2044 ** join, make sure the subquery has no WHERE clause.
2045 ** An examples of why this is not allowed:
2046 **
2047 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
2048 **
2049 ** If we flatten the above, we would get
2050 **
2051 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
2052 **
2053 ** But the t2.x>0 test will always fail on a NULL row of t2, which
2054 ** effectively converts the OUTER JOIN into an INNER JOIN.
2055 */
2056 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
2057 && pSub->pWhere!=0 ){
2058 return 0;
2059 }
2060
drh0bb28102002-05-08 11:54:14 +00002061 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00002062 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00002063 */
drhc31c2eb2003-05-02 16:04:17 +00002064
2065 /* Move all of the FROM elements of the subquery into the
2066 ** the FROM clause of the outer query. Before doing this, remember
2067 ** the cursor number for the original outer query FROM element in
2068 ** iParent. The iParent cursor will never be used. Subsequent code
2069 ** will scan expressions looking for iParent references and replace
2070 ** those references with expressions that resolve to the subquery FROM
2071 ** elements we are now copying in.
2072 */
drh91bb0ee2004-09-01 03:06:34 +00002073 iParent = pSubitem->iCursor;
drhc31c2eb2003-05-02 16:04:17 +00002074 {
2075 int nSubSrc = pSubSrc->nSrc;
drh91bb0ee2004-09-01 03:06:34 +00002076 int jointype = pSubitem->jointype;
drhc31c2eb2003-05-02 16:04:17 +00002077
drhed8a3bb2005-06-06 21:19:56 +00002078 sqlite3DeleteTable(0, pSubitem->pTab);
drh91bb0ee2004-09-01 03:06:34 +00002079 sqliteFree(pSubitem->zDatabase);
2080 sqliteFree(pSubitem->zName);
2081 sqliteFree(pSubitem->zAlias);
drhc31c2eb2003-05-02 16:04:17 +00002082 if( nSubSrc>1 ){
2083 int extra = nSubSrc - 1;
2084 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00002085 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00002086 }
2087 p->pSrc = pSrc;
2088 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2089 pSrc->a[i] = pSrc->a[i-extra];
2090 }
2091 }
2092 for(i=0; i<nSubSrc; i++){
2093 pSrc->a[i+iFrom] = pSubSrc->a[i];
2094 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2095 }
drh8af4d3a2003-05-06 20:35:16 +00002096 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00002097 }
2098
2099 /* Now begin substituting subquery result set expressions for
2100 ** references to the iParent in the outer query.
2101 **
2102 ** Example:
2103 **
2104 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2105 ** \ \_____________ subquery __________/ /
2106 ** \_____________________ outer query ______________________________/
2107 **
2108 ** We look at every expression in the outer query and every place we see
2109 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2110 */
drh6a3ea0e2003-05-02 14:32:12 +00002111 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00002112 pList = p->pEList;
2113 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00002114 Expr *pExpr;
2115 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
2116 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00002117 }
2118 }
drh1b2e0322002-03-03 02:49:51 +00002119 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00002120 substExprList(p->pGroupBy, iParent, pSub->pEList);
2121 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00002122 }
drh174b6192002-12-03 02:22:52 +00002123 if( pSub->pOrderBy ){
2124 assert( p->pOrderBy==0 );
2125 p->pOrderBy = pSub->pOrderBy;
2126 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00002127 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00002128 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00002129 }
drh832508b2002-03-02 17:04:07 +00002130 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002131 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00002132 }else{
2133 pWhere = 0;
2134 }
2135 if( subqueryIsAgg ){
2136 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00002137 p->pHaving = p->pWhere;
2138 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00002139 substExpr(p->pHaving, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002140 p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
drh1b2e0322002-03-03 02:49:51 +00002141 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00002142 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00002143 }else{
drh6a3ea0e2003-05-02 14:32:12 +00002144 substExpr(p->pWhere, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002145 p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
drh832508b2002-03-02 17:04:07 +00002146 }
drhc31c2eb2003-05-02 16:04:17 +00002147
2148 /* The flattened query is distinct if either the inner or the
2149 ** outer query is distinct.
2150 */
drh832508b2002-03-02 17:04:07 +00002151 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00002152
danielk1977a58fdfb2005-02-08 07:50:40 +00002153 /*
2154 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2155 */
danielk1977a2dc3b12005-02-05 12:48:48 +00002156 if( pSub->pLimit ){
2157 p->pLimit = pSub->pLimit;
2158 pSub->pLimit = 0;
drhdf199a22002-06-14 22:38:41 +00002159 }
drh8c74a8c2002-08-25 19:20:40 +00002160
drhc31c2eb2003-05-02 16:04:17 +00002161 /* Finially, delete what is left of the subquery and return
2162 ** success.
2163 */
danielk19774adee202004-05-08 08:23:19 +00002164 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00002165 return 1;
2166}
drhb7f91642004-10-31 02:22:47 +00002167#endif /* SQLITE_OMIT_VIEW */
drh1350b032002-02-27 19:00:20 +00002168
2169/*
drh9562b552002-02-19 15:00:07 +00002170** Analyze the SELECT statement passed in as an argument to see if it
2171** is a simple min() or max() query. If it is and this query can be
2172** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00002173** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00002174** simple min() or max() query, then return 0;
2175**
2176** A simply min() or max() query looks like this:
2177**
2178** SELECT min(a) FROM table;
2179** SELECT max(a) FROM table;
2180**
2181** The query may have only a single table in its FROM argument. There
2182** can be no GROUP BY or HAVING or WHERE clauses. The result set must
2183** be the min() or max() of a single column of the table. The column
2184** in the min() or max() function must be indexed.
2185**
danielk19774adee202004-05-08 08:23:19 +00002186** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00002187** See the header comment on that routine for additional information.
2188*/
2189static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2190 Expr *pExpr;
2191 int iCol;
2192 Table *pTab;
2193 Index *pIdx;
2194 int base;
2195 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00002196 int seekOp;
drh6e175292004-03-13 14:00:36 +00002197 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00002198 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00002199 SrcList *pSrc;
drhec7429a2005-10-06 16:53:14 +00002200 int brk;
drh9562b552002-02-19 15:00:07 +00002201
2202 /* Check to see if this query is a simple min() or max() query. Return
2203 ** zero if it is not.
2204 */
2205 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00002206 pSrc = p->pSrc;
2207 if( pSrc->nSrc!=1 ) return 0;
2208 pEList = p->pEList;
2209 if( pEList->nExpr!=1 ) return 0;
2210 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002211 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002212 pList = pExpr->pList;
2213 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002214 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00002215 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002216 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00002217 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002218 seekOp = OP_Last;
2219 }else{
2220 return 0;
2221 }
drh6e175292004-03-13 14:00:36 +00002222 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002223 if( pExpr->op!=TK_COLUMN ) return 0;
2224 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002225 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002226
2227 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002228 ** Check to make sure we have an index and make pIdx point to the
2229 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2230 ** key column, no index is necessary so set pIdx to NULL. If no
2231 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002232 */
2233 if( iCol<0 ){
2234 pIdx = 0;
2235 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002236 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002237 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2238 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002239 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002240 }
2241 if( pIdx==0 ) return 0;
2242 }
2243
drhe5f50722003-07-19 00:44:14 +00002244 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002245 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002246 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002247 */
danielk19774adee202004-05-08 08:23:19 +00002248 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002249 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002250
drh0c37e632004-01-30 02:01:03 +00002251 /* If the output is destined for a temporary table, open that table.
2252 */
drh9d2985c2005-09-08 01:58:42 +00002253 if( eDest==SRT_VirtualTab ){
drhd81bd4e2005-09-05 20:06:49 +00002254 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002255 }
2256
drh17f71932002-02-21 12:01:27 +00002257 /* Generating code to find the min or the max. Basically all we have
2258 ** to do is find the first or the last entry in the chosen index. If
2259 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2260 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002261 */
danielk19774adee202004-05-08 08:23:19 +00002262 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00002263 base = pSrc->a[0].iCursor;
drhec7429a2005-10-06 16:53:14 +00002264 brk = sqlite3VdbeMakeLabel(v);
2265 computeLimitRegisters(pParse, p, brk);
drh6e175292004-03-13 14:00:36 +00002266 if( pSrc->a[0].pSelect==0 ){
drhad6d9462004-09-19 02:15:24 +00002267 sqlite3OpenTableForReading(v, base, pTab);
drh6e175292004-03-13 14:00:36 +00002268 }
drh9562b552002-02-19 15:00:07 +00002269 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002270 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002271 }else{
danielk19773719d7f2005-01-17 08:57:09 +00002272 /* Even though the cursor used to open the index here is closed
2273 ** as soon as a single value has been read from it, allocate it
2274 ** using (pParse->nTab++) to prevent the cursor id from being
2275 ** reused. This is important for statements of the form
2276 ** "INSERT INTO x SELECT max() FROM x".
2277 */
2278 int iIdx;
2279 iIdx = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +00002280 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002281 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
drhd3d39e92004-05-20 22:16:29 +00002282 (char*)&pIdx->keyInfo, P3_KEYINFO);
drh9eb516c2004-07-18 20:52:32 +00002283 if( seekOp==OP_Rewind ){
drhf0863fe2005-06-12 21:35:51 +00002284 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh1af3fdb2004-07-18 21:33:01 +00002285 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2286 seekOp = OP_MoveGt;
drh9eb516c2004-07-18 20:52:32 +00002287 }
danielk19773719d7f2005-01-17 08:57:09 +00002288 sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
drhf0863fe2005-06-12 21:35:51 +00002289 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002290 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002291 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002292 }
drh5cf8e8c2002-02-19 22:42:05 +00002293 eList.nExpr = 1;
2294 memset(&eListItem, 0, sizeof(eListItem));
2295 eList.a = &eListItem;
2296 eList.a[0].pExpr = pExpr;
drhec7429a2005-10-06 16:53:14 +00002297 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0);
2298 sqlite3VdbeResolveLabel(v, brk);
danielk19774adee202004-05-08 08:23:19 +00002299 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002300
drh9562b552002-02-19 15:00:07 +00002301 return 1;
2302}
2303
2304/*
drh290c1942004-08-21 17:54:45 +00002305** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
2306** the number of errors seen.
2307**
2308** An ORDER BY or GROUP BY is a list of expressions. If any expression
2309** is an integer constant, then that expression is replaced by the
2310** corresponding entry in the result set.
2311*/
2312static int processOrderGroupBy(
danielk1977b3bce662005-01-29 08:32:43 +00002313 NameContext *pNC, /* Name context of the SELECT statement. */
drh290c1942004-08-21 17:54:45 +00002314 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
drh290c1942004-08-21 17:54:45 +00002315 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
2316){
2317 int i;
danielk1977b3bce662005-01-29 08:32:43 +00002318 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */
2319 Parse *pParse = pNC->pParse; /* The result set of the SELECT */
2320 assert( pEList );
2321
drh290c1942004-08-21 17:54:45 +00002322 if( pOrderBy==0 ) return 0;
2323 for(i=0; i<pOrderBy->nExpr; i++){
2324 int iCol;
2325 Expr *pE = pOrderBy->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +00002326 if( sqlite3ExprIsInteger(pE, &iCol) ){
2327 if( iCol>0 && iCol<=pEList->nExpr ){
2328 sqlite3ExprDelete(pE);
2329 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2330 }else{
drh290c1942004-08-21 17:54:45 +00002331 sqlite3ErrorMsg(pParse,
2332 "%s BY column number %d out of range - should be "
2333 "between 1 and %d", zType, iCol, pEList->nExpr);
2334 return 1;
2335 }
2336 }
danielk1977b3bce662005-01-29 08:32:43 +00002337 if( sqlite3ExprResolveNames(pNC, pE) ){
2338 return 1;
2339 }
2340 if( sqlite3ExprIsConstant(pE) ){
2341 sqlite3ErrorMsg(pParse,
2342 "%s BY terms must not be non-integer constants", zType);
2343 return 1;
2344 }
drh290c1942004-08-21 17:54:45 +00002345 }
2346 return 0;
2347}
2348
2349/*
danielk1977b3bce662005-01-29 08:32:43 +00002350** This routine resolves any names used in the result set of the
2351** supplied SELECT statement. If the SELECT statement being resolved
2352** is a sub-select, then pOuterNC is a pointer to the NameContext
2353** of the parent SELECT.
2354*/
2355int sqlite3SelectResolve(
2356 Parse *pParse, /* The parser context */
2357 Select *p, /* The SELECT statement being coded. */
2358 NameContext *pOuterNC /* The outer name context. May be NULL. */
2359){
2360 ExprList *pEList; /* Result set. */
2361 int i; /* For-loop variable used in multiple places */
2362 NameContext sNC; /* Local name-context */
drh13449892005-09-07 21:22:45 +00002363 ExprList *pGroupBy; /* The group by clause */
danielk1977b3bce662005-01-29 08:32:43 +00002364
2365 /* If this routine has run before, return immediately. */
2366 if( p->isResolved ){
2367 assert( !pOuterNC );
2368 return SQLITE_OK;
2369 }
2370 p->isResolved = 1;
2371
2372 /* If there have already been errors, do nothing. */
2373 if( pParse->nErr>0 ){
2374 return SQLITE_ERROR;
2375 }
2376
2377 /* Prepare the select statement. This call will allocate all cursors
2378 ** required to handle the tables and subqueries in the FROM clause.
2379 */
2380 if( prepSelectStmt(pParse, p) ){
2381 return SQLITE_ERROR;
2382 }
2383
danielk1977a2dc3b12005-02-05 12:48:48 +00002384 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2385 ** are not allowed to refer to any names, so pass an empty NameContext.
2386 */
drhffe07b22005-11-03 00:41:17 +00002387 memset(&sNC, 0, sizeof(sNC));
danielk1977b3bce662005-01-29 08:32:43 +00002388 sNC.pParse = pParse;
danielk1977a2dc3b12005-02-05 12:48:48 +00002389 if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2390 sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2391 return SQLITE_ERROR;
2392 }
2393
2394 /* Set up the local name-context to pass to ExprResolveNames() to
2395 ** resolve the expression-list.
2396 */
2397 sNC.allowAgg = 1;
2398 sNC.pSrcList = p->pSrc;
2399 sNC.pNext = pOuterNC;
danielk1977b3bce662005-01-29 08:32:43 +00002400
danielk1977b3bce662005-01-29 08:32:43 +00002401 /* Resolve names in the result set. */
2402 pEList = p->pEList;
2403 if( !pEList ) return SQLITE_ERROR;
2404 for(i=0; i<pEList->nExpr; i++){
2405 Expr *pX = pEList->a[i].pExpr;
2406 if( sqlite3ExprResolveNames(&sNC, pX) ){
2407 return SQLITE_ERROR;
2408 }
2409 }
2410
2411 /* If there are no aggregate functions in the result-set, and no GROUP BY
2412 ** expression, do not allow aggregates in any of the other expressions.
2413 */
2414 assert( !p->isAgg );
drh13449892005-09-07 21:22:45 +00002415 pGroupBy = p->pGroupBy;
2416 if( pGroupBy || sNC.hasAgg ){
danielk1977b3bce662005-01-29 08:32:43 +00002417 p->isAgg = 1;
2418 }else{
2419 sNC.allowAgg = 0;
2420 }
2421
2422 /* If a HAVING clause is present, then there must be a GROUP BY clause.
2423 */
drh13449892005-09-07 21:22:45 +00002424 if( p->pHaving && !pGroupBy ){
danielk1977b3bce662005-01-29 08:32:43 +00002425 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2426 return SQLITE_ERROR;
2427 }
2428
2429 /* Add the expression list to the name-context before parsing the
2430 ** other expressions in the SELECT statement. This is so that
2431 ** expressions in the WHERE clause (etc.) can refer to expressions by
2432 ** aliases in the result set.
2433 **
2434 ** Minor point: If this is the case, then the expression will be
2435 ** re-evaluated for each reference to it.
2436 */
2437 sNC.pEList = p->pEList;
2438 if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2439 sqlite3ExprResolveNames(&sNC, p->pHaving) ||
2440 processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
drh13449892005-09-07 21:22:45 +00002441 processOrderGroupBy(&sNC, pGroupBy, "GROUP")
danielk1977b3bce662005-01-29 08:32:43 +00002442 ){
2443 return SQLITE_ERROR;
2444 }
2445
drh13449892005-09-07 21:22:45 +00002446 /* Make sure the GROUP BY clause does not contain aggregate functions.
2447 */
2448 if( pGroupBy ){
2449 struct ExprList_item *pItem;
2450
2451 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
2452 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
2453 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
2454 "the GROUP BY clause");
2455 return SQLITE_ERROR;
2456 }
2457 }
2458 }
2459
danielk1977b3bce662005-01-29 08:32:43 +00002460 return SQLITE_OK;
2461}
2462
2463/*
drh13449892005-09-07 21:22:45 +00002464** Reset the aggregate accumulator.
2465**
2466** The aggregate accumulator is a set of memory cells that hold
2467** intermediate results while calculating an aggregate. This
2468** routine simply stores NULLs in all of those memory cells.
danielk1977b3bce662005-01-29 08:32:43 +00002469*/
drh13449892005-09-07 21:22:45 +00002470static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
2471 Vdbe *v = pParse->pVdbe;
2472 int i;
drhc99130f2005-09-11 11:56:27 +00002473 struct AggInfo_func *pFunc;
drh13449892005-09-07 21:22:45 +00002474 if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
2475 return;
2476 }
drh13449892005-09-07 21:22:45 +00002477 for(i=0; i<pAggInfo->nColumn; i++){
drhd654be82005-09-20 17:42:23 +00002478 sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
drh13449892005-09-07 21:22:45 +00002479 }
drhc99130f2005-09-11 11:56:27 +00002480 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
drhd654be82005-09-20 17:42:23 +00002481 sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
drhc99130f2005-09-11 11:56:27 +00002482 if( pFunc->iDistinct>=0 ){
2483 Expr *pE = pFunc->pExpr;
2484 if( pE->pList==0 || pE->pList->nExpr!=1 ){
2485 sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
2486 "by an expression");
2487 pFunc->iDistinct = -1;
2488 }else{
2489 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
2490 sqlite3VdbeOp3(v, OP_OpenVirtual, pFunc->iDistinct, 0,
2491 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2492 }
2493 }
drh13449892005-09-07 21:22:45 +00002494 }
danielk1977b3bce662005-01-29 08:32:43 +00002495}
2496
2497/*
drh13449892005-09-07 21:22:45 +00002498** Invoke the OP_AggFinalize opcode for every aggregate function
2499** in the AggInfo structure.
danielk1977b3bce662005-01-29 08:32:43 +00002500*/
drh13449892005-09-07 21:22:45 +00002501static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
2502 Vdbe *v = pParse->pVdbe;
2503 int i;
2504 struct AggInfo_func *pF;
2505 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
drha10a34b2005-09-07 22:09:48 +00002506 ExprList *pList = pF->pExpr->pList;
2507 sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
2508 (void*)pF->pFunc, P3_FUNCDEF);
drh13449892005-09-07 21:22:45 +00002509 }
danielk1977b3bce662005-01-29 08:32:43 +00002510}
drh13449892005-09-07 21:22:45 +00002511
2512/*
2513** Update the accumulator memory cells for an aggregate based on
2514** the current cursor position.
2515*/
2516static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
2517 Vdbe *v = pParse->pVdbe;
2518 int i;
2519 struct AggInfo_func *pF;
2520 struct AggInfo_col *pC;
drh13449892005-09-07 21:22:45 +00002521
2522 pAggInfo->directMode = 1;
2523 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
2524 int nArg;
drhc99130f2005-09-11 11:56:27 +00002525 int addrNext = 0;
drh13449892005-09-07 21:22:45 +00002526 ExprList *pList = pF->pExpr->pList;
2527 if( pList ){
2528 nArg = pList->nExpr;
2529 sqlite3ExprCodeExprList(pParse, pList);
2530 }else{
2531 nArg = 0;
2532 }
drhc99130f2005-09-11 11:56:27 +00002533 if( pF->iDistinct>=0 ){
2534 addrNext = sqlite3VdbeMakeLabel(v);
2535 assert( nArg==1 );
drh9d4673a2005-09-12 23:03:16 +00002536 codeDistinct(v, pF->iDistinct, addrNext, 1, 2);
drhc99130f2005-09-11 11:56:27 +00002537 }
drh13449892005-09-07 21:22:45 +00002538 if( pF->pFunc->needCollSeq ){
2539 CollSeq *pColl = 0;
2540 struct ExprList_item *pItem;
2541 int j;
2542 for(j=0, pItem=pList->a; !pColl && j<pList->nExpr; j++, pItem++){
2543 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
2544 }
2545 if( !pColl ){
2546 pColl = pParse->db->pDfltColl;
2547 }
2548 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2549 }
2550 sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
drhc99130f2005-09-11 11:56:27 +00002551 if( addrNext ){
2552 sqlite3VdbeResolveLabel(v, addrNext);
2553 }
drh13449892005-09-07 21:22:45 +00002554 }
drh13449892005-09-07 21:22:45 +00002555 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
drh5774b802005-09-07 22:48:16 +00002556 sqlite3ExprCode(pParse, pC->pExpr);
drh13449892005-09-07 21:22:45 +00002557 sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
2558 }
2559 pAggInfo->directMode = 0;
2560}
2561
2562
danielk1977b3bce662005-01-29 08:32:43 +00002563/*
drh9bb61fe2000-06-05 16:01:39 +00002564** Generate code for the given SELECT statement.
2565**
drhfef52082000-06-06 01:50:43 +00002566** The results are distributed in various ways depending on the
2567** value of eDest and iParm.
2568**
2569** eDest Value Result
2570** ------------ -------------------------------------------
2571** SRT_Callback Invoke the callback for each row of the result.
2572**
2573** SRT_Mem Store first result in memory cell iParm
2574**
danielk1977e014a832004-05-17 10:48:57 +00002575** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002576**
drh82c3d632000-06-06 21:56:07 +00002577** SRT_Union Store results as a key in a temporary table iParm
2578**
jplyon4b11c6d2004-01-19 04:57:53 +00002579** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002580**
2581** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002582**
drhe78e8282003-01-19 03:59:45 +00002583** The table above is incomplete. Additional eDist value have be added
2584** since this comment was written. See the selectInnerLoop() function for
2585** a complete listing of the allowed values of eDest and their meanings.
2586**
drh9bb61fe2000-06-05 16:01:39 +00002587** This routine returns the number of errors. If any errors are
2588** encountered, then an appropriate error message is left in
2589** pParse->zErrMsg.
2590**
2591** This routine does NOT free the Select structure passed in. The
2592** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002593**
2594** The pParent, parentTab, and *pParentAgg fields are filled in if this
2595** SELECT is a subquery. This routine may try to combine this SELECT
2596** with its parent to form a single flat query. In so doing, it might
2597** change the parent query from a non-aggregate to an aggregate query.
2598** For that reason, the pParentAgg flag is passed as a pointer, so it
2599** can be changed.
drhe78e8282003-01-19 03:59:45 +00002600**
2601** Example 1: The meaning of the pParent parameter.
2602**
2603** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2604** \ \_______ subquery _______/ /
2605** \ /
2606** \____________________ outer query ___________________/
2607**
2608** This routine is called for the outer query first. For that call,
2609** pParent will be NULL. During the processing of the outer query, this
2610** routine is called recursively to handle the subquery. For the recursive
2611** call, pParent will point to the outer query. Because the subquery is
2612** the second element in a three-way join, the parentTab parameter will
2613** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002614*/
danielk19774adee202004-05-08 08:23:19 +00002615int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002616 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002617 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002618 int eDest, /* How to dispose of the results */
2619 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002620 Select *pParent, /* Another SELECT for which this is a sub-query */
2621 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002622 int *pParentAgg, /* True if pParent uses aggregate functions */
danielk1977b3bce662005-01-29 08:32:43 +00002623 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002624){
drh13449892005-09-07 21:22:45 +00002625 int i, j; /* Loop counters */
2626 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
2627 Vdbe *v; /* The virtual machine under construction */
danielk1977b3bce662005-01-29 08:32:43 +00002628 int isAgg; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002629 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002630 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002631 Expr *pWhere; /* The WHERE clause. May be NULL */
2632 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002633 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2634 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002635 int isDistinct; /* True if the DISTINCT keyword is present */
2636 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002637 int rc = 1; /* Value to return from this function */
drh9d2985c2005-09-08 01:58:42 +00002638 int addrSortIndex; /* Address of an OP_OpenVirtual instruction */
drh13449892005-09-07 21:22:45 +00002639 AggInfo sAggInfo; /* Information used by aggregate queries */
drhec7429a2005-10-06 16:53:14 +00002640 int iEnd; /* Address of the end of the query */
drh9bb61fe2000-06-05 16:01:39 +00002641
danielk19776f8a5032004-05-10 10:34:51 +00002642 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002643 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drh13449892005-09-07 21:22:45 +00002644 memset(&sAggInfo, 0, sizeof(sAggInfo));
drhdaffd0e2001-04-11 14:28:42 +00002645
drhb7f91642004-10-31 02:22:47 +00002646#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +00002647 /* If there is are a sequence of queries, do the earlier ones first.
2648 */
2649 if( p->pPrior ){
drh0342b1f2005-09-01 03:07:44 +00002650 if( p->pRightmost==0 ){
2651 Select *pLoop;
2652 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
2653 pLoop->pRightmost = p;
2654 }
2655 }
danielk197784ac9d02004-05-18 09:58:06 +00002656 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002657 }
drhb7f91642004-10-31 02:22:47 +00002658#endif
drh82c3d632000-06-06 21:56:07 +00002659
danielk1977b3bce662005-01-29 08:32:43 +00002660 pOrderBy = p->pOrderBy;
drh13449892005-09-07 21:22:45 +00002661 if( IgnorableOrderby(eDest) ){
danielk1977b3bce662005-01-29 08:32:43 +00002662 p->pOrderBy = 0;
2663 }
2664 if( sqlite3SelectResolve(pParse, p, 0) ){
2665 goto select_end;
2666 }
2667 p->pOrderBy = pOrderBy;
2668
drh82c3d632000-06-06 21:56:07 +00002669 /* Make local copies of the parameters for this query.
2670 */
drh9bb61fe2000-06-05 16:01:39 +00002671 pTabList = p->pSrc;
2672 pWhere = p->pWhere;
drh22827922000-06-06 17:27:05 +00002673 pGroupBy = p->pGroupBy;
2674 pHaving = p->pHaving;
danielk1977b3bce662005-01-29 08:32:43 +00002675 isAgg = p->isAgg;
drh19a775c2000-06-05 18:54:46 +00002676 isDistinct = p->isDistinct;
danielk1977b3bce662005-01-29 08:32:43 +00002677 pEList = p->pEList;
2678 if( pEList==0 ) goto select_end;
drh9bb61fe2000-06-05 16:01:39 +00002679
2680 /*
2681 ** Do not even attempt to generate any code if we have already seen
2682 ** errors before this routine starts.
2683 */
drh1d83f052002-02-17 00:30:36 +00002684 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002685
drh22827922000-06-06 17:27:05 +00002686 /* If writing to memory or generating a set
2687 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002688 */
danielk197793758c82005-01-21 08:13:14 +00002689#ifndef SQLITE_OMIT_SUBQUERY
drhfef52082000-06-06 01:50:43 +00002690 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002691 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002692 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002693 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002694 }
danielk197793758c82005-01-21 08:13:14 +00002695#endif
drh19a775c2000-06-05 18:54:46 +00002696
drhc926afb2002-06-20 03:38:26 +00002697 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002698 */
drh13449892005-09-07 21:22:45 +00002699 if( IgnorableOrderby(eDest) ){
2700 pOrderBy = 0;
drh22827922000-06-06 17:27:05 +00002701 }
2702
drhd820cb12002-02-18 03:21:45 +00002703 /* Begin generating code.
2704 */
danielk19774adee202004-05-08 08:23:19 +00002705 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002706 if( v==0 ) goto select_end;
2707
drhe78e8282003-01-19 03:59:45 +00002708 /* Identify column names if we will be using them in a callback. This
2709 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002710 */
2711 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002712 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002713 }
2714
drhd820cb12002-02-18 03:21:45 +00002715 /* Generate code for all sub-queries in the FROM clause
2716 */
drh51522cd2005-01-20 13:36:19 +00002717#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
drhad3cab52002-05-24 02:04:32 +00002718 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002719 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002720 int needRestoreContext;
drh13449892005-09-07 21:22:45 +00002721 struct SrcList_item *pItem = &pTabList->a[i];
drhc31c2eb2003-05-02 16:04:17 +00002722
drh13449892005-09-07 21:22:45 +00002723 if( pItem->pSelect==0 ) continue;
2724 if( pItem->zName!=0 ){
drh5cf590c2003-04-24 01:45:04 +00002725 zSavedAuthContext = pParse->zAuthContext;
drh13449892005-09-07 21:22:45 +00002726 pParse->zAuthContext = pItem->zName;
drhc31c2eb2003-05-02 16:04:17 +00002727 needRestoreContext = 1;
2728 }else{
2729 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002730 }
drh9d2985c2005-09-08 01:58:42 +00002731 sqlite3Select(pParse, pItem->pSelect, SRT_VirtualTab,
drh13449892005-09-07 21:22:45 +00002732 pItem->iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002733 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002734 pParse->zAuthContext = zSavedAuthContext;
2735 }
drh1b2e0322002-03-03 02:49:51 +00002736 pTabList = p->pSrc;
2737 pWhere = p->pWhere;
drh13449892005-09-07 21:22:45 +00002738 if( !IgnorableOrderby(eDest) ){
drhacd4c692002-03-07 02:02:51 +00002739 pOrderBy = p->pOrderBy;
2740 }
drh1b2e0322002-03-03 02:49:51 +00002741 pGroupBy = p->pGroupBy;
2742 pHaving = p->pHaving;
2743 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002744 }
drh51522cd2005-01-20 13:36:19 +00002745#endif
drhd820cb12002-02-18 03:21:45 +00002746
drh6e175292004-03-13 14:00:36 +00002747 /* Check for the special case of a min() or max() function by itself
2748 ** in the result set.
2749 */
2750 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2751 rc = 0;
2752 goto select_end;
2753 }
2754
drh832508b2002-03-02 17:04:07 +00002755 /* Check to see if this is a subquery that can be "flattened" into its parent.
2756 ** If flattening is a possiblity, do so and return immediately.
2757 */
drhb7f91642004-10-31 02:22:47 +00002758#ifndef SQLITE_OMIT_VIEW
drh1b2e0322002-03-03 02:49:51 +00002759 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002760 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002761 if( isAgg ) *pParentAgg = 1;
danielk1977b3bce662005-01-29 08:32:43 +00002762 goto select_end;
drh832508b2002-03-02 17:04:07 +00002763 }
drhb7f91642004-10-31 02:22:47 +00002764#endif
drh832508b2002-03-02 17:04:07 +00002765
danielk19777cedc8d2004-06-10 10:50:08 +00002766 /* If there is an ORDER BY clause, resolve any collation sequences
drh9d2985c2005-09-08 01:58:42 +00002767 ** names that have been explicitly specified and create a sorting index.
2768 **
2769 ** This sorting index might end up being unused if the data can be
2770 ** extracted in pre-sorted order. If that is the case, then the
2771 ** OP_OpenVirtual instruction will be changed to an OP_Noop once
2772 ** we figure out that the sorting index is not needed. The addrSortIndex
2773 ** variable is used to facilitate that change.
danielk19777cedc8d2004-06-10 10:50:08 +00002774 */
2775 if( pOrderBy ){
drh5d9a4af2005-08-30 00:54:01 +00002776 struct ExprList_item *pTerm;
drh0342b1f2005-09-01 03:07:44 +00002777 KeyInfo *pKeyInfo;
drh5d9a4af2005-08-30 00:54:01 +00002778 for(i=0, pTerm=pOrderBy->a; i<pOrderBy->nExpr; i++, pTerm++){
2779 if( pTerm->zName ){
2780 pTerm->pExpr->pColl = sqlite3LocateCollSeq(pParse, pTerm->zName, -1);
danielk19777cedc8d2004-06-10 10:50:08 +00002781 }
2782 }
2783 if( pParse->nErr ){
2784 goto select_end;
2785 }
drh0342b1f2005-09-01 03:07:44 +00002786 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
drh9d2985c2005-09-08 01:58:42 +00002787 pOrderBy->iECursor = pParse->nTab++;
2788 p->addrOpenVirt[2] = addrSortIndex =
2789 sqlite3VdbeOp3(v, OP_OpenVirtual, pOrderBy->iECursor, pOrderBy->nExpr+2,
drh0342b1f2005-09-01 03:07:44 +00002790 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drh9d2985c2005-09-08 01:58:42 +00002791 }else{
2792 addrSortIndex = -1;
danielk19777cedc8d2004-06-10 10:50:08 +00002793 }
2794
drh7b58dae2003-07-20 01:16:46 +00002795 /* Set the limiter.
2796 */
drhec7429a2005-10-06 16:53:14 +00002797 iEnd = sqlite3VdbeMakeLabel(v);
2798 computeLimitRegisters(pParse, p, iEnd);
drh7b58dae2003-07-20 01:16:46 +00002799
drh2d0794e2002-03-03 03:03:52 +00002800 /* If the output is destined for a temporary table, open that table.
2801 */
drh9d2985c2005-09-08 01:58:42 +00002802 if( eDest==SRT_VirtualTab ){
drh0342b1f2005-09-01 03:07:44 +00002803 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002804 }
2805
drhdece1a82005-08-31 18:20:00 +00002806 /* Open a virtual index to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002807 */
drh19a775c2000-06-05 18:54:46 +00002808 if( isDistinct ){
drh0342b1f2005-09-01 03:07:44 +00002809 KeyInfo *pKeyInfo;
drh832508b2002-03-02 17:04:07 +00002810 distinct = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00002811 pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
2812 sqlite3VdbeOp3(v, OP_OpenVirtual, distinct, 0,
2813 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drh832508b2002-03-02 17:04:07 +00002814 }else{
2815 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002816 }
drh832508b2002-03-02 17:04:07 +00002817
drh13449892005-09-07 21:22:45 +00002818 /* Aggregate and non-aggregate queries are handled differently */
2819 if( !isAgg && pGroupBy==0 ){
2820 /* This case is for non-aggregate queries
2821 ** Begin the database scan
2822 */
2823 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
2824 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002825
drh9d2985c2005-09-08 01:58:42 +00002826 /* If sorting index that was created by a prior OP_OpenVirtual
2827 ** instruction ended up not being needed, then change the OP_OpenVirtual
2828 ** into an OP_Noop.
2829 */
2830 if( addrSortIndex>=0 && pOrderBy==0 ){
2831 uncreateSortingIndex(pParse, addrSortIndex);
2832 p->addrOpenVirt[2] = -1;
2833 }
2834
drh13449892005-09-07 21:22:45 +00002835 /* Use the standard inner loop
2836 */
drhdf199a22002-06-14 22:38:41 +00002837 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002838 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002839 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002840 }
drhefb72512000-05-31 20:00:52 +00002841
drh13449892005-09-07 21:22:45 +00002842 /* End the database scan loop.
2843 */
2844 sqlite3WhereEnd(pWInfo);
2845 }else{
2846 /* This is the processing for aggregate queries */
2847 NameContext sNC; /* Name context for processing aggregate information */
2848 int iAMem; /* First Mem address for storing current GROUP BY */
2849 int iBMem; /* First Mem address for previous GROUP BY */
2850 int iUseFlag; /* Mem address holding flag indicating that at least
2851 ** one row of the input to the aggregator has been
2852 ** processed */
2853 int iAbortFlag; /* Mem address which causes query abort if positive */
2854 int groupBySort; /* Rows come from source in GROUP BY order */
drhcce7d172000-05-31 15:34:51 +00002855
drhcce7d172000-05-31 15:34:51 +00002856
drh13449892005-09-07 21:22:45 +00002857 /* The following variables hold addresses or labels for parts of the
2858 ** virtual machine program we are putting together */
2859 int addrOutputRow; /* Start of subroutine that outputs a result row */
2860 int addrSetAbort; /* Set the abort flag and return */
2861 int addrInitializeLoop; /* Start of code that initializes the input loop */
2862 int addrTopOfLoop; /* Top of the input loop */
2863 int addrGroupByChange; /* Code that runs when any GROUP BY term changes */
2864 int addrProcessRow; /* Code to process a single input row */
2865 int addrEnd; /* End of all processing */
2866 int addrSortingIdx; /* The OP_OpenVirtual for the sorting index */
drhe3133822005-09-20 13:11:59 +00002867 int addrReset; /* Subroutine for resetting the accumulator */
drh13449892005-09-07 21:22:45 +00002868
2869 addrEnd = sqlite3VdbeMakeLabel(v);
2870
2871 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
2872 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
2873 ** SELECT statement.
2874 */
2875 memset(&sNC, 0, sizeof(sNC));
2876 sNC.pParse = pParse;
2877 sNC.pSrcList = pTabList;
2878 sNC.pAggInfo = &sAggInfo;
2879 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
drh9d2985c2005-09-08 01:58:42 +00002880 sAggInfo.pGroupBy = pGroupBy;
drh13449892005-09-07 21:22:45 +00002881 if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
drh1d83f052002-02-17 00:30:36 +00002882 goto select_end;
drh22827922000-06-06 17:27:05 +00002883 }
drh13449892005-09-07 21:22:45 +00002884 if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
2885 goto select_end;
2886 }
2887 if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
2888 goto select_end;
2889 }
2890 sAggInfo.nAccumulator = sAggInfo.nColumn;
2891 for(i=0; i<sAggInfo.nFunc; i++){
2892 if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
2893 goto select_end;
2894 }
2895 }
drh5360ad32005-09-08 00:13:27 +00002896 if( sqlite3_malloc_failed ) goto select_end;
drh13449892005-09-07 21:22:45 +00002897
2898 /* Processing for aggregates with GROUP BY is very different and
2899 ** much more complex tha aggregates without a GROUP BY.
2900 */
2901 if( pGroupBy ){
2902 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
2903
2904 /* Create labels that we will be needing
2905 */
2906
2907 addrInitializeLoop = sqlite3VdbeMakeLabel(v);
2908 addrGroupByChange = sqlite3VdbeMakeLabel(v);
2909 addrProcessRow = sqlite3VdbeMakeLabel(v);
2910
2911 /* If there is a GROUP BY clause we might need a sorting index to
2912 ** implement it. Allocate that sorting index now. If it turns out
2913 ** that we do not need it after all, the OpenVirtual instruction
2914 ** will be converted into a Noop.
2915 */
2916 sAggInfo.sortingIdx = pParse->nTab++;
2917 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
2918 addrSortingIdx =
2919 sqlite3VdbeOp3(v, OP_OpenVirtual, sAggInfo.sortingIdx,
2920 sAggInfo.nSortingColumn,
2921 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2922
2923 /* Initialize memory locations used by GROUP BY aggregate processing
2924 */
2925 iUseFlag = pParse->nMem++;
2926 iAbortFlag = pParse->nMem++;
2927 iAMem = pParse->nMem;
2928 pParse->nMem += pGroupBy->nExpr;
2929 iBMem = pParse->nMem;
2930 pParse->nMem += pGroupBy->nExpr;
drhd654be82005-09-20 17:42:23 +00002931 sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
drhde29e3e2005-09-20 18:13:23 +00002932 VdbeComment((v, "# clear abort flag"));
drhd654be82005-09-20 17:42:23 +00002933 sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
drhde29e3e2005-09-20 18:13:23 +00002934 VdbeComment((v, "# indicate accumulator empty"));
drh13449892005-09-07 21:22:45 +00002935 sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
2936
2937 /* Generate a subroutine that outputs a single row of the result
2938 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
2939 ** is less than or equal to zero, the subroutine is a no-op. If
2940 ** the processing calls for the query to abort, this subroutine
2941 ** increments the iAbortFlag memory location before returning in
2942 ** order to signal the caller to abort.
2943 */
2944 addrSetAbort = sqlite3VdbeCurrentAddr(v);
drhde29e3e2005-09-20 18:13:23 +00002945 sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag);
2946 VdbeComment((v, "# set abort flag"));
drh13449892005-09-07 21:22:45 +00002947 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2948 addrOutputRow = sqlite3VdbeCurrentAddr(v);
2949 sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
drhde29e3e2005-09-20 18:13:23 +00002950 VdbeComment((v, "# Groupby result generator entry point"));
drh13449892005-09-07 21:22:45 +00002951 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2952 finalizeAggFunctions(pParse, &sAggInfo);
2953 if( pHaving ){
2954 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
2955 }
2956 rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
2957 distinct, eDest, iParm,
2958 addrOutputRow+1, addrSetAbort, aff);
2959 if( rc ){
2960 goto select_end;
2961 }
2962 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
drhde29e3e2005-09-20 18:13:23 +00002963 VdbeComment((v, "# end groupby result generator"));
drh13449892005-09-07 21:22:45 +00002964
drhe3133822005-09-20 13:11:59 +00002965 /* Generate a subroutine that will reset the group-by accumulator
2966 */
2967 addrReset = sqlite3VdbeCurrentAddr(v);
2968 resetAccumulator(pParse, &sAggInfo);
2969 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2970
drh13449892005-09-07 21:22:45 +00002971 /* Begin a loop that will extract all source rows in GROUP BY order.
2972 ** This might involve two separate loops with an OP_Sort in between, or
2973 ** it might be a single loop that uses an index to extract information
2974 ** in the right order to begin with.
2975 */
2976 sqlite3VdbeResolveLabel(v, addrInitializeLoop);
drhe3133822005-09-20 13:11:59 +00002977 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
drh13449892005-09-07 21:22:45 +00002978 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
drh5360ad32005-09-08 00:13:27 +00002979 if( pWInfo==0 ) goto select_end;
drh13449892005-09-07 21:22:45 +00002980 if( pGroupBy==0 ){
2981 /* The optimizer is able to deliver rows in group by order so
2982 ** we do not have to sort. The OP_OpenVirtual table will be
2983 ** cancelled later because we still need to use the pKeyInfo
2984 */
2985 pGroupBy = p->pGroupBy;
2986 groupBySort = 0;
2987 }else{
2988 /* Rows are coming out in undetermined order. We have to push
2989 ** each row into a sorting index, terminate the first loop,
2990 ** then loop over the sorting index in order to get the output
2991 ** in sorted order
2992 */
2993 groupBySort = 1;
2994 sqlite3ExprCodeExprList(pParse, pGroupBy);
2995 sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
2996 j = pGroupBy->nExpr+1;
2997 for(i=0; i<sAggInfo.nColumn; i++){
2998 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
2999 if( pCol->iSorterColumn<j ) continue;
3000 if( pCol->iColumn<0 ){
3001 sqlite3VdbeAddOp(v, OP_Rowid, pCol->iTable, 0);
3002 }else{
3003 sqlite3VdbeAddOp(v, OP_Column, pCol->iTable, pCol->iColumn);
3004 }
3005 j++;
3006 }
3007 sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
3008 sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
3009 sqlite3WhereEnd(pWInfo);
drh97571952005-09-08 12:57:28 +00003010 sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
drhde29e3e2005-09-20 18:13:23 +00003011 VdbeComment((v, "# GROUP BY sort"));
drh13449892005-09-07 21:22:45 +00003012 sAggInfo.useSortingIdx = 1;
3013 }
3014
3015 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
3016 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
3017 ** Then compare the current GROUP BY terms against the GROUP BY terms
3018 ** from the previous row currently stored in a0, a1, a2...
3019 */
3020 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
3021 for(j=0; j<pGroupBy->nExpr; j++){
3022 if( groupBySort ){
3023 sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
3024 }else{
3025 sAggInfo.directMode = 1;
3026 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
3027 }
3028 sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
3029 }
3030 for(j=pGroupBy->nExpr-1; j>=0; j--){
3031 if( j<pGroupBy->nExpr-1 ){
3032 sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
3033 }
3034 sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
3035 if( j==0 ){
drhe3133822005-09-20 13:11:59 +00003036 sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
drh13449892005-09-07 21:22:45 +00003037 }else{
drh4f686232005-09-20 13:55:18 +00003038 sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
drh13449892005-09-07 21:22:45 +00003039 }
3040 sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
3041 }
3042
3043 /* Generate code that runs whenever the GROUP BY changes.
3044 ** Change in the GROUP BY are detected by the previous code
3045 ** block. If there were no changes, this block is skipped.
3046 **
3047 ** This code copies current group by terms in b0,b1,b2,...
3048 ** over to a0,a1,a2. It then calls the output subroutine
3049 ** and resets the aggregate accumulator registers in preparation
3050 ** for the next GROUP BY batch.
3051 */
3052 sqlite3VdbeResolveLabel(v, addrGroupByChange);
3053 for(j=0; j<pGroupBy->nExpr; j++){
drhd654be82005-09-20 17:42:23 +00003054 sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
drh13449892005-09-07 21:22:45 +00003055 }
3056 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
drhde29e3e2005-09-20 18:13:23 +00003057 VdbeComment((v, "# output one row"));
drh13449892005-09-07 21:22:45 +00003058 sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
drhde29e3e2005-09-20 18:13:23 +00003059 VdbeComment((v, "# check abort flag"));
drhe3133822005-09-20 13:11:59 +00003060 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
drhde29e3e2005-09-20 18:13:23 +00003061 VdbeComment((v, "# reset accumulator"));
drh13449892005-09-07 21:22:45 +00003062
3063 /* Update the aggregate accumulators based on the content of
3064 ** the current row
3065 */
3066 sqlite3VdbeResolveLabel(v, addrProcessRow);
3067 updateAccumulator(pParse, &sAggInfo);
drhde29e3e2005-09-20 18:13:23 +00003068 sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag);
3069 VdbeComment((v, "# indicate data in accumulator"));
drh13449892005-09-07 21:22:45 +00003070
3071 /* End of the loop
3072 */
3073 if( groupBySort ){
3074 sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
3075 }else{
3076 sqlite3WhereEnd(pWInfo);
3077 uncreateSortingIndex(pParse, addrSortingIdx);
3078 }
3079
3080 /* Output the final row of result
3081 */
3082 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
drhde29e3e2005-09-20 18:13:23 +00003083 VdbeComment((v, "# output final row"));
drh13449892005-09-07 21:22:45 +00003084
3085 } /* endif pGroupBy */
3086 else {
3087 /* This case runs if the aggregate has no GROUP BY clause. The
3088 ** processing is much simpler since there is only a single row
3089 ** of output.
3090 */
3091 resetAccumulator(pParse, &sAggInfo);
3092 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
drh5360ad32005-09-08 00:13:27 +00003093 if( pWInfo==0 ) goto select_end;
drh13449892005-09-07 21:22:45 +00003094 updateAccumulator(pParse, &sAggInfo);
3095 sqlite3WhereEnd(pWInfo);
3096 finalizeAggFunctions(pParse, &sAggInfo);
3097 pOrderBy = 0;
drh5774b802005-09-07 22:48:16 +00003098 if( pHaving ){
3099 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
3100 }
drh13449892005-09-07 21:22:45 +00003101 selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
3102 eDest, iParm, addrEnd, addrEnd, aff);
3103 }
3104 sqlite3VdbeResolveLabel(v, addrEnd);
3105
3106 } /* endif aggregate query */
drh22827922000-06-06 17:27:05 +00003107
drhcce7d172000-05-31 15:34:51 +00003108 /* If there is an ORDER BY clause, then we need to sort the results
3109 ** and send them to the callback one by one.
3110 */
3111 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00003112 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00003113 }
drh6a535342001-10-19 16:44:56 +00003114
danielk197793758c82005-01-21 08:13:14 +00003115#ifndef SQLITE_OMIT_SUBQUERY
drhf620b4e2004-02-09 14:37:50 +00003116 /* If this was a subquery, we have now converted the subquery into a
3117 ** temporary table. So delete the subquery structure from the parent
3118 ** to prevent this subquery from being evaluated again and to force the
3119 ** the use of the temporary table.
3120 */
3121 if( pParent ){
3122 assert( pParent->pSrc->nSrc>parentTab );
3123 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00003124 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00003125 pParent->pSrc->a[parentTab].pSelect = 0;
3126 }
danielk197793758c82005-01-21 08:13:14 +00003127#endif
drhf620b4e2004-02-09 14:37:50 +00003128
drhec7429a2005-10-06 16:53:14 +00003129 /* Jump here to skip this query
3130 */
3131 sqlite3VdbeResolveLabel(v, iEnd);
3132
drh1d83f052002-02-17 00:30:36 +00003133 /* The SELECT was successfully coded. Set the return code to 0
3134 ** to indicate no errors.
3135 */
3136 rc = 0;
3137
3138 /* Control jumps to here if an error is encountered above, or upon
3139 ** successful coding of the SELECT.
3140 */
3141select_end:
drh13449892005-09-07 21:22:45 +00003142 sqliteFree(sAggInfo.aCol);
3143 sqliteFree(sAggInfo.aFunc);
drh1d83f052002-02-17 00:30:36 +00003144 return rc;
drhcce7d172000-05-31 15:34:51 +00003145}