blob: 8588235ed31931252f759f74604e37be261addf8 [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**
drhf0863fe2005-06-12 21:35:51 +000015** $Id: select.c,v 1.252 2005/06/12 21:35:52 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;
drhdaffd0e2001-04-11 14:28:42 +000063 }
drh9bb61fe2000-06-05 16:01:39 +000064 return pNew;
65}
66
67/*
drh01f3f252002-05-24 16:14:15 +000068** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
69** type of join. Return an integer constant that expresses that type
70** in terms of the following bit values:
71**
72** JT_INNER
73** JT_OUTER
74** JT_NATURAL
75** JT_LEFT
76** JT_RIGHT
77**
78** A full outer join is the combination of JT_LEFT and JT_RIGHT.
79**
80** If an illegal or unsupported join type is seen, then still return
81** a join type, but put an error in the pParse structure.
82*/
danielk19774adee202004-05-08 08:23:19 +000083int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
drh01f3f252002-05-24 16:14:15 +000084 int jointype = 0;
85 Token *apAll[3];
86 Token *p;
drh57196282004-10-06 15:41:16 +000087 static const struct {
drh01f3f252002-05-24 16:14:15 +000088 const char *zKeyword;
drh290c1942004-08-21 17:54:45 +000089 u8 nChar;
90 u8 code;
drh01f3f252002-05-24 16:14:15 +000091 } keywords[] = {
92 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000093 { "left", 4, JT_LEFT|JT_OUTER },
94 { "right", 5, JT_RIGHT|JT_OUTER },
95 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +000096 { "outer", 5, JT_OUTER },
97 { "inner", 5, JT_INNER },
98 { "cross", 5, JT_INNER },
99 };
100 int i, j;
101 apAll[0] = pA;
102 apAll[1] = pB;
103 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +0000104 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +0000105 p = apAll[i];
106 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
107 if( p->n==keywords[j].nChar
danielk19774adee202004-05-08 08:23:19 +0000108 && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
drh01f3f252002-05-24 16:14:15 +0000109 jointype |= keywords[j].code;
110 break;
111 }
112 }
113 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
114 jointype |= JT_ERROR;
115 break;
116 }
117 }
drhad2d8302002-05-24 20:31:36 +0000118 if(
119 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000120 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000121 ){
drhae29ffb2004-09-25 14:39:18 +0000122 const char *zSp1 = " ";
123 const char *zSp2 = " ";
124 if( pB==0 ){ zSp1++; }
125 if( pC==0 ){ zSp2++; }
126 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
127 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
drh01f3f252002-05-24 16:14:15 +0000128 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000129 }else if( jointype & JT_RIGHT ){
danielk19774adee202004-05-08 08:23:19 +0000130 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000131 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000132 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000133 }
134 return jointype;
135}
136
137/*
drhad2d8302002-05-24 20:31:36 +0000138** Return the index of a column in a table. Return -1 if the column
139** is not contained in the table.
140*/
141static int columnIndex(Table *pTab, const char *zCol){
142 int i;
143 for(i=0; i<pTab->nCol; i++){
danielk19774adee202004-05-08 08:23:19 +0000144 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
drhad2d8302002-05-24 20:31:36 +0000145 }
146 return -1;
147}
148
149/*
drh91bb0ee2004-09-01 03:06:34 +0000150** Set the value of a token to a '\000'-terminated string.
151*/
152static void setToken(Token *p, const char *z){
153 p->z = z;
154 p->n = strlen(z);
155 p->dyn = 0;
156}
157
158
159/*
drhad2d8302002-05-24 20:31:36 +0000160** Add a term to the WHERE expression in *ppExpr that requires the
161** zCol column to be equal in the two tables pTab1 and pTab2.
162*/
163static void addWhereTerm(
164 const char *zCol, /* Name of the column */
165 const Table *pTab1, /* First table */
drh030530d2005-01-18 17:40:04 +0000166 const char *zAlias1, /* Alias for first table. May be NULL */
drhad2d8302002-05-24 20:31:36 +0000167 const Table *pTab2, /* Second table */
drh030530d2005-01-18 17:40:04 +0000168 const char *zAlias2, /* Alias for second table. May be NULL */
drhad2d8302002-05-24 20:31:36 +0000169 Expr **ppExpr /* Add the equality term to this expression */
170){
171 Token dummy;
172 Expr *pE1a, *pE1b, *pE1c;
173 Expr *pE2a, *pE2b, *pE2c;
174 Expr *pE;
175
drh91bb0ee2004-09-01 03:06:34 +0000176 setToken(&dummy, zCol);
danielk19774adee202004-05-08 08:23:19 +0000177 pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy);
178 pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy);
drh030530d2005-01-18 17:40:04 +0000179 if( zAlias1==0 ){
180 zAlias1 = pTab1->zName;
181 }
182 setToken(&dummy, zAlias1);
danielk19774adee202004-05-08 08:23:19 +0000183 pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy);
drh030530d2005-01-18 17:40:04 +0000184 if( zAlias2==0 ){
185 zAlias2 = pTab2->zName;
186 }
187 setToken(&dummy, zAlias2);
danielk19774adee202004-05-08 08:23:19 +0000188 pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy);
189 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
190 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
191 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000192 ExprSetProperty(pE, EP_FromJoin);
drh91bb0ee2004-09-01 03:06:34 +0000193 *ppExpr = sqlite3ExprAnd(*ppExpr, pE);
drhad2d8302002-05-24 20:31:36 +0000194}
195
196/*
drh1f162302002-10-27 19:35:33 +0000197** Set the EP_FromJoin property on all terms of the given expression.
drh1cc093c2002-06-24 22:01:57 +0000198**
drhe78e8282003-01-19 03:59:45 +0000199** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000200** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000201** join restriction specified in the ON or USING clause and not a part
202** of the more general WHERE clause. These terms are moved over to the
203** WHERE clause during join processing but we need to remember that they
204** originated in the ON or USING clause.
drh1cc093c2002-06-24 22:01:57 +0000205*/
206static void setJoinExpr(Expr *p){
207 while( p ){
drh1f162302002-10-27 19:35:33 +0000208 ExprSetProperty(p, EP_FromJoin);
drh1cc093c2002-06-24 22:01:57 +0000209 setJoinExpr(p->pLeft);
210 p = p->pRight;
211 }
212}
213
214/*
drhad2d8302002-05-24 20:31:36 +0000215** This routine processes the join information for a SELECT statement.
216** ON and USING clauses are converted into extra terms of the WHERE clause.
217** NATURAL joins also create extra WHERE clause terms.
218**
drh91bb0ee2004-09-01 03:06:34 +0000219** The terms of a FROM clause are contained in the Select.pSrc structure.
220** The left most table is the first entry in Select.pSrc. The right-most
221** table is the last entry. The join operator is held in the entry to
222** the left. Thus entry 0 contains the join operator for the join between
223** entries 0 and 1. Any ON or USING clauses associated with the join are
224** also attached to the left entry.
225**
drhad2d8302002-05-24 20:31:36 +0000226** This routine returns the number of errors encountered.
227*/
228static int sqliteProcessJoin(Parse *pParse, Select *p){
drh91bb0ee2004-09-01 03:06:34 +0000229 SrcList *pSrc; /* All tables in the FROM clause */
230 int i, j; /* Loop counters */
231 struct SrcList_item *pLeft; /* Left table being joined */
232 struct SrcList_item *pRight; /* Right table being joined */
drhad2d8302002-05-24 20:31:36 +0000233
drh91bb0ee2004-09-01 03:06:34 +0000234 pSrc = p->pSrc;
235 pLeft = &pSrc->a[0];
236 pRight = &pLeft[1];
237 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
238 Table *pLeftTab = pLeft->pTab;
239 Table *pRightTab = pRight->pTab;
240
241 if( pLeftTab==0 || pRightTab==0 ) continue;
drhad2d8302002-05-24 20:31:36 +0000242
243 /* When the NATURAL keyword is present, add WHERE clause terms for
244 ** every column that the two tables have in common.
245 */
drh91bb0ee2004-09-01 03:06:34 +0000246 if( pLeft->jointype & JT_NATURAL ){
247 if( pLeft->pOn || pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000248 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000249 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000250 return 1;
251 }
drh91bb0ee2004-09-01 03:06:34 +0000252 for(j=0; j<pLeftTab->nCol; j++){
253 char *zName = pLeftTab->aCol[j].zName;
254 if( columnIndex(pRightTab, zName)>=0 ){
drh030530d2005-01-18 17:40:04 +0000255 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
256 pRightTab, pRight->zAlias, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000257 }
258 }
259 }
260
261 /* Disallow both ON and USING clauses in the same join
262 */
drh91bb0ee2004-09-01 03:06:34 +0000263 if( pLeft->pOn && pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000264 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
drhda93d232003-03-31 02:12:46 +0000265 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000266 return 1;
267 }
268
269 /* Add the ON clause to the end of the WHERE clause, connected by
drh91bb0ee2004-09-01 03:06:34 +0000270 ** an AND operator.
drhad2d8302002-05-24 20:31:36 +0000271 */
drh91bb0ee2004-09-01 03:06:34 +0000272 if( pLeft->pOn ){
273 setJoinExpr(pLeft->pOn);
274 p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn);
275 pLeft->pOn = 0;
drhad2d8302002-05-24 20:31:36 +0000276 }
277
278 /* Create extra terms on the WHERE clause for each column named
279 ** in the USING clause. Example: If the two tables to be joined are
280 ** A and B and the USING clause names X, Y, and Z, then add this
281 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
282 ** Report an error if any column mentioned in the USING clause is
283 ** not contained in both tables to be joined.
284 */
drh91bb0ee2004-09-01 03:06:34 +0000285 if( pLeft->pUsing ){
286 IdList *pList = pLeft->pUsing;
drhad2d8302002-05-24 20:31:36 +0000287 for(j=0; j<pList->nId; j++){
drh91bb0ee2004-09-01 03:06:34 +0000288 char *zName = pList->a[j].zName;
289 if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
danielk19774adee202004-05-08 08:23:19 +0000290 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
drh91bb0ee2004-09-01 03:06:34 +0000291 "not present in both tables", zName);
drhad2d8302002-05-24 20:31:36 +0000292 return 1;
293 }
drh030530d2005-01-18 17:40:04 +0000294 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
295 pRightTab, pRight->zAlias, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000296 }
297 }
298 }
299 return 0;
300}
301
302/*
drh9bb61fe2000-06-05 16:01:39 +0000303** Delete the given Select structure and all of its substructures.
304*/
danielk19774adee202004-05-08 08:23:19 +0000305void sqlite3SelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000306 if( p==0 ) return;
danielk19774adee202004-05-08 08:23:19 +0000307 sqlite3ExprListDelete(p->pEList);
308 sqlite3SrcListDelete(p->pSrc);
309 sqlite3ExprDelete(p->pWhere);
310 sqlite3ExprListDelete(p->pGroupBy);
311 sqlite3ExprDelete(p->pHaving);
312 sqlite3ExprListDelete(p->pOrderBy);
313 sqlite3SelectDelete(p->pPrior);
danielk1977a2dc3b12005-02-05 12:48:48 +0000314 sqlite3ExprDelete(p->pLimit);
315 sqlite3ExprDelete(p->pOffset);
drh9bb61fe2000-06-05 16:01:39 +0000316 sqliteFree(p);
317}
318
319/*
drhc926afb2002-06-20 03:38:26 +0000320** Insert code into "v" that will push the record on the top of the
321** stack into the sorter.
322*/
323static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
drhc926afb2002-06-20 03:38:26 +0000324 int i;
drhc926afb2002-06-20 03:38:26 +0000325 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000326 sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
drhc926afb2002-06-20 03:38:26 +0000327 }
danielk1977ededfd52004-06-17 07:53:01 +0000328 sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr, 0);
drhf0863fe2005-06-12 21:35:51 +0000329 sqlite3VdbeAddOp(v, OP_SortInsert, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000330}
331
332/*
drhea48eb22004-07-19 23:16:38 +0000333** Add code to implement the OFFSET and LIMIT
334*/
335static void codeLimiter(
drhbab39e12004-07-19 23:38:11 +0000336 Vdbe *v, /* Generate code into this VM */
drhea48eb22004-07-19 23:16:38 +0000337 Select *p, /* The SELECT statement being coded */
338 int iContinue, /* Jump here to skip the current record */
339 int iBreak, /* Jump here to end the loop */
340 int nPop /* Number of times to pop stack when jumping */
341){
drhea48eb22004-07-19 23:16:38 +0000342 if( p->iOffset>=0 ){
danielk1977a2dc3b12005-02-05 12:48:48 +0000343 int addr = sqlite3VdbeCurrentAddr(v) + 3;
drhea48eb22004-07-19 23:16:38 +0000344 if( nPop>0 ) addr++;
danielk1977a2dc3b12005-02-05 12:48:48 +0000345 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, 0);
346 sqlite3VdbeAddOp(v, OP_IfMemPos, p->iOffset, addr);
drhea48eb22004-07-19 23:16:38 +0000347 if( nPop>0 ){
348 sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
349 }
350 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000351 VdbeComment((v, "# skip OFFSET records"));
drhea48eb22004-07-19 23:16:38 +0000352 }
353 if( p->iLimit>=0 ){
354 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhad6d9462004-09-19 02:15:24 +0000355 VdbeComment((v, "# exit when LIMIT reached"));
drhea48eb22004-07-19 23:16:38 +0000356 }
357}
358
359/*
drh22827922000-06-06 17:27:05 +0000360** This routine generates the code for the inside of the inner loop
361** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000362**
drh38640e12002-07-05 21:42:36 +0000363** If srcTab and nColumn are both zero, then the pEList expressions
364** are evaluated in order to get the data for this row. If nColumn>0
365** then data is pulled from srcTab and pEList is used only to get the
366** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000367*/
368static int selectInnerLoop(
369 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000370 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000371 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000372 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000373 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000374 ExprList *pOrderBy, /* If not NULL, sort results using this key */
375 int distinct, /* If >=0, make sure results are distinct */
376 int eDest, /* How to dispose of the results */
377 int iParm, /* An argument to the disposal method */
378 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000379 int iBreak, /* Jump here to break out of the inner loop */
380 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000381){
382 Vdbe *v = pParse->pVdbe;
383 int i;
drhea48eb22004-07-19 23:16:38 +0000384 int hasDistinct; /* True if the DISTINCT keyword is present */
drh38640e12002-07-05 21:42:36 +0000385
drhdaffd0e2001-04-11 14:28:42 +0000386 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000387 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000388
drhdf199a22002-06-14 22:38:41 +0000389 /* If there was a LIMIT clause on the SELECT statement, then do the check
390 ** to see if this row should be output.
391 */
drhea48eb22004-07-19 23:16:38 +0000392 hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
393 if( pOrderBy==0 && !hasDistinct ){
drhbab39e12004-07-19 23:38:11 +0000394 codeLimiter(v, p, iContinue, iBreak, 0);
drhdf199a22002-06-14 22:38:41 +0000395 }
396
drh967e8b72000-06-21 13:59:10 +0000397 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000398 */
drh38640e12002-07-05 21:42:36 +0000399 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000400 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000401 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000402 }
drh38640e12002-07-05 21:42:36 +0000403 }else{
404 nColumn = pEList->nExpr;
405 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000406 sqlite3ExprCode(pParse, pEList->a[i].pExpr);
drh38640e12002-07-05 21:42:36 +0000407 }
drh22827922000-06-06 17:27:05 +0000408 }
409
drhdaffd0e2001-04-11 14:28:42 +0000410 /* If the DISTINCT keyword was present on the SELECT statement
411 ** and this row has been seen before, then do not make this row
412 ** part of the result.
drh22827922000-06-06 17:27:05 +0000413 */
drhea48eb22004-07-19 23:16:38 +0000414 if( hasDistinct ){
drh0bd1f4e2002-06-06 18:54:39 +0000415#if NULL_ALWAYS_DISTINCT
danielk19774adee202004-05-08 08:23:19 +0000416 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
drh0bd1f4e2002-06-06 18:54:39 +0000417#endif
danielk1977ededfd52004-06-17 07:53:01 +0000418 /* Deliberately leave the affinity string off of the following
419 ** OP_MakeRecord */
420 sqlite3VdbeAddOp(v, OP_MakeRecord, pEList->nExpr * -1, 0);
danielk19774adee202004-05-08 08:23:19 +0000421 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
422 sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
423 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000424 VdbeComment((v, "# skip indistinct records"));
drhf0863fe2005-06-12 21:35:51 +0000425 sqlite3VdbeAddOp(v, OP_IdxInsert, distinct, 0);
drhea48eb22004-07-19 23:16:38 +0000426 if( pOrderBy==0 ){
drhbab39e12004-07-19 23:38:11 +0000427 codeLimiter(v, p, iContinue, iBreak, nColumn);
drhea48eb22004-07-19 23:16:38 +0000428 }
drh22827922000-06-06 17:27:05 +0000429 }
drh82c3d632000-06-06 21:56:07 +0000430
drhc926afb2002-06-20 03:38:26 +0000431 switch( eDest ){
danielk19775338a5f2005-01-20 13:03:10 +0000432#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhc926afb2002-06-20 03:38:26 +0000433 /* In this mode, write each query result to the key of the temporary
434 ** table iParm.
435 */
436 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000437 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000438 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
drhf0863fe2005-06-12 21:35:51 +0000439 sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000440 break;
drh22827922000-06-06 17:27:05 +0000441 }
drh22827922000-06-06 17:27:05 +0000442
drhc926afb2002-06-20 03:38:26 +0000443 /* Construct a record from the query result, but instead of
444 ** saving that record, use it as a key to delete elements from
445 ** the temporary table iParm.
446 */
447 case SRT_Except: {
448 int addr;
danielk19774adee202004-05-08 08:23:19 +0000449 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000450 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000451 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
452 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000453 break;
454 }
danielk19775338a5f2005-01-20 13:03:10 +0000455#endif
456
457 /* Store the result as data using a unique key.
458 */
459 case SRT_Table:
460 case SRT_TempTable: {
461 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
462 if( pOrderBy ){
463 pushOntoSorter(pParse, v, pOrderBy);
464 }else{
drhf0863fe2005-06-12 21:35:51 +0000465 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
danielk19775338a5f2005-01-20 13:03:10 +0000466 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhf0863fe2005-06-12 21:35:51 +0000467 sqlite3VdbeAddOp(v, OP_Insert, iParm, 0);
danielk19775338a5f2005-01-20 13:03:10 +0000468 }
469 break;
470 }
drh5974a302000-06-07 14:42:26 +0000471
danielk197793758c82005-01-21 08:13:14 +0000472#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000473 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
474 ** then there should be a single item on the stack. Write this
475 ** item into the set table with bogus data.
476 */
477 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000478 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000479 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000480
drhc926afb2002-06-20 03:38:26 +0000481 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000482 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
483 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
484 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000485 if( pOrderBy ){
486 pushOntoSorter(pParse, v, pOrderBy);
487 }else{
danielk1977e014a832004-05-17 10:48:57 +0000488 char aff = (iParm>>16)&0xFF;
489 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
drh94a11212004-09-25 13:12:14 +0000490 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1);
drhf0863fe2005-06-12 21:35:51 +0000491 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000492 }
danielk19774adee202004-05-08 08:23:19 +0000493 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000494 break;
495 }
drh22827922000-06-06 17:27:05 +0000496
drhc926afb2002-06-20 03:38:26 +0000497 /* If this is a scalar select that is part of an expression, then
498 ** store the results in the appropriate memory cell and break out
499 ** of the scan loop.
500 */
drh51522cd2005-01-20 13:36:19 +0000501 case SRT_Exists:
drhc926afb2002-06-20 03:38:26 +0000502 case SRT_Mem: {
503 assert( nColumn==1 );
504 if( pOrderBy ){
505 pushOntoSorter(pParse, v, pOrderBy);
506 }else{
danielk19774adee202004-05-08 08:23:19 +0000507 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
508 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000509 }
510 break;
511 }
danielk197793758c82005-01-21 08:13:14 +0000512#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
drh22827922000-06-06 17:27:05 +0000513
drhf46f9052002-06-22 02:33:38 +0000514 /* Send the data to the callback function.
515 */
516 case SRT_Callback:
517 case SRT_Sorter: {
518 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000519 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000520 pushOntoSorter(pParse, v, pOrderBy);
521 }else{
522 assert( eDest==SRT_Callback );
danielk19774adee202004-05-08 08:23:19 +0000523 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000524 }
525 break;
526 }
527
drh142e30d2002-08-28 03:00:58 +0000528 /* Invoke a subroutine to handle the results. The subroutine itself
529 ** is responsible for popping the results off of the stack.
530 */
531 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000532 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000533 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000534 pushOntoSorter(pParse, v, pOrderBy);
535 }else{
danielk19774adee202004-05-08 08:23:19 +0000536 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhac82fcf2002-09-08 17:23:41 +0000537 }
drh142e30d2002-08-28 03:00:58 +0000538 break;
539 }
540
danielk19776a67fe82005-02-04 04:07:16 +0000541#if !defined(SQLITE_OMIT_TRIGGER)
drhc926afb2002-06-20 03:38:26 +0000542 /* Discard the results. This is used for SELECT statements inside
543 ** the body of a TRIGGER. The purpose of such selects is to call
544 ** user-defined functions that have side effects. We do not care
545 ** about the actual results of the select.
546 */
drhc926afb2002-06-20 03:38:26 +0000547 default: {
drhf46f9052002-06-22 02:33:38 +0000548 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000549 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000550 break;
551 }
danielk197793758c82005-01-21 08:13:14 +0000552#endif
drh82c3d632000-06-06 21:56:07 +0000553 }
554 return 0;
555}
556
557/*
drhd8bc7082000-06-07 23:51:50 +0000558** If the inner loop was generated using a non-null pOrderBy argument,
559** then the results were placed in a sorter. After the loop is terminated
560** we need to run the sorter and output the results. The following
561** routine generates the code needed to do that.
562*/
drhc926afb2002-06-20 03:38:26 +0000563static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000564 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000565 Select *p, /* The SELECT statement */
566 Vdbe *v, /* Generate code into this VDBE */
567 int nColumn, /* Number of columns of data */
568 int eDest, /* Write the sorted results here */
569 int iParm /* Optional parameter associated with eDest */
570){
danielk19774adee202004-05-08 08:23:19 +0000571 int end1 = sqlite3VdbeMakeLabel(v);
572 int end2 = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000573 int addr;
drhffbc3082004-05-21 01:29:06 +0000574 KeyInfo *pInfo;
575 ExprList *pOrderBy;
576 int nCol, i;
drh9bb575f2004-09-06 17:24:11 +0000577 sqlite3 *db = pParse->db;
drhffbc3082004-05-21 01:29:06 +0000578
drhf46f9052002-06-22 02:33:38 +0000579 if( eDest==SRT_Sorter ) return;
drhffbc3082004-05-21 01:29:06 +0000580 pOrderBy = p->pOrderBy;
581 nCol = pOrderBy->nExpr;
582 pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
583 if( pInfo==0 ) return;
584 pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
585 pInfo->nField = nCol;
586 for(i=0; i<nCol; i++){
danielk19770202b292004-06-09 09:55:16 +0000587 /* If a collation sequence was specified explicity, then it
588 ** is stored in pOrderBy->a[i].zName. Otherwise, use the default
589 ** collation type for the expression.
590 */
danielk19777cedc8d2004-06-10 10:50:08 +0000591 pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr);
danielk19770202b292004-06-09 09:55:16 +0000592 if( !pInfo->aColl[i] ){
593 pInfo->aColl[i] = db->pDfltColl;
594 }
drhffbc3082004-05-21 01:29:06 +0000595 pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
596 }
597 sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
danielk19774adee202004-05-08 08:23:19 +0000598 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
drhbab39e12004-07-19 23:38:11 +0000599 codeLimiter(v, p, addr, end2, 1);
drhc926afb2002-06-20 03:38:26 +0000600 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000601 case SRT_Table:
602 case SRT_TempTable: {
drhf0863fe2005-06-12 21:35:51 +0000603 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
danielk19774adee202004-05-08 08:23:19 +0000604 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhf0863fe2005-06-12 21:35:51 +0000605 sqlite3VdbeAddOp(v, OP_Insert, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000606 break;
607 }
danielk197793758c82005-01-21 08:13:14 +0000608#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000609 case SRT_Set: {
610 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000611 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
612 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
613 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
danielk1977ededfd52004-06-17 07:53:01 +0000614 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
drhf0863fe2005-06-12 21:35:51 +0000615 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000616 break;
617 }
drh51522cd2005-01-20 13:36:19 +0000618 case SRT_Exists:
drhc926afb2002-06-20 03:38:26 +0000619 case SRT_Mem: {
620 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000621 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
622 sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
drhc926afb2002-06-20 03:38:26 +0000623 break;
624 }
danielk197793758c82005-01-21 08:13:14 +0000625#endif
drhce665cf2004-05-21 03:01:58 +0000626 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000627 case SRT_Subroutine: {
628 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000629 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
630 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000631 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000632 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000633 }
drhce665cf2004-05-21 03:01:58 +0000634 if( eDest==SRT_Callback ){
635 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
636 }else{
637 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
638 }
danielk197784ac9d02004-05-18 09:58:06 +0000639 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000640 break;
641 }
drhc926afb2002-06-20 03:38:26 +0000642 default: {
drhf46f9052002-06-22 02:33:38 +0000643 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000644 break;
645 }
646 }
danielk19774adee202004-05-08 08:23:19 +0000647 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
648 sqlite3VdbeResolveLabel(v, end2);
649 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
650 sqlite3VdbeResolveLabel(v, end1);
651 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000652}
653
654/*
danielk1977517eb642004-06-07 10:00:31 +0000655** Return a pointer to a string containing the 'declaration type' of the
656** expression pExpr. The string may be treated as static by the caller.
drhe78e8282003-01-19 03:59:45 +0000657**
danielk1977517eb642004-06-07 10:00:31 +0000658** If the declaration type is the exact datatype definition extracted from
659** the original CREATE TABLE statement if the expression is a column.
660**
661** The declaration type for an expression is either TEXT, NUMERIC or ANY.
662** The declaration type for a ROWID field is INTEGER.
663*/
danielk1977b3bce662005-01-29 08:32:43 +0000664static const char *columnType(NameContext *pNC, Expr *pExpr){
danielk197700e279d2004-06-21 07:36:32 +0000665 char const *zType;
danielk1977517eb642004-06-07 10:00:31 +0000666 int j;
danielk1977b3bce662005-01-29 08:32:43 +0000667 if( pExpr==0 || pNC->pSrcList==0 ) return 0;
danielk19775338a5f2005-01-20 13:03:10 +0000668
669 /* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING,
670 ** and LIMIT clauses. But pExpr originates in the result set of a
671 ** SELECT. So pExpr can never contain an AS operator.
672 */
673 assert( pExpr->op!=TK_AS );
674
danielk197700e279d2004-06-21 07:36:32 +0000675 switch( pExpr->op ){
676 case TK_COLUMN: {
danielk1977b3bce662005-01-29 08:32:43 +0000677 Table *pTab = 0;
danielk197700e279d2004-06-21 07:36:32 +0000678 int iCol = pExpr->iColumn;
danielk1977b3bce662005-01-29 08:32:43 +0000679 while( pNC && !pTab ){
680 SrcList *pTabList = pNC->pSrcList;
681 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
682 if( j<pTabList->nSrc ){
683 pTab = pTabList->a[j].pTab;
684 }else{
685 pNC = pNC->pNext;
686 }
687 }
drh7e627792005-04-29 02:10:00 +0000688 if( pTab==0 ){
689 /* FIX ME:
690 ** This can occurs if you have something like "SELECT new.x;" inside
691 ** a trigger. In other words, if you reference the special "new"
692 ** table in the result set of a select. We do not have a good way
693 ** to find the actual table type, so call it "TEXT". This is really
694 ** something of a bug, but I do not know how to fix it.
695 **
696 ** This code does not produce the correct answer - it just prevents
697 ** a segfault. See ticket #1229.
698 */
699 zType = "TEXT";
700 break;
701 }
danielk1977b3bce662005-01-29 08:32:43 +0000702 assert( pTab );
danielk197700e279d2004-06-21 07:36:32 +0000703 if( iCol<0 ) iCol = pTab->iPKey;
704 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
705 if( iCol<0 ){
706 zType = "INTEGER";
707 }else{
708 zType = pTab->aCol[iCol].zType;
709 }
710 break;
danielk1977517eb642004-06-07 10:00:31 +0000711 }
danielk197793758c82005-01-21 08:13:14 +0000712#ifndef SQLITE_OMIT_SUBQUERY
danielk197700e279d2004-06-21 07:36:32 +0000713 case TK_SELECT: {
danielk1977b3bce662005-01-29 08:32:43 +0000714 NameContext sNC;
danielk197700e279d2004-06-21 07:36:32 +0000715 Select *pS = pExpr->pSelect;
danielk1977b3bce662005-01-29 08:32:43 +0000716 sNC.pSrcList = pExpr->pSelect->pSrc;
717 sNC.pNext = pNC;
718 zType = columnType(&sNC, pS->pEList->a[0].pExpr);
danielk197700e279d2004-06-21 07:36:32 +0000719 break;
danielk1977517eb642004-06-07 10:00:31 +0000720 }
danielk197793758c82005-01-21 08:13:14 +0000721#endif
danielk197700e279d2004-06-21 07:36:32 +0000722 default:
723 zType = 0;
danielk1977517eb642004-06-07 10:00:31 +0000724 }
danielk197700e279d2004-06-21 07:36:32 +0000725
danielk1977517eb642004-06-07 10:00:31 +0000726 return zType;
727}
728
729/*
730** Generate code that will tell the VDBE the declaration types of columns
731** in the result set.
drhfcb78a42003-01-18 20:11:05 +0000732*/
733static void generateColumnTypes(
734 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000735 SrcList *pTabList, /* List of tables */
736 ExprList *pEList /* Expressions defining the result set */
737){
738 Vdbe *v = pParse->pVdbe;
danielk1977517eb642004-06-07 10:00:31 +0000739 int i;
danielk1977b3bce662005-01-29 08:32:43 +0000740 NameContext sNC;
741 sNC.pSrcList = pTabList;
drhfcb78a42003-01-18 20:11:05 +0000742 for(i=0; i<pEList->nExpr; i++){
743 Expr *p = pEList->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +0000744 const char *zType = columnType(&sNC, p);
danielk197700e279d2004-06-21 07:36:32 +0000745 if( zType==0 ) continue;
danielk1977fbcd5852004-06-15 02:44:18 +0000746 /* The vdbe must make it's own copy of the column-type, in case the
747 ** schema is reset before this virtual machine is deleted.
748 */
749 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
drhfcb78a42003-01-18 20:11:05 +0000750 }
751}
752
753/*
754** Generate code that will tell the VDBE the names of columns
755** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000756** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000757*/
drh832508b2002-03-02 17:04:07 +0000758static void generateColumnNames(
759 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000760 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000761 ExprList *pEList /* Expressions defining the result set */
762){
drhd8bc7082000-06-07 23:51:50 +0000763 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000764 int i, j;
drh9bb575f2004-09-06 17:24:11 +0000765 sqlite3 *db = pParse->db;
drhfcabd462004-02-20 14:50:58 +0000766 int fullNames, shortNames;
767
drhfe2093d2005-01-20 22:48:47 +0000768#ifndef SQLITE_OMIT_EXPLAIN
danielk19773cf86062004-05-26 10:11:05 +0000769 /* If this is an EXPLAIN, skip this step */
770 if( pParse->explain ){
danielk197761de0d12004-05-27 23:56:16 +0000771 return;
danielk19773cf86062004-05-26 10:11:05 +0000772 }
danielk19775338a5f2005-01-20 13:03:10 +0000773#endif
danielk19773cf86062004-05-26 10:11:05 +0000774
drhd6502752004-02-16 03:44:01 +0000775 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000776 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000777 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000778 fullNames = (db->flags & SQLITE_FullColNames)!=0;
779 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
danielk197722322fd2004-05-25 23:35:17 +0000780 sqlite3VdbeSetNumCols(v, pEList->nExpr);
drh82c3d632000-06-06 21:56:07 +0000781 for(i=0; i<pEList->nExpr; i++){
782 Expr *p;
drh5a387052003-01-11 14:19:51 +0000783 p = pEList->a[i].pExpr;
784 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000785 if( pEList->a[i].zName ){
786 char *zName = pEList->a[i].zName;
danielk1977d8123362004-06-12 09:25:12 +0000787 sqlite3VdbeSetColName(v, i, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000788 continue;
789 }
drhfa173a72002-07-10 21:26:00 +0000790 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000791 Table *pTab;
drh97665872002-02-13 23:22:53 +0000792 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000793 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000794 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
795 assert( j<pTabList->nSrc );
796 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000797 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000798 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000799 if( iCol<0 ){
drh47a6db22005-01-18 16:02:40 +0000800 zCol = "rowid";
drhb1363202002-06-26 02:45:03 +0000801 }else{
802 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000803 }
drhfcabd462004-02-20 14:50:58 +0000804 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000805 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
drhfcabd462004-02-20 14:50:58 +0000806 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000807 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000808 char *zTab;
809
drh6a3ea0e2003-05-02 14:32:12 +0000810 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000811 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000812 sqlite3SetString(&zName, zTab, ".", zCol, 0);
danielk19773cf86062004-05-26 10:11:05 +0000813 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000814 }else{
drh47a6db22005-01-18 16:02:40 +0000815 sqlite3VdbeSetColName(v, i, zCol, strlen(zCol));
drh82c3d632000-06-06 21:56:07 +0000816 }
drh6977fea2002-10-22 23:38:04 +0000817 }else if( p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000818 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
819 /* sqlite3VdbeCompressSpace(v, addr); */
drh1bee3d72001-10-15 00:44:35 +0000820 }else{
821 char zName[30];
822 assert( p->op!=TK_COLUMN || pTabList==0 );
823 sprintf(zName, "column%d", i+1);
danielk19773cf86062004-05-26 10:11:05 +0000824 sqlite3VdbeSetColName(v, i, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000825 }
826 }
danielk197776d505b2004-05-28 13:13:02 +0000827 generateColumnTypes(pParse, pTabList, pEList);
drh82c3d632000-06-06 21:56:07 +0000828}
829
danielk197793758c82005-01-21 08:13:14 +0000830#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +0000831/*
drhd8bc7082000-06-07 23:51:50 +0000832** Name of the connection operator, used for error messages.
833*/
834static const char *selectOpName(int id){
835 char *z;
836 switch( id ){
837 case TK_ALL: z = "UNION ALL"; break;
838 case TK_INTERSECT: z = "INTERSECT"; break;
839 case TK_EXCEPT: z = "EXCEPT"; break;
840 default: z = "UNION"; break;
841 }
842 return z;
843}
danielk197793758c82005-01-21 08:13:14 +0000844#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +0000845
846/*
drh315555c2002-10-20 15:53:03 +0000847** Forward declaration
848*/
drh9b3187e2005-01-18 14:45:47 +0000849static int prepSelectStmt(Parse*, Select*);
drh315555c2002-10-20 15:53:03 +0000850
851/*
drh22f70c32002-02-18 01:17:00 +0000852** Given a SELECT statement, generate a Table structure that describes
853** the result set of that SELECT.
854*/
danielk19774adee202004-05-08 08:23:19 +0000855Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000856 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000857 int i, j;
drh22f70c32002-02-18 01:17:00 +0000858 ExprList *pEList;
drh290c1942004-08-21 17:54:45 +0000859 Column *aCol, *pCol;
drh22f70c32002-02-18 01:17:00 +0000860
drh9b3187e2005-01-18 14:45:47 +0000861 if( prepSelectStmt(pParse, pSelect) ){
drh22f70c32002-02-18 01:17:00 +0000862 return 0;
863 }
danielk1977142bdf42005-01-30 11:11:44 +0000864 if( sqlite3SelectResolve(pParse, pSelect, 0) ){
865 return 0;
866 }
drh22f70c32002-02-18 01:17:00 +0000867 pTab = sqliteMalloc( sizeof(Table) );
868 if( pTab==0 ){
869 return 0;
870 }
drhed8a3bb2005-06-06 21:19:56 +0000871 pTab->nRef = 1;
drh22f70c32002-02-18 01:17:00 +0000872 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
873 pEList = pSelect->pEList;
874 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000875 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000876 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh290c1942004-08-21 17:54:45 +0000877 for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
drh79d5f632005-01-18 17:20:10 +0000878 Expr *p, *pR;
danielk1977517eb642004-06-07 10:00:31 +0000879 char *zType;
drh91bb0ee2004-09-01 03:06:34 +0000880 char *zName;
drh79d5f632005-01-18 17:20:10 +0000881 char *zBasename;
882 int cnt;
danielk1977b3bce662005-01-29 08:32:43 +0000883 NameContext sNC;
drh79d5f632005-01-18 17:20:10 +0000884
885 /* Get an appropriate name for the column
886 */
887 p = pEList->a[i].pExpr;
drh290c1942004-08-21 17:54:45 +0000888 assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
drh91bb0ee2004-09-01 03:06:34 +0000889 if( (zName = pEList->a[i].zName)!=0 ){
drh79d5f632005-01-18 17:20:10 +0000890 /* If the column contains an "AS <name>" phrase, use <name> as the name */
drh91bb0ee2004-09-01 03:06:34 +0000891 zName = sqliteStrDup(zName);
danielk1977517eb642004-06-07 10:00:31 +0000892 }else if( p->op==TK_DOT
drh79d5f632005-01-18 17:20:10 +0000893 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
894 /* For columns of the from A.B use B as the name */
drh91bb0ee2004-09-01 03:06:34 +0000895 zName = sqlite3MPrintf("%T", &pR->token);
drhb733d032004-01-24 20:18:12 +0000896 }else if( p->span.z && p->span.z[0] ){
drh79d5f632005-01-18 17:20:10 +0000897 /* Use the original text of the column expression as its name */
drh91bb0ee2004-09-01 03:06:34 +0000898 zName = sqlite3MPrintf("%T", &p->span);
drh22f70c32002-02-18 01:17:00 +0000899 }else{
drh79d5f632005-01-18 17:20:10 +0000900 /* If all else fails, make up a name */
drh91bb0ee2004-09-01 03:06:34 +0000901 zName = sqlite3MPrintf("column%d", i+1);
drh22f70c32002-02-18 01:17:00 +0000902 }
drh91bb0ee2004-09-01 03:06:34 +0000903 sqlite3Dequote(zName);
drhdd5b2fa2005-03-28 03:39:55 +0000904 if( sqlite3_malloc_failed ){
905 sqliteFree(zName);
906 sqlite3DeleteTable(0, pTab);
907 return 0;
908 }
drh79d5f632005-01-18 17:20:10 +0000909
910 /* Make sure the column name is unique. If the name is not unique,
911 ** append a integer to the name so that it becomes unique.
912 */
913 zBasename = zName;
914 for(j=cnt=0; j<i; j++){
915 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
916 zName = sqlite3MPrintf("%s:%d", zBasename, ++cnt);
917 j = -1;
drhdd5b2fa2005-03-28 03:39:55 +0000918 if( zName==0 ) break;
drh79d5f632005-01-18 17:20:10 +0000919 }
920 }
921 if( zBasename!=zName ){
922 sqliteFree(zBasename);
923 }
drh91bb0ee2004-09-01 03:06:34 +0000924 pCol->zName = zName;
danielk1977517eb642004-06-07 10:00:31 +0000925
drh79d5f632005-01-18 17:20:10 +0000926 /* Get the typename, type affinity, and collating sequence for the
927 ** column.
928 */
drhc43e8be2005-05-16 22:37:54 +0000929 memset(&sNC, 0, sizeof(sNC));
danielk1977b3bce662005-01-29 08:32:43 +0000930 sNC.pSrcList = pSelect->pSrc;
931 zType = sqliteStrDup(columnType(&sNC, p));
drh290c1942004-08-21 17:54:45 +0000932 pCol->zType = zType;
danielk1977c60e9b82005-01-31 12:42:29 +0000933 pCol->affinity = sqlite3ExprAffinity(p);
drh290c1942004-08-21 17:54:45 +0000934 pCol->pColl = sqlite3ExprCollSeq(pParse, p);
935 if( !pCol->pColl ){
936 pCol->pColl = pParse->db->pDfltColl;
danielk19770202b292004-06-09 09:55:16 +0000937 }
drh22f70c32002-02-18 01:17:00 +0000938 }
939 pTab->iPKey = -1;
940 return pTab;
941}
942
943/*
drh9b3187e2005-01-18 14:45:47 +0000944** Prepare a SELECT statement for processing by doing the following
945** things:
drhd8bc7082000-06-07 23:51:50 +0000946**
drh9b3187e2005-01-18 14:45:47 +0000947** (1) Make sure VDBE cursor numbers have been assigned to every
948** element of the FROM clause.
949**
950** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
951** defines FROM clause. When views appear in the FROM clause,
drh63eb5f22003-04-29 16:20:44 +0000952** fill pTabList->a[].pSelect with a copy of the SELECT statement
953** that implements the view. A copy is made of the view's SELECT
954** statement so that we can freely modify or delete that statement
955** without worrying about messing up the presistent representation
956** of the view.
drhd8bc7082000-06-07 23:51:50 +0000957**
drh9b3187e2005-01-18 14:45:47 +0000958** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
drhad2d8302002-05-24 20:31:36 +0000959** on joins and the ON and USING clause of joins.
960**
drh9b3187e2005-01-18 14:45:47 +0000961** (4) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000962** for instances of the "*" operator or the TABLE.* operator.
963** If found, expand each "*" to be every column in every table
964** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000965**
966** Return 0 on success. If there are problems, leave an error message
967** in pParse and return non-zero.
968*/
drh9b3187e2005-01-18 14:45:47 +0000969static int prepSelectStmt(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000970 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000971 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000972 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000973 Table *pTab;
drh290c1942004-08-21 17:54:45 +0000974 struct SrcList_item *pFrom;
drhdaffd0e2001-04-11 14:28:42 +0000975
danielk1977e94ddc92005-03-21 03:53:38 +0000976 if( p==0 || p->pSrc==0 || sqlite3_malloc_failed ) return 1;
drhdaffd0e2001-04-11 14:28:42 +0000977 pTabList = p->pSrc;
978 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000979
drh9b3187e2005-01-18 14:45:47 +0000980 /* Make sure cursor numbers have been assigned to all entries in
981 ** the FROM clause of the SELECT statement.
982 */
983 sqlite3SrcListAssignCursors(pParse, p->pSrc);
984
985 /* Look up every table named in the FROM clause of the select. If
986 ** an entry of the FROM clause is a subquery instead of a table or view,
987 ** then create a transient table structure to describe the subquery.
drhd8bc7082000-06-07 23:51:50 +0000988 */
drh290c1942004-08-21 17:54:45 +0000989 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
drh9b3187e2005-01-18 14:45:47 +0000990 if( pFrom->pTab!=0 ){
991 /* This statement has already been prepared. There is no need
992 ** to go further. */
993 assert( i==0 );
drhd8bc7082000-06-07 23:51:50 +0000994 return 0;
995 }
drh290c1942004-08-21 17:54:45 +0000996 if( pFrom->zName==0 ){
danielk197793758c82005-01-21 08:13:14 +0000997#ifndef SQLITE_OMIT_SUBQUERY
drh22f70c32002-02-18 01:17:00 +0000998 /* A sub-query in the FROM clause of a SELECT */
drh290c1942004-08-21 17:54:45 +0000999 assert( pFrom->pSelect!=0 );
1000 if( pFrom->zAlias==0 ){
drh91bb0ee2004-09-01 03:06:34 +00001001 pFrom->zAlias =
1002 sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
drhad2d8302002-05-24 20:31:36 +00001003 }
drhed8a3bb2005-06-06 21:19:56 +00001004 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001005 pFrom->pTab = pTab =
1006 sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
drh22f70c32002-02-18 01:17:00 +00001007 if( pTab==0 ){
1008 return 1;
1009 }
drh5cf590c2003-04-24 01:45:04 +00001010 /* The isTransient flag indicates that the Table structure has been
1011 ** dynamically allocated and may be freed at any time. In other words,
1012 ** pTab is not pointing to a persistent table structure that defines
1013 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +00001014 pTab->isTransient = 1;
danielk197793758c82005-01-21 08:13:14 +00001015#endif
drh22f70c32002-02-18 01:17:00 +00001016 }else{
drha76b5df2002-02-23 02:32:10 +00001017 /* An ordinary table or view name in the FROM clause */
drhed8a3bb2005-06-06 21:19:56 +00001018 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001019 pFrom->pTab = pTab =
1020 sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
drha76b5df2002-02-23 02:32:10 +00001021 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +00001022 return 1;
1023 }
drhed8a3bb2005-06-06 21:19:56 +00001024 pTab->nRef++;
danielk197793758c82005-01-21 08:13:14 +00001025#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00001026 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +00001027 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +00001028 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +00001029 return 1;
1030 }
drh290c1942004-08-21 17:54:45 +00001031 /* If pFrom->pSelect!=0 it means we are dealing with a
drh63eb5f22003-04-29 16:20:44 +00001032 ** view within a view. The SELECT structure has already been
1033 ** copied by the outer view so we can skip the copy step here
1034 ** in the inner view.
1035 */
drh290c1942004-08-21 17:54:45 +00001036 if( pFrom->pSelect==0 ){
1037 pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +00001038 }
drha76b5df2002-02-23 02:32:10 +00001039 }
danielk197793758c82005-01-21 08:13:14 +00001040#endif
drhd8bc7082000-06-07 23:51:50 +00001041 }
1042 }
1043
drhad2d8302002-05-24 20:31:36 +00001044 /* Process NATURAL keywords, and ON and USING clauses of joins.
1045 */
1046 if( sqliteProcessJoin(pParse, p) ) return 1;
1047
drh7c917d12001-12-16 20:05:05 +00001048 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +00001049 ** all columns in all tables. And for every TABLE.* insert the names
1050 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +00001051 ** with the TK_ALL operator for each "*" that it found in the column list.
1052 ** The following code just has to locate the TK_ALL expressions and expand
1053 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +00001054 **
1055 ** The first loop just checks to see if there are any "*" operators
1056 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +00001057 */
drh7c917d12001-12-16 20:05:05 +00001058 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001059 Expr *pE = pEList->a[k].pExpr;
1060 if( pE->op==TK_ALL ) break;
1061 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
1062 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +00001063 }
drh54473222002-04-04 02:10:55 +00001064 rc = 0;
drh7c917d12001-12-16 20:05:05 +00001065 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +00001066 /*
1067 ** If we get here it means the result set contains one or more "*"
1068 ** operators that need to be expanded. Loop through each expression
1069 ** in the result set and expand them one by one.
1070 */
drh7c917d12001-12-16 20:05:05 +00001071 struct ExprList_item *a = pEList->a;
1072 ExprList *pNew = 0;
drhd70dc522005-06-06 16:34:33 +00001073 int flags = pParse->db->flags;
1074 int longNames = (flags & SQLITE_FullColNames)!=0 &&
1075 (flags & SQLITE_ShortColNames)==0;
1076
drh7c917d12001-12-16 20:05:05 +00001077 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001078 Expr *pE = a[k].pExpr;
1079 if( pE->op!=TK_ALL &&
1080 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
1081 /* This particular expression does not need to be expanded.
1082 */
danielk19774adee202004-05-08 08:23:19 +00001083 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001084 pNew->a[pNew->nExpr-1].zName = a[k].zName;
1085 a[k].pExpr = 0;
1086 a[k].zName = 0;
1087 }else{
drh54473222002-04-04 02:10:55 +00001088 /* This expression is a "*" or a "TABLE.*" and needs to be
1089 ** expanded. */
1090 int tableSeen = 0; /* Set to 1 when TABLE matches */
drhcf55b7a2004-07-20 01:45:19 +00001091 char *zTName; /* text of name of TABLE */
drh54473222002-04-04 02:10:55 +00001092 if( pE->op==TK_DOT && pE->pLeft ){
drhcf55b7a2004-07-20 01:45:19 +00001093 zTName = sqlite3NameFromToken(&pE->pLeft->token);
drh54473222002-04-04 02:10:55 +00001094 }else{
drhcf55b7a2004-07-20 01:45:19 +00001095 zTName = 0;
drh54473222002-04-04 02:10:55 +00001096 }
drh290c1942004-08-21 17:54:45 +00001097 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1098 Table *pTab = pFrom->pTab;
1099 char *zTabName = pFrom->zAlias;
drh54473222002-04-04 02:10:55 +00001100 if( zTabName==0 || zTabName[0]==0 ){
1101 zTabName = pTab->zName;
1102 }
drhcf55b7a2004-07-20 01:45:19 +00001103 if( zTName && (zTabName==0 || zTabName[0]==0 ||
1104 sqlite3StrICmp(zTName, zTabName)!=0) ){
drh54473222002-04-04 02:10:55 +00001105 continue;
1106 }
1107 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001108 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001109 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001110 char *zName = pTab->aCol[j].zName;
1111
drh91bb0ee2004-09-01 03:06:34 +00001112 if( i>0 ){
1113 struct SrcList_item *pLeft = &pTabList->a[i-1];
1114 if( (pLeft->jointype & JT_NATURAL)!=0 &&
1115 columnIndex(pLeft->pTab, zName)>=0 ){
1116 /* In a NATURAL join, omit the join columns from the
1117 ** table on the right */
1118 continue;
1119 }
1120 if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1121 /* In a join with a USING clause, omit columns in the
1122 ** using clause from the table on the right. */
1123 continue;
1124 }
drhad2d8302002-05-24 20:31:36 +00001125 }
danielk19774adee202004-05-08 08:23:19 +00001126 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001127 if( pRight==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001128 setToken(&pRight->token, zName);
drhd70dc522005-06-06 16:34:33 +00001129 if( zTabName && (longNames || pTabList->nSrc>1) ){
danielk19774adee202004-05-08 08:23:19 +00001130 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1131 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001132 if( pExpr==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001133 setToken(&pLeft->token, zTabName);
1134 setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
drh6977fea2002-10-22 23:38:04 +00001135 pExpr->span.dyn = 1;
1136 pExpr->token.z = 0;
1137 pExpr->token.n = 0;
1138 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001139 }else{
drh22f70c32002-02-18 01:17:00 +00001140 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001141 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001142 }
drhd70dc522005-06-06 16:34:33 +00001143 if( longNames ){
1144 pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span);
1145 }else{
1146 pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
1147 }
drh7c917d12001-12-16 20:05:05 +00001148 }
drh17e24df2001-11-06 14:10:41 +00001149 }
drh54473222002-04-04 02:10:55 +00001150 if( !tableSeen ){
drhcf55b7a2004-07-20 01:45:19 +00001151 if( zTName ){
1152 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
drhf5db2d32002-06-06 23:42:27 +00001153 }else{
danielk19774adee202004-05-08 08:23:19 +00001154 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001155 }
drh54473222002-04-04 02:10:55 +00001156 rc = 1;
1157 }
drhcf55b7a2004-07-20 01:45:19 +00001158 sqliteFree(zTName);
drhd8bc7082000-06-07 23:51:50 +00001159 }
1160 }
danielk19774adee202004-05-08 08:23:19 +00001161 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001162 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001163 }
drh54473222002-04-04 02:10:55 +00001164 return rc;
drhd8bc7082000-06-07 23:51:50 +00001165}
1166
danielk197793758c82005-01-21 08:13:14 +00001167#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhff78bd22002-02-27 01:47:11 +00001168/*
drhd8bc7082000-06-07 23:51:50 +00001169** This routine associates entries in an ORDER BY expression list with
1170** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001171** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001172** the top-level node is filled in with column number and the iTable
1173** value of the top-level node is filled with iTable parameter.
1174**
1175** If there are prior SELECT clauses, they are processed first. A match
1176** in an earlier SELECT takes precedence over a later SELECT.
1177**
1178** Any entry that does not match is flagged as an error. The number
1179** of errors is returned.
1180*/
1181static int matchOrderbyToColumn(
1182 Parse *pParse, /* A place to leave error messages */
1183 Select *pSelect, /* Match to result columns of this SELECT */
1184 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001185 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001186 int mustComplete /* If TRUE all ORDER BYs must match */
1187){
1188 int nErr = 0;
1189 int i, j;
1190 ExprList *pEList;
1191
drhdaffd0e2001-04-11 14:28:42 +00001192 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001193 if( mustComplete ){
1194 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1195 }
drh9b3187e2005-01-18 14:45:47 +00001196 if( prepSelectStmt(pParse, pSelect) ){
drhd8bc7082000-06-07 23:51:50 +00001197 return 1;
1198 }
1199 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001200 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1201 return 1;
1202 }
drhd8bc7082000-06-07 23:51:50 +00001203 }
1204 pEList = pSelect->pEList;
1205 for(i=0; i<pOrderBy->nExpr; i++){
1206 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001207 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001208 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001209 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001210 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001211 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001212 "ORDER BY position %d should be between 1 and %d",
1213 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001214 nErr++;
1215 break;
1216 }
drhfcb78a42003-01-18 20:11:05 +00001217 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001218 iCol--;
1219 }
1220 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001221 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001222 char *zName, *zLabel;
1223 zName = pEList->a[j].zName;
drha99db3b2004-06-19 14:49:12 +00001224 zLabel = sqlite3NameFromToken(&pE->token);
1225 assert( zLabel!=0 );
danielk19774adee202004-05-08 08:23:19 +00001226 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001227 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001228 }
drh6e142f52000-06-08 13:36:40 +00001229 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001230 }
danielk19774adee202004-05-08 08:23:19 +00001231 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001232 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001233 }
1234 }
drhe4de1fe2002-06-02 16:09:01 +00001235 if( iCol>=0 ){
1236 pE->op = TK_COLUMN;
1237 pE->iColumn = iCol;
1238 pE->iTable = iTable;
danielk1977a58fdfb2005-02-08 07:50:40 +00001239 pE->iAgg = -1;
drhe4de1fe2002-06-02 16:09:01 +00001240 pOrderBy->a[i].done = 1;
1241 }
1242 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001243 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001244 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001245 nErr++;
1246 break;
1247 }
1248 }
1249 return nErr;
1250}
danielk197793758c82005-01-21 08:13:14 +00001251#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +00001252
1253/*
1254** Get a VDBE for the given parser context. Create a new one if necessary.
1255** If an error occurs, return NULL and leave a message in pParse.
1256*/
danielk19774adee202004-05-08 08:23:19 +00001257Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001258 Vdbe *v = pParse->pVdbe;
1259 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001260 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001261 }
drhd8bc7082000-06-07 23:51:50 +00001262 return v;
1263}
drhfcb78a42003-01-18 20:11:05 +00001264
drhd8bc7082000-06-07 23:51:50 +00001265/*
drh7b58dae2003-07-20 01:16:46 +00001266** Compute the iLimit and iOffset fields of the SELECT based on the
danielk1977a2dc3b12005-02-05 12:48:48 +00001267** pLimit and pOffset expressions. nLimit and nOffset hold the expressions
drh7b58dae2003-07-20 01:16:46 +00001268** that appear in the original SQL statement after the LIMIT and OFFSET
danielk1977a2dc3b12005-02-05 12:48:48 +00001269** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
1270** are the integer memory register numbers for counters used to compute
1271** the limit and offset. If there is no limit and/or offset, then
1272** iLimit and iOffset are negative.
drh7b58dae2003-07-20 01:16:46 +00001273**
1274** This routine changes the values if iLimit and iOffset only if
1275** a limit or offset is defined by nLimit and nOffset. iLimit and
1276** iOffset should have been preset to appropriate default values
1277** (usually but not always -1) prior to calling this routine.
1278** Only if nLimit>=0 or nOffset>0 do the limit registers get
1279** redefined. The UNION ALL operator uses this property to force
1280** the reuse of the same limit and offset registers across multiple
1281** SELECT statements.
1282*/
1283static void computeLimitRegisters(Parse *pParse, Select *p){
1284 /*
drh7b58dae2003-07-20 01:16:46 +00001285 ** "LIMIT -1" always shows all rows. There is some
1286 ** contraversy about what the correct behavior should be.
1287 ** The current implementation interprets "LIMIT 0" to mean
1288 ** no rows.
1289 */
danielk1977a2dc3b12005-02-05 12:48:48 +00001290 if( p->pLimit ){
drh7b58dae2003-07-20 01:16:46 +00001291 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001292 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001293 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001294 sqlite3ExprCode(pParse, p->pLimit);
1295 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1296 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001297 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001298 VdbeComment((v, "# LIMIT counter"));
drh7b58dae2003-07-20 01:16:46 +00001299 p->iLimit = iMem;
1300 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001301 if( p->pOffset ){
drh7b58dae2003-07-20 01:16:46 +00001302 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001303 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001304 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001305 sqlite3ExprCode(pParse, p->pOffset);
1306 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1307 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001308 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001309 VdbeComment((v, "# OFFSET counter"));
drh7b58dae2003-07-20 01:16:46 +00001310 p->iOffset = iMem;
1311 }
1312}
1313
1314/*
drhd3d39e92004-05-20 22:16:29 +00001315** Generate VDBE instructions that will open a transient table that
1316** will be used for an index or to store keyed results for a compound
1317** select. In other words, open a transient table that needs a
1318** KeyInfo structure. The number of columns in the KeyInfo is determined
1319** by the result set of the SELECT statement in the second argument.
1320**
danielk1977dc1bdc42004-06-11 10:51:27 +00001321** Specifically, this routine is called to open an index table for
1322** DISTINCT, UNION, INTERSECT and EXCEPT select statements (but not
1323** UNION ALL).
1324**
danielk1977dc1bdc42004-06-11 10:51:27 +00001325** The value returned is the address of the OP_OpenTemp instruction.
drhd3d39e92004-05-20 22:16:29 +00001326*/
drhf0863fe2005-06-12 21:35:51 +00001327static int openTempIndex(Parse *pParse, Select *p, int iTab){
drhd3d39e92004-05-20 22:16:29 +00001328 KeyInfo *pKeyInfo;
drh736c22b2004-05-21 02:14:24 +00001329 int nColumn;
drh9bb575f2004-09-06 17:24:11 +00001330 sqlite3 *db = pParse->db;
drhd3d39e92004-05-20 22:16:29 +00001331 int i;
1332 Vdbe *v = pParse->pVdbe;
danielk1977dc1bdc42004-06-11 10:51:27 +00001333 int addr;
drhd3d39e92004-05-20 22:16:29 +00001334
drh9b3187e2005-01-18 14:45:47 +00001335 if( prepSelectStmt(pParse, p) ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001336 return 0;
drh736c22b2004-05-21 02:14:24 +00001337 }
1338 nColumn = p->pEList->nExpr;
drhd3d39e92004-05-20 22:16:29 +00001339 pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
danielk1977dc1bdc42004-06-11 10:51:27 +00001340 if( pKeyInfo==0 ) return 0;
drh91bb0ee2004-09-01 03:06:34 +00001341 pKeyInfo->enc = db->enc;
drhd3d39e92004-05-20 22:16:29 +00001342 pKeyInfo->nField = nColumn;
1343 for(i=0; i<nColumn; i++){
danielk1977dc1bdc42004-06-11 10:51:27 +00001344 pKeyInfo->aColl[i] = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
1345 if( !pKeyInfo->aColl[i] ){
1346 pKeyInfo->aColl[i] = db->pDfltColl;
1347 }
drhd3d39e92004-05-20 22:16:29 +00001348 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001349 addr = sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0,
1350 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
danielk1977dc1bdc42004-06-11 10:51:27 +00001351 return addr;
1352}
1353
drhb7f91642004-10-31 02:22:47 +00001354#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001355/*
drh8cdbf832004-08-29 16:25:03 +00001356** Add the address "addr" to the set of all OpenTemp opcode addresses
1357** that are being accumulated in p->ppOpenTemp.
drhfbc4ee72004-08-29 01:31:05 +00001358*/
drh8cdbf832004-08-29 16:25:03 +00001359static int multiSelectOpenTempAddr(Select *p, int addr){
1360 IdList *pList = *p->ppOpenTemp = sqlite3IdListAppend(*p->ppOpenTemp, 0);
drhfbc4ee72004-08-29 01:31:05 +00001361 if( pList==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001362 return SQLITE_NOMEM;
1363 }
drhfbc4ee72004-08-29 01:31:05 +00001364 pList->a[pList->nId-1].idx = addr;
danielk1977dc1bdc42004-06-11 10:51:27 +00001365 return SQLITE_OK;
1366}
drhb7f91642004-10-31 02:22:47 +00001367#endif /* SQLITE_OMIT_COMPOUND_SELECT */
danielk1977dc1bdc42004-06-11 10:51:27 +00001368
drhb7f91642004-10-31 02:22:47 +00001369#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001370/*
1371** Return the appropriate collating sequence for the iCol-th column of
1372** the result set for the compound-select statement "p". Return NULL if
1373** the column has no default collating sequence.
1374**
1375** The collating sequence for the compound select is taken from the
1376** left-most term of the select that has a collating sequence.
1377*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001378static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
drhfbc4ee72004-08-29 01:31:05 +00001379 CollSeq *pRet;
danielk1977dc1bdc42004-06-11 10:51:27 +00001380 if( p->pPrior ){
1381 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
drhfbc4ee72004-08-29 01:31:05 +00001382 }else{
1383 pRet = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001384 }
drhfbc4ee72004-08-29 01:31:05 +00001385 if( pRet==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001386 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1387 }
1388 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001389}
drhb7f91642004-10-31 02:22:47 +00001390#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd3d39e92004-05-20 22:16:29 +00001391
drhb7f91642004-10-31 02:22:47 +00001392#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhd3d39e92004-05-20 22:16:29 +00001393/*
drh82c3d632000-06-06 21:56:07 +00001394** This routine is called to process a query that is really the union
1395** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001396**
drhe78e8282003-01-19 03:59:45 +00001397** "p" points to the right-most of the two queries. the query on the
1398** left is p->pPrior. The left query could also be a compound query
1399** in which case this routine will be called recursively.
1400**
1401** The results of the total query are to be written into a destination
1402** of type eDest with parameter iParm.
1403**
1404** Example 1: Consider a three-way compound SQL statement.
1405**
1406** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1407**
1408** This statement is parsed up as follows:
1409**
1410** SELECT c FROM t3
1411** |
1412** `-----> SELECT b FROM t2
1413** |
jplyon4b11c6d2004-01-19 04:57:53 +00001414** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001415**
1416** The arrows in the diagram above represent the Select.pPrior pointer.
1417** So if this routine is called with p equal to the t3 query, then
1418** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1419**
1420** Notice that because of the way SQLite parses compound SELECTs, the
1421** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001422*/
danielk197784ac9d02004-05-18 09:58:06 +00001423static int multiSelect(
drhfbc4ee72004-08-29 01:31:05 +00001424 Parse *pParse, /* Parsing context */
1425 Select *p, /* The right-most of SELECTs to be coded */
1426 int eDest, /* \___ Store query results as specified */
1427 int iParm, /* / by these two parameters. */
1428 char *aff /* If eDest is SRT_Union, the affinity string */
danielk197784ac9d02004-05-18 09:58:06 +00001429){
drhfbc4ee72004-08-29 01:31:05 +00001430 int rc = SQLITE_OK; /* Success code from a subroutine */
1431 Select *pPrior; /* Another SELECT immediately to our left */
1432 Vdbe *v; /* Generate code to this VDBE */
1433 IdList *pOpenTemp = 0;/* OP_OpenTemp opcodes that need a KeyInfo */
drh8cdbf832004-08-29 16:25:03 +00001434 int aAddr[5]; /* Addresses of SetNumColumns operators */
1435 int nAddr = 0; /* Number used */
1436 int nCol; /* Number of columns in the result set */
drh82c3d632000-06-06 21:56:07 +00001437
drh7b58dae2003-07-20 01:16:46 +00001438 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
drhfbc4ee72004-08-29 01:31:05 +00001439 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001440 */
danielk197784ac9d02004-05-18 09:58:06 +00001441 if( p==0 || p->pPrior==0 ){
1442 rc = 1;
1443 goto multi_select_end;
1444 }
drhd8bc7082000-06-07 23:51:50 +00001445 pPrior = p->pPrior;
1446 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001447 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001448 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001449 rc = 1;
1450 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001451 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001452 if( pPrior->pLimit ){
danielk19774adee202004-05-08 08:23:19 +00001453 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001454 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001455 rc = 1;
1456 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001457 }
drh82c3d632000-06-06 21:56:07 +00001458
drhd8bc7082000-06-07 23:51:50 +00001459 /* Make sure we have a valid query engine. If not, create a new one.
1460 */
danielk19774adee202004-05-08 08:23:19 +00001461 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001462 if( v==0 ){
1463 rc = 1;
1464 goto multi_select_end;
1465 }
drhd8bc7082000-06-07 23:51:50 +00001466
drh8cdbf832004-08-29 16:25:03 +00001467 /* If *p this is the right-most select statement, then initialize
1468 ** p->ppOpenTemp to point to pOpenTemp. If *p is not the right most
1469 ** statement then p->ppOpenTemp will have already been initialized
1470 ** by a prior call to this same procedure. Pass along the pOpenTemp
1471 ** pointer to pPrior, the next statement to our left.
drhfbc4ee72004-08-29 01:31:05 +00001472 */
1473 if( p->ppOpenTemp==0 ){
1474 p->ppOpenTemp = &pOpenTemp;
1475 }
1476 pPrior->ppOpenTemp = p->ppOpenTemp;
1477
drh1cc3d752002-03-23 00:31:29 +00001478 /* Create the destination temporary table if necessary
1479 */
1480 if( eDest==SRT_TempTable ){
danielk1977b4964b72004-05-18 01:23:38 +00001481 assert( p->pEList );
danielk19774adee202004-05-08 08:23:19 +00001482 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
drh8cdbf832004-08-29 16:25:03 +00001483 assert( nAddr==0 );
1484 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 0);
drh1cc3d752002-03-23 00:31:29 +00001485 eDest = SRT_Table;
1486 }
1487
drhf46f9052002-06-22 02:33:38 +00001488 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001489 */
drh82c3d632000-06-06 21:56:07 +00001490 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001491 case TK_ALL: {
1492 if( p->pOrderBy==0 ){
danielk1977a2dc3b12005-02-05 12:48:48 +00001493 assert( !pPrior->pLimit );
1494 pPrior->pLimit = p->pLimit;
1495 pPrior->pOffset = p->pOffset;
danielk1977b3bce662005-01-29 08:32:43 +00001496 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001497 if( rc ){
1498 goto multi_select_end;
1499 }
drhf46f9052002-06-22 02:33:38 +00001500 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001501 p->iLimit = pPrior->iLimit;
1502 p->iOffset = pPrior->iOffset;
danielk1977a2dc3b12005-02-05 12:48:48 +00001503 p->pLimit = 0;
1504 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001505 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001506 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001507 if( rc ){
1508 goto multi_select_end;
1509 }
drhf46f9052002-06-22 02:33:38 +00001510 break;
1511 }
1512 /* For UNION ALL ... ORDER BY fall through to the next case */
1513 }
drh82c3d632000-06-06 21:56:07 +00001514 case TK_EXCEPT:
1515 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001516 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001517 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001518 int priorOp; /* The SRT_ operation to apply to prior selects */
danielk1977a2dc3b12005-02-05 12:48:48 +00001519 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1520 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
danielk1977dc1bdc42004-06-11 10:51:27 +00001521 int addr;
drh82c3d632000-06-06 21:56:07 +00001522
drhd8bc7082000-06-07 23:51:50 +00001523 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
danielk1977a2dc3b12005-02-05 12:48:48 +00001524 if( eDest==priorOp && p->pOrderBy==0 && !p->pLimit && !p->pOffset ){
drhd8bc7082000-06-07 23:51:50 +00001525 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001526 ** right.
drhd8bc7082000-06-07 23:51:50 +00001527 */
drh82c3d632000-06-06 21:56:07 +00001528 unionTab = iParm;
1529 }else{
drhd8bc7082000-06-07 23:51:50 +00001530 /* We will need to create our own temporary table to hold the
1531 ** intermediate results.
1532 */
1533 unionTab = pParse->nTab++;
1534 if( p->pOrderBy
1535 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001536 rc = 1;
1537 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001538 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001539 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001540 if( p->op!=TK_ALL ){
drh8cdbf832004-08-29 16:25:03 +00001541 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001542 if( rc!=SQLITE_OK ){
1543 goto multi_select_end;
1544 }
drhd8bc7082000-06-07 23:51:50 +00001545 }
drh8cdbf832004-08-29 16:25:03 +00001546 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1547 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, 0);
danielk197784ac9d02004-05-18 09:58:06 +00001548 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001549 }
drhd8bc7082000-06-07 23:51:50 +00001550
1551 /* Code the SELECT statements to our left
1552 */
danielk1977b3bce662005-01-29 08:32:43 +00001553 assert( !pPrior->pOrderBy );
1554 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001555 if( rc ){
1556 goto multi_select_end;
1557 }
drhd8bc7082000-06-07 23:51:50 +00001558
1559 /* Code the current SELECT statement
1560 */
1561 switch( p->op ){
1562 case TK_EXCEPT: op = SRT_Except; break;
1563 case TK_UNION: op = SRT_Union; break;
1564 case TK_ALL: op = SRT_Table; break;
1565 }
drh82c3d632000-06-06 21:56:07 +00001566 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001567 pOrderBy = p->pOrderBy;
1568 p->pOrderBy = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001569 pLimit = p->pLimit;
1570 p->pLimit = 0;
1571 pOffset = p->pOffset;
1572 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001573 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001574 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001575 p->pOrderBy = pOrderBy;
danielk1977a2dc3b12005-02-05 12:48:48 +00001576 sqlite3ExprDelete(p->pLimit);
1577 p->pLimit = pLimit;
1578 p->pOffset = pOffset;
drhbe5fd492004-12-16 21:09:16 +00001579 p->iLimit = -1;
1580 p->iOffset = -1;
danielk197784ac9d02004-05-18 09:58:06 +00001581 if( rc ){
1582 goto multi_select_end;
1583 }
1584
drhd8bc7082000-06-07 23:51:50 +00001585
1586 /* Convert the data in the temporary table into whatever form
1587 ** it is that we currently need.
1588 */
drhc926afb2002-06-20 03:38:26 +00001589 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001590 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001591 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001592 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001593 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001594 }
danielk19774adee202004-05-08 08:23:19 +00001595 iBreak = sqlite3VdbeMakeLabel(v);
1596 iCont = sqlite3VdbeMakeLabel(v);
1597 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001598 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001599 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001600 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001601 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001602 iCont, iBreak, 0);
1603 if( rc ){
1604 rc = 1;
1605 goto multi_select_end;
1606 }
danielk19774adee202004-05-08 08:23:19 +00001607 sqlite3VdbeResolveLabel(v, iCont);
1608 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1609 sqlite3VdbeResolveLabel(v, iBreak);
1610 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001611 }
1612 break;
1613 }
1614 case TK_INTERSECT: {
1615 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001616 int iCont, iBreak, iStart;
danielk1977a2dc3b12005-02-05 12:48:48 +00001617 Expr *pLimit, *pOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001618 int addr;
drh82c3d632000-06-06 21:56:07 +00001619
drhd8bc7082000-06-07 23:51:50 +00001620 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001621 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001622 ** by allocating the tables we will need.
1623 */
drh82c3d632000-06-06 21:56:07 +00001624 tab1 = pParse->nTab++;
1625 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001626 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001627 rc = 1;
1628 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001629 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001630
1631 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 0);
drh8cdbf832004-08-29 16:25:03 +00001632 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001633 if( rc!=SQLITE_OK ){
1634 goto multi_select_end;
1635 }
drh8cdbf832004-08-29 16:25:03 +00001636 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1637 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab1, 0);
danielk197784ac9d02004-05-18 09:58:06 +00001638 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001639
1640 /* Code the SELECTs to our left into temporary table "tab1".
1641 */
danielk1977b3bce662005-01-29 08:32:43 +00001642 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001643 if( rc ){
1644 goto multi_select_end;
1645 }
drhd8bc7082000-06-07 23:51:50 +00001646
1647 /* Code the current SELECT into temporary table "tab2"
1648 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001649 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0);
drh8cdbf832004-08-29 16:25:03 +00001650 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001651 if( rc!=SQLITE_OK ){
1652 goto multi_select_end;
1653 }
drh8cdbf832004-08-29 16:25:03 +00001654 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1655 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab2, 0);
drh82c3d632000-06-06 21:56:07 +00001656 p->pPrior = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001657 pLimit = p->pLimit;
1658 p->pLimit = 0;
1659 pOffset = p->pOffset;
1660 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001661 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001662 p->pPrior = pPrior;
danielk1977a2dc3b12005-02-05 12:48:48 +00001663 sqlite3ExprDelete(p->pLimit);
1664 p->pLimit = pLimit;
1665 p->pOffset = pOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001666 if( rc ){
1667 goto multi_select_end;
1668 }
drhd8bc7082000-06-07 23:51:50 +00001669
1670 /* Generate code to take the intersection of the two temporary
1671 ** tables.
1672 */
drh82c3d632000-06-06 21:56:07 +00001673 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001674 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001675 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001676 }
danielk19774adee202004-05-08 08:23:19 +00001677 iBreak = sqlite3VdbeMakeLabel(v);
1678 iCont = sqlite3VdbeMakeLabel(v);
1679 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001680 computeLimitRegisters(pParse, p);
drh4a9f2412005-06-12 12:01:19 +00001681 iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
danielk19774adee202004-05-08 08:23:19 +00001682 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001683 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001684 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001685 iCont, iBreak, 0);
1686 if( rc ){
1687 rc = 1;
1688 goto multi_select_end;
1689 }
danielk19774adee202004-05-08 08:23:19 +00001690 sqlite3VdbeResolveLabel(v, iCont);
1691 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1692 sqlite3VdbeResolveLabel(v, iBreak);
1693 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1694 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001695 break;
1696 }
1697 }
drh8cdbf832004-08-29 16:25:03 +00001698
1699 /* Make sure all SELECTs in the statement have the same number of elements
1700 ** in their result sets.
1701 */
drh82c3d632000-06-06 21:56:07 +00001702 assert( p->pEList && pPrior->pEList );
1703 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001704 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001705 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001706 rc = 1;
1707 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001708 }
danielk197784ac9d02004-05-18 09:58:06 +00001709
drh8cdbf832004-08-29 16:25:03 +00001710 /* Set the number of columns in temporary tables
1711 */
1712 nCol = p->pEList->nExpr;
1713 while( nAddr>0 ){
1714 nAddr--;
1715 sqlite3VdbeChangeP2(v, aAddr[nAddr], nCol);
1716 }
1717
drhfbc4ee72004-08-29 01:31:05 +00001718 /* Compute collating sequences used by either the ORDER BY clause or
1719 ** by any temporary tables needed to implement the compound select.
1720 ** Attach the KeyInfo structure to all temporary tables. Invoke the
1721 ** ORDER BY processing if there is an ORDER BY clause.
drh8cdbf832004-08-29 16:25:03 +00001722 **
1723 ** This section is run by the right-most SELECT statement only.
1724 ** SELECT statements to the left always skip this part. The right-most
1725 ** SELECT might also skip this part if it has no ORDER BY clause and
1726 ** no temp tables are required.
drhfbc4ee72004-08-29 01:31:05 +00001727 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001728 if( p->pOrderBy || (pOpenTemp && pOpenTemp->nId>0) ){
drhfbc4ee72004-08-29 01:31:05 +00001729 int i; /* Loop counter */
1730 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
1731
drh8cdbf832004-08-29 16:25:03 +00001732 assert( p->ppOpenTemp == &pOpenTemp );
drhfbc4ee72004-08-29 01:31:05 +00001733 pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*sizeof(CollSeq*));
danielk1977dc1bdc42004-06-11 10:51:27 +00001734 if( !pKeyInfo ){
1735 rc = SQLITE_NOMEM;
1736 goto multi_select_end;
1737 }
1738
1739 pKeyInfo->enc = pParse->db->enc;
1740 pKeyInfo->nField = nCol;
1741
1742 for(i=0; i<nCol; i++){
1743 pKeyInfo->aColl[i] = multiSelectCollSeq(pParse, p, i);
1744 if( !pKeyInfo->aColl[i] ){
1745 pKeyInfo->aColl[i] = pParse->db->pDfltColl;
1746 }
1747 }
1748
1749 for(i=0; pOpenTemp && i<pOpenTemp->nId; i++){
1750 int p3type = (i==0?P3_KEYINFO_HANDOFF:P3_KEYINFO);
1751 int addr = pOpenTemp->a[i].idx;
1752 sqlite3VdbeChangeP3(v, addr, (char *)pKeyInfo, p3type);
1753 }
1754
1755 if( p->pOrderBy ){
drhfbc4ee72004-08-29 01:31:05 +00001756 struct ExprList_item *pOrderByTerm = p->pOrderBy->a;
1757 for(i=0; i<p->pOrderBy->nExpr; i++, pOrderByTerm++){
1758 Expr *pExpr = pOrderByTerm->pExpr;
1759 char *zName = pOrderByTerm->zName;
danielk1977dc1bdc42004-06-11 10:51:27 +00001760 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
danielk1977b3bce662005-01-29 08:32:43 +00001761 /* assert( !pExpr->pColl ); */
danielk1977dc1bdc42004-06-11 10:51:27 +00001762 if( zName ){
1763 pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1);
1764 }else{
1765 pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn];
1766 }
1767 }
1768 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1769 }
1770
1771 if( !pOpenTemp ){
1772 /* This happens for UNION ALL ... ORDER BY */
1773 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001774 }
1775 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001776
1777multi_select_end:
1778 if( pOpenTemp ){
1779 sqlite3IdListDelete(pOpenTemp);
1780 }
1781 p->ppOpenTemp = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001782 return rc;
drh22827922000-06-06 17:27:05 +00001783}
drhb7f91642004-10-31 02:22:47 +00001784#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drh22827922000-06-06 17:27:05 +00001785
drhb7f91642004-10-31 02:22:47 +00001786#ifndef SQLITE_OMIT_VIEW
drh22827922000-06-06 17:27:05 +00001787/*
drh832508b2002-03-02 17:04:07 +00001788** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001789** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001790** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001791** unchanged.)
drh832508b2002-03-02 17:04:07 +00001792**
1793** This routine is part of the flattening procedure. A subquery
1794** whose result set is defined by pEList appears as entry in the
1795** FROM clause of a SELECT such that the VDBE cursor assigned to that
1796** FORM clause entry is iTable. This routine make the necessary
1797** changes to pExpr so that it refers directly to the source table
1798** of the subquery rather the result set of the subquery.
1799*/
drh6a3ea0e2003-05-02 14:32:12 +00001800static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
danielk1977b3bce662005-01-29 08:32:43 +00001801static void substSelect(Select *, int, ExprList *); /* Forward Decl */
drh6a3ea0e2003-05-02 14:32:12 +00001802static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001803 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001804 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1805 if( pExpr->iColumn<0 ){
1806 pExpr->op = TK_NULL;
1807 }else{
1808 Expr *pNew;
1809 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1810 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1811 pNew = pEList->a[pExpr->iColumn].pExpr;
1812 assert( pNew!=0 );
1813 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001814 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001815 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001816 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001817 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001818 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001819 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001820 pExpr->iTable = pNew->iTable;
1821 pExpr->iColumn = pNew->iColumn;
1822 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001823 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1824 sqlite3TokenCopy(&pExpr->span, &pNew->span);
danielk1977a1cb1832005-02-12 08:59:55 +00001825 pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
1826 pExpr->flags = pNew->flags;
drh50350a12004-02-13 16:22:22 +00001827 }
drh832508b2002-03-02 17:04:07 +00001828 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001829 substExpr(pExpr->pLeft, iTable, pEList);
1830 substExpr(pExpr->pRight, iTable, pEList);
danielk1977b3bce662005-01-29 08:32:43 +00001831 substSelect(pExpr->pSelect, iTable, pEList);
drh6a3ea0e2003-05-02 14:32:12 +00001832 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001833 }
1834}
danielk1977b3bce662005-01-29 08:32:43 +00001835static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001836 int i;
1837 if( pList==0 ) return;
1838 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001839 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001840 }
1841}
danielk1977b3bce662005-01-29 08:32:43 +00001842static void substSelect(Select *p, int iTable, ExprList *pEList){
1843 if( !p ) return;
1844 substExprList(p->pEList, iTable, pEList);
1845 substExprList(p->pGroupBy, iTable, pEList);
1846 substExprList(p->pOrderBy, iTable, pEList);
1847 substExpr(p->pHaving, iTable, pEList);
1848 substExpr(p->pWhere, iTable, pEList);
1849}
drhb7f91642004-10-31 02:22:47 +00001850#endif /* !defined(SQLITE_OMIT_VIEW) */
drh832508b2002-03-02 17:04:07 +00001851
drhb7f91642004-10-31 02:22:47 +00001852#ifndef SQLITE_OMIT_VIEW
drh832508b2002-03-02 17:04:07 +00001853/*
drh1350b032002-02-27 19:00:20 +00001854** This routine attempts to flatten subqueries in order to speed
1855** execution. It returns 1 if it makes changes and 0 if no flattening
1856** occurs.
1857**
1858** To understand the concept of flattening, consider the following
1859** query:
1860**
1861** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1862**
1863** The default way of implementing this query is to execute the
1864** subquery first and store the results in a temporary table, then
1865** run the outer query on that temporary table. This requires two
1866** passes over the data. Furthermore, because the temporary table
1867** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001868** optimized.
drh1350b032002-02-27 19:00:20 +00001869**
drh832508b2002-03-02 17:04:07 +00001870** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001871** a single flat select, like this:
1872**
1873** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1874**
1875** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001876** but only has to scan the data once. And because indices might
1877** exist on the table t1, a complete scan of the data might be
1878** avoided.
drh1350b032002-02-27 19:00:20 +00001879**
drh832508b2002-03-02 17:04:07 +00001880** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001881**
drh832508b2002-03-02 17:04:07 +00001882** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001883**
drh832508b2002-03-02 17:04:07 +00001884** (2) The subquery is not an aggregate or the outer query is not a join.
1885**
drh8af4d3a2003-05-06 20:35:16 +00001886** (3) The subquery is not the right operand of a left outer join, or
1887** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001888**
1889** (4) The subquery is not DISTINCT or the outer query is not a join.
1890**
1891** (5) The subquery is not DISTINCT or the outer query does not use
1892** aggregates.
1893**
1894** (6) The subquery does not use aggregates or the outer query is not
1895** DISTINCT.
1896**
drh08192d52002-04-30 19:20:28 +00001897** (7) The subquery has a FROM clause.
1898**
drhdf199a22002-06-14 22:38:41 +00001899** (8) The subquery does not use LIMIT or the outer query is not a join.
1900**
1901** (9) The subquery does not use LIMIT or the outer query does not use
1902** aggregates.
1903**
1904** (10) The subquery does not use aggregates or the outer query does not
1905** use LIMIT.
1906**
drh174b6192002-12-03 02:22:52 +00001907** (11) The subquery and the outer query do not both have ORDER BY clauses.
1908**
drh3fc673e2003-06-16 00:40:34 +00001909** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1910** subquery has no WHERE clause. (added by ticket #350)
1911**
drh832508b2002-03-02 17:04:07 +00001912** In this routine, the "p" parameter is a pointer to the outer query.
1913** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1914** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1915**
drh665de472003-03-31 13:36:09 +00001916** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001917** If flattening is attempted this routine returns 1.
1918**
1919** All of the expression analysis must occur on both the outer query and
1920** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001921*/
drh8c74a8c2002-08-25 19:20:40 +00001922static int flattenSubquery(
1923 Parse *pParse, /* The parsing context */
1924 Select *p, /* The parent or outer SELECT statement */
1925 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1926 int isAgg, /* True if outer SELECT uses aggregate functions */
1927 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1928){
drh0bb28102002-05-08 11:54:14 +00001929 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001930 SrcList *pSrc; /* The FROM clause of the outer query */
1931 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001932 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001933 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh91bb0ee2004-09-01 03:06:34 +00001934 int i; /* Loop counter */
1935 Expr *pWhere; /* The WHERE clause */
1936 struct SrcList_item *pSubitem; /* The subquery */
drh1350b032002-02-27 19:00:20 +00001937
drh832508b2002-03-02 17:04:07 +00001938 /* Check to see if flattening is permitted. Return 0 if not.
1939 */
1940 if( p==0 ) return 0;
1941 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001942 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh91bb0ee2004-09-01 03:06:34 +00001943 pSubitem = &pSrc->a[iFrom];
1944 pSub = pSubitem->pSelect;
drh832508b2002-03-02 17:04:07 +00001945 assert( pSub!=0 );
1946 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001947 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001948 pSubSrc = pSub->pSrc;
1949 assert( pSubSrc );
danielk1977a2dc3b12005-02-05 12:48:48 +00001950 if( (pSub->pLimit && p->pLimit) || pSub->pOffset ||
1951 (pSub->pLimit && isAgg) ) return 0;
drhc31c2eb2003-05-02 16:04:17 +00001952 if( pSubSrc->nSrc==0 ) return 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001953 if( pSub->isDistinct && (pSrc->nSrc>1 || isAgg) ){
drhdf199a22002-06-14 22:38:41 +00001954 return 0;
1955 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001956 if( p->isDistinct && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001957 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001958
drh8af4d3a2003-05-06 20:35:16 +00001959 /* Restriction 3: If the subquery is a join, make sure the subquery is
1960 ** not used as the right operand of an outer join. Examples of why this
1961 ** is not allowed:
1962 **
1963 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1964 **
1965 ** If we flatten the above, we would get
1966 **
1967 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1968 **
1969 ** which is not at all the same thing.
1970 */
1971 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1972 return 0;
1973 }
1974
drh3fc673e2003-06-16 00:40:34 +00001975 /* Restriction 12: If the subquery is the right operand of a left outer
1976 ** join, make sure the subquery has no WHERE clause.
1977 ** An examples of why this is not allowed:
1978 **
1979 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1980 **
1981 ** If we flatten the above, we would get
1982 **
1983 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1984 **
1985 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1986 ** effectively converts the OUTER JOIN into an INNER JOIN.
1987 */
1988 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1989 && pSub->pWhere!=0 ){
1990 return 0;
1991 }
1992
drh0bb28102002-05-08 11:54:14 +00001993 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001994 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001995 */
drhc31c2eb2003-05-02 16:04:17 +00001996
1997 /* Move all of the FROM elements of the subquery into the
1998 ** the FROM clause of the outer query. Before doing this, remember
1999 ** the cursor number for the original outer query FROM element in
2000 ** iParent. The iParent cursor will never be used. Subsequent code
2001 ** will scan expressions looking for iParent references and replace
2002 ** those references with expressions that resolve to the subquery FROM
2003 ** elements we are now copying in.
2004 */
drh91bb0ee2004-09-01 03:06:34 +00002005 iParent = pSubitem->iCursor;
drhc31c2eb2003-05-02 16:04:17 +00002006 {
2007 int nSubSrc = pSubSrc->nSrc;
drh91bb0ee2004-09-01 03:06:34 +00002008 int jointype = pSubitem->jointype;
drhc31c2eb2003-05-02 16:04:17 +00002009
drhed8a3bb2005-06-06 21:19:56 +00002010 sqlite3DeleteTable(0, pSubitem->pTab);
drh91bb0ee2004-09-01 03:06:34 +00002011 sqliteFree(pSubitem->zDatabase);
2012 sqliteFree(pSubitem->zName);
2013 sqliteFree(pSubitem->zAlias);
drhc31c2eb2003-05-02 16:04:17 +00002014 if( nSubSrc>1 ){
2015 int extra = nSubSrc - 1;
2016 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00002017 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00002018 }
2019 p->pSrc = pSrc;
2020 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2021 pSrc->a[i] = pSrc->a[i-extra];
2022 }
2023 }
2024 for(i=0; i<nSubSrc; i++){
2025 pSrc->a[i+iFrom] = pSubSrc->a[i];
2026 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2027 }
drh8af4d3a2003-05-06 20:35:16 +00002028 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00002029 }
2030
2031 /* Now begin substituting subquery result set expressions for
2032 ** references to the iParent in the outer query.
2033 **
2034 ** Example:
2035 **
2036 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2037 ** \ \_____________ subquery __________/ /
2038 ** \_____________________ outer query ______________________________/
2039 **
2040 ** We look at every expression in the outer query and every place we see
2041 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2042 */
drh6a3ea0e2003-05-02 14:32:12 +00002043 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00002044 pList = p->pEList;
2045 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00002046 Expr *pExpr;
2047 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
2048 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00002049 }
2050 }
drh1b2e0322002-03-03 02:49:51 +00002051 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00002052 substExprList(p->pGroupBy, iParent, pSub->pEList);
2053 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00002054 }
drh174b6192002-12-03 02:22:52 +00002055 if( pSub->pOrderBy ){
2056 assert( p->pOrderBy==0 );
2057 p->pOrderBy = pSub->pOrderBy;
2058 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00002059 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00002060 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00002061 }
drh832508b2002-03-02 17:04:07 +00002062 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002063 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00002064 }else{
2065 pWhere = 0;
2066 }
2067 if( subqueryIsAgg ){
2068 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00002069 p->pHaving = p->pWhere;
2070 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00002071 substExpr(p->pHaving, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002072 p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
drh1b2e0322002-03-03 02:49:51 +00002073 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00002074 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00002075 }else{
drh6a3ea0e2003-05-02 14:32:12 +00002076 substExpr(p->pWhere, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002077 p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
drh832508b2002-03-02 17:04:07 +00002078 }
drhc31c2eb2003-05-02 16:04:17 +00002079
2080 /* The flattened query is distinct if either the inner or the
2081 ** outer query is distinct.
2082 */
drh832508b2002-03-02 17:04:07 +00002083 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00002084
danielk1977a58fdfb2005-02-08 07:50:40 +00002085 /*
2086 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2087 */
danielk1977a2dc3b12005-02-05 12:48:48 +00002088 if( pSub->pLimit ){
2089 p->pLimit = pSub->pLimit;
2090 pSub->pLimit = 0;
drhdf199a22002-06-14 22:38:41 +00002091 }
drh8c74a8c2002-08-25 19:20:40 +00002092
drhc31c2eb2003-05-02 16:04:17 +00002093 /* Finially, delete what is left of the subquery and return
2094 ** success.
2095 */
danielk19774adee202004-05-08 08:23:19 +00002096 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00002097 return 1;
2098}
drhb7f91642004-10-31 02:22:47 +00002099#endif /* SQLITE_OMIT_VIEW */
drh1350b032002-02-27 19:00:20 +00002100
2101/*
drh9562b552002-02-19 15:00:07 +00002102** Analyze the SELECT statement passed in as an argument to see if it
2103** is a simple min() or max() query. If it is and this query can be
2104** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00002105** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00002106** simple min() or max() query, then return 0;
2107**
2108** A simply min() or max() query looks like this:
2109**
2110** SELECT min(a) FROM table;
2111** SELECT max(a) FROM table;
2112**
2113** The query may have only a single table in its FROM argument. There
2114** can be no GROUP BY or HAVING or WHERE clauses. The result set must
2115** be the min() or max() of a single column of the table. The column
2116** in the min() or max() function must be indexed.
2117**
danielk19774adee202004-05-08 08:23:19 +00002118** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00002119** See the header comment on that routine for additional information.
2120*/
2121static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2122 Expr *pExpr;
2123 int iCol;
2124 Table *pTab;
2125 Index *pIdx;
2126 int base;
2127 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00002128 int seekOp;
2129 int cont;
drh6e175292004-03-13 14:00:36 +00002130 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00002131 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00002132 SrcList *pSrc;
drh9562b552002-02-19 15:00:07 +00002133
2134 /* Check to see if this query is a simple min() or max() query. Return
2135 ** zero if it is not.
2136 */
2137 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00002138 pSrc = p->pSrc;
2139 if( pSrc->nSrc!=1 ) return 0;
2140 pEList = p->pEList;
2141 if( pEList->nExpr!=1 ) return 0;
2142 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002143 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002144 pList = pExpr->pList;
2145 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002146 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00002147 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002148 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00002149 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002150 seekOp = OP_Last;
2151 }else{
2152 return 0;
2153 }
drh6e175292004-03-13 14:00:36 +00002154 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002155 if( pExpr->op!=TK_COLUMN ) return 0;
2156 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002157 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002158
2159 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002160 ** Check to make sure we have an index and make pIdx point to the
2161 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2162 ** key column, no index is necessary so set pIdx to NULL. If no
2163 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002164 */
2165 if( iCol<0 ){
2166 pIdx = 0;
2167 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002168 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002169 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2170 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002171 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002172 }
2173 if( pIdx==0 ) return 0;
2174 }
2175
drhe5f50722003-07-19 00:44:14 +00002176 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002177 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002178 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002179 */
danielk19774adee202004-05-08 08:23:19 +00002180 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002181 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002182
drh0c37e632004-01-30 02:01:03 +00002183 /* If the output is destined for a temporary table, open that table.
2184 */
2185 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002186 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002187 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002188 }
2189
drh17f71932002-02-21 12:01:27 +00002190 /* Generating code to find the min or the max. Basically all we have
2191 ** to do is find the first or the last entry in the chosen index. If
2192 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2193 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002194 */
danielk19774adee202004-05-08 08:23:19 +00002195 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00002196 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00002197 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00002198 if( pSrc->a[0].pSelect==0 ){
drhad6d9462004-09-19 02:15:24 +00002199 sqlite3OpenTableForReading(v, base, pTab);
drh6e175292004-03-13 14:00:36 +00002200 }
danielk19774adee202004-05-08 08:23:19 +00002201 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00002202 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002203 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002204 }else{
danielk19773719d7f2005-01-17 08:57:09 +00002205 /* Even though the cursor used to open the index here is closed
2206 ** as soon as a single value has been read from it, allocate it
2207 ** using (pParse->nTab++) to prevent the cursor id from being
2208 ** reused. This is important for statements of the form
2209 ** "INSERT INTO x SELECT max() FROM x".
2210 */
2211 int iIdx;
2212 iIdx = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +00002213 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002214 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
drhd3d39e92004-05-20 22:16:29 +00002215 (char*)&pIdx->keyInfo, P3_KEYINFO);
drh9eb516c2004-07-18 20:52:32 +00002216 if( seekOp==OP_Rewind ){
drhf0863fe2005-06-12 21:35:51 +00002217 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh1af3fdb2004-07-18 21:33:01 +00002218 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2219 seekOp = OP_MoveGt;
drh9eb516c2004-07-18 20:52:32 +00002220 }
danielk19773719d7f2005-01-17 08:57:09 +00002221 sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
drhf0863fe2005-06-12 21:35:51 +00002222 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002223 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002224 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002225 }
drh5cf8e8c2002-02-19 22:42:05 +00002226 eList.nExpr = 1;
2227 memset(&eListItem, 0, sizeof(eListItem));
2228 eList.a = &eListItem;
2229 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00002230 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00002231 sqlite3VdbeResolveLabel(v, cont);
2232 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002233
drh9562b552002-02-19 15:00:07 +00002234 return 1;
2235}
2236
2237/*
drh290c1942004-08-21 17:54:45 +00002238** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
2239** the number of errors seen.
2240**
2241** An ORDER BY or GROUP BY is a list of expressions. If any expression
2242** is an integer constant, then that expression is replaced by the
2243** corresponding entry in the result set.
2244*/
2245static int processOrderGroupBy(
danielk1977b3bce662005-01-29 08:32:43 +00002246 NameContext *pNC, /* Name context of the SELECT statement. */
drh290c1942004-08-21 17:54:45 +00002247 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
drh290c1942004-08-21 17:54:45 +00002248 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
2249){
2250 int i;
danielk1977b3bce662005-01-29 08:32:43 +00002251 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */
2252 Parse *pParse = pNC->pParse; /* The result set of the SELECT */
2253 assert( pEList );
2254
drh290c1942004-08-21 17:54:45 +00002255 if( pOrderBy==0 ) return 0;
2256 for(i=0; i<pOrderBy->nExpr; i++){
2257 int iCol;
2258 Expr *pE = pOrderBy->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +00002259 if( sqlite3ExprIsInteger(pE, &iCol) ){
2260 if( iCol>0 && iCol<=pEList->nExpr ){
2261 sqlite3ExprDelete(pE);
2262 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2263 }else{
drh290c1942004-08-21 17:54:45 +00002264 sqlite3ErrorMsg(pParse,
2265 "%s BY column number %d out of range - should be "
2266 "between 1 and %d", zType, iCol, pEList->nExpr);
2267 return 1;
2268 }
2269 }
danielk1977b3bce662005-01-29 08:32:43 +00002270 if( sqlite3ExprResolveNames(pNC, pE) ){
2271 return 1;
2272 }
2273 if( sqlite3ExprIsConstant(pE) ){
2274 sqlite3ErrorMsg(pParse,
2275 "%s BY terms must not be non-integer constants", zType);
2276 return 1;
2277 }
drh290c1942004-08-21 17:54:45 +00002278 }
2279 return 0;
2280}
2281
2282/*
danielk1977b3bce662005-01-29 08:32:43 +00002283** This routine resolves any names used in the result set of the
2284** supplied SELECT statement. If the SELECT statement being resolved
2285** is a sub-select, then pOuterNC is a pointer to the NameContext
2286** of the parent SELECT.
2287*/
2288int sqlite3SelectResolve(
2289 Parse *pParse, /* The parser context */
2290 Select *p, /* The SELECT statement being coded. */
2291 NameContext *pOuterNC /* The outer name context. May be NULL. */
2292){
2293 ExprList *pEList; /* Result set. */
2294 int i; /* For-loop variable used in multiple places */
2295 NameContext sNC; /* Local name-context */
2296
2297 /* If this routine has run before, return immediately. */
2298 if( p->isResolved ){
2299 assert( !pOuterNC );
2300 return SQLITE_OK;
2301 }
2302 p->isResolved = 1;
2303
2304 /* If there have already been errors, do nothing. */
2305 if( pParse->nErr>0 ){
2306 return SQLITE_ERROR;
2307 }
2308
2309 /* Prepare the select statement. This call will allocate all cursors
2310 ** required to handle the tables and subqueries in the FROM clause.
2311 */
2312 if( prepSelectStmt(pParse, p) ){
2313 return SQLITE_ERROR;
2314 }
2315
danielk1977a2dc3b12005-02-05 12:48:48 +00002316 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2317 ** are not allowed to refer to any names, so pass an empty NameContext.
2318 */
danielk1977b3bce662005-01-29 08:32:43 +00002319 sNC.pParse = pParse;
danielk1977b3bce662005-01-29 08:32:43 +00002320 sNC.hasAgg = 0;
2321 sNC.nErr = 0;
2322 sNC.nRef = 0;
2323 sNC.pEList = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00002324 sNC.allowAgg = 0;
2325 sNC.pSrcList = 0;
2326 sNC.pNext = 0;
2327 if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2328 sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2329 return SQLITE_ERROR;
2330 }
2331
2332 /* Set up the local name-context to pass to ExprResolveNames() to
2333 ** resolve the expression-list.
2334 */
2335 sNC.allowAgg = 1;
2336 sNC.pSrcList = p->pSrc;
2337 sNC.pNext = pOuterNC;
danielk1977b3bce662005-01-29 08:32:43 +00002338
2339 /* NameContext.nDepth stores the depth of recursion for this query. For
2340 ** an outer query (e.g. SELECT * FROM sqlite_master) this is 1. For
2341 ** a subquery it is 2. For a subquery of a subquery, 3. And so on.
2342 ** Parse.nMaxDepth is the maximum depth for any subquery resolved so
2343 ** far. This is used to determine the number of aggregate contexts
2344 ** required at runtime.
2345 */
2346 sNC.nDepth = (pOuterNC?pOuterNC->nDepth+1:1);
2347 if( sNC.nDepth>pParse->nMaxDepth ){
2348 pParse->nMaxDepth = sNC.nDepth;
2349 }
2350
2351 /* Resolve names in the result set. */
2352 pEList = p->pEList;
2353 if( !pEList ) return SQLITE_ERROR;
2354 for(i=0; i<pEList->nExpr; i++){
2355 Expr *pX = pEList->a[i].pExpr;
2356 if( sqlite3ExprResolveNames(&sNC, pX) ){
2357 return SQLITE_ERROR;
2358 }
2359 }
2360
2361 /* If there are no aggregate functions in the result-set, and no GROUP BY
2362 ** expression, do not allow aggregates in any of the other expressions.
2363 */
2364 assert( !p->isAgg );
2365 if( p->pGroupBy || sNC.hasAgg ){
2366 p->isAgg = 1;
2367 }else{
2368 sNC.allowAgg = 0;
2369 }
2370
2371 /* If a HAVING clause is present, then there must be a GROUP BY clause.
2372 */
2373 if( p->pHaving && !p->pGroupBy ){
2374 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2375 return SQLITE_ERROR;
2376 }
2377
2378 /* Add the expression list to the name-context before parsing the
2379 ** other expressions in the SELECT statement. This is so that
2380 ** expressions in the WHERE clause (etc.) can refer to expressions by
2381 ** aliases in the result set.
2382 **
2383 ** Minor point: If this is the case, then the expression will be
2384 ** re-evaluated for each reference to it.
2385 */
2386 sNC.pEList = p->pEList;
2387 if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2388 sqlite3ExprResolveNames(&sNC, p->pHaving) ||
2389 processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
2390 processOrderGroupBy(&sNC, p->pGroupBy, "GROUP")
2391 ){
2392 return SQLITE_ERROR;
2393 }
2394
2395 return SQLITE_OK;
2396}
2397
2398/*
2399** An instance of the following struct is used by sqlite3Select()
2400** to save aggregate related information from the Parse object
2401** at the start of each call and to restore it at the end. See
2402** saveAggregateInfo() and restoreAggregateInfo().
2403*/
2404struct AggregateInfo {
danielk1977b3bce662005-01-29 08:32:43 +00002405 int nAgg;
2406 AggExpr *aAgg;
2407};
2408typedef struct AggregateInfo AggregateInfo;
2409
2410/*
2411** Copy aggregate related information from the Parse structure
2412** into the AggregateInfo structure. Zero the aggregate related
2413** values in the Parse struct.
2414*/
2415static void saveAggregateInfo(Parse *pParse, AggregateInfo *pInfo){
2416 pInfo->aAgg = pParse->aAgg;
2417 pInfo->nAgg = pParse->nAgg;
danielk1977b3bce662005-01-29 08:32:43 +00002418 pParse->aAgg = 0;
2419 pParse->nAgg = 0;
danielk1977b3bce662005-01-29 08:32:43 +00002420}
2421
2422/*
2423** Copy aggregate related information from the AggregateInfo struct
2424** back into the Parse structure. The aggregate related information
2425** currently stored in the Parse structure is deleted.
2426*/
2427static void restoreAggregateInfo(Parse *pParse, AggregateInfo *pInfo){
2428 sqliteFree(pParse->aAgg);
2429 pParse->aAgg = pInfo->aAgg;
2430 pParse->nAgg = pInfo->nAgg;
danielk1977b3bce662005-01-29 08:32:43 +00002431}
2432
2433/*
drh9bb61fe2000-06-05 16:01:39 +00002434** Generate code for the given SELECT statement.
2435**
drhfef52082000-06-06 01:50:43 +00002436** The results are distributed in various ways depending on the
2437** value of eDest and iParm.
2438**
2439** eDest Value Result
2440** ------------ -------------------------------------------
2441** SRT_Callback Invoke the callback for each row of the result.
2442**
2443** SRT_Mem Store first result in memory cell iParm
2444**
danielk1977e014a832004-05-17 10:48:57 +00002445** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002446**
drh82c3d632000-06-06 21:56:07 +00002447** SRT_Union Store results as a key in a temporary table iParm
2448**
jplyon4b11c6d2004-01-19 04:57:53 +00002449** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002450**
2451** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002452**
drhe78e8282003-01-19 03:59:45 +00002453** The table above is incomplete. Additional eDist value have be added
2454** since this comment was written. See the selectInnerLoop() function for
2455** a complete listing of the allowed values of eDest and their meanings.
2456**
drh9bb61fe2000-06-05 16:01:39 +00002457** This routine returns the number of errors. If any errors are
2458** encountered, then an appropriate error message is left in
2459** pParse->zErrMsg.
2460**
2461** This routine does NOT free the Select structure passed in. The
2462** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002463**
2464** The pParent, parentTab, and *pParentAgg fields are filled in if this
2465** SELECT is a subquery. This routine may try to combine this SELECT
2466** with its parent to form a single flat query. In so doing, it might
2467** change the parent query from a non-aggregate to an aggregate query.
2468** For that reason, the pParentAgg flag is passed as a pointer, so it
2469** can be changed.
drhe78e8282003-01-19 03:59:45 +00002470**
2471** Example 1: The meaning of the pParent parameter.
2472**
2473** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2474** \ \_______ subquery _______/ /
2475** \ /
2476** \____________________ outer query ___________________/
2477**
2478** This routine is called for the outer query first. For that call,
2479** pParent will be NULL. During the processing of the outer query, this
2480** routine is called recursively to handle the subquery. For the recursive
2481** call, pParent will point to the outer query. Because the subquery is
2482** the second element in a three-way join, the parentTab parameter will
2483** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002484*/
danielk19774adee202004-05-08 08:23:19 +00002485int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002486 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002487 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002488 int eDest, /* How to dispose of the results */
2489 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002490 Select *pParent, /* Another SELECT for which this is a sub-query */
2491 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002492 int *pParentAgg, /* True if pParent uses aggregate functions */
danielk1977b3bce662005-01-29 08:32:43 +00002493 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002494){
drhd8bc7082000-06-07 23:51:50 +00002495 int i;
drhcce7d172000-05-31 15:34:51 +00002496 WhereInfo *pWInfo;
2497 Vdbe *v;
danielk1977b3bce662005-01-29 08:32:43 +00002498 int isAgg; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002499 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002500 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002501 Expr *pWhere; /* The WHERE clause. May be NULL */
2502 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002503 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2504 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002505 int isDistinct; /* True if the DISTINCT keyword is present */
2506 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002507 int rc = 1; /* Value to return from this function */
danielk1977b3bce662005-01-29 08:32:43 +00002508 AggregateInfo sAggInfo;
drh9bb61fe2000-06-05 16:01:39 +00002509
danielk19776f8a5032004-05-10 10:34:51 +00002510 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002511 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002512
drhb7f91642004-10-31 02:22:47 +00002513#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +00002514 /* If there is are a sequence of queries, do the earlier ones first.
2515 */
2516 if( p->pPrior ){
danielk197784ac9d02004-05-18 09:58:06 +00002517 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002518 }
drhb7f91642004-10-31 02:22:47 +00002519#endif
drh82c3d632000-06-06 21:56:07 +00002520
danielk1977b3bce662005-01-29 08:32:43 +00002521 saveAggregateInfo(pParse, &sAggInfo);
2522 pOrderBy = p->pOrderBy;
2523 if( eDest==SRT_Union || eDest==SRT_Except || eDest==SRT_Discard ){
2524 p->pOrderBy = 0;
2525 }
2526 if( sqlite3SelectResolve(pParse, p, 0) ){
2527 goto select_end;
2528 }
2529 p->pOrderBy = pOrderBy;
2530
drh82c3d632000-06-06 21:56:07 +00002531 /* Make local copies of the parameters for this query.
2532 */
drh9bb61fe2000-06-05 16:01:39 +00002533 pTabList = p->pSrc;
2534 pWhere = p->pWhere;
drh22827922000-06-06 17:27:05 +00002535 pGroupBy = p->pGroupBy;
2536 pHaving = p->pHaving;
danielk1977b3bce662005-01-29 08:32:43 +00002537 isAgg = p->isAgg;
drh19a775c2000-06-05 18:54:46 +00002538 isDistinct = p->isDistinct;
danielk1977b3bce662005-01-29 08:32:43 +00002539 pEList = p->pEList;
2540 if( pEList==0 ) goto select_end;
drh9bb61fe2000-06-05 16:01:39 +00002541
2542 /*
2543 ** Do not even attempt to generate any code if we have already seen
2544 ** errors before this routine starts.
2545 */
drh1d83f052002-02-17 00:30:36 +00002546 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002547
drh22827922000-06-06 17:27:05 +00002548 /* If writing to memory or generating a set
2549 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002550 */
drh51522cd2005-01-20 13:36:19 +00002551 assert( eDest!=SRT_Exists || pEList->nExpr==1 );
danielk197793758c82005-01-21 08:13:14 +00002552#ifndef SQLITE_OMIT_SUBQUERY
drhfef52082000-06-06 01:50:43 +00002553 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002554 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002555 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002556 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002557 }
danielk197793758c82005-01-21 08:13:14 +00002558#endif
drh19a775c2000-06-05 18:54:46 +00002559
drhc926afb2002-06-20 03:38:26 +00002560 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002561 */
drhc926afb2002-06-20 03:38:26 +00002562 switch( eDest ){
2563 case SRT_Union:
2564 case SRT_Except:
2565 case SRT_Discard:
2566 pOrderBy = 0;
2567 break;
2568 default:
2569 break;
drh22827922000-06-06 17:27:05 +00002570 }
2571
drhd820cb12002-02-18 03:21:45 +00002572 /* Begin generating code.
2573 */
danielk19774adee202004-05-08 08:23:19 +00002574 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002575 if( v==0 ) goto select_end;
2576
drhe78e8282003-01-19 03:59:45 +00002577 /* Identify column names if we will be using them in a callback. This
2578 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002579 */
2580 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002581 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002582 }
2583
drhd820cb12002-02-18 03:21:45 +00002584 /* Generate code for all sub-queries in the FROM clause
2585 */
drh51522cd2005-01-20 13:36:19 +00002586#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
drhad3cab52002-05-24 02:04:32 +00002587 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002588 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002589 int needRestoreContext;
2590
drha76b5df2002-02-23 02:32:10 +00002591 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002592 if( pTabList->a[i].zName!=0 ){
2593 zSavedAuthContext = pParse->zAuthContext;
2594 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002595 needRestoreContext = 1;
2596 }else{
2597 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002598 }
danielk19774adee202004-05-08 08:23:19 +00002599 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
danielk1977b3bce662005-01-29 08:32:43 +00002600 pTabList->a[i].iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002601 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002602 pParse->zAuthContext = zSavedAuthContext;
2603 }
drh1b2e0322002-03-03 02:49:51 +00002604 pTabList = p->pSrc;
2605 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002606 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002607 pOrderBy = p->pOrderBy;
2608 }
drh1b2e0322002-03-03 02:49:51 +00002609 pGroupBy = p->pGroupBy;
2610 pHaving = p->pHaving;
2611 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002612 }
drh51522cd2005-01-20 13:36:19 +00002613#endif
drhd820cb12002-02-18 03:21:45 +00002614
drh6e175292004-03-13 14:00:36 +00002615 /* Check for the special case of a min() or max() function by itself
2616 ** in the result set.
2617 */
2618 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2619 rc = 0;
2620 goto select_end;
2621 }
2622
drh832508b2002-03-02 17:04:07 +00002623 /* Check to see if this is a subquery that can be "flattened" into its parent.
2624 ** If flattening is a possiblity, do so and return immediately.
2625 */
drhb7f91642004-10-31 02:22:47 +00002626#ifndef SQLITE_OMIT_VIEW
drh1b2e0322002-03-03 02:49:51 +00002627 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002628 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002629 if( isAgg ) *pParentAgg = 1;
danielk1977b3bce662005-01-29 08:32:43 +00002630 goto select_end;
drh832508b2002-03-02 17:04:07 +00002631 }
drhb7f91642004-10-31 02:22:47 +00002632#endif
drh832508b2002-03-02 17:04:07 +00002633
danielk19777cedc8d2004-06-10 10:50:08 +00002634 /* If there is an ORDER BY clause, resolve any collation sequences
2635 ** names that have been explicitly specified.
2636 */
2637 if( pOrderBy ){
2638 for(i=0; i<pOrderBy->nExpr; i++){
2639 if( pOrderBy->a[i].zName ){
2640 pOrderBy->a[i].pExpr->pColl =
2641 sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1);
2642 }
2643 }
2644 if( pParse->nErr ){
2645 goto select_end;
2646 }
2647 }
2648
drh7b58dae2003-07-20 01:16:46 +00002649 /* Set the limiter.
2650 */
2651 computeLimitRegisters(pParse, p);
2652
drh2d0794e2002-03-03 03:03:52 +00002653 /* If the output is destined for a temporary table, open that table.
2654 */
2655 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002656 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002657 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002658 }
2659
drh22827922000-06-06 17:27:05 +00002660 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002661 */
drhbb999ef2003-02-02 12:41:25 +00002662 if( isAgg || pGroupBy ){
danielk1977a58fdfb2005-02-08 07:50:40 +00002663 NameContext sNC;
2664 memset(&sNC, 0, sizeof(sNC));
2665 sNC.pParse = pParse;
2666 sNC.pSrcList = pTabList;
2667
drh0bce8352002-02-28 00:41:10 +00002668 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002669 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002670 for(i=0; i<pEList->nExpr; i++){
danielk1977a58fdfb2005-02-08 07:50:40 +00002671 if( sqlite3ExprAnalyzeAggregates(&sNC, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002672 goto select_end;
drh22827922000-06-06 17:27:05 +00002673 }
2674 }
2675 if( pGroupBy ){
2676 for(i=0; i<pGroupBy->nExpr; i++){
danielk1977a58fdfb2005-02-08 07:50:40 +00002677 if( sqlite3ExprAnalyzeAggregates(&sNC, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002678 goto select_end;
drh22827922000-06-06 17:27:05 +00002679 }
2680 }
2681 }
danielk1977a58fdfb2005-02-08 07:50:40 +00002682 if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002683 goto select_end;
drh22827922000-06-06 17:27:05 +00002684 }
drh191b6902000-06-08 11:13:01 +00002685 if( pOrderBy ){
2686 for(i=0; i<pOrderBy->nExpr; i++){
danielk1977a58fdfb2005-02-08 07:50:40 +00002687 if( sqlite3ExprAnalyzeAggregates(&sNC, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002688 goto select_end;
drh191b6902000-06-08 11:13:01 +00002689 }
2690 }
2691 }
drhefb72512000-05-31 20:00:52 +00002692 }
2693
drh22827922000-06-06 17:27:05 +00002694 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002695 */
2696 if( isAgg ){
danielk1977e159fdf2004-06-21 10:45:06 +00002697 int addr = sqlite3VdbeAddOp(v, OP_AggReset, (pGroupBy?0:1), pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002698 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002699 FuncDef *pFunc;
2700 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
danielk19775c2d9152005-05-26 14:41:47 +00002701 int nExpr = 0;
2702#ifdef SQLITE_SSE
2703 Expr *pAggExpr = pParse->aAgg[i].pExpr;
2704 if( pAggExpr && pAggExpr->pList ){
2705 nExpr = pAggExpr->pList->nExpr;
2706 }
2707#endif
2708 sqlite3VdbeOp3(v, OP_AggInit, nExpr, i, (char*)pFunc, P3_FUNCDEF);
drhe5095352002-02-24 03:25:14 +00002709 }
2710 }
danielk1977e159fdf2004-06-21 10:45:06 +00002711 if( pGroupBy ){
danielk1977ce2663c2004-06-11 13:19:21 +00002712 int sz = sizeof(KeyInfo) + pGroupBy->nExpr*sizeof(CollSeq*);
2713 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(sz);
2714 if( 0==pKey ){
2715 goto select_end;
2716 }
2717 pKey->enc = pParse->db->enc;
2718 pKey->nField = pGroupBy->nExpr;
2719 for(i=0; i<pGroupBy->nExpr; i++){
2720 pKey->aColl[i] = sqlite3ExprCollSeq(pParse, pGroupBy->a[i].pExpr);
2721 if( !pKey->aColl[i] ){
2722 pKey->aColl[i] = pParse->db->pDfltColl;
2723 }
2724 }
2725 sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF);
drh1bee3d72001-10-15 00:44:35 +00002726 }
drhcce7d172000-05-31 15:34:51 +00002727 }
2728
drh51522cd2005-01-20 13:36:19 +00002729 /* Initialize the memory cell to NULL for SRT_Mem or 0 for SRT_Exists
drh19a775c2000-06-05 18:54:46 +00002730 */
drh51522cd2005-01-20 13:36:19 +00002731 if( eDest==SRT_Mem || eDest==SRT_Exists ){
drhf0863fe2005-06-12 21:35:51 +00002732 sqlite3VdbeAddOp(v, eDest==SRT_Mem ? OP_Null : OP_Integer, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00002733 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002734 }
2735
drh832508b2002-03-02 17:04:07 +00002736 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002737 */
drh19a775c2000-06-05 18:54:46 +00002738 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002739 distinct = pParse->nTab++;
drhf0863fe2005-06-12 21:35:51 +00002740 openTempIndex(pParse, p, distinct);
drh832508b2002-03-02 17:04:07 +00002741 }else{
2742 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002743 }
drh832508b2002-03-02 17:04:07 +00002744
2745 /* Begin the database scan
2746 */
drhe6f85e72004-12-25 01:03:13 +00002747 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,
drhf8db1bc2005-04-22 02:38:37 +00002748 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002749 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002750
drh22827922000-06-06 17:27:05 +00002751 /* Use the standard inner loop if we are not dealing with
2752 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002753 */
drhda9d6c42000-05-31 18:20:14 +00002754 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002755 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002756 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002757 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002758 }
drhcce7d172000-05-31 15:34:51 +00002759 }
drhefb72512000-05-31 20:00:52 +00002760
drhe3184742002-06-19 14:27:05 +00002761 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002762 ** processing.
drhefb72512000-05-31 20:00:52 +00002763 */
drh22827922000-06-06 17:27:05 +00002764 else{
drh268380c2004-02-25 13:47:31 +00002765 AggExpr *pAgg;
danielk1977a58fdfb2005-02-08 07:50:40 +00002766 int lbl1 = 0;
2767 pParse->fillAgg = 1;
drh22827922000-06-06 17:27:05 +00002768 if( pGroupBy ){
2769 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002770 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
drh22827922000-06-06 17:27:05 +00002771 }
danielk1977ededfd52004-06-17 07:53:01 +00002772 /* No affinity string is attached to the following OP_MakeRecord
drhd3d39e92004-05-20 22:16:29 +00002773 ** because we do not need to do any coercion of datatypes. */
danielk1977ededfd52004-06-17 07:53:01 +00002774 sqlite3VdbeAddOp(v, OP_MakeRecord, pGroupBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +00002775 lbl1 = sqlite3VdbeMakeLabel(v);
2776 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
danielk1977a58fdfb2005-02-08 07:50:40 +00002777 }
2778 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2779 if( pAgg->isAgg ) continue;
2780 sqlite3ExprCode(pParse, pAgg->pExpr);
2781 sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
2782 }
2783 pParse->fillAgg = 0;
2784 if( lbl1<0 ){
danielk19774adee202004-05-08 08:23:19 +00002785 sqlite3VdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002786 }
drh268380c2004-02-25 13:47:31 +00002787 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002788 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002789 int nExpr;
2790 FuncDef *pDef;
2791 if( !pAgg->isAgg ) continue;
2792 assert( pAgg->pFunc!=0 );
2793 assert( pAgg->pFunc->xStep!=0 );
2794 pDef = pAgg->pFunc;
2795 pE = pAgg->pExpr;
2796 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002797 assert( pE->op==TK_AGG_FUNCTION );
drhf9b596e2004-05-26 16:54:42 +00002798 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
danielk19774adee202004-05-08 08:23:19 +00002799 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
danielk1977dc1bdc42004-06-11 10:51:27 +00002800 if( pDef->needCollSeq ){
2801 CollSeq *pColl = 0;
2802 int j;
2803 for(j=0; !pColl && j<nExpr; j++){
2804 pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr);
2805 }
2806 if( !pColl ) pColl = pParse->db->pDfltColl;
2807 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2808 }
danielk19771f55c052005-05-19 08:42:59 +00002809 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_FUNCDEF);
drh22827922000-06-06 17:27:05 +00002810 }
drhcce7d172000-05-31 15:34:51 +00002811 }
2812
2813 /* End the database scan loop.
2814 */
danielk19774adee202004-05-08 08:23:19 +00002815 sqlite3WhereEnd(pWInfo);
drhcce7d172000-05-31 15:34:51 +00002816
drh22827922000-06-06 17:27:05 +00002817 /* If we are processing aggregates, we need to set up a second loop
2818 ** over all of the aggregate values and process them.
2819 */
2820 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002821 int endagg = sqlite3VdbeMakeLabel(v);
drh22827922000-06-06 17:27:05 +00002822 int startagg;
danielk19774adee202004-05-08 08:23:19 +00002823 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002824 if( pHaving ){
danielk19774adee202004-05-08 08:23:19 +00002825 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002826 }
drhdf199a22002-06-14 22:38:41 +00002827 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002828 iParm, startagg, endagg, aff) ){
drh1d83f052002-02-17 00:30:36 +00002829 goto select_end;
drh22827922000-06-06 17:27:05 +00002830 }
danielk19774adee202004-05-08 08:23:19 +00002831 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2832 sqlite3VdbeResolveLabel(v, endagg);
2833 sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002834 }
2835
drhcce7d172000-05-31 15:34:51 +00002836 /* If there is an ORDER BY clause, then we need to sort the results
2837 ** and send them to the callback one by one.
2838 */
2839 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00002840 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002841 }
drh6a535342001-10-19 16:44:56 +00002842
danielk197793758c82005-01-21 08:13:14 +00002843#ifndef SQLITE_OMIT_SUBQUERY
drhf620b4e2004-02-09 14:37:50 +00002844 /* If this was a subquery, we have now converted the subquery into a
2845 ** temporary table. So delete the subquery structure from the parent
2846 ** to prevent this subquery from being evaluated again and to force the
2847 ** the use of the temporary table.
2848 */
2849 if( pParent ){
2850 assert( pParent->pSrc->nSrc>parentTab );
2851 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00002852 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00002853 pParent->pSrc->a[parentTab].pSelect = 0;
2854 }
danielk197793758c82005-01-21 08:13:14 +00002855#endif
drhf620b4e2004-02-09 14:37:50 +00002856
drh1d83f052002-02-17 00:30:36 +00002857 /* The SELECT was successfully coded. Set the return code to 0
2858 ** to indicate no errors.
2859 */
2860 rc = 0;
2861
2862 /* Control jumps to here if an error is encountered above, or upon
2863 ** successful coding of the SELECT.
2864 */
2865select_end:
danielk1977b3bce662005-01-29 08:32:43 +00002866 restoreAggregateInfo(pParse, &sAggInfo);
drh1d83f052002-02-17 00:30:36 +00002867 return rc;
drhcce7d172000-05-31 15:34:51 +00002868}