blob: af19681c524e722aef7218d77b45c538b7054544 [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**
danielk1977ad68cb62006-01-05 14:22:33 +000015** $Id: select.c,v 1.285 2006/01/05 14:22:34 danielk1977 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
drh2646da72005-12-09 20:02:05 +0000112 && sqlite3StrNICmp((char*)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){
drh2646da72005-12-09 20:02:05 +0000157 p->z = (u8*)z;
danielk1977261919c2005-12-06 12:52:59 +0000158 p->n = z ? strlen(z) : 0;
drh91bb0ee2004-09-01 03:06:34 +0000159 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 ){
drh2646da72005-12-09 20:02:05 +0000635 pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
drhdece1a82005-08-31 18:20:00 +0000636 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 );
danielk1977261919c2005-12-06 12:52:59 +0000859 if( pParse->colNamesSet || v==0 || sqlite3Tsd()->mallocFailed ) 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] ){
drh2646da72005-12-09 20:02:05 +0000888 sqlite3VdbeSetColName(v, i, (char*)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;
drhf93339d2006-01-03 15:16:26 +0000895 sqlite3SetString(&zName, zTab, ".", zCol, (char*)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] ){
drh2646da72005-12-09 20:02:05 +0000901 sqlite3VdbeSetColName(v, i, (char*)p->span.z, p->span.n);
danielk19773cf86062004-05-26 10:11:05 +0000902 /* 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);
danielk1977261919c2005-12-06 12:52:59 +0000987 if( sqlite3Tsd()->mallocFailed ){
drhdd5b2fa2005-03-28 03:39:55 +0000988 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
danielk1977261919c2005-12-06 12:52:59 +00001059 if( p==0 || p->pSrc==0 || sqlite3Tsd()->mallocFailed ) 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);
danielk1977261919c2005-12-06 12:52:59 +00001167 if( pNew ){
1168 pNew->a[pNew->nExpr-1].zName = a[k].zName;
1169 }else{
1170 rc = 1;
1171 }
drh7c917d12001-12-16 20:05:05 +00001172 a[k].pExpr = 0;
1173 a[k].zName = 0;
1174 }else{
drh54473222002-04-04 02:10:55 +00001175 /* This expression is a "*" or a "TABLE.*" and needs to be
1176 ** expanded. */
1177 int tableSeen = 0; /* Set to 1 when TABLE matches */
drhcf55b7a2004-07-20 01:45:19 +00001178 char *zTName; /* text of name of TABLE */
drh54473222002-04-04 02:10:55 +00001179 if( pE->op==TK_DOT && pE->pLeft ){
drhcf55b7a2004-07-20 01:45:19 +00001180 zTName = sqlite3NameFromToken(&pE->pLeft->token);
drh54473222002-04-04 02:10:55 +00001181 }else{
drhcf55b7a2004-07-20 01:45:19 +00001182 zTName = 0;
drh54473222002-04-04 02:10:55 +00001183 }
drh290c1942004-08-21 17:54:45 +00001184 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1185 Table *pTab = pFrom->pTab;
1186 char *zTabName = pFrom->zAlias;
drh54473222002-04-04 02:10:55 +00001187 if( zTabName==0 || zTabName[0]==0 ){
1188 zTabName = pTab->zName;
1189 }
drhcf55b7a2004-07-20 01:45:19 +00001190 if( zTName && (zTabName==0 || zTabName[0]==0 ||
1191 sqlite3StrICmp(zTName, zTabName)!=0) ){
drh54473222002-04-04 02:10:55 +00001192 continue;
1193 }
1194 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001195 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001196 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001197 char *zName = pTab->aCol[j].zName;
1198
drh91bb0ee2004-09-01 03:06:34 +00001199 if( i>0 ){
1200 struct SrcList_item *pLeft = &pTabList->a[i-1];
1201 if( (pLeft->jointype & JT_NATURAL)!=0 &&
1202 columnIndex(pLeft->pTab, zName)>=0 ){
1203 /* In a NATURAL join, omit the join columns from the
1204 ** table on the right */
1205 continue;
1206 }
1207 if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1208 /* In a join with a USING clause, omit columns in the
1209 ** using clause from the table on the right. */
1210 continue;
1211 }
drhad2d8302002-05-24 20:31:36 +00001212 }
danielk19774adee202004-05-08 08:23:19 +00001213 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001214 if( pRight==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001215 setToken(&pRight->token, zName);
drhd70dc522005-06-06 16:34:33 +00001216 if( zTabName && (longNames || pTabList->nSrc>1) ){
danielk19774adee202004-05-08 08:23:19 +00001217 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1218 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001219 if( pExpr==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001220 setToken(&pLeft->token, zTabName);
1221 setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
drh6977fea2002-10-22 23:38:04 +00001222 pExpr->span.dyn = 1;
1223 pExpr->token.z = 0;
1224 pExpr->token.n = 0;
1225 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001226 }else{
drh22f70c32002-02-18 01:17:00 +00001227 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001228 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001229 }
drhd70dc522005-06-06 16:34:33 +00001230 if( longNames ){
1231 pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span);
1232 }else{
1233 pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
1234 }
drh7c917d12001-12-16 20:05:05 +00001235 }
drh17e24df2001-11-06 14:10:41 +00001236 }
drh54473222002-04-04 02:10:55 +00001237 if( !tableSeen ){
drhcf55b7a2004-07-20 01:45:19 +00001238 if( zTName ){
1239 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
drhf5db2d32002-06-06 23:42:27 +00001240 }else{
danielk19774adee202004-05-08 08:23:19 +00001241 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001242 }
drh54473222002-04-04 02:10:55 +00001243 rc = 1;
1244 }
drhcf55b7a2004-07-20 01:45:19 +00001245 sqliteFree(zTName);
drhd8bc7082000-06-07 23:51:50 +00001246 }
1247 }
danielk19774adee202004-05-08 08:23:19 +00001248 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001249 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001250 }
drh54473222002-04-04 02:10:55 +00001251 return rc;
drhd8bc7082000-06-07 23:51:50 +00001252}
1253
danielk197793758c82005-01-21 08:13:14 +00001254#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhff78bd22002-02-27 01:47:11 +00001255/*
drhd8bc7082000-06-07 23:51:50 +00001256** This routine associates entries in an ORDER BY expression list with
1257** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001258** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001259** the top-level node is filled in with column number and the iTable
1260** value of the top-level node is filled with iTable parameter.
1261**
1262** If there are prior SELECT clauses, they are processed first. A match
1263** in an earlier SELECT takes precedence over a later SELECT.
1264**
1265** Any entry that does not match is flagged as an error. The number
1266** of errors is returned.
1267*/
1268static int matchOrderbyToColumn(
1269 Parse *pParse, /* A place to leave error messages */
1270 Select *pSelect, /* Match to result columns of this SELECT */
1271 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001272 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001273 int mustComplete /* If TRUE all ORDER BYs must match */
1274){
1275 int nErr = 0;
1276 int i, j;
1277 ExprList *pEList;
1278
drhdaffd0e2001-04-11 14:28:42 +00001279 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001280 if( mustComplete ){
1281 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1282 }
drh9b3187e2005-01-18 14:45:47 +00001283 if( prepSelectStmt(pParse, pSelect) ){
drhd8bc7082000-06-07 23:51:50 +00001284 return 1;
1285 }
1286 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001287 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1288 return 1;
1289 }
drhd8bc7082000-06-07 23:51:50 +00001290 }
1291 pEList = pSelect->pEList;
1292 for(i=0; i<pOrderBy->nExpr; i++){
1293 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001294 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001295 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001296 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001297 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001298 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001299 "ORDER BY position %d should be between 1 and %d",
1300 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001301 nErr++;
1302 break;
1303 }
drhfcb78a42003-01-18 20:11:05 +00001304 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001305 iCol--;
1306 }
1307 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001308 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001309 char *zName, *zLabel;
1310 zName = pEList->a[j].zName;
drha99db3b2004-06-19 14:49:12 +00001311 zLabel = sqlite3NameFromToken(&pE->token);
1312 assert( zLabel!=0 );
danielk19774adee202004-05-08 08:23:19 +00001313 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001314 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001315 }
drh6e142f52000-06-08 13:36:40 +00001316 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001317 }
danielk19774adee202004-05-08 08:23:19 +00001318 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001319 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001320 }
1321 }
drhe4de1fe2002-06-02 16:09:01 +00001322 if( iCol>=0 ){
1323 pE->op = TK_COLUMN;
1324 pE->iColumn = iCol;
1325 pE->iTable = iTable;
danielk1977a58fdfb2005-02-08 07:50:40 +00001326 pE->iAgg = -1;
drhe4de1fe2002-06-02 16:09:01 +00001327 pOrderBy->a[i].done = 1;
1328 }
1329 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001330 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001331 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001332 nErr++;
1333 break;
1334 }
1335 }
1336 return nErr;
1337}
danielk197793758c82005-01-21 08:13:14 +00001338#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +00001339
1340/*
1341** Get a VDBE for the given parser context. Create a new one if necessary.
1342** If an error occurs, return NULL and leave a message in pParse.
1343*/
danielk19774adee202004-05-08 08:23:19 +00001344Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001345 Vdbe *v = pParse->pVdbe;
1346 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001347 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001348 }
drhd8bc7082000-06-07 23:51:50 +00001349 return v;
1350}
drhfcb78a42003-01-18 20:11:05 +00001351
drhd8bc7082000-06-07 23:51:50 +00001352/*
drh7b58dae2003-07-20 01:16:46 +00001353** Compute the iLimit and iOffset fields of the SELECT based on the
drhec7429a2005-10-06 16:53:14 +00001354** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
drh7b58dae2003-07-20 01:16:46 +00001355** that appear in the original SQL statement after the LIMIT and OFFSET
danielk1977a2dc3b12005-02-05 12:48:48 +00001356** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
1357** are the integer memory register numbers for counters used to compute
1358** the limit and offset. If there is no limit and/or offset, then
1359** iLimit and iOffset are negative.
drh7b58dae2003-07-20 01:16:46 +00001360**
1361** This routine changes the values if iLimit and iOffset only if
drhec7429a2005-10-06 16:53:14 +00001362** a limit or offset is defined by pLimit and pOffset. iLimit and
drh7b58dae2003-07-20 01:16:46 +00001363** iOffset should have been preset to appropriate default values
1364** (usually but not always -1) prior to calling this routine.
drhec7429a2005-10-06 16:53:14 +00001365** Only if pLimit!=0 or pOffset!=0 do the limit registers get
drh7b58dae2003-07-20 01:16:46 +00001366** redefined. The UNION ALL operator uses this property to force
1367** the reuse of the same limit and offset registers across multiple
1368** SELECT statements.
1369*/
drhec7429a2005-10-06 16:53:14 +00001370static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
drh7b58dae2003-07-20 01:16:46 +00001371 /*
drh7b58dae2003-07-20 01:16:46 +00001372 ** "LIMIT -1" always shows all rows. There is some
1373 ** contraversy about what the correct behavior should be.
1374 ** The current implementation interprets "LIMIT 0" to mean
1375 ** no rows.
1376 */
danielk1977a2dc3b12005-02-05 12:48:48 +00001377 if( p->pLimit ){
drh7b58dae2003-07-20 01:16:46 +00001378 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001379 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001380 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001381 sqlite3ExprCode(pParse, p->pLimit);
1382 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1383 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001384 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001385 VdbeComment((v, "# LIMIT counter"));
drhec7429a2005-10-06 16:53:14 +00001386 sqlite3VdbeAddOp(v, OP_IfMemZero, iMem, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001387 p->iLimit = iMem;
1388 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001389 if( p->pOffset ){
drh7b58dae2003-07-20 01:16:46 +00001390 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001391 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001392 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001393 sqlite3ExprCode(pParse, p->pOffset);
1394 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1395 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001396 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001397 VdbeComment((v, "# OFFSET counter"));
drh7b58dae2003-07-20 01:16:46 +00001398 p->iOffset = iMem;
1399 }
1400}
1401
1402/*
drh0342b1f2005-09-01 03:07:44 +00001403** Allocate a virtual index to use for sorting.
drhd3d39e92004-05-20 22:16:29 +00001404*/
drh4db38a72005-09-01 12:16:28 +00001405static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
drh0342b1f2005-09-01 03:07:44 +00001406 if( pOrderBy ){
1407 int addr;
drh9d2985c2005-09-08 01:58:42 +00001408 assert( pOrderBy->iECursor==0 );
1409 pOrderBy->iECursor = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001410 addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenVirtual,
drh9d2985c2005-09-08 01:58:42 +00001411 pOrderBy->iECursor, pOrderBy->nExpr+1);
drh0342b1f2005-09-01 03:07:44 +00001412 assert( p->addrOpenVirt[2] == -1 );
1413 p->addrOpenVirt[2] = addr;
drh736c22b2004-05-21 02:14:24 +00001414 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001415}
1416
drh13449892005-09-07 21:22:45 +00001417/*
1418** The opcode at addr is an OP_OpenVirtual that created a sorting
1419** index tha we ended up not needing. This routine changes that
1420** opcode to OP_Noop.
1421*/
1422static void uncreateSortingIndex(Parse *pParse, int addr){
1423 Vdbe *v = pParse->pVdbe;
1424 VdbeOp *pOp = sqlite3VdbeGetOp(v, addr);
1425 sqlite3VdbeChangeP3(v, addr, 0, 0);
1426 pOp->opcode = OP_Noop;
1427 pOp->p1 = 0;
1428 pOp->p2 = 0;
1429}
1430
drhb7f91642004-10-31 02:22:47 +00001431#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001432/*
drhfbc4ee72004-08-29 01:31:05 +00001433** Return the appropriate collating sequence for the iCol-th column of
1434** the result set for the compound-select statement "p". Return NULL if
1435** the column has no default collating sequence.
1436**
1437** The collating sequence for the compound select is taken from the
1438** left-most term of the select that has a collating sequence.
1439*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001440static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
drhfbc4ee72004-08-29 01:31:05 +00001441 CollSeq *pRet;
danielk1977dc1bdc42004-06-11 10:51:27 +00001442 if( p->pPrior ){
1443 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
drhfbc4ee72004-08-29 01:31:05 +00001444 }else{
1445 pRet = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001446 }
drhfbc4ee72004-08-29 01:31:05 +00001447 if( pRet==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001448 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1449 }
1450 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001451}
drhb7f91642004-10-31 02:22:47 +00001452#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd3d39e92004-05-20 22:16:29 +00001453
drhb7f91642004-10-31 02:22:47 +00001454#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhd3d39e92004-05-20 22:16:29 +00001455/*
drh82c3d632000-06-06 21:56:07 +00001456** This routine is called to process a query that is really the union
1457** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001458**
drhe78e8282003-01-19 03:59:45 +00001459** "p" points to the right-most of the two queries. the query on the
1460** left is p->pPrior. The left query could also be a compound query
1461** in which case this routine will be called recursively.
1462**
1463** The results of the total query are to be written into a destination
1464** of type eDest with parameter iParm.
1465**
1466** Example 1: Consider a three-way compound SQL statement.
1467**
1468** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1469**
1470** This statement is parsed up as follows:
1471**
1472** SELECT c FROM t3
1473** |
1474** `-----> SELECT b FROM t2
1475** |
jplyon4b11c6d2004-01-19 04:57:53 +00001476** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001477**
1478** The arrows in the diagram above represent the Select.pPrior pointer.
1479** So if this routine is called with p equal to the t3 query, then
1480** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1481**
1482** Notice that because of the way SQLite parses compound SELECTs, the
1483** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001484*/
danielk197784ac9d02004-05-18 09:58:06 +00001485static int multiSelect(
drhfbc4ee72004-08-29 01:31:05 +00001486 Parse *pParse, /* Parsing context */
1487 Select *p, /* The right-most of SELECTs to be coded */
1488 int eDest, /* \___ Store query results as specified */
1489 int iParm, /* / by these two parameters. */
1490 char *aff /* If eDest is SRT_Union, the affinity string */
danielk197784ac9d02004-05-18 09:58:06 +00001491){
drhfbc4ee72004-08-29 01:31:05 +00001492 int rc = SQLITE_OK; /* Success code from a subroutine */
1493 Select *pPrior; /* Another SELECT immediately to our left */
1494 Vdbe *v; /* Generate code to this VDBE */
drh8cdbf832004-08-29 16:25:03 +00001495 int nCol; /* Number of columns in the result set */
drh0342b1f2005-09-01 03:07:44 +00001496 ExprList *pOrderBy; /* The ORDER BY clause on p */
1497 int aSetP2[2]; /* Set P2 value of these op to number of columns */
1498 int nSetP2 = 0; /* Number of slots in aSetP2[] used */
drh82c3d632000-06-06 21:56:07 +00001499
drh7b58dae2003-07-20 01:16:46 +00001500 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
drhfbc4ee72004-08-29 01:31:05 +00001501 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001502 */
danielk197784ac9d02004-05-18 09:58:06 +00001503 if( p==0 || p->pPrior==0 ){
1504 rc = 1;
1505 goto multi_select_end;
1506 }
drhd8bc7082000-06-07 23:51:50 +00001507 pPrior = p->pPrior;
drh0342b1f2005-09-01 03:07:44 +00001508 assert( pPrior->pRightmost!=pPrior );
1509 assert( pPrior->pRightmost==p->pRightmost );
drhd8bc7082000-06-07 23:51:50 +00001510 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001511 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001512 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001513 rc = 1;
1514 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001515 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001516 if( pPrior->pLimit ){
danielk19774adee202004-05-08 08:23:19 +00001517 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001518 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001519 rc = 1;
1520 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001521 }
drh82c3d632000-06-06 21:56:07 +00001522
drhd8bc7082000-06-07 23:51:50 +00001523 /* Make sure we have a valid query engine. If not, create a new one.
1524 */
danielk19774adee202004-05-08 08:23:19 +00001525 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001526 if( v==0 ){
1527 rc = 1;
1528 goto multi_select_end;
1529 }
drhd8bc7082000-06-07 23:51:50 +00001530
drh1cc3d752002-03-23 00:31:29 +00001531 /* Create the destination temporary table if necessary
1532 */
drh9d2985c2005-09-08 01:58:42 +00001533 if( eDest==SRT_VirtualTab ){
danielk1977b4964b72004-05-18 01:23:38 +00001534 assert( p->pEList );
drh0342b1f2005-09-01 03:07:44 +00001535 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1536 aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 0);
drh1cc3d752002-03-23 00:31:29 +00001537 eDest = SRT_Table;
1538 }
1539
drhf46f9052002-06-22 02:33:38 +00001540 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001541 */
drh0342b1f2005-09-01 03:07:44 +00001542 pOrderBy = p->pOrderBy;
drh82c3d632000-06-06 21:56:07 +00001543 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001544 case TK_ALL: {
drh0342b1f2005-09-01 03:07:44 +00001545 if( pOrderBy==0 ){
drhec7429a2005-10-06 16:53:14 +00001546 int addr = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001547 assert( !pPrior->pLimit );
1548 pPrior->pLimit = p->pLimit;
1549 pPrior->pOffset = p->pOffset;
danielk1977b3bce662005-01-29 08:32:43 +00001550 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
danielk1977ad68cb62006-01-05 14:22:33 +00001551 p->pLimit = 0;
1552 p->pOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001553 if( rc ){
1554 goto multi_select_end;
1555 }
drhf46f9052002-06-22 02:33:38 +00001556 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001557 p->iLimit = pPrior->iLimit;
1558 p->iOffset = pPrior->iOffset;
drhec7429a2005-10-06 16:53:14 +00001559 if( p->iLimit>=0 ){
1560 addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0);
1561 VdbeComment((v, "# Jump ahead if LIMIT reached"));
1562 }
danielk1977b3bce662005-01-29 08:32:43 +00001563 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001564 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001565 if( rc ){
1566 goto multi_select_end;
1567 }
drhec7429a2005-10-06 16:53:14 +00001568 if( addr ){
1569 sqlite3VdbeJumpHere(v, addr);
1570 }
drhf46f9052002-06-22 02:33:38 +00001571 break;
1572 }
1573 /* For UNION ALL ... ORDER BY fall through to the next case */
1574 }
drh82c3d632000-06-06 21:56:07 +00001575 case TK_EXCEPT:
1576 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001577 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001578 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001579 int priorOp; /* The SRT_ operation to apply to prior selects */
danielk1977a2dc3b12005-02-05 12:48:48 +00001580 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
danielk1977dc1bdc42004-06-11 10:51:27 +00001581 int addr;
drh82c3d632000-06-06 21:56:07 +00001582
drhd8bc7082000-06-07 23:51:50 +00001583 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh0342b1f2005-09-01 03:07:44 +00001584 if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
drhd8bc7082000-06-07 23:51:50 +00001585 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001586 ** right.
drhd8bc7082000-06-07 23:51:50 +00001587 */
drh82c3d632000-06-06 21:56:07 +00001588 unionTab = iParm;
1589 }else{
drhd8bc7082000-06-07 23:51:50 +00001590 /* We will need to create our own temporary table to hold the
1591 ** intermediate results.
1592 */
1593 unionTab = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001594 if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001595 rc = 1;
1596 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001597 }
drh9170dd72005-07-08 17:13:46 +00001598 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, unionTab, 0);
drh0342b1f2005-09-01 03:07:44 +00001599 if( priorOp==SRT_Table ){
1600 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1601 aSetP2[nSetP2++] = addr;
1602 }else{
1603 assert( p->addrOpenVirt[0] == -1 );
1604 p->addrOpenVirt[0] = addr;
1605 p->pRightmost->usesVirt = 1;
drhd8bc7082000-06-07 23:51:50 +00001606 }
drh0342b1f2005-09-01 03:07:44 +00001607 createSortingIndex(pParse, p, pOrderBy);
danielk197784ac9d02004-05-18 09:58:06 +00001608 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001609 }
drhd8bc7082000-06-07 23:51:50 +00001610
1611 /* Code the SELECT statements to our left
1612 */
danielk1977b3bce662005-01-29 08:32:43 +00001613 assert( !pPrior->pOrderBy );
1614 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001615 if( rc ){
1616 goto multi_select_end;
1617 }
drhd8bc7082000-06-07 23:51:50 +00001618
1619 /* Code the current SELECT statement
1620 */
1621 switch( p->op ){
1622 case TK_EXCEPT: op = SRT_Except; break;
1623 case TK_UNION: op = SRT_Union; break;
1624 case TK_ALL: op = SRT_Table; break;
1625 }
drh82c3d632000-06-06 21:56:07 +00001626 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001627 p->pOrderBy = 0;
drh4b14b4d2005-09-19 17:35:53 +00001628 p->disallowOrderBy = pOrderBy!=0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001629 pLimit = p->pLimit;
1630 p->pLimit = 0;
1631 pOffset = p->pOffset;
1632 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001633 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001634 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001635 p->pOrderBy = pOrderBy;
danielk1977a2dc3b12005-02-05 12:48:48 +00001636 sqlite3ExprDelete(p->pLimit);
1637 p->pLimit = pLimit;
1638 p->pOffset = pOffset;
drhbe5fd492004-12-16 21:09:16 +00001639 p->iLimit = -1;
1640 p->iOffset = -1;
danielk197784ac9d02004-05-18 09:58:06 +00001641 if( rc ){
1642 goto multi_select_end;
1643 }
1644
drhd8bc7082000-06-07 23:51:50 +00001645
1646 /* Convert the data in the temporary table into whatever form
1647 ** it is that we currently need.
1648 */
drhc926afb2002-06-20 03:38:26 +00001649 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001650 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001651 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001652 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001653 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001654 }
danielk19774adee202004-05-08 08:23:19 +00001655 iBreak = sqlite3VdbeMakeLabel(v);
1656 iCont = sqlite3VdbeMakeLabel(v);
drhec7429a2005-10-06 16:53:14 +00001657 computeLimitRegisters(pParse, p, iBreak);
danielk19774adee202004-05-08 08:23:19 +00001658 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
danielk19774adee202004-05-08 08:23:19 +00001659 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001660 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001661 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001662 iCont, iBreak, 0);
1663 if( rc ){
1664 rc = 1;
1665 goto multi_select_end;
1666 }
danielk19774adee202004-05-08 08:23:19 +00001667 sqlite3VdbeResolveLabel(v, iCont);
1668 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1669 sqlite3VdbeResolveLabel(v, iBreak);
1670 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001671 }
1672 break;
1673 }
1674 case TK_INTERSECT: {
1675 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001676 int iCont, iBreak, iStart;
danielk1977a2dc3b12005-02-05 12:48:48 +00001677 Expr *pLimit, *pOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001678 int addr;
drh82c3d632000-06-06 21:56:07 +00001679
drhd8bc7082000-06-07 23:51:50 +00001680 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001681 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001682 ** by allocating the tables we will need.
1683 */
drh82c3d632000-06-06 21:56:07 +00001684 tab1 = pParse->nTab++;
1685 tab2 = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001686 if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001687 rc = 1;
1688 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001689 }
drh0342b1f2005-09-01 03:07:44 +00001690 createSortingIndex(pParse, p, pOrderBy);
danielk1977dc1bdc42004-06-11 10:51:27 +00001691
drh9170dd72005-07-08 17:13:46 +00001692 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab1, 0);
drh0342b1f2005-09-01 03:07:44 +00001693 assert( p->addrOpenVirt[0] == -1 );
1694 p->addrOpenVirt[0] = addr;
1695 p->pRightmost->usesVirt = 1;
danielk197784ac9d02004-05-18 09:58:06 +00001696 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001697
1698 /* Code the SELECTs to our left into temporary table "tab1".
1699 */
danielk1977b3bce662005-01-29 08:32:43 +00001700 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001701 if( rc ){
1702 goto multi_select_end;
1703 }
drhd8bc7082000-06-07 23:51:50 +00001704
1705 /* Code the current SELECT into temporary table "tab2"
1706 */
drh9170dd72005-07-08 17:13:46 +00001707 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab2, 0);
drh0342b1f2005-09-01 03:07:44 +00001708 assert( p->addrOpenVirt[1] == -1 );
1709 p->addrOpenVirt[1] = addr;
drh82c3d632000-06-06 21:56:07 +00001710 p->pPrior = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001711 pLimit = p->pLimit;
1712 p->pLimit = 0;
1713 pOffset = p->pOffset;
1714 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001715 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001716 p->pPrior = pPrior;
danielk1977a2dc3b12005-02-05 12:48:48 +00001717 sqlite3ExprDelete(p->pLimit);
1718 p->pLimit = pLimit;
1719 p->pOffset = pOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001720 if( rc ){
1721 goto multi_select_end;
1722 }
drhd8bc7082000-06-07 23:51:50 +00001723
1724 /* Generate code to take the intersection of the two temporary
1725 ** tables.
1726 */
drh82c3d632000-06-06 21:56:07 +00001727 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001728 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001729 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001730 }
danielk19774adee202004-05-08 08:23:19 +00001731 iBreak = sqlite3VdbeMakeLabel(v);
1732 iCont = sqlite3VdbeMakeLabel(v);
drhec7429a2005-10-06 16:53:14 +00001733 computeLimitRegisters(pParse, p, iBreak);
danielk19774adee202004-05-08 08:23:19 +00001734 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh4a9f2412005-06-12 12:01:19 +00001735 iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
danielk19774adee202004-05-08 08:23:19 +00001736 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001737 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001738 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001739 iCont, iBreak, 0);
1740 if( rc ){
1741 rc = 1;
1742 goto multi_select_end;
1743 }
danielk19774adee202004-05-08 08:23:19 +00001744 sqlite3VdbeResolveLabel(v, iCont);
1745 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1746 sqlite3VdbeResolveLabel(v, iBreak);
1747 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1748 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001749 break;
1750 }
1751 }
drh8cdbf832004-08-29 16:25:03 +00001752
1753 /* Make sure all SELECTs in the statement have the same number of elements
1754 ** in their result sets.
1755 */
drh82c3d632000-06-06 21:56:07 +00001756 assert( p->pEList && pPrior->pEList );
1757 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001758 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001759 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001760 rc = 1;
1761 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001762 }
danielk197784ac9d02004-05-18 09:58:06 +00001763
drh8cdbf832004-08-29 16:25:03 +00001764 /* Set the number of columns in temporary tables
1765 */
1766 nCol = p->pEList->nExpr;
drh0342b1f2005-09-01 03:07:44 +00001767 while( nSetP2 ){
1768 sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
drh8cdbf832004-08-29 16:25:03 +00001769 }
1770
drhfbc4ee72004-08-29 01:31:05 +00001771 /* Compute collating sequences used by either the ORDER BY clause or
1772 ** by any temporary tables needed to implement the compound select.
1773 ** Attach the KeyInfo structure to all temporary tables. Invoke the
1774 ** ORDER BY processing if there is an ORDER BY clause.
drh8cdbf832004-08-29 16:25:03 +00001775 **
1776 ** This section is run by the right-most SELECT statement only.
1777 ** SELECT statements to the left always skip this part. The right-most
1778 ** SELECT might also skip this part if it has no ORDER BY clause and
1779 ** no temp tables are required.
drhfbc4ee72004-08-29 01:31:05 +00001780 */
drh0342b1f2005-09-01 03:07:44 +00001781 if( pOrderBy || p->usesVirt ){
drhfbc4ee72004-08-29 01:31:05 +00001782 int i; /* Loop counter */
1783 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
drh0342b1f2005-09-01 03:07:44 +00001784 Select *pLoop; /* For looping through SELECT statements */
1785 CollSeq **apColl;
1786 CollSeq **aCopy;
drhfbc4ee72004-08-29 01:31:05 +00001787
drh0342b1f2005-09-01 03:07:44 +00001788 assert( p->pRightmost==p );
drh4db38a72005-09-01 12:16:28 +00001789 pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*2*sizeof(CollSeq*) + nCol);
danielk1977dc1bdc42004-06-11 10:51:27 +00001790 if( !pKeyInfo ){
1791 rc = SQLITE_NOMEM;
1792 goto multi_select_end;
1793 }
1794
1795 pKeyInfo->enc = pParse->db->enc;
1796 pKeyInfo->nField = nCol;
1797
drh0342b1f2005-09-01 03:07:44 +00001798 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
1799 *apColl = multiSelectCollSeq(pParse, p, i);
1800 if( 0==*apColl ){
1801 *apColl = pParse->db->pDfltColl;
danielk1977dc1bdc42004-06-11 10:51:27 +00001802 }
1803 }
1804
drh0342b1f2005-09-01 03:07:44 +00001805 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
1806 for(i=0; i<2; i++){
1807 int addr = pLoop->addrOpenVirt[i];
1808 if( addr<0 ){
1809 /* If [0] is unused then [1] is also unused. So we can
1810 ** always safely abort as soon as the first unused slot is found */
1811 assert( pLoop->addrOpenVirt[1]<0 );
1812 break;
1813 }
1814 sqlite3VdbeChangeP2(v, addr, nCol);
1815 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
1816 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001817 }
1818
drh0342b1f2005-09-01 03:07:44 +00001819 if( pOrderBy ){
1820 struct ExprList_item *pOTerm = pOrderBy->a;
drh4efc0832005-11-16 13:47:50 +00001821 int nOrderByExpr = pOrderBy->nExpr;
drh0342b1f2005-09-01 03:07:44 +00001822 int addr;
drh4db38a72005-09-01 12:16:28 +00001823 u8 *pSortOrder;
drh0342b1f2005-09-01 03:07:44 +00001824
1825 aCopy = (CollSeq**)&pKeyInfo[1];
drh4efc0832005-11-16 13:47:50 +00001826 pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
drh0342b1f2005-09-01 03:07:44 +00001827 memcpy(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
1828 apColl = pKeyInfo->aColl;
drh4efc0832005-11-16 13:47:50 +00001829 for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
drh0342b1f2005-09-01 03:07:44 +00001830 Expr *pExpr = pOTerm->pExpr;
1831 char *zName = pOTerm->zName;
danielk1977dc1bdc42004-06-11 10:51:27 +00001832 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
danielk1977dc1bdc42004-06-11 10:51:27 +00001833 if( zName ){
drh0342b1f2005-09-01 03:07:44 +00001834 *apColl = sqlite3LocateCollSeq(pParse, zName, -1);
danielk1977dc1bdc42004-06-11 10:51:27 +00001835 }else{
drh0342b1f2005-09-01 03:07:44 +00001836 *apColl = aCopy[pExpr->iColumn];
danielk1977dc1bdc42004-06-11 10:51:27 +00001837 }
drh4db38a72005-09-01 12:16:28 +00001838 *pSortOrder = pOTerm->sortOrder;
danielk1977dc1bdc42004-06-11 10:51:27 +00001839 }
drh0342b1f2005-09-01 03:07:44 +00001840 assert( p->pRightmost==p );
1841 assert( p->addrOpenVirt[2]>=0 );
1842 addr = p->addrOpenVirt[2];
drh4db38a72005-09-01 12:16:28 +00001843 sqlite3VdbeChangeP2(v, addr, p->pEList->nExpr+2);
drh4efc0832005-11-16 13:47:50 +00001844 pKeyInfo->nField = nOrderByExpr;
drh4db38a72005-09-01 12:16:28 +00001845 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
1846 pKeyInfo = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001847 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1848 }
1849
drh0342b1f2005-09-01 03:07:44 +00001850 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001851 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001852
1853multi_select_end:
danielk197784ac9d02004-05-18 09:58:06 +00001854 return rc;
drh22827922000-06-06 17:27:05 +00001855}
drhb7f91642004-10-31 02:22:47 +00001856#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drh22827922000-06-06 17:27:05 +00001857
drhb7f91642004-10-31 02:22:47 +00001858#ifndef SQLITE_OMIT_VIEW
drh22827922000-06-06 17:27:05 +00001859/*
drh832508b2002-03-02 17:04:07 +00001860** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001861** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001862** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001863** unchanged.)
drh832508b2002-03-02 17:04:07 +00001864**
1865** This routine is part of the flattening procedure. A subquery
1866** whose result set is defined by pEList appears as entry in the
1867** FROM clause of a SELECT such that the VDBE cursor assigned to that
1868** FORM clause entry is iTable. This routine make the necessary
1869** changes to pExpr so that it refers directly to the source table
1870** of the subquery rather the result set of the subquery.
1871*/
drh6a3ea0e2003-05-02 14:32:12 +00001872static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
danielk1977b3bce662005-01-29 08:32:43 +00001873static void substSelect(Select *, int, ExprList *); /* Forward Decl */
drh6a3ea0e2003-05-02 14:32:12 +00001874static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001875 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001876 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1877 if( pExpr->iColumn<0 ){
1878 pExpr->op = TK_NULL;
1879 }else{
1880 Expr *pNew;
1881 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1882 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1883 pNew = pEList->a[pExpr->iColumn].pExpr;
1884 assert( pNew!=0 );
1885 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001886 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001887 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001888 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001889 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001890 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001891 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001892 pExpr->iTable = pNew->iTable;
1893 pExpr->iColumn = pNew->iColumn;
1894 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001895 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1896 sqlite3TokenCopy(&pExpr->span, &pNew->span);
danielk1977a1cb1832005-02-12 08:59:55 +00001897 pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
1898 pExpr->flags = pNew->flags;
drh50350a12004-02-13 16:22:22 +00001899 }
drh832508b2002-03-02 17:04:07 +00001900 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001901 substExpr(pExpr->pLeft, iTable, pEList);
1902 substExpr(pExpr->pRight, iTable, pEList);
danielk1977b3bce662005-01-29 08:32:43 +00001903 substSelect(pExpr->pSelect, iTable, pEList);
drh6a3ea0e2003-05-02 14:32:12 +00001904 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001905 }
1906}
danielk1977b3bce662005-01-29 08:32:43 +00001907static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001908 int i;
1909 if( pList==0 ) return;
1910 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001911 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001912 }
1913}
danielk1977b3bce662005-01-29 08:32:43 +00001914static void substSelect(Select *p, int iTable, ExprList *pEList){
1915 if( !p ) return;
1916 substExprList(p->pEList, iTable, pEList);
1917 substExprList(p->pGroupBy, iTable, pEList);
1918 substExprList(p->pOrderBy, iTable, pEList);
1919 substExpr(p->pHaving, iTable, pEList);
1920 substExpr(p->pWhere, iTable, pEList);
1921}
drhb7f91642004-10-31 02:22:47 +00001922#endif /* !defined(SQLITE_OMIT_VIEW) */
drh832508b2002-03-02 17:04:07 +00001923
drhb7f91642004-10-31 02:22:47 +00001924#ifndef SQLITE_OMIT_VIEW
drh832508b2002-03-02 17:04:07 +00001925/*
drh1350b032002-02-27 19:00:20 +00001926** This routine attempts to flatten subqueries in order to speed
1927** execution. It returns 1 if it makes changes and 0 if no flattening
1928** occurs.
1929**
1930** To understand the concept of flattening, consider the following
1931** query:
1932**
1933** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1934**
1935** The default way of implementing this query is to execute the
1936** subquery first and store the results in a temporary table, then
1937** run the outer query on that temporary table. This requires two
1938** passes over the data. Furthermore, because the temporary table
1939** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001940** optimized.
drh1350b032002-02-27 19:00:20 +00001941**
drh832508b2002-03-02 17:04:07 +00001942** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001943** a single flat select, like this:
1944**
1945** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1946**
1947** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001948** but only has to scan the data once. And because indices might
1949** exist on the table t1, a complete scan of the data might be
1950** avoided.
drh1350b032002-02-27 19:00:20 +00001951**
drh832508b2002-03-02 17:04:07 +00001952** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001953**
drh832508b2002-03-02 17:04:07 +00001954** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001955**
drh832508b2002-03-02 17:04:07 +00001956** (2) The subquery is not an aggregate or the outer query is not a join.
1957**
drh8af4d3a2003-05-06 20:35:16 +00001958** (3) The subquery is not the right operand of a left outer join, or
1959** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001960**
1961** (4) The subquery is not DISTINCT or the outer query is not a join.
1962**
1963** (5) The subquery is not DISTINCT or the outer query does not use
1964** aggregates.
1965**
1966** (6) The subquery does not use aggregates or the outer query is not
1967** DISTINCT.
1968**
drh08192d52002-04-30 19:20:28 +00001969** (7) The subquery has a FROM clause.
1970**
drhdf199a22002-06-14 22:38:41 +00001971** (8) The subquery does not use LIMIT or the outer query is not a join.
1972**
1973** (9) The subquery does not use LIMIT or the outer query does not use
1974** aggregates.
1975**
1976** (10) The subquery does not use aggregates or the outer query does not
1977** use LIMIT.
1978**
drh174b6192002-12-03 02:22:52 +00001979** (11) The subquery and the outer query do not both have ORDER BY clauses.
1980**
drh3fc673e2003-06-16 00:40:34 +00001981** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1982** subquery has no WHERE clause. (added by ticket #350)
1983**
drh832508b2002-03-02 17:04:07 +00001984** In this routine, the "p" parameter is a pointer to the outer query.
1985** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1986** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1987**
drh665de472003-03-31 13:36:09 +00001988** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001989** If flattening is attempted this routine returns 1.
1990**
1991** All of the expression analysis must occur on both the outer query and
1992** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001993*/
drh8c74a8c2002-08-25 19:20:40 +00001994static int flattenSubquery(
1995 Parse *pParse, /* The parsing context */
1996 Select *p, /* The parent or outer SELECT statement */
1997 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1998 int isAgg, /* True if outer SELECT uses aggregate functions */
1999 int subqueryIsAgg /* True if the subquery uses aggregate functions */
2000){
drh0bb28102002-05-08 11:54:14 +00002001 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00002002 SrcList *pSrc; /* The FROM clause of the outer query */
2003 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00002004 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00002005 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh91bb0ee2004-09-01 03:06:34 +00002006 int i; /* Loop counter */
2007 Expr *pWhere; /* The WHERE clause */
2008 struct SrcList_item *pSubitem; /* The subquery */
drh1350b032002-02-27 19:00:20 +00002009
drh832508b2002-03-02 17:04:07 +00002010 /* Check to see if flattening is permitted. Return 0 if not.
2011 */
2012 if( p==0 ) return 0;
2013 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00002014 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh91bb0ee2004-09-01 03:06:34 +00002015 pSubitem = &pSrc->a[iFrom];
2016 pSub = pSubitem->pSelect;
drh832508b2002-03-02 17:04:07 +00002017 assert( pSub!=0 );
2018 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00002019 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00002020 pSubSrc = pSub->pSrc;
2021 assert( pSubSrc );
danielk1977a2dc3b12005-02-05 12:48:48 +00002022 if( (pSub->pLimit && p->pLimit) || pSub->pOffset ||
2023 (pSub->pLimit && isAgg) ) return 0;
drhc31c2eb2003-05-02 16:04:17 +00002024 if( pSubSrc->nSrc==0 ) return 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00002025 if( pSub->isDistinct && (pSrc->nSrc>1 || isAgg) ){
drhdf199a22002-06-14 22:38:41 +00002026 return 0;
2027 }
danielk1977a2dc3b12005-02-05 12:48:48 +00002028 if( p->isDistinct && subqueryIsAgg ) return 0;
drh4b14b4d2005-09-19 17:35:53 +00002029 if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00002030
drh8af4d3a2003-05-06 20:35:16 +00002031 /* Restriction 3: If the subquery is a join, make sure the subquery is
2032 ** not used as the right operand of an outer join. Examples of why this
2033 ** is not allowed:
2034 **
2035 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
2036 **
2037 ** If we flatten the above, we would get
2038 **
2039 ** (t1 LEFT OUTER JOIN t2) JOIN t3
2040 **
2041 ** which is not at all the same thing.
2042 */
2043 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
2044 return 0;
2045 }
2046
drh3fc673e2003-06-16 00:40:34 +00002047 /* Restriction 12: If the subquery is the right operand of a left outer
2048 ** join, make sure the subquery has no WHERE clause.
2049 ** An examples of why this is not allowed:
2050 **
2051 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
2052 **
2053 ** If we flatten the above, we would get
2054 **
2055 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
2056 **
2057 ** But the t2.x>0 test will always fail on a NULL row of t2, which
2058 ** effectively converts the OUTER JOIN into an INNER JOIN.
2059 */
2060 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
2061 && pSub->pWhere!=0 ){
2062 return 0;
2063 }
2064
drh0bb28102002-05-08 11:54:14 +00002065 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00002066 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00002067 */
drhc31c2eb2003-05-02 16:04:17 +00002068
2069 /* Move all of the FROM elements of the subquery into the
2070 ** the FROM clause of the outer query. Before doing this, remember
2071 ** the cursor number for the original outer query FROM element in
2072 ** iParent. The iParent cursor will never be used. Subsequent code
2073 ** will scan expressions looking for iParent references and replace
2074 ** those references with expressions that resolve to the subquery FROM
2075 ** elements we are now copying in.
2076 */
drh91bb0ee2004-09-01 03:06:34 +00002077 iParent = pSubitem->iCursor;
drhc31c2eb2003-05-02 16:04:17 +00002078 {
2079 int nSubSrc = pSubSrc->nSrc;
drh91bb0ee2004-09-01 03:06:34 +00002080 int jointype = pSubitem->jointype;
drhc31c2eb2003-05-02 16:04:17 +00002081
drhed8a3bb2005-06-06 21:19:56 +00002082 sqlite3DeleteTable(0, pSubitem->pTab);
drh91bb0ee2004-09-01 03:06:34 +00002083 sqliteFree(pSubitem->zDatabase);
2084 sqliteFree(pSubitem->zName);
2085 sqliteFree(pSubitem->zAlias);
drhc31c2eb2003-05-02 16:04:17 +00002086 if( nSubSrc>1 ){
2087 int extra = nSubSrc - 1;
2088 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00002089 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00002090 }
2091 p->pSrc = pSrc;
2092 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2093 pSrc->a[i] = pSrc->a[i-extra];
2094 }
2095 }
2096 for(i=0; i<nSubSrc; i++){
2097 pSrc->a[i+iFrom] = pSubSrc->a[i];
2098 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2099 }
drh8af4d3a2003-05-06 20:35:16 +00002100 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00002101 }
2102
2103 /* Now begin substituting subquery result set expressions for
2104 ** references to the iParent in the outer query.
2105 **
2106 ** Example:
2107 **
2108 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2109 ** \ \_____________ subquery __________/ /
2110 ** \_____________________ outer query ______________________________/
2111 **
2112 ** We look at every expression in the outer query and every place we see
2113 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2114 */
drh6a3ea0e2003-05-02 14:32:12 +00002115 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00002116 pList = p->pEList;
2117 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00002118 Expr *pExpr;
2119 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
drh2646da72005-12-09 20:02:05 +00002120 pList->a[i].zName = sqliteStrNDup((char*)pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00002121 }
2122 }
drh1b2e0322002-03-03 02:49:51 +00002123 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00002124 substExprList(p->pGroupBy, iParent, pSub->pEList);
2125 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00002126 }
drh174b6192002-12-03 02:22:52 +00002127 if( pSub->pOrderBy ){
2128 assert( p->pOrderBy==0 );
2129 p->pOrderBy = pSub->pOrderBy;
2130 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00002131 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00002132 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00002133 }
drh832508b2002-03-02 17:04:07 +00002134 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002135 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00002136 }else{
2137 pWhere = 0;
2138 }
2139 if( subqueryIsAgg ){
2140 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00002141 p->pHaving = p->pWhere;
2142 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00002143 substExpr(p->pHaving, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002144 p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
drh1b2e0322002-03-03 02:49:51 +00002145 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00002146 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00002147 }else{
drh6a3ea0e2003-05-02 14:32:12 +00002148 substExpr(p->pWhere, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002149 p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
drh832508b2002-03-02 17:04:07 +00002150 }
drhc31c2eb2003-05-02 16:04:17 +00002151
2152 /* The flattened query is distinct if either the inner or the
2153 ** outer query is distinct.
2154 */
drh832508b2002-03-02 17:04:07 +00002155 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00002156
danielk1977a58fdfb2005-02-08 07:50:40 +00002157 /*
2158 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2159 */
danielk1977a2dc3b12005-02-05 12:48:48 +00002160 if( pSub->pLimit ){
2161 p->pLimit = pSub->pLimit;
2162 pSub->pLimit = 0;
drhdf199a22002-06-14 22:38:41 +00002163 }
drh8c74a8c2002-08-25 19:20:40 +00002164
drhc31c2eb2003-05-02 16:04:17 +00002165 /* Finially, delete what is left of the subquery and return
2166 ** success.
2167 */
danielk19774adee202004-05-08 08:23:19 +00002168 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00002169 return 1;
2170}
drhb7f91642004-10-31 02:22:47 +00002171#endif /* SQLITE_OMIT_VIEW */
drh1350b032002-02-27 19:00:20 +00002172
2173/*
drh9562b552002-02-19 15:00:07 +00002174** Analyze the SELECT statement passed in as an argument to see if it
2175** is a simple min() or max() query. If it is and this query can be
2176** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00002177** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00002178** simple min() or max() query, then return 0;
2179**
2180** A simply min() or max() query looks like this:
2181**
2182** SELECT min(a) FROM table;
2183** SELECT max(a) FROM table;
2184**
2185** The query may have only a single table in its FROM argument. There
2186** can be no GROUP BY or HAVING or WHERE clauses. The result set must
2187** be the min() or max() of a single column of the table. The column
2188** in the min() or max() function must be indexed.
2189**
danielk19774adee202004-05-08 08:23:19 +00002190** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00002191** See the header comment on that routine for additional information.
2192*/
2193static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2194 Expr *pExpr;
2195 int iCol;
2196 Table *pTab;
2197 Index *pIdx;
2198 int base;
2199 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00002200 int seekOp;
drh6e175292004-03-13 14:00:36 +00002201 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00002202 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00002203 SrcList *pSrc;
drhec7429a2005-10-06 16:53:14 +00002204 int brk;
danielk1977da184232006-01-05 11:34:32 +00002205 int iDb;
drh9562b552002-02-19 15:00:07 +00002206
2207 /* Check to see if this query is a simple min() or max() query. Return
2208 ** zero if it is not.
2209 */
2210 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00002211 pSrc = p->pSrc;
2212 if( pSrc->nSrc!=1 ) return 0;
2213 pEList = p->pEList;
2214 if( pEList->nExpr!=1 ) return 0;
2215 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002216 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002217 pList = pExpr->pList;
2218 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002219 if( pExpr->token.n!=3 ) return 0;
drh2646da72005-12-09 20:02:05 +00002220 if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002221 seekOp = OP_Rewind;
drh2646da72005-12-09 20:02:05 +00002222 }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002223 seekOp = OP_Last;
2224 }else{
2225 return 0;
2226 }
drh6e175292004-03-13 14:00:36 +00002227 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002228 if( pExpr->op!=TK_COLUMN ) return 0;
2229 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002230 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002231
2232 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002233 ** Check to make sure we have an index and make pIdx point to the
2234 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2235 ** key column, no index is necessary so set pIdx to NULL. If no
2236 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002237 */
2238 if( iCol<0 ){
2239 pIdx = 0;
2240 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002241 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002242 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2243 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002244 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002245 }
2246 if( pIdx==0 ) return 0;
2247 }
2248
drhe5f50722003-07-19 00:44:14 +00002249 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002250 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002251 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002252 */
danielk19774adee202004-05-08 08:23:19 +00002253 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002254 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002255
drh0c37e632004-01-30 02:01:03 +00002256 /* If the output is destined for a temporary table, open that table.
2257 */
drh9d2985c2005-09-08 01:58:42 +00002258 if( eDest==SRT_VirtualTab ){
drhd81bd4e2005-09-05 20:06:49 +00002259 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002260 }
2261
drh17f71932002-02-21 12:01:27 +00002262 /* Generating code to find the min or the max. Basically all we have
2263 ** to do is find the first or the last entry in the chosen index. If
2264 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2265 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002266 */
danielk1977da184232006-01-05 11:34:32 +00002267 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2268 sqlite3CodeVerifySchema(pParse, iDb);
drh6e175292004-03-13 14:00:36 +00002269 base = pSrc->a[0].iCursor;
drhec7429a2005-10-06 16:53:14 +00002270 brk = sqlite3VdbeMakeLabel(v);
2271 computeLimitRegisters(pParse, p, brk);
drh6e175292004-03-13 14:00:36 +00002272 if( pSrc->a[0].pSelect==0 ){
danielk1977da184232006-01-05 11:34:32 +00002273 sqlite3OpenTableForReading(v, base, iDb, pTab);
drh6e175292004-03-13 14:00:36 +00002274 }
drh9562b552002-02-19 15:00:07 +00002275 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002276 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002277 }else{
danielk19773719d7f2005-01-17 08:57:09 +00002278 /* Even though the cursor used to open the index here is closed
2279 ** as soon as a single value has been read from it, allocate it
2280 ** using (pParse->nTab++) to prevent the cursor id from being
2281 ** reused. This is important for statements of the form
2282 ** "INSERT INTO x SELECT max() FROM x".
2283 */
2284 int iIdx;
2285 iIdx = pParse->nTab++;
danielk1977da184232006-01-05 11:34:32 +00002286 assert( pIdx->pSchema==pTab->pSchema );
2287 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002288 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
drhd3d39e92004-05-20 22:16:29 +00002289 (char*)&pIdx->keyInfo, P3_KEYINFO);
drh9eb516c2004-07-18 20:52:32 +00002290 if( seekOp==OP_Rewind ){
drhf0863fe2005-06-12 21:35:51 +00002291 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh1af3fdb2004-07-18 21:33:01 +00002292 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2293 seekOp = OP_MoveGt;
drh9eb516c2004-07-18 20:52:32 +00002294 }
danielk19773719d7f2005-01-17 08:57:09 +00002295 sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
drhf0863fe2005-06-12 21:35:51 +00002296 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002297 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002298 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002299 }
drh5cf8e8c2002-02-19 22:42:05 +00002300 eList.nExpr = 1;
2301 memset(&eListItem, 0, sizeof(eListItem));
2302 eList.a = &eListItem;
2303 eList.a[0].pExpr = pExpr;
drhec7429a2005-10-06 16:53:14 +00002304 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0);
2305 sqlite3VdbeResolveLabel(v, brk);
danielk19774adee202004-05-08 08:23:19 +00002306 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002307
drh9562b552002-02-19 15:00:07 +00002308 return 1;
2309}
2310
2311/*
drh290c1942004-08-21 17:54:45 +00002312** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
2313** the number of errors seen.
2314**
2315** An ORDER BY or GROUP BY is a list of expressions. If any expression
2316** is an integer constant, then that expression is replaced by the
2317** corresponding entry in the result set.
2318*/
2319static int processOrderGroupBy(
danielk1977b3bce662005-01-29 08:32:43 +00002320 NameContext *pNC, /* Name context of the SELECT statement. */
drh290c1942004-08-21 17:54:45 +00002321 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
drh290c1942004-08-21 17:54:45 +00002322 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
2323){
2324 int i;
danielk1977b3bce662005-01-29 08:32:43 +00002325 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */
2326 Parse *pParse = pNC->pParse; /* The result set of the SELECT */
2327 assert( pEList );
2328
drh290c1942004-08-21 17:54:45 +00002329 if( pOrderBy==0 ) return 0;
2330 for(i=0; i<pOrderBy->nExpr; i++){
2331 int iCol;
2332 Expr *pE = pOrderBy->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +00002333 if( sqlite3ExprIsInteger(pE, &iCol) ){
2334 if( iCol>0 && iCol<=pEList->nExpr ){
2335 sqlite3ExprDelete(pE);
2336 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2337 }else{
drh290c1942004-08-21 17:54:45 +00002338 sqlite3ErrorMsg(pParse,
2339 "%s BY column number %d out of range - should be "
2340 "between 1 and %d", zType, iCol, pEList->nExpr);
2341 return 1;
2342 }
2343 }
danielk1977b3bce662005-01-29 08:32:43 +00002344 if( sqlite3ExprResolveNames(pNC, pE) ){
2345 return 1;
2346 }
2347 if( sqlite3ExprIsConstant(pE) ){
2348 sqlite3ErrorMsg(pParse,
2349 "%s BY terms must not be non-integer constants", zType);
2350 return 1;
2351 }
drh290c1942004-08-21 17:54:45 +00002352 }
2353 return 0;
2354}
2355
2356/*
danielk1977b3bce662005-01-29 08:32:43 +00002357** This routine resolves any names used in the result set of the
2358** supplied SELECT statement. If the SELECT statement being resolved
2359** is a sub-select, then pOuterNC is a pointer to the NameContext
2360** of the parent SELECT.
2361*/
2362int sqlite3SelectResolve(
2363 Parse *pParse, /* The parser context */
2364 Select *p, /* The SELECT statement being coded. */
2365 NameContext *pOuterNC /* The outer name context. May be NULL. */
2366){
2367 ExprList *pEList; /* Result set. */
2368 int i; /* For-loop variable used in multiple places */
2369 NameContext sNC; /* Local name-context */
drh13449892005-09-07 21:22:45 +00002370 ExprList *pGroupBy; /* The group by clause */
danielk1977b3bce662005-01-29 08:32:43 +00002371
2372 /* If this routine has run before, return immediately. */
2373 if( p->isResolved ){
2374 assert( !pOuterNC );
2375 return SQLITE_OK;
2376 }
2377 p->isResolved = 1;
2378
2379 /* If there have already been errors, do nothing. */
2380 if( pParse->nErr>0 ){
2381 return SQLITE_ERROR;
2382 }
2383
2384 /* Prepare the select statement. This call will allocate all cursors
2385 ** required to handle the tables and subqueries in the FROM clause.
2386 */
2387 if( prepSelectStmt(pParse, p) ){
2388 return SQLITE_ERROR;
2389 }
2390
danielk1977a2dc3b12005-02-05 12:48:48 +00002391 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2392 ** are not allowed to refer to any names, so pass an empty NameContext.
2393 */
drhffe07b22005-11-03 00:41:17 +00002394 memset(&sNC, 0, sizeof(sNC));
danielk1977b3bce662005-01-29 08:32:43 +00002395 sNC.pParse = pParse;
danielk1977a2dc3b12005-02-05 12:48:48 +00002396 if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2397 sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2398 return SQLITE_ERROR;
2399 }
2400
2401 /* Set up the local name-context to pass to ExprResolveNames() to
2402 ** resolve the expression-list.
2403 */
2404 sNC.allowAgg = 1;
2405 sNC.pSrcList = p->pSrc;
2406 sNC.pNext = pOuterNC;
danielk1977b3bce662005-01-29 08:32:43 +00002407
danielk1977b3bce662005-01-29 08:32:43 +00002408 /* Resolve names in the result set. */
2409 pEList = p->pEList;
2410 if( !pEList ) return SQLITE_ERROR;
2411 for(i=0; i<pEList->nExpr; i++){
2412 Expr *pX = pEList->a[i].pExpr;
2413 if( sqlite3ExprResolveNames(&sNC, pX) ){
2414 return SQLITE_ERROR;
2415 }
2416 }
2417
2418 /* If there are no aggregate functions in the result-set, and no GROUP BY
2419 ** expression, do not allow aggregates in any of the other expressions.
2420 */
2421 assert( !p->isAgg );
drh13449892005-09-07 21:22:45 +00002422 pGroupBy = p->pGroupBy;
2423 if( pGroupBy || sNC.hasAgg ){
danielk1977b3bce662005-01-29 08:32:43 +00002424 p->isAgg = 1;
2425 }else{
2426 sNC.allowAgg = 0;
2427 }
2428
2429 /* If a HAVING clause is present, then there must be a GROUP BY clause.
2430 */
drh13449892005-09-07 21:22:45 +00002431 if( p->pHaving && !pGroupBy ){
danielk1977b3bce662005-01-29 08:32:43 +00002432 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2433 return SQLITE_ERROR;
2434 }
2435
2436 /* Add the expression list to the name-context before parsing the
2437 ** other expressions in the SELECT statement. This is so that
2438 ** expressions in the WHERE clause (etc.) can refer to expressions by
2439 ** aliases in the result set.
2440 **
2441 ** Minor point: If this is the case, then the expression will be
2442 ** re-evaluated for each reference to it.
2443 */
2444 sNC.pEList = p->pEList;
2445 if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2446 sqlite3ExprResolveNames(&sNC, p->pHaving) ||
2447 processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
drh13449892005-09-07 21:22:45 +00002448 processOrderGroupBy(&sNC, pGroupBy, "GROUP")
danielk1977b3bce662005-01-29 08:32:43 +00002449 ){
2450 return SQLITE_ERROR;
2451 }
2452
drh13449892005-09-07 21:22:45 +00002453 /* Make sure the GROUP BY clause does not contain aggregate functions.
2454 */
2455 if( pGroupBy ){
2456 struct ExprList_item *pItem;
2457
2458 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
2459 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
2460 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
2461 "the GROUP BY clause");
2462 return SQLITE_ERROR;
2463 }
2464 }
2465 }
2466
danielk1977b3bce662005-01-29 08:32:43 +00002467 return SQLITE_OK;
2468}
2469
2470/*
drh13449892005-09-07 21:22:45 +00002471** Reset the aggregate accumulator.
2472**
2473** The aggregate accumulator is a set of memory cells that hold
2474** intermediate results while calculating an aggregate. This
2475** routine simply stores NULLs in all of those memory cells.
danielk1977b3bce662005-01-29 08:32:43 +00002476*/
drh13449892005-09-07 21:22:45 +00002477static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
2478 Vdbe *v = pParse->pVdbe;
2479 int i;
drhc99130f2005-09-11 11:56:27 +00002480 struct AggInfo_func *pFunc;
drh13449892005-09-07 21:22:45 +00002481 if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
2482 return;
2483 }
drh13449892005-09-07 21:22:45 +00002484 for(i=0; i<pAggInfo->nColumn; i++){
drhd654be82005-09-20 17:42:23 +00002485 sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
drh13449892005-09-07 21:22:45 +00002486 }
drhc99130f2005-09-11 11:56:27 +00002487 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
drhd654be82005-09-20 17:42:23 +00002488 sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
drhc99130f2005-09-11 11:56:27 +00002489 if( pFunc->iDistinct>=0 ){
2490 Expr *pE = pFunc->pExpr;
2491 if( pE->pList==0 || pE->pList->nExpr!=1 ){
2492 sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
2493 "by an expression");
2494 pFunc->iDistinct = -1;
2495 }else{
2496 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
2497 sqlite3VdbeOp3(v, OP_OpenVirtual, pFunc->iDistinct, 0,
2498 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2499 }
2500 }
drh13449892005-09-07 21:22:45 +00002501 }
danielk1977b3bce662005-01-29 08:32:43 +00002502}
2503
2504/*
drh13449892005-09-07 21:22:45 +00002505** Invoke the OP_AggFinalize opcode for every aggregate function
2506** in the AggInfo structure.
danielk1977b3bce662005-01-29 08:32:43 +00002507*/
drh13449892005-09-07 21:22:45 +00002508static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
2509 Vdbe *v = pParse->pVdbe;
2510 int i;
2511 struct AggInfo_func *pF;
2512 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
drha10a34b2005-09-07 22:09:48 +00002513 ExprList *pList = pF->pExpr->pList;
2514 sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
2515 (void*)pF->pFunc, P3_FUNCDEF);
drh13449892005-09-07 21:22:45 +00002516 }
danielk1977b3bce662005-01-29 08:32:43 +00002517}
drh13449892005-09-07 21:22:45 +00002518
2519/*
2520** Update the accumulator memory cells for an aggregate based on
2521** the current cursor position.
2522*/
2523static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
2524 Vdbe *v = pParse->pVdbe;
2525 int i;
2526 struct AggInfo_func *pF;
2527 struct AggInfo_col *pC;
drh13449892005-09-07 21:22:45 +00002528
2529 pAggInfo->directMode = 1;
2530 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
2531 int nArg;
drhc99130f2005-09-11 11:56:27 +00002532 int addrNext = 0;
drh13449892005-09-07 21:22:45 +00002533 ExprList *pList = pF->pExpr->pList;
2534 if( pList ){
2535 nArg = pList->nExpr;
2536 sqlite3ExprCodeExprList(pParse, pList);
2537 }else{
2538 nArg = 0;
2539 }
drhc99130f2005-09-11 11:56:27 +00002540 if( pF->iDistinct>=0 ){
2541 addrNext = sqlite3VdbeMakeLabel(v);
2542 assert( nArg==1 );
drh9d4673a2005-09-12 23:03:16 +00002543 codeDistinct(v, pF->iDistinct, addrNext, 1, 2);
drhc99130f2005-09-11 11:56:27 +00002544 }
drh13449892005-09-07 21:22:45 +00002545 if( pF->pFunc->needCollSeq ){
2546 CollSeq *pColl = 0;
2547 struct ExprList_item *pItem;
2548 int j;
2549 for(j=0, pItem=pList->a; !pColl && j<pList->nExpr; j++, pItem++){
2550 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
2551 }
2552 if( !pColl ){
2553 pColl = pParse->db->pDfltColl;
2554 }
2555 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2556 }
2557 sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
drhc99130f2005-09-11 11:56:27 +00002558 if( addrNext ){
2559 sqlite3VdbeResolveLabel(v, addrNext);
2560 }
drh13449892005-09-07 21:22:45 +00002561 }
drh13449892005-09-07 21:22:45 +00002562 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
drh5774b802005-09-07 22:48:16 +00002563 sqlite3ExprCode(pParse, pC->pExpr);
drh13449892005-09-07 21:22:45 +00002564 sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
2565 }
2566 pAggInfo->directMode = 0;
2567}
2568
2569
danielk1977b3bce662005-01-29 08:32:43 +00002570/*
drh9bb61fe2000-06-05 16:01:39 +00002571** Generate code for the given SELECT statement.
2572**
drhfef52082000-06-06 01:50:43 +00002573** The results are distributed in various ways depending on the
2574** value of eDest and iParm.
2575**
2576** eDest Value Result
2577** ------------ -------------------------------------------
2578** SRT_Callback Invoke the callback for each row of the result.
2579**
2580** SRT_Mem Store first result in memory cell iParm
2581**
danielk1977e014a832004-05-17 10:48:57 +00002582** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002583**
drh82c3d632000-06-06 21:56:07 +00002584** SRT_Union Store results as a key in a temporary table iParm
2585**
jplyon4b11c6d2004-01-19 04:57:53 +00002586** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002587**
2588** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002589**
drhe78e8282003-01-19 03:59:45 +00002590** The table above is incomplete. Additional eDist value have be added
2591** since this comment was written. See the selectInnerLoop() function for
2592** a complete listing of the allowed values of eDest and their meanings.
2593**
drh9bb61fe2000-06-05 16:01:39 +00002594** This routine returns the number of errors. If any errors are
2595** encountered, then an appropriate error message is left in
2596** pParse->zErrMsg.
2597**
2598** This routine does NOT free the Select structure passed in. The
2599** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002600**
2601** The pParent, parentTab, and *pParentAgg fields are filled in if this
2602** SELECT is a subquery. This routine may try to combine this SELECT
2603** with its parent to form a single flat query. In so doing, it might
2604** change the parent query from a non-aggregate to an aggregate query.
2605** For that reason, the pParentAgg flag is passed as a pointer, so it
2606** can be changed.
drhe78e8282003-01-19 03:59:45 +00002607**
2608** Example 1: The meaning of the pParent parameter.
2609**
2610** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2611** \ \_______ subquery _______/ /
2612** \ /
2613** \____________________ outer query ___________________/
2614**
2615** This routine is called for the outer query first. For that call,
2616** pParent will be NULL. During the processing of the outer query, this
2617** routine is called recursively to handle the subquery. For the recursive
2618** call, pParent will point to the outer query. Because the subquery is
2619** the second element in a three-way join, the parentTab parameter will
2620** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002621*/
danielk19774adee202004-05-08 08:23:19 +00002622int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002623 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002624 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002625 int eDest, /* How to dispose of the results */
2626 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002627 Select *pParent, /* Another SELECT for which this is a sub-query */
2628 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002629 int *pParentAgg, /* True if pParent uses aggregate functions */
danielk1977b3bce662005-01-29 08:32:43 +00002630 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002631){
drh13449892005-09-07 21:22:45 +00002632 int i, j; /* Loop counters */
2633 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
2634 Vdbe *v; /* The virtual machine under construction */
danielk1977b3bce662005-01-29 08:32:43 +00002635 int isAgg; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002636 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002637 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002638 Expr *pWhere; /* The WHERE clause. May be NULL */
2639 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002640 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2641 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002642 int isDistinct; /* True if the DISTINCT keyword is present */
2643 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002644 int rc = 1; /* Value to return from this function */
drh9d2985c2005-09-08 01:58:42 +00002645 int addrSortIndex; /* Address of an OP_OpenVirtual instruction */
drh13449892005-09-07 21:22:45 +00002646 AggInfo sAggInfo; /* Information used by aggregate queries */
drhec7429a2005-10-06 16:53:14 +00002647 int iEnd; /* Address of the end of the query */
drh9bb61fe2000-06-05 16:01:39 +00002648
danielk1977261919c2005-12-06 12:52:59 +00002649 if( sqlite3Tsd()->mallocFailed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002650 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drh13449892005-09-07 21:22:45 +00002651 memset(&sAggInfo, 0, sizeof(sAggInfo));
drhdaffd0e2001-04-11 14:28:42 +00002652
drhb7f91642004-10-31 02:22:47 +00002653#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +00002654 /* If there is are a sequence of queries, do the earlier ones first.
2655 */
2656 if( p->pPrior ){
drh0342b1f2005-09-01 03:07:44 +00002657 if( p->pRightmost==0 ){
2658 Select *pLoop;
2659 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
2660 pLoop->pRightmost = p;
2661 }
2662 }
danielk197784ac9d02004-05-18 09:58:06 +00002663 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002664 }
drhb7f91642004-10-31 02:22:47 +00002665#endif
drh82c3d632000-06-06 21:56:07 +00002666
danielk1977b3bce662005-01-29 08:32:43 +00002667 pOrderBy = p->pOrderBy;
drh13449892005-09-07 21:22:45 +00002668 if( IgnorableOrderby(eDest) ){
danielk1977b3bce662005-01-29 08:32:43 +00002669 p->pOrderBy = 0;
2670 }
2671 if( sqlite3SelectResolve(pParse, p, 0) ){
2672 goto select_end;
2673 }
2674 p->pOrderBy = pOrderBy;
2675
drh82c3d632000-06-06 21:56:07 +00002676 /* Make local copies of the parameters for this query.
2677 */
drh9bb61fe2000-06-05 16:01:39 +00002678 pTabList = p->pSrc;
2679 pWhere = p->pWhere;
drh22827922000-06-06 17:27:05 +00002680 pGroupBy = p->pGroupBy;
2681 pHaving = p->pHaving;
danielk1977b3bce662005-01-29 08:32:43 +00002682 isAgg = p->isAgg;
drh19a775c2000-06-05 18:54:46 +00002683 isDistinct = p->isDistinct;
danielk1977b3bce662005-01-29 08:32:43 +00002684 pEList = p->pEList;
2685 if( pEList==0 ) goto select_end;
drh9bb61fe2000-06-05 16:01:39 +00002686
2687 /*
2688 ** Do not even attempt to generate any code if we have already seen
2689 ** errors before this routine starts.
2690 */
drh1d83f052002-02-17 00:30:36 +00002691 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002692
drh22827922000-06-06 17:27:05 +00002693 /* If writing to memory or generating a set
2694 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002695 */
danielk197793758c82005-01-21 08:13:14 +00002696#ifndef SQLITE_OMIT_SUBQUERY
drhfef52082000-06-06 01:50:43 +00002697 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002698 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002699 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002700 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002701 }
danielk197793758c82005-01-21 08:13:14 +00002702#endif
drh19a775c2000-06-05 18:54:46 +00002703
drhc926afb2002-06-20 03:38:26 +00002704 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002705 */
drh13449892005-09-07 21:22:45 +00002706 if( IgnorableOrderby(eDest) ){
2707 pOrderBy = 0;
drh22827922000-06-06 17:27:05 +00002708 }
2709
drhd820cb12002-02-18 03:21:45 +00002710 /* Begin generating code.
2711 */
danielk19774adee202004-05-08 08:23:19 +00002712 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002713 if( v==0 ) goto select_end;
2714
drhe78e8282003-01-19 03:59:45 +00002715 /* Identify column names if we will be using them in a callback. This
2716 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002717 */
2718 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002719 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002720 }
2721
drhd820cb12002-02-18 03:21:45 +00002722 /* Generate code for all sub-queries in the FROM clause
2723 */
drh51522cd2005-01-20 13:36:19 +00002724#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
drhad3cab52002-05-24 02:04:32 +00002725 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002726 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002727 int needRestoreContext;
drh13449892005-09-07 21:22:45 +00002728 struct SrcList_item *pItem = &pTabList->a[i];
drhc31c2eb2003-05-02 16:04:17 +00002729
drh13449892005-09-07 21:22:45 +00002730 if( pItem->pSelect==0 ) continue;
2731 if( pItem->zName!=0 ){
drh5cf590c2003-04-24 01:45:04 +00002732 zSavedAuthContext = pParse->zAuthContext;
drh13449892005-09-07 21:22:45 +00002733 pParse->zAuthContext = pItem->zName;
drhc31c2eb2003-05-02 16:04:17 +00002734 needRestoreContext = 1;
2735 }else{
2736 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002737 }
drh9d2985c2005-09-08 01:58:42 +00002738 sqlite3Select(pParse, pItem->pSelect, SRT_VirtualTab,
drh13449892005-09-07 21:22:45 +00002739 pItem->iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002740 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002741 pParse->zAuthContext = zSavedAuthContext;
2742 }
drh1b2e0322002-03-03 02:49:51 +00002743 pTabList = p->pSrc;
2744 pWhere = p->pWhere;
drh13449892005-09-07 21:22:45 +00002745 if( !IgnorableOrderby(eDest) ){
drhacd4c692002-03-07 02:02:51 +00002746 pOrderBy = p->pOrderBy;
2747 }
drh1b2e0322002-03-03 02:49:51 +00002748 pGroupBy = p->pGroupBy;
2749 pHaving = p->pHaving;
2750 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002751 }
drh51522cd2005-01-20 13:36:19 +00002752#endif
drhd820cb12002-02-18 03:21:45 +00002753
drh6e175292004-03-13 14:00:36 +00002754 /* Check for the special case of a min() or max() function by itself
2755 ** in the result set.
2756 */
2757 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2758 rc = 0;
2759 goto select_end;
2760 }
2761
drh832508b2002-03-02 17:04:07 +00002762 /* Check to see if this is a subquery that can be "flattened" into its parent.
2763 ** If flattening is a possiblity, do so and return immediately.
2764 */
drhb7f91642004-10-31 02:22:47 +00002765#ifndef SQLITE_OMIT_VIEW
drh1b2e0322002-03-03 02:49:51 +00002766 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002767 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002768 if( isAgg ) *pParentAgg = 1;
danielk1977b3bce662005-01-29 08:32:43 +00002769 goto select_end;
drh832508b2002-03-02 17:04:07 +00002770 }
drhb7f91642004-10-31 02:22:47 +00002771#endif
drh832508b2002-03-02 17:04:07 +00002772
danielk19777cedc8d2004-06-10 10:50:08 +00002773 /* If there is an ORDER BY clause, resolve any collation sequences
drh9d2985c2005-09-08 01:58:42 +00002774 ** names that have been explicitly specified and create a sorting index.
2775 **
2776 ** This sorting index might end up being unused if the data can be
2777 ** extracted in pre-sorted order. If that is the case, then the
2778 ** OP_OpenVirtual instruction will be changed to an OP_Noop once
2779 ** we figure out that the sorting index is not needed. The addrSortIndex
2780 ** variable is used to facilitate that change.
danielk19777cedc8d2004-06-10 10:50:08 +00002781 */
2782 if( pOrderBy ){
drh5d9a4af2005-08-30 00:54:01 +00002783 struct ExprList_item *pTerm;
drh0342b1f2005-09-01 03:07:44 +00002784 KeyInfo *pKeyInfo;
drh5d9a4af2005-08-30 00:54:01 +00002785 for(i=0, pTerm=pOrderBy->a; i<pOrderBy->nExpr; i++, pTerm++){
2786 if( pTerm->zName ){
2787 pTerm->pExpr->pColl = sqlite3LocateCollSeq(pParse, pTerm->zName, -1);
danielk19777cedc8d2004-06-10 10:50:08 +00002788 }
2789 }
2790 if( pParse->nErr ){
2791 goto select_end;
2792 }
drh0342b1f2005-09-01 03:07:44 +00002793 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
drh9d2985c2005-09-08 01:58:42 +00002794 pOrderBy->iECursor = pParse->nTab++;
2795 p->addrOpenVirt[2] = addrSortIndex =
2796 sqlite3VdbeOp3(v, OP_OpenVirtual, pOrderBy->iECursor, pOrderBy->nExpr+2,
drh0342b1f2005-09-01 03:07:44 +00002797 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drh9d2985c2005-09-08 01:58:42 +00002798 }else{
2799 addrSortIndex = -1;
danielk19777cedc8d2004-06-10 10:50:08 +00002800 }
2801
drh7b58dae2003-07-20 01:16:46 +00002802 /* Set the limiter.
2803 */
drhec7429a2005-10-06 16:53:14 +00002804 iEnd = sqlite3VdbeMakeLabel(v);
2805 computeLimitRegisters(pParse, p, iEnd);
drh7b58dae2003-07-20 01:16:46 +00002806
drh2d0794e2002-03-03 03:03:52 +00002807 /* If the output is destined for a temporary table, open that table.
2808 */
drh9d2985c2005-09-08 01:58:42 +00002809 if( eDest==SRT_VirtualTab ){
drh0342b1f2005-09-01 03:07:44 +00002810 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002811 }
2812
drhdece1a82005-08-31 18:20:00 +00002813 /* Open a virtual index to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002814 */
drh19a775c2000-06-05 18:54:46 +00002815 if( isDistinct ){
drh0342b1f2005-09-01 03:07:44 +00002816 KeyInfo *pKeyInfo;
drh832508b2002-03-02 17:04:07 +00002817 distinct = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00002818 pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
2819 sqlite3VdbeOp3(v, OP_OpenVirtual, distinct, 0,
2820 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drh832508b2002-03-02 17:04:07 +00002821 }else{
2822 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002823 }
drh832508b2002-03-02 17:04:07 +00002824
drh13449892005-09-07 21:22:45 +00002825 /* Aggregate and non-aggregate queries are handled differently */
2826 if( !isAgg && pGroupBy==0 ){
2827 /* This case is for non-aggregate queries
2828 ** Begin the database scan
2829 */
2830 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
2831 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002832
drh9d2985c2005-09-08 01:58:42 +00002833 /* If sorting index that was created by a prior OP_OpenVirtual
2834 ** instruction ended up not being needed, then change the OP_OpenVirtual
2835 ** into an OP_Noop.
2836 */
2837 if( addrSortIndex>=0 && pOrderBy==0 ){
2838 uncreateSortingIndex(pParse, addrSortIndex);
2839 p->addrOpenVirt[2] = -1;
2840 }
2841
drh13449892005-09-07 21:22:45 +00002842 /* Use the standard inner loop
2843 */
drhdf199a22002-06-14 22:38:41 +00002844 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002845 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002846 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002847 }
drhefb72512000-05-31 20:00:52 +00002848
drh13449892005-09-07 21:22:45 +00002849 /* End the database scan loop.
2850 */
2851 sqlite3WhereEnd(pWInfo);
2852 }else{
2853 /* This is the processing for aggregate queries */
2854 NameContext sNC; /* Name context for processing aggregate information */
2855 int iAMem; /* First Mem address for storing current GROUP BY */
2856 int iBMem; /* First Mem address for previous GROUP BY */
2857 int iUseFlag; /* Mem address holding flag indicating that at least
2858 ** one row of the input to the aggregator has been
2859 ** processed */
2860 int iAbortFlag; /* Mem address which causes query abort if positive */
2861 int groupBySort; /* Rows come from source in GROUP BY order */
drhcce7d172000-05-31 15:34:51 +00002862
drhcce7d172000-05-31 15:34:51 +00002863
drh13449892005-09-07 21:22:45 +00002864 /* The following variables hold addresses or labels for parts of the
2865 ** virtual machine program we are putting together */
2866 int addrOutputRow; /* Start of subroutine that outputs a result row */
2867 int addrSetAbort; /* Set the abort flag and return */
2868 int addrInitializeLoop; /* Start of code that initializes the input loop */
2869 int addrTopOfLoop; /* Top of the input loop */
2870 int addrGroupByChange; /* Code that runs when any GROUP BY term changes */
2871 int addrProcessRow; /* Code to process a single input row */
2872 int addrEnd; /* End of all processing */
2873 int addrSortingIdx; /* The OP_OpenVirtual for the sorting index */
drhe3133822005-09-20 13:11:59 +00002874 int addrReset; /* Subroutine for resetting the accumulator */
drh13449892005-09-07 21:22:45 +00002875
2876 addrEnd = sqlite3VdbeMakeLabel(v);
2877
2878 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
2879 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
2880 ** SELECT statement.
2881 */
2882 memset(&sNC, 0, sizeof(sNC));
2883 sNC.pParse = pParse;
2884 sNC.pSrcList = pTabList;
2885 sNC.pAggInfo = &sAggInfo;
2886 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
drh9d2985c2005-09-08 01:58:42 +00002887 sAggInfo.pGroupBy = pGroupBy;
drh13449892005-09-07 21:22:45 +00002888 if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
drh1d83f052002-02-17 00:30:36 +00002889 goto select_end;
drh22827922000-06-06 17:27:05 +00002890 }
drh13449892005-09-07 21:22:45 +00002891 if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
2892 goto select_end;
2893 }
2894 if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
2895 goto select_end;
2896 }
2897 sAggInfo.nAccumulator = sAggInfo.nColumn;
2898 for(i=0; i<sAggInfo.nFunc; i++){
2899 if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
2900 goto select_end;
2901 }
2902 }
danielk1977261919c2005-12-06 12:52:59 +00002903 if( sqlite3Tsd()->mallocFailed ) goto select_end;
drh13449892005-09-07 21:22:45 +00002904
2905 /* Processing for aggregates with GROUP BY is very different and
2906 ** much more complex tha aggregates without a GROUP BY.
2907 */
2908 if( pGroupBy ){
2909 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
2910
2911 /* Create labels that we will be needing
2912 */
2913
2914 addrInitializeLoop = sqlite3VdbeMakeLabel(v);
2915 addrGroupByChange = sqlite3VdbeMakeLabel(v);
2916 addrProcessRow = sqlite3VdbeMakeLabel(v);
2917
2918 /* If there is a GROUP BY clause we might need a sorting index to
2919 ** implement it. Allocate that sorting index now. If it turns out
2920 ** that we do not need it after all, the OpenVirtual instruction
2921 ** will be converted into a Noop.
2922 */
2923 sAggInfo.sortingIdx = pParse->nTab++;
2924 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
2925 addrSortingIdx =
2926 sqlite3VdbeOp3(v, OP_OpenVirtual, sAggInfo.sortingIdx,
2927 sAggInfo.nSortingColumn,
2928 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2929
2930 /* Initialize memory locations used by GROUP BY aggregate processing
2931 */
2932 iUseFlag = pParse->nMem++;
2933 iAbortFlag = pParse->nMem++;
2934 iAMem = pParse->nMem;
2935 pParse->nMem += pGroupBy->nExpr;
2936 iBMem = pParse->nMem;
2937 pParse->nMem += pGroupBy->nExpr;
drhd654be82005-09-20 17:42:23 +00002938 sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
drhde29e3e2005-09-20 18:13:23 +00002939 VdbeComment((v, "# clear abort flag"));
drhd654be82005-09-20 17:42:23 +00002940 sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
drhde29e3e2005-09-20 18:13:23 +00002941 VdbeComment((v, "# indicate accumulator empty"));
drh13449892005-09-07 21:22:45 +00002942 sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
2943
2944 /* Generate a subroutine that outputs a single row of the result
2945 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
2946 ** is less than or equal to zero, the subroutine is a no-op. If
2947 ** the processing calls for the query to abort, this subroutine
2948 ** increments the iAbortFlag memory location before returning in
2949 ** order to signal the caller to abort.
2950 */
2951 addrSetAbort = sqlite3VdbeCurrentAddr(v);
drhde29e3e2005-09-20 18:13:23 +00002952 sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag);
2953 VdbeComment((v, "# set abort flag"));
drh13449892005-09-07 21:22:45 +00002954 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2955 addrOutputRow = sqlite3VdbeCurrentAddr(v);
2956 sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
drhde29e3e2005-09-20 18:13:23 +00002957 VdbeComment((v, "# Groupby result generator entry point"));
drh13449892005-09-07 21:22:45 +00002958 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2959 finalizeAggFunctions(pParse, &sAggInfo);
2960 if( pHaving ){
2961 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
2962 }
2963 rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
2964 distinct, eDest, iParm,
2965 addrOutputRow+1, addrSetAbort, aff);
2966 if( rc ){
2967 goto select_end;
2968 }
2969 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
drhde29e3e2005-09-20 18:13:23 +00002970 VdbeComment((v, "# end groupby result generator"));
drh13449892005-09-07 21:22:45 +00002971
drhe3133822005-09-20 13:11:59 +00002972 /* Generate a subroutine that will reset the group-by accumulator
2973 */
2974 addrReset = sqlite3VdbeCurrentAddr(v);
2975 resetAccumulator(pParse, &sAggInfo);
2976 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2977
drh13449892005-09-07 21:22:45 +00002978 /* Begin a loop that will extract all source rows in GROUP BY order.
2979 ** This might involve two separate loops with an OP_Sort in between, or
2980 ** it might be a single loop that uses an index to extract information
2981 ** in the right order to begin with.
2982 */
2983 sqlite3VdbeResolveLabel(v, addrInitializeLoop);
drhe3133822005-09-20 13:11:59 +00002984 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
drh13449892005-09-07 21:22:45 +00002985 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
drh5360ad32005-09-08 00:13:27 +00002986 if( pWInfo==0 ) goto select_end;
drh13449892005-09-07 21:22:45 +00002987 if( pGroupBy==0 ){
2988 /* The optimizer is able to deliver rows in group by order so
2989 ** we do not have to sort. The OP_OpenVirtual table will be
2990 ** cancelled later because we still need to use the pKeyInfo
2991 */
2992 pGroupBy = p->pGroupBy;
2993 groupBySort = 0;
2994 }else{
2995 /* Rows are coming out in undetermined order. We have to push
2996 ** each row into a sorting index, terminate the first loop,
2997 ** then loop over the sorting index in order to get the output
2998 ** in sorted order
2999 */
3000 groupBySort = 1;
3001 sqlite3ExprCodeExprList(pParse, pGroupBy);
3002 sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
3003 j = pGroupBy->nExpr+1;
3004 for(i=0; i<sAggInfo.nColumn; i++){
3005 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
3006 if( pCol->iSorterColumn<j ) continue;
3007 if( pCol->iColumn<0 ){
3008 sqlite3VdbeAddOp(v, OP_Rowid, pCol->iTable, 0);
3009 }else{
3010 sqlite3VdbeAddOp(v, OP_Column, pCol->iTable, pCol->iColumn);
3011 }
3012 j++;
3013 }
3014 sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
3015 sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
3016 sqlite3WhereEnd(pWInfo);
drh97571952005-09-08 12:57:28 +00003017 sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
drhde29e3e2005-09-20 18:13:23 +00003018 VdbeComment((v, "# GROUP BY sort"));
drh13449892005-09-07 21:22:45 +00003019 sAggInfo.useSortingIdx = 1;
3020 }
3021
3022 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
3023 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
3024 ** Then compare the current GROUP BY terms against the GROUP BY terms
3025 ** from the previous row currently stored in a0, a1, a2...
3026 */
3027 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
3028 for(j=0; j<pGroupBy->nExpr; j++){
3029 if( groupBySort ){
3030 sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
3031 }else{
3032 sAggInfo.directMode = 1;
3033 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
3034 }
3035 sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
3036 }
3037 for(j=pGroupBy->nExpr-1; j>=0; j--){
3038 if( j<pGroupBy->nExpr-1 ){
3039 sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
3040 }
3041 sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
3042 if( j==0 ){
drhe3133822005-09-20 13:11:59 +00003043 sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
drh13449892005-09-07 21:22:45 +00003044 }else{
drh4f686232005-09-20 13:55:18 +00003045 sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
drh13449892005-09-07 21:22:45 +00003046 }
3047 sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
3048 }
3049
3050 /* Generate code that runs whenever the GROUP BY changes.
3051 ** Change in the GROUP BY are detected by the previous code
3052 ** block. If there were no changes, this block is skipped.
3053 **
3054 ** This code copies current group by terms in b0,b1,b2,...
3055 ** over to a0,a1,a2. It then calls the output subroutine
3056 ** and resets the aggregate accumulator registers in preparation
3057 ** for the next GROUP BY batch.
3058 */
3059 sqlite3VdbeResolveLabel(v, addrGroupByChange);
3060 for(j=0; j<pGroupBy->nExpr; j++){
drhd654be82005-09-20 17:42:23 +00003061 sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
drh13449892005-09-07 21:22:45 +00003062 }
3063 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
drhde29e3e2005-09-20 18:13:23 +00003064 VdbeComment((v, "# output one row"));
drh13449892005-09-07 21:22:45 +00003065 sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
drhde29e3e2005-09-20 18:13:23 +00003066 VdbeComment((v, "# check abort flag"));
drhe3133822005-09-20 13:11:59 +00003067 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
drhde29e3e2005-09-20 18:13:23 +00003068 VdbeComment((v, "# reset accumulator"));
drh13449892005-09-07 21:22:45 +00003069
3070 /* Update the aggregate accumulators based on the content of
3071 ** the current row
3072 */
3073 sqlite3VdbeResolveLabel(v, addrProcessRow);
3074 updateAccumulator(pParse, &sAggInfo);
drhde29e3e2005-09-20 18:13:23 +00003075 sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag);
3076 VdbeComment((v, "# indicate data in accumulator"));
drh13449892005-09-07 21:22:45 +00003077
3078 /* End of the loop
3079 */
3080 if( groupBySort ){
3081 sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
3082 }else{
3083 sqlite3WhereEnd(pWInfo);
3084 uncreateSortingIndex(pParse, addrSortingIdx);
3085 }
3086
3087 /* Output the final row of result
3088 */
3089 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
drhde29e3e2005-09-20 18:13:23 +00003090 VdbeComment((v, "# output final row"));
drh13449892005-09-07 21:22:45 +00003091
3092 } /* endif pGroupBy */
3093 else {
3094 /* This case runs if the aggregate has no GROUP BY clause. The
3095 ** processing is much simpler since there is only a single row
3096 ** of output.
3097 */
3098 resetAccumulator(pParse, &sAggInfo);
3099 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
drh5360ad32005-09-08 00:13:27 +00003100 if( pWInfo==0 ) goto select_end;
drh13449892005-09-07 21:22:45 +00003101 updateAccumulator(pParse, &sAggInfo);
3102 sqlite3WhereEnd(pWInfo);
3103 finalizeAggFunctions(pParse, &sAggInfo);
3104 pOrderBy = 0;
drh5774b802005-09-07 22:48:16 +00003105 if( pHaving ){
3106 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
3107 }
drh13449892005-09-07 21:22:45 +00003108 selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
3109 eDest, iParm, addrEnd, addrEnd, aff);
3110 }
3111 sqlite3VdbeResolveLabel(v, addrEnd);
3112
3113 } /* endif aggregate query */
drh22827922000-06-06 17:27:05 +00003114
drhcce7d172000-05-31 15:34:51 +00003115 /* If there is an ORDER BY clause, then we need to sort the results
3116 ** and send them to the callback one by one.
3117 */
3118 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00003119 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00003120 }
drh6a535342001-10-19 16:44:56 +00003121
danielk197793758c82005-01-21 08:13:14 +00003122#ifndef SQLITE_OMIT_SUBQUERY
drhf620b4e2004-02-09 14:37:50 +00003123 /* If this was a subquery, we have now converted the subquery into a
3124 ** temporary table. So delete the subquery structure from the parent
3125 ** to prevent this subquery from being evaluated again and to force the
3126 ** the use of the temporary table.
3127 */
3128 if( pParent ){
3129 assert( pParent->pSrc->nSrc>parentTab );
3130 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00003131 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00003132 pParent->pSrc->a[parentTab].pSelect = 0;
3133 }
danielk197793758c82005-01-21 08:13:14 +00003134#endif
drhf620b4e2004-02-09 14:37:50 +00003135
drhec7429a2005-10-06 16:53:14 +00003136 /* Jump here to skip this query
3137 */
3138 sqlite3VdbeResolveLabel(v, iEnd);
3139
drh1d83f052002-02-17 00:30:36 +00003140 /* The SELECT was successfully coded. Set the return code to 0
3141 ** to indicate no errors.
3142 */
3143 rc = 0;
3144
3145 /* Control jumps to here if an error is encountered above, or upon
3146 ** successful coding of the SELECT.
3147 */
3148select_end:
drh13449892005-09-07 21:22:45 +00003149 sqliteFree(sAggInfo.aCol);
3150 sqliteFree(sAggInfo.aFunc);
drh1d83f052002-02-17 00:30:36 +00003151 return rc;
drhcce7d172000-05-31 15:34:51 +00003152}