blob: 9b0be55ecd45c34234711d5e4cbc6c96c283729a [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**
drh15007a92006-01-08 18:10:17 +000015** $Id: select.c,v 1.288 2006/01/08 18:10:18 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
drh2646da72005-12-09 20:02:05 +0000112 && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
drh01f3f252002-05-24 16:14:15 +0000113 jointype |= keywords[j].code;
114 break;
115 }
116 }
117 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
118 jointype |= JT_ERROR;
119 break;
120 }
121 }
drhad2d8302002-05-24 20:31:36 +0000122 if(
123 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000124 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000125 ){
drhae29ffb2004-09-25 14:39:18 +0000126 const char *zSp1 = " ";
127 const char *zSp2 = " ";
128 if( pB==0 ){ zSp1++; }
129 if( pC==0 ){ zSp2++; }
130 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
131 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
drh01f3f252002-05-24 16:14:15 +0000132 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000133 }else if( jointype & JT_RIGHT ){
danielk19774adee202004-05-08 08:23:19 +0000134 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000135 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000136 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000137 }
138 return jointype;
139}
140
141/*
drhad2d8302002-05-24 20:31:36 +0000142** Return the index of a column in a table. Return -1 if the column
143** is not contained in the table.
144*/
145static int columnIndex(Table *pTab, const char *zCol){
146 int i;
147 for(i=0; i<pTab->nCol; i++){
danielk19774adee202004-05-08 08:23:19 +0000148 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
drhad2d8302002-05-24 20:31:36 +0000149 }
150 return -1;
151}
152
153/*
drh91bb0ee2004-09-01 03:06:34 +0000154** Set the value of a token to a '\000'-terminated string.
155*/
156static void setToken(Token *p, const char *z){
drh2646da72005-12-09 20:02:05 +0000157 p->z = (u8*)z;
danielk1977261919c2005-12-06 12:52:59 +0000158 p->n = z ? strlen(z) : 0;
drh91bb0ee2004-09-01 03:06:34 +0000159 p->dyn = 0;
160}
161
drhc182d162005-08-14 20:47:16 +0000162/*
163** Create an expression node for an identifier with the name of zName
164*/
165static Expr *createIdExpr(const char *zName){
166 Token dummy;
167 setToken(&dummy, zName);
168 return sqlite3Expr(TK_ID, 0, 0, &dummy);
169}
170
drh91bb0ee2004-09-01 03:06:34 +0000171
172/*
drhad2d8302002-05-24 20:31:36 +0000173** Add a term to the WHERE expression in *ppExpr that requires the
174** zCol column to be equal in the two tables pTab1 and pTab2.
175*/
176static void addWhereTerm(
177 const char *zCol, /* Name of the column */
178 const Table *pTab1, /* First table */
drh030530d2005-01-18 17:40:04 +0000179 const char *zAlias1, /* Alias for first table. May be NULL */
drhad2d8302002-05-24 20:31:36 +0000180 const Table *pTab2, /* Second table */
drh030530d2005-01-18 17:40:04 +0000181 const char *zAlias2, /* Alias for second table. May be NULL */
drh22d6a532005-09-19 21:05:48 +0000182 int iRightJoinTable, /* VDBE cursor for the right table */
drhad2d8302002-05-24 20:31:36 +0000183 Expr **ppExpr /* Add the equality term to this expression */
184){
drhad2d8302002-05-24 20:31:36 +0000185 Expr *pE1a, *pE1b, *pE1c;
186 Expr *pE2a, *pE2b, *pE2c;
187 Expr *pE;
188
drhc182d162005-08-14 20:47:16 +0000189 pE1a = createIdExpr(zCol);
190 pE2a = createIdExpr(zCol);
drh030530d2005-01-18 17:40:04 +0000191 if( zAlias1==0 ){
192 zAlias1 = pTab1->zName;
193 }
drhc182d162005-08-14 20:47:16 +0000194 pE1b = createIdExpr(zAlias1);
drh030530d2005-01-18 17:40:04 +0000195 if( zAlias2==0 ){
196 zAlias2 = pTab2->zName;
197 }
drhc182d162005-08-14 20:47:16 +0000198 pE2b = createIdExpr(zAlias2);
danielk19774adee202004-05-08 08:23:19 +0000199 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
200 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
201 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000202 ExprSetProperty(pE, EP_FromJoin);
drh22d6a532005-09-19 21:05:48 +0000203 pE->iRightJoinTable = iRightJoinTable;
drh91bb0ee2004-09-01 03:06:34 +0000204 *ppExpr = sqlite3ExprAnd(*ppExpr, pE);
drhad2d8302002-05-24 20:31:36 +0000205}
206
207/*
drh1f162302002-10-27 19:35:33 +0000208** Set the EP_FromJoin property on all terms of the given expression.
drh22d6a532005-09-19 21:05:48 +0000209** And set the Expr.iRightJoinTable to iTable for every term in the
210** expression.
drh1cc093c2002-06-24 22:01:57 +0000211**
drhe78e8282003-01-19 03:59:45 +0000212** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000213** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000214** join restriction specified in the ON or USING clause and not a part
215** of the more general WHERE clause. These terms are moved over to the
216** WHERE clause during join processing but we need to remember that they
217** originated in the ON or USING clause.
drh22d6a532005-09-19 21:05:48 +0000218**
219** The Expr.iRightJoinTable tells the WHERE clause processing that the
220** expression depends on table iRightJoinTable even if that table is not
221** explicitly mentioned in the expression. That information is needed
222** for cases like this:
223**
224** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
225**
226** The where clause needs to defer the handling of the t1.x=5
227** term until after the t2 loop of the join. In that way, a
228** NULL t2 row will be inserted whenever t1.x!=5. If we do not
229** defer the handling of t1.x=5, it will be processed immediately
230** after the t1 loop and rows with t1.x!=5 will never appear in
231** the output, which is incorrect.
drh1cc093c2002-06-24 22:01:57 +0000232*/
drh22d6a532005-09-19 21:05:48 +0000233static void setJoinExpr(Expr *p, int iTable){
drh1cc093c2002-06-24 22:01:57 +0000234 while( p ){
drh1f162302002-10-27 19:35:33 +0000235 ExprSetProperty(p, EP_FromJoin);
drh22d6a532005-09-19 21:05:48 +0000236 p->iRightJoinTable = iTable;
237 setJoinExpr(p->pLeft, iTable);
drh1cc093c2002-06-24 22:01:57 +0000238 p = p->pRight;
239 }
240}
241
242/*
drhad2d8302002-05-24 20:31:36 +0000243** This routine processes the join information for a SELECT statement.
244** ON and USING clauses are converted into extra terms of the WHERE clause.
245** NATURAL joins also create extra WHERE clause terms.
246**
drh91bb0ee2004-09-01 03:06:34 +0000247** The terms of a FROM clause are contained in the Select.pSrc structure.
248** The left most table is the first entry in Select.pSrc. The right-most
249** table is the last entry. The join operator is held in the entry to
250** the left. Thus entry 0 contains the join operator for the join between
251** entries 0 and 1. Any ON or USING clauses associated with the join are
252** also attached to the left entry.
253**
drhad2d8302002-05-24 20:31:36 +0000254** This routine returns the number of errors encountered.
255*/
256static int sqliteProcessJoin(Parse *pParse, Select *p){
drh91bb0ee2004-09-01 03:06:34 +0000257 SrcList *pSrc; /* All tables in the FROM clause */
258 int i, j; /* Loop counters */
259 struct SrcList_item *pLeft; /* Left table being joined */
260 struct SrcList_item *pRight; /* Right table being joined */
drhad2d8302002-05-24 20:31:36 +0000261
drh91bb0ee2004-09-01 03:06:34 +0000262 pSrc = p->pSrc;
263 pLeft = &pSrc->a[0];
264 pRight = &pLeft[1];
265 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
266 Table *pLeftTab = pLeft->pTab;
267 Table *pRightTab = pRight->pTab;
268
269 if( pLeftTab==0 || pRightTab==0 ) continue;
drhad2d8302002-05-24 20:31:36 +0000270
271 /* When the NATURAL keyword is present, add WHERE clause terms for
272 ** every column that the two tables have in common.
273 */
drh91bb0ee2004-09-01 03:06:34 +0000274 if( pLeft->jointype & JT_NATURAL ){
275 if( pLeft->pOn || pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000276 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000277 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000278 return 1;
279 }
drh91bb0ee2004-09-01 03:06:34 +0000280 for(j=0; j<pLeftTab->nCol; j++){
281 char *zName = pLeftTab->aCol[j].zName;
282 if( columnIndex(pRightTab, zName)>=0 ){
drh030530d2005-01-18 17:40:04 +0000283 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
drh22d6a532005-09-19 21:05:48 +0000284 pRightTab, pRight->zAlias,
285 pRight->iCursor, &p->pWhere);
286
drhad2d8302002-05-24 20:31:36 +0000287 }
288 }
289 }
290
291 /* Disallow both ON and USING clauses in the same join
292 */
drh91bb0ee2004-09-01 03:06:34 +0000293 if( pLeft->pOn && pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000294 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
drhda93d232003-03-31 02:12:46 +0000295 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000296 return 1;
297 }
298
299 /* Add the ON clause to the end of the WHERE clause, connected by
drh91bb0ee2004-09-01 03:06:34 +0000300 ** an AND operator.
drhad2d8302002-05-24 20:31:36 +0000301 */
drh91bb0ee2004-09-01 03:06:34 +0000302 if( pLeft->pOn ){
drh22d6a532005-09-19 21:05:48 +0000303 setJoinExpr(pLeft->pOn, pRight->iCursor);
drh91bb0ee2004-09-01 03:06:34 +0000304 p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn);
305 pLeft->pOn = 0;
drhad2d8302002-05-24 20:31:36 +0000306 }
307
308 /* Create extra terms on the WHERE clause for each column named
309 ** in the USING clause. Example: If the two tables to be joined are
310 ** A and B and the USING clause names X, Y, and Z, then add this
311 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
312 ** Report an error if any column mentioned in the USING clause is
313 ** not contained in both tables to be joined.
314 */
drh91bb0ee2004-09-01 03:06:34 +0000315 if( pLeft->pUsing ){
316 IdList *pList = pLeft->pUsing;
drhad2d8302002-05-24 20:31:36 +0000317 for(j=0; j<pList->nId; j++){
drh91bb0ee2004-09-01 03:06:34 +0000318 char *zName = pList->a[j].zName;
319 if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
danielk19774adee202004-05-08 08:23:19 +0000320 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
drh91bb0ee2004-09-01 03:06:34 +0000321 "not present in both tables", zName);
drhad2d8302002-05-24 20:31:36 +0000322 return 1;
323 }
drh030530d2005-01-18 17:40:04 +0000324 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
drh22d6a532005-09-19 21:05:48 +0000325 pRightTab, pRight->zAlias,
326 pRight->iCursor, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000327 }
328 }
329 }
330 return 0;
331}
332
333/*
drh9bb61fe2000-06-05 16:01:39 +0000334** Delete the given Select structure and all of its substructures.
335*/
danielk19774adee202004-05-08 08:23:19 +0000336void sqlite3SelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000337 if( p==0 ) return;
danielk19774adee202004-05-08 08:23:19 +0000338 sqlite3ExprListDelete(p->pEList);
339 sqlite3SrcListDelete(p->pSrc);
340 sqlite3ExprDelete(p->pWhere);
341 sqlite3ExprListDelete(p->pGroupBy);
342 sqlite3ExprDelete(p->pHaving);
343 sqlite3ExprListDelete(p->pOrderBy);
344 sqlite3SelectDelete(p->pPrior);
danielk1977a2dc3b12005-02-05 12:48:48 +0000345 sqlite3ExprDelete(p->pLimit);
346 sqlite3ExprDelete(p->pOffset);
drh9bb61fe2000-06-05 16:01:39 +0000347 sqliteFree(p);
348}
349
350/*
drhc926afb2002-06-20 03:38:26 +0000351** Insert code into "v" that will push the record on the top of the
352** stack into the sorter.
353*/
drhd59ba6c2006-01-08 05:02:54 +0000354static void pushOntoSorter(
355 Parse *pParse, /* Parser context */
356 ExprList *pOrderBy, /* The ORDER BY clause */
357 Select *pSelect /* The whole SELECT statement */
358){
359 Vdbe *v = pParse->pVdbe;
drhc182d162005-08-14 20:47:16 +0000360 sqlite3ExprCodeExprList(pParse, pOrderBy);
drh9d2985c2005-09-08 01:58:42 +0000361 sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0);
drh4db38a72005-09-01 12:16:28 +0000362 sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0);
363 sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0);
drh9d2985c2005-09-08 01:58:42 +0000364 sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0);
drhd59ba6c2006-01-08 05:02:54 +0000365 if( pSelect->iLimit>=0 ){
drh15007a92006-01-08 18:10:17 +0000366 int addr1, addr2;
367 addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0);
368 sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1);
369 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhd59ba6c2006-01-08 05:02:54 +0000370 sqlite3VdbeJumpHere(v, addr1);
371 sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0);
372 sqlite3VdbeAddOp(v, OP_Delete, pOrderBy->iECursor, 0);
drh15007a92006-01-08 18:10:17 +0000373 sqlite3VdbeJumpHere(v, addr2);
drhd59ba6c2006-01-08 05:02:54 +0000374 pSelect->iLimit = -1;
375 }
drhc926afb2002-06-20 03:38:26 +0000376}
377
378/*
drhec7429a2005-10-06 16:53:14 +0000379** Add code to implement the OFFSET
drhea48eb22004-07-19 23:16:38 +0000380*/
drhec7429a2005-10-06 16:53:14 +0000381static void codeOffset(
drhbab39e12004-07-19 23:38:11 +0000382 Vdbe *v, /* Generate code into this VM */
drhea48eb22004-07-19 23:16:38 +0000383 Select *p, /* The SELECT statement being coded */
384 int iContinue, /* Jump here to skip the current record */
drhea48eb22004-07-19 23:16:38 +0000385 int nPop /* Number of times to pop stack when jumping */
386){
drh13449892005-09-07 21:22:45 +0000387 if( p->iOffset>=0 && iContinue!=0 ){
drh15007a92006-01-08 18:10:17 +0000388 int addr;
389 sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iOffset);
390 addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, addr);
drhea48eb22004-07-19 23:16:38 +0000391 if( nPop>0 ){
392 sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
393 }
394 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000395 VdbeComment((v, "# skip OFFSET records"));
drh15007a92006-01-08 18:10:17 +0000396 sqlite3VdbeJumpHere(v, addr);
drhea48eb22004-07-19 23:16:38 +0000397 }
drhea48eb22004-07-19 23:16:38 +0000398}
399
400/*
drhc99130f2005-09-11 11:56:27 +0000401** Add code that will check to make sure the top N elements of the
402** stack are distinct. iTab is a sorting index that holds previously
403** seen combinations of the N values. A new entry is made in iTab
404** if the current N values are new.
405**
406** A jump to addrRepeat is made and the K values are popped from the
407** stack if the top N elements are not distinct.
408*/
409static void codeDistinct(
410 Vdbe *v, /* Generate code into this VM */
411 int iTab, /* A sorting index used to test for distinctness */
412 int addrRepeat, /* Jump to here if not distinct */
413 int N, /* The top N elements of the stack must be distinct */
414 int K /* Pop K elements from the stack if indistinct */
415){
416#if NULL_ALWAYS_DISTINCT
417 sqlite3VdbeAddOp(v, OP_IsNull, -N, sqlite3VdbeCurrentAddr(v)+6);
418#endif
419 sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0);
420 sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3);
421 sqlite3VdbeAddOp(v, OP_Pop, K, 0);
422 sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat);
423 VdbeComment((v, "# skip indistinct records"));
424 sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0);
425}
426
427
428/*
drh22827922000-06-06 17:27:05 +0000429** This routine generates the code for the inside of the inner loop
430** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000431**
drh38640e12002-07-05 21:42:36 +0000432** If srcTab and nColumn are both zero, then the pEList expressions
433** are evaluated in order to get the data for this row. If nColumn>0
434** then data is pulled from srcTab and pEList is used only to get the
435** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000436*/
437static int selectInnerLoop(
438 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000439 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000440 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000441 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000442 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000443 ExprList *pOrderBy, /* If not NULL, sort results using this key */
444 int distinct, /* If >=0, make sure results are distinct */
445 int eDest, /* How to dispose of the results */
446 int iParm, /* An argument to the disposal method */
447 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000448 int iBreak, /* Jump here to break out of the inner loop */
449 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000450){
451 Vdbe *v = pParse->pVdbe;
452 int i;
drhea48eb22004-07-19 23:16:38 +0000453 int hasDistinct; /* True if the DISTINCT keyword is present */
drh38640e12002-07-05 21:42:36 +0000454
drhdaffd0e2001-04-11 14:28:42 +0000455 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000456 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000457
drhdf199a22002-06-14 22:38:41 +0000458 /* If there was a LIMIT clause on the SELECT statement, then do the check
459 ** to see if this row should be output.
460 */
drhea48eb22004-07-19 23:16:38 +0000461 hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
462 if( pOrderBy==0 && !hasDistinct ){
drhec7429a2005-10-06 16:53:14 +0000463 codeOffset(v, p, iContinue, 0);
drhdf199a22002-06-14 22:38:41 +0000464 }
465
drh967e8b72000-06-21 13:59:10 +0000466 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000467 */
drh38640e12002-07-05 21:42:36 +0000468 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000469 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000470 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000471 }
drh38640e12002-07-05 21:42:36 +0000472 }else{
473 nColumn = pEList->nExpr;
drhc182d162005-08-14 20:47:16 +0000474 sqlite3ExprCodeExprList(pParse, pEList);
drh22827922000-06-06 17:27:05 +0000475 }
476
drhdaffd0e2001-04-11 14:28:42 +0000477 /* If the DISTINCT keyword was present on the SELECT statement
478 ** and this row has been seen before, then do not make this row
479 ** part of the result.
drh22827922000-06-06 17:27:05 +0000480 */
drhea48eb22004-07-19 23:16:38 +0000481 if( hasDistinct ){
drhc182d162005-08-14 20:47:16 +0000482 int n = pEList->nExpr;
drhc99130f2005-09-11 11:56:27 +0000483 codeDistinct(v, distinct, iContinue, n, n+1);
drhea48eb22004-07-19 23:16:38 +0000484 if( pOrderBy==0 ){
drhec7429a2005-10-06 16:53:14 +0000485 codeOffset(v, p, iContinue, nColumn);
drhea48eb22004-07-19 23:16:38 +0000486 }
drh22827922000-06-06 17:27:05 +0000487 }
drh82c3d632000-06-06 21:56:07 +0000488
drhc926afb2002-06-20 03:38:26 +0000489 switch( eDest ){
490 /* In this mode, write each query result to the key of the temporary
491 ** table iParm.
492 */
drh13449892005-09-07 21:22:45 +0000493#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhc926afb2002-06-20 03:38:26 +0000494 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000495 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
drh13449892005-09-07 21:22:45 +0000496 if( aff ){
497 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
498 }
drhf0863fe2005-06-12 21:35:51 +0000499 sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000500 break;
drh22827922000-06-06 17:27:05 +0000501 }
drh22827922000-06-06 17:27:05 +0000502
drhc926afb2002-06-20 03:38:26 +0000503 /* Construct a record from the query result, but instead of
504 ** saving that record, use it as a key to delete elements from
505 ** the temporary table iParm.
506 */
507 case SRT_Except: {
508 int addr;
danielk19774adee202004-05-08 08:23:19 +0000509 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000510 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000511 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
512 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000513 break;
514 }
danielk19775338a5f2005-01-20 13:03:10 +0000515#endif
516
517 /* Store the result as data using a unique key.
518 */
519 case SRT_Table:
drh9d2985c2005-09-08 01:58:42 +0000520 case SRT_VirtualTab: {
danielk19775338a5f2005-01-20 13:03:10 +0000521 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
522 if( pOrderBy ){
drhd59ba6c2006-01-08 05:02:54 +0000523 pushOntoSorter(pParse, pOrderBy, p);
danielk19775338a5f2005-01-20 13:03:10 +0000524 }else{
drhf0863fe2005-06-12 21:35:51 +0000525 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
danielk19775338a5f2005-01-20 13:03:10 +0000526 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhf0863fe2005-06-12 21:35:51 +0000527 sqlite3VdbeAddOp(v, OP_Insert, iParm, 0);
danielk19775338a5f2005-01-20 13:03:10 +0000528 }
529 break;
530 }
drh5974a302000-06-07 14:42:26 +0000531
danielk197793758c82005-01-21 08:13:14 +0000532#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000533 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
534 ** then there should be a single item on the stack. Write this
535 ** item into the set table with bogus data.
536 */
537 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000538 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000539 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000540
drhc926afb2002-06-20 03:38:26 +0000541 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000542 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
543 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
544 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000545 if( pOrderBy ){
drhde941c62005-08-28 01:34:21 +0000546 /* At first glance you would think we could optimize out the
547 ** ORDER BY in this case since the order of entries in the set
548 ** does not matter. But there might be a LIMIT clause, in which
549 ** case the order does matter */
drhd59ba6c2006-01-08 05:02:54 +0000550 pushOntoSorter(pParse, pOrderBy, p);
drhc926afb2002-06-20 03:38:26 +0000551 }else{
danielk1977e014a832004-05-17 10:48:57 +0000552 char aff = (iParm>>16)&0xFF;
553 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
drh94a11212004-09-25 13:12:14 +0000554 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1);
drhf0863fe2005-06-12 21:35:51 +0000555 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000556 }
drhd654be82005-09-20 17:42:23 +0000557 sqlite3VdbeJumpHere(v, addr2);
drhc926afb2002-06-20 03:38:26 +0000558 break;
559 }
drh22827922000-06-06 17:27:05 +0000560
drhec7429a2005-10-06 16:53:14 +0000561 /* If any row exists in the result set, record that fact and abort.
562 */
563 case SRT_Exists: {
564 sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm);
565 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
566 /* The LIMIT clause will terminate the loop for us */
567 break;
568 }
569
drhc926afb2002-06-20 03:38:26 +0000570 /* If this is a scalar select that is part of an expression, then
571 ** store the results in the appropriate memory cell and break out
572 ** of the scan loop.
573 */
574 case SRT_Mem: {
575 assert( nColumn==1 );
576 if( pOrderBy ){
drhd59ba6c2006-01-08 05:02:54 +0000577 pushOntoSorter(pParse, pOrderBy, p);
drhc926afb2002-06-20 03:38:26 +0000578 }else{
danielk19774adee202004-05-08 08:23:19 +0000579 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drhec7429a2005-10-06 16:53:14 +0000580 /* The LIMIT clause will jump out of the loop for us */
drhc926afb2002-06-20 03:38:26 +0000581 }
582 break;
583 }
danielk197793758c82005-01-21 08:13:14 +0000584#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
drh22827922000-06-06 17:27:05 +0000585
drhc182d162005-08-14 20:47:16 +0000586 /* Send the data to the callback function or to a subroutine. In the
587 ** case of a subroutine, the subroutine itself is responsible for
588 ** popping the data from the stack.
drhf46f9052002-06-22 02:33:38 +0000589 */
drhc182d162005-08-14 20:47:16 +0000590 case SRT_Subroutine:
drh9d2985c2005-09-08 01:58:42 +0000591 case SRT_Callback: {
drhf46f9052002-06-22 02:33:38 +0000592 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000593 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhd59ba6c2006-01-08 05:02:54 +0000594 pushOntoSorter(pParse, pOrderBy, p);
drhc182d162005-08-14 20:47:16 +0000595 }else if( eDest==SRT_Subroutine ){
danielk19774adee202004-05-08 08:23:19 +0000596 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhc182d162005-08-14 20:47:16 +0000597 }else{
drhc182d162005-08-14 20:47:16 +0000598 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000599 }
drh142e30d2002-08-28 03:00:58 +0000600 break;
601 }
602
danielk19776a67fe82005-02-04 04:07:16 +0000603#if !defined(SQLITE_OMIT_TRIGGER)
drhc926afb2002-06-20 03:38:26 +0000604 /* Discard the results. This is used for SELECT statements inside
605 ** the body of a TRIGGER. The purpose of such selects is to call
606 ** user-defined functions that have side effects. We do not care
607 ** about the actual results of the select.
608 */
drhc926afb2002-06-20 03:38:26 +0000609 default: {
drhf46f9052002-06-22 02:33:38 +0000610 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000611 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000612 break;
613 }
danielk197793758c82005-01-21 08:13:14 +0000614#endif
drh82c3d632000-06-06 21:56:07 +0000615 }
drhec7429a2005-10-06 16:53:14 +0000616
617 /* Jump to the end of the loop if the LIMIT is reached.
618 */
619 if( p->iLimit>=0 && pOrderBy==0 ){
drh15007a92006-01-08 18:10:17 +0000620 sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
drhec7429a2005-10-06 16:53:14 +0000621 sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak);
622 }
drh82c3d632000-06-06 21:56:07 +0000623 return 0;
624}
625
626/*
drhdece1a82005-08-31 18:20:00 +0000627** Given an expression list, generate a KeyInfo structure that records
628** the collating sequence for each expression in that expression list.
629**
drh0342b1f2005-09-01 03:07:44 +0000630** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
631** KeyInfo structure is appropriate for initializing a virtual index to
632** implement that clause. If the ExprList is the result set of a SELECT
633** then the KeyInfo structure is appropriate for initializing a virtual
634** index to implement a DISTINCT test.
635**
drhdece1a82005-08-31 18:20:00 +0000636** Space to hold the KeyInfo structure is obtain from malloc. The calling
637** function is responsible for seeing that this structure is eventually
638** freed. Add the KeyInfo structure to the P3 field of an opcode using
639** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
640*/
641static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
642 sqlite3 *db = pParse->db;
643 int nExpr;
644 KeyInfo *pInfo;
645 struct ExprList_item *pItem;
646 int i;
647
648 nExpr = pList->nExpr;
649 pInfo = sqliteMalloc( sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
650 if( pInfo ){
drh2646da72005-12-09 20:02:05 +0000651 pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
drhdece1a82005-08-31 18:20:00 +0000652 pInfo->nField = nExpr;
653 pInfo->enc = db->enc;
654 for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
655 CollSeq *pColl;
656 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
657 if( !pColl ){
658 pColl = db->pDfltColl;
659 }
660 pInfo->aColl[i] = pColl;
661 pInfo->aSortOrder[i] = pItem->sortOrder;
662 }
663 }
664 return pInfo;
665}
666
667
668/*
drhd8bc7082000-06-07 23:51:50 +0000669** If the inner loop was generated using a non-null pOrderBy argument,
670** then the results were placed in a sorter. After the loop is terminated
671** we need to run the sorter and output the results. The following
672** routine generates the code needed to do that.
673*/
drhc926afb2002-06-20 03:38:26 +0000674static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000675 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000676 Select *p, /* The SELECT statement */
677 Vdbe *v, /* Generate code into this VDBE */
678 int nColumn, /* Number of columns of data */
679 int eDest, /* Write the sorted results here */
680 int iParm /* Optional parameter associated with eDest */
681){
drh0342b1f2005-09-01 03:07:44 +0000682 int brk = sqlite3VdbeMakeLabel(v);
683 int cont = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000684 int addr;
drh0342b1f2005-09-01 03:07:44 +0000685 int iTab;
686 ExprList *pOrderBy = p->pOrderBy;
drhffbc3082004-05-21 01:29:06 +0000687
drh9d2985c2005-09-08 01:58:42 +0000688 iTab = pOrderBy->iECursor;
drh0342b1f2005-09-01 03:07:44 +0000689 addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
drhec7429a2005-10-06 16:53:14 +0000690 codeOffset(v, p, cont, 0);
drh4db38a72005-09-01 12:16:28 +0000691 sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1);
drhc926afb2002-06-20 03:38:26 +0000692 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000693 case SRT_Table:
drh9d2985c2005-09-08 01:58:42 +0000694 case SRT_VirtualTab: {
drhf0863fe2005-06-12 21:35:51 +0000695 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
danielk19774adee202004-05-08 08:23:19 +0000696 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhf0863fe2005-06-12 21:35:51 +0000697 sqlite3VdbeAddOp(v, OP_Insert, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000698 break;
699 }
danielk197793758c82005-01-21 08:13:14 +0000700#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000701 case SRT_Set: {
702 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000703 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
704 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
705 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
drh8a512562005-11-14 22:29:05 +0000706 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "c", P3_STATIC);
drhf0863fe2005-06-12 21:35:51 +0000707 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000708 break;
709 }
710 case SRT_Mem: {
711 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000712 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drhec7429a2005-10-06 16:53:14 +0000713 /* The LIMIT clause will terminate the loop for us */
drhc926afb2002-06-20 03:38:26 +0000714 break;
715 }
danielk197793758c82005-01-21 08:13:14 +0000716#endif
drhce665cf2004-05-21 03:01:58 +0000717 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000718 case SRT_Subroutine: {
719 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000720 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
721 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000722 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000723 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000724 }
drhce665cf2004-05-21 03:01:58 +0000725 if( eDest==SRT_Callback ){
726 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
727 }else{
728 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
729 }
danielk197784ac9d02004-05-18 09:58:06 +0000730 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000731 break;
732 }
drhc926afb2002-06-20 03:38:26 +0000733 default: {
drhf46f9052002-06-22 02:33:38 +0000734 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000735 break;
736 }
737 }
drhec7429a2005-10-06 16:53:14 +0000738
739 /* Jump to the end of the loop when the LIMIT is reached
740 */
741 if( p->iLimit>=0 ){
drh15007a92006-01-08 18:10:17 +0000742 sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
drhec7429a2005-10-06 16:53:14 +0000743 sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk);
744 }
745
746 /* The bottom of the loop
747 */
drh0342b1f2005-09-01 03:07:44 +0000748 sqlite3VdbeResolveLabel(v, cont);
749 sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
750 sqlite3VdbeResolveLabel(v, brk);
drhd8bc7082000-06-07 23:51:50 +0000751}
752
753/*
danielk1977517eb642004-06-07 10:00:31 +0000754** Return a pointer to a string containing the 'declaration type' of the
755** expression pExpr. The string may be treated as static by the caller.
drhe78e8282003-01-19 03:59:45 +0000756**
danielk1977517eb642004-06-07 10:00:31 +0000757** If the declaration type is the exact datatype definition extracted from
758** the original CREATE TABLE statement if the expression is a column.
759**
760** The declaration type for an expression is either TEXT, NUMERIC or ANY.
761** The declaration type for a ROWID field is INTEGER.
762*/
danielk1977b3bce662005-01-29 08:32:43 +0000763static const char *columnType(NameContext *pNC, Expr *pExpr){
danielk197700e279d2004-06-21 07:36:32 +0000764 char const *zType;
danielk1977517eb642004-06-07 10:00:31 +0000765 int j;
danielk1977b3bce662005-01-29 08:32:43 +0000766 if( pExpr==0 || pNC->pSrcList==0 ) return 0;
danielk19775338a5f2005-01-20 13:03:10 +0000767
768 /* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING,
769 ** and LIMIT clauses. But pExpr originates in the result set of a
770 ** SELECT. So pExpr can never contain an AS operator.
771 */
772 assert( pExpr->op!=TK_AS );
773
danielk197700e279d2004-06-21 07:36:32 +0000774 switch( pExpr->op ){
775 case TK_COLUMN: {
danielk1977b3bce662005-01-29 08:32:43 +0000776 Table *pTab = 0;
danielk197700e279d2004-06-21 07:36:32 +0000777 int iCol = pExpr->iColumn;
danielk1977b3bce662005-01-29 08:32:43 +0000778 while( pNC && !pTab ){
779 SrcList *pTabList = pNC->pSrcList;
780 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
781 if( j<pTabList->nSrc ){
782 pTab = pTabList->a[j].pTab;
783 }else{
784 pNC = pNC->pNext;
785 }
786 }
drh7e627792005-04-29 02:10:00 +0000787 if( pTab==0 ){
788 /* FIX ME:
789 ** This can occurs if you have something like "SELECT new.x;" inside
790 ** a trigger. In other words, if you reference the special "new"
791 ** table in the result set of a select. We do not have a good way
792 ** to find the actual table type, so call it "TEXT". This is really
793 ** something of a bug, but I do not know how to fix it.
794 **
795 ** This code does not produce the correct answer - it just prevents
796 ** a segfault. See ticket #1229.
797 */
798 zType = "TEXT";
799 break;
800 }
danielk1977b3bce662005-01-29 08:32:43 +0000801 assert( pTab );
danielk197700e279d2004-06-21 07:36:32 +0000802 if( iCol<0 ) iCol = pTab->iPKey;
803 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
804 if( iCol<0 ){
805 zType = "INTEGER";
806 }else{
807 zType = pTab->aCol[iCol].zType;
808 }
809 break;
danielk1977517eb642004-06-07 10:00:31 +0000810 }
danielk197793758c82005-01-21 08:13:14 +0000811#ifndef SQLITE_OMIT_SUBQUERY
danielk197700e279d2004-06-21 07:36:32 +0000812 case TK_SELECT: {
danielk1977b3bce662005-01-29 08:32:43 +0000813 NameContext sNC;
danielk197700e279d2004-06-21 07:36:32 +0000814 Select *pS = pExpr->pSelect;
danielk1977b3bce662005-01-29 08:32:43 +0000815 sNC.pSrcList = pExpr->pSelect->pSrc;
816 sNC.pNext = pNC;
817 zType = columnType(&sNC, pS->pEList->a[0].pExpr);
danielk197700e279d2004-06-21 07:36:32 +0000818 break;
danielk1977517eb642004-06-07 10:00:31 +0000819 }
danielk197793758c82005-01-21 08:13:14 +0000820#endif
danielk197700e279d2004-06-21 07:36:32 +0000821 default:
822 zType = 0;
danielk1977517eb642004-06-07 10:00:31 +0000823 }
danielk197700e279d2004-06-21 07:36:32 +0000824
danielk1977517eb642004-06-07 10:00:31 +0000825 return zType;
826}
827
828/*
829** Generate code that will tell the VDBE the declaration types of columns
830** in the result set.
drhfcb78a42003-01-18 20:11:05 +0000831*/
832static void generateColumnTypes(
833 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000834 SrcList *pTabList, /* List of tables */
835 ExprList *pEList /* Expressions defining the result set */
836){
837 Vdbe *v = pParse->pVdbe;
danielk1977517eb642004-06-07 10:00:31 +0000838 int i;
danielk1977b3bce662005-01-29 08:32:43 +0000839 NameContext sNC;
840 sNC.pSrcList = pTabList;
drhfcb78a42003-01-18 20:11:05 +0000841 for(i=0; i<pEList->nExpr; i++){
842 Expr *p = pEList->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +0000843 const char *zType = columnType(&sNC, p);
danielk197700e279d2004-06-21 07:36:32 +0000844 if( zType==0 ) continue;
danielk1977fbcd5852004-06-15 02:44:18 +0000845 /* The vdbe must make it's own copy of the column-type, in case the
846 ** schema is reset before this virtual machine is deleted.
847 */
848 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
drhfcb78a42003-01-18 20:11:05 +0000849 }
850}
851
852/*
853** Generate code that will tell the VDBE the names of columns
854** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000855** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000856*/
drh832508b2002-03-02 17:04:07 +0000857static void generateColumnNames(
858 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000859 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000860 ExprList *pEList /* Expressions defining the result set */
861){
drhd8bc7082000-06-07 23:51:50 +0000862 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000863 int i, j;
drh9bb575f2004-09-06 17:24:11 +0000864 sqlite3 *db = pParse->db;
drhfcabd462004-02-20 14:50:58 +0000865 int fullNames, shortNames;
866
drhfe2093d2005-01-20 22:48:47 +0000867#ifndef SQLITE_OMIT_EXPLAIN
danielk19773cf86062004-05-26 10:11:05 +0000868 /* If this is an EXPLAIN, skip this step */
869 if( pParse->explain ){
danielk197761de0d12004-05-27 23:56:16 +0000870 return;
danielk19773cf86062004-05-26 10:11:05 +0000871 }
danielk19775338a5f2005-01-20 13:03:10 +0000872#endif
danielk19773cf86062004-05-26 10:11:05 +0000873
drhd6502752004-02-16 03:44:01 +0000874 assert( v!=0 );
danielk1977261919c2005-12-06 12:52:59 +0000875 if( pParse->colNamesSet || v==0 || sqlite3Tsd()->mallocFailed ) return;
drhd8bc7082000-06-07 23:51:50 +0000876 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000877 fullNames = (db->flags & SQLITE_FullColNames)!=0;
878 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
danielk197722322fd2004-05-25 23:35:17 +0000879 sqlite3VdbeSetNumCols(v, pEList->nExpr);
drh82c3d632000-06-06 21:56:07 +0000880 for(i=0; i<pEList->nExpr; i++){
881 Expr *p;
drh5a387052003-01-11 14:19:51 +0000882 p = pEList->a[i].pExpr;
883 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000884 if( pEList->a[i].zName ){
885 char *zName = pEList->a[i].zName;
danielk1977d8123362004-06-12 09:25:12 +0000886 sqlite3VdbeSetColName(v, i, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000887 continue;
888 }
drhfa173a72002-07-10 21:26:00 +0000889 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000890 Table *pTab;
drh97665872002-02-13 23:22:53 +0000891 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000892 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000893 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
894 assert( j<pTabList->nSrc );
895 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000896 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000897 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000898 if( iCol<0 ){
drh47a6db22005-01-18 16:02:40 +0000899 zCol = "rowid";
drhb1363202002-06-26 02:45:03 +0000900 }else{
901 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000902 }
drhfcabd462004-02-20 14:50:58 +0000903 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
drh2646da72005-12-09 20:02:05 +0000904 sqlite3VdbeSetColName(v, i, (char*)p->span.z, p->span.n);
drhfcabd462004-02-20 14:50:58 +0000905 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000906 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000907 char *zTab;
908
drh6a3ea0e2003-05-02 14:32:12 +0000909 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000910 if( fullNames || zTab==0 ) zTab = pTab->zName;
drhf93339d2006-01-03 15:16:26 +0000911 sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
danielk19773cf86062004-05-26 10:11:05 +0000912 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000913 }else{
drh47a6db22005-01-18 16:02:40 +0000914 sqlite3VdbeSetColName(v, i, zCol, strlen(zCol));
drh82c3d632000-06-06 21:56:07 +0000915 }
drh6977fea2002-10-22 23:38:04 +0000916 }else if( p->span.z && p->span.z[0] ){
drh2646da72005-12-09 20:02:05 +0000917 sqlite3VdbeSetColName(v, i, (char*)p->span.z, p->span.n);
danielk19773cf86062004-05-26 10:11:05 +0000918 /* sqlite3VdbeCompressSpace(v, addr); */
drh1bee3d72001-10-15 00:44:35 +0000919 }else{
920 char zName[30];
921 assert( p->op!=TK_COLUMN || pTabList==0 );
922 sprintf(zName, "column%d", i+1);
danielk19773cf86062004-05-26 10:11:05 +0000923 sqlite3VdbeSetColName(v, i, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000924 }
925 }
danielk197776d505b2004-05-28 13:13:02 +0000926 generateColumnTypes(pParse, pTabList, pEList);
drh82c3d632000-06-06 21:56:07 +0000927}
928
danielk197793758c82005-01-21 08:13:14 +0000929#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +0000930/*
drhd8bc7082000-06-07 23:51:50 +0000931** Name of the connection operator, used for error messages.
932*/
933static const char *selectOpName(int id){
934 char *z;
935 switch( id ){
936 case TK_ALL: z = "UNION ALL"; break;
937 case TK_INTERSECT: z = "INTERSECT"; break;
938 case TK_EXCEPT: z = "EXCEPT"; break;
939 default: z = "UNION"; break;
940 }
941 return z;
942}
danielk197793758c82005-01-21 08:13:14 +0000943#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +0000944
945/*
drh315555c2002-10-20 15:53:03 +0000946** Forward declaration
947*/
drh9b3187e2005-01-18 14:45:47 +0000948static int prepSelectStmt(Parse*, Select*);
drh315555c2002-10-20 15:53:03 +0000949
950/*
drh22f70c32002-02-18 01:17:00 +0000951** Given a SELECT statement, generate a Table structure that describes
952** the result set of that SELECT.
953*/
danielk19774adee202004-05-08 08:23:19 +0000954Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000955 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000956 int i, j;
drh22f70c32002-02-18 01:17:00 +0000957 ExprList *pEList;
drh290c1942004-08-21 17:54:45 +0000958 Column *aCol, *pCol;
drh22f70c32002-02-18 01:17:00 +0000959
drh9b3187e2005-01-18 14:45:47 +0000960 if( prepSelectStmt(pParse, pSelect) ){
drh22f70c32002-02-18 01:17:00 +0000961 return 0;
962 }
danielk1977142bdf42005-01-30 11:11:44 +0000963 if( sqlite3SelectResolve(pParse, pSelect, 0) ){
964 return 0;
965 }
drh22f70c32002-02-18 01:17:00 +0000966 pTab = sqliteMalloc( sizeof(Table) );
967 if( pTab==0 ){
968 return 0;
969 }
drhed8a3bb2005-06-06 21:19:56 +0000970 pTab->nRef = 1;
drh22f70c32002-02-18 01:17:00 +0000971 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
972 pEList = pSelect->pEList;
973 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000974 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000975 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh290c1942004-08-21 17:54:45 +0000976 for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
drh79d5f632005-01-18 17:20:10 +0000977 Expr *p, *pR;
danielk1977517eb642004-06-07 10:00:31 +0000978 char *zType;
drh91bb0ee2004-09-01 03:06:34 +0000979 char *zName;
drh79d5f632005-01-18 17:20:10 +0000980 char *zBasename;
981 int cnt;
danielk1977b3bce662005-01-29 08:32:43 +0000982 NameContext sNC;
drh79d5f632005-01-18 17:20:10 +0000983
984 /* Get an appropriate name for the column
985 */
986 p = pEList->a[i].pExpr;
drh290c1942004-08-21 17:54:45 +0000987 assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
drh91bb0ee2004-09-01 03:06:34 +0000988 if( (zName = pEList->a[i].zName)!=0 ){
drh79d5f632005-01-18 17:20:10 +0000989 /* If the column contains an "AS <name>" phrase, use <name> as the name */
drh91bb0ee2004-09-01 03:06:34 +0000990 zName = sqliteStrDup(zName);
danielk1977517eb642004-06-07 10:00:31 +0000991 }else if( p->op==TK_DOT
drh79d5f632005-01-18 17:20:10 +0000992 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
993 /* For columns of the from A.B use B as the name */
drh91bb0ee2004-09-01 03:06:34 +0000994 zName = sqlite3MPrintf("%T", &pR->token);
drhb733d032004-01-24 20:18:12 +0000995 }else if( p->span.z && p->span.z[0] ){
drh79d5f632005-01-18 17:20:10 +0000996 /* Use the original text of the column expression as its name */
drh91bb0ee2004-09-01 03:06:34 +0000997 zName = sqlite3MPrintf("%T", &p->span);
drh22f70c32002-02-18 01:17:00 +0000998 }else{
drh79d5f632005-01-18 17:20:10 +0000999 /* If all else fails, make up a name */
drh91bb0ee2004-09-01 03:06:34 +00001000 zName = sqlite3MPrintf("column%d", i+1);
drh22f70c32002-02-18 01:17:00 +00001001 }
drh91bb0ee2004-09-01 03:06:34 +00001002 sqlite3Dequote(zName);
danielk1977261919c2005-12-06 12:52:59 +00001003 if( sqlite3Tsd()->mallocFailed ){
drhdd5b2fa2005-03-28 03:39:55 +00001004 sqliteFree(zName);
1005 sqlite3DeleteTable(0, pTab);
1006 return 0;
1007 }
drh79d5f632005-01-18 17:20:10 +00001008
1009 /* Make sure the column name is unique. If the name is not unique,
1010 ** append a integer to the name so that it becomes unique.
1011 */
1012 zBasename = zName;
1013 for(j=cnt=0; j<i; j++){
1014 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
1015 zName = sqlite3MPrintf("%s:%d", zBasename, ++cnt);
1016 j = -1;
drhdd5b2fa2005-03-28 03:39:55 +00001017 if( zName==0 ) break;
drh79d5f632005-01-18 17:20:10 +00001018 }
1019 }
1020 if( zBasename!=zName ){
1021 sqliteFree(zBasename);
1022 }
drh91bb0ee2004-09-01 03:06:34 +00001023 pCol->zName = zName;
danielk1977517eb642004-06-07 10:00:31 +00001024
drh79d5f632005-01-18 17:20:10 +00001025 /* Get the typename, type affinity, and collating sequence for the
1026 ** column.
1027 */
drhc43e8be2005-05-16 22:37:54 +00001028 memset(&sNC, 0, sizeof(sNC));
danielk1977b3bce662005-01-29 08:32:43 +00001029 sNC.pSrcList = pSelect->pSrc;
1030 zType = sqliteStrDup(columnType(&sNC, p));
drh290c1942004-08-21 17:54:45 +00001031 pCol->zType = zType;
danielk1977c60e9b82005-01-31 12:42:29 +00001032 pCol->affinity = sqlite3ExprAffinity(p);
drh290c1942004-08-21 17:54:45 +00001033 pCol->pColl = sqlite3ExprCollSeq(pParse, p);
1034 if( !pCol->pColl ){
1035 pCol->pColl = pParse->db->pDfltColl;
danielk19770202b292004-06-09 09:55:16 +00001036 }
drh22f70c32002-02-18 01:17:00 +00001037 }
1038 pTab->iPKey = -1;
1039 return pTab;
1040}
1041
1042/*
drh9b3187e2005-01-18 14:45:47 +00001043** Prepare a SELECT statement for processing by doing the following
1044** things:
drhd8bc7082000-06-07 23:51:50 +00001045**
drh9b3187e2005-01-18 14:45:47 +00001046** (1) Make sure VDBE cursor numbers have been assigned to every
1047** element of the FROM clause.
1048**
1049** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
1050** defines FROM clause. When views appear in the FROM clause,
drh63eb5f22003-04-29 16:20:44 +00001051** fill pTabList->a[].pSelect with a copy of the SELECT statement
1052** that implements the view. A copy is made of the view's SELECT
1053** statement so that we can freely modify or delete that statement
1054** without worrying about messing up the presistent representation
1055** of the view.
drhd8bc7082000-06-07 23:51:50 +00001056**
drh9b3187e2005-01-18 14:45:47 +00001057** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
drhad2d8302002-05-24 20:31:36 +00001058** on joins and the ON and USING clause of joins.
1059**
drh9b3187e2005-01-18 14:45:47 +00001060** (4) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +00001061** for instances of the "*" operator or the TABLE.* operator.
1062** If found, expand each "*" to be every column in every table
1063** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +00001064**
1065** Return 0 on success. If there are problems, leave an error message
1066** in pParse and return non-zero.
1067*/
drh9b3187e2005-01-18 14:45:47 +00001068static int prepSelectStmt(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +00001069 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +00001070 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +00001071 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +00001072 Table *pTab;
drh290c1942004-08-21 17:54:45 +00001073 struct SrcList_item *pFrom;
drhdaffd0e2001-04-11 14:28:42 +00001074
danielk1977261919c2005-12-06 12:52:59 +00001075 if( p==0 || p->pSrc==0 || sqlite3Tsd()->mallocFailed ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00001076 pTabList = p->pSrc;
1077 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +00001078
drh9b3187e2005-01-18 14:45:47 +00001079 /* Make sure cursor numbers have been assigned to all entries in
1080 ** the FROM clause of the SELECT statement.
1081 */
1082 sqlite3SrcListAssignCursors(pParse, p->pSrc);
1083
1084 /* Look up every table named in the FROM clause of the select. If
1085 ** an entry of the FROM clause is a subquery instead of a table or view,
1086 ** then create a transient table structure to describe the subquery.
drhd8bc7082000-06-07 23:51:50 +00001087 */
drh290c1942004-08-21 17:54:45 +00001088 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
drh9b3187e2005-01-18 14:45:47 +00001089 if( pFrom->pTab!=0 ){
1090 /* This statement has already been prepared. There is no need
1091 ** to go further. */
1092 assert( i==0 );
drhd8bc7082000-06-07 23:51:50 +00001093 return 0;
1094 }
drh290c1942004-08-21 17:54:45 +00001095 if( pFrom->zName==0 ){
danielk197793758c82005-01-21 08:13:14 +00001096#ifndef SQLITE_OMIT_SUBQUERY
drh22f70c32002-02-18 01:17:00 +00001097 /* A sub-query in the FROM clause of a SELECT */
drh290c1942004-08-21 17:54:45 +00001098 assert( pFrom->pSelect!=0 );
1099 if( pFrom->zAlias==0 ){
drh91bb0ee2004-09-01 03:06:34 +00001100 pFrom->zAlias =
1101 sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
drhad2d8302002-05-24 20:31:36 +00001102 }
drhed8a3bb2005-06-06 21:19:56 +00001103 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001104 pFrom->pTab = pTab =
1105 sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
drh22f70c32002-02-18 01:17:00 +00001106 if( pTab==0 ){
1107 return 1;
1108 }
drh5cf590c2003-04-24 01:45:04 +00001109 /* The isTransient flag indicates that the Table structure has been
1110 ** dynamically allocated and may be freed at any time. In other words,
1111 ** pTab is not pointing to a persistent table structure that defines
1112 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +00001113 pTab->isTransient = 1;
danielk197793758c82005-01-21 08:13:14 +00001114#endif
drh22f70c32002-02-18 01:17:00 +00001115 }else{
drha76b5df2002-02-23 02:32:10 +00001116 /* An ordinary table or view name in the FROM clause */
drhed8a3bb2005-06-06 21:19:56 +00001117 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001118 pFrom->pTab = pTab =
1119 sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
drha76b5df2002-02-23 02:32:10 +00001120 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +00001121 return 1;
1122 }
drhed8a3bb2005-06-06 21:19:56 +00001123 pTab->nRef++;
danielk197793758c82005-01-21 08:13:14 +00001124#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00001125 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +00001126 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +00001127 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +00001128 return 1;
1129 }
drh290c1942004-08-21 17:54:45 +00001130 /* If pFrom->pSelect!=0 it means we are dealing with a
drh63eb5f22003-04-29 16:20:44 +00001131 ** view within a view. The SELECT structure has already been
1132 ** copied by the outer view so we can skip the copy step here
1133 ** in the inner view.
1134 */
drh290c1942004-08-21 17:54:45 +00001135 if( pFrom->pSelect==0 ){
1136 pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +00001137 }
drha76b5df2002-02-23 02:32:10 +00001138 }
danielk197793758c82005-01-21 08:13:14 +00001139#endif
drhd8bc7082000-06-07 23:51:50 +00001140 }
1141 }
1142
drhad2d8302002-05-24 20:31:36 +00001143 /* Process NATURAL keywords, and ON and USING clauses of joins.
1144 */
1145 if( sqliteProcessJoin(pParse, p) ) return 1;
1146
drh7c917d12001-12-16 20:05:05 +00001147 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +00001148 ** all columns in all tables. And for every TABLE.* insert the names
1149 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +00001150 ** with the TK_ALL operator for each "*" that it found in the column list.
1151 ** The following code just has to locate the TK_ALL expressions and expand
1152 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +00001153 **
1154 ** The first loop just checks to see if there are any "*" operators
1155 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +00001156 */
drh7c917d12001-12-16 20:05:05 +00001157 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001158 Expr *pE = pEList->a[k].pExpr;
1159 if( pE->op==TK_ALL ) break;
1160 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
1161 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +00001162 }
drh54473222002-04-04 02:10:55 +00001163 rc = 0;
drh7c917d12001-12-16 20:05:05 +00001164 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +00001165 /*
1166 ** If we get here it means the result set contains one or more "*"
1167 ** operators that need to be expanded. Loop through each expression
1168 ** in the result set and expand them one by one.
1169 */
drh7c917d12001-12-16 20:05:05 +00001170 struct ExprList_item *a = pEList->a;
1171 ExprList *pNew = 0;
drhd70dc522005-06-06 16:34:33 +00001172 int flags = pParse->db->flags;
1173 int longNames = (flags & SQLITE_FullColNames)!=0 &&
1174 (flags & SQLITE_ShortColNames)==0;
1175
drh7c917d12001-12-16 20:05:05 +00001176 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001177 Expr *pE = a[k].pExpr;
1178 if( pE->op!=TK_ALL &&
1179 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
1180 /* This particular expression does not need to be expanded.
1181 */
danielk19774adee202004-05-08 08:23:19 +00001182 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
danielk1977261919c2005-12-06 12:52:59 +00001183 if( pNew ){
1184 pNew->a[pNew->nExpr-1].zName = a[k].zName;
1185 }else{
1186 rc = 1;
1187 }
drh7c917d12001-12-16 20:05:05 +00001188 a[k].pExpr = 0;
1189 a[k].zName = 0;
1190 }else{
drh54473222002-04-04 02:10:55 +00001191 /* This expression is a "*" or a "TABLE.*" and needs to be
1192 ** expanded. */
1193 int tableSeen = 0; /* Set to 1 when TABLE matches */
drhcf55b7a2004-07-20 01:45:19 +00001194 char *zTName; /* text of name of TABLE */
drh54473222002-04-04 02:10:55 +00001195 if( pE->op==TK_DOT && pE->pLeft ){
drhcf55b7a2004-07-20 01:45:19 +00001196 zTName = sqlite3NameFromToken(&pE->pLeft->token);
drh54473222002-04-04 02:10:55 +00001197 }else{
drhcf55b7a2004-07-20 01:45:19 +00001198 zTName = 0;
drh54473222002-04-04 02:10:55 +00001199 }
drh290c1942004-08-21 17:54:45 +00001200 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1201 Table *pTab = pFrom->pTab;
1202 char *zTabName = pFrom->zAlias;
drh54473222002-04-04 02:10:55 +00001203 if( zTabName==0 || zTabName[0]==0 ){
1204 zTabName = pTab->zName;
1205 }
drhcf55b7a2004-07-20 01:45:19 +00001206 if( zTName && (zTabName==0 || zTabName[0]==0 ||
1207 sqlite3StrICmp(zTName, zTabName)!=0) ){
drh54473222002-04-04 02:10:55 +00001208 continue;
1209 }
1210 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001211 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001212 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001213 char *zName = pTab->aCol[j].zName;
1214
drh91bb0ee2004-09-01 03:06:34 +00001215 if( i>0 ){
1216 struct SrcList_item *pLeft = &pTabList->a[i-1];
1217 if( (pLeft->jointype & JT_NATURAL)!=0 &&
1218 columnIndex(pLeft->pTab, zName)>=0 ){
1219 /* In a NATURAL join, omit the join columns from the
1220 ** table on the right */
1221 continue;
1222 }
1223 if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1224 /* In a join with a USING clause, omit columns in the
1225 ** using clause from the table on the right. */
1226 continue;
1227 }
drhad2d8302002-05-24 20:31:36 +00001228 }
danielk19774adee202004-05-08 08:23:19 +00001229 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001230 if( pRight==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001231 setToken(&pRight->token, zName);
drhd70dc522005-06-06 16:34:33 +00001232 if( zTabName && (longNames || pTabList->nSrc>1) ){
danielk19774adee202004-05-08 08:23:19 +00001233 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1234 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001235 if( pExpr==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001236 setToken(&pLeft->token, zTabName);
1237 setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
drh6977fea2002-10-22 23:38:04 +00001238 pExpr->span.dyn = 1;
1239 pExpr->token.z = 0;
1240 pExpr->token.n = 0;
1241 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001242 }else{
drh22f70c32002-02-18 01:17:00 +00001243 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001244 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001245 }
drhd70dc522005-06-06 16:34:33 +00001246 if( longNames ){
1247 pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span);
1248 }else{
1249 pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
1250 }
drh7c917d12001-12-16 20:05:05 +00001251 }
drh17e24df2001-11-06 14:10:41 +00001252 }
drh54473222002-04-04 02:10:55 +00001253 if( !tableSeen ){
drhcf55b7a2004-07-20 01:45:19 +00001254 if( zTName ){
1255 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
drhf5db2d32002-06-06 23:42:27 +00001256 }else{
danielk19774adee202004-05-08 08:23:19 +00001257 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001258 }
drh54473222002-04-04 02:10:55 +00001259 rc = 1;
1260 }
drhcf55b7a2004-07-20 01:45:19 +00001261 sqliteFree(zTName);
drhd8bc7082000-06-07 23:51:50 +00001262 }
1263 }
danielk19774adee202004-05-08 08:23:19 +00001264 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001265 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001266 }
drh54473222002-04-04 02:10:55 +00001267 return rc;
drhd8bc7082000-06-07 23:51:50 +00001268}
1269
danielk197793758c82005-01-21 08:13:14 +00001270#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhff78bd22002-02-27 01:47:11 +00001271/*
drhd8bc7082000-06-07 23:51:50 +00001272** This routine associates entries in an ORDER BY expression list with
1273** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001274** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001275** the top-level node is filled in with column number and the iTable
1276** value of the top-level node is filled with iTable parameter.
1277**
1278** If there are prior SELECT clauses, they are processed first. A match
1279** in an earlier SELECT takes precedence over a later SELECT.
1280**
1281** Any entry that does not match is flagged as an error. The number
1282** of errors is returned.
1283*/
1284static int matchOrderbyToColumn(
1285 Parse *pParse, /* A place to leave error messages */
1286 Select *pSelect, /* Match to result columns of this SELECT */
1287 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001288 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001289 int mustComplete /* If TRUE all ORDER BYs must match */
1290){
1291 int nErr = 0;
1292 int i, j;
1293 ExprList *pEList;
1294
drhdaffd0e2001-04-11 14:28:42 +00001295 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001296 if( mustComplete ){
1297 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1298 }
drh9b3187e2005-01-18 14:45:47 +00001299 if( prepSelectStmt(pParse, pSelect) ){
drhd8bc7082000-06-07 23:51:50 +00001300 return 1;
1301 }
1302 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001303 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1304 return 1;
1305 }
drhd8bc7082000-06-07 23:51:50 +00001306 }
1307 pEList = pSelect->pEList;
1308 for(i=0; i<pOrderBy->nExpr; i++){
1309 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001310 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001311 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001312 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001313 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001314 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001315 "ORDER BY position %d should be between 1 and %d",
1316 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001317 nErr++;
1318 break;
1319 }
drhfcb78a42003-01-18 20:11:05 +00001320 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001321 iCol--;
1322 }
1323 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001324 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001325 char *zName, *zLabel;
1326 zName = pEList->a[j].zName;
drha99db3b2004-06-19 14:49:12 +00001327 zLabel = sqlite3NameFromToken(&pE->token);
1328 assert( zLabel!=0 );
danielk19774adee202004-05-08 08:23:19 +00001329 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001330 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001331 }
drh6e142f52000-06-08 13:36:40 +00001332 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001333 }
danielk19774adee202004-05-08 08:23:19 +00001334 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001335 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001336 }
1337 }
drhe4de1fe2002-06-02 16:09:01 +00001338 if( iCol>=0 ){
1339 pE->op = TK_COLUMN;
1340 pE->iColumn = iCol;
1341 pE->iTable = iTable;
danielk1977a58fdfb2005-02-08 07:50:40 +00001342 pE->iAgg = -1;
drhe4de1fe2002-06-02 16:09:01 +00001343 pOrderBy->a[i].done = 1;
1344 }
1345 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001346 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001347 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001348 nErr++;
1349 break;
1350 }
1351 }
1352 return nErr;
1353}
danielk197793758c82005-01-21 08:13:14 +00001354#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +00001355
1356/*
1357** Get a VDBE for the given parser context. Create a new one if necessary.
1358** If an error occurs, return NULL and leave a message in pParse.
1359*/
danielk19774adee202004-05-08 08:23:19 +00001360Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001361 Vdbe *v = pParse->pVdbe;
1362 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001363 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001364 }
drhd8bc7082000-06-07 23:51:50 +00001365 return v;
1366}
drhfcb78a42003-01-18 20:11:05 +00001367
drh15007a92006-01-08 18:10:17 +00001368
drhd8bc7082000-06-07 23:51:50 +00001369/*
drh7b58dae2003-07-20 01:16:46 +00001370** Compute the iLimit and iOffset fields of the SELECT based on the
drhec7429a2005-10-06 16:53:14 +00001371** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
drh7b58dae2003-07-20 01:16:46 +00001372** that appear in the original SQL statement after the LIMIT and OFFSET
danielk1977a2dc3b12005-02-05 12:48:48 +00001373** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
1374** are the integer memory register numbers for counters used to compute
1375** the limit and offset. If there is no limit and/or offset, then
1376** iLimit and iOffset are negative.
drh7b58dae2003-07-20 01:16:46 +00001377**
drhd59ba6c2006-01-08 05:02:54 +00001378** This routine changes the values of iLimit and iOffset only if
drhec7429a2005-10-06 16:53:14 +00001379** a limit or offset is defined by pLimit and pOffset. iLimit and
drh7b58dae2003-07-20 01:16:46 +00001380** iOffset should have been preset to appropriate default values
1381** (usually but not always -1) prior to calling this routine.
drhec7429a2005-10-06 16:53:14 +00001382** Only if pLimit!=0 or pOffset!=0 do the limit registers get
drh7b58dae2003-07-20 01:16:46 +00001383** redefined. The UNION ALL operator uses this property to force
1384** the reuse of the same limit and offset registers across multiple
1385** SELECT statements.
1386*/
drhec7429a2005-10-06 16:53:14 +00001387static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
drh15007a92006-01-08 18:10:17 +00001388 Vdbe *v;
1389 int iLimit;
1390 int iOffset;
1391 int addr1, addr2;
1392
drh7b58dae2003-07-20 01:16:46 +00001393 /*
drh7b58dae2003-07-20 01:16:46 +00001394 ** "LIMIT -1" always shows all rows. There is some
1395 ** contraversy about what the correct behavior should be.
1396 ** The current implementation interprets "LIMIT 0" to mean
1397 ** no rows.
1398 */
danielk1977a2dc3b12005-02-05 12:48:48 +00001399 if( p->pLimit ){
drh15007a92006-01-08 18:10:17 +00001400 p->iLimit = iLimit = pParse->nMem;
drhd59ba6c2006-01-08 05:02:54 +00001401 pParse->nMem += 2;
drh15007a92006-01-08 18:10:17 +00001402 v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001403 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001404 sqlite3ExprCode(pParse, p->pLimit);
1405 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
drh15007a92006-01-08 18:10:17 +00001406 sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 0);
drhad6d9462004-09-19 02:15:24 +00001407 VdbeComment((v, "# LIMIT counter"));
drh15007a92006-01-08 18:10:17 +00001408 sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001409 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001410 if( p->pOffset ){
drh15007a92006-01-08 18:10:17 +00001411 p->iOffset = iOffset = pParse->nMem++;
1412 v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001413 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001414 sqlite3ExprCode(pParse, p->pOffset);
1415 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
drh15007a92006-01-08 18:10:17 +00001416 sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0);
drhad6d9462004-09-19 02:15:24 +00001417 VdbeComment((v, "# OFFSET counter"));
drh15007a92006-01-08 18:10:17 +00001418 addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0);
1419 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1420 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
1421 sqlite3VdbeJumpHere(v, addr1);
drhd59ba6c2006-01-08 05:02:54 +00001422 if( p->pLimit ){
1423 sqlite3VdbeAddOp(v, OP_Add, 0, 0);
1424 }
drh7b58dae2003-07-20 01:16:46 +00001425 }
drhd59ba6c2006-01-08 05:02:54 +00001426 if( p->pLimit ){
drh15007a92006-01-08 18:10:17 +00001427 addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0);
1428 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1429 sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1);
1430 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
1431 sqlite3VdbeJumpHere(v, addr1);
1432 sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1);
drhd59ba6c2006-01-08 05:02:54 +00001433 VdbeComment((v, "# LIMIT+OFFSET"));
drh15007a92006-01-08 18:10:17 +00001434 sqlite3VdbeJumpHere(v, addr2);
drhd59ba6c2006-01-08 05:02:54 +00001435 }
drh7b58dae2003-07-20 01:16:46 +00001436}
1437
1438/*
drh0342b1f2005-09-01 03:07:44 +00001439** Allocate a virtual index to use for sorting.
drhd3d39e92004-05-20 22:16:29 +00001440*/
drh4db38a72005-09-01 12:16:28 +00001441static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
drh0342b1f2005-09-01 03:07:44 +00001442 if( pOrderBy ){
1443 int addr;
drh9d2985c2005-09-08 01:58:42 +00001444 assert( pOrderBy->iECursor==0 );
1445 pOrderBy->iECursor = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001446 addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenVirtual,
drh9d2985c2005-09-08 01:58:42 +00001447 pOrderBy->iECursor, pOrderBy->nExpr+1);
drh0342b1f2005-09-01 03:07:44 +00001448 assert( p->addrOpenVirt[2] == -1 );
1449 p->addrOpenVirt[2] = addr;
drh736c22b2004-05-21 02:14:24 +00001450 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001451}
1452
drh13449892005-09-07 21:22:45 +00001453/*
1454** The opcode at addr is an OP_OpenVirtual that created a sorting
1455** index tha we ended up not needing. This routine changes that
1456** opcode to OP_Noop.
1457*/
1458static void uncreateSortingIndex(Parse *pParse, int addr){
1459 Vdbe *v = pParse->pVdbe;
1460 VdbeOp *pOp = sqlite3VdbeGetOp(v, addr);
1461 sqlite3VdbeChangeP3(v, addr, 0, 0);
1462 pOp->opcode = OP_Noop;
1463 pOp->p1 = 0;
1464 pOp->p2 = 0;
1465}
1466
drhb7f91642004-10-31 02:22:47 +00001467#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001468/*
drhfbc4ee72004-08-29 01:31:05 +00001469** Return the appropriate collating sequence for the iCol-th column of
1470** the result set for the compound-select statement "p". Return NULL if
1471** the column has no default collating sequence.
1472**
1473** The collating sequence for the compound select is taken from the
1474** left-most term of the select that has a collating sequence.
1475*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001476static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
drhfbc4ee72004-08-29 01:31:05 +00001477 CollSeq *pRet;
danielk1977dc1bdc42004-06-11 10:51:27 +00001478 if( p->pPrior ){
1479 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
drhfbc4ee72004-08-29 01:31:05 +00001480 }else{
1481 pRet = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001482 }
drhfbc4ee72004-08-29 01:31:05 +00001483 if( pRet==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001484 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1485 }
1486 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001487}
drhb7f91642004-10-31 02:22:47 +00001488#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd3d39e92004-05-20 22:16:29 +00001489
drhb7f91642004-10-31 02:22:47 +00001490#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhd3d39e92004-05-20 22:16:29 +00001491/*
drh82c3d632000-06-06 21:56:07 +00001492** This routine is called to process a query that is really the union
1493** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001494**
drhe78e8282003-01-19 03:59:45 +00001495** "p" points to the right-most of the two queries. the query on the
1496** left is p->pPrior. The left query could also be a compound query
1497** in which case this routine will be called recursively.
1498**
1499** The results of the total query are to be written into a destination
1500** of type eDest with parameter iParm.
1501**
1502** Example 1: Consider a three-way compound SQL statement.
1503**
1504** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1505**
1506** This statement is parsed up as follows:
1507**
1508** SELECT c FROM t3
1509** |
1510** `-----> SELECT b FROM t2
1511** |
jplyon4b11c6d2004-01-19 04:57:53 +00001512** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001513**
1514** The arrows in the diagram above represent the Select.pPrior pointer.
1515** So if this routine is called with p equal to the t3 query, then
1516** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1517**
1518** Notice that because of the way SQLite parses compound SELECTs, the
1519** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001520*/
danielk197784ac9d02004-05-18 09:58:06 +00001521static int multiSelect(
drhfbc4ee72004-08-29 01:31:05 +00001522 Parse *pParse, /* Parsing context */
1523 Select *p, /* The right-most of SELECTs to be coded */
1524 int eDest, /* \___ Store query results as specified */
1525 int iParm, /* / by these two parameters. */
1526 char *aff /* If eDest is SRT_Union, the affinity string */
danielk197784ac9d02004-05-18 09:58:06 +00001527){
drhfbc4ee72004-08-29 01:31:05 +00001528 int rc = SQLITE_OK; /* Success code from a subroutine */
1529 Select *pPrior; /* Another SELECT immediately to our left */
1530 Vdbe *v; /* Generate code to this VDBE */
drh8cdbf832004-08-29 16:25:03 +00001531 int nCol; /* Number of columns in the result set */
drh0342b1f2005-09-01 03:07:44 +00001532 ExprList *pOrderBy; /* The ORDER BY clause on p */
1533 int aSetP2[2]; /* Set P2 value of these op to number of columns */
1534 int nSetP2 = 0; /* Number of slots in aSetP2[] used */
drh82c3d632000-06-06 21:56:07 +00001535
drh7b58dae2003-07-20 01:16:46 +00001536 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
drhfbc4ee72004-08-29 01:31:05 +00001537 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001538 */
danielk197784ac9d02004-05-18 09:58:06 +00001539 if( p==0 || p->pPrior==0 ){
1540 rc = 1;
1541 goto multi_select_end;
1542 }
drhd8bc7082000-06-07 23:51:50 +00001543 pPrior = p->pPrior;
drh0342b1f2005-09-01 03:07:44 +00001544 assert( pPrior->pRightmost!=pPrior );
1545 assert( pPrior->pRightmost==p->pRightmost );
drhd8bc7082000-06-07 23:51:50 +00001546 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001547 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001548 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001549 rc = 1;
1550 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001551 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001552 if( pPrior->pLimit ){
danielk19774adee202004-05-08 08:23:19 +00001553 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001554 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001555 rc = 1;
1556 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001557 }
drh82c3d632000-06-06 21:56:07 +00001558
drhd8bc7082000-06-07 23:51:50 +00001559 /* Make sure we have a valid query engine. If not, create a new one.
1560 */
danielk19774adee202004-05-08 08:23:19 +00001561 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001562 if( v==0 ){
1563 rc = 1;
1564 goto multi_select_end;
1565 }
drhd8bc7082000-06-07 23:51:50 +00001566
drh1cc3d752002-03-23 00:31:29 +00001567 /* Create the destination temporary table if necessary
1568 */
drh9d2985c2005-09-08 01:58:42 +00001569 if( eDest==SRT_VirtualTab ){
danielk1977b4964b72004-05-18 01:23:38 +00001570 assert( p->pEList );
drh0342b1f2005-09-01 03:07:44 +00001571 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1572 aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 0);
drh1cc3d752002-03-23 00:31:29 +00001573 eDest = SRT_Table;
1574 }
1575
drhf46f9052002-06-22 02:33:38 +00001576 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001577 */
drh0342b1f2005-09-01 03:07:44 +00001578 pOrderBy = p->pOrderBy;
drh82c3d632000-06-06 21:56:07 +00001579 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001580 case TK_ALL: {
drh0342b1f2005-09-01 03:07:44 +00001581 if( pOrderBy==0 ){
drhec7429a2005-10-06 16:53:14 +00001582 int addr = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001583 assert( !pPrior->pLimit );
1584 pPrior->pLimit = p->pLimit;
1585 pPrior->pOffset = p->pOffset;
danielk1977b3bce662005-01-29 08:32:43 +00001586 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
danielk1977ad68cb62006-01-05 14:22:33 +00001587 p->pLimit = 0;
1588 p->pOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001589 if( rc ){
1590 goto multi_select_end;
1591 }
drhf46f9052002-06-22 02:33:38 +00001592 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001593 p->iLimit = pPrior->iLimit;
1594 p->iOffset = pPrior->iOffset;
drhec7429a2005-10-06 16:53:14 +00001595 if( p->iLimit>=0 ){
1596 addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0);
1597 VdbeComment((v, "# Jump ahead if LIMIT reached"));
1598 }
danielk1977b3bce662005-01-29 08:32:43 +00001599 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001600 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001601 if( rc ){
1602 goto multi_select_end;
1603 }
drhec7429a2005-10-06 16:53:14 +00001604 if( addr ){
1605 sqlite3VdbeJumpHere(v, addr);
1606 }
drhf46f9052002-06-22 02:33:38 +00001607 break;
1608 }
1609 /* For UNION ALL ... ORDER BY fall through to the next case */
1610 }
drh82c3d632000-06-06 21:56:07 +00001611 case TK_EXCEPT:
1612 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001613 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001614 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001615 int priorOp; /* The SRT_ operation to apply to prior selects */
danielk1977a2dc3b12005-02-05 12:48:48 +00001616 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
danielk1977dc1bdc42004-06-11 10:51:27 +00001617 int addr;
drh82c3d632000-06-06 21:56:07 +00001618
drhd8bc7082000-06-07 23:51:50 +00001619 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh0342b1f2005-09-01 03:07:44 +00001620 if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
drhd8bc7082000-06-07 23:51:50 +00001621 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001622 ** right.
drhd8bc7082000-06-07 23:51:50 +00001623 */
drh82c3d632000-06-06 21:56:07 +00001624 unionTab = iParm;
1625 }else{
drhd8bc7082000-06-07 23:51:50 +00001626 /* We will need to create our own temporary table to hold the
1627 ** intermediate results.
1628 */
1629 unionTab = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001630 if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001631 rc = 1;
1632 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001633 }
drh9170dd72005-07-08 17:13:46 +00001634 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, unionTab, 0);
drh0342b1f2005-09-01 03:07:44 +00001635 if( priorOp==SRT_Table ){
1636 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1637 aSetP2[nSetP2++] = addr;
1638 }else{
1639 assert( p->addrOpenVirt[0] == -1 );
1640 p->addrOpenVirt[0] = addr;
1641 p->pRightmost->usesVirt = 1;
drhd8bc7082000-06-07 23:51:50 +00001642 }
drh0342b1f2005-09-01 03:07:44 +00001643 createSortingIndex(pParse, p, pOrderBy);
danielk197784ac9d02004-05-18 09:58:06 +00001644 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001645 }
drhd8bc7082000-06-07 23:51:50 +00001646
1647 /* Code the SELECT statements to our left
1648 */
danielk1977b3bce662005-01-29 08:32:43 +00001649 assert( !pPrior->pOrderBy );
1650 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001651 if( rc ){
1652 goto multi_select_end;
1653 }
drhd8bc7082000-06-07 23:51:50 +00001654
1655 /* Code the current SELECT statement
1656 */
1657 switch( p->op ){
1658 case TK_EXCEPT: op = SRT_Except; break;
1659 case TK_UNION: op = SRT_Union; break;
1660 case TK_ALL: op = SRT_Table; break;
1661 }
drh82c3d632000-06-06 21:56:07 +00001662 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001663 p->pOrderBy = 0;
drh4b14b4d2005-09-19 17:35:53 +00001664 p->disallowOrderBy = pOrderBy!=0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001665 pLimit = p->pLimit;
1666 p->pLimit = 0;
1667 pOffset = p->pOffset;
1668 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001669 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001670 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001671 p->pOrderBy = pOrderBy;
danielk1977a2dc3b12005-02-05 12:48:48 +00001672 sqlite3ExprDelete(p->pLimit);
1673 p->pLimit = pLimit;
1674 p->pOffset = pOffset;
drhbe5fd492004-12-16 21:09:16 +00001675 p->iLimit = -1;
1676 p->iOffset = -1;
danielk197784ac9d02004-05-18 09:58:06 +00001677 if( rc ){
1678 goto multi_select_end;
1679 }
1680
drhd8bc7082000-06-07 23:51:50 +00001681
1682 /* Convert the data in the temporary table into whatever form
1683 ** it is that we currently need.
1684 */
drhc926afb2002-06-20 03:38:26 +00001685 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001686 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001687 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001688 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001689 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001690 }
danielk19774adee202004-05-08 08:23:19 +00001691 iBreak = sqlite3VdbeMakeLabel(v);
1692 iCont = sqlite3VdbeMakeLabel(v);
drhec7429a2005-10-06 16:53:14 +00001693 computeLimitRegisters(pParse, p, iBreak);
danielk19774adee202004-05-08 08:23:19 +00001694 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
danielk19774adee202004-05-08 08:23:19 +00001695 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001696 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001697 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001698 iCont, iBreak, 0);
1699 if( rc ){
1700 rc = 1;
1701 goto multi_select_end;
1702 }
danielk19774adee202004-05-08 08:23:19 +00001703 sqlite3VdbeResolveLabel(v, iCont);
1704 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1705 sqlite3VdbeResolveLabel(v, iBreak);
1706 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001707 }
1708 break;
1709 }
1710 case TK_INTERSECT: {
1711 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001712 int iCont, iBreak, iStart;
danielk1977a2dc3b12005-02-05 12:48:48 +00001713 Expr *pLimit, *pOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001714 int addr;
drh82c3d632000-06-06 21:56:07 +00001715
drhd8bc7082000-06-07 23:51:50 +00001716 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001717 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001718 ** by allocating the tables we will need.
1719 */
drh82c3d632000-06-06 21:56:07 +00001720 tab1 = pParse->nTab++;
1721 tab2 = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001722 if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001723 rc = 1;
1724 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001725 }
drh0342b1f2005-09-01 03:07:44 +00001726 createSortingIndex(pParse, p, pOrderBy);
danielk1977dc1bdc42004-06-11 10:51:27 +00001727
drh9170dd72005-07-08 17:13:46 +00001728 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab1, 0);
drh0342b1f2005-09-01 03:07:44 +00001729 assert( p->addrOpenVirt[0] == -1 );
1730 p->addrOpenVirt[0] = addr;
1731 p->pRightmost->usesVirt = 1;
danielk197784ac9d02004-05-18 09:58:06 +00001732 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001733
1734 /* Code the SELECTs to our left into temporary table "tab1".
1735 */
danielk1977b3bce662005-01-29 08:32:43 +00001736 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001737 if( rc ){
1738 goto multi_select_end;
1739 }
drhd8bc7082000-06-07 23:51:50 +00001740
1741 /* Code the current SELECT into temporary table "tab2"
1742 */
drh9170dd72005-07-08 17:13:46 +00001743 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab2, 0);
drh0342b1f2005-09-01 03:07:44 +00001744 assert( p->addrOpenVirt[1] == -1 );
1745 p->addrOpenVirt[1] = addr;
drh82c3d632000-06-06 21:56:07 +00001746 p->pPrior = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001747 pLimit = p->pLimit;
1748 p->pLimit = 0;
1749 pOffset = p->pOffset;
1750 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001751 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001752 p->pPrior = pPrior;
danielk1977a2dc3b12005-02-05 12:48:48 +00001753 sqlite3ExprDelete(p->pLimit);
1754 p->pLimit = pLimit;
1755 p->pOffset = pOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001756 if( rc ){
1757 goto multi_select_end;
1758 }
drhd8bc7082000-06-07 23:51:50 +00001759
1760 /* Generate code to take the intersection of the two temporary
1761 ** tables.
1762 */
drh82c3d632000-06-06 21:56:07 +00001763 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001764 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001765 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001766 }
danielk19774adee202004-05-08 08:23:19 +00001767 iBreak = sqlite3VdbeMakeLabel(v);
1768 iCont = sqlite3VdbeMakeLabel(v);
drhec7429a2005-10-06 16:53:14 +00001769 computeLimitRegisters(pParse, p, iBreak);
danielk19774adee202004-05-08 08:23:19 +00001770 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh4a9f2412005-06-12 12:01:19 +00001771 iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
danielk19774adee202004-05-08 08:23:19 +00001772 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001773 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001774 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001775 iCont, iBreak, 0);
1776 if( rc ){
1777 rc = 1;
1778 goto multi_select_end;
1779 }
danielk19774adee202004-05-08 08:23:19 +00001780 sqlite3VdbeResolveLabel(v, iCont);
1781 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1782 sqlite3VdbeResolveLabel(v, iBreak);
1783 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1784 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001785 break;
1786 }
1787 }
drh8cdbf832004-08-29 16:25:03 +00001788
1789 /* Make sure all SELECTs in the statement have the same number of elements
1790 ** in their result sets.
1791 */
drh82c3d632000-06-06 21:56:07 +00001792 assert( p->pEList && pPrior->pEList );
1793 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001794 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001795 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001796 rc = 1;
1797 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001798 }
danielk197784ac9d02004-05-18 09:58:06 +00001799
drh8cdbf832004-08-29 16:25:03 +00001800 /* Set the number of columns in temporary tables
1801 */
1802 nCol = p->pEList->nExpr;
drh0342b1f2005-09-01 03:07:44 +00001803 while( nSetP2 ){
1804 sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
drh8cdbf832004-08-29 16:25:03 +00001805 }
1806
drhfbc4ee72004-08-29 01:31:05 +00001807 /* Compute collating sequences used by either the ORDER BY clause or
1808 ** by any temporary tables needed to implement the compound select.
1809 ** Attach the KeyInfo structure to all temporary tables. Invoke the
1810 ** ORDER BY processing if there is an ORDER BY clause.
drh8cdbf832004-08-29 16:25:03 +00001811 **
1812 ** This section is run by the right-most SELECT statement only.
1813 ** SELECT statements to the left always skip this part. The right-most
1814 ** SELECT might also skip this part if it has no ORDER BY clause and
1815 ** no temp tables are required.
drhfbc4ee72004-08-29 01:31:05 +00001816 */
drh0342b1f2005-09-01 03:07:44 +00001817 if( pOrderBy || p->usesVirt ){
drhfbc4ee72004-08-29 01:31:05 +00001818 int i; /* Loop counter */
1819 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
drh0342b1f2005-09-01 03:07:44 +00001820 Select *pLoop; /* For looping through SELECT statements */
1821 CollSeq **apColl;
1822 CollSeq **aCopy;
drhfbc4ee72004-08-29 01:31:05 +00001823
drh0342b1f2005-09-01 03:07:44 +00001824 assert( p->pRightmost==p );
drh4db38a72005-09-01 12:16:28 +00001825 pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*2*sizeof(CollSeq*) + nCol);
danielk1977dc1bdc42004-06-11 10:51:27 +00001826 if( !pKeyInfo ){
1827 rc = SQLITE_NOMEM;
1828 goto multi_select_end;
1829 }
1830
1831 pKeyInfo->enc = pParse->db->enc;
1832 pKeyInfo->nField = nCol;
1833
drh0342b1f2005-09-01 03:07:44 +00001834 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
1835 *apColl = multiSelectCollSeq(pParse, p, i);
1836 if( 0==*apColl ){
1837 *apColl = pParse->db->pDfltColl;
danielk1977dc1bdc42004-06-11 10:51:27 +00001838 }
1839 }
1840
drh0342b1f2005-09-01 03:07:44 +00001841 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
1842 for(i=0; i<2; i++){
1843 int addr = pLoop->addrOpenVirt[i];
1844 if( addr<0 ){
1845 /* If [0] is unused then [1] is also unused. So we can
1846 ** always safely abort as soon as the first unused slot is found */
1847 assert( pLoop->addrOpenVirt[1]<0 );
1848 break;
1849 }
1850 sqlite3VdbeChangeP2(v, addr, nCol);
1851 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
1852 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001853 }
1854
drh0342b1f2005-09-01 03:07:44 +00001855 if( pOrderBy ){
1856 struct ExprList_item *pOTerm = pOrderBy->a;
drh4efc0832005-11-16 13:47:50 +00001857 int nOrderByExpr = pOrderBy->nExpr;
drh0342b1f2005-09-01 03:07:44 +00001858 int addr;
drh4db38a72005-09-01 12:16:28 +00001859 u8 *pSortOrder;
drh0342b1f2005-09-01 03:07:44 +00001860
1861 aCopy = (CollSeq**)&pKeyInfo[1];
drh4efc0832005-11-16 13:47:50 +00001862 pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
drh0342b1f2005-09-01 03:07:44 +00001863 memcpy(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
1864 apColl = pKeyInfo->aColl;
drh4efc0832005-11-16 13:47:50 +00001865 for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
drh0342b1f2005-09-01 03:07:44 +00001866 Expr *pExpr = pOTerm->pExpr;
1867 char *zName = pOTerm->zName;
danielk1977dc1bdc42004-06-11 10:51:27 +00001868 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
danielk1977dc1bdc42004-06-11 10:51:27 +00001869 if( zName ){
drh0342b1f2005-09-01 03:07:44 +00001870 *apColl = sqlite3LocateCollSeq(pParse, zName, -1);
danielk1977dc1bdc42004-06-11 10:51:27 +00001871 }else{
drh0342b1f2005-09-01 03:07:44 +00001872 *apColl = aCopy[pExpr->iColumn];
danielk1977dc1bdc42004-06-11 10:51:27 +00001873 }
drh4db38a72005-09-01 12:16:28 +00001874 *pSortOrder = pOTerm->sortOrder;
danielk1977dc1bdc42004-06-11 10:51:27 +00001875 }
drh0342b1f2005-09-01 03:07:44 +00001876 assert( p->pRightmost==p );
1877 assert( p->addrOpenVirt[2]>=0 );
1878 addr = p->addrOpenVirt[2];
drh4db38a72005-09-01 12:16:28 +00001879 sqlite3VdbeChangeP2(v, addr, p->pEList->nExpr+2);
drh4efc0832005-11-16 13:47:50 +00001880 pKeyInfo->nField = nOrderByExpr;
drh4db38a72005-09-01 12:16:28 +00001881 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
1882 pKeyInfo = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001883 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1884 }
1885
drh0342b1f2005-09-01 03:07:44 +00001886 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001887 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001888
1889multi_select_end:
danielk197784ac9d02004-05-18 09:58:06 +00001890 return rc;
drh22827922000-06-06 17:27:05 +00001891}
drhb7f91642004-10-31 02:22:47 +00001892#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drh22827922000-06-06 17:27:05 +00001893
drhb7f91642004-10-31 02:22:47 +00001894#ifndef SQLITE_OMIT_VIEW
drh22827922000-06-06 17:27:05 +00001895/*
drh832508b2002-03-02 17:04:07 +00001896** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001897** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001898** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001899** unchanged.)
drh832508b2002-03-02 17:04:07 +00001900**
1901** This routine is part of the flattening procedure. A subquery
1902** whose result set is defined by pEList appears as entry in the
1903** FROM clause of a SELECT such that the VDBE cursor assigned to that
1904** FORM clause entry is iTable. This routine make the necessary
1905** changes to pExpr so that it refers directly to the source table
1906** of the subquery rather the result set of the subquery.
1907*/
drh6a3ea0e2003-05-02 14:32:12 +00001908static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
danielk1977b3bce662005-01-29 08:32:43 +00001909static void substSelect(Select *, int, ExprList *); /* Forward Decl */
drh6a3ea0e2003-05-02 14:32:12 +00001910static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001911 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001912 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1913 if( pExpr->iColumn<0 ){
1914 pExpr->op = TK_NULL;
1915 }else{
1916 Expr *pNew;
1917 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1918 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1919 pNew = pEList->a[pExpr->iColumn].pExpr;
1920 assert( pNew!=0 );
1921 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001922 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001923 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001924 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001925 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001926 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001927 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001928 pExpr->iTable = pNew->iTable;
1929 pExpr->iColumn = pNew->iColumn;
1930 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001931 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1932 sqlite3TokenCopy(&pExpr->span, &pNew->span);
danielk1977a1cb1832005-02-12 08:59:55 +00001933 pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
1934 pExpr->flags = pNew->flags;
drh50350a12004-02-13 16:22:22 +00001935 }
drh832508b2002-03-02 17:04:07 +00001936 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001937 substExpr(pExpr->pLeft, iTable, pEList);
1938 substExpr(pExpr->pRight, iTable, pEList);
danielk1977b3bce662005-01-29 08:32:43 +00001939 substSelect(pExpr->pSelect, iTable, pEList);
drh6a3ea0e2003-05-02 14:32:12 +00001940 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001941 }
1942}
danielk1977b3bce662005-01-29 08:32:43 +00001943static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001944 int i;
1945 if( pList==0 ) return;
1946 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001947 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001948 }
1949}
danielk1977b3bce662005-01-29 08:32:43 +00001950static void substSelect(Select *p, int iTable, ExprList *pEList){
1951 if( !p ) return;
1952 substExprList(p->pEList, iTable, pEList);
1953 substExprList(p->pGroupBy, iTable, pEList);
1954 substExprList(p->pOrderBy, iTable, pEList);
1955 substExpr(p->pHaving, iTable, pEList);
1956 substExpr(p->pWhere, iTable, pEList);
1957}
drhb7f91642004-10-31 02:22:47 +00001958#endif /* !defined(SQLITE_OMIT_VIEW) */
drh832508b2002-03-02 17:04:07 +00001959
drhb7f91642004-10-31 02:22:47 +00001960#ifndef SQLITE_OMIT_VIEW
drh832508b2002-03-02 17:04:07 +00001961/*
drh1350b032002-02-27 19:00:20 +00001962** This routine attempts to flatten subqueries in order to speed
1963** execution. It returns 1 if it makes changes and 0 if no flattening
1964** occurs.
1965**
1966** To understand the concept of flattening, consider the following
1967** query:
1968**
1969** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1970**
1971** The default way of implementing this query is to execute the
1972** subquery first and store the results in a temporary table, then
1973** run the outer query on that temporary table. This requires two
1974** passes over the data. Furthermore, because the temporary table
1975** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001976** optimized.
drh1350b032002-02-27 19:00:20 +00001977**
drh832508b2002-03-02 17:04:07 +00001978** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001979** a single flat select, like this:
1980**
1981** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1982**
1983** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001984** but only has to scan the data once. And because indices might
1985** exist on the table t1, a complete scan of the data might be
1986** avoided.
drh1350b032002-02-27 19:00:20 +00001987**
drh832508b2002-03-02 17:04:07 +00001988** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001989**
drh832508b2002-03-02 17:04:07 +00001990** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001991**
drh832508b2002-03-02 17:04:07 +00001992** (2) The subquery is not an aggregate or the outer query is not a join.
1993**
drh8af4d3a2003-05-06 20:35:16 +00001994** (3) The subquery is not the right operand of a left outer join, or
1995** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001996**
1997** (4) The subquery is not DISTINCT or the outer query is not a join.
1998**
1999** (5) The subquery is not DISTINCT or the outer query does not use
2000** aggregates.
2001**
2002** (6) The subquery does not use aggregates or the outer query is not
2003** DISTINCT.
2004**
drh08192d52002-04-30 19:20:28 +00002005** (7) The subquery has a FROM clause.
2006**
drhdf199a22002-06-14 22:38:41 +00002007** (8) The subquery does not use LIMIT or the outer query is not a join.
2008**
2009** (9) The subquery does not use LIMIT or the outer query does not use
2010** aggregates.
2011**
2012** (10) The subquery does not use aggregates or the outer query does not
2013** use LIMIT.
2014**
drh174b6192002-12-03 02:22:52 +00002015** (11) The subquery and the outer query do not both have ORDER BY clauses.
2016**
drh3fc673e2003-06-16 00:40:34 +00002017** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
2018** subquery has no WHERE clause. (added by ticket #350)
2019**
drh832508b2002-03-02 17:04:07 +00002020** In this routine, the "p" parameter is a pointer to the outer query.
2021** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
2022** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2023**
drh665de472003-03-31 13:36:09 +00002024** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00002025** If flattening is attempted this routine returns 1.
2026**
2027** All of the expression analysis must occur on both the outer query and
2028** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00002029*/
drh8c74a8c2002-08-25 19:20:40 +00002030static int flattenSubquery(
2031 Parse *pParse, /* The parsing context */
2032 Select *p, /* The parent or outer SELECT statement */
2033 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
2034 int isAgg, /* True if outer SELECT uses aggregate functions */
2035 int subqueryIsAgg /* True if the subquery uses aggregate functions */
2036){
drh0bb28102002-05-08 11:54:14 +00002037 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00002038 SrcList *pSrc; /* The FROM clause of the outer query */
2039 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00002040 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00002041 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh91bb0ee2004-09-01 03:06:34 +00002042 int i; /* Loop counter */
2043 Expr *pWhere; /* The WHERE clause */
2044 struct SrcList_item *pSubitem; /* The subquery */
drh1350b032002-02-27 19:00:20 +00002045
drh832508b2002-03-02 17:04:07 +00002046 /* Check to see if flattening is permitted. Return 0 if not.
2047 */
2048 if( p==0 ) return 0;
2049 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00002050 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh91bb0ee2004-09-01 03:06:34 +00002051 pSubitem = &pSrc->a[iFrom];
2052 pSub = pSubitem->pSelect;
drh832508b2002-03-02 17:04:07 +00002053 assert( pSub!=0 );
2054 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00002055 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00002056 pSubSrc = pSub->pSrc;
2057 assert( pSubSrc );
danielk1977a2dc3b12005-02-05 12:48:48 +00002058 if( (pSub->pLimit && p->pLimit) || pSub->pOffset ||
2059 (pSub->pLimit && isAgg) ) return 0;
drhc31c2eb2003-05-02 16:04:17 +00002060 if( pSubSrc->nSrc==0 ) return 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00002061 if( pSub->isDistinct && (pSrc->nSrc>1 || isAgg) ){
drhdf199a22002-06-14 22:38:41 +00002062 return 0;
2063 }
danielk1977a2dc3b12005-02-05 12:48:48 +00002064 if( p->isDistinct && subqueryIsAgg ) return 0;
drh4b14b4d2005-09-19 17:35:53 +00002065 if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00002066
drh8af4d3a2003-05-06 20:35:16 +00002067 /* Restriction 3: If the subquery is a join, make sure the subquery is
2068 ** not used as the right operand of an outer join. Examples of why this
2069 ** is not allowed:
2070 **
2071 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
2072 **
2073 ** If we flatten the above, we would get
2074 **
2075 ** (t1 LEFT OUTER JOIN t2) JOIN t3
2076 **
2077 ** which is not at all the same thing.
2078 */
2079 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
2080 return 0;
2081 }
2082
drh3fc673e2003-06-16 00:40:34 +00002083 /* Restriction 12: If the subquery is the right operand of a left outer
2084 ** join, make sure the subquery has no WHERE clause.
2085 ** An examples of why this is not allowed:
2086 **
2087 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
2088 **
2089 ** If we flatten the above, we would get
2090 **
2091 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
2092 **
2093 ** But the t2.x>0 test will always fail on a NULL row of t2, which
2094 ** effectively converts the OUTER JOIN into an INNER JOIN.
2095 */
2096 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
2097 && pSub->pWhere!=0 ){
2098 return 0;
2099 }
2100
drh0bb28102002-05-08 11:54:14 +00002101 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00002102 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00002103 */
drhc31c2eb2003-05-02 16:04:17 +00002104
2105 /* Move all of the FROM elements of the subquery into the
2106 ** the FROM clause of the outer query. Before doing this, remember
2107 ** the cursor number for the original outer query FROM element in
2108 ** iParent. The iParent cursor will never be used. Subsequent code
2109 ** will scan expressions looking for iParent references and replace
2110 ** those references with expressions that resolve to the subquery FROM
2111 ** elements we are now copying in.
2112 */
drh91bb0ee2004-09-01 03:06:34 +00002113 iParent = pSubitem->iCursor;
drhc31c2eb2003-05-02 16:04:17 +00002114 {
2115 int nSubSrc = pSubSrc->nSrc;
drh91bb0ee2004-09-01 03:06:34 +00002116 int jointype = pSubitem->jointype;
drhc31c2eb2003-05-02 16:04:17 +00002117
drhed8a3bb2005-06-06 21:19:56 +00002118 sqlite3DeleteTable(0, pSubitem->pTab);
drh91bb0ee2004-09-01 03:06:34 +00002119 sqliteFree(pSubitem->zDatabase);
2120 sqliteFree(pSubitem->zName);
2121 sqliteFree(pSubitem->zAlias);
drhc31c2eb2003-05-02 16:04:17 +00002122 if( nSubSrc>1 ){
2123 int extra = nSubSrc - 1;
2124 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00002125 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00002126 }
2127 p->pSrc = pSrc;
2128 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2129 pSrc->a[i] = pSrc->a[i-extra];
2130 }
2131 }
2132 for(i=0; i<nSubSrc; i++){
2133 pSrc->a[i+iFrom] = pSubSrc->a[i];
2134 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2135 }
drh8af4d3a2003-05-06 20:35:16 +00002136 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00002137 }
2138
2139 /* Now begin substituting subquery result set expressions for
2140 ** references to the iParent in the outer query.
2141 **
2142 ** Example:
2143 **
2144 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2145 ** \ \_____________ subquery __________/ /
2146 ** \_____________________ outer query ______________________________/
2147 **
2148 ** We look at every expression in the outer query and every place we see
2149 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2150 */
drh6a3ea0e2003-05-02 14:32:12 +00002151 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00002152 pList = p->pEList;
2153 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00002154 Expr *pExpr;
2155 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
drh2646da72005-12-09 20:02:05 +00002156 pList->a[i].zName = sqliteStrNDup((char*)pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00002157 }
2158 }
drh1b2e0322002-03-03 02:49:51 +00002159 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00002160 substExprList(p->pGroupBy, iParent, pSub->pEList);
2161 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00002162 }
drh174b6192002-12-03 02:22:52 +00002163 if( pSub->pOrderBy ){
2164 assert( p->pOrderBy==0 );
2165 p->pOrderBy = pSub->pOrderBy;
2166 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00002167 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00002168 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00002169 }
drh832508b2002-03-02 17:04:07 +00002170 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002171 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00002172 }else{
2173 pWhere = 0;
2174 }
2175 if( subqueryIsAgg ){
2176 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00002177 p->pHaving = p->pWhere;
2178 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00002179 substExpr(p->pHaving, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002180 p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
drh1b2e0322002-03-03 02:49:51 +00002181 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00002182 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00002183 }else{
drh6a3ea0e2003-05-02 14:32:12 +00002184 substExpr(p->pWhere, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002185 p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
drh832508b2002-03-02 17:04:07 +00002186 }
drhc31c2eb2003-05-02 16:04:17 +00002187
2188 /* The flattened query is distinct if either the inner or the
2189 ** outer query is distinct.
2190 */
drh832508b2002-03-02 17:04:07 +00002191 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00002192
danielk1977a58fdfb2005-02-08 07:50:40 +00002193 /*
2194 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2195 */
danielk1977a2dc3b12005-02-05 12:48:48 +00002196 if( pSub->pLimit ){
2197 p->pLimit = pSub->pLimit;
2198 pSub->pLimit = 0;
drhdf199a22002-06-14 22:38:41 +00002199 }
drh8c74a8c2002-08-25 19:20:40 +00002200
drhc31c2eb2003-05-02 16:04:17 +00002201 /* Finially, delete what is left of the subquery and return
2202 ** success.
2203 */
danielk19774adee202004-05-08 08:23:19 +00002204 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00002205 return 1;
2206}
drhb7f91642004-10-31 02:22:47 +00002207#endif /* SQLITE_OMIT_VIEW */
drh1350b032002-02-27 19:00:20 +00002208
2209/*
drh9562b552002-02-19 15:00:07 +00002210** Analyze the SELECT statement passed in as an argument to see if it
2211** is a simple min() or max() query. If it is and this query can be
2212** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00002213** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00002214** simple min() or max() query, then return 0;
2215**
2216** A simply min() or max() query looks like this:
2217**
2218** SELECT min(a) FROM table;
2219** SELECT max(a) FROM table;
2220**
2221** The query may have only a single table in its FROM argument. There
2222** can be no GROUP BY or HAVING or WHERE clauses. The result set must
2223** be the min() or max() of a single column of the table. The column
2224** in the min() or max() function must be indexed.
2225**
danielk19774adee202004-05-08 08:23:19 +00002226** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00002227** See the header comment on that routine for additional information.
2228*/
2229static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2230 Expr *pExpr;
2231 int iCol;
2232 Table *pTab;
2233 Index *pIdx;
2234 int base;
2235 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00002236 int seekOp;
drh6e175292004-03-13 14:00:36 +00002237 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00002238 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00002239 SrcList *pSrc;
drhec7429a2005-10-06 16:53:14 +00002240 int brk;
danielk1977da184232006-01-05 11:34:32 +00002241 int iDb;
drh9562b552002-02-19 15:00:07 +00002242
2243 /* Check to see if this query is a simple min() or max() query. Return
2244 ** zero if it is not.
2245 */
2246 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00002247 pSrc = p->pSrc;
2248 if( pSrc->nSrc!=1 ) return 0;
2249 pEList = p->pEList;
2250 if( pEList->nExpr!=1 ) return 0;
2251 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002252 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002253 pList = pExpr->pList;
2254 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002255 if( pExpr->token.n!=3 ) return 0;
drh2646da72005-12-09 20:02:05 +00002256 if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002257 seekOp = OP_Rewind;
drh2646da72005-12-09 20:02:05 +00002258 }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002259 seekOp = OP_Last;
2260 }else{
2261 return 0;
2262 }
drh6e175292004-03-13 14:00:36 +00002263 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002264 if( pExpr->op!=TK_COLUMN ) return 0;
2265 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002266 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002267
danielk1977c00da102006-01-07 13:21:04 +00002268
drh9562b552002-02-19 15:00:07 +00002269 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002270 ** Check to make sure we have an index and make pIdx point to the
2271 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2272 ** key column, no index is necessary so set pIdx to NULL. If no
2273 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002274 */
2275 if( iCol<0 ){
2276 pIdx = 0;
2277 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002278 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002279 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2280 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002281 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002282 }
2283 if( pIdx==0 ) return 0;
2284 }
2285
drhe5f50722003-07-19 00:44:14 +00002286 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002287 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002288 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002289 */
danielk19774adee202004-05-08 08:23:19 +00002290 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002291 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002292
drh0c37e632004-01-30 02:01:03 +00002293 /* If the output is destined for a temporary table, open that table.
2294 */
drh9d2985c2005-09-08 01:58:42 +00002295 if( eDest==SRT_VirtualTab ){
drhd81bd4e2005-09-05 20:06:49 +00002296 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002297 }
2298
drh17f71932002-02-21 12:01:27 +00002299 /* Generating code to find the min or the max. Basically all we have
2300 ** to do is find the first or the last entry in the chosen index. If
2301 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2302 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002303 */
danielk1977da184232006-01-05 11:34:32 +00002304 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2305 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977c00da102006-01-07 13:21:04 +00002306 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh6e175292004-03-13 14:00:36 +00002307 base = pSrc->a[0].iCursor;
drhec7429a2005-10-06 16:53:14 +00002308 brk = sqlite3VdbeMakeLabel(v);
2309 computeLimitRegisters(pParse, p, brk);
drh6e175292004-03-13 14:00:36 +00002310 if( pSrc->a[0].pSelect==0 ){
danielk1977c00da102006-01-07 13:21:04 +00002311 sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead);
drh6e175292004-03-13 14:00:36 +00002312 }
drh9562b552002-02-19 15:00:07 +00002313 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002314 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002315 }else{
danielk19773719d7f2005-01-17 08:57:09 +00002316 /* Even though the cursor used to open the index here is closed
2317 ** as soon as a single value has been read from it, allocate it
2318 ** using (pParse->nTab++) to prevent the cursor id from being
2319 ** reused. This is important for statements of the form
2320 ** "INSERT INTO x SELECT max() FROM x".
2321 */
2322 int iIdx;
2323 iIdx = pParse->nTab++;
danielk1977da184232006-01-05 11:34:32 +00002324 assert( pIdx->pSchema==pTab->pSchema );
2325 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002326 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
drhd3d39e92004-05-20 22:16:29 +00002327 (char*)&pIdx->keyInfo, P3_KEYINFO);
drh9eb516c2004-07-18 20:52:32 +00002328 if( seekOp==OP_Rewind ){
drhf0863fe2005-06-12 21:35:51 +00002329 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh1af3fdb2004-07-18 21:33:01 +00002330 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2331 seekOp = OP_MoveGt;
drh9eb516c2004-07-18 20:52:32 +00002332 }
danielk19773719d7f2005-01-17 08:57:09 +00002333 sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
drhf0863fe2005-06-12 21:35:51 +00002334 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002335 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002336 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002337 }
drh5cf8e8c2002-02-19 22:42:05 +00002338 eList.nExpr = 1;
2339 memset(&eListItem, 0, sizeof(eListItem));
2340 eList.a = &eListItem;
2341 eList.a[0].pExpr = pExpr;
drhec7429a2005-10-06 16:53:14 +00002342 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0);
2343 sqlite3VdbeResolveLabel(v, brk);
danielk19774adee202004-05-08 08:23:19 +00002344 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002345
drh9562b552002-02-19 15:00:07 +00002346 return 1;
2347}
2348
2349/*
drh290c1942004-08-21 17:54:45 +00002350** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
2351** the number of errors seen.
2352**
2353** An ORDER BY or GROUP BY is a list of expressions. If any expression
2354** is an integer constant, then that expression is replaced by the
2355** corresponding entry in the result set.
2356*/
2357static int processOrderGroupBy(
danielk1977b3bce662005-01-29 08:32:43 +00002358 NameContext *pNC, /* Name context of the SELECT statement. */
drh290c1942004-08-21 17:54:45 +00002359 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
drh290c1942004-08-21 17:54:45 +00002360 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
2361){
2362 int i;
danielk1977b3bce662005-01-29 08:32:43 +00002363 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */
2364 Parse *pParse = pNC->pParse; /* The result set of the SELECT */
2365 assert( pEList );
2366
drh290c1942004-08-21 17:54:45 +00002367 if( pOrderBy==0 ) return 0;
2368 for(i=0; i<pOrderBy->nExpr; i++){
2369 int iCol;
2370 Expr *pE = pOrderBy->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +00002371 if( sqlite3ExprIsInteger(pE, &iCol) ){
2372 if( iCol>0 && iCol<=pEList->nExpr ){
2373 sqlite3ExprDelete(pE);
2374 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2375 }else{
drh290c1942004-08-21 17:54:45 +00002376 sqlite3ErrorMsg(pParse,
2377 "%s BY column number %d out of range - should be "
2378 "between 1 and %d", zType, iCol, pEList->nExpr);
2379 return 1;
2380 }
2381 }
danielk1977b3bce662005-01-29 08:32:43 +00002382 if( sqlite3ExprResolveNames(pNC, pE) ){
2383 return 1;
2384 }
2385 if( sqlite3ExprIsConstant(pE) ){
2386 sqlite3ErrorMsg(pParse,
2387 "%s BY terms must not be non-integer constants", zType);
2388 return 1;
2389 }
drh290c1942004-08-21 17:54:45 +00002390 }
2391 return 0;
2392}
2393
2394/*
danielk1977b3bce662005-01-29 08:32:43 +00002395** This routine resolves any names used in the result set of the
2396** supplied SELECT statement. If the SELECT statement being resolved
2397** is a sub-select, then pOuterNC is a pointer to the NameContext
2398** of the parent SELECT.
2399*/
2400int sqlite3SelectResolve(
2401 Parse *pParse, /* The parser context */
2402 Select *p, /* The SELECT statement being coded. */
2403 NameContext *pOuterNC /* The outer name context. May be NULL. */
2404){
2405 ExprList *pEList; /* Result set. */
2406 int i; /* For-loop variable used in multiple places */
2407 NameContext sNC; /* Local name-context */
drh13449892005-09-07 21:22:45 +00002408 ExprList *pGroupBy; /* The group by clause */
danielk1977b3bce662005-01-29 08:32:43 +00002409
2410 /* If this routine has run before, return immediately. */
2411 if( p->isResolved ){
2412 assert( !pOuterNC );
2413 return SQLITE_OK;
2414 }
2415 p->isResolved = 1;
2416
2417 /* If there have already been errors, do nothing. */
2418 if( pParse->nErr>0 ){
2419 return SQLITE_ERROR;
2420 }
2421
2422 /* Prepare the select statement. This call will allocate all cursors
2423 ** required to handle the tables and subqueries in the FROM clause.
2424 */
2425 if( prepSelectStmt(pParse, p) ){
2426 return SQLITE_ERROR;
2427 }
2428
danielk1977a2dc3b12005-02-05 12:48:48 +00002429 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2430 ** are not allowed to refer to any names, so pass an empty NameContext.
2431 */
drhffe07b22005-11-03 00:41:17 +00002432 memset(&sNC, 0, sizeof(sNC));
danielk1977b3bce662005-01-29 08:32:43 +00002433 sNC.pParse = pParse;
danielk1977a2dc3b12005-02-05 12:48:48 +00002434 if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2435 sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2436 return SQLITE_ERROR;
2437 }
2438
2439 /* Set up the local name-context to pass to ExprResolveNames() to
2440 ** resolve the expression-list.
2441 */
2442 sNC.allowAgg = 1;
2443 sNC.pSrcList = p->pSrc;
2444 sNC.pNext = pOuterNC;
danielk1977b3bce662005-01-29 08:32:43 +00002445
danielk1977b3bce662005-01-29 08:32:43 +00002446 /* Resolve names in the result set. */
2447 pEList = p->pEList;
2448 if( !pEList ) return SQLITE_ERROR;
2449 for(i=0; i<pEList->nExpr; i++){
2450 Expr *pX = pEList->a[i].pExpr;
2451 if( sqlite3ExprResolveNames(&sNC, pX) ){
2452 return SQLITE_ERROR;
2453 }
2454 }
2455
2456 /* If there are no aggregate functions in the result-set, and no GROUP BY
2457 ** expression, do not allow aggregates in any of the other expressions.
2458 */
2459 assert( !p->isAgg );
drh13449892005-09-07 21:22:45 +00002460 pGroupBy = p->pGroupBy;
2461 if( pGroupBy || sNC.hasAgg ){
danielk1977b3bce662005-01-29 08:32:43 +00002462 p->isAgg = 1;
2463 }else{
2464 sNC.allowAgg = 0;
2465 }
2466
2467 /* If a HAVING clause is present, then there must be a GROUP BY clause.
2468 */
drh13449892005-09-07 21:22:45 +00002469 if( p->pHaving && !pGroupBy ){
danielk1977b3bce662005-01-29 08:32:43 +00002470 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2471 return SQLITE_ERROR;
2472 }
2473
2474 /* Add the expression list to the name-context before parsing the
2475 ** other expressions in the SELECT statement. This is so that
2476 ** expressions in the WHERE clause (etc.) can refer to expressions by
2477 ** aliases in the result set.
2478 **
2479 ** Minor point: If this is the case, then the expression will be
2480 ** re-evaluated for each reference to it.
2481 */
2482 sNC.pEList = p->pEList;
2483 if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2484 sqlite3ExprResolveNames(&sNC, p->pHaving) ||
2485 processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
drh13449892005-09-07 21:22:45 +00002486 processOrderGroupBy(&sNC, pGroupBy, "GROUP")
danielk1977b3bce662005-01-29 08:32:43 +00002487 ){
2488 return SQLITE_ERROR;
2489 }
2490
drh13449892005-09-07 21:22:45 +00002491 /* Make sure the GROUP BY clause does not contain aggregate functions.
2492 */
2493 if( pGroupBy ){
2494 struct ExprList_item *pItem;
2495
2496 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
2497 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
2498 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
2499 "the GROUP BY clause");
2500 return SQLITE_ERROR;
2501 }
2502 }
2503 }
2504
danielk1977b3bce662005-01-29 08:32:43 +00002505 return SQLITE_OK;
2506}
2507
2508/*
drh13449892005-09-07 21:22:45 +00002509** Reset the aggregate accumulator.
2510**
2511** The aggregate accumulator is a set of memory cells that hold
2512** intermediate results while calculating an aggregate. This
2513** routine simply stores NULLs in all of those memory cells.
danielk1977b3bce662005-01-29 08:32:43 +00002514*/
drh13449892005-09-07 21:22:45 +00002515static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
2516 Vdbe *v = pParse->pVdbe;
2517 int i;
drhc99130f2005-09-11 11:56:27 +00002518 struct AggInfo_func *pFunc;
drh13449892005-09-07 21:22:45 +00002519 if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
2520 return;
2521 }
drh13449892005-09-07 21:22:45 +00002522 for(i=0; i<pAggInfo->nColumn; i++){
drhd654be82005-09-20 17:42:23 +00002523 sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
drh13449892005-09-07 21:22:45 +00002524 }
drhc99130f2005-09-11 11:56:27 +00002525 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
drhd654be82005-09-20 17:42:23 +00002526 sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
drhc99130f2005-09-11 11:56:27 +00002527 if( pFunc->iDistinct>=0 ){
2528 Expr *pE = pFunc->pExpr;
2529 if( pE->pList==0 || pE->pList->nExpr!=1 ){
2530 sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
2531 "by an expression");
2532 pFunc->iDistinct = -1;
2533 }else{
2534 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
2535 sqlite3VdbeOp3(v, OP_OpenVirtual, pFunc->iDistinct, 0,
2536 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2537 }
2538 }
drh13449892005-09-07 21:22:45 +00002539 }
danielk1977b3bce662005-01-29 08:32:43 +00002540}
2541
2542/*
drh13449892005-09-07 21:22:45 +00002543** Invoke the OP_AggFinalize opcode for every aggregate function
2544** in the AggInfo structure.
danielk1977b3bce662005-01-29 08:32:43 +00002545*/
drh13449892005-09-07 21:22:45 +00002546static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
2547 Vdbe *v = pParse->pVdbe;
2548 int i;
2549 struct AggInfo_func *pF;
2550 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
drha10a34b2005-09-07 22:09:48 +00002551 ExprList *pList = pF->pExpr->pList;
2552 sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
2553 (void*)pF->pFunc, P3_FUNCDEF);
drh13449892005-09-07 21:22:45 +00002554 }
danielk1977b3bce662005-01-29 08:32:43 +00002555}
drh13449892005-09-07 21:22:45 +00002556
2557/*
2558** Update the accumulator memory cells for an aggregate based on
2559** the current cursor position.
2560*/
2561static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
2562 Vdbe *v = pParse->pVdbe;
2563 int i;
2564 struct AggInfo_func *pF;
2565 struct AggInfo_col *pC;
drh13449892005-09-07 21:22:45 +00002566
2567 pAggInfo->directMode = 1;
2568 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
2569 int nArg;
drhc99130f2005-09-11 11:56:27 +00002570 int addrNext = 0;
drh13449892005-09-07 21:22:45 +00002571 ExprList *pList = pF->pExpr->pList;
2572 if( pList ){
2573 nArg = pList->nExpr;
2574 sqlite3ExprCodeExprList(pParse, pList);
2575 }else{
2576 nArg = 0;
2577 }
drhc99130f2005-09-11 11:56:27 +00002578 if( pF->iDistinct>=0 ){
2579 addrNext = sqlite3VdbeMakeLabel(v);
2580 assert( nArg==1 );
drh9d4673a2005-09-12 23:03:16 +00002581 codeDistinct(v, pF->iDistinct, addrNext, 1, 2);
drhc99130f2005-09-11 11:56:27 +00002582 }
drh13449892005-09-07 21:22:45 +00002583 if( pF->pFunc->needCollSeq ){
2584 CollSeq *pColl = 0;
2585 struct ExprList_item *pItem;
2586 int j;
2587 for(j=0, pItem=pList->a; !pColl && j<pList->nExpr; j++, pItem++){
2588 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
2589 }
2590 if( !pColl ){
2591 pColl = pParse->db->pDfltColl;
2592 }
2593 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2594 }
2595 sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
drhc99130f2005-09-11 11:56:27 +00002596 if( addrNext ){
2597 sqlite3VdbeResolveLabel(v, addrNext);
2598 }
drh13449892005-09-07 21:22:45 +00002599 }
drh13449892005-09-07 21:22:45 +00002600 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
drh5774b802005-09-07 22:48:16 +00002601 sqlite3ExprCode(pParse, pC->pExpr);
drh13449892005-09-07 21:22:45 +00002602 sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
2603 }
2604 pAggInfo->directMode = 0;
2605}
2606
2607
danielk1977b3bce662005-01-29 08:32:43 +00002608/*
drh9bb61fe2000-06-05 16:01:39 +00002609** Generate code for the given SELECT statement.
2610**
drhfef52082000-06-06 01:50:43 +00002611** The results are distributed in various ways depending on the
2612** value of eDest and iParm.
2613**
2614** eDest Value Result
2615** ------------ -------------------------------------------
2616** SRT_Callback Invoke the callback for each row of the result.
2617**
2618** SRT_Mem Store first result in memory cell iParm
2619**
danielk1977e014a832004-05-17 10:48:57 +00002620** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002621**
drh82c3d632000-06-06 21:56:07 +00002622** SRT_Union Store results as a key in a temporary table iParm
2623**
jplyon4b11c6d2004-01-19 04:57:53 +00002624** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002625**
2626** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002627**
drhe78e8282003-01-19 03:59:45 +00002628** The table above is incomplete. Additional eDist value have be added
2629** since this comment was written. See the selectInnerLoop() function for
2630** a complete listing of the allowed values of eDest and their meanings.
2631**
drh9bb61fe2000-06-05 16:01:39 +00002632** This routine returns the number of errors. If any errors are
2633** encountered, then an appropriate error message is left in
2634** pParse->zErrMsg.
2635**
2636** This routine does NOT free the Select structure passed in. The
2637** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002638**
2639** The pParent, parentTab, and *pParentAgg fields are filled in if this
2640** SELECT is a subquery. This routine may try to combine this SELECT
2641** with its parent to form a single flat query. In so doing, it might
2642** change the parent query from a non-aggregate to an aggregate query.
2643** For that reason, the pParentAgg flag is passed as a pointer, so it
2644** can be changed.
drhe78e8282003-01-19 03:59:45 +00002645**
2646** Example 1: The meaning of the pParent parameter.
2647**
2648** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2649** \ \_______ subquery _______/ /
2650** \ /
2651** \____________________ outer query ___________________/
2652**
2653** This routine is called for the outer query first. For that call,
2654** pParent will be NULL. During the processing of the outer query, this
2655** routine is called recursively to handle the subquery. For the recursive
2656** call, pParent will point to the outer query. Because the subquery is
2657** the second element in a three-way join, the parentTab parameter will
2658** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002659*/
danielk19774adee202004-05-08 08:23:19 +00002660int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002661 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002662 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002663 int eDest, /* How to dispose of the results */
2664 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002665 Select *pParent, /* Another SELECT for which this is a sub-query */
2666 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002667 int *pParentAgg, /* True if pParent uses aggregate functions */
danielk1977b3bce662005-01-29 08:32:43 +00002668 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002669){
drh13449892005-09-07 21:22:45 +00002670 int i, j; /* Loop counters */
2671 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
2672 Vdbe *v; /* The virtual machine under construction */
danielk1977b3bce662005-01-29 08:32:43 +00002673 int isAgg; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002674 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002675 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002676 Expr *pWhere; /* The WHERE clause. May be NULL */
2677 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002678 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2679 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002680 int isDistinct; /* True if the DISTINCT keyword is present */
2681 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002682 int rc = 1; /* Value to return from this function */
drh9d2985c2005-09-08 01:58:42 +00002683 int addrSortIndex; /* Address of an OP_OpenVirtual instruction */
drh13449892005-09-07 21:22:45 +00002684 AggInfo sAggInfo; /* Information used by aggregate queries */
drhec7429a2005-10-06 16:53:14 +00002685 int iEnd; /* Address of the end of the query */
drh9bb61fe2000-06-05 16:01:39 +00002686
danielk1977261919c2005-12-06 12:52:59 +00002687 if( sqlite3Tsd()->mallocFailed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002688 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drh13449892005-09-07 21:22:45 +00002689 memset(&sAggInfo, 0, sizeof(sAggInfo));
drhdaffd0e2001-04-11 14:28:42 +00002690
drhb7f91642004-10-31 02:22:47 +00002691#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +00002692 /* If there is are a sequence of queries, do the earlier ones first.
2693 */
2694 if( p->pPrior ){
drh0342b1f2005-09-01 03:07:44 +00002695 if( p->pRightmost==0 ){
2696 Select *pLoop;
2697 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
2698 pLoop->pRightmost = p;
2699 }
2700 }
danielk197784ac9d02004-05-18 09:58:06 +00002701 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002702 }
drhb7f91642004-10-31 02:22:47 +00002703#endif
drh82c3d632000-06-06 21:56:07 +00002704
danielk1977b3bce662005-01-29 08:32:43 +00002705 pOrderBy = p->pOrderBy;
drh13449892005-09-07 21:22:45 +00002706 if( IgnorableOrderby(eDest) ){
danielk1977b3bce662005-01-29 08:32:43 +00002707 p->pOrderBy = 0;
2708 }
2709 if( sqlite3SelectResolve(pParse, p, 0) ){
2710 goto select_end;
2711 }
2712 p->pOrderBy = pOrderBy;
2713
drh82c3d632000-06-06 21:56:07 +00002714 /* Make local copies of the parameters for this query.
2715 */
drh9bb61fe2000-06-05 16:01:39 +00002716 pTabList = p->pSrc;
2717 pWhere = p->pWhere;
drh22827922000-06-06 17:27:05 +00002718 pGroupBy = p->pGroupBy;
2719 pHaving = p->pHaving;
danielk1977b3bce662005-01-29 08:32:43 +00002720 isAgg = p->isAgg;
drh19a775c2000-06-05 18:54:46 +00002721 isDistinct = p->isDistinct;
danielk1977b3bce662005-01-29 08:32:43 +00002722 pEList = p->pEList;
2723 if( pEList==0 ) goto select_end;
drh9bb61fe2000-06-05 16:01:39 +00002724
2725 /*
2726 ** Do not even attempt to generate any code if we have already seen
2727 ** errors before this routine starts.
2728 */
drh1d83f052002-02-17 00:30:36 +00002729 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002730
drh22827922000-06-06 17:27:05 +00002731 /* If writing to memory or generating a set
2732 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002733 */
danielk197793758c82005-01-21 08:13:14 +00002734#ifndef SQLITE_OMIT_SUBQUERY
drhfef52082000-06-06 01:50:43 +00002735 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002736 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002737 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002738 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002739 }
danielk197793758c82005-01-21 08:13:14 +00002740#endif
drh19a775c2000-06-05 18:54:46 +00002741
drhc926afb2002-06-20 03:38:26 +00002742 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002743 */
drh13449892005-09-07 21:22:45 +00002744 if( IgnorableOrderby(eDest) ){
2745 pOrderBy = 0;
drh22827922000-06-06 17:27:05 +00002746 }
2747
drhd820cb12002-02-18 03:21:45 +00002748 /* Begin generating code.
2749 */
danielk19774adee202004-05-08 08:23:19 +00002750 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002751 if( v==0 ) goto select_end;
2752
drhe78e8282003-01-19 03:59:45 +00002753 /* Identify column names if we will be using them in a callback. This
2754 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002755 */
2756 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002757 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002758 }
2759
drhd820cb12002-02-18 03:21:45 +00002760 /* Generate code for all sub-queries in the FROM clause
2761 */
drh51522cd2005-01-20 13:36:19 +00002762#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
drhad3cab52002-05-24 02:04:32 +00002763 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002764 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002765 int needRestoreContext;
drh13449892005-09-07 21:22:45 +00002766 struct SrcList_item *pItem = &pTabList->a[i];
drhc31c2eb2003-05-02 16:04:17 +00002767
drh13449892005-09-07 21:22:45 +00002768 if( pItem->pSelect==0 ) continue;
2769 if( pItem->zName!=0 ){
drh5cf590c2003-04-24 01:45:04 +00002770 zSavedAuthContext = pParse->zAuthContext;
drh13449892005-09-07 21:22:45 +00002771 pParse->zAuthContext = pItem->zName;
drhc31c2eb2003-05-02 16:04:17 +00002772 needRestoreContext = 1;
2773 }else{
2774 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002775 }
drh9d2985c2005-09-08 01:58:42 +00002776 sqlite3Select(pParse, pItem->pSelect, SRT_VirtualTab,
drh13449892005-09-07 21:22:45 +00002777 pItem->iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002778 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002779 pParse->zAuthContext = zSavedAuthContext;
2780 }
drh1b2e0322002-03-03 02:49:51 +00002781 pTabList = p->pSrc;
2782 pWhere = p->pWhere;
drh13449892005-09-07 21:22:45 +00002783 if( !IgnorableOrderby(eDest) ){
drhacd4c692002-03-07 02:02:51 +00002784 pOrderBy = p->pOrderBy;
2785 }
drh1b2e0322002-03-03 02:49:51 +00002786 pGroupBy = p->pGroupBy;
2787 pHaving = p->pHaving;
2788 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002789 }
drh51522cd2005-01-20 13:36:19 +00002790#endif
drhd820cb12002-02-18 03:21:45 +00002791
drh6e175292004-03-13 14:00:36 +00002792 /* Check for the special case of a min() or max() function by itself
2793 ** in the result set.
2794 */
2795 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2796 rc = 0;
2797 goto select_end;
2798 }
2799
drh832508b2002-03-02 17:04:07 +00002800 /* Check to see if this is a subquery that can be "flattened" into its parent.
2801 ** If flattening is a possiblity, do so and return immediately.
2802 */
drhb7f91642004-10-31 02:22:47 +00002803#ifndef SQLITE_OMIT_VIEW
drh1b2e0322002-03-03 02:49:51 +00002804 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002805 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002806 if( isAgg ) *pParentAgg = 1;
danielk1977b3bce662005-01-29 08:32:43 +00002807 goto select_end;
drh832508b2002-03-02 17:04:07 +00002808 }
drhb7f91642004-10-31 02:22:47 +00002809#endif
drh832508b2002-03-02 17:04:07 +00002810
danielk19777cedc8d2004-06-10 10:50:08 +00002811 /* If there is an ORDER BY clause, resolve any collation sequences
drh9d2985c2005-09-08 01:58:42 +00002812 ** names that have been explicitly specified and create a sorting index.
2813 **
2814 ** This sorting index might end up being unused if the data can be
2815 ** extracted in pre-sorted order. If that is the case, then the
2816 ** OP_OpenVirtual instruction will be changed to an OP_Noop once
2817 ** we figure out that the sorting index is not needed. The addrSortIndex
2818 ** variable is used to facilitate that change.
danielk19777cedc8d2004-06-10 10:50:08 +00002819 */
2820 if( pOrderBy ){
drh5d9a4af2005-08-30 00:54:01 +00002821 struct ExprList_item *pTerm;
drh0342b1f2005-09-01 03:07:44 +00002822 KeyInfo *pKeyInfo;
drh5d9a4af2005-08-30 00:54:01 +00002823 for(i=0, pTerm=pOrderBy->a; i<pOrderBy->nExpr; i++, pTerm++){
2824 if( pTerm->zName ){
2825 pTerm->pExpr->pColl = sqlite3LocateCollSeq(pParse, pTerm->zName, -1);
danielk19777cedc8d2004-06-10 10:50:08 +00002826 }
2827 }
2828 if( pParse->nErr ){
2829 goto select_end;
2830 }
drh0342b1f2005-09-01 03:07:44 +00002831 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
drh9d2985c2005-09-08 01:58:42 +00002832 pOrderBy->iECursor = pParse->nTab++;
2833 p->addrOpenVirt[2] = addrSortIndex =
2834 sqlite3VdbeOp3(v, OP_OpenVirtual, pOrderBy->iECursor, pOrderBy->nExpr+2,
drh0342b1f2005-09-01 03:07:44 +00002835 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drh9d2985c2005-09-08 01:58:42 +00002836 }else{
2837 addrSortIndex = -1;
danielk19777cedc8d2004-06-10 10:50:08 +00002838 }
2839
drh7b58dae2003-07-20 01:16:46 +00002840 /* Set the limiter.
2841 */
drhec7429a2005-10-06 16:53:14 +00002842 iEnd = sqlite3VdbeMakeLabel(v);
2843 computeLimitRegisters(pParse, p, iEnd);
drh7b58dae2003-07-20 01:16:46 +00002844
drh2d0794e2002-03-03 03:03:52 +00002845 /* If the output is destined for a temporary table, open that table.
2846 */
drh9d2985c2005-09-08 01:58:42 +00002847 if( eDest==SRT_VirtualTab ){
drh0342b1f2005-09-01 03:07:44 +00002848 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002849 }
2850
drhdece1a82005-08-31 18:20:00 +00002851 /* Open a virtual index to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002852 */
drh19a775c2000-06-05 18:54:46 +00002853 if( isDistinct ){
drh0342b1f2005-09-01 03:07:44 +00002854 KeyInfo *pKeyInfo;
drh832508b2002-03-02 17:04:07 +00002855 distinct = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00002856 pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
2857 sqlite3VdbeOp3(v, OP_OpenVirtual, distinct, 0,
2858 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drh832508b2002-03-02 17:04:07 +00002859 }else{
2860 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002861 }
drh832508b2002-03-02 17:04:07 +00002862
drh13449892005-09-07 21:22:45 +00002863 /* Aggregate and non-aggregate queries are handled differently */
2864 if( !isAgg && pGroupBy==0 ){
2865 /* This case is for non-aggregate queries
2866 ** Begin the database scan
2867 */
2868 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
2869 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002870
drh9d2985c2005-09-08 01:58:42 +00002871 /* If sorting index that was created by a prior OP_OpenVirtual
2872 ** instruction ended up not being needed, then change the OP_OpenVirtual
2873 ** into an OP_Noop.
2874 */
2875 if( addrSortIndex>=0 && pOrderBy==0 ){
2876 uncreateSortingIndex(pParse, addrSortIndex);
2877 p->addrOpenVirt[2] = -1;
2878 }
2879
drh13449892005-09-07 21:22:45 +00002880 /* Use the standard inner loop
2881 */
drhdf199a22002-06-14 22:38:41 +00002882 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002883 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002884 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002885 }
drhefb72512000-05-31 20:00:52 +00002886
drh13449892005-09-07 21:22:45 +00002887 /* End the database scan loop.
2888 */
2889 sqlite3WhereEnd(pWInfo);
2890 }else{
2891 /* This is the processing for aggregate queries */
2892 NameContext sNC; /* Name context for processing aggregate information */
2893 int iAMem; /* First Mem address for storing current GROUP BY */
2894 int iBMem; /* First Mem address for previous GROUP BY */
2895 int iUseFlag; /* Mem address holding flag indicating that at least
2896 ** one row of the input to the aggregator has been
2897 ** processed */
2898 int iAbortFlag; /* Mem address which causes query abort if positive */
2899 int groupBySort; /* Rows come from source in GROUP BY order */
drhcce7d172000-05-31 15:34:51 +00002900
drhcce7d172000-05-31 15:34:51 +00002901
drh13449892005-09-07 21:22:45 +00002902 /* The following variables hold addresses or labels for parts of the
2903 ** virtual machine program we are putting together */
2904 int addrOutputRow; /* Start of subroutine that outputs a result row */
2905 int addrSetAbort; /* Set the abort flag and return */
2906 int addrInitializeLoop; /* Start of code that initializes the input loop */
2907 int addrTopOfLoop; /* Top of the input loop */
2908 int addrGroupByChange; /* Code that runs when any GROUP BY term changes */
2909 int addrProcessRow; /* Code to process a single input row */
2910 int addrEnd; /* End of all processing */
2911 int addrSortingIdx; /* The OP_OpenVirtual for the sorting index */
drhe3133822005-09-20 13:11:59 +00002912 int addrReset; /* Subroutine for resetting the accumulator */
drh13449892005-09-07 21:22:45 +00002913
2914 addrEnd = sqlite3VdbeMakeLabel(v);
2915
2916 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
2917 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
2918 ** SELECT statement.
2919 */
2920 memset(&sNC, 0, sizeof(sNC));
2921 sNC.pParse = pParse;
2922 sNC.pSrcList = pTabList;
2923 sNC.pAggInfo = &sAggInfo;
2924 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
drh9d2985c2005-09-08 01:58:42 +00002925 sAggInfo.pGroupBy = pGroupBy;
drh13449892005-09-07 21:22:45 +00002926 if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
drh1d83f052002-02-17 00:30:36 +00002927 goto select_end;
drh22827922000-06-06 17:27:05 +00002928 }
drh13449892005-09-07 21:22:45 +00002929 if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
2930 goto select_end;
2931 }
2932 if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
2933 goto select_end;
2934 }
2935 sAggInfo.nAccumulator = sAggInfo.nColumn;
2936 for(i=0; i<sAggInfo.nFunc; i++){
2937 if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
2938 goto select_end;
2939 }
2940 }
danielk1977261919c2005-12-06 12:52:59 +00002941 if( sqlite3Tsd()->mallocFailed ) goto select_end;
drh13449892005-09-07 21:22:45 +00002942
2943 /* Processing for aggregates with GROUP BY is very different and
2944 ** much more complex tha aggregates without a GROUP BY.
2945 */
2946 if( pGroupBy ){
2947 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
2948
2949 /* Create labels that we will be needing
2950 */
2951
2952 addrInitializeLoop = sqlite3VdbeMakeLabel(v);
2953 addrGroupByChange = sqlite3VdbeMakeLabel(v);
2954 addrProcessRow = sqlite3VdbeMakeLabel(v);
2955
2956 /* If there is a GROUP BY clause we might need a sorting index to
2957 ** implement it. Allocate that sorting index now. If it turns out
2958 ** that we do not need it after all, the OpenVirtual instruction
2959 ** will be converted into a Noop.
2960 */
2961 sAggInfo.sortingIdx = pParse->nTab++;
2962 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
2963 addrSortingIdx =
2964 sqlite3VdbeOp3(v, OP_OpenVirtual, sAggInfo.sortingIdx,
2965 sAggInfo.nSortingColumn,
2966 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2967
2968 /* Initialize memory locations used by GROUP BY aggregate processing
2969 */
2970 iUseFlag = pParse->nMem++;
2971 iAbortFlag = pParse->nMem++;
2972 iAMem = pParse->nMem;
2973 pParse->nMem += pGroupBy->nExpr;
2974 iBMem = pParse->nMem;
2975 pParse->nMem += pGroupBy->nExpr;
drhd654be82005-09-20 17:42:23 +00002976 sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
drhde29e3e2005-09-20 18:13:23 +00002977 VdbeComment((v, "# clear abort flag"));
drhd654be82005-09-20 17:42:23 +00002978 sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
drhde29e3e2005-09-20 18:13:23 +00002979 VdbeComment((v, "# indicate accumulator empty"));
drh13449892005-09-07 21:22:45 +00002980 sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
2981
2982 /* Generate a subroutine that outputs a single row of the result
2983 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
2984 ** is less than or equal to zero, the subroutine is a no-op. If
2985 ** the processing calls for the query to abort, this subroutine
2986 ** increments the iAbortFlag memory location before returning in
2987 ** order to signal the caller to abort.
2988 */
2989 addrSetAbort = sqlite3VdbeCurrentAddr(v);
drhde29e3e2005-09-20 18:13:23 +00002990 sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag);
2991 VdbeComment((v, "# set abort flag"));
drh13449892005-09-07 21:22:45 +00002992 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2993 addrOutputRow = sqlite3VdbeCurrentAddr(v);
2994 sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
drhde29e3e2005-09-20 18:13:23 +00002995 VdbeComment((v, "# Groupby result generator entry point"));
drh13449892005-09-07 21:22:45 +00002996 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2997 finalizeAggFunctions(pParse, &sAggInfo);
2998 if( pHaving ){
2999 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
3000 }
3001 rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
3002 distinct, eDest, iParm,
3003 addrOutputRow+1, addrSetAbort, aff);
3004 if( rc ){
3005 goto select_end;
3006 }
3007 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
drhde29e3e2005-09-20 18:13:23 +00003008 VdbeComment((v, "# end groupby result generator"));
drh13449892005-09-07 21:22:45 +00003009
drhe3133822005-09-20 13:11:59 +00003010 /* Generate a subroutine that will reset the group-by accumulator
3011 */
3012 addrReset = sqlite3VdbeCurrentAddr(v);
3013 resetAccumulator(pParse, &sAggInfo);
3014 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
3015
drh13449892005-09-07 21:22:45 +00003016 /* Begin a loop that will extract all source rows in GROUP BY order.
3017 ** This might involve two separate loops with an OP_Sort in between, or
3018 ** it might be a single loop that uses an index to extract information
3019 ** in the right order to begin with.
3020 */
3021 sqlite3VdbeResolveLabel(v, addrInitializeLoop);
drhe3133822005-09-20 13:11:59 +00003022 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
drh13449892005-09-07 21:22:45 +00003023 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
drh5360ad32005-09-08 00:13:27 +00003024 if( pWInfo==0 ) goto select_end;
drh13449892005-09-07 21:22:45 +00003025 if( pGroupBy==0 ){
3026 /* The optimizer is able to deliver rows in group by order so
3027 ** we do not have to sort. The OP_OpenVirtual table will be
3028 ** cancelled later because we still need to use the pKeyInfo
3029 */
3030 pGroupBy = p->pGroupBy;
3031 groupBySort = 0;
3032 }else{
3033 /* Rows are coming out in undetermined order. We have to push
3034 ** each row into a sorting index, terminate the first loop,
3035 ** then loop over the sorting index in order to get the output
3036 ** in sorted order
3037 */
3038 groupBySort = 1;
3039 sqlite3ExprCodeExprList(pParse, pGroupBy);
3040 sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
3041 j = pGroupBy->nExpr+1;
3042 for(i=0; i<sAggInfo.nColumn; i++){
3043 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
3044 if( pCol->iSorterColumn<j ) continue;
3045 if( pCol->iColumn<0 ){
3046 sqlite3VdbeAddOp(v, OP_Rowid, pCol->iTable, 0);
3047 }else{
3048 sqlite3VdbeAddOp(v, OP_Column, pCol->iTable, pCol->iColumn);
3049 }
3050 j++;
3051 }
3052 sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
3053 sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
3054 sqlite3WhereEnd(pWInfo);
drh97571952005-09-08 12:57:28 +00003055 sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
drhde29e3e2005-09-20 18:13:23 +00003056 VdbeComment((v, "# GROUP BY sort"));
drh13449892005-09-07 21:22:45 +00003057 sAggInfo.useSortingIdx = 1;
3058 }
3059
3060 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
3061 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
3062 ** Then compare the current GROUP BY terms against the GROUP BY terms
3063 ** from the previous row currently stored in a0, a1, a2...
3064 */
3065 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
3066 for(j=0; j<pGroupBy->nExpr; j++){
3067 if( groupBySort ){
3068 sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
3069 }else{
3070 sAggInfo.directMode = 1;
3071 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
3072 }
3073 sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
3074 }
3075 for(j=pGroupBy->nExpr-1; j>=0; j--){
3076 if( j<pGroupBy->nExpr-1 ){
3077 sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
3078 }
3079 sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
3080 if( j==0 ){
drhe3133822005-09-20 13:11:59 +00003081 sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
drh13449892005-09-07 21:22:45 +00003082 }else{
drh4f686232005-09-20 13:55:18 +00003083 sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
drh13449892005-09-07 21:22:45 +00003084 }
3085 sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
3086 }
3087
3088 /* Generate code that runs whenever the GROUP BY changes.
3089 ** Change in the GROUP BY are detected by the previous code
3090 ** block. If there were no changes, this block is skipped.
3091 **
3092 ** This code copies current group by terms in b0,b1,b2,...
3093 ** over to a0,a1,a2. It then calls the output subroutine
3094 ** and resets the aggregate accumulator registers in preparation
3095 ** for the next GROUP BY batch.
3096 */
3097 sqlite3VdbeResolveLabel(v, addrGroupByChange);
3098 for(j=0; j<pGroupBy->nExpr; j++){
drhd654be82005-09-20 17:42:23 +00003099 sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
drh13449892005-09-07 21:22:45 +00003100 }
3101 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
drhde29e3e2005-09-20 18:13:23 +00003102 VdbeComment((v, "# output one row"));
drh13449892005-09-07 21:22:45 +00003103 sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
drhde29e3e2005-09-20 18:13:23 +00003104 VdbeComment((v, "# check abort flag"));
drhe3133822005-09-20 13:11:59 +00003105 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
drhde29e3e2005-09-20 18:13:23 +00003106 VdbeComment((v, "# reset accumulator"));
drh13449892005-09-07 21:22:45 +00003107
3108 /* Update the aggregate accumulators based on the content of
3109 ** the current row
3110 */
3111 sqlite3VdbeResolveLabel(v, addrProcessRow);
3112 updateAccumulator(pParse, &sAggInfo);
drhde29e3e2005-09-20 18:13:23 +00003113 sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag);
3114 VdbeComment((v, "# indicate data in accumulator"));
drh13449892005-09-07 21:22:45 +00003115
3116 /* End of the loop
3117 */
3118 if( groupBySort ){
3119 sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
3120 }else{
3121 sqlite3WhereEnd(pWInfo);
3122 uncreateSortingIndex(pParse, addrSortingIdx);
3123 }
3124
3125 /* Output the final row of result
3126 */
3127 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
drhde29e3e2005-09-20 18:13:23 +00003128 VdbeComment((v, "# output final row"));
drh13449892005-09-07 21:22:45 +00003129
3130 } /* endif pGroupBy */
3131 else {
3132 /* This case runs if the aggregate has no GROUP BY clause. The
3133 ** processing is much simpler since there is only a single row
3134 ** of output.
3135 */
3136 resetAccumulator(pParse, &sAggInfo);
3137 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
drh5360ad32005-09-08 00:13:27 +00003138 if( pWInfo==0 ) goto select_end;
drh13449892005-09-07 21:22:45 +00003139 updateAccumulator(pParse, &sAggInfo);
3140 sqlite3WhereEnd(pWInfo);
3141 finalizeAggFunctions(pParse, &sAggInfo);
3142 pOrderBy = 0;
drh5774b802005-09-07 22:48:16 +00003143 if( pHaving ){
3144 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
3145 }
drh13449892005-09-07 21:22:45 +00003146 selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
3147 eDest, iParm, addrEnd, addrEnd, aff);
3148 }
3149 sqlite3VdbeResolveLabel(v, addrEnd);
3150
3151 } /* endif aggregate query */
drh22827922000-06-06 17:27:05 +00003152
drhcce7d172000-05-31 15:34:51 +00003153 /* If there is an ORDER BY clause, then we need to sort the results
3154 ** and send them to the callback one by one.
3155 */
3156 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00003157 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00003158 }
drh6a535342001-10-19 16:44:56 +00003159
danielk197793758c82005-01-21 08:13:14 +00003160#ifndef SQLITE_OMIT_SUBQUERY
drhf620b4e2004-02-09 14:37:50 +00003161 /* If this was a subquery, we have now converted the subquery into a
3162 ** temporary table. So delete the subquery structure from the parent
3163 ** to prevent this subquery from being evaluated again and to force the
3164 ** the use of the temporary table.
3165 */
3166 if( pParent ){
3167 assert( pParent->pSrc->nSrc>parentTab );
3168 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00003169 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00003170 pParent->pSrc->a[parentTab].pSelect = 0;
3171 }
danielk197793758c82005-01-21 08:13:14 +00003172#endif
drhf620b4e2004-02-09 14:37:50 +00003173
drhec7429a2005-10-06 16:53:14 +00003174 /* Jump here to skip this query
3175 */
3176 sqlite3VdbeResolveLabel(v, iEnd);
3177
drh1d83f052002-02-17 00:30:36 +00003178 /* The SELECT was successfully coded. Set the return code to 0
3179 ** to indicate no errors.
3180 */
3181 rc = 0;
3182
3183 /* Control jumps to here if an error is encountered above, or upon
3184 ** successful coding of the SELECT.
3185 */
3186select_end:
drh13449892005-09-07 21:22:45 +00003187 sqliteFree(sAggInfo.aCol);
3188 sqliteFree(sAggInfo.aFunc);
drh1d83f052002-02-17 00:30:36 +00003189 return rc;
drhcce7d172000-05-31 15:34:51 +00003190}