blob: 3ebcc2f301d95804d99ba0c2a8907a2479784a2a [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**
drhac839632006-01-21 22:19:54 +000015** $Id: select.c,v 1.297 2006/01/21 22:19:55 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);
drh3a129242006-01-09 00:09:01 +0000390 addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, 0);
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;
danielk197714db2662006-01-09 16:12:04 +0000653 pInfo->enc = ENC(db);
drhdece1a82005-08-31 18:20:00 +0000654 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 );
danielk19779e128002006-01-18 16:51:35 +0000875 if( pParse->colNamesSet || v==0 || sqlite3MallocFailed() ) 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;
danielk1977b3bf5562006-01-10 17:58:23 +0000981 CollSeq *pColl;
drh79d5f632005-01-18 17:20:10 +0000982 int cnt;
danielk1977b3bce662005-01-29 08:32:43 +0000983 NameContext sNC;
drh79d5f632005-01-18 17:20:10 +0000984
985 /* Get an appropriate name for the column
986 */
987 p = pEList->a[i].pExpr;
drh290c1942004-08-21 17:54:45 +0000988 assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
drh91bb0ee2004-09-01 03:06:34 +0000989 if( (zName = pEList->a[i].zName)!=0 ){
drh79d5f632005-01-18 17:20:10 +0000990 /* If the column contains an "AS <name>" phrase, use <name> as the name */
drh91bb0ee2004-09-01 03:06:34 +0000991 zName = sqliteStrDup(zName);
danielk1977517eb642004-06-07 10:00:31 +0000992 }else if( p->op==TK_DOT
drh79d5f632005-01-18 17:20:10 +0000993 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
994 /* For columns of the from A.B use B as the name */
drh91bb0ee2004-09-01 03:06:34 +0000995 zName = sqlite3MPrintf("%T", &pR->token);
drhb733d032004-01-24 20:18:12 +0000996 }else if( p->span.z && p->span.z[0] ){
drh79d5f632005-01-18 17:20:10 +0000997 /* Use the original text of the column expression as its name */
drh91bb0ee2004-09-01 03:06:34 +0000998 zName = sqlite3MPrintf("%T", &p->span);
drh22f70c32002-02-18 01:17:00 +0000999 }else{
drh79d5f632005-01-18 17:20:10 +00001000 /* If all else fails, make up a name */
drh91bb0ee2004-09-01 03:06:34 +00001001 zName = sqlite3MPrintf("column%d", i+1);
drh22f70c32002-02-18 01:17:00 +00001002 }
drh91bb0ee2004-09-01 03:06:34 +00001003 sqlite3Dequote(zName);
danielk19779e128002006-01-18 16:51:35 +00001004 if( sqlite3MallocFailed() ){
drhdd5b2fa2005-03-28 03:39:55 +00001005 sqliteFree(zName);
1006 sqlite3DeleteTable(0, pTab);
1007 return 0;
1008 }
drh79d5f632005-01-18 17:20:10 +00001009
1010 /* Make sure the column name is unique. If the name is not unique,
1011 ** append a integer to the name so that it becomes unique.
1012 */
1013 zBasename = zName;
1014 for(j=cnt=0; j<i; j++){
1015 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
1016 zName = sqlite3MPrintf("%s:%d", zBasename, ++cnt);
1017 j = -1;
drhdd5b2fa2005-03-28 03:39:55 +00001018 if( zName==0 ) break;
drh79d5f632005-01-18 17:20:10 +00001019 }
1020 }
1021 if( zBasename!=zName ){
1022 sqliteFree(zBasename);
1023 }
drh91bb0ee2004-09-01 03:06:34 +00001024 pCol->zName = zName;
danielk1977517eb642004-06-07 10:00:31 +00001025
drh79d5f632005-01-18 17:20:10 +00001026 /* Get the typename, type affinity, and collating sequence for the
1027 ** column.
1028 */
drhc43e8be2005-05-16 22:37:54 +00001029 memset(&sNC, 0, sizeof(sNC));
danielk1977b3bce662005-01-29 08:32:43 +00001030 sNC.pSrcList = pSelect->pSrc;
1031 zType = sqliteStrDup(columnType(&sNC, p));
drh290c1942004-08-21 17:54:45 +00001032 pCol->zType = zType;
danielk1977c60e9b82005-01-31 12:42:29 +00001033 pCol->affinity = sqlite3ExprAffinity(p);
danielk1977b3bf5562006-01-10 17:58:23 +00001034 pColl = sqlite3ExprCollSeq(pParse, p);
1035 if( pColl ){
danielk1977e7259292006-01-13 06:33:23 +00001036 pCol->zColl = sqliteStrDup(pColl->zName);
danielk19770202b292004-06-09 09:55:16 +00001037 }
drh22f70c32002-02-18 01:17:00 +00001038 }
1039 pTab->iPKey = -1;
1040 return pTab;
1041}
1042
1043/*
drh9b3187e2005-01-18 14:45:47 +00001044** Prepare a SELECT statement for processing by doing the following
1045** things:
drhd8bc7082000-06-07 23:51:50 +00001046**
drh9b3187e2005-01-18 14:45:47 +00001047** (1) Make sure VDBE cursor numbers have been assigned to every
1048** element of the FROM clause.
1049**
1050** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
1051** defines FROM clause. When views appear in the FROM clause,
drh63eb5f22003-04-29 16:20:44 +00001052** fill pTabList->a[].pSelect with a copy of the SELECT statement
1053** that implements the view. A copy is made of the view's SELECT
1054** statement so that we can freely modify or delete that statement
1055** without worrying about messing up the presistent representation
1056** of the view.
drhd8bc7082000-06-07 23:51:50 +00001057**
drh9b3187e2005-01-18 14:45:47 +00001058** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
drhad2d8302002-05-24 20:31:36 +00001059** on joins and the ON and USING clause of joins.
1060**
drh9b3187e2005-01-18 14:45:47 +00001061** (4) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +00001062** for instances of the "*" operator or the TABLE.* operator.
1063** If found, expand each "*" to be every column in every table
1064** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +00001065**
1066** Return 0 on success. If there are problems, leave an error message
1067** in pParse and return non-zero.
1068*/
drh9b3187e2005-01-18 14:45:47 +00001069static int prepSelectStmt(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +00001070 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +00001071 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +00001072 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +00001073 Table *pTab;
drh290c1942004-08-21 17:54:45 +00001074 struct SrcList_item *pFrom;
drhdaffd0e2001-04-11 14:28:42 +00001075
danielk19779e128002006-01-18 16:51:35 +00001076 if( p==0 || p->pSrc==0 || sqlite3MallocFailed() ){
drh6f7adc82006-01-11 21:41:20 +00001077 return 1;
1078 }
drhdaffd0e2001-04-11 14:28:42 +00001079 pTabList = p->pSrc;
1080 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +00001081
drh9b3187e2005-01-18 14:45:47 +00001082 /* Make sure cursor numbers have been assigned to all entries in
1083 ** the FROM clause of the SELECT statement.
1084 */
1085 sqlite3SrcListAssignCursors(pParse, p->pSrc);
1086
1087 /* Look up every table named in the FROM clause of the select. If
1088 ** an entry of the FROM clause is a subquery instead of a table or view,
1089 ** then create a transient table structure to describe the subquery.
drhd8bc7082000-06-07 23:51:50 +00001090 */
drh290c1942004-08-21 17:54:45 +00001091 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
drh9b3187e2005-01-18 14:45:47 +00001092 if( pFrom->pTab!=0 ){
1093 /* This statement has already been prepared. There is no need
1094 ** to go further. */
1095 assert( i==0 );
drhd8bc7082000-06-07 23:51:50 +00001096 return 0;
1097 }
drh290c1942004-08-21 17:54:45 +00001098 if( pFrom->zName==0 ){
danielk197793758c82005-01-21 08:13:14 +00001099#ifndef SQLITE_OMIT_SUBQUERY
drh22f70c32002-02-18 01:17:00 +00001100 /* A sub-query in the FROM clause of a SELECT */
drh290c1942004-08-21 17:54:45 +00001101 assert( pFrom->pSelect!=0 );
1102 if( pFrom->zAlias==0 ){
drh91bb0ee2004-09-01 03:06:34 +00001103 pFrom->zAlias =
1104 sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
drhad2d8302002-05-24 20:31:36 +00001105 }
drhed8a3bb2005-06-06 21:19:56 +00001106 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001107 pFrom->pTab = pTab =
1108 sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
drh22f70c32002-02-18 01:17:00 +00001109 if( pTab==0 ){
1110 return 1;
1111 }
drh5cf590c2003-04-24 01:45:04 +00001112 /* The isTransient flag indicates that the Table structure has been
1113 ** dynamically allocated and may be freed at any time. In other words,
1114 ** pTab is not pointing to a persistent table structure that defines
1115 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +00001116 pTab->isTransient = 1;
danielk197793758c82005-01-21 08:13:14 +00001117#endif
drh22f70c32002-02-18 01:17:00 +00001118 }else{
drha76b5df2002-02-23 02:32:10 +00001119 /* An ordinary table or view name in the FROM clause */
drhed8a3bb2005-06-06 21:19:56 +00001120 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001121 pFrom->pTab = pTab =
1122 sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
drha76b5df2002-02-23 02:32:10 +00001123 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +00001124 return 1;
1125 }
drhed8a3bb2005-06-06 21:19:56 +00001126 pTab->nRef++;
danielk197793758c82005-01-21 08:13:14 +00001127#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00001128 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +00001129 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +00001130 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +00001131 return 1;
1132 }
drh290c1942004-08-21 17:54:45 +00001133 /* If pFrom->pSelect!=0 it means we are dealing with a
drh63eb5f22003-04-29 16:20:44 +00001134 ** view within a view. The SELECT structure has already been
1135 ** copied by the outer view so we can skip the copy step here
1136 ** in the inner view.
1137 */
drh290c1942004-08-21 17:54:45 +00001138 if( pFrom->pSelect==0 ){
1139 pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +00001140 }
drha76b5df2002-02-23 02:32:10 +00001141 }
danielk197793758c82005-01-21 08:13:14 +00001142#endif
drhd8bc7082000-06-07 23:51:50 +00001143 }
1144 }
1145
drhad2d8302002-05-24 20:31:36 +00001146 /* Process NATURAL keywords, and ON and USING clauses of joins.
1147 */
1148 if( sqliteProcessJoin(pParse, p) ) return 1;
1149
drh7c917d12001-12-16 20:05:05 +00001150 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +00001151 ** all columns in all tables. And for every TABLE.* insert the names
1152 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +00001153 ** with the TK_ALL operator for each "*" that it found in the column list.
1154 ** The following code just has to locate the TK_ALL expressions and expand
1155 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +00001156 **
1157 ** The first loop just checks to see if there are any "*" operators
1158 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +00001159 */
drh7c917d12001-12-16 20:05:05 +00001160 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001161 Expr *pE = pEList->a[k].pExpr;
1162 if( pE->op==TK_ALL ) break;
1163 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
1164 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +00001165 }
drh54473222002-04-04 02:10:55 +00001166 rc = 0;
drh7c917d12001-12-16 20:05:05 +00001167 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +00001168 /*
1169 ** If we get here it means the result set contains one or more "*"
1170 ** operators that need to be expanded. Loop through each expression
1171 ** in the result set and expand them one by one.
1172 */
drh7c917d12001-12-16 20:05:05 +00001173 struct ExprList_item *a = pEList->a;
1174 ExprList *pNew = 0;
drhd70dc522005-06-06 16:34:33 +00001175 int flags = pParse->db->flags;
1176 int longNames = (flags & SQLITE_FullColNames)!=0 &&
1177 (flags & SQLITE_ShortColNames)==0;
1178
drh7c917d12001-12-16 20:05:05 +00001179 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001180 Expr *pE = a[k].pExpr;
1181 if( pE->op!=TK_ALL &&
1182 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
1183 /* This particular expression does not need to be expanded.
1184 */
danielk19774adee202004-05-08 08:23:19 +00001185 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
danielk1977261919c2005-12-06 12:52:59 +00001186 if( pNew ){
1187 pNew->a[pNew->nExpr-1].zName = a[k].zName;
1188 }else{
1189 rc = 1;
1190 }
drh7c917d12001-12-16 20:05:05 +00001191 a[k].pExpr = 0;
1192 a[k].zName = 0;
1193 }else{
drh54473222002-04-04 02:10:55 +00001194 /* This expression is a "*" or a "TABLE.*" and needs to be
1195 ** expanded. */
1196 int tableSeen = 0; /* Set to 1 when TABLE matches */
drhcf55b7a2004-07-20 01:45:19 +00001197 char *zTName; /* text of name of TABLE */
drh54473222002-04-04 02:10:55 +00001198 if( pE->op==TK_DOT && pE->pLeft ){
drhcf55b7a2004-07-20 01:45:19 +00001199 zTName = sqlite3NameFromToken(&pE->pLeft->token);
drh54473222002-04-04 02:10:55 +00001200 }else{
drhcf55b7a2004-07-20 01:45:19 +00001201 zTName = 0;
drh54473222002-04-04 02:10:55 +00001202 }
drh290c1942004-08-21 17:54:45 +00001203 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1204 Table *pTab = pFrom->pTab;
1205 char *zTabName = pFrom->zAlias;
drh54473222002-04-04 02:10:55 +00001206 if( zTabName==0 || zTabName[0]==0 ){
1207 zTabName = pTab->zName;
1208 }
drhcf55b7a2004-07-20 01:45:19 +00001209 if( zTName && (zTabName==0 || zTabName[0]==0 ||
1210 sqlite3StrICmp(zTName, zTabName)!=0) ){
drh54473222002-04-04 02:10:55 +00001211 continue;
1212 }
1213 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001214 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001215 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001216 char *zName = pTab->aCol[j].zName;
1217
drh91bb0ee2004-09-01 03:06:34 +00001218 if( i>0 ){
1219 struct SrcList_item *pLeft = &pTabList->a[i-1];
1220 if( (pLeft->jointype & JT_NATURAL)!=0 &&
1221 columnIndex(pLeft->pTab, zName)>=0 ){
1222 /* In a NATURAL join, omit the join columns from the
1223 ** table on the right */
1224 continue;
1225 }
1226 if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1227 /* In a join with a USING clause, omit columns in the
1228 ** using clause from the table on the right. */
1229 continue;
1230 }
drhad2d8302002-05-24 20:31:36 +00001231 }
danielk19774adee202004-05-08 08:23:19 +00001232 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001233 if( pRight==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001234 setToken(&pRight->token, zName);
drhd70dc522005-06-06 16:34:33 +00001235 if( zTabName && (longNames || pTabList->nSrc>1) ){
danielk19774adee202004-05-08 08:23:19 +00001236 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1237 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001238 if( pExpr==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001239 setToken(&pLeft->token, zTabName);
1240 setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
drh6977fea2002-10-22 23:38:04 +00001241 pExpr->span.dyn = 1;
1242 pExpr->token.z = 0;
1243 pExpr->token.n = 0;
1244 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001245 }else{
drh22f70c32002-02-18 01:17:00 +00001246 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001247 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001248 }
drhd70dc522005-06-06 16:34:33 +00001249 if( longNames ){
1250 pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span);
1251 }else{
1252 pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
1253 }
drh7c917d12001-12-16 20:05:05 +00001254 }
drh17e24df2001-11-06 14:10:41 +00001255 }
drh54473222002-04-04 02:10:55 +00001256 if( !tableSeen ){
drhcf55b7a2004-07-20 01:45:19 +00001257 if( zTName ){
1258 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
drhf5db2d32002-06-06 23:42:27 +00001259 }else{
danielk19774adee202004-05-08 08:23:19 +00001260 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001261 }
drh54473222002-04-04 02:10:55 +00001262 rc = 1;
1263 }
drhcf55b7a2004-07-20 01:45:19 +00001264 sqliteFree(zTName);
drhd8bc7082000-06-07 23:51:50 +00001265 }
1266 }
danielk19774adee202004-05-08 08:23:19 +00001267 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001268 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001269 }
drh54473222002-04-04 02:10:55 +00001270 return rc;
drhd8bc7082000-06-07 23:51:50 +00001271}
1272
danielk197793758c82005-01-21 08:13:14 +00001273#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhff78bd22002-02-27 01:47:11 +00001274/*
drhd8bc7082000-06-07 23:51:50 +00001275** This routine associates entries in an ORDER BY expression list with
1276** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001277** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001278** the top-level node is filled in with column number and the iTable
1279** value of the top-level node is filled with iTable parameter.
1280**
1281** If there are prior SELECT clauses, they are processed first. A match
1282** in an earlier SELECT takes precedence over a later SELECT.
1283**
1284** Any entry that does not match is flagged as an error. The number
1285** of errors is returned.
1286*/
1287static int matchOrderbyToColumn(
1288 Parse *pParse, /* A place to leave error messages */
1289 Select *pSelect, /* Match to result columns of this SELECT */
1290 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001291 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001292 int mustComplete /* If TRUE all ORDER BYs must match */
1293){
1294 int nErr = 0;
1295 int i, j;
1296 ExprList *pEList;
1297
drhdaffd0e2001-04-11 14:28:42 +00001298 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001299 if( mustComplete ){
1300 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1301 }
drh9b3187e2005-01-18 14:45:47 +00001302 if( prepSelectStmt(pParse, pSelect) ){
drhd8bc7082000-06-07 23:51:50 +00001303 return 1;
1304 }
1305 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001306 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1307 return 1;
1308 }
drhd8bc7082000-06-07 23:51:50 +00001309 }
1310 pEList = pSelect->pEList;
1311 for(i=0; i<pOrderBy->nExpr; i++){
1312 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001313 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001314 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001315 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001316 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001317 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001318 "ORDER BY position %d should be between 1 and %d",
1319 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001320 nErr++;
1321 break;
1322 }
drhfcb78a42003-01-18 20:11:05 +00001323 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001324 iCol--;
1325 }
1326 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001327 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001328 char *zName, *zLabel;
1329 zName = pEList->a[j].zName;
drha99db3b2004-06-19 14:49:12 +00001330 zLabel = sqlite3NameFromToken(&pE->token);
1331 assert( zLabel!=0 );
danielk19774adee202004-05-08 08:23:19 +00001332 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001333 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001334 }
drh6e142f52000-06-08 13:36:40 +00001335 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001336 }
danielk19774adee202004-05-08 08:23:19 +00001337 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001338 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001339 }
1340 }
drhe4de1fe2002-06-02 16:09:01 +00001341 if( iCol>=0 ){
1342 pE->op = TK_COLUMN;
1343 pE->iColumn = iCol;
1344 pE->iTable = iTable;
danielk1977a58fdfb2005-02-08 07:50:40 +00001345 pE->iAgg = -1;
drhe4de1fe2002-06-02 16:09:01 +00001346 pOrderBy->a[i].done = 1;
1347 }
1348 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001349 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001350 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001351 nErr++;
1352 break;
1353 }
1354 }
1355 return nErr;
1356}
danielk197793758c82005-01-21 08:13:14 +00001357#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +00001358
1359/*
1360** Get a VDBE for the given parser context. Create a new one if necessary.
1361** If an error occurs, return NULL and leave a message in pParse.
1362*/
danielk19774adee202004-05-08 08:23:19 +00001363Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001364 Vdbe *v = pParse->pVdbe;
1365 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001366 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001367 }
drhd8bc7082000-06-07 23:51:50 +00001368 return v;
1369}
drhfcb78a42003-01-18 20:11:05 +00001370
drh15007a92006-01-08 18:10:17 +00001371
drhd8bc7082000-06-07 23:51:50 +00001372/*
drh7b58dae2003-07-20 01:16:46 +00001373** Compute the iLimit and iOffset fields of the SELECT based on the
drhec7429a2005-10-06 16:53:14 +00001374** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
drh7b58dae2003-07-20 01:16:46 +00001375** that appear in the original SQL statement after the LIMIT and OFFSET
danielk1977a2dc3b12005-02-05 12:48:48 +00001376** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
1377** are the integer memory register numbers for counters used to compute
1378** the limit and offset. If there is no limit and/or offset, then
1379** iLimit and iOffset are negative.
drh7b58dae2003-07-20 01:16:46 +00001380**
drhd59ba6c2006-01-08 05:02:54 +00001381** This routine changes the values of iLimit and iOffset only if
drhec7429a2005-10-06 16:53:14 +00001382** a limit or offset is defined by pLimit and pOffset. iLimit and
drh7b58dae2003-07-20 01:16:46 +00001383** iOffset should have been preset to appropriate default values
1384** (usually but not always -1) prior to calling this routine.
drhec7429a2005-10-06 16:53:14 +00001385** Only if pLimit!=0 or pOffset!=0 do the limit registers get
drh7b58dae2003-07-20 01:16:46 +00001386** redefined. The UNION ALL operator uses this property to force
1387** the reuse of the same limit and offset registers across multiple
1388** SELECT statements.
1389*/
drhec7429a2005-10-06 16:53:14 +00001390static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
drh02afc862006-01-20 18:10:57 +00001391 Vdbe *v = 0;
1392 int iLimit = 0;
drh15007a92006-01-08 18:10:17 +00001393 int iOffset;
1394 int addr1, addr2;
1395
drh7b58dae2003-07-20 01:16:46 +00001396 /*
drh7b58dae2003-07-20 01:16:46 +00001397 ** "LIMIT -1" always shows all rows. There is some
1398 ** contraversy about what the correct behavior should be.
1399 ** The current implementation interprets "LIMIT 0" to mean
1400 ** no rows.
1401 */
danielk1977a2dc3b12005-02-05 12:48:48 +00001402 if( p->pLimit ){
drh15007a92006-01-08 18:10:17 +00001403 p->iLimit = iLimit = pParse->nMem;
drhd59ba6c2006-01-08 05:02:54 +00001404 pParse->nMem += 2;
drh15007a92006-01-08 18:10:17 +00001405 v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001406 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001407 sqlite3ExprCode(pParse, p->pLimit);
1408 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
drh15007a92006-01-08 18:10:17 +00001409 sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 0);
drhad6d9462004-09-19 02:15:24 +00001410 VdbeComment((v, "# LIMIT counter"));
drh15007a92006-01-08 18:10:17 +00001411 sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001412 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001413 if( p->pOffset ){
drh15007a92006-01-08 18:10:17 +00001414 p->iOffset = iOffset = pParse->nMem++;
1415 v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001416 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001417 sqlite3ExprCode(pParse, p->pOffset);
1418 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
drh15007a92006-01-08 18:10:17 +00001419 sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0);
drhad6d9462004-09-19 02:15:24 +00001420 VdbeComment((v, "# OFFSET counter"));
drh15007a92006-01-08 18:10:17 +00001421 addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0);
1422 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1423 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
1424 sqlite3VdbeJumpHere(v, addr1);
drhd59ba6c2006-01-08 05:02:54 +00001425 if( p->pLimit ){
1426 sqlite3VdbeAddOp(v, OP_Add, 0, 0);
1427 }
drh7b58dae2003-07-20 01:16:46 +00001428 }
drhd59ba6c2006-01-08 05:02:54 +00001429 if( p->pLimit ){
drh15007a92006-01-08 18:10:17 +00001430 addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0);
1431 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1432 sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1);
1433 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
1434 sqlite3VdbeJumpHere(v, addr1);
1435 sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1);
drhd59ba6c2006-01-08 05:02:54 +00001436 VdbeComment((v, "# LIMIT+OFFSET"));
drh15007a92006-01-08 18:10:17 +00001437 sqlite3VdbeJumpHere(v, addr2);
drhd59ba6c2006-01-08 05:02:54 +00001438 }
drh7b58dae2003-07-20 01:16:46 +00001439}
1440
1441/*
drh0342b1f2005-09-01 03:07:44 +00001442** Allocate a virtual index to use for sorting.
drhd3d39e92004-05-20 22:16:29 +00001443*/
drh4db38a72005-09-01 12:16:28 +00001444static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
drh0342b1f2005-09-01 03:07:44 +00001445 if( pOrderBy ){
1446 int addr;
drh9d2985c2005-09-08 01:58:42 +00001447 assert( pOrderBy->iECursor==0 );
1448 pOrderBy->iECursor = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001449 addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenVirtual,
drh9d2985c2005-09-08 01:58:42 +00001450 pOrderBy->iECursor, pOrderBy->nExpr+1);
drh0342b1f2005-09-01 03:07:44 +00001451 assert( p->addrOpenVirt[2] == -1 );
1452 p->addrOpenVirt[2] = addr;
drh736c22b2004-05-21 02:14:24 +00001453 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001454}
1455
drh13449892005-09-07 21:22:45 +00001456/*
1457** The opcode at addr is an OP_OpenVirtual that created a sorting
1458** index tha we ended up not needing. This routine changes that
1459** opcode to OP_Noop.
1460*/
1461static void uncreateSortingIndex(Parse *pParse, int addr){
1462 Vdbe *v = pParse->pVdbe;
1463 VdbeOp *pOp = sqlite3VdbeGetOp(v, addr);
1464 sqlite3VdbeChangeP3(v, addr, 0, 0);
1465 pOp->opcode = OP_Noop;
1466 pOp->p1 = 0;
1467 pOp->p2 = 0;
1468}
1469
drhb7f91642004-10-31 02:22:47 +00001470#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001471/*
drhfbc4ee72004-08-29 01:31:05 +00001472** Return the appropriate collating sequence for the iCol-th column of
1473** the result set for the compound-select statement "p". Return NULL if
1474** the column has no default collating sequence.
1475**
1476** The collating sequence for the compound select is taken from the
1477** left-most term of the select that has a collating sequence.
1478*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001479static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
drhfbc4ee72004-08-29 01:31:05 +00001480 CollSeq *pRet;
danielk1977dc1bdc42004-06-11 10:51:27 +00001481 if( p->pPrior ){
1482 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
drhfbc4ee72004-08-29 01:31:05 +00001483 }else{
1484 pRet = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001485 }
drhfbc4ee72004-08-29 01:31:05 +00001486 if( pRet==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001487 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1488 }
1489 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001490}
drhb7f91642004-10-31 02:22:47 +00001491#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd3d39e92004-05-20 22:16:29 +00001492
drhb7f91642004-10-31 02:22:47 +00001493#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhd3d39e92004-05-20 22:16:29 +00001494/*
drh82c3d632000-06-06 21:56:07 +00001495** This routine is called to process a query that is really the union
1496** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001497**
drhe78e8282003-01-19 03:59:45 +00001498** "p" points to the right-most of the two queries. the query on the
1499** left is p->pPrior. The left query could also be a compound query
1500** in which case this routine will be called recursively.
1501**
1502** The results of the total query are to be written into a destination
1503** of type eDest with parameter iParm.
1504**
1505** Example 1: Consider a three-way compound SQL statement.
1506**
1507** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1508**
1509** This statement is parsed up as follows:
1510**
1511** SELECT c FROM t3
1512** |
1513** `-----> SELECT b FROM t2
1514** |
jplyon4b11c6d2004-01-19 04:57:53 +00001515** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001516**
1517** The arrows in the diagram above represent the Select.pPrior pointer.
1518** So if this routine is called with p equal to the t3 query, then
1519** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1520**
1521** Notice that because of the way SQLite parses compound SELECTs, the
1522** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001523*/
danielk197784ac9d02004-05-18 09:58:06 +00001524static int multiSelect(
drhfbc4ee72004-08-29 01:31:05 +00001525 Parse *pParse, /* Parsing context */
1526 Select *p, /* The right-most of SELECTs to be coded */
1527 int eDest, /* \___ Store query results as specified */
1528 int iParm, /* / by these two parameters. */
1529 char *aff /* If eDest is SRT_Union, the affinity string */
danielk197784ac9d02004-05-18 09:58:06 +00001530){
drhfbc4ee72004-08-29 01:31:05 +00001531 int rc = SQLITE_OK; /* Success code from a subroutine */
1532 Select *pPrior; /* Another SELECT immediately to our left */
1533 Vdbe *v; /* Generate code to this VDBE */
drh8cdbf832004-08-29 16:25:03 +00001534 int nCol; /* Number of columns in the result set */
drh0342b1f2005-09-01 03:07:44 +00001535 ExprList *pOrderBy; /* The ORDER BY clause on p */
1536 int aSetP2[2]; /* Set P2 value of these op to number of columns */
1537 int nSetP2 = 0; /* Number of slots in aSetP2[] used */
drh82c3d632000-06-06 21:56:07 +00001538
drh7b58dae2003-07-20 01:16:46 +00001539 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
drhfbc4ee72004-08-29 01:31:05 +00001540 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001541 */
danielk197784ac9d02004-05-18 09:58:06 +00001542 if( p==0 || p->pPrior==0 ){
1543 rc = 1;
1544 goto multi_select_end;
1545 }
drhd8bc7082000-06-07 23:51:50 +00001546 pPrior = p->pPrior;
drh0342b1f2005-09-01 03:07:44 +00001547 assert( pPrior->pRightmost!=pPrior );
1548 assert( pPrior->pRightmost==p->pRightmost );
drhd8bc7082000-06-07 23:51:50 +00001549 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001550 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001551 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001552 rc = 1;
1553 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001554 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001555 if( pPrior->pLimit ){
danielk19774adee202004-05-08 08:23:19 +00001556 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001557 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001558 rc = 1;
1559 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001560 }
drh82c3d632000-06-06 21:56:07 +00001561
drhd8bc7082000-06-07 23:51:50 +00001562 /* Make sure we have a valid query engine. If not, create a new one.
1563 */
danielk19774adee202004-05-08 08:23:19 +00001564 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001565 if( v==0 ){
1566 rc = 1;
1567 goto multi_select_end;
1568 }
drhd8bc7082000-06-07 23:51:50 +00001569
drh1cc3d752002-03-23 00:31:29 +00001570 /* Create the destination temporary table if necessary
1571 */
drh9d2985c2005-09-08 01:58:42 +00001572 if( eDest==SRT_VirtualTab ){
danielk1977b4964b72004-05-18 01:23:38 +00001573 assert( p->pEList );
drh0342b1f2005-09-01 03:07:44 +00001574 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1575 aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 0);
drh1cc3d752002-03-23 00:31:29 +00001576 eDest = SRT_Table;
1577 }
1578
drhf46f9052002-06-22 02:33:38 +00001579 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001580 */
drh0342b1f2005-09-01 03:07:44 +00001581 pOrderBy = p->pOrderBy;
drh82c3d632000-06-06 21:56:07 +00001582 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001583 case TK_ALL: {
drh0342b1f2005-09-01 03:07:44 +00001584 if( pOrderBy==0 ){
drhec7429a2005-10-06 16:53:14 +00001585 int addr = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001586 assert( !pPrior->pLimit );
1587 pPrior->pLimit = p->pLimit;
1588 pPrior->pOffset = p->pOffset;
danielk1977b3bce662005-01-29 08:32:43 +00001589 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
danielk1977ad68cb62006-01-05 14:22:33 +00001590 p->pLimit = 0;
1591 p->pOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001592 if( rc ){
1593 goto multi_select_end;
1594 }
drhf46f9052002-06-22 02:33:38 +00001595 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001596 p->iLimit = pPrior->iLimit;
1597 p->iOffset = pPrior->iOffset;
drhec7429a2005-10-06 16:53:14 +00001598 if( p->iLimit>=0 ){
1599 addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0);
1600 VdbeComment((v, "# Jump ahead if LIMIT reached"));
1601 }
danielk1977b3bce662005-01-29 08:32:43 +00001602 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001603 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001604 if( rc ){
1605 goto multi_select_end;
1606 }
drhec7429a2005-10-06 16:53:14 +00001607 if( addr ){
1608 sqlite3VdbeJumpHere(v, addr);
1609 }
drhf46f9052002-06-22 02:33:38 +00001610 break;
1611 }
1612 /* For UNION ALL ... ORDER BY fall through to the next case */
1613 }
drh82c3d632000-06-06 21:56:07 +00001614 case TK_EXCEPT:
1615 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001616 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001617 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001618 int priorOp; /* The SRT_ operation to apply to prior selects */
danielk1977a2dc3b12005-02-05 12:48:48 +00001619 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
danielk1977dc1bdc42004-06-11 10:51:27 +00001620 int addr;
drh82c3d632000-06-06 21:56:07 +00001621
drhd8bc7082000-06-07 23:51:50 +00001622 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh0342b1f2005-09-01 03:07:44 +00001623 if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
drhd8bc7082000-06-07 23:51:50 +00001624 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001625 ** right.
drhd8bc7082000-06-07 23:51:50 +00001626 */
drh82c3d632000-06-06 21:56:07 +00001627 unionTab = iParm;
1628 }else{
drhd8bc7082000-06-07 23:51:50 +00001629 /* We will need to create our own temporary table to hold the
1630 ** intermediate results.
1631 */
1632 unionTab = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001633 if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001634 rc = 1;
1635 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001636 }
drh9170dd72005-07-08 17:13:46 +00001637 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, unionTab, 0);
drh0342b1f2005-09-01 03:07:44 +00001638 if( priorOp==SRT_Table ){
1639 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1640 aSetP2[nSetP2++] = addr;
1641 }else{
1642 assert( p->addrOpenVirt[0] == -1 );
1643 p->addrOpenVirt[0] = addr;
1644 p->pRightmost->usesVirt = 1;
drhd8bc7082000-06-07 23:51:50 +00001645 }
drh0342b1f2005-09-01 03:07:44 +00001646 createSortingIndex(pParse, p, pOrderBy);
danielk197784ac9d02004-05-18 09:58:06 +00001647 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001648 }
drhd8bc7082000-06-07 23:51:50 +00001649
1650 /* Code the SELECT statements to our left
1651 */
danielk1977b3bce662005-01-29 08:32:43 +00001652 assert( !pPrior->pOrderBy );
1653 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001654 if( rc ){
1655 goto multi_select_end;
1656 }
drhd8bc7082000-06-07 23:51:50 +00001657
1658 /* Code the current SELECT statement
1659 */
1660 switch( p->op ){
1661 case TK_EXCEPT: op = SRT_Except; break;
1662 case TK_UNION: op = SRT_Union; break;
1663 case TK_ALL: op = SRT_Table; break;
1664 }
drh82c3d632000-06-06 21:56:07 +00001665 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001666 p->pOrderBy = 0;
drh4b14b4d2005-09-19 17:35:53 +00001667 p->disallowOrderBy = pOrderBy!=0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001668 pLimit = p->pLimit;
1669 p->pLimit = 0;
1670 pOffset = p->pOffset;
1671 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001672 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001673 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001674 p->pOrderBy = pOrderBy;
danielk1977a2dc3b12005-02-05 12:48:48 +00001675 sqlite3ExprDelete(p->pLimit);
1676 p->pLimit = pLimit;
1677 p->pOffset = pOffset;
drhbe5fd492004-12-16 21:09:16 +00001678 p->iLimit = -1;
1679 p->iOffset = -1;
danielk197784ac9d02004-05-18 09:58:06 +00001680 if( rc ){
1681 goto multi_select_end;
1682 }
1683
drhd8bc7082000-06-07 23:51:50 +00001684
1685 /* Convert the data in the temporary table into whatever form
1686 ** it is that we currently need.
1687 */
drhc926afb2002-06-20 03:38:26 +00001688 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001689 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001690 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001691 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001692 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001693 }
danielk19774adee202004-05-08 08:23:19 +00001694 iBreak = sqlite3VdbeMakeLabel(v);
1695 iCont = sqlite3VdbeMakeLabel(v);
drhec7429a2005-10-06 16:53:14 +00001696 computeLimitRegisters(pParse, p, iBreak);
danielk19774adee202004-05-08 08:23:19 +00001697 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
danielk19774adee202004-05-08 08:23:19 +00001698 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001699 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001700 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001701 iCont, iBreak, 0);
1702 if( rc ){
1703 rc = 1;
1704 goto multi_select_end;
1705 }
danielk19774adee202004-05-08 08:23:19 +00001706 sqlite3VdbeResolveLabel(v, iCont);
1707 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1708 sqlite3VdbeResolveLabel(v, iBreak);
1709 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001710 }
1711 break;
1712 }
1713 case TK_INTERSECT: {
1714 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001715 int iCont, iBreak, iStart;
danielk1977a2dc3b12005-02-05 12:48:48 +00001716 Expr *pLimit, *pOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001717 int addr;
drh82c3d632000-06-06 21:56:07 +00001718
drhd8bc7082000-06-07 23:51:50 +00001719 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001720 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001721 ** by allocating the tables we will need.
1722 */
drh82c3d632000-06-06 21:56:07 +00001723 tab1 = pParse->nTab++;
1724 tab2 = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001725 if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001726 rc = 1;
1727 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001728 }
drh0342b1f2005-09-01 03:07:44 +00001729 createSortingIndex(pParse, p, pOrderBy);
danielk1977dc1bdc42004-06-11 10:51:27 +00001730
drh9170dd72005-07-08 17:13:46 +00001731 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab1, 0);
drh0342b1f2005-09-01 03:07:44 +00001732 assert( p->addrOpenVirt[0] == -1 );
1733 p->addrOpenVirt[0] = addr;
1734 p->pRightmost->usesVirt = 1;
danielk197784ac9d02004-05-18 09:58:06 +00001735 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001736
1737 /* Code the SELECTs to our left into temporary table "tab1".
1738 */
danielk1977b3bce662005-01-29 08:32:43 +00001739 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001740 if( rc ){
1741 goto multi_select_end;
1742 }
drhd8bc7082000-06-07 23:51:50 +00001743
1744 /* Code the current SELECT into temporary table "tab2"
1745 */
drh9170dd72005-07-08 17:13:46 +00001746 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab2, 0);
drh0342b1f2005-09-01 03:07:44 +00001747 assert( p->addrOpenVirt[1] == -1 );
1748 p->addrOpenVirt[1] = addr;
drh82c3d632000-06-06 21:56:07 +00001749 p->pPrior = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001750 pLimit = p->pLimit;
1751 p->pLimit = 0;
1752 pOffset = p->pOffset;
1753 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001754 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001755 p->pPrior = pPrior;
danielk1977a2dc3b12005-02-05 12:48:48 +00001756 sqlite3ExprDelete(p->pLimit);
1757 p->pLimit = pLimit;
1758 p->pOffset = pOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001759 if( rc ){
1760 goto multi_select_end;
1761 }
drhd8bc7082000-06-07 23:51:50 +00001762
1763 /* Generate code to take the intersection of the two temporary
1764 ** tables.
1765 */
drh82c3d632000-06-06 21:56:07 +00001766 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001767 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001768 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001769 }
danielk19774adee202004-05-08 08:23:19 +00001770 iBreak = sqlite3VdbeMakeLabel(v);
1771 iCont = sqlite3VdbeMakeLabel(v);
drhec7429a2005-10-06 16:53:14 +00001772 computeLimitRegisters(pParse, p, iBreak);
danielk19774adee202004-05-08 08:23:19 +00001773 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh4a9f2412005-06-12 12:01:19 +00001774 iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
danielk19774adee202004-05-08 08:23:19 +00001775 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001776 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001777 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001778 iCont, iBreak, 0);
1779 if( rc ){
1780 rc = 1;
1781 goto multi_select_end;
1782 }
danielk19774adee202004-05-08 08:23:19 +00001783 sqlite3VdbeResolveLabel(v, iCont);
1784 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1785 sqlite3VdbeResolveLabel(v, iBreak);
1786 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1787 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001788 break;
1789 }
1790 }
drh8cdbf832004-08-29 16:25:03 +00001791
1792 /* Make sure all SELECTs in the statement have the same number of elements
1793 ** in their result sets.
1794 */
drh82c3d632000-06-06 21:56:07 +00001795 assert( p->pEList && pPrior->pEList );
1796 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001797 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001798 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001799 rc = 1;
1800 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001801 }
danielk197784ac9d02004-05-18 09:58:06 +00001802
drh8cdbf832004-08-29 16:25:03 +00001803 /* Set the number of columns in temporary tables
1804 */
1805 nCol = p->pEList->nExpr;
drh0342b1f2005-09-01 03:07:44 +00001806 while( nSetP2 ){
1807 sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
drh8cdbf832004-08-29 16:25:03 +00001808 }
1809
drhfbc4ee72004-08-29 01:31:05 +00001810 /* Compute collating sequences used by either the ORDER BY clause or
1811 ** by any temporary tables needed to implement the compound select.
1812 ** Attach the KeyInfo structure to all temporary tables. Invoke the
1813 ** ORDER BY processing if there is an ORDER BY clause.
drh8cdbf832004-08-29 16:25:03 +00001814 **
1815 ** This section is run by the right-most SELECT statement only.
1816 ** SELECT statements to the left always skip this part. The right-most
1817 ** SELECT might also skip this part if it has no ORDER BY clause and
1818 ** no temp tables are required.
drhfbc4ee72004-08-29 01:31:05 +00001819 */
drh0342b1f2005-09-01 03:07:44 +00001820 if( pOrderBy || p->usesVirt ){
drhfbc4ee72004-08-29 01:31:05 +00001821 int i; /* Loop counter */
1822 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
drh0342b1f2005-09-01 03:07:44 +00001823 Select *pLoop; /* For looping through SELECT statements */
1824 CollSeq **apColl;
1825 CollSeq **aCopy;
drhfbc4ee72004-08-29 01:31:05 +00001826
drh0342b1f2005-09-01 03:07:44 +00001827 assert( p->pRightmost==p );
drh4db38a72005-09-01 12:16:28 +00001828 pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*2*sizeof(CollSeq*) + nCol);
danielk1977dc1bdc42004-06-11 10:51:27 +00001829 if( !pKeyInfo ){
1830 rc = SQLITE_NOMEM;
1831 goto multi_select_end;
1832 }
1833
danielk197714db2662006-01-09 16:12:04 +00001834 pKeyInfo->enc = ENC(pParse->db);
danielk1977dc1bdc42004-06-11 10:51:27 +00001835 pKeyInfo->nField = nCol;
1836
drh0342b1f2005-09-01 03:07:44 +00001837 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
1838 *apColl = multiSelectCollSeq(pParse, p, i);
1839 if( 0==*apColl ){
1840 *apColl = pParse->db->pDfltColl;
danielk1977dc1bdc42004-06-11 10:51:27 +00001841 }
1842 }
1843
drh0342b1f2005-09-01 03:07:44 +00001844 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
1845 for(i=0; i<2; i++){
1846 int addr = pLoop->addrOpenVirt[i];
1847 if( addr<0 ){
1848 /* If [0] is unused then [1] is also unused. So we can
1849 ** always safely abort as soon as the first unused slot is found */
1850 assert( pLoop->addrOpenVirt[1]<0 );
1851 break;
1852 }
1853 sqlite3VdbeChangeP2(v, addr, nCol);
1854 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
1855 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001856 }
1857
drh0342b1f2005-09-01 03:07:44 +00001858 if( pOrderBy ){
1859 struct ExprList_item *pOTerm = pOrderBy->a;
drh4efc0832005-11-16 13:47:50 +00001860 int nOrderByExpr = pOrderBy->nExpr;
drh0342b1f2005-09-01 03:07:44 +00001861 int addr;
drh4db38a72005-09-01 12:16:28 +00001862 u8 *pSortOrder;
drh0342b1f2005-09-01 03:07:44 +00001863
1864 aCopy = (CollSeq**)&pKeyInfo[1];
drh4efc0832005-11-16 13:47:50 +00001865 pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
drh0342b1f2005-09-01 03:07:44 +00001866 memcpy(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
1867 apColl = pKeyInfo->aColl;
drh4efc0832005-11-16 13:47:50 +00001868 for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
drh0342b1f2005-09-01 03:07:44 +00001869 Expr *pExpr = pOTerm->pExpr;
1870 char *zName = pOTerm->zName;
danielk1977dc1bdc42004-06-11 10:51:27 +00001871 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
danielk1977dc1bdc42004-06-11 10:51:27 +00001872 if( zName ){
drh0342b1f2005-09-01 03:07:44 +00001873 *apColl = sqlite3LocateCollSeq(pParse, zName, -1);
danielk1977dc1bdc42004-06-11 10:51:27 +00001874 }else{
drh0342b1f2005-09-01 03:07:44 +00001875 *apColl = aCopy[pExpr->iColumn];
danielk1977dc1bdc42004-06-11 10:51:27 +00001876 }
drh4db38a72005-09-01 12:16:28 +00001877 *pSortOrder = pOTerm->sortOrder;
danielk1977dc1bdc42004-06-11 10:51:27 +00001878 }
drh0342b1f2005-09-01 03:07:44 +00001879 assert( p->pRightmost==p );
1880 assert( p->addrOpenVirt[2]>=0 );
1881 addr = p->addrOpenVirt[2];
drh4db38a72005-09-01 12:16:28 +00001882 sqlite3VdbeChangeP2(v, addr, p->pEList->nExpr+2);
drh4efc0832005-11-16 13:47:50 +00001883 pKeyInfo->nField = nOrderByExpr;
drh4db38a72005-09-01 12:16:28 +00001884 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
1885 pKeyInfo = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001886 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1887 }
1888
drh0342b1f2005-09-01 03:07:44 +00001889 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001890 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001891
1892multi_select_end:
danielk197784ac9d02004-05-18 09:58:06 +00001893 return rc;
drh22827922000-06-06 17:27:05 +00001894}
drhb7f91642004-10-31 02:22:47 +00001895#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drh22827922000-06-06 17:27:05 +00001896
drhb7f91642004-10-31 02:22:47 +00001897#ifndef SQLITE_OMIT_VIEW
drh22827922000-06-06 17:27:05 +00001898/*
drh832508b2002-03-02 17:04:07 +00001899** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001900** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001901** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001902** unchanged.)
drh832508b2002-03-02 17:04:07 +00001903**
1904** This routine is part of the flattening procedure. A subquery
1905** whose result set is defined by pEList appears as entry in the
1906** FROM clause of a SELECT such that the VDBE cursor assigned to that
1907** FORM clause entry is iTable. This routine make the necessary
1908** changes to pExpr so that it refers directly to the source table
1909** of the subquery rather the result set of the subquery.
1910*/
drh6a3ea0e2003-05-02 14:32:12 +00001911static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
danielk1977b3bce662005-01-29 08:32:43 +00001912static void substSelect(Select *, int, ExprList *); /* Forward Decl */
drh6a3ea0e2003-05-02 14:32:12 +00001913static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001914 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001915 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1916 if( pExpr->iColumn<0 ){
1917 pExpr->op = TK_NULL;
1918 }else{
1919 Expr *pNew;
1920 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1921 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1922 pNew = pEList->a[pExpr->iColumn].pExpr;
1923 assert( pNew!=0 );
1924 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001925 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001926 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001927 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001928 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001929 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001930 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001931 pExpr->iTable = pNew->iTable;
1932 pExpr->iColumn = pNew->iColumn;
1933 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001934 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1935 sqlite3TokenCopy(&pExpr->span, &pNew->span);
danielk1977a1cb1832005-02-12 08:59:55 +00001936 pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
1937 pExpr->flags = pNew->flags;
drh50350a12004-02-13 16:22:22 +00001938 }
drh832508b2002-03-02 17:04:07 +00001939 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001940 substExpr(pExpr->pLeft, iTable, pEList);
1941 substExpr(pExpr->pRight, iTable, pEList);
danielk1977b3bce662005-01-29 08:32:43 +00001942 substSelect(pExpr->pSelect, iTable, pEList);
drh6a3ea0e2003-05-02 14:32:12 +00001943 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001944 }
1945}
danielk1977b3bce662005-01-29 08:32:43 +00001946static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001947 int i;
1948 if( pList==0 ) return;
1949 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001950 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001951 }
1952}
danielk1977b3bce662005-01-29 08:32:43 +00001953static void substSelect(Select *p, int iTable, ExprList *pEList){
1954 if( !p ) return;
1955 substExprList(p->pEList, iTable, pEList);
1956 substExprList(p->pGroupBy, iTable, pEList);
1957 substExprList(p->pOrderBy, iTable, pEList);
1958 substExpr(p->pHaving, iTable, pEList);
1959 substExpr(p->pWhere, iTable, pEList);
1960}
drhb7f91642004-10-31 02:22:47 +00001961#endif /* !defined(SQLITE_OMIT_VIEW) */
drh832508b2002-03-02 17:04:07 +00001962
drhb7f91642004-10-31 02:22:47 +00001963#ifndef SQLITE_OMIT_VIEW
drh832508b2002-03-02 17:04:07 +00001964/*
drh1350b032002-02-27 19:00:20 +00001965** This routine attempts to flatten subqueries in order to speed
1966** execution. It returns 1 if it makes changes and 0 if no flattening
1967** occurs.
1968**
1969** To understand the concept of flattening, consider the following
1970** query:
1971**
1972** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1973**
1974** The default way of implementing this query is to execute the
1975** subquery first and store the results in a temporary table, then
1976** run the outer query on that temporary table. This requires two
1977** passes over the data. Furthermore, because the temporary table
1978** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001979** optimized.
drh1350b032002-02-27 19:00:20 +00001980**
drh832508b2002-03-02 17:04:07 +00001981** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001982** a single flat select, like this:
1983**
1984** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1985**
1986** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001987** but only has to scan the data once. And because indices might
1988** exist on the table t1, a complete scan of the data might be
1989** avoided.
drh1350b032002-02-27 19:00:20 +00001990**
drh832508b2002-03-02 17:04:07 +00001991** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001992**
drh832508b2002-03-02 17:04:07 +00001993** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001994**
drh832508b2002-03-02 17:04:07 +00001995** (2) The subquery is not an aggregate or the outer query is not a join.
1996**
drh8af4d3a2003-05-06 20:35:16 +00001997** (3) The subquery is not the right operand of a left outer join, or
1998** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001999**
2000** (4) The subquery is not DISTINCT or the outer query is not a join.
2001**
2002** (5) The subquery is not DISTINCT or the outer query does not use
2003** aggregates.
2004**
2005** (6) The subquery does not use aggregates or the outer query is not
2006** DISTINCT.
2007**
drh08192d52002-04-30 19:20:28 +00002008** (7) The subquery has a FROM clause.
2009**
drhdf199a22002-06-14 22:38:41 +00002010** (8) The subquery does not use LIMIT or the outer query is not a join.
2011**
2012** (9) The subquery does not use LIMIT or the outer query does not use
2013** aggregates.
2014**
2015** (10) The subquery does not use aggregates or the outer query does not
2016** use LIMIT.
2017**
drh174b6192002-12-03 02:22:52 +00002018** (11) The subquery and the outer query do not both have ORDER BY clauses.
2019**
drh3fc673e2003-06-16 00:40:34 +00002020** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
2021** subquery has no WHERE clause. (added by ticket #350)
2022**
drhac839632006-01-21 22:19:54 +00002023** (13) The subquery and outer query do not both use LIMIT
2024**
2025** (14) The subquery does not use OFFSET
2026**
drh832508b2002-03-02 17:04:07 +00002027** In this routine, the "p" parameter is a pointer to the outer query.
2028** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
2029** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2030**
drh665de472003-03-31 13:36:09 +00002031** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00002032** If flattening is attempted this routine returns 1.
2033**
2034** All of the expression analysis must occur on both the outer query and
2035** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00002036*/
drh8c74a8c2002-08-25 19:20:40 +00002037static int flattenSubquery(
2038 Parse *pParse, /* The parsing context */
2039 Select *p, /* The parent or outer SELECT statement */
2040 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
2041 int isAgg, /* True if outer SELECT uses aggregate functions */
2042 int subqueryIsAgg /* True if the subquery uses aggregate functions */
2043){
drh0bb28102002-05-08 11:54:14 +00002044 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00002045 SrcList *pSrc; /* The FROM clause of the outer query */
2046 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00002047 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00002048 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh91bb0ee2004-09-01 03:06:34 +00002049 int i; /* Loop counter */
2050 Expr *pWhere; /* The WHERE clause */
2051 struct SrcList_item *pSubitem; /* The subquery */
drh1350b032002-02-27 19:00:20 +00002052
drh832508b2002-03-02 17:04:07 +00002053 /* Check to see if flattening is permitted. Return 0 if not.
2054 */
2055 if( p==0 ) return 0;
2056 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00002057 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh91bb0ee2004-09-01 03:06:34 +00002058 pSubitem = &pSrc->a[iFrom];
2059 pSub = pSubitem->pSelect;
drh832508b2002-03-02 17:04:07 +00002060 assert( pSub!=0 );
drhac839632006-01-21 22:19:54 +00002061 if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
2062 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
drh832508b2002-03-02 17:04:07 +00002063 pSubSrc = pSub->pSrc;
2064 assert( pSubSrc );
drhac839632006-01-21 22:19:54 +00002065 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2066 ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2067 ** because they could be computed at compile-time. But when LIMIT and OFFSET
2068 ** became arbitrary expressions, we were forced to add restrictions (13)
2069 ** and (14). */
2070 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
2071 if( pSub->pOffset ) return 0; /* Restriction (14) */
2072 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
2073 if( (pSub->isDistinct || pSub->pLimit)
2074 && (pSrc->nSrc>1 || isAgg) ){ /* Restrictions (4)(5)(8)(9) */
2075 return 0;
drhdf199a22002-06-14 22:38:41 +00002076 }
drhac839632006-01-21 22:19:54 +00002077 if( p->isDistinct && subqueryIsAgg ) return 0; /* Restriction (6) */
2078 if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
2079 return 0; /* Restriction (11) */
2080 }
drh832508b2002-03-02 17:04:07 +00002081
drh8af4d3a2003-05-06 20:35:16 +00002082 /* Restriction 3: If the subquery is a join, make sure the subquery is
2083 ** not used as the right operand of an outer join. Examples of why this
2084 ** is not allowed:
2085 **
2086 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
2087 **
2088 ** If we flatten the above, we would get
2089 **
2090 ** (t1 LEFT OUTER JOIN t2) JOIN t3
2091 **
2092 ** which is not at all the same thing.
2093 */
2094 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
2095 return 0;
2096 }
2097
drh3fc673e2003-06-16 00:40:34 +00002098 /* Restriction 12: If the subquery is the right operand of a left outer
2099 ** join, make sure the subquery has no WHERE clause.
2100 ** An examples of why this is not allowed:
2101 **
2102 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
2103 **
2104 ** If we flatten the above, we would get
2105 **
2106 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
2107 **
2108 ** But the t2.x>0 test will always fail on a NULL row of t2, which
2109 ** effectively converts the OUTER JOIN into an INNER JOIN.
2110 */
2111 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
2112 && pSub->pWhere!=0 ){
2113 return 0;
2114 }
2115
drh0bb28102002-05-08 11:54:14 +00002116 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00002117 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00002118 */
drhc31c2eb2003-05-02 16:04:17 +00002119
2120 /* Move all of the FROM elements of the subquery into the
2121 ** the FROM clause of the outer query. Before doing this, remember
2122 ** the cursor number for the original outer query FROM element in
2123 ** iParent. The iParent cursor will never be used. Subsequent code
2124 ** will scan expressions looking for iParent references and replace
2125 ** those references with expressions that resolve to the subquery FROM
2126 ** elements we are now copying in.
2127 */
drh91bb0ee2004-09-01 03:06:34 +00002128 iParent = pSubitem->iCursor;
drhc31c2eb2003-05-02 16:04:17 +00002129 {
2130 int nSubSrc = pSubSrc->nSrc;
drh91bb0ee2004-09-01 03:06:34 +00002131 int jointype = pSubitem->jointype;
drhc31c2eb2003-05-02 16:04:17 +00002132
drhed8a3bb2005-06-06 21:19:56 +00002133 sqlite3DeleteTable(0, pSubitem->pTab);
drh91bb0ee2004-09-01 03:06:34 +00002134 sqliteFree(pSubitem->zDatabase);
2135 sqliteFree(pSubitem->zName);
2136 sqliteFree(pSubitem->zAlias);
drhc31c2eb2003-05-02 16:04:17 +00002137 if( nSubSrc>1 ){
2138 int extra = nSubSrc - 1;
2139 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00002140 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00002141 }
2142 p->pSrc = pSrc;
2143 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2144 pSrc->a[i] = pSrc->a[i-extra];
2145 }
2146 }
2147 for(i=0; i<nSubSrc; i++){
2148 pSrc->a[i+iFrom] = pSubSrc->a[i];
2149 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2150 }
drh8af4d3a2003-05-06 20:35:16 +00002151 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00002152 }
2153
2154 /* Now begin substituting subquery result set expressions for
2155 ** references to the iParent in the outer query.
2156 **
2157 ** Example:
2158 **
2159 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2160 ** \ \_____________ subquery __________/ /
2161 ** \_____________________ outer query ______________________________/
2162 **
2163 ** We look at every expression in the outer query and every place we see
2164 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2165 */
drh6a3ea0e2003-05-02 14:32:12 +00002166 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00002167 pList = p->pEList;
2168 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00002169 Expr *pExpr;
2170 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
drh2646da72005-12-09 20:02:05 +00002171 pList->a[i].zName = sqliteStrNDup((char*)pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00002172 }
2173 }
drh1b2e0322002-03-03 02:49:51 +00002174 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00002175 substExprList(p->pGroupBy, iParent, pSub->pEList);
2176 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00002177 }
drh174b6192002-12-03 02:22:52 +00002178 if( pSub->pOrderBy ){
2179 assert( p->pOrderBy==0 );
2180 p->pOrderBy = pSub->pOrderBy;
2181 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00002182 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00002183 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00002184 }
drh832508b2002-03-02 17:04:07 +00002185 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002186 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00002187 }else{
2188 pWhere = 0;
2189 }
2190 if( subqueryIsAgg ){
2191 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00002192 p->pHaving = p->pWhere;
2193 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00002194 substExpr(p->pHaving, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002195 p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
drh1b2e0322002-03-03 02:49:51 +00002196 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00002197 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00002198 }else{
drh6a3ea0e2003-05-02 14:32:12 +00002199 substExpr(p->pWhere, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002200 p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
drh832508b2002-03-02 17:04:07 +00002201 }
drhc31c2eb2003-05-02 16:04:17 +00002202
2203 /* The flattened query is distinct if either the inner or the
2204 ** outer query is distinct.
2205 */
drh832508b2002-03-02 17:04:07 +00002206 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00002207
danielk1977a58fdfb2005-02-08 07:50:40 +00002208 /*
2209 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
drhac839632006-01-21 22:19:54 +00002210 **
2211 ** One is tempted to try to add a and b to combine the limits. But this
2212 ** does not work if either limit is negative.
danielk1977a58fdfb2005-02-08 07:50:40 +00002213 */
danielk1977a2dc3b12005-02-05 12:48:48 +00002214 if( pSub->pLimit ){
2215 p->pLimit = pSub->pLimit;
2216 pSub->pLimit = 0;
drhdf199a22002-06-14 22:38:41 +00002217 }
drh8c74a8c2002-08-25 19:20:40 +00002218
drhc31c2eb2003-05-02 16:04:17 +00002219 /* Finially, delete what is left of the subquery and return
2220 ** success.
2221 */
danielk19774adee202004-05-08 08:23:19 +00002222 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00002223 return 1;
2224}
drhb7f91642004-10-31 02:22:47 +00002225#endif /* SQLITE_OMIT_VIEW */
drh1350b032002-02-27 19:00:20 +00002226
2227/*
drh9562b552002-02-19 15:00:07 +00002228** Analyze the SELECT statement passed in as an argument to see if it
2229** is a simple min() or max() query. If it is and this query can be
2230** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00002231** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00002232** simple min() or max() query, then return 0;
2233**
2234** A simply min() or max() query looks like this:
2235**
2236** SELECT min(a) FROM table;
2237** SELECT max(a) FROM table;
2238**
2239** The query may have only a single table in its FROM argument. There
2240** can be no GROUP BY or HAVING or WHERE clauses. The result set must
2241** be the min() or max() of a single column of the table. The column
2242** in the min() or max() function must be indexed.
2243**
danielk19774adee202004-05-08 08:23:19 +00002244** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00002245** See the header comment on that routine for additional information.
2246*/
2247static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2248 Expr *pExpr;
2249 int iCol;
2250 Table *pTab;
2251 Index *pIdx;
2252 int base;
2253 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00002254 int seekOp;
drh6e175292004-03-13 14:00:36 +00002255 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00002256 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00002257 SrcList *pSrc;
drhec7429a2005-10-06 16:53:14 +00002258 int brk;
danielk1977da184232006-01-05 11:34:32 +00002259 int iDb;
drh9562b552002-02-19 15:00:07 +00002260
2261 /* Check to see if this query is a simple min() or max() query. Return
2262 ** zero if it is not.
2263 */
2264 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00002265 pSrc = p->pSrc;
2266 if( pSrc->nSrc!=1 ) return 0;
2267 pEList = p->pEList;
2268 if( pEList->nExpr!=1 ) return 0;
2269 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002270 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002271 pList = pExpr->pList;
2272 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002273 if( pExpr->token.n!=3 ) return 0;
drh2646da72005-12-09 20:02:05 +00002274 if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002275 seekOp = OP_Rewind;
drh2646da72005-12-09 20:02:05 +00002276 }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002277 seekOp = OP_Last;
2278 }else{
2279 return 0;
2280 }
drh6e175292004-03-13 14:00:36 +00002281 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002282 if( pExpr->op!=TK_COLUMN ) return 0;
2283 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002284 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002285
danielk1977c00da102006-01-07 13:21:04 +00002286
drh9562b552002-02-19 15:00:07 +00002287 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002288 ** Check to make sure we have an index and make pIdx point to the
2289 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2290 ** key column, no index is necessary so set pIdx to NULL. If no
2291 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002292 */
2293 if( iCol<0 ){
2294 pIdx = 0;
2295 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002296 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002297 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2298 assert( pIdx->nColumn>=1 );
danielk1977b3bf5562006-01-10 17:58:23 +00002299 if( pIdx->aiColumn[0]==iCol &&
2300 0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){
2301 break;
2302 }
drh9562b552002-02-19 15:00:07 +00002303 }
2304 if( pIdx==0 ) return 0;
2305 }
2306
drhe5f50722003-07-19 00:44:14 +00002307 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002308 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002309 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002310 */
danielk19774adee202004-05-08 08:23:19 +00002311 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002312 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002313
drh0c37e632004-01-30 02:01:03 +00002314 /* If the output is destined for a temporary table, open that table.
2315 */
drh9d2985c2005-09-08 01:58:42 +00002316 if( eDest==SRT_VirtualTab ){
drhd81bd4e2005-09-05 20:06:49 +00002317 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002318 }
2319
drh17f71932002-02-21 12:01:27 +00002320 /* Generating code to find the min or the max. Basically all we have
2321 ** to do is find the first or the last entry in the chosen index. If
2322 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2323 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002324 */
danielk1977da184232006-01-05 11:34:32 +00002325 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
danielk197714db2662006-01-09 16:12:04 +00002326 assert( iDb>=0 || pTab->isTransient );
danielk1977da184232006-01-05 11:34:32 +00002327 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977c00da102006-01-07 13:21:04 +00002328 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh6e175292004-03-13 14:00:36 +00002329 base = pSrc->a[0].iCursor;
drhec7429a2005-10-06 16:53:14 +00002330 brk = sqlite3VdbeMakeLabel(v);
2331 computeLimitRegisters(pParse, p, brk);
drh6e175292004-03-13 14:00:36 +00002332 if( pSrc->a[0].pSelect==0 ){
danielk1977c00da102006-01-07 13:21:04 +00002333 sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead);
drh6e175292004-03-13 14:00:36 +00002334 }
drh9562b552002-02-19 15:00:07 +00002335 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002336 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002337 }else{
danielk19773719d7f2005-01-17 08:57:09 +00002338 /* Even though the cursor used to open the index here is closed
2339 ** as soon as a single value has been read from it, allocate it
2340 ** using (pParse->nTab++) to prevent the cursor id from being
2341 ** reused. This is important for statements of the form
2342 ** "INSERT INTO x SELECT max() FROM x".
2343 */
2344 int iIdx;
danielk1977b3bf5562006-01-10 17:58:23 +00002345 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
danielk19773719d7f2005-01-17 08:57:09 +00002346 iIdx = pParse->nTab++;
danielk1977da184232006-01-05 11:34:32 +00002347 assert( pIdx->pSchema==pTab->pSchema );
2348 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk1977b3bf5562006-01-10 17:58:23 +00002349 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
2350 (char*)pKey, P3_KEYINFO_HANDOFF);
drh9eb516c2004-07-18 20:52:32 +00002351 if( seekOp==OP_Rewind ){
drhf0863fe2005-06-12 21:35:51 +00002352 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh1af3fdb2004-07-18 21:33:01 +00002353 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2354 seekOp = OP_MoveGt;
drh9eb516c2004-07-18 20:52:32 +00002355 }
danielk19773719d7f2005-01-17 08:57:09 +00002356 sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
drhf0863fe2005-06-12 21:35:51 +00002357 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002358 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002359 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002360 }
drh5cf8e8c2002-02-19 22:42:05 +00002361 eList.nExpr = 1;
2362 memset(&eListItem, 0, sizeof(eListItem));
2363 eList.a = &eListItem;
2364 eList.a[0].pExpr = pExpr;
drhec7429a2005-10-06 16:53:14 +00002365 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0);
2366 sqlite3VdbeResolveLabel(v, brk);
danielk19774adee202004-05-08 08:23:19 +00002367 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002368
drh9562b552002-02-19 15:00:07 +00002369 return 1;
2370}
2371
2372/*
drh290c1942004-08-21 17:54:45 +00002373** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
2374** the number of errors seen.
2375**
2376** An ORDER BY or GROUP BY is a list of expressions. If any expression
2377** is an integer constant, then that expression is replaced by the
2378** corresponding entry in the result set.
2379*/
2380static int processOrderGroupBy(
danielk1977b3bce662005-01-29 08:32:43 +00002381 NameContext *pNC, /* Name context of the SELECT statement. */
drh290c1942004-08-21 17:54:45 +00002382 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
drh290c1942004-08-21 17:54:45 +00002383 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
2384){
2385 int i;
danielk1977b3bce662005-01-29 08:32:43 +00002386 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */
2387 Parse *pParse = pNC->pParse; /* The result set of the SELECT */
2388 assert( pEList );
2389
drh290c1942004-08-21 17:54:45 +00002390 if( pOrderBy==0 ) return 0;
2391 for(i=0; i<pOrderBy->nExpr; i++){
2392 int iCol;
2393 Expr *pE = pOrderBy->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +00002394 if( sqlite3ExprIsInteger(pE, &iCol) ){
2395 if( iCol>0 && iCol<=pEList->nExpr ){
2396 sqlite3ExprDelete(pE);
2397 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2398 }else{
drh290c1942004-08-21 17:54:45 +00002399 sqlite3ErrorMsg(pParse,
2400 "%s BY column number %d out of range - should be "
2401 "between 1 and %d", zType, iCol, pEList->nExpr);
2402 return 1;
2403 }
2404 }
danielk1977b3bce662005-01-29 08:32:43 +00002405 if( sqlite3ExprResolveNames(pNC, pE) ){
2406 return 1;
2407 }
2408 if( sqlite3ExprIsConstant(pE) ){
2409 sqlite3ErrorMsg(pParse,
2410 "%s BY terms must not be non-integer constants", zType);
2411 return 1;
2412 }
drh290c1942004-08-21 17:54:45 +00002413 }
2414 return 0;
2415}
2416
2417/*
danielk1977b3bce662005-01-29 08:32:43 +00002418** This routine resolves any names used in the result set of the
2419** supplied SELECT statement. If the SELECT statement being resolved
2420** is a sub-select, then pOuterNC is a pointer to the NameContext
2421** of the parent SELECT.
2422*/
2423int sqlite3SelectResolve(
2424 Parse *pParse, /* The parser context */
2425 Select *p, /* The SELECT statement being coded. */
2426 NameContext *pOuterNC /* The outer name context. May be NULL. */
2427){
2428 ExprList *pEList; /* Result set. */
2429 int i; /* For-loop variable used in multiple places */
2430 NameContext sNC; /* Local name-context */
drh13449892005-09-07 21:22:45 +00002431 ExprList *pGroupBy; /* The group by clause */
danielk1977b3bce662005-01-29 08:32:43 +00002432
2433 /* If this routine has run before, return immediately. */
2434 if( p->isResolved ){
2435 assert( !pOuterNC );
2436 return SQLITE_OK;
2437 }
2438 p->isResolved = 1;
2439
2440 /* If there have already been errors, do nothing. */
2441 if( pParse->nErr>0 ){
2442 return SQLITE_ERROR;
2443 }
2444
2445 /* Prepare the select statement. This call will allocate all cursors
2446 ** required to handle the tables and subqueries in the FROM clause.
2447 */
2448 if( prepSelectStmt(pParse, p) ){
2449 return SQLITE_ERROR;
2450 }
2451
danielk1977a2dc3b12005-02-05 12:48:48 +00002452 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2453 ** are not allowed to refer to any names, so pass an empty NameContext.
2454 */
drhffe07b22005-11-03 00:41:17 +00002455 memset(&sNC, 0, sizeof(sNC));
danielk1977b3bce662005-01-29 08:32:43 +00002456 sNC.pParse = pParse;
danielk1977a2dc3b12005-02-05 12:48:48 +00002457 if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2458 sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2459 return SQLITE_ERROR;
2460 }
2461
2462 /* Set up the local name-context to pass to ExprResolveNames() to
2463 ** resolve the expression-list.
2464 */
2465 sNC.allowAgg = 1;
2466 sNC.pSrcList = p->pSrc;
2467 sNC.pNext = pOuterNC;
danielk1977b3bce662005-01-29 08:32:43 +00002468
danielk1977b3bce662005-01-29 08:32:43 +00002469 /* Resolve names in the result set. */
2470 pEList = p->pEList;
2471 if( !pEList ) return SQLITE_ERROR;
2472 for(i=0; i<pEList->nExpr; i++){
2473 Expr *pX = pEList->a[i].pExpr;
2474 if( sqlite3ExprResolveNames(&sNC, pX) ){
2475 return SQLITE_ERROR;
2476 }
2477 }
2478
2479 /* If there are no aggregate functions in the result-set, and no GROUP BY
2480 ** expression, do not allow aggregates in any of the other expressions.
2481 */
2482 assert( !p->isAgg );
drh13449892005-09-07 21:22:45 +00002483 pGroupBy = p->pGroupBy;
2484 if( pGroupBy || sNC.hasAgg ){
danielk1977b3bce662005-01-29 08:32:43 +00002485 p->isAgg = 1;
2486 }else{
2487 sNC.allowAgg = 0;
2488 }
2489
2490 /* If a HAVING clause is present, then there must be a GROUP BY clause.
2491 */
drh13449892005-09-07 21:22:45 +00002492 if( p->pHaving && !pGroupBy ){
danielk1977b3bce662005-01-29 08:32:43 +00002493 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2494 return SQLITE_ERROR;
2495 }
2496
2497 /* Add the expression list to the name-context before parsing the
2498 ** other expressions in the SELECT statement. This is so that
2499 ** expressions in the WHERE clause (etc.) can refer to expressions by
2500 ** aliases in the result set.
2501 **
2502 ** Minor point: If this is the case, then the expression will be
2503 ** re-evaluated for each reference to it.
2504 */
2505 sNC.pEList = p->pEList;
2506 if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2507 sqlite3ExprResolveNames(&sNC, p->pHaving) ||
2508 processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
drh13449892005-09-07 21:22:45 +00002509 processOrderGroupBy(&sNC, pGroupBy, "GROUP")
danielk1977b3bce662005-01-29 08:32:43 +00002510 ){
2511 return SQLITE_ERROR;
2512 }
2513
drh13449892005-09-07 21:22:45 +00002514 /* Make sure the GROUP BY clause does not contain aggregate functions.
2515 */
2516 if( pGroupBy ){
2517 struct ExprList_item *pItem;
2518
2519 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
2520 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
2521 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
2522 "the GROUP BY clause");
2523 return SQLITE_ERROR;
2524 }
2525 }
2526 }
2527
danielk1977b3bce662005-01-29 08:32:43 +00002528 return SQLITE_OK;
2529}
2530
2531/*
drh13449892005-09-07 21:22:45 +00002532** Reset the aggregate accumulator.
2533**
2534** The aggregate accumulator is a set of memory cells that hold
2535** intermediate results while calculating an aggregate. This
2536** routine simply stores NULLs in all of those memory cells.
danielk1977b3bce662005-01-29 08:32:43 +00002537*/
drh13449892005-09-07 21:22:45 +00002538static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
2539 Vdbe *v = pParse->pVdbe;
2540 int i;
drhc99130f2005-09-11 11:56:27 +00002541 struct AggInfo_func *pFunc;
drh13449892005-09-07 21:22:45 +00002542 if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
2543 return;
2544 }
drh13449892005-09-07 21:22:45 +00002545 for(i=0; i<pAggInfo->nColumn; i++){
drhd654be82005-09-20 17:42:23 +00002546 sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
drh13449892005-09-07 21:22:45 +00002547 }
drhc99130f2005-09-11 11:56:27 +00002548 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
drhd654be82005-09-20 17:42:23 +00002549 sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
drhc99130f2005-09-11 11:56:27 +00002550 if( pFunc->iDistinct>=0 ){
2551 Expr *pE = pFunc->pExpr;
2552 if( pE->pList==0 || pE->pList->nExpr!=1 ){
2553 sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
2554 "by an expression");
2555 pFunc->iDistinct = -1;
2556 }else{
2557 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
2558 sqlite3VdbeOp3(v, OP_OpenVirtual, pFunc->iDistinct, 0,
2559 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2560 }
2561 }
drh13449892005-09-07 21:22:45 +00002562 }
danielk1977b3bce662005-01-29 08:32:43 +00002563}
2564
2565/*
drh13449892005-09-07 21:22:45 +00002566** Invoke the OP_AggFinalize opcode for every aggregate function
2567** in the AggInfo structure.
danielk1977b3bce662005-01-29 08:32:43 +00002568*/
drh13449892005-09-07 21:22:45 +00002569static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
2570 Vdbe *v = pParse->pVdbe;
2571 int i;
2572 struct AggInfo_func *pF;
2573 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
drha10a34b2005-09-07 22:09:48 +00002574 ExprList *pList = pF->pExpr->pList;
2575 sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
2576 (void*)pF->pFunc, P3_FUNCDEF);
drh13449892005-09-07 21:22:45 +00002577 }
danielk1977b3bce662005-01-29 08:32:43 +00002578}
drh13449892005-09-07 21:22:45 +00002579
2580/*
2581** Update the accumulator memory cells for an aggregate based on
2582** the current cursor position.
2583*/
2584static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
2585 Vdbe *v = pParse->pVdbe;
2586 int i;
2587 struct AggInfo_func *pF;
2588 struct AggInfo_col *pC;
drh13449892005-09-07 21:22:45 +00002589
2590 pAggInfo->directMode = 1;
2591 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
2592 int nArg;
drhc99130f2005-09-11 11:56:27 +00002593 int addrNext = 0;
drh13449892005-09-07 21:22:45 +00002594 ExprList *pList = pF->pExpr->pList;
2595 if( pList ){
2596 nArg = pList->nExpr;
2597 sqlite3ExprCodeExprList(pParse, pList);
2598 }else{
2599 nArg = 0;
2600 }
drhc99130f2005-09-11 11:56:27 +00002601 if( pF->iDistinct>=0 ){
2602 addrNext = sqlite3VdbeMakeLabel(v);
2603 assert( nArg==1 );
drh9d4673a2005-09-12 23:03:16 +00002604 codeDistinct(v, pF->iDistinct, addrNext, 1, 2);
drhc99130f2005-09-11 11:56:27 +00002605 }
drh13449892005-09-07 21:22:45 +00002606 if( pF->pFunc->needCollSeq ){
2607 CollSeq *pColl = 0;
2608 struct ExprList_item *pItem;
2609 int j;
2610 for(j=0, pItem=pList->a; !pColl && j<pList->nExpr; j++, pItem++){
2611 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
2612 }
2613 if( !pColl ){
2614 pColl = pParse->db->pDfltColl;
2615 }
2616 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2617 }
2618 sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
drhc99130f2005-09-11 11:56:27 +00002619 if( addrNext ){
2620 sqlite3VdbeResolveLabel(v, addrNext);
2621 }
drh13449892005-09-07 21:22:45 +00002622 }
drh13449892005-09-07 21:22:45 +00002623 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
drh5774b802005-09-07 22:48:16 +00002624 sqlite3ExprCode(pParse, pC->pExpr);
drh13449892005-09-07 21:22:45 +00002625 sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
2626 }
2627 pAggInfo->directMode = 0;
2628}
2629
2630
danielk1977b3bce662005-01-29 08:32:43 +00002631/*
drh9bb61fe2000-06-05 16:01:39 +00002632** Generate code for the given SELECT statement.
2633**
drhfef52082000-06-06 01:50:43 +00002634** The results are distributed in various ways depending on the
2635** value of eDest and iParm.
2636**
2637** eDest Value Result
2638** ------------ -------------------------------------------
2639** SRT_Callback Invoke the callback for each row of the result.
2640**
2641** SRT_Mem Store first result in memory cell iParm
2642**
danielk1977e014a832004-05-17 10:48:57 +00002643** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002644**
drh82c3d632000-06-06 21:56:07 +00002645** SRT_Union Store results as a key in a temporary table iParm
2646**
jplyon4b11c6d2004-01-19 04:57:53 +00002647** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002648**
2649** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002650**
drhe78e8282003-01-19 03:59:45 +00002651** The table above is incomplete. Additional eDist value have be added
2652** since this comment was written. See the selectInnerLoop() function for
2653** a complete listing of the allowed values of eDest and their meanings.
2654**
drh9bb61fe2000-06-05 16:01:39 +00002655** This routine returns the number of errors. If any errors are
2656** encountered, then an appropriate error message is left in
2657** pParse->zErrMsg.
2658**
2659** This routine does NOT free the Select structure passed in. The
2660** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002661**
2662** The pParent, parentTab, and *pParentAgg fields are filled in if this
2663** SELECT is a subquery. This routine may try to combine this SELECT
2664** with its parent to form a single flat query. In so doing, it might
2665** change the parent query from a non-aggregate to an aggregate query.
2666** For that reason, the pParentAgg flag is passed as a pointer, so it
2667** can be changed.
drhe78e8282003-01-19 03:59:45 +00002668**
2669** Example 1: The meaning of the pParent parameter.
2670**
2671** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2672** \ \_______ subquery _______/ /
2673** \ /
2674** \____________________ outer query ___________________/
2675**
2676** This routine is called for the outer query first. For that call,
2677** pParent will be NULL. During the processing of the outer query, this
2678** routine is called recursively to handle the subquery. For the recursive
2679** call, pParent will point to the outer query. Because the subquery is
2680** the second element in a three-way join, the parentTab parameter will
2681** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002682*/
danielk19774adee202004-05-08 08:23:19 +00002683int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002684 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002685 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002686 int eDest, /* How to dispose of the results */
2687 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002688 Select *pParent, /* Another SELECT for which this is a sub-query */
2689 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002690 int *pParentAgg, /* True if pParent uses aggregate functions */
danielk1977b3bce662005-01-29 08:32:43 +00002691 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002692){
drh13449892005-09-07 21:22:45 +00002693 int i, j; /* Loop counters */
2694 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
2695 Vdbe *v; /* The virtual machine under construction */
danielk1977b3bce662005-01-29 08:32:43 +00002696 int isAgg; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002697 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002698 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002699 Expr *pWhere; /* The WHERE clause. May be NULL */
2700 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002701 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2702 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002703 int isDistinct; /* True if the DISTINCT keyword is present */
2704 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002705 int rc = 1; /* Value to return from this function */
drh9d2985c2005-09-08 01:58:42 +00002706 int addrSortIndex; /* Address of an OP_OpenVirtual instruction */
drh13449892005-09-07 21:22:45 +00002707 AggInfo sAggInfo; /* Information used by aggregate queries */
drhec7429a2005-10-06 16:53:14 +00002708 int iEnd; /* Address of the end of the query */
drh9bb61fe2000-06-05 16:01:39 +00002709
danielk19779e128002006-01-18 16:51:35 +00002710 if( p==0 || sqlite3MallocFailed() || pParse->nErr ){
drh6f7adc82006-01-11 21:41:20 +00002711 return 1;
2712 }
danielk19774adee202004-05-08 08:23:19 +00002713 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drh13449892005-09-07 21:22:45 +00002714 memset(&sAggInfo, 0, sizeof(sAggInfo));
drhdaffd0e2001-04-11 14:28:42 +00002715
drhb7f91642004-10-31 02:22:47 +00002716#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +00002717 /* If there is are a sequence of queries, do the earlier ones first.
2718 */
2719 if( p->pPrior ){
drh0342b1f2005-09-01 03:07:44 +00002720 if( p->pRightmost==0 ){
2721 Select *pLoop;
2722 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
2723 pLoop->pRightmost = p;
2724 }
2725 }
danielk197784ac9d02004-05-18 09:58:06 +00002726 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002727 }
drhb7f91642004-10-31 02:22:47 +00002728#endif
drh82c3d632000-06-06 21:56:07 +00002729
danielk1977b3bce662005-01-29 08:32:43 +00002730 pOrderBy = p->pOrderBy;
drh13449892005-09-07 21:22:45 +00002731 if( IgnorableOrderby(eDest) ){
danielk1977b3bce662005-01-29 08:32:43 +00002732 p->pOrderBy = 0;
2733 }
2734 if( sqlite3SelectResolve(pParse, p, 0) ){
2735 goto select_end;
2736 }
2737 p->pOrderBy = pOrderBy;
2738
drh82c3d632000-06-06 21:56:07 +00002739 /* Make local copies of the parameters for this query.
2740 */
drh9bb61fe2000-06-05 16:01:39 +00002741 pTabList = p->pSrc;
2742 pWhere = p->pWhere;
drh22827922000-06-06 17:27:05 +00002743 pGroupBy = p->pGroupBy;
2744 pHaving = p->pHaving;
danielk1977b3bce662005-01-29 08:32:43 +00002745 isAgg = p->isAgg;
drh19a775c2000-06-05 18:54:46 +00002746 isDistinct = p->isDistinct;
danielk1977b3bce662005-01-29 08:32:43 +00002747 pEList = p->pEList;
2748 if( pEList==0 ) goto select_end;
drh9bb61fe2000-06-05 16:01:39 +00002749
2750 /*
2751 ** Do not even attempt to generate any code if we have already seen
2752 ** errors before this routine starts.
2753 */
drh1d83f052002-02-17 00:30:36 +00002754 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002755
drh22827922000-06-06 17:27:05 +00002756 /* If writing to memory or generating a set
2757 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002758 */
danielk197793758c82005-01-21 08:13:14 +00002759#ifndef SQLITE_OMIT_SUBQUERY
drhfef52082000-06-06 01:50:43 +00002760 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002761 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002762 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002763 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002764 }
danielk197793758c82005-01-21 08:13:14 +00002765#endif
drh19a775c2000-06-05 18:54:46 +00002766
drhc926afb2002-06-20 03:38:26 +00002767 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002768 */
drh13449892005-09-07 21:22:45 +00002769 if( IgnorableOrderby(eDest) ){
2770 pOrderBy = 0;
drh22827922000-06-06 17:27:05 +00002771 }
2772
drhd820cb12002-02-18 03:21:45 +00002773 /* Begin generating code.
2774 */
danielk19774adee202004-05-08 08:23:19 +00002775 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002776 if( v==0 ) goto select_end;
2777
drhe78e8282003-01-19 03:59:45 +00002778 /* Identify column names if we will be using them in a callback. This
2779 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002780 */
2781 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002782 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002783 }
2784
drhd820cb12002-02-18 03:21:45 +00002785 /* Generate code for all sub-queries in the FROM clause
2786 */
drh51522cd2005-01-20 13:36:19 +00002787#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
drhad3cab52002-05-24 02:04:32 +00002788 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002789 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002790 int needRestoreContext;
drh13449892005-09-07 21:22:45 +00002791 struct SrcList_item *pItem = &pTabList->a[i];
drhc31c2eb2003-05-02 16:04:17 +00002792
drh13449892005-09-07 21:22:45 +00002793 if( pItem->pSelect==0 ) continue;
2794 if( pItem->zName!=0 ){
drh5cf590c2003-04-24 01:45:04 +00002795 zSavedAuthContext = pParse->zAuthContext;
drh13449892005-09-07 21:22:45 +00002796 pParse->zAuthContext = pItem->zName;
drhc31c2eb2003-05-02 16:04:17 +00002797 needRestoreContext = 1;
2798 }else{
2799 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002800 }
drh9d2985c2005-09-08 01:58:42 +00002801 sqlite3Select(pParse, pItem->pSelect, SRT_VirtualTab,
drh13449892005-09-07 21:22:45 +00002802 pItem->iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002803 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002804 pParse->zAuthContext = zSavedAuthContext;
2805 }
drh1b2e0322002-03-03 02:49:51 +00002806 pTabList = p->pSrc;
2807 pWhere = p->pWhere;
drh13449892005-09-07 21:22:45 +00002808 if( !IgnorableOrderby(eDest) ){
drhacd4c692002-03-07 02:02:51 +00002809 pOrderBy = p->pOrderBy;
2810 }
drh1b2e0322002-03-03 02:49:51 +00002811 pGroupBy = p->pGroupBy;
2812 pHaving = p->pHaving;
2813 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002814 }
drh51522cd2005-01-20 13:36:19 +00002815#endif
drhd820cb12002-02-18 03:21:45 +00002816
drh6e175292004-03-13 14:00:36 +00002817 /* Check for the special case of a min() or max() function by itself
2818 ** in the result set.
2819 */
2820 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2821 rc = 0;
2822 goto select_end;
2823 }
2824
drh832508b2002-03-02 17:04:07 +00002825 /* Check to see if this is a subquery that can be "flattened" into its parent.
2826 ** If flattening is a possiblity, do so and return immediately.
2827 */
drhb7f91642004-10-31 02:22:47 +00002828#ifndef SQLITE_OMIT_VIEW
drh1b2e0322002-03-03 02:49:51 +00002829 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002830 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002831 if( isAgg ) *pParentAgg = 1;
danielk1977b3bce662005-01-29 08:32:43 +00002832 goto select_end;
drh832508b2002-03-02 17:04:07 +00002833 }
drhb7f91642004-10-31 02:22:47 +00002834#endif
drh832508b2002-03-02 17:04:07 +00002835
danielk19777cedc8d2004-06-10 10:50:08 +00002836 /* If there is an ORDER BY clause, resolve any collation sequences
drh9d2985c2005-09-08 01:58:42 +00002837 ** names that have been explicitly specified and create a sorting index.
2838 **
2839 ** This sorting index might end up being unused if the data can be
2840 ** extracted in pre-sorted order. If that is the case, then the
2841 ** OP_OpenVirtual instruction will be changed to an OP_Noop once
2842 ** we figure out that the sorting index is not needed. The addrSortIndex
2843 ** variable is used to facilitate that change.
danielk19777cedc8d2004-06-10 10:50:08 +00002844 */
2845 if( pOrderBy ){
drh5d9a4af2005-08-30 00:54:01 +00002846 struct ExprList_item *pTerm;
drh0342b1f2005-09-01 03:07:44 +00002847 KeyInfo *pKeyInfo;
drh5d9a4af2005-08-30 00:54:01 +00002848 for(i=0, pTerm=pOrderBy->a; i<pOrderBy->nExpr; i++, pTerm++){
2849 if( pTerm->zName ){
2850 pTerm->pExpr->pColl = sqlite3LocateCollSeq(pParse, pTerm->zName, -1);
danielk19777cedc8d2004-06-10 10:50:08 +00002851 }
2852 }
2853 if( pParse->nErr ){
2854 goto select_end;
2855 }
drh0342b1f2005-09-01 03:07:44 +00002856 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
drh9d2985c2005-09-08 01:58:42 +00002857 pOrderBy->iECursor = pParse->nTab++;
2858 p->addrOpenVirt[2] = addrSortIndex =
2859 sqlite3VdbeOp3(v, OP_OpenVirtual, pOrderBy->iECursor, pOrderBy->nExpr+2,
drh0342b1f2005-09-01 03:07:44 +00002860 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drh9d2985c2005-09-08 01:58:42 +00002861 }else{
2862 addrSortIndex = -1;
danielk19777cedc8d2004-06-10 10:50:08 +00002863 }
2864
drh7b58dae2003-07-20 01:16:46 +00002865 /* Set the limiter.
2866 */
drhec7429a2005-10-06 16:53:14 +00002867 iEnd = sqlite3VdbeMakeLabel(v);
2868 computeLimitRegisters(pParse, p, iEnd);
drh7b58dae2003-07-20 01:16:46 +00002869
drh2d0794e2002-03-03 03:03:52 +00002870 /* If the output is destined for a temporary table, open that table.
2871 */
drh9d2985c2005-09-08 01:58:42 +00002872 if( eDest==SRT_VirtualTab ){
drh0342b1f2005-09-01 03:07:44 +00002873 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002874 }
2875
drhdece1a82005-08-31 18:20:00 +00002876 /* Open a virtual index to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002877 */
drh19a775c2000-06-05 18:54:46 +00002878 if( isDistinct ){
drh0342b1f2005-09-01 03:07:44 +00002879 KeyInfo *pKeyInfo;
drh832508b2002-03-02 17:04:07 +00002880 distinct = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00002881 pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
2882 sqlite3VdbeOp3(v, OP_OpenVirtual, distinct, 0,
2883 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drh832508b2002-03-02 17:04:07 +00002884 }else{
2885 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002886 }
drh832508b2002-03-02 17:04:07 +00002887
drh13449892005-09-07 21:22:45 +00002888 /* Aggregate and non-aggregate queries are handled differently */
2889 if( !isAgg && pGroupBy==0 ){
2890 /* This case is for non-aggregate queries
2891 ** Begin the database scan
2892 */
2893 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
2894 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002895
drh9d2985c2005-09-08 01:58:42 +00002896 /* If sorting index that was created by a prior OP_OpenVirtual
2897 ** instruction ended up not being needed, then change the OP_OpenVirtual
2898 ** into an OP_Noop.
2899 */
2900 if( addrSortIndex>=0 && pOrderBy==0 ){
2901 uncreateSortingIndex(pParse, addrSortIndex);
2902 p->addrOpenVirt[2] = -1;
2903 }
2904
drh13449892005-09-07 21:22:45 +00002905 /* Use the standard inner loop
2906 */
drhdf199a22002-06-14 22:38:41 +00002907 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002908 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002909 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002910 }
drhefb72512000-05-31 20:00:52 +00002911
drh13449892005-09-07 21:22:45 +00002912 /* End the database scan loop.
2913 */
2914 sqlite3WhereEnd(pWInfo);
2915 }else{
2916 /* This is the processing for aggregate queries */
2917 NameContext sNC; /* Name context for processing aggregate information */
2918 int iAMem; /* First Mem address for storing current GROUP BY */
2919 int iBMem; /* First Mem address for previous GROUP BY */
2920 int iUseFlag; /* Mem address holding flag indicating that at least
2921 ** one row of the input to the aggregator has been
2922 ** processed */
2923 int iAbortFlag; /* Mem address which causes query abort if positive */
2924 int groupBySort; /* Rows come from source in GROUP BY order */
drhcce7d172000-05-31 15:34:51 +00002925
drhcce7d172000-05-31 15:34:51 +00002926
drh13449892005-09-07 21:22:45 +00002927 /* The following variables hold addresses or labels for parts of the
2928 ** virtual machine program we are putting together */
2929 int addrOutputRow; /* Start of subroutine that outputs a result row */
2930 int addrSetAbort; /* Set the abort flag and return */
2931 int addrInitializeLoop; /* Start of code that initializes the input loop */
2932 int addrTopOfLoop; /* Top of the input loop */
2933 int addrGroupByChange; /* Code that runs when any GROUP BY term changes */
2934 int addrProcessRow; /* Code to process a single input row */
2935 int addrEnd; /* End of all processing */
2936 int addrSortingIdx; /* The OP_OpenVirtual for the sorting index */
drhe3133822005-09-20 13:11:59 +00002937 int addrReset; /* Subroutine for resetting the accumulator */
drh13449892005-09-07 21:22:45 +00002938
2939 addrEnd = sqlite3VdbeMakeLabel(v);
2940
2941 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
2942 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
2943 ** SELECT statement.
2944 */
2945 memset(&sNC, 0, sizeof(sNC));
2946 sNC.pParse = pParse;
2947 sNC.pSrcList = pTabList;
2948 sNC.pAggInfo = &sAggInfo;
2949 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
drh9d2985c2005-09-08 01:58:42 +00002950 sAggInfo.pGroupBy = pGroupBy;
drh13449892005-09-07 21:22:45 +00002951 if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
drh1d83f052002-02-17 00:30:36 +00002952 goto select_end;
drh22827922000-06-06 17:27:05 +00002953 }
drh13449892005-09-07 21:22:45 +00002954 if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
2955 goto select_end;
2956 }
2957 if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
2958 goto select_end;
2959 }
2960 sAggInfo.nAccumulator = sAggInfo.nColumn;
2961 for(i=0; i<sAggInfo.nFunc; i++){
2962 if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
2963 goto select_end;
2964 }
2965 }
danielk19779e128002006-01-18 16:51:35 +00002966 if( sqlite3MallocFailed() ) goto select_end;
drh13449892005-09-07 21:22:45 +00002967
2968 /* Processing for aggregates with GROUP BY is very different and
2969 ** much more complex tha aggregates without a GROUP BY.
2970 */
2971 if( pGroupBy ){
2972 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
2973
2974 /* Create labels that we will be needing
2975 */
2976
2977 addrInitializeLoop = sqlite3VdbeMakeLabel(v);
2978 addrGroupByChange = sqlite3VdbeMakeLabel(v);
2979 addrProcessRow = sqlite3VdbeMakeLabel(v);
2980
2981 /* If there is a GROUP BY clause we might need a sorting index to
2982 ** implement it. Allocate that sorting index now. If it turns out
2983 ** that we do not need it after all, the OpenVirtual instruction
2984 ** will be converted into a Noop.
2985 */
2986 sAggInfo.sortingIdx = pParse->nTab++;
2987 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
2988 addrSortingIdx =
2989 sqlite3VdbeOp3(v, OP_OpenVirtual, sAggInfo.sortingIdx,
2990 sAggInfo.nSortingColumn,
2991 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2992
2993 /* Initialize memory locations used by GROUP BY aggregate processing
2994 */
2995 iUseFlag = pParse->nMem++;
2996 iAbortFlag = pParse->nMem++;
2997 iAMem = pParse->nMem;
2998 pParse->nMem += pGroupBy->nExpr;
2999 iBMem = pParse->nMem;
3000 pParse->nMem += pGroupBy->nExpr;
drhd654be82005-09-20 17:42:23 +00003001 sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
drhde29e3e2005-09-20 18:13:23 +00003002 VdbeComment((v, "# clear abort flag"));
drhd654be82005-09-20 17:42:23 +00003003 sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
drhde29e3e2005-09-20 18:13:23 +00003004 VdbeComment((v, "# indicate accumulator empty"));
drh13449892005-09-07 21:22:45 +00003005 sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
3006
3007 /* Generate a subroutine that outputs a single row of the result
3008 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
3009 ** is less than or equal to zero, the subroutine is a no-op. If
3010 ** the processing calls for the query to abort, this subroutine
3011 ** increments the iAbortFlag memory location before returning in
3012 ** order to signal the caller to abort.
3013 */
3014 addrSetAbort = sqlite3VdbeCurrentAddr(v);
drhde29e3e2005-09-20 18:13:23 +00003015 sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag);
3016 VdbeComment((v, "# set abort flag"));
drh13449892005-09-07 21:22:45 +00003017 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
3018 addrOutputRow = sqlite3VdbeCurrentAddr(v);
3019 sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
drhde29e3e2005-09-20 18:13:23 +00003020 VdbeComment((v, "# Groupby result generator entry point"));
drh13449892005-09-07 21:22:45 +00003021 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
3022 finalizeAggFunctions(pParse, &sAggInfo);
3023 if( pHaving ){
3024 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
3025 }
3026 rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
3027 distinct, eDest, iParm,
3028 addrOutputRow+1, addrSetAbort, aff);
3029 if( rc ){
3030 goto select_end;
3031 }
3032 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
drhde29e3e2005-09-20 18:13:23 +00003033 VdbeComment((v, "# end groupby result generator"));
drh13449892005-09-07 21:22:45 +00003034
drhe3133822005-09-20 13:11:59 +00003035 /* Generate a subroutine that will reset the group-by accumulator
3036 */
3037 addrReset = sqlite3VdbeCurrentAddr(v);
3038 resetAccumulator(pParse, &sAggInfo);
3039 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
3040
drh13449892005-09-07 21:22:45 +00003041 /* Begin a loop that will extract all source rows in GROUP BY order.
3042 ** This might involve two separate loops with an OP_Sort in between, or
3043 ** it might be a single loop that uses an index to extract information
3044 ** in the right order to begin with.
3045 */
3046 sqlite3VdbeResolveLabel(v, addrInitializeLoop);
drhe3133822005-09-20 13:11:59 +00003047 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
drh13449892005-09-07 21:22:45 +00003048 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
drh5360ad32005-09-08 00:13:27 +00003049 if( pWInfo==0 ) goto select_end;
drh13449892005-09-07 21:22:45 +00003050 if( pGroupBy==0 ){
3051 /* The optimizer is able to deliver rows in group by order so
3052 ** we do not have to sort. The OP_OpenVirtual table will be
3053 ** cancelled later because we still need to use the pKeyInfo
3054 */
3055 pGroupBy = p->pGroupBy;
3056 groupBySort = 0;
3057 }else{
3058 /* Rows are coming out in undetermined order. We have to push
3059 ** each row into a sorting index, terminate the first loop,
3060 ** then loop over the sorting index in order to get the output
3061 ** in sorted order
3062 */
3063 groupBySort = 1;
3064 sqlite3ExprCodeExprList(pParse, pGroupBy);
3065 sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
3066 j = pGroupBy->nExpr+1;
3067 for(i=0; i<sAggInfo.nColumn; i++){
3068 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
3069 if( pCol->iSorterColumn<j ) continue;
3070 if( pCol->iColumn<0 ){
3071 sqlite3VdbeAddOp(v, OP_Rowid, pCol->iTable, 0);
3072 }else{
3073 sqlite3VdbeAddOp(v, OP_Column, pCol->iTable, pCol->iColumn);
3074 }
3075 j++;
3076 }
3077 sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
3078 sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
3079 sqlite3WhereEnd(pWInfo);
drh97571952005-09-08 12:57:28 +00003080 sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
drhde29e3e2005-09-20 18:13:23 +00003081 VdbeComment((v, "# GROUP BY sort"));
drh13449892005-09-07 21:22:45 +00003082 sAggInfo.useSortingIdx = 1;
3083 }
3084
3085 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
3086 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
3087 ** Then compare the current GROUP BY terms against the GROUP BY terms
3088 ** from the previous row currently stored in a0, a1, a2...
3089 */
3090 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
3091 for(j=0; j<pGroupBy->nExpr; j++){
3092 if( groupBySort ){
3093 sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
3094 }else{
3095 sAggInfo.directMode = 1;
3096 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
3097 }
3098 sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
3099 }
3100 for(j=pGroupBy->nExpr-1; j>=0; j--){
3101 if( j<pGroupBy->nExpr-1 ){
3102 sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
3103 }
3104 sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
3105 if( j==0 ){
drhe3133822005-09-20 13:11:59 +00003106 sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
drh13449892005-09-07 21:22:45 +00003107 }else{
drh4f686232005-09-20 13:55:18 +00003108 sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
drh13449892005-09-07 21:22:45 +00003109 }
3110 sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
3111 }
3112
3113 /* Generate code that runs whenever the GROUP BY changes.
3114 ** Change in the GROUP BY are detected by the previous code
3115 ** block. If there were no changes, this block is skipped.
3116 **
3117 ** This code copies current group by terms in b0,b1,b2,...
3118 ** over to a0,a1,a2. It then calls the output subroutine
3119 ** and resets the aggregate accumulator registers in preparation
3120 ** for the next GROUP BY batch.
3121 */
3122 sqlite3VdbeResolveLabel(v, addrGroupByChange);
3123 for(j=0; j<pGroupBy->nExpr; j++){
drhd654be82005-09-20 17:42:23 +00003124 sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
drh13449892005-09-07 21:22:45 +00003125 }
3126 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
drhde29e3e2005-09-20 18:13:23 +00003127 VdbeComment((v, "# output one row"));
drh13449892005-09-07 21:22:45 +00003128 sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
drhde29e3e2005-09-20 18:13:23 +00003129 VdbeComment((v, "# check abort flag"));
drhe3133822005-09-20 13:11:59 +00003130 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
drhde29e3e2005-09-20 18:13:23 +00003131 VdbeComment((v, "# reset accumulator"));
drh13449892005-09-07 21:22:45 +00003132
3133 /* Update the aggregate accumulators based on the content of
3134 ** the current row
3135 */
3136 sqlite3VdbeResolveLabel(v, addrProcessRow);
3137 updateAccumulator(pParse, &sAggInfo);
drhde29e3e2005-09-20 18:13:23 +00003138 sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag);
3139 VdbeComment((v, "# indicate data in accumulator"));
drh13449892005-09-07 21:22:45 +00003140
3141 /* End of the loop
3142 */
3143 if( groupBySort ){
3144 sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
3145 }else{
3146 sqlite3WhereEnd(pWInfo);
3147 uncreateSortingIndex(pParse, addrSortingIdx);
3148 }
3149
3150 /* Output the final row of result
3151 */
3152 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
drhde29e3e2005-09-20 18:13:23 +00003153 VdbeComment((v, "# output final row"));
drh13449892005-09-07 21:22:45 +00003154
3155 } /* endif pGroupBy */
3156 else {
3157 /* This case runs if the aggregate has no GROUP BY clause. The
3158 ** processing is much simpler since there is only a single row
3159 ** of output.
3160 */
3161 resetAccumulator(pParse, &sAggInfo);
3162 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
drh5360ad32005-09-08 00:13:27 +00003163 if( pWInfo==0 ) goto select_end;
drh13449892005-09-07 21:22:45 +00003164 updateAccumulator(pParse, &sAggInfo);
3165 sqlite3WhereEnd(pWInfo);
3166 finalizeAggFunctions(pParse, &sAggInfo);
3167 pOrderBy = 0;
drh5774b802005-09-07 22:48:16 +00003168 if( pHaving ){
3169 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
3170 }
drh13449892005-09-07 21:22:45 +00003171 selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
3172 eDest, iParm, addrEnd, addrEnd, aff);
3173 }
3174 sqlite3VdbeResolveLabel(v, addrEnd);
3175
3176 } /* endif aggregate query */
drh22827922000-06-06 17:27:05 +00003177
drhcce7d172000-05-31 15:34:51 +00003178 /* If there is an ORDER BY clause, then we need to sort the results
3179 ** and send them to the callback one by one.
3180 */
3181 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00003182 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00003183 }
drh6a535342001-10-19 16:44:56 +00003184
danielk197793758c82005-01-21 08:13:14 +00003185#ifndef SQLITE_OMIT_SUBQUERY
drhf620b4e2004-02-09 14:37:50 +00003186 /* If this was a subquery, we have now converted the subquery into a
3187 ** temporary table. So delete the subquery structure from the parent
3188 ** to prevent this subquery from being evaluated again and to force the
3189 ** the use of the temporary table.
3190 */
3191 if( pParent ){
3192 assert( pParent->pSrc->nSrc>parentTab );
3193 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00003194 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00003195 pParent->pSrc->a[parentTab].pSelect = 0;
3196 }
danielk197793758c82005-01-21 08:13:14 +00003197#endif
drhf620b4e2004-02-09 14:37:50 +00003198
drhec7429a2005-10-06 16:53:14 +00003199 /* Jump here to skip this query
3200 */
3201 sqlite3VdbeResolveLabel(v, iEnd);
3202
drh1d83f052002-02-17 00:30:36 +00003203 /* The SELECT was successfully coded. Set the return code to 0
3204 ** to indicate no errors.
3205 */
3206 rc = 0;
3207
3208 /* Control jumps to here if an error is encountered above, or upon
3209 ** successful coding of the SELECT.
3210 */
3211select_end:
drh13449892005-09-07 21:22:45 +00003212 sqliteFree(sAggInfo.aCol);
3213 sqliteFree(sAggInfo.aFunc);
drh1d83f052002-02-17 00:30:36 +00003214 return rc;
drhcce7d172000-05-31 15:34:51 +00003215}