blob: 5065be892a1f883dff8bbdbd386978ff065dedca [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**
drhd654be82005-09-20 17:42:23 +000015** $Id: select.c,v 1.275 2005/09/20 17:42:23 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
drh315555c2002-10-20 15:53:03 +000019
drhcce7d172000-05-31 15:34:51 +000020/*
drh9bb61fe2000-06-05 16:01:39 +000021** Allocate a new Select structure and return a pointer to that
22** structure.
drhcce7d172000-05-31 15:34:51 +000023*/
danielk19774adee202004-05-08 08:23:19 +000024Select *sqlite3SelectNew(
drhdaffd0e2001-04-11 14:28:42 +000025 ExprList *pEList, /* which columns to include in the result */
drhad3cab52002-05-24 02:04:32 +000026 SrcList *pSrc, /* the FROM clause -- which tables to scan */
drhdaffd0e2001-04-11 14:28:42 +000027 Expr *pWhere, /* the WHERE clause */
28 ExprList *pGroupBy, /* the GROUP BY clause */
29 Expr *pHaving, /* the HAVING clause */
30 ExprList *pOrderBy, /* the ORDER BY clause */
drh9bbca4c2001-11-06 04:00:18 +000031 int isDistinct, /* true if the DISTINCT keyword is present */
danielk1977a2dc3b12005-02-05 12:48:48 +000032 Expr *pLimit, /* LIMIT value. NULL means not used */
33 Expr *pOffset /* OFFSET value. NULL means no offset */
drh9bb61fe2000-06-05 16:01:39 +000034){
35 Select *pNew;
36 pNew = sqliteMalloc( sizeof(*pNew) );
danielk1977a2dc3b12005-02-05 12:48:48 +000037 assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */
drhdaffd0e2001-04-11 14:28:42 +000038 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +000039 sqlite3ExprListDelete(pEList);
40 sqlite3SrcListDelete(pSrc);
41 sqlite3ExprDelete(pWhere);
42 sqlite3ExprListDelete(pGroupBy);
43 sqlite3ExprDelete(pHaving);
44 sqlite3ExprListDelete(pOrderBy);
danielk1977a2dc3b12005-02-05 12:48:48 +000045 sqlite3ExprDelete(pLimit);
46 sqlite3ExprDelete(pOffset);
drhdaffd0e2001-04-11 14:28:42 +000047 }else{
drhb733d032004-01-24 20:18:12 +000048 if( pEList==0 ){
danielk19774adee202004-05-08 08:23:19 +000049 pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
drhb733d032004-01-24 20:18:12 +000050 }
drhdaffd0e2001-04-11 14:28:42 +000051 pNew->pEList = pEList;
52 pNew->pSrc = pSrc;
53 pNew->pWhere = pWhere;
54 pNew->pGroupBy = pGroupBy;
55 pNew->pHaving = pHaving;
56 pNew->pOrderBy = pOrderBy;
57 pNew->isDistinct = isDistinct;
58 pNew->op = TK_SELECT;
danielk1977a2dc3b12005-02-05 12:48:48 +000059 pNew->pLimit = pLimit;
60 pNew->pOffset = pOffset;
drh7b58dae2003-07-20 01:16:46 +000061 pNew->iLimit = -1;
62 pNew->iOffset = -1;
drh0342b1f2005-09-01 03:07:44 +000063 pNew->addrOpenVirt[0] = -1;
64 pNew->addrOpenVirt[1] = -1;
65 pNew->addrOpenVirt[2] = -1;
drhdaffd0e2001-04-11 14:28:42 +000066 }
drh9bb61fe2000-06-05 16:01:39 +000067 return pNew;
68}
69
70/*
drh01f3f252002-05-24 16:14:15 +000071** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
72** type of join. Return an integer constant that expresses that type
73** in terms of the following bit values:
74**
75** JT_INNER
drh3dec2232005-09-10 15:28:09 +000076** JT_CROSS
drh01f3f252002-05-24 16:14:15 +000077** JT_OUTER
78** JT_NATURAL
79** JT_LEFT
80** JT_RIGHT
81**
82** A full outer join is the combination of JT_LEFT and JT_RIGHT.
83**
84** If an illegal or unsupported join type is seen, then still return
85** a join type, but put an error in the pParse structure.
86*/
danielk19774adee202004-05-08 08:23:19 +000087int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
drh01f3f252002-05-24 16:14:15 +000088 int jointype = 0;
89 Token *apAll[3];
90 Token *p;
drh57196282004-10-06 15:41:16 +000091 static const struct {
drhc182d162005-08-14 20:47:16 +000092 const char zKeyword[8];
drh290c1942004-08-21 17:54:45 +000093 u8 nChar;
94 u8 code;
drh01f3f252002-05-24 16:14:15 +000095 } keywords[] = {
96 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000097 { "left", 4, JT_LEFT|JT_OUTER },
98 { "right", 5, JT_RIGHT|JT_OUTER },
99 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +0000100 { "outer", 5, JT_OUTER },
101 { "inner", 5, JT_INNER },
drh3dec2232005-09-10 15:28:09 +0000102 { "cross", 5, JT_INNER|JT_CROSS },
drh01f3f252002-05-24 16:14:15 +0000103 };
104 int i, j;
105 apAll[0] = pA;
106 apAll[1] = pB;
107 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +0000108 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +0000109 p = apAll[i];
110 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
111 if( p->n==keywords[j].nChar
danielk19774adee202004-05-08 08:23:19 +0000112 && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
drh01f3f252002-05-24 16:14:15 +0000113 jointype |= keywords[j].code;
114 break;
115 }
116 }
117 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
118 jointype |= JT_ERROR;
119 break;
120 }
121 }
drhad2d8302002-05-24 20:31:36 +0000122 if(
123 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000124 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000125 ){
drhae29ffb2004-09-25 14:39:18 +0000126 const char *zSp1 = " ";
127 const char *zSp2 = " ";
128 if( pB==0 ){ zSp1++; }
129 if( pC==0 ){ zSp2++; }
130 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
131 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
drh01f3f252002-05-24 16:14:15 +0000132 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000133 }else if( jointype & JT_RIGHT ){
danielk19774adee202004-05-08 08:23:19 +0000134 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000135 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000136 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000137 }
138 return jointype;
139}
140
141/*
drhad2d8302002-05-24 20:31:36 +0000142** Return the index of a column in a table. Return -1 if the column
143** is not contained in the table.
144*/
145static int columnIndex(Table *pTab, const char *zCol){
146 int i;
147 for(i=0; i<pTab->nCol; i++){
danielk19774adee202004-05-08 08:23:19 +0000148 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
drhad2d8302002-05-24 20:31:36 +0000149 }
150 return -1;
151}
152
153/*
drh91bb0ee2004-09-01 03:06:34 +0000154** Set the value of a token to a '\000'-terminated string.
155*/
156static void setToken(Token *p, const char *z){
157 p->z = z;
158 p->n = strlen(z);
159 p->dyn = 0;
160}
161
drhc182d162005-08-14 20:47:16 +0000162/*
163** Create an expression node for an identifier with the name of zName
164*/
165static Expr *createIdExpr(const char *zName){
166 Token dummy;
167 setToken(&dummy, zName);
168 return sqlite3Expr(TK_ID, 0, 0, &dummy);
169}
170
drh91bb0ee2004-09-01 03:06:34 +0000171
172/*
drhad2d8302002-05-24 20:31:36 +0000173** Add a term to the WHERE expression in *ppExpr that requires the
174** zCol column to be equal in the two tables pTab1 and pTab2.
175*/
176static void addWhereTerm(
177 const char *zCol, /* Name of the column */
178 const Table *pTab1, /* First table */
drh030530d2005-01-18 17:40:04 +0000179 const char *zAlias1, /* Alias for first table. May be NULL */
drhad2d8302002-05-24 20:31:36 +0000180 const Table *pTab2, /* Second table */
drh030530d2005-01-18 17:40:04 +0000181 const char *zAlias2, /* Alias for second table. May be NULL */
drh22d6a532005-09-19 21:05:48 +0000182 int iRightJoinTable, /* VDBE cursor for the right table */
drhad2d8302002-05-24 20:31:36 +0000183 Expr **ppExpr /* Add the equality term to this expression */
184){
drhad2d8302002-05-24 20:31:36 +0000185 Expr *pE1a, *pE1b, *pE1c;
186 Expr *pE2a, *pE2b, *pE2c;
187 Expr *pE;
188
drhc182d162005-08-14 20:47:16 +0000189 pE1a = createIdExpr(zCol);
190 pE2a = createIdExpr(zCol);
drh030530d2005-01-18 17:40:04 +0000191 if( zAlias1==0 ){
192 zAlias1 = pTab1->zName;
193 }
drhc182d162005-08-14 20:47:16 +0000194 pE1b = createIdExpr(zAlias1);
drh030530d2005-01-18 17:40:04 +0000195 if( zAlias2==0 ){
196 zAlias2 = pTab2->zName;
197 }
drhc182d162005-08-14 20:47:16 +0000198 pE2b = createIdExpr(zAlias2);
danielk19774adee202004-05-08 08:23:19 +0000199 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
200 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
201 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000202 ExprSetProperty(pE, EP_FromJoin);
drh22d6a532005-09-19 21:05:48 +0000203 pE->iRightJoinTable = iRightJoinTable;
drh91bb0ee2004-09-01 03:06:34 +0000204 *ppExpr = sqlite3ExprAnd(*ppExpr, pE);
drhad2d8302002-05-24 20:31:36 +0000205}
206
207/*
drh1f162302002-10-27 19:35:33 +0000208** Set the EP_FromJoin property on all terms of the given expression.
drh22d6a532005-09-19 21:05:48 +0000209** And set the Expr.iRightJoinTable to iTable for every term in the
210** expression.
drh1cc093c2002-06-24 22:01:57 +0000211**
drhe78e8282003-01-19 03:59:45 +0000212** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000213** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000214** join restriction specified in the ON or USING clause and not a part
215** of the more general WHERE clause. These terms are moved over to the
216** WHERE clause during join processing but we need to remember that they
217** originated in the ON or USING clause.
drh22d6a532005-09-19 21:05:48 +0000218**
219** The Expr.iRightJoinTable tells the WHERE clause processing that the
220** expression depends on table iRightJoinTable even if that table is not
221** explicitly mentioned in the expression. That information is needed
222** for cases like this:
223**
224** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
225**
226** The where clause needs to defer the handling of the t1.x=5
227** term until after the t2 loop of the join. In that way, a
228** NULL t2 row will be inserted whenever t1.x!=5. If we do not
229** defer the handling of t1.x=5, it will be processed immediately
230** after the t1 loop and rows with t1.x!=5 will never appear in
231** the output, which is incorrect.
drh1cc093c2002-06-24 22:01:57 +0000232*/
drh22d6a532005-09-19 21:05:48 +0000233static void setJoinExpr(Expr *p, int iTable){
drh1cc093c2002-06-24 22:01:57 +0000234 while( p ){
drh1f162302002-10-27 19:35:33 +0000235 ExprSetProperty(p, EP_FromJoin);
drh22d6a532005-09-19 21:05:48 +0000236 p->iRightJoinTable = iTable;
237 setJoinExpr(p->pLeft, iTable);
drh1cc093c2002-06-24 22:01:57 +0000238 p = p->pRight;
239 }
240}
241
242/*
drhad2d8302002-05-24 20:31:36 +0000243** This routine processes the join information for a SELECT statement.
244** ON and USING clauses are converted into extra terms of the WHERE clause.
245** NATURAL joins also create extra WHERE clause terms.
246**
drh91bb0ee2004-09-01 03:06:34 +0000247** The terms of a FROM clause are contained in the Select.pSrc structure.
248** The left most table is the first entry in Select.pSrc. The right-most
249** table is the last entry. The join operator is held in the entry to
250** the left. Thus entry 0 contains the join operator for the join between
251** entries 0 and 1. Any ON or USING clauses associated with the join are
252** also attached to the left entry.
253**
drhad2d8302002-05-24 20:31:36 +0000254** This routine returns the number of errors encountered.
255*/
256static int sqliteProcessJoin(Parse *pParse, Select *p){
drh91bb0ee2004-09-01 03:06:34 +0000257 SrcList *pSrc; /* All tables in the FROM clause */
258 int i, j; /* Loop counters */
259 struct SrcList_item *pLeft; /* Left table being joined */
260 struct SrcList_item *pRight; /* Right table being joined */
drhad2d8302002-05-24 20:31:36 +0000261
drh91bb0ee2004-09-01 03:06:34 +0000262 pSrc = p->pSrc;
263 pLeft = &pSrc->a[0];
264 pRight = &pLeft[1];
265 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
266 Table *pLeftTab = pLeft->pTab;
267 Table *pRightTab = pRight->pTab;
268
269 if( pLeftTab==0 || pRightTab==0 ) continue;
drhad2d8302002-05-24 20:31:36 +0000270
271 /* When the NATURAL keyword is present, add WHERE clause terms for
272 ** every column that the two tables have in common.
273 */
drh91bb0ee2004-09-01 03:06:34 +0000274 if( pLeft->jointype & JT_NATURAL ){
275 if( pLeft->pOn || pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000276 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000277 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000278 return 1;
279 }
drh91bb0ee2004-09-01 03:06:34 +0000280 for(j=0; j<pLeftTab->nCol; j++){
281 char *zName = pLeftTab->aCol[j].zName;
282 if( columnIndex(pRightTab, zName)>=0 ){
drh030530d2005-01-18 17:40:04 +0000283 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
drh22d6a532005-09-19 21:05:48 +0000284 pRightTab, pRight->zAlias,
285 pRight->iCursor, &p->pWhere);
286
drhad2d8302002-05-24 20:31:36 +0000287 }
288 }
289 }
290
291 /* Disallow both ON and USING clauses in the same join
292 */
drh91bb0ee2004-09-01 03:06:34 +0000293 if( pLeft->pOn && pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000294 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
drhda93d232003-03-31 02:12:46 +0000295 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000296 return 1;
297 }
298
299 /* Add the ON clause to the end of the WHERE clause, connected by
drh91bb0ee2004-09-01 03:06:34 +0000300 ** an AND operator.
drhad2d8302002-05-24 20:31:36 +0000301 */
drh91bb0ee2004-09-01 03:06:34 +0000302 if( pLeft->pOn ){
drh22d6a532005-09-19 21:05:48 +0000303 setJoinExpr(pLeft->pOn, pRight->iCursor);
drh91bb0ee2004-09-01 03:06:34 +0000304 p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn);
305 pLeft->pOn = 0;
drhad2d8302002-05-24 20:31:36 +0000306 }
307
308 /* Create extra terms on the WHERE clause for each column named
309 ** in the USING clause. Example: If the two tables to be joined are
310 ** A and B and the USING clause names X, Y, and Z, then add this
311 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
312 ** Report an error if any column mentioned in the USING clause is
313 ** not contained in both tables to be joined.
314 */
drh91bb0ee2004-09-01 03:06:34 +0000315 if( pLeft->pUsing ){
316 IdList *pList = pLeft->pUsing;
drhad2d8302002-05-24 20:31:36 +0000317 for(j=0; j<pList->nId; j++){
drh91bb0ee2004-09-01 03:06:34 +0000318 char *zName = pList->a[j].zName;
319 if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
danielk19774adee202004-05-08 08:23:19 +0000320 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
drh91bb0ee2004-09-01 03:06:34 +0000321 "not present in both tables", zName);
drhad2d8302002-05-24 20:31:36 +0000322 return 1;
323 }
drh030530d2005-01-18 17:40:04 +0000324 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
drh22d6a532005-09-19 21:05:48 +0000325 pRightTab, pRight->zAlias,
326 pRight->iCursor, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000327 }
328 }
329 }
330 return 0;
331}
332
333/*
drh9bb61fe2000-06-05 16:01:39 +0000334** Delete the given Select structure and all of its substructures.
335*/
danielk19774adee202004-05-08 08:23:19 +0000336void sqlite3SelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000337 if( p==0 ) return;
danielk19774adee202004-05-08 08:23:19 +0000338 sqlite3ExprListDelete(p->pEList);
339 sqlite3SrcListDelete(p->pSrc);
340 sqlite3ExprDelete(p->pWhere);
341 sqlite3ExprListDelete(p->pGroupBy);
342 sqlite3ExprDelete(p->pHaving);
343 sqlite3ExprListDelete(p->pOrderBy);
344 sqlite3SelectDelete(p->pPrior);
danielk1977a2dc3b12005-02-05 12:48:48 +0000345 sqlite3ExprDelete(p->pLimit);
346 sqlite3ExprDelete(p->pOffset);
drh9bb61fe2000-06-05 16:01:39 +0000347 sqliteFree(p);
348}
349
350/*
drhc926afb2002-06-20 03:38:26 +0000351** Insert code into "v" that will push the record on the top of the
352** stack into the sorter.
353*/
354static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
drhc182d162005-08-14 20:47:16 +0000355 sqlite3ExprCodeExprList(pParse, pOrderBy);
drh9d2985c2005-09-08 01:58:42 +0000356 sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0);
drh4db38a72005-09-01 12:16:28 +0000357 sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0);
358 sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0);
drh9d2985c2005-09-08 01:58:42 +0000359 sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0);
drhc926afb2002-06-20 03:38:26 +0000360}
361
362/*
drhea48eb22004-07-19 23:16:38 +0000363** Add code to implement the OFFSET and LIMIT
364*/
365static void codeLimiter(
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 */
369 int iBreak, /* Jump here to end the loop */
370 int nPop /* Number of times to pop stack when jumping */
371){
drh13449892005-09-07 21:22:45 +0000372 if( p->iOffset>=0 && iContinue!=0 ){
danielk1977a2dc3b12005-02-05 12:48:48 +0000373 int addr = sqlite3VdbeCurrentAddr(v) + 3;
drhea48eb22004-07-19 23:16:38 +0000374 if( nPop>0 ) addr++;
danielk1977a2dc3b12005-02-05 12:48:48 +0000375 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, 0);
376 sqlite3VdbeAddOp(v, OP_IfMemPos, p->iOffset, addr);
drhea48eb22004-07-19 23:16:38 +0000377 if( nPop>0 ){
378 sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
379 }
380 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000381 VdbeComment((v, "# skip OFFSET records"));
drhea48eb22004-07-19 23:16:38 +0000382 }
drh13449892005-09-07 21:22:45 +0000383 if( p->iLimit>=0 && iBreak!=0 ){
drhea48eb22004-07-19 23:16:38 +0000384 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhad6d9462004-09-19 02:15:24 +0000385 VdbeComment((v, "# exit when LIMIT reached"));
drhea48eb22004-07-19 23:16:38 +0000386 }
387}
388
389/*
drhc99130f2005-09-11 11:56:27 +0000390** Add code that will check to make sure the top N elements of the
391** stack are distinct. iTab is a sorting index that holds previously
392** seen combinations of the N values. A new entry is made in iTab
393** if the current N values are new.
394**
395** A jump to addrRepeat is made and the K values are popped from the
396** stack if the top N elements are not distinct.
397*/
398static void codeDistinct(
399 Vdbe *v, /* Generate code into this VM */
400 int iTab, /* A sorting index used to test for distinctness */
401 int addrRepeat, /* Jump to here if not distinct */
402 int N, /* The top N elements of the stack must be distinct */
403 int K /* Pop K elements from the stack if indistinct */
404){
405#if NULL_ALWAYS_DISTINCT
406 sqlite3VdbeAddOp(v, OP_IsNull, -N, sqlite3VdbeCurrentAddr(v)+6);
407#endif
408 sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0);
409 sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3);
410 sqlite3VdbeAddOp(v, OP_Pop, K, 0);
411 sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat);
412 VdbeComment((v, "# skip indistinct records"));
413 sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0);
414}
415
416
417/*
drh22827922000-06-06 17:27:05 +0000418** This routine generates the code for the inside of the inner loop
419** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000420**
drh38640e12002-07-05 21:42:36 +0000421** If srcTab and nColumn are both zero, then the pEList expressions
422** are evaluated in order to get the data for this row. If nColumn>0
423** then data is pulled from srcTab and pEList is used only to get the
424** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000425*/
426static int selectInnerLoop(
427 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000428 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000429 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000430 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000431 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000432 ExprList *pOrderBy, /* If not NULL, sort results using this key */
433 int distinct, /* If >=0, make sure results are distinct */
434 int eDest, /* How to dispose of the results */
435 int iParm, /* An argument to the disposal method */
436 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000437 int iBreak, /* Jump here to break out of the inner loop */
438 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000439){
440 Vdbe *v = pParse->pVdbe;
441 int i;
drhea48eb22004-07-19 23:16:38 +0000442 int hasDistinct; /* True if the DISTINCT keyword is present */
drh38640e12002-07-05 21:42:36 +0000443
drhdaffd0e2001-04-11 14:28:42 +0000444 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000445 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000446
drhdf199a22002-06-14 22:38:41 +0000447 /* If there was a LIMIT clause on the SELECT statement, then do the check
448 ** to see if this row should be output.
449 */
drhea48eb22004-07-19 23:16:38 +0000450 hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
451 if( pOrderBy==0 && !hasDistinct ){
drhbab39e12004-07-19 23:38:11 +0000452 codeLimiter(v, p, iContinue, iBreak, 0);
drhdf199a22002-06-14 22:38:41 +0000453 }
454
drh967e8b72000-06-21 13:59:10 +0000455 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000456 */
drh38640e12002-07-05 21:42:36 +0000457 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000458 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000459 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000460 }
drh38640e12002-07-05 21:42:36 +0000461 }else{
462 nColumn = pEList->nExpr;
drhc182d162005-08-14 20:47:16 +0000463 sqlite3ExprCodeExprList(pParse, pEList);
drh22827922000-06-06 17:27:05 +0000464 }
465
drhdaffd0e2001-04-11 14:28:42 +0000466 /* If the DISTINCT keyword was present on the SELECT statement
467 ** and this row has been seen before, then do not make this row
468 ** part of the result.
drh22827922000-06-06 17:27:05 +0000469 */
drhea48eb22004-07-19 23:16:38 +0000470 if( hasDistinct ){
drhc182d162005-08-14 20:47:16 +0000471 int n = pEList->nExpr;
drhc99130f2005-09-11 11:56:27 +0000472 codeDistinct(v, distinct, iContinue, n, n+1);
drhea48eb22004-07-19 23:16:38 +0000473 if( pOrderBy==0 ){
drhbab39e12004-07-19 23:38:11 +0000474 codeLimiter(v, p, iContinue, iBreak, nColumn);
drhea48eb22004-07-19 23:16:38 +0000475 }
drh22827922000-06-06 17:27:05 +0000476 }
drh82c3d632000-06-06 21:56:07 +0000477
drhc926afb2002-06-20 03:38:26 +0000478 switch( eDest ){
479 /* In this mode, write each query result to the key of the temporary
480 ** table iParm.
481 */
drh13449892005-09-07 21:22:45 +0000482#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhc926afb2002-06-20 03:38:26 +0000483 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000484 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
drh13449892005-09-07 21:22:45 +0000485 if( aff ){
486 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
487 }
drhf0863fe2005-06-12 21:35:51 +0000488 sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000489 break;
drh22827922000-06-06 17:27:05 +0000490 }
drh22827922000-06-06 17:27:05 +0000491
drhc926afb2002-06-20 03:38:26 +0000492 /* Construct a record from the query result, but instead of
493 ** saving that record, use it as a key to delete elements from
494 ** the temporary table iParm.
495 */
496 case SRT_Except: {
497 int addr;
danielk19774adee202004-05-08 08:23:19 +0000498 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000499 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000500 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
501 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000502 break;
503 }
danielk19775338a5f2005-01-20 13:03:10 +0000504#endif
505
506 /* Store the result as data using a unique key.
507 */
508 case SRT_Table:
drh9d2985c2005-09-08 01:58:42 +0000509 case SRT_VirtualTab: {
danielk19775338a5f2005-01-20 13:03:10 +0000510 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
511 if( pOrderBy ){
512 pushOntoSorter(pParse, v, pOrderBy);
513 }else{
drhf0863fe2005-06-12 21:35:51 +0000514 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
danielk19775338a5f2005-01-20 13:03:10 +0000515 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhf0863fe2005-06-12 21:35:51 +0000516 sqlite3VdbeAddOp(v, OP_Insert, iParm, 0);
danielk19775338a5f2005-01-20 13:03:10 +0000517 }
518 break;
519 }
drh5974a302000-06-07 14:42:26 +0000520
danielk197793758c82005-01-21 08:13:14 +0000521#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000522 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
523 ** then there should be a single item on the stack. Write this
524 ** item into the set table with bogus data.
525 */
526 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000527 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000528 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000529
drhc926afb2002-06-20 03:38:26 +0000530 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000531 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
532 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
533 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000534 if( pOrderBy ){
drhde941c62005-08-28 01:34:21 +0000535 /* At first glance you would think we could optimize out the
536 ** ORDER BY in this case since the order of entries in the set
537 ** does not matter. But there might be a LIMIT clause, in which
538 ** case the order does matter */
drhc926afb2002-06-20 03:38:26 +0000539 pushOntoSorter(pParse, v, pOrderBy);
540 }else{
danielk1977e014a832004-05-17 10:48:57 +0000541 char aff = (iParm>>16)&0xFF;
542 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
drh94a11212004-09-25 13:12:14 +0000543 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1);
drhf0863fe2005-06-12 21:35:51 +0000544 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000545 }
drhd654be82005-09-20 17:42:23 +0000546 sqlite3VdbeJumpHere(v, addr2);
drhc926afb2002-06-20 03:38:26 +0000547 break;
548 }
drh22827922000-06-06 17:27:05 +0000549
drhc926afb2002-06-20 03:38:26 +0000550 /* If this is a scalar select that is part of an expression, then
551 ** store the results in the appropriate memory cell and break out
552 ** of the scan loop.
553 */
drh51522cd2005-01-20 13:36:19 +0000554 case SRT_Exists:
drhc926afb2002-06-20 03:38:26 +0000555 case SRT_Mem: {
556 assert( nColumn==1 );
557 if( pOrderBy ){
558 pushOntoSorter(pParse, v, pOrderBy);
559 }else{
danielk19774adee202004-05-08 08:23:19 +0000560 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
561 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000562 }
563 break;
564 }
danielk197793758c82005-01-21 08:13:14 +0000565#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
drh22827922000-06-06 17:27:05 +0000566
drhc182d162005-08-14 20:47:16 +0000567 /* Send the data to the callback function or to a subroutine. In the
568 ** case of a subroutine, the subroutine itself is responsible for
569 ** popping the data from the stack.
drhf46f9052002-06-22 02:33:38 +0000570 */
drhc182d162005-08-14 20:47:16 +0000571 case SRT_Subroutine:
drh9d2985c2005-09-08 01:58:42 +0000572 case SRT_Callback: {
drhf46f9052002-06-22 02:33:38 +0000573 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000574 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000575 pushOntoSorter(pParse, v, pOrderBy);
drhc182d162005-08-14 20:47:16 +0000576 }else if( eDest==SRT_Subroutine ){
danielk19774adee202004-05-08 08:23:19 +0000577 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhc182d162005-08-14 20:47:16 +0000578 }else{
drhc182d162005-08-14 20:47:16 +0000579 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000580 }
drh142e30d2002-08-28 03:00:58 +0000581 break;
582 }
583
danielk19776a67fe82005-02-04 04:07:16 +0000584#if !defined(SQLITE_OMIT_TRIGGER)
drhc926afb2002-06-20 03:38:26 +0000585 /* Discard the results. This is used for SELECT statements inside
586 ** the body of a TRIGGER. The purpose of such selects is to call
587 ** user-defined functions that have side effects. We do not care
588 ** about the actual results of the select.
589 */
drhc926afb2002-06-20 03:38:26 +0000590 default: {
drhf46f9052002-06-22 02:33:38 +0000591 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000592 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000593 break;
594 }
danielk197793758c82005-01-21 08:13:14 +0000595#endif
drh82c3d632000-06-06 21:56:07 +0000596 }
597 return 0;
598}
599
600/*
drhdece1a82005-08-31 18:20:00 +0000601** Given an expression list, generate a KeyInfo structure that records
602** the collating sequence for each expression in that expression list.
603**
drh0342b1f2005-09-01 03:07:44 +0000604** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
605** KeyInfo structure is appropriate for initializing a virtual index to
606** implement that clause. If the ExprList is the result set of a SELECT
607** then the KeyInfo structure is appropriate for initializing a virtual
608** index to implement a DISTINCT test.
609**
drhdece1a82005-08-31 18:20:00 +0000610** Space to hold the KeyInfo structure is obtain from malloc. The calling
611** function is responsible for seeing that this structure is eventually
612** freed. Add the KeyInfo structure to the P3 field of an opcode using
613** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
614*/
615static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
616 sqlite3 *db = pParse->db;
617 int nExpr;
618 KeyInfo *pInfo;
619 struct ExprList_item *pItem;
620 int i;
621
622 nExpr = pList->nExpr;
623 pInfo = sqliteMalloc( sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
624 if( pInfo ){
625 pInfo->aSortOrder = (char*)&pInfo->aColl[nExpr];
626 pInfo->nField = nExpr;
627 pInfo->enc = db->enc;
628 for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
629 CollSeq *pColl;
630 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
631 if( !pColl ){
632 pColl = db->pDfltColl;
633 }
634 pInfo->aColl[i] = pColl;
635 pInfo->aSortOrder[i] = pItem->sortOrder;
636 }
637 }
638 return pInfo;
639}
640
641
642/*
drhd8bc7082000-06-07 23:51:50 +0000643** If the inner loop was generated using a non-null pOrderBy argument,
644** then the results were placed in a sorter. After the loop is terminated
645** we need to run the sorter and output the results. The following
646** routine generates the code needed to do that.
647*/
drhc926afb2002-06-20 03:38:26 +0000648static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000649 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000650 Select *p, /* The SELECT statement */
651 Vdbe *v, /* Generate code into this VDBE */
652 int nColumn, /* Number of columns of data */
653 int eDest, /* Write the sorted results here */
654 int iParm /* Optional parameter associated with eDest */
655){
drh0342b1f2005-09-01 03:07:44 +0000656 int brk = sqlite3VdbeMakeLabel(v);
657 int cont = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000658 int addr;
drh0342b1f2005-09-01 03:07:44 +0000659 int iTab;
660 ExprList *pOrderBy = p->pOrderBy;
drhffbc3082004-05-21 01:29:06 +0000661
drh9d2985c2005-09-08 01:58:42 +0000662 iTab = pOrderBy->iECursor;
drh0342b1f2005-09-01 03:07:44 +0000663 addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
664 codeLimiter(v, p, cont, brk, 0);
drh4db38a72005-09-01 12:16:28 +0000665 sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1);
drhc926afb2002-06-20 03:38:26 +0000666 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000667 case SRT_Table:
drh9d2985c2005-09-08 01:58:42 +0000668 case SRT_VirtualTab: {
drhf0863fe2005-06-12 21:35:51 +0000669 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
danielk19774adee202004-05-08 08:23:19 +0000670 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhf0863fe2005-06-12 21:35:51 +0000671 sqlite3VdbeAddOp(v, OP_Insert, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000672 break;
673 }
danielk197793758c82005-01-21 08:13:14 +0000674#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000675 case SRT_Set: {
676 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000677 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
678 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
679 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
danielk1977ededfd52004-06-17 07:53:01 +0000680 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
drhf0863fe2005-06-12 21:35:51 +0000681 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000682 break;
683 }
drh51522cd2005-01-20 13:36:19 +0000684 case SRT_Exists:
drhc926afb2002-06-20 03:38:26 +0000685 case SRT_Mem: {
686 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000687 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh0342b1f2005-09-01 03:07:44 +0000688 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
drhc926afb2002-06-20 03:38:26 +0000689 break;
690 }
danielk197793758c82005-01-21 08:13:14 +0000691#endif
drhce665cf2004-05-21 03:01:58 +0000692 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000693 case SRT_Subroutine: {
694 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000695 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
696 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000697 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000698 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000699 }
drhce665cf2004-05-21 03:01:58 +0000700 if( eDest==SRT_Callback ){
701 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
702 }else{
703 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
704 }
danielk197784ac9d02004-05-18 09:58:06 +0000705 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000706 break;
707 }
drhc926afb2002-06-20 03:38:26 +0000708 default: {
drhf46f9052002-06-22 02:33:38 +0000709 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000710 break;
711 }
712 }
drh0342b1f2005-09-01 03:07:44 +0000713 sqlite3VdbeResolveLabel(v, cont);
714 sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
715 sqlite3VdbeResolveLabel(v, brk);
drhd8bc7082000-06-07 23:51:50 +0000716}
717
718/*
danielk1977517eb642004-06-07 10:00:31 +0000719** Return a pointer to a string containing the 'declaration type' of the
720** expression pExpr. The string may be treated as static by the caller.
drhe78e8282003-01-19 03:59:45 +0000721**
danielk1977517eb642004-06-07 10:00:31 +0000722** If the declaration type is the exact datatype definition extracted from
723** the original CREATE TABLE statement if the expression is a column.
724**
725** The declaration type for an expression is either TEXT, NUMERIC or ANY.
726** The declaration type for a ROWID field is INTEGER.
727*/
danielk1977b3bce662005-01-29 08:32:43 +0000728static const char *columnType(NameContext *pNC, Expr *pExpr){
danielk197700e279d2004-06-21 07:36:32 +0000729 char const *zType;
danielk1977517eb642004-06-07 10:00:31 +0000730 int j;
danielk1977b3bce662005-01-29 08:32:43 +0000731 if( pExpr==0 || pNC->pSrcList==0 ) return 0;
danielk19775338a5f2005-01-20 13:03:10 +0000732
733 /* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING,
734 ** and LIMIT clauses. But pExpr originates in the result set of a
735 ** SELECT. So pExpr can never contain an AS operator.
736 */
737 assert( pExpr->op!=TK_AS );
738
danielk197700e279d2004-06-21 07:36:32 +0000739 switch( pExpr->op ){
740 case TK_COLUMN: {
danielk1977b3bce662005-01-29 08:32:43 +0000741 Table *pTab = 0;
danielk197700e279d2004-06-21 07:36:32 +0000742 int iCol = pExpr->iColumn;
danielk1977b3bce662005-01-29 08:32:43 +0000743 while( pNC && !pTab ){
744 SrcList *pTabList = pNC->pSrcList;
745 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
746 if( j<pTabList->nSrc ){
747 pTab = pTabList->a[j].pTab;
748 }else{
749 pNC = pNC->pNext;
750 }
751 }
drh7e627792005-04-29 02:10:00 +0000752 if( pTab==0 ){
753 /* FIX ME:
754 ** This can occurs if you have something like "SELECT new.x;" inside
755 ** a trigger. In other words, if you reference the special "new"
756 ** table in the result set of a select. We do not have a good way
757 ** to find the actual table type, so call it "TEXT". This is really
758 ** something of a bug, but I do not know how to fix it.
759 **
760 ** This code does not produce the correct answer - it just prevents
761 ** a segfault. See ticket #1229.
762 */
763 zType = "TEXT";
764 break;
765 }
danielk1977b3bce662005-01-29 08:32:43 +0000766 assert( pTab );
danielk197700e279d2004-06-21 07:36:32 +0000767 if( iCol<0 ) iCol = pTab->iPKey;
768 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
769 if( iCol<0 ){
770 zType = "INTEGER";
771 }else{
772 zType = pTab->aCol[iCol].zType;
773 }
774 break;
danielk1977517eb642004-06-07 10:00:31 +0000775 }
danielk197793758c82005-01-21 08:13:14 +0000776#ifndef SQLITE_OMIT_SUBQUERY
danielk197700e279d2004-06-21 07:36:32 +0000777 case TK_SELECT: {
danielk1977b3bce662005-01-29 08:32:43 +0000778 NameContext sNC;
danielk197700e279d2004-06-21 07:36:32 +0000779 Select *pS = pExpr->pSelect;
danielk1977b3bce662005-01-29 08:32:43 +0000780 sNC.pSrcList = pExpr->pSelect->pSrc;
781 sNC.pNext = pNC;
782 zType = columnType(&sNC, pS->pEList->a[0].pExpr);
danielk197700e279d2004-06-21 07:36:32 +0000783 break;
danielk1977517eb642004-06-07 10:00:31 +0000784 }
danielk197793758c82005-01-21 08:13:14 +0000785#endif
danielk197700e279d2004-06-21 07:36:32 +0000786 default:
787 zType = 0;
danielk1977517eb642004-06-07 10:00:31 +0000788 }
danielk197700e279d2004-06-21 07:36:32 +0000789
danielk1977517eb642004-06-07 10:00:31 +0000790 return zType;
791}
792
793/*
794** Generate code that will tell the VDBE the declaration types of columns
795** in the result set.
drhfcb78a42003-01-18 20:11:05 +0000796*/
797static void generateColumnTypes(
798 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000799 SrcList *pTabList, /* List of tables */
800 ExprList *pEList /* Expressions defining the result set */
801){
802 Vdbe *v = pParse->pVdbe;
danielk1977517eb642004-06-07 10:00:31 +0000803 int i;
danielk1977b3bce662005-01-29 08:32:43 +0000804 NameContext sNC;
805 sNC.pSrcList = pTabList;
drhfcb78a42003-01-18 20:11:05 +0000806 for(i=0; i<pEList->nExpr; i++){
807 Expr *p = pEList->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +0000808 const char *zType = columnType(&sNC, p);
danielk197700e279d2004-06-21 07:36:32 +0000809 if( zType==0 ) continue;
danielk1977fbcd5852004-06-15 02:44:18 +0000810 /* The vdbe must make it's own copy of the column-type, in case the
811 ** schema is reset before this virtual machine is deleted.
812 */
813 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
drhfcb78a42003-01-18 20:11:05 +0000814 }
815}
816
817/*
818** Generate code that will tell the VDBE the names of columns
819** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000820** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000821*/
drh832508b2002-03-02 17:04:07 +0000822static void generateColumnNames(
823 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000824 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000825 ExprList *pEList /* Expressions defining the result set */
826){
drhd8bc7082000-06-07 23:51:50 +0000827 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000828 int i, j;
drh9bb575f2004-09-06 17:24:11 +0000829 sqlite3 *db = pParse->db;
drhfcabd462004-02-20 14:50:58 +0000830 int fullNames, shortNames;
831
drhfe2093d2005-01-20 22:48:47 +0000832#ifndef SQLITE_OMIT_EXPLAIN
danielk19773cf86062004-05-26 10:11:05 +0000833 /* If this is an EXPLAIN, skip this step */
834 if( pParse->explain ){
danielk197761de0d12004-05-27 23:56:16 +0000835 return;
danielk19773cf86062004-05-26 10:11:05 +0000836 }
danielk19775338a5f2005-01-20 13:03:10 +0000837#endif
danielk19773cf86062004-05-26 10:11:05 +0000838
drhd6502752004-02-16 03:44:01 +0000839 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000840 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000841 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000842 fullNames = (db->flags & SQLITE_FullColNames)!=0;
843 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
danielk197722322fd2004-05-25 23:35:17 +0000844 sqlite3VdbeSetNumCols(v, pEList->nExpr);
drh82c3d632000-06-06 21:56:07 +0000845 for(i=0; i<pEList->nExpr; i++){
846 Expr *p;
drh5a387052003-01-11 14:19:51 +0000847 p = pEList->a[i].pExpr;
848 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000849 if( pEList->a[i].zName ){
850 char *zName = pEList->a[i].zName;
danielk1977d8123362004-06-12 09:25:12 +0000851 sqlite3VdbeSetColName(v, i, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000852 continue;
853 }
drhfa173a72002-07-10 21:26:00 +0000854 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000855 Table *pTab;
drh97665872002-02-13 23:22:53 +0000856 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000857 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000858 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
859 assert( j<pTabList->nSrc );
860 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000861 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000862 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000863 if( iCol<0 ){
drh47a6db22005-01-18 16:02:40 +0000864 zCol = "rowid";
drhb1363202002-06-26 02:45:03 +0000865 }else{
866 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000867 }
drhfcabd462004-02-20 14:50:58 +0000868 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000869 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
drhfcabd462004-02-20 14:50:58 +0000870 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000871 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000872 char *zTab;
873
drh6a3ea0e2003-05-02 14:32:12 +0000874 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000875 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000876 sqlite3SetString(&zName, zTab, ".", zCol, 0);
danielk19773cf86062004-05-26 10:11:05 +0000877 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000878 }else{
drh47a6db22005-01-18 16:02:40 +0000879 sqlite3VdbeSetColName(v, i, zCol, strlen(zCol));
drh82c3d632000-06-06 21:56:07 +0000880 }
drh6977fea2002-10-22 23:38:04 +0000881 }else if( p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000882 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
883 /* sqlite3VdbeCompressSpace(v, addr); */
drh1bee3d72001-10-15 00:44:35 +0000884 }else{
885 char zName[30];
886 assert( p->op!=TK_COLUMN || pTabList==0 );
887 sprintf(zName, "column%d", i+1);
danielk19773cf86062004-05-26 10:11:05 +0000888 sqlite3VdbeSetColName(v, i, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000889 }
890 }
danielk197776d505b2004-05-28 13:13:02 +0000891 generateColumnTypes(pParse, pTabList, pEList);
drh82c3d632000-06-06 21:56:07 +0000892}
893
danielk197793758c82005-01-21 08:13:14 +0000894#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +0000895/*
drhd8bc7082000-06-07 23:51:50 +0000896** Name of the connection operator, used for error messages.
897*/
898static const char *selectOpName(int id){
899 char *z;
900 switch( id ){
901 case TK_ALL: z = "UNION ALL"; break;
902 case TK_INTERSECT: z = "INTERSECT"; break;
903 case TK_EXCEPT: z = "EXCEPT"; break;
904 default: z = "UNION"; break;
905 }
906 return z;
907}
danielk197793758c82005-01-21 08:13:14 +0000908#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +0000909
910/*
drh315555c2002-10-20 15:53:03 +0000911** Forward declaration
912*/
drh9b3187e2005-01-18 14:45:47 +0000913static int prepSelectStmt(Parse*, Select*);
drh315555c2002-10-20 15:53:03 +0000914
915/*
drh22f70c32002-02-18 01:17:00 +0000916** Given a SELECT statement, generate a Table structure that describes
917** the result set of that SELECT.
918*/
danielk19774adee202004-05-08 08:23:19 +0000919Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000920 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000921 int i, j;
drh22f70c32002-02-18 01:17:00 +0000922 ExprList *pEList;
drh290c1942004-08-21 17:54:45 +0000923 Column *aCol, *pCol;
drh22f70c32002-02-18 01:17:00 +0000924
drh9b3187e2005-01-18 14:45:47 +0000925 if( prepSelectStmt(pParse, pSelect) ){
drh22f70c32002-02-18 01:17:00 +0000926 return 0;
927 }
danielk1977142bdf42005-01-30 11:11:44 +0000928 if( sqlite3SelectResolve(pParse, pSelect, 0) ){
929 return 0;
930 }
drh22f70c32002-02-18 01:17:00 +0000931 pTab = sqliteMalloc( sizeof(Table) );
932 if( pTab==0 ){
933 return 0;
934 }
drhed8a3bb2005-06-06 21:19:56 +0000935 pTab->nRef = 1;
drh22f70c32002-02-18 01:17:00 +0000936 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
937 pEList = pSelect->pEList;
938 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000939 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000940 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh290c1942004-08-21 17:54:45 +0000941 for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
drh79d5f632005-01-18 17:20:10 +0000942 Expr *p, *pR;
danielk1977517eb642004-06-07 10:00:31 +0000943 char *zType;
drh91bb0ee2004-09-01 03:06:34 +0000944 char *zName;
drh79d5f632005-01-18 17:20:10 +0000945 char *zBasename;
946 int cnt;
danielk1977b3bce662005-01-29 08:32:43 +0000947 NameContext sNC;
drh79d5f632005-01-18 17:20:10 +0000948
949 /* Get an appropriate name for the column
950 */
951 p = pEList->a[i].pExpr;
drh290c1942004-08-21 17:54:45 +0000952 assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
drh91bb0ee2004-09-01 03:06:34 +0000953 if( (zName = pEList->a[i].zName)!=0 ){
drh79d5f632005-01-18 17:20:10 +0000954 /* If the column contains an "AS <name>" phrase, use <name> as the name */
drh91bb0ee2004-09-01 03:06:34 +0000955 zName = sqliteStrDup(zName);
danielk1977517eb642004-06-07 10:00:31 +0000956 }else if( p->op==TK_DOT
drh79d5f632005-01-18 17:20:10 +0000957 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
958 /* For columns of the from A.B use B as the name */
drh91bb0ee2004-09-01 03:06:34 +0000959 zName = sqlite3MPrintf("%T", &pR->token);
drhb733d032004-01-24 20:18:12 +0000960 }else if( p->span.z && p->span.z[0] ){
drh79d5f632005-01-18 17:20:10 +0000961 /* Use the original text of the column expression as its name */
drh91bb0ee2004-09-01 03:06:34 +0000962 zName = sqlite3MPrintf("%T", &p->span);
drh22f70c32002-02-18 01:17:00 +0000963 }else{
drh79d5f632005-01-18 17:20:10 +0000964 /* If all else fails, make up a name */
drh91bb0ee2004-09-01 03:06:34 +0000965 zName = sqlite3MPrintf("column%d", i+1);
drh22f70c32002-02-18 01:17:00 +0000966 }
drh91bb0ee2004-09-01 03:06:34 +0000967 sqlite3Dequote(zName);
drhdd5b2fa2005-03-28 03:39:55 +0000968 if( sqlite3_malloc_failed ){
969 sqliteFree(zName);
970 sqlite3DeleteTable(0, pTab);
971 return 0;
972 }
drh79d5f632005-01-18 17:20:10 +0000973
974 /* Make sure the column name is unique. If the name is not unique,
975 ** append a integer to the name so that it becomes unique.
976 */
977 zBasename = zName;
978 for(j=cnt=0; j<i; j++){
979 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
980 zName = sqlite3MPrintf("%s:%d", zBasename, ++cnt);
981 j = -1;
drhdd5b2fa2005-03-28 03:39:55 +0000982 if( zName==0 ) break;
drh79d5f632005-01-18 17:20:10 +0000983 }
984 }
985 if( zBasename!=zName ){
986 sqliteFree(zBasename);
987 }
drh91bb0ee2004-09-01 03:06:34 +0000988 pCol->zName = zName;
danielk1977517eb642004-06-07 10:00:31 +0000989
drh79d5f632005-01-18 17:20:10 +0000990 /* Get the typename, type affinity, and collating sequence for the
991 ** column.
992 */
drhc43e8be2005-05-16 22:37:54 +0000993 memset(&sNC, 0, sizeof(sNC));
danielk1977b3bce662005-01-29 08:32:43 +0000994 sNC.pSrcList = pSelect->pSrc;
995 zType = sqliteStrDup(columnType(&sNC, p));
drh290c1942004-08-21 17:54:45 +0000996 pCol->zType = zType;
danielk1977c60e9b82005-01-31 12:42:29 +0000997 pCol->affinity = sqlite3ExprAffinity(p);
drh290c1942004-08-21 17:54:45 +0000998 pCol->pColl = sqlite3ExprCollSeq(pParse, p);
999 if( !pCol->pColl ){
1000 pCol->pColl = pParse->db->pDfltColl;
danielk19770202b292004-06-09 09:55:16 +00001001 }
drh22f70c32002-02-18 01:17:00 +00001002 }
1003 pTab->iPKey = -1;
1004 return pTab;
1005}
1006
1007/*
drh9b3187e2005-01-18 14:45:47 +00001008** Prepare a SELECT statement for processing by doing the following
1009** things:
drhd8bc7082000-06-07 23:51:50 +00001010**
drh9b3187e2005-01-18 14:45:47 +00001011** (1) Make sure VDBE cursor numbers have been assigned to every
1012** element of the FROM clause.
1013**
1014** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
1015** defines FROM clause. When views appear in the FROM clause,
drh63eb5f22003-04-29 16:20:44 +00001016** fill pTabList->a[].pSelect with a copy of the SELECT statement
1017** that implements the view. A copy is made of the view's SELECT
1018** statement so that we can freely modify or delete that statement
1019** without worrying about messing up the presistent representation
1020** of the view.
drhd8bc7082000-06-07 23:51:50 +00001021**
drh9b3187e2005-01-18 14:45:47 +00001022** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
drhad2d8302002-05-24 20:31:36 +00001023** on joins and the ON and USING clause of joins.
1024**
drh9b3187e2005-01-18 14:45:47 +00001025** (4) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +00001026** for instances of the "*" operator or the TABLE.* operator.
1027** If found, expand each "*" to be every column in every table
1028** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +00001029**
1030** Return 0 on success. If there are problems, leave an error message
1031** in pParse and return non-zero.
1032*/
drh9b3187e2005-01-18 14:45:47 +00001033static int prepSelectStmt(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +00001034 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +00001035 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +00001036 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +00001037 Table *pTab;
drh290c1942004-08-21 17:54:45 +00001038 struct SrcList_item *pFrom;
drhdaffd0e2001-04-11 14:28:42 +00001039
danielk1977e94ddc92005-03-21 03:53:38 +00001040 if( p==0 || p->pSrc==0 || sqlite3_malloc_failed ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00001041 pTabList = p->pSrc;
1042 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +00001043
drh9b3187e2005-01-18 14:45:47 +00001044 /* Make sure cursor numbers have been assigned to all entries in
1045 ** the FROM clause of the SELECT statement.
1046 */
1047 sqlite3SrcListAssignCursors(pParse, p->pSrc);
1048
1049 /* Look up every table named in the FROM clause of the select. If
1050 ** an entry of the FROM clause is a subquery instead of a table or view,
1051 ** then create a transient table structure to describe the subquery.
drhd8bc7082000-06-07 23:51:50 +00001052 */
drh290c1942004-08-21 17:54:45 +00001053 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
drh9b3187e2005-01-18 14:45:47 +00001054 if( pFrom->pTab!=0 ){
1055 /* This statement has already been prepared. There is no need
1056 ** to go further. */
1057 assert( i==0 );
drhd8bc7082000-06-07 23:51:50 +00001058 return 0;
1059 }
drh290c1942004-08-21 17:54:45 +00001060 if( pFrom->zName==0 ){
danielk197793758c82005-01-21 08:13:14 +00001061#ifndef SQLITE_OMIT_SUBQUERY
drh22f70c32002-02-18 01:17:00 +00001062 /* A sub-query in the FROM clause of a SELECT */
drh290c1942004-08-21 17:54:45 +00001063 assert( pFrom->pSelect!=0 );
1064 if( pFrom->zAlias==0 ){
drh91bb0ee2004-09-01 03:06:34 +00001065 pFrom->zAlias =
1066 sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
drhad2d8302002-05-24 20:31:36 +00001067 }
drhed8a3bb2005-06-06 21:19:56 +00001068 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001069 pFrom->pTab = pTab =
1070 sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
drh22f70c32002-02-18 01:17:00 +00001071 if( pTab==0 ){
1072 return 1;
1073 }
drh5cf590c2003-04-24 01:45:04 +00001074 /* The isTransient flag indicates that the Table structure has been
1075 ** dynamically allocated and may be freed at any time. In other words,
1076 ** pTab is not pointing to a persistent table structure that defines
1077 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +00001078 pTab->isTransient = 1;
danielk197793758c82005-01-21 08:13:14 +00001079#endif
drh22f70c32002-02-18 01:17:00 +00001080 }else{
drha76b5df2002-02-23 02:32:10 +00001081 /* An ordinary table or view name in the FROM clause */
drhed8a3bb2005-06-06 21:19:56 +00001082 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001083 pFrom->pTab = pTab =
1084 sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
drha76b5df2002-02-23 02:32:10 +00001085 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +00001086 return 1;
1087 }
drhed8a3bb2005-06-06 21:19:56 +00001088 pTab->nRef++;
danielk197793758c82005-01-21 08:13:14 +00001089#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00001090 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +00001091 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +00001092 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +00001093 return 1;
1094 }
drh290c1942004-08-21 17:54:45 +00001095 /* If pFrom->pSelect!=0 it means we are dealing with a
drh63eb5f22003-04-29 16:20:44 +00001096 ** view within a view. The SELECT structure has already been
1097 ** copied by the outer view so we can skip the copy step here
1098 ** in the inner view.
1099 */
drh290c1942004-08-21 17:54:45 +00001100 if( pFrom->pSelect==0 ){
1101 pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +00001102 }
drha76b5df2002-02-23 02:32:10 +00001103 }
danielk197793758c82005-01-21 08:13:14 +00001104#endif
drhd8bc7082000-06-07 23:51:50 +00001105 }
1106 }
1107
drhad2d8302002-05-24 20:31:36 +00001108 /* Process NATURAL keywords, and ON and USING clauses of joins.
1109 */
1110 if( sqliteProcessJoin(pParse, p) ) return 1;
1111
drh7c917d12001-12-16 20:05:05 +00001112 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +00001113 ** all columns in all tables. And for every TABLE.* insert the names
1114 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +00001115 ** with the TK_ALL operator for each "*" that it found in the column list.
1116 ** The following code just has to locate the TK_ALL expressions and expand
1117 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +00001118 **
1119 ** The first loop just checks to see if there are any "*" operators
1120 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +00001121 */
drh7c917d12001-12-16 20:05:05 +00001122 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001123 Expr *pE = pEList->a[k].pExpr;
1124 if( pE->op==TK_ALL ) break;
1125 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
1126 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +00001127 }
drh54473222002-04-04 02:10:55 +00001128 rc = 0;
drh7c917d12001-12-16 20:05:05 +00001129 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +00001130 /*
1131 ** If we get here it means the result set contains one or more "*"
1132 ** operators that need to be expanded. Loop through each expression
1133 ** in the result set and expand them one by one.
1134 */
drh7c917d12001-12-16 20:05:05 +00001135 struct ExprList_item *a = pEList->a;
1136 ExprList *pNew = 0;
drhd70dc522005-06-06 16:34:33 +00001137 int flags = pParse->db->flags;
1138 int longNames = (flags & SQLITE_FullColNames)!=0 &&
1139 (flags & SQLITE_ShortColNames)==0;
1140
drh7c917d12001-12-16 20:05:05 +00001141 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001142 Expr *pE = a[k].pExpr;
1143 if( pE->op!=TK_ALL &&
1144 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
1145 /* This particular expression does not need to be expanded.
1146 */
danielk19774adee202004-05-08 08:23:19 +00001147 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001148 pNew->a[pNew->nExpr-1].zName = a[k].zName;
1149 a[k].pExpr = 0;
1150 a[k].zName = 0;
1151 }else{
drh54473222002-04-04 02:10:55 +00001152 /* This expression is a "*" or a "TABLE.*" and needs to be
1153 ** expanded. */
1154 int tableSeen = 0; /* Set to 1 when TABLE matches */
drhcf55b7a2004-07-20 01:45:19 +00001155 char *zTName; /* text of name of TABLE */
drh54473222002-04-04 02:10:55 +00001156 if( pE->op==TK_DOT && pE->pLeft ){
drhcf55b7a2004-07-20 01:45:19 +00001157 zTName = sqlite3NameFromToken(&pE->pLeft->token);
drh54473222002-04-04 02:10:55 +00001158 }else{
drhcf55b7a2004-07-20 01:45:19 +00001159 zTName = 0;
drh54473222002-04-04 02:10:55 +00001160 }
drh290c1942004-08-21 17:54:45 +00001161 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1162 Table *pTab = pFrom->pTab;
1163 char *zTabName = pFrom->zAlias;
drh54473222002-04-04 02:10:55 +00001164 if( zTabName==0 || zTabName[0]==0 ){
1165 zTabName = pTab->zName;
1166 }
drhcf55b7a2004-07-20 01:45:19 +00001167 if( zTName && (zTabName==0 || zTabName[0]==0 ||
1168 sqlite3StrICmp(zTName, zTabName)!=0) ){
drh54473222002-04-04 02:10:55 +00001169 continue;
1170 }
1171 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001172 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001173 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001174 char *zName = pTab->aCol[j].zName;
1175
drh91bb0ee2004-09-01 03:06:34 +00001176 if( i>0 ){
1177 struct SrcList_item *pLeft = &pTabList->a[i-1];
1178 if( (pLeft->jointype & JT_NATURAL)!=0 &&
1179 columnIndex(pLeft->pTab, zName)>=0 ){
1180 /* In a NATURAL join, omit the join columns from the
1181 ** table on the right */
1182 continue;
1183 }
1184 if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1185 /* In a join with a USING clause, omit columns in the
1186 ** using clause from the table on the right. */
1187 continue;
1188 }
drhad2d8302002-05-24 20:31:36 +00001189 }
danielk19774adee202004-05-08 08:23:19 +00001190 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001191 if( pRight==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001192 setToken(&pRight->token, zName);
drhd70dc522005-06-06 16:34:33 +00001193 if( zTabName && (longNames || pTabList->nSrc>1) ){
danielk19774adee202004-05-08 08:23:19 +00001194 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1195 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001196 if( pExpr==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001197 setToken(&pLeft->token, zTabName);
1198 setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
drh6977fea2002-10-22 23:38:04 +00001199 pExpr->span.dyn = 1;
1200 pExpr->token.z = 0;
1201 pExpr->token.n = 0;
1202 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001203 }else{
drh22f70c32002-02-18 01:17:00 +00001204 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001205 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001206 }
drhd70dc522005-06-06 16:34:33 +00001207 if( longNames ){
1208 pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span);
1209 }else{
1210 pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
1211 }
drh7c917d12001-12-16 20:05:05 +00001212 }
drh17e24df2001-11-06 14:10:41 +00001213 }
drh54473222002-04-04 02:10:55 +00001214 if( !tableSeen ){
drhcf55b7a2004-07-20 01:45:19 +00001215 if( zTName ){
1216 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
drhf5db2d32002-06-06 23:42:27 +00001217 }else{
danielk19774adee202004-05-08 08:23:19 +00001218 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001219 }
drh54473222002-04-04 02:10:55 +00001220 rc = 1;
1221 }
drhcf55b7a2004-07-20 01:45:19 +00001222 sqliteFree(zTName);
drhd8bc7082000-06-07 23:51:50 +00001223 }
1224 }
danielk19774adee202004-05-08 08:23:19 +00001225 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001226 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001227 }
drh54473222002-04-04 02:10:55 +00001228 return rc;
drhd8bc7082000-06-07 23:51:50 +00001229}
1230
danielk197793758c82005-01-21 08:13:14 +00001231#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhff78bd22002-02-27 01:47:11 +00001232/*
drhd8bc7082000-06-07 23:51:50 +00001233** This routine associates entries in an ORDER BY expression list with
1234** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001235** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001236** the top-level node is filled in with column number and the iTable
1237** value of the top-level node is filled with iTable parameter.
1238**
1239** If there are prior SELECT clauses, they are processed first. A match
1240** in an earlier SELECT takes precedence over a later SELECT.
1241**
1242** Any entry that does not match is flagged as an error. The number
1243** of errors is returned.
1244*/
1245static int matchOrderbyToColumn(
1246 Parse *pParse, /* A place to leave error messages */
1247 Select *pSelect, /* Match to result columns of this SELECT */
1248 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001249 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001250 int mustComplete /* If TRUE all ORDER BYs must match */
1251){
1252 int nErr = 0;
1253 int i, j;
1254 ExprList *pEList;
1255
drhdaffd0e2001-04-11 14:28:42 +00001256 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001257 if( mustComplete ){
1258 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1259 }
drh9b3187e2005-01-18 14:45:47 +00001260 if( prepSelectStmt(pParse, pSelect) ){
drhd8bc7082000-06-07 23:51:50 +00001261 return 1;
1262 }
1263 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001264 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1265 return 1;
1266 }
drhd8bc7082000-06-07 23:51:50 +00001267 }
1268 pEList = pSelect->pEList;
1269 for(i=0; i<pOrderBy->nExpr; i++){
1270 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001271 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001272 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001273 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001274 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001275 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001276 "ORDER BY position %d should be between 1 and %d",
1277 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001278 nErr++;
1279 break;
1280 }
drhfcb78a42003-01-18 20:11:05 +00001281 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001282 iCol--;
1283 }
1284 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001285 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001286 char *zName, *zLabel;
1287 zName = pEList->a[j].zName;
drha99db3b2004-06-19 14:49:12 +00001288 zLabel = sqlite3NameFromToken(&pE->token);
1289 assert( zLabel!=0 );
danielk19774adee202004-05-08 08:23:19 +00001290 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001291 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001292 }
drh6e142f52000-06-08 13:36:40 +00001293 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001294 }
danielk19774adee202004-05-08 08:23:19 +00001295 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001296 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001297 }
1298 }
drhe4de1fe2002-06-02 16:09:01 +00001299 if( iCol>=0 ){
1300 pE->op = TK_COLUMN;
1301 pE->iColumn = iCol;
1302 pE->iTable = iTable;
danielk1977a58fdfb2005-02-08 07:50:40 +00001303 pE->iAgg = -1;
drhe4de1fe2002-06-02 16:09:01 +00001304 pOrderBy->a[i].done = 1;
1305 }
1306 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001307 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001308 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001309 nErr++;
1310 break;
1311 }
1312 }
1313 return nErr;
1314}
danielk197793758c82005-01-21 08:13:14 +00001315#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +00001316
1317/*
1318** Get a VDBE for the given parser context. Create a new one if necessary.
1319** If an error occurs, return NULL and leave a message in pParse.
1320*/
danielk19774adee202004-05-08 08:23:19 +00001321Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001322 Vdbe *v = pParse->pVdbe;
1323 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001324 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001325 }
drhd8bc7082000-06-07 23:51:50 +00001326 return v;
1327}
drhfcb78a42003-01-18 20:11:05 +00001328
drhd8bc7082000-06-07 23:51:50 +00001329/*
drh7b58dae2003-07-20 01:16:46 +00001330** Compute the iLimit and iOffset fields of the SELECT based on the
danielk1977a2dc3b12005-02-05 12:48:48 +00001331** pLimit and pOffset expressions. nLimit and nOffset hold the expressions
drh7b58dae2003-07-20 01:16:46 +00001332** that appear in the original SQL statement after the LIMIT and OFFSET
danielk1977a2dc3b12005-02-05 12:48:48 +00001333** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
1334** are the integer memory register numbers for counters used to compute
1335** the limit and offset. If there is no limit and/or offset, then
1336** iLimit and iOffset are negative.
drh7b58dae2003-07-20 01:16:46 +00001337**
1338** This routine changes the values if iLimit and iOffset only if
1339** a limit or offset is defined by nLimit and nOffset. iLimit and
1340** iOffset should have been preset to appropriate default values
1341** (usually but not always -1) prior to calling this routine.
1342** Only if nLimit>=0 or nOffset>0 do the limit registers get
1343** redefined. The UNION ALL operator uses this property to force
1344** the reuse of the same limit and offset registers across multiple
1345** SELECT statements.
1346*/
1347static void computeLimitRegisters(Parse *pParse, Select *p){
1348 /*
drh7b58dae2003-07-20 01:16:46 +00001349 ** "LIMIT -1" always shows all rows. There is some
1350 ** contraversy about what the correct behavior should be.
1351 ** The current implementation interprets "LIMIT 0" to mean
1352 ** no rows.
1353 */
danielk1977a2dc3b12005-02-05 12:48:48 +00001354 if( p->pLimit ){
drh7b58dae2003-07-20 01:16:46 +00001355 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001356 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001357 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001358 sqlite3ExprCode(pParse, p->pLimit);
1359 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1360 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001361 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001362 VdbeComment((v, "# LIMIT counter"));
drh7b58dae2003-07-20 01:16:46 +00001363 p->iLimit = iMem;
1364 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001365 if( p->pOffset ){
drh7b58dae2003-07-20 01:16:46 +00001366 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001367 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001368 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001369 sqlite3ExprCode(pParse, p->pOffset);
1370 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1371 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001372 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001373 VdbeComment((v, "# OFFSET counter"));
drh7b58dae2003-07-20 01:16:46 +00001374 p->iOffset = iMem;
1375 }
1376}
1377
1378/*
drh0342b1f2005-09-01 03:07:44 +00001379** Allocate a virtual index to use for sorting.
drhd3d39e92004-05-20 22:16:29 +00001380*/
drh4db38a72005-09-01 12:16:28 +00001381static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
drh0342b1f2005-09-01 03:07:44 +00001382 if( pOrderBy ){
1383 int addr;
drh9d2985c2005-09-08 01:58:42 +00001384 assert( pOrderBy->iECursor==0 );
1385 pOrderBy->iECursor = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001386 addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenVirtual,
drh9d2985c2005-09-08 01:58:42 +00001387 pOrderBy->iECursor, pOrderBy->nExpr+1);
drh0342b1f2005-09-01 03:07:44 +00001388 assert( p->addrOpenVirt[2] == -1 );
1389 p->addrOpenVirt[2] = addr;
drh736c22b2004-05-21 02:14:24 +00001390 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001391}
1392
drh13449892005-09-07 21:22:45 +00001393/*
1394** The opcode at addr is an OP_OpenVirtual that created a sorting
1395** index tha we ended up not needing. This routine changes that
1396** opcode to OP_Noop.
1397*/
1398static void uncreateSortingIndex(Parse *pParse, int addr){
1399 Vdbe *v = pParse->pVdbe;
1400 VdbeOp *pOp = sqlite3VdbeGetOp(v, addr);
1401 sqlite3VdbeChangeP3(v, addr, 0, 0);
1402 pOp->opcode = OP_Noop;
1403 pOp->p1 = 0;
1404 pOp->p2 = 0;
1405}
1406
drhb7f91642004-10-31 02:22:47 +00001407#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001408/*
drhfbc4ee72004-08-29 01:31:05 +00001409** Return the appropriate collating sequence for the iCol-th column of
1410** the result set for the compound-select statement "p". Return NULL if
1411** the column has no default collating sequence.
1412**
1413** The collating sequence for the compound select is taken from the
1414** left-most term of the select that has a collating sequence.
1415*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001416static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
drhfbc4ee72004-08-29 01:31:05 +00001417 CollSeq *pRet;
danielk1977dc1bdc42004-06-11 10:51:27 +00001418 if( p->pPrior ){
1419 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
drhfbc4ee72004-08-29 01:31:05 +00001420 }else{
1421 pRet = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001422 }
drhfbc4ee72004-08-29 01:31:05 +00001423 if( pRet==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001424 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1425 }
1426 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001427}
drhb7f91642004-10-31 02:22:47 +00001428#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd3d39e92004-05-20 22:16:29 +00001429
drhb7f91642004-10-31 02:22:47 +00001430#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhd3d39e92004-05-20 22:16:29 +00001431/*
drh82c3d632000-06-06 21:56:07 +00001432** This routine is called to process a query that is really the union
1433** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001434**
drhe78e8282003-01-19 03:59:45 +00001435** "p" points to the right-most of the two queries. the query on the
1436** left is p->pPrior. The left query could also be a compound query
1437** in which case this routine will be called recursively.
1438**
1439** The results of the total query are to be written into a destination
1440** of type eDest with parameter iParm.
1441**
1442** Example 1: Consider a three-way compound SQL statement.
1443**
1444** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1445**
1446** This statement is parsed up as follows:
1447**
1448** SELECT c FROM t3
1449** |
1450** `-----> SELECT b FROM t2
1451** |
jplyon4b11c6d2004-01-19 04:57:53 +00001452** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001453**
1454** The arrows in the diagram above represent the Select.pPrior pointer.
1455** So if this routine is called with p equal to the t3 query, then
1456** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1457**
1458** Notice that because of the way SQLite parses compound SELECTs, the
1459** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001460*/
danielk197784ac9d02004-05-18 09:58:06 +00001461static int multiSelect(
drhfbc4ee72004-08-29 01:31:05 +00001462 Parse *pParse, /* Parsing context */
1463 Select *p, /* The right-most of SELECTs to be coded */
1464 int eDest, /* \___ Store query results as specified */
1465 int iParm, /* / by these two parameters. */
1466 char *aff /* If eDest is SRT_Union, the affinity string */
danielk197784ac9d02004-05-18 09:58:06 +00001467){
drhfbc4ee72004-08-29 01:31:05 +00001468 int rc = SQLITE_OK; /* Success code from a subroutine */
1469 Select *pPrior; /* Another SELECT immediately to our left */
1470 Vdbe *v; /* Generate code to this VDBE */
drh8cdbf832004-08-29 16:25:03 +00001471 int nCol; /* Number of columns in the result set */
drh0342b1f2005-09-01 03:07:44 +00001472 ExprList *pOrderBy; /* The ORDER BY clause on p */
1473 int aSetP2[2]; /* Set P2 value of these op to number of columns */
1474 int nSetP2 = 0; /* Number of slots in aSetP2[] used */
drh82c3d632000-06-06 21:56:07 +00001475
drh7b58dae2003-07-20 01:16:46 +00001476 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
drhfbc4ee72004-08-29 01:31:05 +00001477 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001478 */
danielk197784ac9d02004-05-18 09:58:06 +00001479 if( p==0 || p->pPrior==0 ){
1480 rc = 1;
1481 goto multi_select_end;
1482 }
drhd8bc7082000-06-07 23:51:50 +00001483 pPrior = p->pPrior;
drh0342b1f2005-09-01 03:07:44 +00001484 assert( pPrior->pRightmost!=pPrior );
1485 assert( pPrior->pRightmost==p->pRightmost );
drhd8bc7082000-06-07 23:51:50 +00001486 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001487 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001488 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001489 rc = 1;
1490 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001491 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001492 if( pPrior->pLimit ){
danielk19774adee202004-05-08 08:23:19 +00001493 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001494 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001495 rc = 1;
1496 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001497 }
drh82c3d632000-06-06 21:56:07 +00001498
drhd8bc7082000-06-07 23:51:50 +00001499 /* Make sure we have a valid query engine. If not, create a new one.
1500 */
danielk19774adee202004-05-08 08:23:19 +00001501 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001502 if( v==0 ){
1503 rc = 1;
1504 goto multi_select_end;
1505 }
drhd8bc7082000-06-07 23:51:50 +00001506
drh1cc3d752002-03-23 00:31:29 +00001507 /* Create the destination temporary table if necessary
1508 */
drh9d2985c2005-09-08 01:58:42 +00001509 if( eDest==SRT_VirtualTab ){
danielk1977b4964b72004-05-18 01:23:38 +00001510 assert( p->pEList );
drh0342b1f2005-09-01 03:07:44 +00001511 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1512 aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 0);
drh1cc3d752002-03-23 00:31:29 +00001513 eDest = SRT_Table;
1514 }
1515
drhf46f9052002-06-22 02:33:38 +00001516 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001517 */
drh0342b1f2005-09-01 03:07:44 +00001518 pOrderBy = p->pOrderBy;
drh82c3d632000-06-06 21:56:07 +00001519 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001520 case TK_ALL: {
drh0342b1f2005-09-01 03:07:44 +00001521 if( pOrderBy==0 ){
danielk1977a2dc3b12005-02-05 12:48:48 +00001522 assert( !pPrior->pLimit );
1523 pPrior->pLimit = p->pLimit;
1524 pPrior->pOffset = p->pOffset;
danielk1977b3bce662005-01-29 08:32:43 +00001525 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001526 if( rc ){
1527 goto multi_select_end;
1528 }
drhf46f9052002-06-22 02:33:38 +00001529 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001530 p->iLimit = pPrior->iLimit;
1531 p->iOffset = pPrior->iOffset;
danielk1977a2dc3b12005-02-05 12:48:48 +00001532 p->pLimit = 0;
1533 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001534 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001535 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001536 if( rc ){
1537 goto multi_select_end;
1538 }
drhf46f9052002-06-22 02:33:38 +00001539 break;
1540 }
1541 /* For UNION ALL ... ORDER BY fall through to the next case */
1542 }
drh82c3d632000-06-06 21:56:07 +00001543 case TK_EXCEPT:
1544 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001545 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001546 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001547 int priorOp; /* The SRT_ operation to apply to prior selects */
danielk1977a2dc3b12005-02-05 12:48:48 +00001548 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
danielk1977dc1bdc42004-06-11 10:51:27 +00001549 int addr;
drh82c3d632000-06-06 21:56:07 +00001550
drhd8bc7082000-06-07 23:51:50 +00001551 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh0342b1f2005-09-01 03:07:44 +00001552 if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
drhd8bc7082000-06-07 23:51:50 +00001553 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001554 ** right.
drhd8bc7082000-06-07 23:51:50 +00001555 */
drh82c3d632000-06-06 21:56:07 +00001556 unionTab = iParm;
1557 }else{
drhd8bc7082000-06-07 23:51:50 +00001558 /* We will need to create our own temporary table to hold the
1559 ** intermediate results.
1560 */
1561 unionTab = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001562 if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001563 rc = 1;
1564 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001565 }
drh9170dd72005-07-08 17:13:46 +00001566 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, unionTab, 0);
drh0342b1f2005-09-01 03:07:44 +00001567 if( priorOp==SRT_Table ){
1568 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1569 aSetP2[nSetP2++] = addr;
1570 }else{
1571 assert( p->addrOpenVirt[0] == -1 );
1572 p->addrOpenVirt[0] = addr;
1573 p->pRightmost->usesVirt = 1;
drhd8bc7082000-06-07 23:51:50 +00001574 }
drh0342b1f2005-09-01 03:07:44 +00001575 createSortingIndex(pParse, p, pOrderBy);
danielk197784ac9d02004-05-18 09:58:06 +00001576 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001577 }
drhd8bc7082000-06-07 23:51:50 +00001578
1579 /* Code the SELECT statements to our left
1580 */
danielk1977b3bce662005-01-29 08:32:43 +00001581 assert( !pPrior->pOrderBy );
1582 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001583 if( rc ){
1584 goto multi_select_end;
1585 }
drhd8bc7082000-06-07 23:51:50 +00001586
1587 /* Code the current SELECT statement
1588 */
1589 switch( p->op ){
1590 case TK_EXCEPT: op = SRT_Except; break;
1591 case TK_UNION: op = SRT_Union; break;
1592 case TK_ALL: op = SRT_Table; break;
1593 }
drh82c3d632000-06-06 21:56:07 +00001594 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001595 p->pOrderBy = 0;
drh4b14b4d2005-09-19 17:35:53 +00001596 p->disallowOrderBy = pOrderBy!=0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001597 pLimit = p->pLimit;
1598 p->pLimit = 0;
1599 pOffset = p->pOffset;
1600 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001601 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001602 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001603 p->pOrderBy = pOrderBy;
danielk1977a2dc3b12005-02-05 12:48:48 +00001604 sqlite3ExprDelete(p->pLimit);
1605 p->pLimit = pLimit;
1606 p->pOffset = pOffset;
drhbe5fd492004-12-16 21:09:16 +00001607 p->iLimit = -1;
1608 p->iOffset = -1;
danielk197784ac9d02004-05-18 09:58:06 +00001609 if( rc ){
1610 goto multi_select_end;
1611 }
1612
drhd8bc7082000-06-07 23:51:50 +00001613
1614 /* Convert the data in the temporary table into whatever form
1615 ** it is that we currently need.
1616 */
drhc926afb2002-06-20 03:38:26 +00001617 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001618 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001619 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001620 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001621 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001622 }
danielk19774adee202004-05-08 08:23:19 +00001623 iBreak = sqlite3VdbeMakeLabel(v);
1624 iCont = sqlite3VdbeMakeLabel(v);
1625 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001626 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001627 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001628 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001629 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001630 iCont, iBreak, 0);
1631 if( rc ){
1632 rc = 1;
1633 goto multi_select_end;
1634 }
danielk19774adee202004-05-08 08:23:19 +00001635 sqlite3VdbeResolveLabel(v, iCont);
1636 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1637 sqlite3VdbeResolveLabel(v, iBreak);
1638 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001639 }
1640 break;
1641 }
1642 case TK_INTERSECT: {
1643 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001644 int iCont, iBreak, iStart;
danielk1977a2dc3b12005-02-05 12:48:48 +00001645 Expr *pLimit, *pOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001646 int addr;
drh82c3d632000-06-06 21:56:07 +00001647
drhd8bc7082000-06-07 23:51:50 +00001648 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001649 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001650 ** by allocating the tables we will need.
1651 */
drh82c3d632000-06-06 21:56:07 +00001652 tab1 = pParse->nTab++;
1653 tab2 = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001654 if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001655 rc = 1;
1656 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001657 }
drh0342b1f2005-09-01 03:07:44 +00001658 createSortingIndex(pParse, p, pOrderBy);
danielk1977dc1bdc42004-06-11 10:51:27 +00001659
drh9170dd72005-07-08 17:13:46 +00001660 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab1, 0);
drh0342b1f2005-09-01 03:07:44 +00001661 assert( p->addrOpenVirt[0] == -1 );
1662 p->addrOpenVirt[0] = addr;
1663 p->pRightmost->usesVirt = 1;
danielk197784ac9d02004-05-18 09:58:06 +00001664 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001665
1666 /* Code the SELECTs to our left into temporary table "tab1".
1667 */
danielk1977b3bce662005-01-29 08:32:43 +00001668 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001669 if( rc ){
1670 goto multi_select_end;
1671 }
drhd8bc7082000-06-07 23:51:50 +00001672
1673 /* Code the current SELECT into temporary table "tab2"
1674 */
drh9170dd72005-07-08 17:13:46 +00001675 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab2, 0);
drh0342b1f2005-09-01 03:07:44 +00001676 assert( p->addrOpenVirt[1] == -1 );
1677 p->addrOpenVirt[1] = addr;
drh82c3d632000-06-06 21:56:07 +00001678 p->pPrior = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001679 pLimit = p->pLimit;
1680 p->pLimit = 0;
1681 pOffset = p->pOffset;
1682 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001683 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001684 p->pPrior = pPrior;
danielk1977a2dc3b12005-02-05 12:48:48 +00001685 sqlite3ExprDelete(p->pLimit);
1686 p->pLimit = pLimit;
1687 p->pOffset = pOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001688 if( rc ){
1689 goto multi_select_end;
1690 }
drhd8bc7082000-06-07 23:51:50 +00001691
1692 /* Generate code to take the intersection of the two temporary
1693 ** tables.
1694 */
drh82c3d632000-06-06 21:56:07 +00001695 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001696 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001697 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001698 }
danielk19774adee202004-05-08 08:23:19 +00001699 iBreak = sqlite3VdbeMakeLabel(v);
1700 iCont = sqlite3VdbeMakeLabel(v);
1701 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001702 computeLimitRegisters(pParse, p);
drh4a9f2412005-06-12 12:01:19 +00001703 iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
danielk19774adee202004-05-08 08:23:19 +00001704 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001705 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001706 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001707 iCont, iBreak, 0);
1708 if( rc ){
1709 rc = 1;
1710 goto multi_select_end;
1711 }
danielk19774adee202004-05-08 08:23:19 +00001712 sqlite3VdbeResolveLabel(v, iCont);
1713 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1714 sqlite3VdbeResolveLabel(v, iBreak);
1715 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1716 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001717 break;
1718 }
1719 }
drh8cdbf832004-08-29 16:25:03 +00001720
1721 /* Make sure all SELECTs in the statement have the same number of elements
1722 ** in their result sets.
1723 */
drh82c3d632000-06-06 21:56:07 +00001724 assert( p->pEList && pPrior->pEList );
1725 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001726 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001727 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001728 rc = 1;
1729 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001730 }
danielk197784ac9d02004-05-18 09:58:06 +00001731
drh8cdbf832004-08-29 16:25:03 +00001732 /* Set the number of columns in temporary tables
1733 */
1734 nCol = p->pEList->nExpr;
drh0342b1f2005-09-01 03:07:44 +00001735 while( nSetP2 ){
1736 sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
drh8cdbf832004-08-29 16:25:03 +00001737 }
1738
drhfbc4ee72004-08-29 01:31:05 +00001739 /* Compute collating sequences used by either the ORDER BY clause or
1740 ** by any temporary tables needed to implement the compound select.
1741 ** Attach the KeyInfo structure to all temporary tables. Invoke the
1742 ** ORDER BY processing if there is an ORDER BY clause.
drh8cdbf832004-08-29 16:25:03 +00001743 **
1744 ** This section is run by the right-most SELECT statement only.
1745 ** SELECT statements to the left always skip this part. The right-most
1746 ** SELECT might also skip this part if it has no ORDER BY clause and
1747 ** no temp tables are required.
drhfbc4ee72004-08-29 01:31:05 +00001748 */
drh0342b1f2005-09-01 03:07:44 +00001749 if( pOrderBy || p->usesVirt ){
drhfbc4ee72004-08-29 01:31:05 +00001750 int i; /* Loop counter */
1751 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
drh0342b1f2005-09-01 03:07:44 +00001752 Select *pLoop; /* For looping through SELECT statements */
1753 CollSeq **apColl;
1754 CollSeq **aCopy;
drhfbc4ee72004-08-29 01:31:05 +00001755
drh0342b1f2005-09-01 03:07:44 +00001756 assert( p->pRightmost==p );
drh4db38a72005-09-01 12:16:28 +00001757 pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*2*sizeof(CollSeq*) + nCol);
danielk1977dc1bdc42004-06-11 10:51:27 +00001758 if( !pKeyInfo ){
1759 rc = SQLITE_NOMEM;
1760 goto multi_select_end;
1761 }
1762
1763 pKeyInfo->enc = pParse->db->enc;
1764 pKeyInfo->nField = nCol;
1765
drh0342b1f2005-09-01 03:07:44 +00001766 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
1767 *apColl = multiSelectCollSeq(pParse, p, i);
1768 if( 0==*apColl ){
1769 *apColl = pParse->db->pDfltColl;
danielk1977dc1bdc42004-06-11 10:51:27 +00001770 }
1771 }
1772
drh0342b1f2005-09-01 03:07:44 +00001773 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
1774 for(i=0; i<2; i++){
1775 int addr = pLoop->addrOpenVirt[i];
1776 if( addr<0 ){
1777 /* If [0] is unused then [1] is also unused. So we can
1778 ** always safely abort as soon as the first unused slot is found */
1779 assert( pLoop->addrOpenVirt[1]<0 );
1780 break;
1781 }
1782 sqlite3VdbeChangeP2(v, addr, nCol);
1783 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
1784 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001785 }
1786
drh0342b1f2005-09-01 03:07:44 +00001787 if( pOrderBy ){
1788 struct ExprList_item *pOTerm = pOrderBy->a;
1789 int nExpr = pOrderBy->nExpr;
1790 int addr;
drh4db38a72005-09-01 12:16:28 +00001791 u8 *pSortOrder;
drh0342b1f2005-09-01 03:07:44 +00001792
1793 aCopy = (CollSeq**)&pKeyInfo[1];
drh4db38a72005-09-01 12:16:28 +00001794 pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nExpr];
drh0342b1f2005-09-01 03:07:44 +00001795 memcpy(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
1796 apColl = pKeyInfo->aColl;
drh4db38a72005-09-01 12:16:28 +00001797 for(i=0; i<pOrderBy->nExpr; i++, pOTerm++, apColl++, pSortOrder++){
drh0342b1f2005-09-01 03:07:44 +00001798 Expr *pExpr = pOTerm->pExpr;
1799 char *zName = pOTerm->zName;
danielk1977dc1bdc42004-06-11 10:51:27 +00001800 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
danielk1977dc1bdc42004-06-11 10:51:27 +00001801 if( zName ){
drh0342b1f2005-09-01 03:07:44 +00001802 *apColl = sqlite3LocateCollSeq(pParse, zName, -1);
danielk1977dc1bdc42004-06-11 10:51:27 +00001803 }else{
drh0342b1f2005-09-01 03:07:44 +00001804 *apColl = aCopy[pExpr->iColumn];
danielk1977dc1bdc42004-06-11 10:51:27 +00001805 }
drh4db38a72005-09-01 12:16:28 +00001806 *pSortOrder = pOTerm->sortOrder;
danielk1977dc1bdc42004-06-11 10:51:27 +00001807 }
drh0342b1f2005-09-01 03:07:44 +00001808 assert( p->pRightmost==p );
1809 assert( p->addrOpenVirt[2]>=0 );
1810 addr = p->addrOpenVirt[2];
drh4db38a72005-09-01 12:16:28 +00001811 sqlite3VdbeChangeP2(v, addr, p->pEList->nExpr+2);
drha7aa59e2005-09-19 15:37:06 +00001812 pKeyInfo->nField = pOrderBy->nExpr;
drh4db38a72005-09-01 12:16:28 +00001813 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
1814 pKeyInfo = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001815 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1816 }
1817
drh0342b1f2005-09-01 03:07:44 +00001818 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001819 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001820
1821multi_select_end:
danielk197784ac9d02004-05-18 09:58:06 +00001822 return rc;
drh22827922000-06-06 17:27:05 +00001823}
drhb7f91642004-10-31 02:22:47 +00001824#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drh22827922000-06-06 17:27:05 +00001825
drhb7f91642004-10-31 02:22:47 +00001826#ifndef SQLITE_OMIT_VIEW
drh22827922000-06-06 17:27:05 +00001827/*
drh832508b2002-03-02 17:04:07 +00001828** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001829** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001830** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001831** unchanged.)
drh832508b2002-03-02 17:04:07 +00001832**
1833** This routine is part of the flattening procedure. A subquery
1834** whose result set is defined by pEList appears as entry in the
1835** FROM clause of a SELECT such that the VDBE cursor assigned to that
1836** FORM clause entry is iTable. This routine make the necessary
1837** changes to pExpr so that it refers directly to the source table
1838** of the subquery rather the result set of the subquery.
1839*/
drh6a3ea0e2003-05-02 14:32:12 +00001840static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
danielk1977b3bce662005-01-29 08:32:43 +00001841static void substSelect(Select *, int, ExprList *); /* Forward Decl */
drh6a3ea0e2003-05-02 14:32:12 +00001842static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001843 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001844 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1845 if( pExpr->iColumn<0 ){
1846 pExpr->op = TK_NULL;
1847 }else{
1848 Expr *pNew;
1849 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1850 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1851 pNew = pEList->a[pExpr->iColumn].pExpr;
1852 assert( pNew!=0 );
1853 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001854 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001855 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001856 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001857 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001858 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001859 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001860 pExpr->iTable = pNew->iTable;
1861 pExpr->iColumn = pNew->iColumn;
1862 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001863 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1864 sqlite3TokenCopy(&pExpr->span, &pNew->span);
danielk1977a1cb1832005-02-12 08:59:55 +00001865 pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
1866 pExpr->flags = pNew->flags;
drh50350a12004-02-13 16:22:22 +00001867 }
drh832508b2002-03-02 17:04:07 +00001868 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001869 substExpr(pExpr->pLeft, iTable, pEList);
1870 substExpr(pExpr->pRight, iTable, pEList);
danielk1977b3bce662005-01-29 08:32:43 +00001871 substSelect(pExpr->pSelect, iTable, pEList);
drh6a3ea0e2003-05-02 14:32:12 +00001872 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001873 }
1874}
danielk1977b3bce662005-01-29 08:32:43 +00001875static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001876 int i;
1877 if( pList==0 ) return;
1878 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001879 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001880 }
1881}
danielk1977b3bce662005-01-29 08:32:43 +00001882static void substSelect(Select *p, int iTable, ExprList *pEList){
1883 if( !p ) return;
1884 substExprList(p->pEList, iTable, pEList);
1885 substExprList(p->pGroupBy, iTable, pEList);
1886 substExprList(p->pOrderBy, iTable, pEList);
1887 substExpr(p->pHaving, iTable, pEList);
1888 substExpr(p->pWhere, iTable, pEList);
1889}
drhb7f91642004-10-31 02:22:47 +00001890#endif /* !defined(SQLITE_OMIT_VIEW) */
drh832508b2002-03-02 17:04:07 +00001891
drhb7f91642004-10-31 02:22:47 +00001892#ifndef SQLITE_OMIT_VIEW
drh832508b2002-03-02 17:04:07 +00001893/*
drh1350b032002-02-27 19:00:20 +00001894** This routine attempts to flatten subqueries in order to speed
1895** execution. It returns 1 if it makes changes and 0 if no flattening
1896** occurs.
1897**
1898** To understand the concept of flattening, consider the following
1899** query:
1900**
1901** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1902**
1903** The default way of implementing this query is to execute the
1904** subquery first and store the results in a temporary table, then
1905** run the outer query on that temporary table. This requires two
1906** passes over the data. Furthermore, because the temporary table
1907** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001908** optimized.
drh1350b032002-02-27 19:00:20 +00001909**
drh832508b2002-03-02 17:04:07 +00001910** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001911** a single flat select, like this:
1912**
1913** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1914**
1915** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001916** but only has to scan the data once. And because indices might
1917** exist on the table t1, a complete scan of the data might be
1918** avoided.
drh1350b032002-02-27 19:00:20 +00001919**
drh832508b2002-03-02 17:04:07 +00001920** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001921**
drh832508b2002-03-02 17:04:07 +00001922** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001923**
drh832508b2002-03-02 17:04:07 +00001924** (2) The subquery is not an aggregate or the outer query is not a join.
1925**
drh8af4d3a2003-05-06 20:35:16 +00001926** (3) The subquery is not the right operand of a left outer join, or
1927** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001928**
1929** (4) The subquery is not DISTINCT or the outer query is not a join.
1930**
1931** (5) The subquery is not DISTINCT or the outer query does not use
1932** aggregates.
1933**
1934** (6) The subquery does not use aggregates or the outer query is not
1935** DISTINCT.
1936**
drh08192d52002-04-30 19:20:28 +00001937** (7) The subquery has a FROM clause.
1938**
drhdf199a22002-06-14 22:38:41 +00001939** (8) The subquery does not use LIMIT or the outer query is not a join.
1940**
1941** (9) The subquery does not use LIMIT or the outer query does not use
1942** aggregates.
1943**
1944** (10) The subquery does not use aggregates or the outer query does not
1945** use LIMIT.
1946**
drh174b6192002-12-03 02:22:52 +00001947** (11) The subquery and the outer query do not both have ORDER BY clauses.
1948**
drh3fc673e2003-06-16 00:40:34 +00001949** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1950** subquery has no WHERE clause. (added by ticket #350)
1951**
drh832508b2002-03-02 17:04:07 +00001952** In this routine, the "p" parameter is a pointer to the outer query.
1953** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1954** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1955**
drh665de472003-03-31 13:36:09 +00001956** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001957** If flattening is attempted this routine returns 1.
1958**
1959** All of the expression analysis must occur on both the outer query and
1960** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001961*/
drh8c74a8c2002-08-25 19:20:40 +00001962static int flattenSubquery(
1963 Parse *pParse, /* The parsing context */
1964 Select *p, /* The parent or outer SELECT statement */
1965 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1966 int isAgg, /* True if outer SELECT uses aggregate functions */
1967 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1968){
drh0bb28102002-05-08 11:54:14 +00001969 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001970 SrcList *pSrc; /* The FROM clause of the outer query */
1971 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001972 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001973 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh91bb0ee2004-09-01 03:06:34 +00001974 int i; /* Loop counter */
1975 Expr *pWhere; /* The WHERE clause */
1976 struct SrcList_item *pSubitem; /* The subquery */
drh1350b032002-02-27 19:00:20 +00001977
drh832508b2002-03-02 17:04:07 +00001978 /* Check to see if flattening is permitted. Return 0 if not.
1979 */
1980 if( p==0 ) return 0;
1981 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001982 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh91bb0ee2004-09-01 03:06:34 +00001983 pSubitem = &pSrc->a[iFrom];
1984 pSub = pSubitem->pSelect;
drh832508b2002-03-02 17:04:07 +00001985 assert( pSub!=0 );
1986 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001987 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001988 pSubSrc = pSub->pSrc;
1989 assert( pSubSrc );
danielk1977a2dc3b12005-02-05 12:48:48 +00001990 if( (pSub->pLimit && p->pLimit) || pSub->pOffset ||
1991 (pSub->pLimit && isAgg) ) return 0;
drhc31c2eb2003-05-02 16:04:17 +00001992 if( pSubSrc->nSrc==0 ) return 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001993 if( pSub->isDistinct && (pSrc->nSrc>1 || isAgg) ){
drhdf199a22002-06-14 22:38:41 +00001994 return 0;
1995 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001996 if( p->isDistinct && subqueryIsAgg ) return 0;
drh4b14b4d2005-09-19 17:35:53 +00001997 if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001998
drh8af4d3a2003-05-06 20:35:16 +00001999 /* Restriction 3: If the subquery is a join, make sure the subquery is
2000 ** not used as the right operand of an outer join. Examples of why this
2001 ** is not allowed:
2002 **
2003 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
2004 **
2005 ** If we flatten the above, we would get
2006 **
2007 ** (t1 LEFT OUTER JOIN t2) JOIN t3
2008 **
2009 ** which is not at all the same thing.
2010 */
2011 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
2012 return 0;
2013 }
2014
drh3fc673e2003-06-16 00:40:34 +00002015 /* Restriction 12: If the subquery is the right operand of a left outer
2016 ** join, make sure the subquery has no WHERE clause.
2017 ** An examples of why this is not allowed:
2018 **
2019 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
2020 **
2021 ** If we flatten the above, we would get
2022 **
2023 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
2024 **
2025 ** But the t2.x>0 test will always fail on a NULL row of t2, which
2026 ** effectively converts the OUTER JOIN into an INNER JOIN.
2027 */
2028 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
2029 && pSub->pWhere!=0 ){
2030 return 0;
2031 }
2032
drh0bb28102002-05-08 11:54:14 +00002033 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00002034 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00002035 */
drhc31c2eb2003-05-02 16:04:17 +00002036
2037 /* Move all of the FROM elements of the subquery into the
2038 ** the FROM clause of the outer query. Before doing this, remember
2039 ** the cursor number for the original outer query FROM element in
2040 ** iParent. The iParent cursor will never be used. Subsequent code
2041 ** will scan expressions looking for iParent references and replace
2042 ** those references with expressions that resolve to the subquery FROM
2043 ** elements we are now copying in.
2044 */
drh91bb0ee2004-09-01 03:06:34 +00002045 iParent = pSubitem->iCursor;
drhc31c2eb2003-05-02 16:04:17 +00002046 {
2047 int nSubSrc = pSubSrc->nSrc;
drh91bb0ee2004-09-01 03:06:34 +00002048 int jointype = pSubitem->jointype;
drhc31c2eb2003-05-02 16:04:17 +00002049
drhed8a3bb2005-06-06 21:19:56 +00002050 sqlite3DeleteTable(0, pSubitem->pTab);
drh91bb0ee2004-09-01 03:06:34 +00002051 sqliteFree(pSubitem->zDatabase);
2052 sqliteFree(pSubitem->zName);
2053 sqliteFree(pSubitem->zAlias);
drhc31c2eb2003-05-02 16:04:17 +00002054 if( nSubSrc>1 ){
2055 int extra = nSubSrc - 1;
2056 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00002057 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00002058 }
2059 p->pSrc = pSrc;
2060 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2061 pSrc->a[i] = pSrc->a[i-extra];
2062 }
2063 }
2064 for(i=0; i<nSubSrc; i++){
2065 pSrc->a[i+iFrom] = pSubSrc->a[i];
2066 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2067 }
drh8af4d3a2003-05-06 20:35:16 +00002068 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00002069 }
2070
2071 /* Now begin substituting subquery result set expressions for
2072 ** references to the iParent in the outer query.
2073 **
2074 ** Example:
2075 **
2076 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2077 ** \ \_____________ subquery __________/ /
2078 ** \_____________________ outer query ______________________________/
2079 **
2080 ** We look at every expression in the outer query and every place we see
2081 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2082 */
drh6a3ea0e2003-05-02 14:32:12 +00002083 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00002084 pList = p->pEList;
2085 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00002086 Expr *pExpr;
2087 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
2088 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00002089 }
2090 }
drh1b2e0322002-03-03 02:49:51 +00002091 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00002092 substExprList(p->pGroupBy, iParent, pSub->pEList);
2093 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00002094 }
drh174b6192002-12-03 02:22:52 +00002095 if( pSub->pOrderBy ){
2096 assert( p->pOrderBy==0 );
2097 p->pOrderBy = pSub->pOrderBy;
2098 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00002099 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00002100 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00002101 }
drh832508b2002-03-02 17:04:07 +00002102 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002103 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00002104 }else{
2105 pWhere = 0;
2106 }
2107 if( subqueryIsAgg ){
2108 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00002109 p->pHaving = p->pWhere;
2110 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00002111 substExpr(p->pHaving, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002112 p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
drh1b2e0322002-03-03 02:49:51 +00002113 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00002114 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00002115 }else{
drh6a3ea0e2003-05-02 14:32:12 +00002116 substExpr(p->pWhere, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002117 p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
drh832508b2002-03-02 17:04:07 +00002118 }
drhc31c2eb2003-05-02 16:04:17 +00002119
2120 /* The flattened query is distinct if either the inner or the
2121 ** outer query is distinct.
2122 */
drh832508b2002-03-02 17:04:07 +00002123 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00002124
danielk1977a58fdfb2005-02-08 07:50:40 +00002125 /*
2126 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2127 */
danielk1977a2dc3b12005-02-05 12:48:48 +00002128 if( pSub->pLimit ){
2129 p->pLimit = pSub->pLimit;
2130 pSub->pLimit = 0;
drhdf199a22002-06-14 22:38:41 +00002131 }
drh8c74a8c2002-08-25 19:20:40 +00002132
drhc31c2eb2003-05-02 16:04:17 +00002133 /* Finially, delete what is left of the subquery and return
2134 ** success.
2135 */
danielk19774adee202004-05-08 08:23:19 +00002136 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00002137 return 1;
2138}
drhb7f91642004-10-31 02:22:47 +00002139#endif /* SQLITE_OMIT_VIEW */
drh1350b032002-02-27 19:00:20 +00002140
2141/*
drh9562b552002-02-19 15:00:07 +00002142** Analyze the SELECT statement passed in as an argument to see if it
2143** is a simple min() or max() query. If it is and this query can be
2144** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00002145** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00002146** simple min() or max() query, then return 0;
2147**
2148** A simply min() or max() query looks like this:
2149**
2150** SELECT min(a) FROM table;
2151** SELECT max(a) FROM table;
2152**
2153** The query may have only a single table in its FROM argument. There
2154** can be no GROUP BY or HAVING or WHERE clauses. The result set must
2155** be the min() or max() of a single column of the table. The column
2156** in the min() or max() function must be indexed.
2157**
danielk19774adee202004-05-08 08:23:19 +00002158** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00002159** See the header comment on that routine for additional information.
2160*/
2161static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2162 Expr *pExpr;
2163 int iCol;
2164 Table *pTab;
2165 Index *pIdx;
2166 int base;
2167 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00002168 int seekOp;
2169 int cont;
drh6e175292004-03-13 14:00:36 +00002170 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00002171 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00002172 SrcList *pSrc;
drh9562b552002-02-19 15:00:07 +00002173
2174 /* Check to see if this query is a simple min() or max() query. Return
2175 ** zero if it is not.
2176 */
2177 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00002178 pSrc = p->pSrc;
2179 if( pSrc->nSrc!=1 ) return 0;
2180 pEList = p->pEList;
2181 if( pEList->nExpr!=1 ) return 0;
2182 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002183 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002184 pList = pExpr->pList;
2185 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002186 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00002187 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002188 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00002189 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002190 seekOp = OP_Last;
2191 }else{
2192 return 0;
2193 }
drh6e175292004-03-13 14:00:36 +00002194 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002195 if( pExpr->op!=TK_COLUMN ) return 0;
2196 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002197 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002198
2199 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002200 ** Check to make sure we have an index and make pIdx point to the
2201 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2202 ** key column, no index is necessary so set pIdx to NULL. If no
2203 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002204 */
2205 if( iCol<0 ){
2206 pIdx = 0;
2207 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002208 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002209 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2210 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002211 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002212 }
2213 if( pIdx==0 ) return 0;
2214 }
2215
drhe5f50722003-07-19 00:44:14 +00002216 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002217 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002218 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002219 */
danielk19774adee202004-05-08 08:23:19 +00002220 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002221 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002222
drh0c37e632004-01-30 02:01:03 +00002223 /* If the output is destined for a temporary table, open that table.
2224 */
drh9d2985c2005-09-08 01:58:42 +00002225 if( eDest==SRT_VirtualTab ){
drhd81bd4e2005-09-05 20:06:49 +00002226 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002227 }
2228
drh17f71932002-02-21 12:01:27 +00002229 /* Generating code to find the min or the max. Basically all we have
2230 ** to do is find the first or the last entry in the chosen index. If
2231 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2232 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002233 */
danielk19774adee202004-05-08 08:23:19 +00002234 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00002235 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00002236 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00002237 if( pSrc->a[0].pSelect==0 ){
drhad6d9462004-09-19 02:15:24 +00002238 sqlite3OpenTableForReading(v, base, pTab);
drh6e175292004-03-13 14:00:36 +00002239 }
danielk19774adee202004-05-08 08:23:19 +00002240 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00002241 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002242 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002243 }else{
danielk19773719d7f2005-01-17 08:57:09 +00002244 /* Even though the cursor used to open the index here is closed
2245 ** as soon as a single value has been read from it, allocate it
2246 ** using (pParse->nTab++) to prevent the cursor id from being
2247 ** reused. This is important for statements of the form
2248 ** "INSERT INTO x SELECT max() FROM x".
2249 */
2250 int iIdx;
2251 iIdx = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +00002252 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002253 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
drhd3d39e92004-05-20 22:16:29 +00002254 (char*)&pIdx->keyInfo, P3_KEYINFO);
drh9eb516c2004-07-18 20:52:32 +00002255 if( seekOp==OP_Rewind ){
drhf0863fe2005-06-12 21:35:51 +00002256 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh1af3fdb2004-07-18 21:33:01 +00002257 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2258 seekOp = OP_MoveGt;
drh9eb516c2004-07-18 20:52:32 +00002259 }
danielk19773719d7f2005-01-17 08:57:09 +00002260 sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
drhf0863fe2005-06-12 21:35:51 +00002261 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002262 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002263 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002264 }
drh5cf8e8c2002-02-19 22:42:05 +00002265 eList.nExpr = 1;
2266 memset(&eListItem, 0, sizeof(eListItem));
2267 eList.a = &eListItem;
2268 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00002269 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00002270 sqlite3VdbeResolveLabel(v, cont);
2271 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002272
drh9562b552002-02-19 15:00:07 +00002273 return 1;
2274}
2275
2276/*
drh290c1942004-08-21 17:54:45 +00002277** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
2278** the number of errors seen.
2279**
2280** An ORDER BY or GROUP BY is a list of expressions. If any expression
2281** is an integer constant, then that expression is replaced by the
2282** corresponding entry in the result set.
2283*/
2284static int processOrderGroupBy(
danielk1977b3bce662005-01-29 08:32:43 +00002285 NameContext *pNC, /* Name context of the SELECT statement. */
drh290c1942004-08-21 17:54:45 +00002286 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
drh290c1942004-08-21 17:54:45 +00002287 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
2288){
2289 int i;
danielk1977b3bce662005-01-29 08:32:43 +00002290 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */
2291 Parse *pParse = pNC->pParse; /* The result set of the SELECT */
2292 assert( pEList );
2293
drh290c1942004-08-21 17:54:45 +00002294 if( pOrderBy==0 ) return 0;
2295 for(i=0; i<pOrderBy->nExpr; i++){
2296 int iCol;
2297 Expr *pE = pOrderBy->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +00002298 if( sqlite3ExprIsInteger(pE, &iCol) ){
2299 if( iCol>0 && iCol<=pEList->nExpr ){
2300 sqlite3ExprDelete(pE);
2301 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2302 }else{
drh290c1942004-08-21 17:54:45 +00002303 sqlite3ErrorMsg(pParse,
2304 "%s BY column number %d out of range - should be "
2305 "between 1 and %d", zType, iCol, pEList->nExpr);
2306 return 1;
2307 }
2308 }
danielk1977b3bce662005-01-29 08:32:43 +00002309 if( sqlite3ExprResolveNames(pNC, pE) ){
2310 return 1;
2311 }
2312 if( sqlite3ExprIsConstant(pE) ){
2313 sqlite3ErrorMsg(pParse,
2314 "%s BY terms must not be non-integer constants", zType);
2315 return 1;
2316 }
drh290c1942004-08-21 17:54:45 +00002317 }
2318 return 0;
2319}
2320
2321/*
danielk1977b3bce662005-01-29 08:32:43 +00002322** This routine resolves any names used in the result set of the
2323** supplied SELECT statement. If the SELECT statement being resolved
2324** is a sub-select, then pOuterNC is a pointer to the NameContext
2325** of the parent SELECT.
2326*/
2327int sqlite3SelectResolve(
2328 Parse *pParse, /* The parser context */
2329 Select *p, /* The SELECT statement being coded. */
2330 NameContext *pOuterNC /* The outer name context. May be NULL. */
2331){
2332 ExprList *pEList; /* Result set. */
2333 int i; /* For-loop variable used in multiple places */
2334 NameContext sNC; /* Local name-context */
drh13449892005-09-07 21:22:45 +00002335 ExprList *pGroupBy; /* The group by clause */
danielk1977b3bce662005-01-29 08:32:43 +00002336
2337 /* If this routine has run before, return immediately. */
2338 if( p->isResolved ){
2339 assert( !pOuterNC );
2340 return SQLITE_OK;
2341 }
2342 p->isResolved = 1;
2343
2344 /* If there have already been errors, do nothing. */
2345 if( pParse->nErr>0 ){
2346 return SQLITE_ERROR;
2347 }
2348
2349 /* Prepare the select statement. This call will allocate all cursors
2350 ** required to handle the tables and subqueries in the FROM clause.
2351 */
2352 if( prepSelectStmt(pParse, p) ){
2353 return SQLITE_ERROR;
2354 }
2355
danielk1977a2dc3b12005-02-05 12:48:48 +00002356 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2357 ** are not allowed to refer to any names, so pass an empty NameContext.
2358 */
danielk1977b3bce662005-01-29 08:32:43 +00002359 sNC.pParse = pParse;
danielk1977b3bce662005-01-29 08:32:43 +00002360 sNC.hasAgg = 0;
2361 sNC.nErr = 0;
2362 sNC.nRef = 0;
2363 sNC.pEList = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00002364 sNC.allowAgg = 0;
2365 sNC.pSrcList = 0;
2366 sNC.pNext = 0;
2367 if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2368 sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2369 return SQLITE_ERROR;
2370 }
2371
2372 /* Set up the local name-context to pass to ExprResolveNames() to
2373 ** resolve the expression-list.
2374 */
2375 sNC.allowAgg = 1;
2376 sNC.pSrcList = p->pSrc;
2377 sNC.pNext = pOuterNC;
danielk1977b3bce662005-01-29 08:32:43 +00002378
danielk1977b3bce662005-01-29 08:32:43 +00002379 /* Resolve names in the result set. */
2380 pEList = p->pEList;
2381 if( !pEList ) return SQLITE_ERROR;
2382 for(i=0; i<pEList->nExpr; i++){
2383 Expr *pX = pEList->a[i].pExpr;
2384 if( sqlite3ExprResolveNames(&sNC, pX) ){
2385 return SQLITE_ERROR;
2386 }
2387 }
2388
2389 /* If there are no aggregate functions in the result-set, and no GROUP BY
2390 ** expression, do not allow aggregates in any of the other expressions.
2391 */
2392 assert( !p->isAgg );
drh13449892005-09-07 21:22:45 +00002393 pGroupBy = p->pGroupBy;
2394 if( pGroupBy || sNC.hasAgg ){
danielk1977b3bce662005-01-29 08:32:43 +00002395 p->isAgg = 1;
2396 }else{
2397 sNC.allowAgg = 0;
2398 }
2399
2400 /* If a HAVING clause is present, then there must be a GROUP BY clause.
2401 */
drh13449892005-09-07 21:22:45 +00002402 if( p->pHaving && !pGroupBy ){
danielk1977b3bce662005-01-29 08:32:43 +00002403 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2404 return SQLITE_ERROR;
2405 }
2406
2407 /* Add the expression list to the name-context before parsing the
2408 ** other expressions in the SELECT statement. This is so that
2409 ** expressions in the WHERE clause (etc.) can refer to expressions by
2410 ** aliases in the result set.
2411 **
2412 ** Minor point: If this is the case, then the expression will be
2413 ** re-evaluated for each reference to it.
2414 */
2415 sNC.pEList = p->pEList;
2416 if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2417 sqlite3ExprResolveNames(&sNC, p->pHaving) ||
2418 processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
drh13449892005-09-07 21:22:45 +00002419 processOrderGroupBy(&sNC, pGroupBy, "GROUP")
danielk1977b3bce662005-01-29 08:32:43 +00002420 ){
2421 return SQLITE_ERROR;
2422 }
2423
drh13449892005-09-07 21:22:45 +00002424 /* Make sure the GROUP BY clause does not contain aggregate functions.
2425 */
2426 if( pGroupBy ){
2427 struct ExprList_item *pItem;
2428
2429 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
2430 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
2431 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
2432 "the GROUP BY clause");
2433 return SQLITE_ERROR;
2434 }
2435 }
2436 }
2437
danielk1977b3bce662005-01-29 08:32:43 +00002438 return SQLITE_OK;
2439}
2440
2441/*
drh13449892005-09-07 21:22:45 +00002442** Reset the aggregate accumulator.
2443**
2444** The aggregate accumulator is a set of memory cells that hold
2445** intermediate results while calculating an aggregate. This
2446** routine simply stores NULLs in all of those memory cells.
danielk1977b3bce662005-01-29 08:32:43 +00002447*/
drh13449892005-09-07 21:22:45 +00002448static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
2449 Vdbe *v = pParse->pVdbe;
2450 int i;
drhc99130f2005-09-11 11:56:27 +00002451 struct AggInfo_func *pFunc;
drh13449892005-09-07 21:22:45 +00002452 if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
2453 return;
2454 }
drh13449892005-09-07 21:22:45 +00002455 for(i=0; i<pAggInfo->nColumn; i++){
drhd654be82005-09-20 17:42:23 +00002456 sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
drh13449892005-09-07 21:22:45 +00002457 }
drhc99130f2005-09-11 11:56:27 +00002458 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
drhd654be82005-09-20 17:42:23 +00002459 sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
drhc99130f2005-09-11 11:56:27 +00002460 if( pFunc->iDistinct>=0 ){
2461 Expr *pE = pFunc->pExpr;
2462 if( pE->pList==0 || pE->pList->nExpr!=1 ){
2463 sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
2464 "by an expression");
2465 pFunc->iDistinct = -1;
2466 }else{
2467 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
2468 sqlite3VdbeOp3(v, OP_OpenVirtual, pFunc->iDistinct, 0,
2469 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2470 }
2471 }
drh13449892005-09-07 21:22:45 +00002472 }
danielk1977b3bce662005-01-29 08:32:43 +00002473}
2474
2475/*
drh13449892005-09-07 21:22:45 +00002476** Invoke the OP_AggFinalize opcode for every aggregate function
2477** in the AggInfo structure.
danielk1977b3bce662005-01-29 08:32:43 +00002478*/
drh13449892005-09-07 21:22:45 +00002479static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
2480 Vdbe *v = pParse->pVdbe;
2481 int i;
2482 struct AggInfo_func *pF;
2483 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
drha10a34b2005-09-07 22:09:48 +00002484 ExprList *pList = pF->pExpr->pList;
2485 sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
2486 (void*)pF->pFunc, P3_FUNCDEF);
drh13449892005-09-07 21:22:45 +00002487 }
danielk1977b3bce662005-01-29 08:32:43 +00002488}
drh13449892005-09-07 21:22:45 +00002489
2490/*
2491** Update the accumulator memory cells for an aggregate based on
2492** the current cursor position.
2493*/
2494static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
2495 Vdbe *v = pParse->pVdbe;
2496 int i;
2497 struct AggInfo_func *pF;
2498 struct AggInfo_col *pC;
drh13449892005-09-07 21:22:45 +00002499
2500 pAggInfo->directMode = 1;
2501 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
2502 int nArg;
drhc99130f2005-09-11 11:56:27 +00002503 int addrNext = 0;
drh13449892005-09-07 21:22:45 +00002504 ExprList *pList = pF->pExpr->pList;
2505 if( pList ){
2506 nArg = pList->nExpr;
2507 sqlite3ExprCodeExprList(pParse, pList);
2508 }else{
2509 nArg = 0;
2510 }
drhc99130f2005-09-11 11:56:27 +00002511 if( pF->iDistinct>=0 ){
2512 addrNext = sqlite3VdbeMakeLabel(v);
2513 assert( nArg==1 );
drh9d4673a2005-09-12 23:03:16 +00002514 codeDistinct(v, pF->iDistinct, addrNext, 1, 2);
drhc99130f2005-09-11 11:56:27 +00002515 }
drh13449892005-09-07 21:22:45 +00002516 if( pF->pFunc->needCollSeq ){
2517 CollSeq *pColl = 0;
2518 struct ExprList_item *pItem;
2519 int j;
2520 for(j=0, pItem=pList->a; !pColl && j<pList->nExpr; j++, pItem++){
2521 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
2522 }
2523 if( !pColl ){
2524 pColl = pParse->db->pDfltColl;
2525 }
2526 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2527 }
2528 sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
drhc99130f2005-09-11 11:56:27 +00002529 if( addrNext ){
2530 sqlite3VdbeResolveLabel(v, addrNext);
2531 }
drh13449892005-09-07 21:22:45 +00002532 }
drh13449892005-09-07 21:22:45 +00002533 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
drh5774b802005-09-07 22:48:16 +00002534 sqlite3ExprCode(pParse, pC->pExpr);
drh13449892005-09-07 21:22:45 +00002535 sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
2536 }
2537 pAggInfo->directMode = 0;
2538}
2539
2540
danielk1977b3bce662005-01-29 08:32:43 +00002541/*
drh9bb61fe2000-06-05 16:01:39 +00002542** Generate code for the given SELECT statement.
2543**
drhfef52082000-06-06 01:50:43 +00002544** The results are distributed in various ways depending on the
2545** value of eDest and iParm.
2546**
2547** eDest Value Result
2548** ------------ -------------------------------------------
2549** SRT_Callback Invoke the callback for each row of the result.
2550**
2551** SRT_Mem Store first result in memory cell iParm
2552**
danielk1977e014a832004-05-17 10:48:57 +00002553** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002554**
drh82c3d632000-06-06 21:56:07 +00002555** SRT_Union Store results as a key in a temporary table iParm
2556**
jplyon4b11c6d2004-01-19 04:57:53 +00002557** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002558**
2559** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002560**
drhe78e8282003-01-19 03:59:45 +00002561** The table above is incomplete. Additional eDist value have be added
2562** since this comment was written. See the selectInnerLoop() function for
2563** a complete listing of the allowed values of eDest and their meanings.
2564**
drh9bb61fe2000-06-05 16:01:39 +00002565** This routine returns the number of errors. If any errors are
2566** encountered, then an appropriate error message is left in
2567** pParse->zErrMsg.
2568**
2569** This routine does NOT free the Select structure passed in. The
2570** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002571**
2572** The pParent, parentTab, and *pParentAgg fields are filled in if this
2573** SELECT is a subquery. This routine may try to combine this SELECT
2574** with its parent to form a single flat query. In so doing, it might
2575** change the parent query from a non-aggregate to an aggregate query.
2576** For that reason, the pParentAgg flag is passed as a pointer, so it
2577** can be changed.
drhe78e8282003-01-19 03:59:45 +00002578**
2579** Example 1: The meaning of the pParent parameter.
2580**
2581** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2582** \ \_______ subquery _______/ /
2583** \ /
2584** \____________________ outer query ___________________/
2585**
2586** This routine is called for the outer query first. For that call,
2587** pParent will be NULL. During the processing of the outer query, this
2588** routine is called recursively to handle the subquery. For the recursive
2589** call, pParent will point to the outer query. Because the subquery is
2590** the second element in a three-way join, the parentTab parameter will
2591** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002592*/
danielk19774adee202004-05-08 08:23:19 +00002593int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002594 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002595 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002596 int eDest, /* How to dispose of the results */
2597 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002598 Select *pParent, /* Another SELECT for which this is a sub-query */
2599 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002600 int *pParentAgg, /* True if pParent uses aggregate functions */
danielk1977b3bce662005-01-29 08:32:43 +00002601 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002602){
drh13449892005-09-07 21:22:45 +00002603 int i, j; /* Loop counters */
2604 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
2605 Vdbe *v; /* The virtual machine under construction */
danielk1977b3bce662005-01-29 08:32:43 +00002606 int isAgg; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002607 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002608 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002609 Expr *pWhere; /* The WHERE clause. May be NULL */
2610 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002611 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2612 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002613 int isDistinct; /* True if the DISTINCT keyword is present */
2614 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002615 int rc = 1; /* Value to return from this function */
drh9d2985c2005-09-08 01:58:42 +00002616 int addrSortIndex; /* Address of an OP_OpenVirtual instruction */
drh13449892005-09-07 21:22:45 +00002617 AggInfo sAggInfo; /* Information used by aggregate queries */
drh9bb61fe2000-06-05 16:01:39 +00002618
danielk19776f8a5032004-05-10 10:34:51 +00002619 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002620 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drh13449892005-09-07 21:22:45 +00002621 memset(&sAggInfo, 0, sizeof(sAggInfo));
drhdaffd0e2001-04-11 14:28:42 +00002622
drhb7f91642004-10-31 02:22:47 +00002623#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +00002624 /* If there is are a sequence of queries, do the earlier ones first.
2625 */
2626 if( p->pPrior ){
drh0342b1f2005-09-01 03:07:44 +00002627 if( p->pRightmost==0 ){
2628 Select *pLoop;
2629 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
2630 pLoop->pRightmost = p;
2631 }
2632 }
danielk197784ac9d02004-05-18 09:58:06 +00002633 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002634 }
drhb7f91642004-10-31 02:22:47 +00002635#endif
drh82c3d632000-06-06 21:56:07 +00002636
danielk1977b3bce662005-01-29 08:32:43 +00002637 pOrderBy = p->pOrderBy;
drh13449892005-09-07 21:22:45 +00002638 if( IgnorableOrderby(eDest) ){
danielk1977b3bce662005-01-29 08:32:43 +00002639 p->pOrderBy = 0;
2640 }
2641 if( sqlite3SelectResolve(pParse, p, 0) ){
2642 goto select_end;
2643 }
2644 p->pOrderBy = pOrderBy;
2645
drh82c3d632000-06-06 21:56:07 +00002646 /* Make local copies of the parameters for this query.
2647 */
drh9bb61fe2000-06-05 16:01:39 +00002648 pTabList = p->pSrc;
2649 pWhere = p->pWhere;
drh22827922000-06-06 17:27:05 +00002650 pGroupBy = p->pGroupBy;
2651 pHaving = p->pHaving;
danielk1977b3bce662005-01-29 08:32:43 +00002652 isAgg = p->isAgg;
drh19a775c2000-06-05 18:54:46 +00002653 isDistinct = p->isDistinct;
danielk1977b3bce662005-01-29 08:32:43 +00002654 pEList = p->pEList;
2655 if( pEList==0 ) goto select_end;
drh9bb61fe2000-06-05 16:01:39 +00002656
2657 /*
2658 ** Do not even attempt to generate any code if we have already seen
2659 ** errors before this routine starts.
2660 */
drh1d83f052002-02-17 00:30:36 +00002661 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002662
drh22827922000-06-06 17:27:05 +00002663 /* If writing to memory or generating a set
2664 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002665 */
drh51522cd2005-01-20 13:36:19 +00002666 assert( eDest!=SRT_Exists || pEList->nExpr==1 );
danielk197793758c82005-01-21 08:13:14 +00002667#ifndef SQLITE_OMIT_SUBQUERY
drhfef52082000-06-06 01:50:43 +00002668 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002669 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002670 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002671 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002672 }
danielk197793758c82005-01-21 08:13:14 +00002673#endif
drh19a775c2000-06-05 18:54:46 +00002674
drhc926afb2002-06-20 03:38:26 +00002675 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002676 */
drh13449892005-09-07 21:22:45 +00002677 if( IgnorableOrderby(eDest) ){
2678 pOrderBy = 0;
drh22827922000-06-06 17:27:05 +00002679 }
2680
drhd820cb12002-02-18 03:21:45 +00002681 /* Begin generating code.
2682 */
danielk19774adee202004-05-08 08:23:19 +00002683 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002684 if( v==0 ) goto select_end;
2685
drhe78e8282003-01-19 03:59:45 +00002686 /* Identify column names if we will be using them in a callback. This
2687 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002688 */
2689 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002690 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002691 }
2692
drhd820cb12002-02-18 03:21:45 +00002693 /* Generate code for all sub-queries in the FROM clause
2694 */
drh51522cd2005-01-20 13:36:19 +00002695#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
drhad3cab52002-05-24 02:04:32 +00002696 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002697 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002698 int needRestoreContext;
drh13449892005-09-07 21:22:45 +00002699 struct SrcList_item *pItem = &pTabList->a[i];
drhc31c2eb2003-05-02 16:04:17 +00002700
drh13449892005-09-07 21:22:45 +00002701 if( pItem->pSelect==0 ) continue;
2702 if( pItem->zName!=0 ){
drh5cf590c2003-04-24 01:45:04 +00002703 zSavedAuthContext = pParse->zAuthContext;
drh13449892005-09-07 21:22:45 +00002704 pParse->zAuthContext = pItem->zName;
drhc31c2eb2003-05-02 16:04:17 +00002705 needRestoreContext = 1;
2706 }else{
2707 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002708 }
drh9d2985c2005-09-08 01:58:42 +00002709 sqlite3Select(pParse, pItem->pSelect, SRT_VirtualTab,
drh13449892005-09-07 21:22:45 +00002710 pItem->iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002711 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002712 pParse->zAuthContext = zSavedAuthContext;
2713 }
drh1b2e0322002-03-03 02:49:51 +00002714 pTabList = p->pSrc;
2715 pWhere = p->pWhere;
drh13449892005-09-07 21:22:45 +00002716 if( !IgnorableOrderby(eDest) ){
drhacd4c692002-03-07 02:02:51 +00002717 pOrderBy = p->pOrderBy;
2718 }
drh1b2e0322002-03-03 02:49:51 +00002719 pGroupBy = p->pGroupBy;
2720 pHaving = p->pHaving;
2721 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002722 }
drh51522cd2005-01-20 13:36:19 +00002723#endif
drhd820cb12002-02-18 03:21:45 +00002724
drh6e175292004-03-13 14:00:36 +00002725 /* Check for the special case of a min() or max() function by itself
2726 ** in the result set.
2727 */
2728 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2729 rc = 0;
2730 goto select_end;
2731 }
2732
drh832508b2002-03-02 17:04:07 +00002733 /* Check to see if this is a subquery that can be "flattened" into its parent.
2734 ** If flattening is a possiblity, do so and return immediately.
2735 */
drhb7f91642004-10-31 02:22:47 +00002736#ifndef SQLITE_OMIT_VIEW
drh1b2e0322002-03-03 02:49:51 +00002737 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002738 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002739 if( isAgg ) *pParentAgg = 1;
danielk1977b3bce662005-01-29 08:32:43 +00002740 goto select_end;
drh832508b2002-03-02 17:04:07 +00002741 }
drhb7f91642004-10-31 02:22:47 +00002742#endif
drh832508b2002-03-02 17:04:07 +00002743
danielk19777cedc8d2004-06-10 10:50:08 +00002744 /* If there is an ORDER BY clause, resolve any collation sequences
drh9d2985c2005-09-08 01:58:42 +00002745 ** names that have been explicitly specified and create a sorting index.
2746 **
2747 ** This sorting index might end up being unused if the data can be
2748 ** extracted in pre-sorted order. If that is the case, then the
2749 ** OP_OpenVirtual instruction will be changed to an OP_Noop once
2750 ** we figure out that the sorting index is not needed. The addrSortIndex
2751 ** variable is used to facilitate that change.
danielk19777cedc8d2004-06-10 10:50:08 +00002752 */
2753 if( pOrderBy ){
drh5d9a4af2005-08-30 00:54:01 +00002754 struct ExprList_item *pTerm;
drh0342b1f2005-09-01 03:07:44 +00002755 KeyInfo *pKeyInfo;
drh5d9a4af2005-08-30 00:54:01 +00002756 for(i=0, pTerm=pOrderBy->a; i<pOrderBy->nExpr; i++, pTerm++){
2757 if( pTerm->zName ){
2758 pTerm->pExpr->pColl = sqlite3LocateCollSeq(pParse, pTerm->zName, -1);
danielk19777cedc8d2004-06-10 10:50:08 +00002759 }
2760 }
2761 if( pParse->nErr ){
2762 goto select_end;
2763 }
drh0342b1f2005-09-01 03:07:44 +00002764 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
drh9d2985c2005-09-08 01:58:42 +00002765 pOrderBy->iECursor = pParse->nTab++;
2766 p->addrOpenVirt[2] = addrSortIndex =
2767 sqlite3VdbeOp3(v, OP_OpenVirtual, pOrderBy->iECursor, pOrderBy->nExpr+2,
drh0342b1f2005-09-01 03:07:44 +00002768 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drh9d2985c2005-09-08 01:58:42 +00002769 }else{
2770 addrSortIndex = -1;
danielk19777cedc8d2004-06-10 10:50:08 +00002771 }
2772
drh7b58dae2003-07-20 01:16:46 +00002773 /* Set the limiter.
2774 */
2775 computeLimitRegisters(pParse, p);
2776
drh2d0794e2002-03-03 03:03:52 +00002777 /* If the output is destined for a temporary table, open that table.
2778 */
drh9d2985c2005-09-08 01:58:42 +00002779 if( eDest==SRT_VirtualTab ){
drh0342b1f2005-09-01 03:07:44 +00002780 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002781 }
2782
drhcce7d172000-05-31 15:34:51 +00002783
drh51522cd2005-01-20 13:36:19 +00002784 /* Initialize the memory cell to NULL for SRT_Mem or 0 for SRT_Exists
drh19a775c2000-06-05 18:54:46 +00002785 */
drhd654be82005-09-20 17:42:23 +00002786 if( eDest==SRT_Mem ){
2787 sqlite3VdbeAddOp(v, OP_MemNull, iParm, 0);
2788 }else if( eDest==SRT_Exists ){
2789 sqlite3VdbeAddOp(v, OP_MemInt, 0, iParm);
drh19a775c2000-06-05 18:54:46 +00002790 }
2791
drhdece1a82005-08-31 18:20:00 +00002792 /* Open a virtual index to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002793 */
drh19a775c2000-06-05 18:54:46 +00002794 if( isDistinct ){
drh0342b1f2005-09-01 03:07:44 +00002795 KeyInfo *pKeyInfo;
drh832508b2002-03-02 17:04:07 +00002796 distinct = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00002797 pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
2798 sqlite3VdbeOp3(v, OP_OpenVirtual, distinct, 0,
2799 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drh832508b2002-03-02 17:04:07 +00002800 }else{
2801 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002802 }
drh832508b2002-03-02 17:04:07 +00002803
drh13449892005-09-07 21:22:45 +00002804 /* Aggregate and non-aggregate queries are handled differently */
2805 if( !isAgg && pGroupBy==0 ){
2806 /* This case is for non-aggregate queries
2807 ** Begin the database scan
2808 */
2809 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
2810 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002811
drh9d2985c2005-09-08 01:58:42 +00002812 /* If sorting index that was created by a prior OP_OpenVirtual
2813 ** instruction ended up not being needed, then change the OP_OpenVirtual
2814 ** into an OP_Noop.
2815 */
2816 if( addrSortIndex>=0 && pOrderBy==0 ){
2817 uncreateSortingIndex(pParse, addrSortIndex);
2818 p->addrOpenVirt[2] = -1;
2819 }
2820
drh13449892005-09-07 21:22:45 +00002821 /* Use the standard inner loop
2822 */
drhdf199a22002-06-14 22:38:41 +00002823 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002824 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002825 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002826 }
drhefb72512000-05-31 20:00:52 +00002827
drh13449892005-09-07 21:22:45 +00002828 /* End the database scan loop.
2829 */
2830 sqlite3WhereEnd(pWInfo);
2831 }else{
2832 /* This is the processing for aggregate queries */
2833 NameContext sNC; /* Name context for processing aggregate information */
2834 int iAMem; /* First Mem address for storing current GROUP BY */
2835 int iBMem; /* First Mem address for previous GROUP BY */
2836 int iUseFlag; /* Mem address holding flag indicating that at least
2837 ** one row of the input to the aggregator has been
2838 ** processed */
2839 int iAbortFlag; /* Mem address which causes query abort if positive */
2840 int groupBySort; /* Rows come from source in GROUP BY order */
drhcce7d172000-05-31 15:34:51 +00002841
drhcce7d172000-05-31 15:34:51 +00002842
drh13449892005-09-07 21:22:45 +00002843 /* The following variables hold addresses or labels for parts of the
2844 ** virtual machine program we are putting together */
2845 int addrOutputRow; /* Start of subroutine that outputs a result row */
2846 int addrSetAbort; /* Set the abort flag and return */
2847 int addrInitializeLoop; /* Start of code that initializes the input loop */
2848 int addrTopOfLoop; /* Top of the input loop */
2849 int addrGroupByChange; /* Code that runs when any GROUP BY term changes */
2850 int addrProcessRow; /* Code to process a single input row */
2851 int addrEnd; /* End of all processing */
2852 int addrSortingIdx; /* The OP_OpenVirtual for the sorting index */
drhe3133822005-09-20 13:11:59 +00002853 int addrReset; /* Subroutine for resetting the accumulator */
drh13449892005-09-07 21:22:45 +00002854
2855 addrEnd = sqlite3VdbeMakeLabel(v);
2856
2857 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
2858 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
2859 ** SELECT statement.
2860 */
2861 memset(&sNC, 0, sizeof(sNC));
2862 sNC.pParse = pParse;
2863 sNC.pSrcList = pTabList;
2864 sNC.pAggInfo = &sAggInfo;
2865 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
drh9d2985c2005-09-08 01:58:42 +00002866 sAggInfo.pGroupBy = pGroupBy;
drh13449892005-09-07 21:22:45 +00002867 if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
drh1d83f052002-02-17 00:30:36 +00002868 goto select_end;
drh22827922000-06-06 17:27:05 +00002869 }
drh13449892005-09-07 21:22:45 +00002870 if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
2871 goto select_end;
2872 }
2873 if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
2874 goto select_end;
2875 }
2876 sAggInfo.nAccumulator = sAggInfo.nColumn;
2877 for(i=0; i<sAggInfo.nFunc; i++){
2878 if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
2879 goto select_end;
2880 }
2881 }
drh5360ad32005-09-08 00:13:27 +00002882 if( sqlite3_malloc_failed ) goto select_end;
drh13449892005-09-07 21:22:45 +00002883
2884 /* Processing for aggregates with GROUP BY is very different and
2885 ** much more complex tha aggregates without a GROUP BY.
2886 */
2887 if( pGroupBy ){
2888 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
2889
2890 /* Create labels that we will be needing
2891 */
2892
2893 addrInitializeLoop = sqlite3VdbeMakeLabel(v);
2894 addrGroupByChange = sqlite3VdbeMakeLabel(v);
2895 addrProcessRow = sqlite3VdbeMakeLabel(v);
2896
2897 /* If there is a GROUP BY clause we might need a sorting index to
2898 ** implement it. Allocate that sorting index now. If it turns out
2899 ** that we do not need it after all, the OpenVirtual instruction
2900 ** will be converted into a Noop.
2901 */
2902 sAggInfo.sortingIdx = pParse->nTab++;
2903 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
2904 addrSortingIdx =
2905 sqlite3VdbeOp3(v, OP_OpenVirtual, sAggInfo.sortingIdx,
2906 sAggInfo.nSortingColumn,
2907 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2908
2909 /* Initialize memory locations used by GROUP BY aggregate processing
2910 */
2911 iUseFlag = pParse->nMem++;
2912 iAbortFlag = pParse->nMem++;
2913 iAMem = pParse->nMem;
2914 pParse->nMem += pGroupBy->nExpr;
2915 iBMem = pParse->nMem;
2916 pParse->nMem += pGroupBy->nExpr;
drhd654be82005-09-20 17:42:23 +00002917 sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
2918 sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
2919 sqlite3VdbeAddOp(v, OP_MemNull, iAMem, 0);
drh13449892005-09-07 21:22:45 +00002920 sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
2921
2922 /* Generate a subroutine that outputs a single row of the result
2923 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
2924 ** is less than or equal to zero, the subroutine is a no-op. If
2925 ** the processing calls for the query to abort, this subroutine
2926 ** increments the iAbortFlag memory location before returning in
2927 ** order to signal the caller to abort.
2928 */
2929 addrSetAbort = sqlite3VdbeCurrentAddr(v);
2930 sqlite3VdbeAddOp(v, OP_MemIncr, iAbortFlag, 0);
2931 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2932 addrOutputRow = sqlite3VdbeCurrentAddr(v);
2933 sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
2934 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2935 finalizeAggFunctions(pParse, &sAggInfo);
2936 if( pHaving ){
2937 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
2938 }
2939 rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
2940 distinct, eDest, iParm,
2941 addrOutputRow+1, addrSetAbort, aff);
2942 if( rc ){
2943 goto select_end;
2944 }
2945 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2946
drhe3133822005-09-20 13:11:59 +00002947 /* Generate a subroutine that will reset the group-by accumulator
2948 */
2949 addrReset = sqlite3VdbeCurrentAddr(v);
2950 resetAccumulator(pParse, &sAggInfo);
2951 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2952
drh13449892005-09-07 21:22:45 +00002953 /* Begin a loop that will extract all source rows in GROUP BY order.
2954 ** This might involve two separate loops with an OP_Sort in between, or
2955 ** it might be a single loop that uses an index to extract information
2956 ** in the right order to begin with.
2957 */
2958 sqlite3VdbeResolveLabel(v, addrInitializeLoop);
drhe3133822005-09-20 13:11:59 +00002959 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
drh13449892005-09-07 21:22:45 +00002960 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
drh5360ad32005-09-08 00:13:27 +00002961 if( pWInfo==0 ) goto select_end;
drh13449892005-09-07 21:22:45 +00002962 if( pGroupBy==0 ){
2963 /* The optimizer is able to deliver rows in group by order so
2964 ** we do not have to sort. The OP_OpenVirtual table will be
2965 ** cancelled later because we still need to use the pKeyInfo
2966 */
2967 pGroupBy = p->pGroupBy;
2968 groupBySort = 0;
2969 }else{
2970 /* Rows are coming out in undetermined order. We have to push
2971 ** each row into a sorting index, terminate the first loop,
2972 ** then loop over the sorting index in order to get the output
2973 ** in sorted order
2974 */
2975 groupBySort = 1;
2976 sqlite3ExprCodeExprList(pParse, pGroupBy);
2977 sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
2978 j = pGroupBy->nExpr+1;
2979 for(i=0; i<sAggInfo.nColumn; i++){
2980 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
2981 if( pCol->iSorterColumn<j ) continue;
2982 if( pCol->iColumn<0 ){
2983 sqlite3VdbeAddOp(v, OP_Rowid, pCol->iTable, 0);
2984 }else{
2985 sqlite3VdbeAddOp(v, OP_Column, pCol->iTable, pCol->iColumn);
2986 }
2987 j++;
2988 }
2989 sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
2990 sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
2991 sqlite3WhereEnd(pWInfo);
drh97571952005-09-08 12:57:28 +00002992 sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
drh13449892005-09-07 21:22:45 +00002993 sAggInfo.useSortingIdx = 1;
2994 }
2995
2996 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
2997 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
2998 ** Then compare the current GROUP BY terms against the GROUP BY terms
2999 ** from the previous row currently stored in a0, a1, a2...
3000 */
3001 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
3002 for(j=0; j<pGroupBy->nExpr; j++){
3003 if( groupBySort ){
3004 sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
3005 }else{
3006 sAggInfo.directMode = 1;
3007 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
3008 }
3009 sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
3010 }
3011 for(j=pGroupBy->nExpr-1; j>=0; j--){
3012 if( j<pGroupBy->nExpr-1 ){
3013 sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
3014 }
3015 sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
3016 if( j==0 ){
drhe3133822005-09-20 13:11:59 +00003017 sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
drh13449892005-09-07 21:22:45 +00003018 }else{
drh4f686232005-09-20 13:55:18 +00003019 sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
drh13449892005-09-07 21:22:45 +00003020 }
3021 sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
3022 }
3023
3024 /* Generate code that runs whenever the GROUP BY changes.
3025 ** Change in the GROUP BY are detected by the previous code
3026 ** block. If there were no changes, this block is skipped.
3027 **
3028 ** This code copies current group by terms in b0,b1,b2,...
3029 ** over to a0,a1,a2. It then calls the output subroutine
3030 ** and resets the aggregate accumulator registers in preparation
3031 ** for the next GROUP BY batch.
3032 */
3033 sqlite3VdbeResolveLabel(v, addrGroupByChange);
3034 for(j=0; j<pGroupBy->nExpr; j++){
drhd654be82005-09-20 17:42:23 +00003035 sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
drh13449892005-09-07 21:22:45 +00003036 }
3037 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
3038 sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
drhe3133822005-09-20 13:11:59 +00003039 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
drh13449892005-09-07 21:22:45 +00003040
3041 /* Update the aggregate accumulators based on the content of
3042 ** the current row
3043 */
3044 sqlite3VdbeResolveLabel(v, addrProcessRow);
3045 updateAccumulator(pParse, &sAggInfo);
3046 sqlite3VdbeAddOp(v, OP_MemIncr, iUseFlag, 0);
3047
3048 /* End of the loop
3049 */
3050 if( groupBySort ){
3051 sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
3052 }else{
3053 sqlite3WhereEnd(pWInfo);
3054 uncreateSortingIndex(pParse, addrSortingIdx);
3055 }
3056
3057 /* Output the final row of result
3058 */
3059 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
3060
3061 } /* endif pGroupBy */
3062 else {
3063 /* This case runs if the aggregate has no GROUP BY clause. The
3064 ** processing is much simpler since there is only a single row
3065 ** of output.
3066 */
3067 resetAccumulator(pParse, &sAggInfo);
3068 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
drh5360ad32005-09-08 00:13:27 +00003069 if( pWInfo==0 ) goto select_end;
drh13449892005-09-07 21:22:45 +00003070 updateAccumulator(pParse, &sAggInfo);
3071 sqlite3WhereEnd(pWInfo);
3072 finalizeAggFunctions(pParse, &sAggInfo);
3073 pOrderBy = 0;
drh5774b802005-09-07 22:48:16 +00003074 if( pHaving ){
3075 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
3076 }
drh13449892005-09-07 21:22:45 +00003077 selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
3078 eDest, iParm, addrEnd, addrEnd, aff);
3079 }
3080 sqlite3VdbeResolveLabel(v, addrEnd);
3081
3082 } /* endif aggregate query */
drh22827922000-06-06 17:27:05 +00003083
drhcce7d172000-05-31 15:34:51 +00003084 /* If there is an ORDER BY clause, then we need to sort the results
3085 ** and send them to the callback one by one.
3086 */
3087 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00003088 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00003089 }
drh6a535342001-10-19 16:44:56 +00003090
danielk197793758c82005-01-21 08:13:14 +00003091#ifndef SQLITE_OMIT_SUBQUERY
drhf620b4e2004-02-09 14:37:50 +00003092 /* If this was a subquery, we have now converted the subquery into a
3093 ** temporary table. So delete the subquery structure from the parent
3094 ** to prevent this subquery from being evaluated again and to force the
3095 ** the use of the temporary table.
3096 */
3097 if( pParent ){
3098 assert( pParent->pSrc->nSrc>parentTab );
3099 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00003100 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00003101 pParent->pSrc->a[parentTab].pSelect = 0;
3102 }
danielk197793758c82005-01-21 08:13:14 +00003103#endif
drhf620b4e2004-02-09 14:37:50 +00003104
drh1d83f052002-02-17 00:30:36 +00003105 /* The SELECT was successfully coded. Set the return code to 0
3106 ** to indicate no errors.
3107 */
3108 rc = 0;
3109
3110 /* Control jumps to here if an error is encountered above, or upon
3111 ** successful coding of the SELECT.
3112 */
3113select_end:
drh13449892005-09-07 21:22:45 +00003114 sqliteFree(sAggInfo.aCol);
3115 sqliteFree(sAggInfo.aFunc);
drh1d83f052002-02-17 00:30:36 +00003116 return rc;
drhcce7d172000-05-31 15:34:51 +00003117}