blob: b792f9d5a26479e6b74fe66580dc0eb0099c619b [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**
danielk1977a1cb1832005-02-12 08:59:55 +000015** $Id: select.c,v 1.241 2005/02/12 08:59:57 danielk1977 Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
drh315555c2002-10-20 15:53:03 +000019
drhcce7d172000-05-31 15:34:51 +000020/*
drh9bb61fe2000-06-05 16:01:39 +000021** Allocate a new Select structure and return a pointer to that
22** structure.
drhcce7d172000-05-31 15:34:51 +000023*/
danielk19774adee202004-05-08 08:23:19 +000024Select *sqlite3SelectNew(
drhdaffd0e2001-04-11 14:28:42 +000025 ExprList *pEList, /* which columns to include in the result */
drhad3cab52002-05-24 02:04:32 +000026 SrcList *pSrc, /* the FROM clause -- which tables to scan */
drhdaffd0e2001-04-11 14:28:42 +000027 Expr *pWhere, /* the WHERE clause */
28 ExprList *pGroupBy, /* the GROUP BY clause */
29 Expr *pHaving, /* the HAVING clause */
30 ExprList *pOrderBy, /* the ORDER BY clause */
drh9bbca4c2001-11-06 04:00:18 +000031 int isDistinct, /* true if the DISTINCT keyword is present */
danielk1977a2dc3b12005-02-05 12:48:48 +000032 Expr *pLimit, /* LIMIT value. NULL means not used */
33 Expr *pOffset /* OFFSET value. NULL means no offset */
drh9bb61fe2000-06-05 16:01:39 +000034){
35 Select *pNew;
36 pNew = sqliteMalloc( sizeof(*pNew) );
danielk1977a2dc3b12005-02-05 12:48:48 +000037 assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */
drhdaffd0e2001-04-11 14:28:42 +000038 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +000039 sqlite3ExprListDelete(pEList);
40 sqlite3SrcListDelete(pSrc);
41 sqlite3ExprDelete(pWhere);
42 sqlite3ExprListDelete(pGroupBy);
43 sqlite3ExprDelete(pHaving);
44 sqlite3ExprListDelete(pOrderBy);
danielk1977a2dc3b12005-02-05 12:48:48 +000045 sqlite3ExprDelete(pLimit);
46 sqlite3ExprDelete(pOffset);
drhdaffd0e2001-04-11 14:28:42 +000047 }else{
drhb733d032004-01-24 20:18:12 +000048 if( pEList==0 ){
danielk19774adee202004-05-08 08:23:19 +000049 pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
drhb733d032004-01-24 20:18:12 +000050 }
drhdaffd0e2001-04-11 14:28:42 +000051 pNew->pEList = pEList;
52 pNew->pSrc = pSrc;
53 pNew->pWhere = pWhere;
54 pNew->pGroupBy = pGroupBy;
55 pNew->pHaving = pHaving;
56 pNew->pOrderBy = pOrderBy;
57 pNew->isDistinct = isDistinct;
58 pNew->op = TK_SELECT;
danielk1977a2dc3b12005-02-05 12:48:48 +000059 pNew->pLimit = pLimit;
60 pNew->pOffset = pOffset;
drh7b58dae2003-07-20 01:16:46 +000061 pNew->iLimit = -1;
62 pNew->iOffset = -1;
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);
danielk19774adee202004-05-08 08:23:19 +0000329 sqlite3VdbeAddOp(v, OP_SortPut, 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"));
danielk19770f69c1e2004-05-29 11:24:50 +0000425 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000426 sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
drhea48eb22004-07-19 23:16:38 +0000427 if( pOrderBy==0 ){
drhbab39e12004-07-19 23:38:11 +0000428 codeLimiter(v, p, iContinue, iBreak, nColumn);
drhea48eb22004-07-19 23:16:38 +0000429 }
drh22827922000-06-06 17:27:05 +0000430 }
drh82c3d632000-06-06 21:56:07 +0000431
drhc926afb2002-06-20 03:38:26 +0000432 switch( eDest ){
danielk19775338a5f2005-01-20 13:03:10 +0000433#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhc926afb2002-06-20 03:38:26 +0000434 /* In this mode, write each query result to the key of the temporary
435 ** table iParm.
436 */
437 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000438 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000439 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000440 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000441 sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000442 break;
drh22827922000-06-06 17:27:05 +0000443 }
drh22827922000-06-06 17:27:05 +0000444
drhc926afb2002-06-20 03:38:26 +0000445 /* Construct a record from the query result, but instead of
446 ** saving that record, use it as a key to delete elements from
447 ** the temporary table iParm.
448 */
449 case SRT_Except: {
450 int addr;
danielk19774adee202004-05-08 08:23:19 +0000451 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000452 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000453 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
454 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000455 break;
456 }
danielk19775338a5f2005-01-20 13:03:10 +0000457#endif
458
459 /* Store the result as data using a unique key.
460 */
461 case SRT_Table:
462 case SRT_TempTable: {
463 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
464 if( pOrderBy ){
465 pushOntoSorter(pParse, v, pOrderBy);
466 }else{
467 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
468 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
469 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
470 }
471 break;
472 }
drh5974a302000-06-07 14:42:26 +0000473
danielk197793758c82005-01-21 08:13:14 +0000474#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000475 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
476 ** then there should be a single item on the stack. Write this
477 ** item into the set table with bogus data.
478 */
479 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000480 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000481 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000482
drhc926afb2002-06-20 03:38:26 +0000483 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000484 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
485 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
486 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000487 if( pOrderBy ){
488 pushOntoSorter(pParse, v, pOrderBy);
489 }else{
danielk1977e014a832004-05-17 10:48:57 +0000490 char aff = (iParm>>16)&0xFF;
491 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
drh94a11212004-09-25 13:12:14 +0000492 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1);
danielk19770f69c1e2004-05-29 11:24:50 +0000493 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000494 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000495 }
danielk19774adee202004-05-08 08:23:19 +0000496 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000497 break;
498 }
drh22827922000-06-06 17:27:05 +0000499
drhc926afb2002-06-20 03:38:26 +0000500 /* If this is a scalar select that is part of an expression, then
501 ** store the results in the appropriate memory cell and break out
502 ** of the scan loop.
503 */
drh51522cd2005-01-20 13:36:19 +0000504 case SRT_Exists:
drhc926afb2002-06-20 03:38:26 +0000505 case SRT_Mem: {
506 assert( nColumn==1 );
507 if( pOrderBy ){
508 pushOntoSorter(pParse, v, pOrderBy);
509 }else{
danielk19774adee202004-05-08 08:23:19 +0000510 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
511 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000512 }
513 break;
514 }
danielk197793758c82005-01-21 08:13:14 +0000515#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
drh22827922000-06-06 17:27:05 +0000516
drhf46f9052002-06-22 02:33:38 +0000517 /* Send the data to the callback function.
518 */
519 case SRT_Callback:
520 case SRT_Sorter: {
521 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000522 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000523 pushOntoSorter(pParse, v, pOrderBy);
524 }else{
525 assert( eDest==SRT_Callback );
danielk19774adee202004-05-08 08:23:19 +0000526 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000527 }
528 break;
529 }
530
drh142e30d2002-08-28 03:00:58 +0000531 /* Invoke a subroutine to handle the results. The subroutine itself
532 ** is responsible for popping the results off of the stack.
533 */
534 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000535 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000536 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000537 pushOntoSorter(pParse, v, pOrderBy);
538 }else{
danielk19774adee202004-05-08 08:23:19 +0000539 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhac82fcf2002-09-08 17:23:41 +0000540 }
drh142e30d2002-08-28 03:00:58 +0000541 break;
542 }
543
danielk19776a67fe82005-02-04 04:07:16 +0000544#if !defined(SQLITE_OMIT_TRIGGER)
drhc926afb2002-06-20 03:38:26 +0000545 /* Discard the results. This is used for SELECT statements inside
546 ** the body of a TRIGGER. The purpose of such selects is to call
547 ** user-defined functions that have side effects. We do not care
548 ** about the actual results of the select.
549 */
drhc926afb2002-06-20 03:38:26 +0000550 default: {
drhf46f9052002-06-22 02:33:38 +0000551 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000552 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000553 break;
554 }
danielk197793758c82005-01-21 08:13:14 +0000555#endif
drh82c3d632000-06-06 21:56:07 +0000556 }
557 return 0;
558}
559
560/*
drhd8bc7082000-06-07 23:51:50 +0000561** If the inner loop was generated using a non-null pOrderBy argument,
562** then the results were placed in a sorter. After the loop is terminated
563** we need to run the sorter and output the results. The following
564** routine generates the code needed to do that.
565*/
drhc926afb2002-06-20 03:38:26 +0000566static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000567 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000568 Select *p, /* The SELECT statement */
569 Vdbe *v, /* Generate code into this VDBE */
570 int nColumn, /* Number of columns of data */
571 int eDest, /* Write the sorted results here */
572 int iParm /* Optional parameter associated with eDest */
573){
danielk19774adee202004-05-08 08:23:19 +0000574 int end1 = sqlite3VdbeMakeLabel(v);
575 int end2 = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000576 int addr;
drhffbc3082004-05-21 01:29:06 +0000577 KeyInfo *pInfo;
578 ExprList *pOrderBy;
579 int nCol, i;
drh9bb575f2004-09-06 17:24:11 +0000580 sqlite3 *db = pParse->db;
drhffbc3082004-05-21 01:29:06 +0000581
drhf46f9052002-06-22 02:33:38 +0000582 if( eDest==SRT_Sorter ) return;
drhffbc3082004-05-21 01:29:06 +0000583 pOrderBy = p->pOrderBy;
584 nCol = pOrderBy->nExpr;
585 pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
586 if( pInfo==0 ) return;
587 pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
588 pInfo->nField = nCol;
589 for(i=0; i<nCol; i++){
danielk19770202b292004-06-09 09:55:16 +0000590 /* If a collation sequence was specified explicity, then it
591 ** is stored in pOrderBy->a[i].zName. Otherwise, use the default
592 ** collation type for the expression.
593 */
danielk19777cedc8d2004-06-10 10:50:08 +0000594 pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr);
danielk19770202b292004-06-09 09:55:16 +0000595 if( !pInfo->aColl[i] ){
596 pInfo->aColl[i] = db->pDfltColl;
597 }
drhffbc3082004-05-21 01:29:06 +0000598 pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
599 }
600 sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
danielk19774adee202004-05-08 08:23:19 +0000601 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
drhbab39e12004-07-19 23:38:11 +0000602 codeLimiter(v, p, addr, end2, 1);
drhc926afb2002-06-20 03:38:26 +0000603 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000604 case SRT_Table:
605 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000606 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
607 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
608 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000609 break;
610 }
danielk197793758c82005-01-21 08:13:14 +0000611#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000612 case SRT_Set: {
613 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000614 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
615 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
616 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
danielk1977ededfd52004-06-17 07:53:01 +0000617 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000618 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000619 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000620 break;
621 }
drh51522cd2005-01-20 13:36:19 +0000622 case SRT_Exists:
drhc926afb2002-06-20 03:38:26 +0000623 case SRT_Mem: {
624 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000625 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
626 sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
drhc926afb2002-06-20 03:38:26 +0000627 break;
628 }
danielk197793758c82005-01-21 08:13:14 +0000629#endif
drhce665cf2004-05-21 03:01:58 +0000630 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000631 case SRT_Subroutine: {
632 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000633 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
634 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000635 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000636 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000637 }
drhce665cf2004-05-21 03:01:58 +0000638 if( eDest==SRT_Callback ){
639 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
640 }else{
641 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
642 }
danielk197784ac9d02004-05-18 09:58:06 +0000643 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000644 break;
645 }
drhc926afb2002-06-20 03:38:26 +0000646 default: {
drhf46f9052002-06-22 02:33:38 +0000647 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000648 break;
649 }
650 }
danielk19774adee202004-05-08 08:23:19 +0000651 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
652 sqlite3VdbeResolveLabel(v, end2);
653 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
654 sqlite3VdbeResolveLabel(v, end1);
655 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000656}
657
658/*
danielk1977517eb642004-06-07 10:00:31 +0000659** Return a pointer to a string containing the 'declaration type' of the
660** expression pExpr. The string may be treated as static by the caller.
drhe78e8282003-01-19 03:59:45 +0000661**
danielk1977517eb642004-06-07 10:00:31 +0000662** If the declaration type is the exact datatype definition extracted from
663** the original CREATE TABLE statement if the expression is a column.
664**
665** The declaration type for an expression is either TEXT, NUMERIC or ANY.
666** The declaration type for a ROWID field is INTEGER.
667*/
danielk1977b3bce662005-01-29 08:32:43 +0000668static const char *columnType(NameContext *pNC, Expr *pExpr){
danielk197700e279d2004-06-21 07:36:32 +0000669 char const *zType;
danielk1977517eb642004-06-07 10:00:31 +0000670 int j;
danielk1977b3bce662005-01-29 08:32:43 +0000671 if( pExpr==0 || pNC->pSrcList==0 ) return 0;
danielk19775338a5f2005-01-20 13:03:10 +0000672
673 /* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING,
674 ** and LIMIT clauses. But pExpr originates in the result set of a
675 ** SELECT. So pExpr can never contain an AS operator.
676 */
677 assert( pExpr->op!=TK_AS );
678
danielk197700e279d2004-06-21 07:36:32 +0000679 switch( pExpr->op ){
680 case TK_COLUMN: {
danielk1977b3bce662005-01-29 08:32:43 +0000681 Table *pTab = 0;
danielk197700e279d2004-06-21 07:36:32 +0000682 int iCol = pExpr->iColumn;
danielk1977b3bce662005-01-29 08:32:43 +0000683 while( pNC && !pTab ){
684 SrcList *pTabList = pNC->pSrcList;
685 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
686 if( j<pTabList->nSrc ){
687 pTab = pTabList->a[j].pTab;
688 }else{
689 pNC = pNC->pNext;
690 }
691 }
692 assert( pTab );
danielk197700e279d2004-06-21 07:36:32 +0000693 if( iCol<0 ) iCol = pTab->iPKey;
694 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
695 if( iCol<0 ){
696 zType = "INTEGER";
697 }else{
698 zType = pTab->aCol[iCol].zType;
699 }
700 break;
danielk1977517eb642004-06-07 10:00:31 +0000701 }
danielk197793758c82005-01-21 08:13:14 +0000702#ifndef SQLITE_OMIT_SUBQUERY
danielk197700e279d2004-06-21 07:36:32 +0000703 case TK_SELECT: {
danielk1977b3bce662005-01-29 08:32:43 +0000704 NameContext sNC;
danielk197700e279d2004-06-21 07:36:32 +0000705 Select *pS = pExpr->pSelect;
danielk1977b3bce662005-01-29 08:32:43 +0000706 sNC.pSrcList = pExpr->pSelect->pSrc;
707 sNC.pNext = pNC;
708 zType = columnType(&sNC, pS->pEList->a[0].pExpr);
danielk197700e279d2004-06-21 07:36:32 +0000709 break;
danielk1977517eb642004-06-07 10:00:31 +0000710 }
danielk197793758c82005-01-21 08:13:14 +0000711#endif
danielk197700e279d2004-06-21 07:36:32 +0000712 default:
713 zType = 0;
danielk1977517eb642004-06-07 10:00:31 +0000714 }
danielk197700e279d2004-06-21 07:36:32 +0000715
danielk1977517eb642004-06-07 10:00:31 +0000716 return zType;
717}
718
719/*
720** Generate code that will tell the VDBE the declaration types of columns
721** in the result set.
drhfcb78a42003-01-18 20:11:05 +0000722*/
723static void generateColumnTypes(
724 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000725 SrcList *pTabList, /* List of tables */
726 ExprList *pEList /* Expressions defining the result set */
727){
728 Vdbe *v = pParse->pVdbe;
danielk1977517eb642004-06-07 10:00:31 +0000729 int i;
danielk1977b3bce662005-01-29 08:32:43 +0000730 NameContext sNC;
731 sNC.pSrcList = pTabList;
drhfcb78a42003-01-18 20:11:05 +0000732 for(i=0; i<pEList->nExpr; i++){
733 Expr *p = pEList->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +0000734 const char *zType = columnType(&sNC, p);
danielk197700e279d2004-06-21 07:36:32 +0000735 if( zType==0 ) continue;
danielk1977fbcd5852004-06-15 02:44:18 +0000736 /* The vdbe must make it's own copy of the column-type, in case the
737 ** schema is reset before this virtual machine is deleted.
738 */
739 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
drhfcb78a42003-01-18 20:11:05 +0000740 }
741}
742
743/*
744** Generate code that will tell the VDBE the names of columns
745** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000746** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000747*/
drh832508b2002-03-02 17:04:07 +0000748static void generateColumnNames(
749 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000750 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000751 ExprList *pEList /* Expressions defining the result set */
752){
drhd8bc7082000-06-07 23:51:50 +0000753 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000754 int i, j;
drh9bb575f2004-09-06 17:24:11 +0000755 sqlite3 *db = pParse->db;
drhfcabd462004-02-20 14:50:58 +0000756 int fullNames, shortNames;
757
drhfe2093d2005-01-20 22:48:47 +0000758#ifndef SQLITE_OMIT_EXPLAIN
danielk19773cf86062004-05-26 10:11:05 +0000759 /* If this is an EXPLAIN, skip this step */
760 if( pParse->explain ){
danielk197761de0d12004-05-27 23:56:16 +0000761 return;
danielk19773cf86062004-05-26 10:11:05 +0000762 }
danielk19775338a5f2005-01-20 13:03:10 +0000763#endif
danielk19773cf86062004-05-26 10:11:05 +0000764
drhd6502752004-02-16 03:44:01 +0000765 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000766 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000767 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000768 fullNames = (db->flags & SQLITE_FullColNames)!=0;
769 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
danielk197722322fd2004-05-25 23:35:17 +0000770 sqlite3VdbeSetNumCols(v, pEList->nExpr);
drh82c3d632000-06-06 21:56:07 +0000771 for(i=0; i<pEList->nExpr; i++){
772 Expr *p;
drh5a387052003-01-11 14:19:51 +0000773 p = pEList->a[i].pExpr;
774 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000775 if( pEList->a[i].zName ){
776 char *zName = pEList->a[i].zName;
danielk1977d8123362004-06-12 09:25:12 +0000777 sqlite3VdbeSetColName(v, i, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000778 continue;
779 }
drhfa173a72002-07-10 21:26:00 +0000780 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000781 Table *pTab;
drh97665872002-02-13 23:22:53 +0000782 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000783 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000784 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
785 assert( j<pTabList->nSrc );
786 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000787 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000788 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000789 if( iCol<0 ){
drh47a6db22005-01-18 16:02:40 +0000790 zCol = "rowid";
drhb1363202002-06-26 02:45:03 +0000791 }else{
792 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000793 }
drhfcabd462004-02-20 14:50:58 +0000794 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000795 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
drhfcabd462004-02-20 14:50:58 +0000796 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000797 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000798 char *zTab;
799
drh6a3ea0e2003-05-02 14:32:12 +0000800 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000801 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000802 sqlite3SetString(&zName, zTab, ".", zCol, 0);
danielk19773cf86062004-05-26 10:11:05 +0000803 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000804 }else{
drh47a6db22005-01-18 16:02:40 +0000805 sqlite3VdbeSetColName(v, i, zCol, strlen(zCol));
drh82c3d632000-06-06 21:56:07 +0000806 }
drh6977fea2002-10-22 23:38:04 +0000807 }else if( p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000808 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
809 /* sqlite3VdbeCompressSpace(v, addr); */
drh1bee3d72001-10-15 00:44:35 +0000810 }else{
811 char zName[30];
812 assert( p->op!=TK_COLUMN || pTabList==0 );
813 sprintf(zName, "column%d", i+1);
danielk19773cf86062004-05-26 10:11:05 +0000814 sqlite3VdbeSetColName(v, i, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000815 }
816 }
danielk197776d505b2004-05-28 13:13:02 +0000817 generateColumnTypes(pParse, pTabList, pEList);
drh82c3d632000-06-06 21:56:07 +0000818}
819
danielk197793758c82005-01-21 08:13:14 +0000820#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +0000821/*
drhd8bc7082000-06-07 23:51:50 +0000822** Name of the connection operator, used for error messages.
823*/
824static const char *selectOpName(int id){
825 char *z;
826 switch( id ){
827 case TK_ALL: z = "UNION ALL"; break;
828 case TK_INTERSECT: z = "INTERSECT"; break;
829 case TK_EXCEPT: z = "EXCEPT"; break;
830 default: z = "UNION"; break;
831 }
832 return z;
833}
danielk197793758c82005-01-21 08:13:14 +0000834#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +0000835
836/*
drh315555c2002-10-20 15:53:03 +0000837** Forward declaration
838*/
drh9b3187e2005-01-18 14:45:47 +0000839static int prepSelectStmt(Parse*, Select*);
drh315555c2002-10-20 15:53:03 +0000840
841/*
drh22f70c32002-02-18 01:17:00 +0000842** Given a SELECT statement, generate a Table structure that describes
843** the result set of that SELECT.
844*/
danielk19774adee202004-05-08 08:23:19 +0000845Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000846 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000847 int i, j;
drh22f70c32002-02-18 01:17:00 +0000848 ExprList *pEList;
drh290c1942004-08-21 17:54:45 +0000849 Column *aCol, *pCol;
drh22f70c32002-02-18 01:17:00 +0000850
drh9b3187e2005-01-18 14:45:47 +0000851 if( prepSelectStmt(pParse, pSelect) ){
drh22f70c32002-02-18 01:17:00 +0000852 return 0;
853 }
danielk1977142bdf42005-01-30 11:11:44 +0000854 if( sqlite3SelectResolve(pParse, pSelect, 0) ){
855 return 0;
856 }
drh22f70c32002-02-18 01:17:00 +0000857 pTab = sqliteMalloc( sizeof(Table) );
858 if( pTab==0 ){
859 return 0;
860 }
861 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
862 pEList = pSelect->pEList;
863 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000864 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000865 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh290c1942004-08-21 17:54:45 +0000866 for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
drh79d5f632005-01-18 17:20:10 +0000867 Expr *p, *pR;
danielk1977517eb642004-06-07 10:00:31 +0000868 char *zType;
drh91bb0ee2004-09-01 03:06:34 +0000869 char *zName;
drh79d5f632005-01-18 17:20:10 +0000870 char *zBasename;
871 int cnt;
danielk1977b3bce662005-01-29 08:32:43 +0000872 NameContext sNC;
drh79d5f632005-01-18 17:20:10 +0000873
874 /* Get an appropriate name for the column
875 */
876 p = pEList->a[i].pExpr;
drh290c1942004-08-21 17:54:45 +0000877 assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
drh91bb0ee2004-09-01 03:06:34 +0000878 if( (zName = pEList->a[i].zName)!=0 ){
drh79d5f632005-01-18 17:20:10 +0000879 /* If the column contains an "AS <name>" phrase, use <name> as the name */
drh91bb0ee2004-09-01 03:06:34 +0000880 zName = sqliteStrDup(zName);
danielk1977517eb642004-06-07 10:00:31 +0000881 }else if( p->op==TK_DOT
drh79d5f632005-01-18 17:20:10 +0000882 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
883 /* For columns of the from A.B use B as the name */
drh91bb0ee2004-09-01 03:06:34 +0000884 zName = sqlite3MPrintf("%T", &pR->token);
drhb733d032004-01-24 20:18:12 +0000885 }else if( p->span.z && p->span.z[0] ){
drh79d5f632005-01-18 17:20:10 +0000886 /* Use the original text of the column expression as its name */
drh91bb0ee2004-09-01 03:06:34 +0000887 zName = sqlite3MPrintf("%T", &p->span);
drh22f70c32002-02-18 01:17:00 +0000888 }else{
drh79d5f632005-01-18 17:20:10 +0000889 /* If all else fails, make up a name */
drh91bb0ee2004-09-01 03:06:34 +0000890 zName = sqlite3MPrintf("column%d", i+1);
drh22f70c32002-02-18 01:17:00 +0000891 }
drh91bb0ee2004-09-01 03:06:34 +0000892 sqlite3Dequote(zName);
drh79d5f632005-01-18 17:20:10 +0000893
894 /* Make sure the column name is unique. If the name is not unique,
895 ** append a integer to the name so that it becomes unique.
896 */
897 zBasename = zName;
898 for(j=cnt=0; j<i; j++){
899 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
900 zName = sqlite3MPrintf("%s:%d", zBasename, ++cnt);
901 j = -1;
902 }
903 }
904 if( zBasename!=zName ){
905 sqliteFree(zBasename);
906 }
drh91bb0ee2004-09-01 03:06:34 +0000907 pCol->zName = zName;
danielk1977517eb642004-06-07 10:00:31 +0000908
drh79d5f632005-01-18 17:20:10 +0000909 /* Get the typename, type affinity, and collating sequence for the
910 ** column.
911 */
danielk1977b3bce662005-01-29 08:32:43 +0000912 sNC.pSrcList = pSelect->pSrc;
913 zType = sqliteStrDup(columnType(&sNC, p));
drh290c1942004-08-21 17:54:45 +0000914 pCol->zType = zType;
danielk1977c60e9b82005-01-31 12:42:29 +0000915 pCol->affinity = sqlite3ExprAffinity(p);
drh290c1942004-08-21 17:54:45 +0000916 pCol->pColl = sqlite3ExprCollSeq(pParse, p);
917 if( !pCol->pColl ){
918 pCol->pColl = pParse->db->pDfltColl;
danielk19770202b292004-06-09 09:55:16 +0000919 }
drh22f70c32002-02-18 01:17:00 +0000920 }
921 pTab->iPKey = -1;
922 return pTab;
923}
924
925/*
drh9b3187e2005-01-18 14:45:47 +0000926** Prepare a SELECT statement for processing by doing the following
927** things:
drhd8bc7082000-06-07 23:51:50 +0000928**
drh9b3187e2005-01-18 14:45:47 +0000929** (1) Make sure VDBE cursor numbers have been assigned to every
930** element of the FROM clause.
931**
932** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
933** defines FROM clause. When views appear in the FROM clause,
drh63eb5f22003-04-29 16:20:44 +0000934** fill pTabList->a[].pSelect with a copy of the SELECT statement
935** that implements the view. A copy is made of the view's SELECT
936** statement so that we can freely modify or delete that statement
937** without worrying about messing up the presistent representation
938** of the view.
drhd8bc7082000-06-07 23:51:50 +0000939**
drh9b3187e2005-01-18 14:45:47 +0000940** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
drhad2d8302002-05-24 20:31:36 +0000941** on joins and the ON and USING clause of joins.
942**
drh9b3187e2005-01-18 14:45:47 +0000943** (4) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000944** for instances of the "*" operator or the TABLE.* operator.
945** If found, expand each "*" to be every column in every table
946** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000947**
948** Return 0 on success. If there are problems, leave an error message
949** in pParse and return non-zero.
950*/
drh9b3187e2005-01-18 14:45:47 +0000951static int prepSelectStmt(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000952 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000953 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000954 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000955 Table *pTab;
drh290c1942004-08-21 17:54:45 +0000956 struct SrcList_item *pFrom;
drhdaffd0e2001-04-11 14:28:42 +0000957
958 if( p==0 || p->pSrc==0 ) return 1;
959 pTabList = p->pSrc;
960 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000961
drh9b3187e2005-01-18 14:45:47 +0000962 /* Make sure cursor numbers have been assigned to all entries in
963 ** the FROM clause of the SELECT statement.
964 */
965 sqlite3SrcListAssignCursors(pParse, p->pSrc);
966
967 /* Look up every table named in the FROM clause of the select. If
968 ** an entry of the FROM clause is a subquery instead of a table or view,
969 ** then create a transient table structure to describe the subquery.
drhd8bc7082000-06-07 23:51:50 +0000970 */
drh290c1942004-08-21 17:54:45 +0000971 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
drh9b3187e2005-01-18 14:45:47 +0000972 if( pFrom->pTab!=0 ){
973 /* This statement has already been prepared. There is no need
974 ** to go further. */
975 assert( i==0 );
drhd8bc7082000-06-07 23:51:50 +0000976 return 0;
977 }
drh290c1942004-08-21 17:54:45 +0000978 if( pFrom->zName==0 ){
danielk197793758c82005-01-21 08:13:14 +0000979#ifndef SQLITE_OMIT_SUBQUERY
drh22f70c32002-02-18 01:17:00 +0000980 /* A sub-query in the FROM clause of a SELECT */
drh290c1942004-08-21 17:54:45 +0000981 assert( pFrom->pSelect!=0 );
982 if( pFrom->zAlias==0 ){
drh91bb0ee2004-09-01 03:06:34 +0000983 pFrom->zAlias =
984 sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
drhad2d8302002-05-24 20:31:36 +0000985 }
drh290c1942004-08-21 17:54:45 +0000986 pFrom->pTab = pTab =
987 sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
drh22f70c32002-02-18 01:17:00 +0000988 if( pTab==0 ){
989 return 1;
990 }
drh5cf590c2003-04-24 01:45:04 +0000991 /* The isTransient flag indicates that the Table structure has been
992 ** dynamically allocated and may be freed at any time. In other words,
993 ** pTab is not pointing to a persistent table structure that defines
994 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000995 pTab->isTransient = 1;
danielk197793758c82005-01-21 08:13:14 +0000996#endif
drh22f70c32002-02-18 01:17:00 +0000997 }else{
drha76b5df2002-02-23 02:32:10 +0000998 /* An ordinary table or view name in the FROM clause */
drh290c1942004-08-21 17:54:45 +0000999 pFrom->pTab = pTab =
1000 sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
drha76b5df2002-02-23 02:32:10 +00001001 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +00001002 return 1;
1003 }
danielk197793758c82005-01-21 08:13:14 +00001004#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00001005 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +00001006 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +00001007 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +00001008 return 1;
1009 }
drh290c1942004-08-21 17:54:45 +00001010 /* If pFrom->pSelect!=0 it means we are dealing with a
drh63eb5f22003-04-29 16:20:44 +00001011 ** view within a view. The SELECT structure has already been
1012 ** copied by the outer view so we can skip the copy step here
1013 ** in the inner view.
1014 */
drh290c1942004-08-21 17:54:45 +00001015 if( pFrom->pSelect==0 ){
1016 pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +00001017 }
drha76b5df2002-02-23 02:32:10 +00001018 }
danielk197793758c82005-01-21 08:13:14 +00001019#endif
drhd8bc7082000-06-07 23:51:50 +00001020 }
1021 }
1022
drhad2d8302002-05-24 20:31:36 +00001023 /* Process NATURAL keywords, and ON and USING clauses of joins.
1024 */
1025 if( sqliteProcessJoin(pParse, p) ) return 1;
1026
drh7c917d12001-12-16 20:05:05 +00001027 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +00001028 ** all columns in all tables. And for every TABLE.* insert the names
1029 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +00001030 ** with the TK_ALL operator for each "*" that it found in the column list.
1031 ** The following code just has to locate the TK_ALL expressions and expand
1032 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +00001033 **
1034 ** The first loop just checks to see if there are any "*" operators
1035 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +00001036 */
drh7c917d12001-12-16 20:05:05 +00001037 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001038 Expr *pE = pEList->a[k].pExpr;
1039 if( pE->op==TK_ALL ) break;
1040 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
1041 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +00001042 }
drh54473222002-04-04 02:10:55 +00001043 rc = 0;
drh7c917d12001-12-16 20:05:05 +00001044 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +00001045 /*
1046 ** If we get here it means the result set contains one or more "*"
1047 ** operators that need to be expanded. Loop through each expression
1048 ** in the result set and expand them one by one.
1049 */
drh7c917d12001-12-16 20:05:05 +00001050 struct ExprList_item *a = pEList->a;
1051 ExprList *pNew = 0;
1052 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001053 Expr *pE = a[k].pExpr;
1054 if( pE->op!=TK_ALL &&
1055 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
1056 /* This particular expression does not need to be expanded.
1057 */
danielk19774adee202004-05-08 08:23:19 +00001058 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001059 pNew->a[pNew->nExpr-1].zName = a[k].zName;
1060 a[k].pExpr = 0;
1061 a[k].zName = 0;
1062 }else{
drh54473222002-04-04 02:10:55 +00001063 /* This expression is a "*" or a "TABLE.*" and needs to be
1064 ** expanded. */
1065 int tableSeen = 0; /* Set to 1 when TABLE matches */
drhcf55b7a2004-07-20 01:45:19 +00001066 char *zTName; /* text of name of TABLE */
drh54473222002-04-04 02:10:55 +00001067 if( pE->op==TK_DOT && pE->pLeft ){
drhcf55b7a2004-07-20 01:45:19 +00001068 zTName = sqlite3NameFromToken(&pE->pLeft->token);
drh54473222002-04-04 02:10:55 +00001069 }else{
drhcf55b7a2004-07-20 01:45:19 +00001070 zTName = 0;
drh54473222002-04-04 02:10:55 +00001071 }
drh290c1942004-08-21 17:54:45 +00001072 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1073 Table *pTab = pFrom->pTab;
1074 char *zTabName = pFrom->zAlias;
drh54473222002-04-04 02:10:55 +00001075 if( zTabName==0 || zTabName[0]==0 ){
1076 zTabName = pTab->zName;
1077 }
drhcf55b7a2004-07-20 01:45:19 +00001078 if( zTName && (zTabName==0 || zTabName[0]==0 ||
1079 sqlite3StrICmp(zTName, zTabName)!=0) ){
drh54473222002-04-04 02:10:55 +00001080 continue;
1081 }
1082 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001083 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001084 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001085 char *zName = pTab->aCol[j].zName;
1086
drh91bb0ee2004-09-01 03:06:34 +00001087 if( i>0 ){
1088 struct SrcList_item *pLeft = &pTabList->a[i-1];
1089 if( (pLeft->jointype & JT_NATURAL)!=0 &&
1090 columnIndex(pLeft->pTab, zName)>=0 ){
1091 /* In a NATURAL join, omit the join columns from the
1092 ** table on the right */
1093 continue;
1094 }
1095 if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1096 /* In a join with a USING clause, omit columns in the
1097 ** using clause from the table on the right. */
1098 continue;
1099 }
drhad2d8302002-05-24 20:31:36 +00001100 }
danielk19774adee202004-05-08 08:23:19 +00001101 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001102 if( pRight==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001103 setToken(&pRight->token, zName);
drh4b59ab52002-08-24 18:24:51 +00001104 if( zTabName && pTabList->nSrc>1 ){
danielk19774adee202004-05-08 08:23:19 +00001105 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1106 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001107 if( pExpr==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001108 setToken(&pLeft->token, zTabName);
1109 setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
drh6977fea2002-10-22 23:38:04 +00001110 pExpr->span.dyn = 1;
1111 pExpr->token.z = 0;
1112 pExpr->token.n = 0;
1113 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001114 }else{
drh22f70c32002-02-18 01:17:00 +00001115 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001116 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001117 }
drh79d5f632005-01-18 17:20:10 +00001118 pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
drh7c917d12001-12-16 20:05:05 +00001119 }
drh17e24df2001-11-06 14:10:41 +00001120 }
drh54473222002-04-04 02:10:55 +00001121 if( !tableSeen ){
drhcf55b7a2004-07-20 01:45:19 +00001122 if( zTName ){
1123 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
drhf5db2d32002-06-06 23:42:27 +00001124 }else{
danielk19774adee202004-05-08 08:23:19 +00001125 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001126 }
drh54473222002-04-04 02:10:55 +00001127 rc = 1;
1128 }
drhcf55b7a2004-07-20 01:45:19 +00001129 sqliteFree(zTName);
drhd8bc7082000-06-07 23:51:50 +00001130 }
1131 }
danielk19774adee202004-05-08 08:23:19 +00001132 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001133 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001134 }
drh54473222002-04-04 02:10:55 +00001135 return rc;
drhd8bc7082000-06-07 23:51:50 +00001136}
1137
1138/*
drhff78bd22002-02-27 01:47:11 +00001139** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1140** in a select structure. It just sets the pointers to NULL. This
1141** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1142** pointer is not NULL, this routine is called recursively on that pointer.
1143**
1144** This routine is called on the Select structure that defines a
1145** VIEW in order to undo any bindings to tables. This is necessary
1146** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001147** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1148** will be left pointing to a deallocated Table structure after the
1149** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001150*/
danielk19775338a5f2005-01-20 13:03:10 +00001151#if 0
danielk19774adee202004-05-08 08:23:19 +00001152void sqlite3SelectUnbind(Select *p){
drhff78bd22002-02-27 01:47:11 +00001153 int i;
drhad3cab52002-05-24 02:04:32 +00001154 SrcList *pSrc = p->pSrc;
drh91bb0ee2004-09-01 03:06:34 +00001155 struct SrcList_item *pItem;
drhff78bd22002-02-27 01:47:11 +00001156 Table *pTab;
1157 if( p==0 ) return;
drh91bb0ee2004-09-01 03:06:34 +00001158 for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
1159 if( (pTab = pItem->pTab)!=0 ){
drhff78bd22002-02-27 01:47:11 +00001160 if( pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001161 sqlite3DeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001162 }
drh91bb0ee2004-09-01 03:06:34 +00001163 pItem->pTab = 0;
1164 if( pItem->pSelect ){
1165 sqlite3SelectUnbind(pItem->pSelect);
drhff78bd22002-02-27 01:47:11 +00001166 }
1167 }
1168 }
1169}
danielk19775338a5f2005-01-20 13:03:10 +00001170#endif
drhff78bd22002-02-27 01:47:11 +00001171
danielk197793758c82005-01-21 08:13:14 +00001172#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhff78bd22002-02-27 01:47:11 +00001173/*
drhd8bc7082000-06-07 23:51:50 +00001174** This routine associates entries in an ORDER BY expression list with
1175** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001176** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001177** the top-level node is filled in with column number and the iTable
1178** value of the top-level node is filled with iTable parameter.
1179**
1180** If there are prior SELECT clauses, they are processed first. A match
1181** in an earlier SELECT takes precedence over a later SELECT.
1182**
1183** Any entry that does not match is flagged as an error. The number
1184** of errors is returned.
1185*/
1186static int matchOrderbyToColumn(
1187 Parse *pParse, /* A place to leave error messages */
1188 Select *pSelect, /* Match to result columns of this SELECT */
1189 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001190 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001191 int mustComplete /* If TRUE all ORDER BYs must match */
1192){
1193 int nErr = 0;
1194 int i, j;
1195 ExprList *pEList;
1196
drhdaffd0e2001-04-11 14:28:42 +00001197 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001198 if( mustComplete ){
1199 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1200 }
drh9b3187e2005-01-18 14:45:47 +00001201 if( prepSelectStmt(pParse, pSelect) ){
drhd8bc7082000-06-07 23:51:50 +00001202 return 1;
1203 }
1204 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001205 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1206 return 1;
1207 }
drhd8bc7082000-06-07 23:51:50 +00001208 }
1209 pEList = pSelect->pEList;
1210 for(i=0; i<pOrderBy->nExpr; i++){
1211 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001212 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001213 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001214 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001215 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001216 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001217 "ORDER BY position %d should be between 1 and %d",
1218 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001219 nErr++;
1220 break;
1221 }
drhfcb78a42003-01-18 20:11:05 +00001222 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001223 iCol--;
1224 }
1225 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001226 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001227 char *zName, *zLabel;
1228 zName = pEList->a[j].zName;
drha99db3b2004-06-19 14:49:12 +00001229 zLabel = sqlite3NameFromToken(&pE->token);
1230 assert( zLabel!=0 );
danielk19774adee202004-05-08 08:23:19 +00001231 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001232 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001233 }
drh6e142f52000-06-08 13:36:40 +00001234 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001235 }
danielk19774adee202004-05-08 08:23:19 +00001236 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001237 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001238 }
1239 }
drhe4de1fe2002-06-02 16:09:01 +00001240 if( iCol>=0 ){
1241 pE->op = TK_COLUMN;
1242 pE->iColumn = iCol;
1243 pE->iTable = iTable;
danielk1977a58fdfb2005-02-08 07:50:40 +00001244 pE->iAgg = -1;
drhe4de1fe2002-06-02 16:09:01 +00001245 pOrderBy->a[i].done = 1;
1246 }
1247 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001248 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001249 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001250 nErr++;
1251 break;
1252 }
1253 }
1254 return nErr;
1255}
danielk197793758c82005-01-21 08:13:14 +00001256#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +00001257
1258/*
1259** Get a VDBE for the given parser context. Create a new one if necessary.
1260** If an error occurs, return NULL and leave a message in pParse.
1261*/
danielk19774adee202004-05-08 08:23:19 +00001262Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001263 Vdbe *v = pParse->pVdbe;
1264 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001265 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001266 }
drhd8bc7082000-06-07 23:51:50 +00001267 return v;
1268}
drhfcb78a42003-01-18 20:11:05 +00001269
drhd8bc7082000-06-07 23:51:50 +00001270/*
drh7b58dae2003-07-20 01:16:46 +00001271** Compute the iLimit and iOffset fields of the SELECT based on the
danielk1977a2dc3b12005-02-05 12:48:48 +00001272** pLimit and pOffset expressions. nLimit and nOffset hold the expressions
drh7b58dae2003-07-20 01:16:46 +00001273** that appear in the original SQL statement after the LIMIT and OFFSET
danielk1977a2dc3b12005-02-05 12:48:48 +00001274** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
1275** are the integer memory register numbers for counters used to compute
1276** the limit and offset. If there is no limit and/or offset, then
1277** iLimit and iOffset are negative.
drh7b58dae2003-07-20 01:16:46 +00001278**
1279** This routine changes the values if iLimit and iOffset only if
1280** a limit or offset is defined by nLimit and nOffset. iLimit and
1281** iOffset should have been preset to appropriate default values
1282** (usually but not always -1) prior to calling this routine.
1283** Only if nLimit>=0 or nOffset>0 do the limit registers get
1284** redefined. The UNION ALL operator uses this property to force
1285** the reuse of the same limit and offset registers across multiple
1286** SELECT statements.
1287*/
1288static void computeLimitRegisters(Parse *pParse, Select *p){
1289 /*
drh7b58dae2003-07-20 01:16:46 +00001290 ** "LIMIT -1" always shows all rows. There is some
1291 ** contraversy about what the correct behavior should be.
1292 ** The current implementation interprets "LIMIT 0" to mean
1293 ** no rows.
1294 */
danielk1977a2dc3b12005-02-05 12:48:48 +00001295 if( p->pLimit ){
drh7b58dae2003-07-20 01:16:46 +00001296 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001297 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001298 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001299 sqlite3ExprCode(pParse, p->pLimit);
1300 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1301 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001302 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001303 VdbeComment((v, "# LIMIT counter"));
drh7b58dae2003-07-20 01:16:46 +00001304 p->iLimit = iMem;
1305 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001306 if( p->pOffset ){
drh7b58dae2003-07-20 01:16:46 +00001307 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001308 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001309 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001310 sqlite3ExprCode(pParse, p->pOffset);
1311 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1312 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001313 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001314 VdbeComment((v, "# OFFSET counter"));
drh7b58dae2003-07-20 01:16:46 +00001315 p->iOffset = iMem;
1316 }
1317}
1318
1319/*
drhd3d39e92004-05-20 22:16:29 +00001320** Generate VDBE instructions that will open a transient table that
1321** will be used for an index or to store keyed results for a compound
1322** select. In other words, open a transient table that needs a
1323** KeyInfo structure. The number of columns in the KeyInfo is determined
1324** by the result set of the SELECT statement in the second argument.
1325**
danielk1977dc1bdc42004-06-11 10:51:27 +00001326** Specifically, this routine is called to open an index table for
1327** DISTINCT, UNION, INTERSECT and EXCEPT select statements (but not
1328** UNION ALL).
1329**
drhd3d39e92004-05-20 22:16:29 +00001330** Make the new table a KeyAsData table if keyAsData is true.
danielk1977dc1bdc42004-06-11 10:51:27 +00001331**
1332** The value returned is the address of the OP_OpenTemp instruction.
drhd3d39e92004-05-20 22:16:29 +00001333*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001334static int openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
drhd3d39e92004-05-20 22:16:29 +00001335 KeyInfo *pKeyInfo;
drh736c22b2004-05-21 02:14:24 +00001336 int nColumn;
drh9bb575f2004-09-06 17:24:11 +00001337 sqlite3 *db = pParse->db;
drhd3d39e92004-05-20 22:16:29 +00001338 int i;
1339 Vdbe *v = pParse->pVdbe;
danielk1977dc1bdc42004-06-11 10:51:27 +00001340 int addr;
drhd3d39e92004-05-20 22:16:29 +00001341
drh9b3187e2005-01-18 14:45:47 +00001342 if( prepSelectStmt(pParse, p) ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001343 return 0;
drh736c22b2004-05-21 02:14:24 +00001344 }
1345 nColumn = p->pEList->nExpr;
drhd3d39e92004-05-20 22:16:29 +00001346 pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
danielk1977dc1bdc42004-06-11 10:51:27 +00001347 if( pKeyInfo==0 ) return 0;
drh91bb0ee2004-09-01 03:06:34 +00001348 pKeyInfo->enc = db->enc;
drhd3d39e92004-05-20 22:16:29 +00001349 pKeyInfo->nField = nColumn;
1350 for(i=0; i<nColumn; i++){
danielk1977dc1bdc42004-06-11 10:51:27 +00001351 pKeyInfo->aColl[i] = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
1352 if( !pKeyInfo->aColl[i] ){
1353 pKeyInfo->aColl[i] = db->pDfltColl;
1354 }
drhd3d39e92004-05-20 22:16:29 +00001355 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001356 addr = sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0,
1357 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drhd3d39e92004-05-20 22:16:29 +00001358 if( keyAsData ){
1359 sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1360 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001361 return addr;
1362}
1363
drhb7f91642004-10-31 02:22:47 +00001364#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001365/*
drh8cdbf832004-08-29 16:25:03 +00001366** Add the address "addr" to the set of all OpenTemp opcode addresses
1367** that are being accumulated in p->ppOpenTemp.
drhfbc4ee72004-08-29 01:31:05 +00001368*/
drh8cdbf832004-08-29 16:25:03 +00001369static int multiSelectOpenTempAddr(Select *p, int addr){
1370 IdList *pList = *p->ppOpenTemp = sqlite3IdListAppend(*p->ppOpenTemp, 0);
drhfbc4ee72004-08-29 01:31:05 +00001371 if( pList==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001372 return SQLITE_NOMEM;
1373 }
drhfbc4ee72004-08-29 01:31:05 +00001374 pList->a[pList->nId-1].idx = addr;
danielk1977dc1bdc42004-06-11 10:51:27 +00001375 return SQLITE_OK;
1376}
drhb7f91642004-10-31 02:22:47 +00001377#endif /* SQLITE_OMIT_COMPOUND_SELECT */
danielk1977dc1bdc42004-06-11 10:51:27 +00001378
drhb7f91642004-10-31 02:22:47 +00001379#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001380/*
1381** Return the appropriate collating sequence for the iCol-th column of
1382** the result set for the compound-select statement "p". Return NULL if
1383** the column has no default collating sequence.
1384**
1385** The collating sequence for the compound select is taken from the
1386** left-most term of the select that has a collating sequence.
1387*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001388static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
drhfbc4ee72004-08-29 01:31:05 +00001389 CollSeq *pRet;
danielk1977dc1bdc42004-06-11 10:51:27 +00001390 if( p->pPrior ){
1391 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
drhfbc4ee72004-08-29 01:31:05 +00001392 }else{
1393 pRet = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001394 }
drhfbc4ee72004-08-29 01:31:05 +00001395 if( pRet==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001396 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1397 }
1398 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001399}
drhb7f91642004-10-31 02:22:47 +00001400#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd3d39e92004-05-20 22:16:29 +00001401
drhb7f91642004-10-31 02:22:47 +00001402#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhd3d39e92004-05-20 22:16:29 +00001403/*
drh82c3d632000-06-06 21:56:07 +00001404** This routine is called to process a query that is really the union
1405** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001406**
drhe78e8282003-01-19 03:59:45 +00001407** "p" points to the right-most of the two queries. the query on the
1408** left is p->pPrior. The left query could also be a compound query
1409** in which case this routine will be called recursively.
1410**
1411** The results of the total query are to be written into a destination
1412** of type eDest with parameter iParm.
1413**
1414** Example 1: Consider a three-way compound SQL statement.
1415**
1416** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1417**
1418** This statement is parsed up as follows:
1419**
1420** SELECT c FROM t3
1421** |
1422** `-----> SELECT b FROM t2
1423** |
jplyon4b11c6d2004-01-19 04:57:53 +00001424** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001425**
1426** The arrows in the diagram above represent the Select.pPrior pointer.
1427** So if this routine is called with p equal to the t3 query, then
1428** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1429**
1430** Notice that because of the way SQLite parses compound SELECTs, the
1431** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001432*/
danielk197784ac9d02004-05-18 09:58:06 +00001433static int multiSelect(
drhfbc4ee72004-08-29 01:31:05 +00001434 Parse *pParse, /* Parsing context */
1435 Select *p, /* The right-most of SELECTs to be coded */
1436 int eDest, /* \___ Store query results as specified */
1437 int iParm, /* / by these two parameters. */
1438 char *aff /* If eDest is SRT_Union, the affinity string */
danielk197784ac9d02004-05-18 09:58:06 +00001439){
drhfbc4ee72004-08-29 01:31:05 +00001440 int rc = SQLITE_OK; /* Success code from a subroutine */
1441 Select *pPrior; /* Another SELECT immediately to our left */
1442 Vdbe *v; /* Generate code to this VDBE */
1443 IdList *pOpenTemp = 0;/* OP_OpenTemp opcodes that need a KeyInfo */
drh8cdbf832004-08-29 16:25:03 +00001444 int aAddr[5]; /* Addresses of SetNumColumns operators */
1445 int nAddr = 0; /* Number used */
1446 int nCol; /* Number of columns in the result set */
drh82c3d632000-06-06 21:56:07 +00001447
drh7b58dae2003-07-20 01:16:46 +00001448 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
drhfbc4ee72004-08-29 01:31:05 +00001449 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001450 */
danielk197784ac9d02004-05-18 09:58:06 +00001451 if( p==0 || p->pPrior==0 ){
1452 rc = 1;
1453 goto multi_select_end;
1454 }
drhd8bc7082000-06-07 23:51:50 +00001455 pPrior = p->pPrior;
1456 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001457 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001458 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001459 rc = 1;
1460 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001461 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001462 if( pPrior->pLimit ){
danielk19774adee202004-05-08 08:23:19 +00001463 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001464 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001465 rc = 1;
1466 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001467 }
drh82c3d632000-06-06 21:56:07 +00001468
drhd8bc7082000-06-07 23:51:50 +00001469 /* Make sure we have a valid query engine. If not, create a new one.
1470 */
danielk19774adee202004-05-08 08:23:19 +00001471 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001472 if( v==0 ){
1473 rc = 1;
1474 goto multi_select_end;
1475 }
drhd8bc7082000-06-07 23:51:50 +00001476
drh8cdbf832004-08-29 16:25:03 +00001477 /* If *p this is the right-most select statement, then initialize
1478 ** p->ppOpenTemp to point to pOpenTemp. If *p is not the right most
1479 ** statement then p->ppOpenTemp will have already been initialized
1480 ** by a prior call to this same procedure. Pass along the pOpenTemp
1481 ** pointer to pPrior, the next statement to our left.
drhfbc4ee72004-08-29 01:31:05 +00001482 */
1483 if( p->ppOpenTemp==0 ){
1484 p->ppOpenTemp = &pOpenTemp;
1485 }
1486 pPrior->ppOpenTemp = p->ppOpenTemp;
1487
drh1cc3d752002-03-23 00:31:29 +00001488 /* Create the destination temporary table if necessary
1489 */
1490 if( eDest==SRT_TempTable ){
danielk1977b4964b72004-05-18 01:23:38 +00001491 assert( p->pEList );
danielk19774adee202004-05-08 08:23:19 +00001492 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
drh8cdbf832004-08-29 16:25:03 +00001493 assert( nAddr==0 );
1494 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 0);
drh1cc3d752002-03-23 00:31:29 +00001495 eDest = SRT_Table;
1496 }
1497
drhf46f9052002-06-22 02:33:38 +00001498 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001499 */
drh82c3d632000-06-06 21:56:07 +00001500 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001501 case TK_ALL: {
1502 if( p->pOrderBy==0 ){
danielk1977a2dc3b12005-02-05 12:48:48 +00001503 assert( !pPrior->pLimit );
1504 pPrior->pLimit = p->pLimit;
1505 pPrior->pOffset = p->pOffset;
danielk1977b3bce662005-01-29 08:32:43 +00001506 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001507 if( rc ){
1508 goto multi_select_end;
1509 }
drhf46f9052002-06-22 02:33:38 +00001510 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001511 p->iLimit = pPrior->iLimit;
1512 p->iOffset = pPrior->iOffset;
danielk1977a2dc3b12005-02-05 12:48:48 +00001513 p->pLimit = 0;
1514 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001515 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001516 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001517 if( rc ){
1518 goto multi_select_end;
1519 }
drhf46f9052002-06-22 02:33:38 +00001520 break;
1521 }
1522 /* For UNION ALL ... ORDER BY fall through to the next case */
1523 }
drh82c3d632000-06-06 21:56:07 +00001524 case TK_EXCEPT:
1525 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001526 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001527 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001528 int priorOp; /* The SRT_ operation to apply to prior selects */
danielk1977a2dc3b12005-02-05 12:48:48 +00001529 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1530 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
danielk1977dc1bdc42004-06-11 10:51:27 +00001531 int addr;
drh82c3d632000-06-06 21:56:07 +00001532
drhd8bc7082000-06-07 23:51:50 +00001533 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
danielk1977a2dc3b12005-02-05 12:48:48 +00001534 if( eDest==priorOp && p->pOrderBy==0 && !p->pLimit && !p->pOffset ){
drhd8bc7082000-06-07 23:51:50 +00001535 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001536 ** right.
drhd8bc7082000-06-07 23:51:50 +00001537 */
drh82c3d632000-06-06 21:56:07 +00001538 unionTab = iParm;
1539 }else{
drhd8bc7082000-06-07 23:51:50 +00001540 /* We will need to create our own temporary table to hold the
1541 ** intermediate results.
1542 */
1543 unionTab = pParse->nTab++;
1544 if( p->pOrderBy
1545 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001546 rc = 1;
1547 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001548 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001549 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001550 if( p->op!=TK_ALL ){
drh8cdbf832004-08-29 16:25:03 +00001551 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001552 if( rc!=SQLITE_OK ){
1553 goto multi_select_end;
1554 }
1555 sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drhd8bc7082000-06-07 23:51:50 +00001556 }
drh8cdbf832004-08-29 16:25:03 +00001557 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1558 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, 0);
danielk197784ac9d02004-05-18 09:58:06 +00001559 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001560 }
drhd8bc7082000-06-07 23:51:50 +00001561
1562 /* Code the SELECT statements to our left
1563 */
danielk1977b3bce662005-01-29 08:32:43 +00001564 assert( !pPrior->pOrderBy );
1565 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001566 if( rc ){
1567 goto multi_select_end;
1568 }
drhd8bc7082000-06-07 23:51:50 +00001569
1570 /* Code the current SELECT statement
1571 */
1572 switch( p->op ){
1573 case TK_EXCEPT: op = SRT_Except; break;
1574 case TK_UNION: op = SRT_Union; break;
1575 case TK_ALL: op = SRT_Table; break;
1576 }
drh82c3d632000-06-06 21:56:07 +00001577 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001578 pOrderBy = p->pOrderBy;
1579 p->pOrderBy = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001580 pLimit = p->pLimit;
1581 p->pLimit = 0;
1582 pOffset = p->pOffset;
1583 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001584 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001585 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001586 p->pOrderBy = pOrderBy;
danielk1977a2dc3b12005-02-05 12:48:48 +00001587 sqlite3ExprDelete(p->pLimit);
1588 p->pLimit = pLimit;
1589 p->pOffset = pOffset;
drhbe5fd492004-12-16 21:09:16 +00001590 p->iLimit = -1;
1591 p->iOffset = -1;
danielk197784ac9d02004-05-18 09:58:06 +00001592 if( rc ){
1593 goto multi_select_end;
1594 }
1595
drhd8bc7082000-06-07 23:51:50 +00001596
1597 /* Convert the data in the temporary table into whatever form
1598 ** it is that we currently need.
1599 */
drhc926afb2002-06-20 03:38:26 +00001600 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001601 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001602 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001603 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001604 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001605 }
danielk19774adee202004-05-08 08:23:19 +00001606 iBreak = sqlite3VdbeMakeLabel(v);
1607 iCont = sqlite3VdbeMakeLabel(v);
1608 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001609 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001610 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001611 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001612 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001613 iCont, iBreak, 0);
1614 if( rc ){
1615 rc = 1;
1616 goto multi_select_end;
1617 }
danielk19774adee202004-05-08 08:23:19 +00001618 sqlite3VdbeResolveLabel(v, iCont);
1619 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1620 sqlite3VdbeResolveLabel(v, iBreak);
1621 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001622 }
1623 break;
1624 }
1625 case TK_INTERSECT: {
1626 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001627 int iCont, iBreak, iStart;
danielk1977a2dc3b12005-02-05 12:48:48 +00001628 Expr *pLimit, *pOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001629 int addr;
drh82c3d632000-06-06 21:56:07 +00001630
drhd8bc7082000-06-07 23:51:50 +00001631 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001632 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001633 ** by allocating the tables we will need.
1634 */
drh82c3d632000-06-06 21:56:07 +00001635 tab1 = pParse->nTab++;
1636 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001637 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001638 rc = 1;
1639 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001640 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001641
1642 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 0);
drh8cdbf832004-08-29 16:25:03 +00001643 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001644 if( rc!=SQLITE_OK ){
1645 goto multi_select_end;
1646 }
1647 sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
drh8cdbf832004-08-29 16:25:03 +00001648 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1649 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab1, 0);
danielk197784ac9d02004-05-18 09:58:06 +00001650 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001651
1652 /* Code the SELECTs to our left into temporary table "tab1".
1653 */
danielk1977b3bce662005-01-29 08:32:43 +00001654 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001655 if( rc ){
1656 goto multi_select_end;
1657 }
drhd8bc7082000-06-07 23:51:50 +00001658
1659 /* Code the current SELECT into temporary table "tab2"
1660 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001661 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0);
drh8cdbf832004-08-29 16:25:03 +00001662 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001663 if( rc!=SQLITE_OK ){
1664 goto multi_select_end;
1665 }
1666 sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh8cdbf832004-08-29 16:25:03 +00001667 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1668 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab2, 0);
drh82c3d632000-06-06 21:56:07 +00001669 p->pPrior = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001670 pLimit = p->pLimit;
1671 p->pLimit = 0;
1672 pOffset = p->pOffset;
1673 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001674 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001675 p->pPrior = pPrior;
danielk1977a2dc3b12005-02-05 12:48:48 +00001676 sqlite3ExprDelete(p->pLimit);
1677 p->pLimit = pLimit;
1678 p->pOffset = pOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001679 if( rc ){
1680 goto multi_select_end;
1681 }
drhd8bc7082000-06-07 23:51:50 +00001682
1683 /* Generate code to take the intersection of the two temporary
1684 ** tables.
1685 */
drh82c3d632000-06-06 21:56:07 +00001686 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001687 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001688 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001689 }
danielk19774adee202004-05-08 08:23:19 +00001690 iBreak = sqlite3VdbeMakeLabel(v);
1691 iCont = sqlite3VdbeMakeLabel(v);
1692 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001693 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001694 iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
1695 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001696 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001697 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001698 iCont, iBreak, 0);
1699 if( rc ){
1700 rc = 1;
1701 goto multi_select_end;
1702 }
danielk19774adee202004-05-08 08:23:19 +00001703 sqlite3VdbeResolveLabel(v, iCont);
1704 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1705 sqlite3VdbeResolveLabel(v, iBreak);
1706 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1707 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001708 break;
1709 }
1710 }
drh8cdbf832004-08-29 16:25:03 +00001711
1712 /* Make sure all SELECTs in the statement have the same number of elements
1713 ** in their result sets.
1714 */
drh82c3d632000-06-06 21:56:07 +00001715 assert( p->pEList && pPrior->pEList );
1716 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001717 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001718 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001719 rc = 1;
1720 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001721 }
danielk197784ac9d02004-05-18 09:58:06 +00001722
drh8cdbf832004-08-29 16:25:03 +00001723 /* Set the number of columns in temporary tables
1724 */
1725 nCol = p->pEList->nExpr;
1726 while( nAddr>0 ){
1727 nAddr--;
1728 sqlite3VdbeChangeP2(v, aAddr[nAddr], nCol);
1729 }
1730
drhfbc4ee72004-08-29 01:31:05 +00001731 /* Compute collating sequences used by either the ORDER BY clause or
1732 ** by any temporary tables needed to implement the compound select.
1733 ** Attach the KeyInfo structure to all temporary tables. Invoke the
1734 ** ORDER BY processing if there is an ORDER BY clause.
drh8cdbf832004-08-29 16:25:03 +00001735 **
1736 ** This section is run by the right-most SELECT statement only.
1737 ** SELECT statements to the left always skip this part. The right-most
1738 ** SELECT might also skip this part if it has no ORDER BY clause and
1739 ** no temp tables are required.
drhfbc4ee72004-08-29 01:31:05 +00001740 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001741 if( p->pOrderBy || (pOpenTemp && pOpenTemp->nId>0) ){
drhfbc4ee72004-08-29 01:31:05 +00001742 int i; /* Loop counter */
1743 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
1744
drh8cdbf832004-08-29 16:25:03 +00001745 assert( p->ppOpenTemp == &pOpenTemp );
drhfbc4ee72004-08-29 01:31:05 +00001746 pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*sizeof(CollSeq*));
danielk1977dc1bdc42004-06-11 10:51:27 +00001747 if( !pKeyInfo ){
1748 rc = SQLITE_NOMEM;
1749 goto multi_select_end;
1750 }
1751
1752 pKeyInfo->enc = pParse->db->enc;
1753 pKeyInfo->nField = nCol;
1754
1755 for(i=0; i<nCol; i++){
1756 pKeyInfo->aColl[i] = multiSelectCollSeq(pParse, p, i);
1757 if( !pKeyInfo->aColl[i] ){
1758 pKeyInfo->aColl[i] = pParse->db->pDfltColl;
1759 }
1760 }
1761
1762 for(i=0; pOpenTemp && i<pOpenTemp->nId; i++){
1763 int p3type = (i==0?P3_KEYINFO_HANDOFF:P3_KEYINFO);
1764 int addr = pOpenTemp->a[i].idx;
1765 sqlite3VdbeChangeP3(v, addr, (char *)pKeyInfo, p3type);
1766 }
1767
1768 if( p->pOrderBy ){
drhfbc4ee72004-08-29 01:31:05 +00001769 struct ExprList_item *pOrderByTerm = p->pOrderBy->a;
1770 for(i=0; i<p->pOrderBy->nExpr; i++, pOrderByTerm++){
1771 Expr *pExpr = pOrderByTerm->pExpr;
1772 char *zName = pOrderByTerm->zName;
danielk1977dc1bdc42004-06-11 10:51:27 +00001773 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
danielk1977b3bce662005-01-29 08:32:43 +00001774 /* assert( !pExpr->pColl ); */
danielk1977dc1bdc42004-06-11 10:51:27 +00001775 if( zName ){
1776 pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1);
1777 }else{
1778 pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn];
1779 }
1780 }
1781 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1782 }
1783
1784 if( !pOpenTemp ){
1785 /* This happens for UNION ALL ... ORDER BY */
1786 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001787 }
1788 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001789
1790multi_select_end:
1791 if( pOpenTemp ){
1792 sqlite3IdListDelete(pOpenTemp);
1793 }
1794 p->ppOpenTemp = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001795 return rc;
drh22827922000-06-06 17:27:05 +00001796}
drhb7f91642004-10-31 02:22:47 +00001797#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drh22827922000-06-06 17:27:05 +00001798
drhb7f91642004-10-31 02:22:47 +00001799#ifndef SQLITE_OMIT_VIEW
drh22827922000-06-06 17:27:05 +00001800/*
drh832508b2002-03-02 17:04:07 +00001801** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001802** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001803** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001804** unchanged.)
drh832508b2002-03-02 17:04:07 +00001805**
1806** This routine is part of the flattening procedure. A subquery
1807** whose result set is defined by pEList appears as entry in the
1808** FROM clause of a SELECT such that the VDBE cursor assigned to that
1809** FORM clause entry is iTable. This routine make the necessary
1810** changes to pExpr so that it refers directly to the source table
1811** of the subquery rather the result set of the subquery.
1812*/
drh6a3ea0e2003-05-02 14:32:12 +00001813static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
danielk1977b3bce662005-01-29 08:32:43 +00001814static void substSelect(Select *, int, ExprList *); /* Forward Decl */
drh6a3ea0e2003-05-02 14:32:12 +00001815static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001816 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001817 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1818 if( pExpr->iColumn<0 ){
1819 pExpr->op = TK_NULL;
1820 }else{
1821 Expr *pNew;
1822 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1823 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1824 pNew = pEList->a[pExpr->iColumn].pExpr;
1825 assert( pNew!=0 );
1826 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001827 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001828 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001829 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001830 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001831 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001832 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001833 pExpr->iTable = pNew->iTable;
1834 pExpr->iColumn = pNew->iColumn;
1835 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001836 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1837 sqlite3TokenCopy(&pExpr->span, &pNew->span);
danielk1977a1cb1832005-02-12 08:59:55 +00001838 pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
1839 pExpr->flags = pNew->flags;
drh50350a12004-02-13 16:22:22 +00001840 }
drh832508b2002-03-02 17:04:07 +00001841 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001842 substExpr(pExpr->pLeft, iTable, pEList);
1843 substExpr(pExpr->pRight, iTable, pEList);
danielk1977b3bce662005-01-29 08:32:43 +00001844 substSelect(pExpr->pSelect, iTable, pEList);
drh6a3ea0e2003-05-02 14:32:12 +00001845 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001846 }
1847}
danielk1977b3bce662005-01-29 08:32:43 +00001848static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001849 int i;
1850 if( pList==0 ) return;
1851 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001852 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001853 }
1854}
danielk1977b3bce662005-01-29 08:32:43 +00001855static void substSelect(Select *p, int iTable, ExprList *pEList){
1856 if( !p ) return;
1857 substExprList(p->pEList, iTable, pEList);
1858 substExprList(p->pGroupBy, iTable, pEList);
1859 substExprList(p->pOrderBy, iTable, pEList);
1860 substExpr(p->pHaving, iTable, pEList);
1861 substExpr(p->pWhere, iTable, pEList);
1862}
drhb7f91642004-10-31 02:22:47 +00001863#endif /* !defined(SQLITE_OMIT_VIEW) */
drh832508b2002-03-02 17:04:07 +00001864
drhb7f91642004-10-31 02:22:47 +00001865#ifndef SQLITE_OMIT_VIEW
drh832508b2002-03-02 17:04:07 +00001866/*
drh1350b032002-02-27 19:00:20 +00001867** This routine attempts to flatten subqueries in order to speed
1868** execution. It returns 1 if it makes changes and 0 if no flattening
1869** occurs.
1870**
1871** To understand the concept of flattening, consider the following
1872** query:
1873**
1874** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1875**
1876** The default way of implementing this query is to execute the
1877** subquery first and store the results in a temporary table, then
1878** run the outer query on that temporary table. This requires two
1879** passes over the data. Furthermore, because the temporary table
1880** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001881** optimized.
drh1350b032002-02-27 19:00:20 +00001882**
drh832508b2002-03-02 17:04:07 +00001883** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001884** a single flat select, like this:
1885**
1886** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1887**
1888** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001889** but only has to scan the data once. And because indices might
1890** exist on the table t1, a complete scan of the data might be
1891** avoided.
drh1350b032002-02-27 19:00:20 +00001892**
drh832508b2002-03-02 17:04:07 +00001893** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001894**
drh832508b2002-03-02 17:04:07 +00001895** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001896**
drh832508b2002-03-02 17:04:07 +00001897** (2) The subquery is not an aggregate or the outer query is not a join.
1898**
drh8af4d3a2003-05-06 20:35:16 +00001899** (3) The subquery is not the right operand of a left outer join, or
1900** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001901**
1902** (4) The subquery is not DISTINCT or the outer query is not a join.
1903**
1904** (5) The subquery is not DISTINCT or the outer query does not use
1905** aggregates.
1906**
1907** (6) The subquery does not use aggregates or the outer query is not
1908** DISTINCT.
1909**
drh08192d52002-04-30 19:20:28 +00001910** (7) The subquery has a FROM clause.
1911**
drhdf199a22002-06-14 22:38:41 +00001912** (8) The subquery does not use LIMIT or the outer query is not a join.
1913**
1914** (9) The subquery does not use LIMIT or the outer query does not use
1915** aggregates.
1916**
1917** (10) The subquery does not use aggregates or the outer query does not
1918** use LIMIT.
1919**
drh174b6192002-12-03 02:22:52 +00001920** (11) The subquery and the outer query do not both have ORDER BY clauses.
1921**
drh3fc673e2003-06-16 00:40:34 +00001922** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1923** subquery has no WHERE clause. (added by ticket #350)
1924**
drh832508b2002-03-02 17:04:07 +00001925** In this routine, the "p" parameter is a pointer to the outer query.
1926** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1927** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1928**
drh665de472003-03-31 13:36:09 +00001929** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001930** If flattening is attempted this routine returns 1.
1931**
1932** All of the expression analysis must occur on both the outer query and
1933** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001934*/
drh8c74a8c2002-08-25 19:20:40 +00001935static int flattenSubquery(
1936 Parse *pParse, /* The parsing context */
1937 Select *p, /* The parent or outer SELECT statement */
1938 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1939 int isAgg, /* True if outer SELECT uses aggregate functions */
1940 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1941){
drh0bb28102002-05-08 11:54:14 +00001942 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001943 SrcList *pSrc; /* The FROM clause of the outer query */
1944 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001945 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001946 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh91bb0ee2004-09-01 03:06:34 +00001947 int i; /* Loop counter */
1948 Expr *pWhere; /* The WHERE clause */
1949 struct SrcList_item *pSubitem; /* The subquery */
drh1350b032002-02-27 19:00:20 +00001950
drh832508b2002-03-02 17:04:07 +00001951 /* Check to see if flattening is permitted. Return 0 if not.
1952 */
1953 if( p==0 ) return 0;
1954 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001955 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh91bb0ee2004-09-01 03:06:34 +00001956 pSubitem = &pSrc->a[iFrom];
1957 pSub = pSubitem->pSelect;
drh832508b2002-03-02 17:04:07 +00001958 assert( pSub!=0 );
1959 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001960 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001961 pSubSrc = pSub->pSrc;
1962 assert( pSubSrc );
danielk1977a2dc3b12005-02-05 12:48:48 +00001963 if( (pSub->pLimit && p->pLimit) || pSub->pOffset ||
1964 (pSub->pLimit && isAgg) ) return 0;
drhc31c2eb2003-05-02 16:04:17 +00001965 if( pSubSrc->nSrc==0 ) return 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001966 if( pSub->isDistinct && (pSrc->nSrc>1 || isAgg) ){
drhdf199a22002-06-14 22:38:41 +00001967 return 0;
1968 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001969 if( p->isDistinct && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001970 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001971
drh8af4d3a2003-05-06 20:35:16 +00001972 /* Restriction 3: If the subquery is a join, make sure the subquery is
1973 ** not used as the right operand of an outer join. Examples of why this
1974 ** is not allowed:
1975 **
1976 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1977 **
1978 ** If we flatten the above, we would get
1979 **
1980 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1981 **
1982 ** which is not at all the same thing.
1983 */
1984 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1985 return 0;
1986 }
1987
drh3fc673e2003-06-16 00:40:34 +00001988 /* Restriction 12: If the subquery is the right operand of a left outer
1989 ** join, make sure the subquery has no WHERE clause.
1990 ** An examples of why this is not allowed:
1991 **
1992 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1993 **
1994 ** If we flatten the above, we would get
1995 **
1996 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1997 **
1998 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1999 ** effectively converts the OUTER JOIN into an INNER JOIN.
2000 */
2001 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
2002 && pSub->pWhere!=0 ){
2003 return 0;
2004 }
2005
drh0bb28102002-05-08 11:54:14 +00002006 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00002007 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00002008 */
drhc31c2eb2003-05-02 16:04:17 +00002009
2010 /* Move all of the FROM elements of the subquery into the
2011 ** the FROM clause of the outer query. Before doing this, remember
2012 ** the cursor number for the original outer query FROM element in
2013 ** iParent. The iParent cursor will never be used. Subsequent code
2014 ** will scan expressions looking for iParent references and replace
2015 ** those references with expressions that resolve to the subquery FROM
2016 ** elements we are now copying in.
2017 */
drh91bb0ee2004-09-01 03:06:34 +00002018 iParent = pSubitem->iCursor;
drhc31c2eb2003-05-02 16:04:17 +00002019 {
2020 int nSubSrc = pSubSrc->nSrc;
drh91bb0ee2004-09-01 03:06:34 +00002021 int jointype = pSubitem->jointype;
2022 Table *pTab = pSubitem->pTab;
drhc31c2eb2003-05-02 16:04:17 +00002023
drh91bb0ee2004-09-01 03:06:34 +00002024 if( pTab && pTab->isTransient ){
2025 sqlite3DeleteTable(0, pSubitem->pTab);
drhc31c2eb2003-05-02 16:04:17 +00002026 }
drh91bb0ee2004-09-01 03:06:34 +00002027 sqliteFree(pSubitem->zDatabase);
2028 sqliteFree(pSubitem->zName);
2029 sqliteFree(pSubitem->zAlias);
drhc31c2eb2003-05-02 16:04:17 +00002030 if( nSubSrc>1 ){
2031 int extra = nSubSrc - 1;
2032 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00002033 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00002034 }
2035 p->pSrc = pSrc;
2036 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2037 pSrc->a[i] = pSrc->a[i-extra];
2038 }
2039 }
2040 for(i=0; i<nSubSrc; i++){
2041 pSrc->a[i+iFrom] = pSubSrc->a[i];
2042 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2043 }
drh8af4d3a2003-05-06 20:35:16 +00002044 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00002045 }
2046
2047 /* Now begin substituting subquery result set expressions for
2048 ** references to the iParent in the outer query.
2049 **
2050 ** Example:
2051 **
2052 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2053 ** \ \_____________ subquery __________/ /
2054 ** \_____________________ outer query ______________________________/
2055 **
2056 ** We look at every expression in the outer query and every place we see
2057 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2058 */
drh6a3ea0e2003-05-02 14:32:12 +00002059 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00002060 pList = p->pEList;
2061 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00002062 Expr *pExpr;
2063 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
2064 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00002065 }
2066 }
drh1b2e0322002-03-03 02:49:51 +00002067 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00002068 substExprList(p->pGroupBy, iParent, pSub->pEList);
2069 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00002070 }
drh174b6192002-12-03 02:22:52 +00002071 if( pSub->pOrderBy ){
2072 assert( p->pOrderBy==0 );
2073 p->pOrderBy = pSub->pOrderBy;
2074 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00002075 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00002076 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00002077 }
drh832508b2002-03-02 17:04:07 +00002078 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002079 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00002080 }else{
2081 pWhere = 0;
2082 }
2083 if( subqueryIsAgg ){
2084 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00002085 p->pHaving = p->pWhere;
2086 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00002087 substExpr(p->pHaving, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002088 p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
drh1b2e0322002-03-03 02:49:51 +00002089 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00002090 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00002091 }else{
drh6a3ea0e2003-05-02 14:32:12 +00002092 substExpr(p->pWhere, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002093 p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
drh832508b2002-03-02 17:04:07 +00002094 }
drhc31c2eb2003-05-02 16:04:17 +00002095
2096 /* The flattened query is distinct if either the inner or the
2097 ** outer query is distinct.
2098 */
drh832508b2002-03-02 17:04:07 +00002099 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00002100
danielk1977a58fdfb2005-02-08 07:50:40 +00002101 /*
2102 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2103 */
danielk1977a2dc3b12005-02-05 12:48:48 +00002104 if( pSub->pLimit ){
2105 p->pLimit = pSub->pLimit;
2106 pSub->pLimit = 0;
drhdf199a22002-06-14 22:38:41 +00002107 }
drh8c74a8c2002-08-25 19:20:40 +00002108
drhc31c2eb2003-05-02 16:04:17 +00002109 /* Finially, delete what is left of the subquery and return
2110 ** success.
2111 */
danielk19774adee202004-05-08 08:23:19 +00002112 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00002113 return 1;
2114}
drhb7f91642004-10-31 02:22:47 +00002115#endif /* SQLITE_OMIT_VIEW */
drh1350b032002-02-27 19:00:20 +00002116
2117/*
drh9562b552002-02-19 15:00:07 +00002118** Analyze the SELECT statement passed in as an argument to see if it
2119** is a simple min() or max() query. If it is and this query can be
2120** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00002121** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00002122** simple min() or max() query, then return 0;
2123**
2124** A simply min() or max() query looks like this:
2125**
2126** SELECT min(a) FROM table;
2127** SELECT max(a) FROM table;
2128**
2129** The query may have only a single table in its FROM argument. There
2130** can be no GROUP BY or HAVING or WHERE clauses. The result set must
2131** be the min() or max() of a single column of the table. The column
2132** in the min() or max() function must be indexed.
2133**
danielk19774adee202004-05-08 08:23:19 +00002134** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00002135** See the header comment on that routine for additional information.
2136*/
2137static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2138 Expr *pExpr;
2139 int iCol;
2140 Table *pTab;
2141 Index *pIdx;
2142 int base;
2143 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00002144 int seekOp;
2145 int cont;
drh6e175292004-03-13 14:00:36 +00002146 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00002147 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00002148 SrcList *pSrc;
drh9562b552002-02-19 15:00:07 +00002149
2150 /* Check to see if this query is a simple min() or max() query. Return
2151 ** zero if it is not.
2152 */
2153 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00002154 pSrc = p->pSrc;
2155 if( pSrc->nSrc!=1 ) return 0;
2156 pEList = p->pEList;
2157 if( pEList->nExpr!=1 ) return 0;
2158 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002159 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002160 pList = pExpr->pList;
2161 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002162 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00002163 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002164 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00002165 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002166 seekOp = OP_Last;
2167 }else{
2168 return 0;
2169 }
drh6e175292004-03-13 14:00:36 +00002170 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002171 if( pExpr->op!=TK_COLUMN ) return 0;
2172 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002173 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002174
2175 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002176 ** Check to make sure we have an index and make pIdx point to the
2177 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2178 ** key column, no index is necessary so set pIdx to NULL. If no
2179 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002180 */
2181 if( iCol<0 ){
2182 pIdx = 0;
2183 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002184 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002185 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2186 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002187 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002188 }
2189 if( pIdx==0 ) return 0;
2190 }
2191
drhe5f50722003-07-19 00:44:14 +00002192 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002193 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002194 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002195 */
danielk19774adee202004-05-08 08:23:19 +00002196 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002197 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002198
drh0c37e632004-01-30 02:01:03 +00002199 /* If the output is destined for a temporary table, open that table.
2200 */
2201 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002202 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002203 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002204 }
2205
drh17f71932002-02-21 12:01:27 +00002206 /* Generating code to find the min or the max. Basically all we have
2207 ** to do is find the first or the last entry in the chosen index. If
2208 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2209 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002210 */
danielk19774adee202004-05-08 08:23:19 +00002211 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00002212 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00002213 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00002214 if( pSrc->a[0].pSelect==0 ){
drhad6d9462004-09-19 02:15:24 +00002215 sqlite3OpenTableForReading(v, base, pTab);
drh6e175292004-03-13 14:00:36 +00002216 }
danielk19774adee202004-05-08 08:23:19 +00002217 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00002218 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002219 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002220 }else{
danielk19773719d7f2005-01-17 08:57:09 +00002221 /* Even though the cursor used to open the index here is closed
2222 ** as soon as a single value has been read from it, allocate it
2223 ** using (pParse->nTab++) to prevent the cursor id from being
2224 ** reused. This is important for statements of the form
2225 ** "INSERT INTO x SELECT max() FROM x".
2226 */
2227 int iIdx;
2228 iIdx = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +00002229 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002230 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
drhd3d39e92004-05-20 22:16:29 +00002231 (char*)&pIdx->keyInfo, P3_KEYINFO);
drh9eb516c2004-07-18 20:52:32 +00002232 if( seekOp==OP_Rewind ){
drh1af3fdb2004-07-18 21:33:01 +00002233 sqlite3VdbeAddOp(v, OP_String, 0, 0);
2234 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2235 seekOp = OP_MoveGt;
drh9eb516c2004-07-18 20:52:32 +00002236 }
danielk19773719d7f2005-01-17 08:57:09 +00002237 sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
2238 sqlite3VdbeAddOp(v, OP_IdxRecno, iIdx, 0);
2239 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002240 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002241 }
drh5cf8e8c2002-02-19 22:42:05 +00002242 eList.nExpr = 1;
2243 memset(&eListItem, 0, sizeof(eListItem));
2244 eList.a = &eListItem;
2245 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00002246 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00002247 sqlite3VdbeResolveLabel(v, cont);
2248 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002249
drh9562b552002-02-19 15:00:07 +00002250 return 1;
2251}
2252
2253/*
drh290c1942004-08-21 17:54:45 +00002254** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
2255** the number of errors seen.
2256**
2257** An ORDER BY or GROUP BY is a list of expressions. If any expression
2258** is an integer constant, then that expression is replaced by the
2259** corresponding entry in the result set.
2260*/
2261static int processOrderGroupBy(
danielk1977b3bce662005-01-29 08:32:43 +00002262 NameContext *pNC, /* Name context of the SELECT statement. */
drh290c1942004-08-21 17:54:45 +00002263 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
drh290c1942004-08-21 17:54:45 +00002264 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
2265){
2266 int i;
danielk1977b3bce662005-01-29 08:32:43 +00002267 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */
2268 Parse *pParse = pNC->pParse; /* The result set of the SELECT */
2269 assert( pEList );
2270
drh290c1942004-08-21 17:54:45 +00002271 if( pOrderBy==0 ) return 0;
2272 for(i=0; i<pOrderBy->nExpr; i++){
2273 int iCol;
2274 Expr *pE = pOrderBy->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +00002275 if( sqlite3ExprIsInteger(pE, &iCol) ){
2276 if( iCol>0 && iCol<=pEList->nExpr ){
2277 sqlite3ExprDelete(pE);
2278 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2279 }else{
drh290c1942004-08-21 17:54:45 +00002280 sqlite3ErrorMsg(pParse,
2281 "%s BY column number %d out of range - should be "
2282 "between 1 and %d", zType, iCol, pEList->nExpr);
2283 return 1;
2284 }
2285 }
danielk1977b3bce662005-01-29 08:32:43 +00002286 if( sqlite3ExprResolveNames(pNC, pE) ){
2287 return 1;
2288 }
2289 if( sqlite3ExprIsConstant(pE) ){
2290 sqlite3ErrorMsg(pParse,
2291 "%s BY terms must not be non-integer constants", zType);
2292 return 1;
2293 }
drh290c1942004-08-21 17:54:45 +00002294 }
2295 return 0;
2296}
2297
2298/*
danielk1977b3bce662005-01-29 08:32:43 +00002299** This routine resolves any names used in the result set of the
2300** supplied SELECT statement. If the SELECT statement being resolved
2301** is a sub-select, then pOuterNC is a pointer to the NameContext
2302** of the parent SELECT.
2303*/
2304int sqlite3SelectResolve(
2305 Parse *pParse, /* The parser context */
2306 Select *p, /* The SELECT statement being coded. */
2307 NameContext *pOuterNC /* The outer name context. May be NULL. */
2308){
2309 ExprList *pEList; /* Result set. */
2310 int i; /* For-loop variable used in multiple places */
2311 NameContext sNC; /* Local name-context */
2312
2313 /* If this routine has run before, return immediately. */
2314 if( p->isResolved ){
2315 assert( !pOuterNC );
2316 return SQLITE_OK;
2317 }
2318 p->isResolved = 1;
2319
2320 /* If there have already been errors, do nothing. */
2321 if( pParse->nErr>0 ){
2322 return SQLITE_ERROR;
2323 }
2324
2325 /* Prepare the select statement. This call will allocate all cursors
2326 ** required to handle the tables and subqueries in the FROM clause.
2327 */
2328 if( prepSelectStmt(pParse, p) ){
2329 return SQLITE_ERROR;
2330 }
2331
danielk1977a2dc3b12005-02-05 12:48:48 +00002332 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2333 ** are not allowed to refer to any names, so pass an empty NameContext.
2334 */
danielk1977b3bce662005-01-29 08:32:43 +00002335 sNC.pParse = pParse;
danielk1977b3bce662005-01-29 08:32:43 +00002336 sNC.hasAgg = 0;
2337 sNC.nErr = 0;
2338 sNC.nRef = 0;
2339 sNC.pEList = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00002340 sNC.allowAgg = 0;
2341 sNC.pSrcList = 0;
2342 sNC.pNext = 0;
2343 if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2344 sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2345 return SQLITE_ERROR;
2346 }
2347
2348 /* Set up the local name-context to pass to ExprResolveNames() to
2349 ** resolve the expression-list.
2350 */
2351 sNC.allowAgg = 1;
2352 sNC.pSrcList = p->pSrc;
2353 sNC.pNext = pOuterNC;
danielk1977b3bce662005-01-29 08:32:43 +00002354
2355 /* NameContext.nDepth stores the depth of recursion for this query. For
2356 ** an outer query (e.g. SELECT * FROM sqlite_master) this is 1. For
2357 ** a subquery it is 2. For a subquery of a subquery, 3. And so on.
2358 ** Parse.nMaxDepth is the maximum depth for any subquery resolved so
2359 ** far. This is used to determine the number of aggregate contexts
2360 ** required at runtime.
2361 */
2362 sNC.nDepth = (pOuterNC?pOuterNC->nDepth+1:1);
2363 if( sNC.nDepth>pParse->nMaxDepth ){
2364 pParse->nMaxDepth = sNC.nDepth;
2365 }
2366
2367 /* Resolve names in the result set. */
2368 pEList = p->pEList;
2369 if( !pEList ) return SQLITE_ERROR;
2370 for(i=0; i<pEList->nExpr; i++){
2371 Expr *pX = pEList->a[i].pExpr;
2372 if( sqlite3ExprResolveNames(&sNC, pX) ){
2373 return SQLITE_ERROR;
2374 }
2375 }
2376
2377 /* If there are no aggregate functions in the result-set, and no GROUP BY
2378 ** expression, do not allow aggregates in any of the other expressions.
2379 */
2380 assert( !p->isAgg );
2381 if( p->pGroupBy || sNC.hasAgg ){
2382 p->isAgg = 1;
2383 }else{
2384 sNC.allowAgg = 0;
2385 }
2386
2387 /* If a HAVING clause is present, then there must be a GROUP BY clause.
2388 */
2389 if( p->pHaving && !p->pGroupBy ){
2390 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2391 return SQLITE_ERROR;
2392 }
2393
2394 /* Add the expression list to the name-context before parsing the
2395 ** other expressions in the SELECT statement. This is so that
2396 ** expressions in the WHERE clause (etc.) can refer to expressions by
2397 ** aliases in the result set.
2398 **
2399 ** Minor point: If this is the case, then the expression will be
2400 ** re-evaluated for each reference to it.
2401 */
2402 sNC.pEList = p->pEList;
2403 if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2404 sqlite3ExprResolveNames(&sNC, p->pHaving) ||
2405 processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
2406 processOrderGroupBy(&sNC, p->pGroupBy, "GROUP")
2407 ){
2408 return SQLITE_ERROR;
2409 }
2410
2411 return SQLITE_OK;
2412}
2413
2414/*
2415** An instance of the following struct is used by sqlite3Select()
2416** to save aggregate related information from the Parse object
2417** at the start of each call and to restore it at the end. See
2418** saveAggregateInfo() and restoreAggregateInfo().
2419*/
2420struct AggregateInfo {
danielk1977b3bce662005-01-29 08:32:43 +00002421 int nAgg;
2422 AggExpr *aAgg;
2423};
2424typedef struct AggregateInfo AggregateInfo;
2425
2426/*
2427** Copy aggregate related information from the Parse structure
2428** into the AggregateInfo structure. Zero the aggregate related
2429** values in the Parse struct.
2430*/
2431static void saveAggregateInfo(Parse *pParse, AggregateInfo *pInfo){
2432 pInfo->aAgg = pParse->aAgg;
2433 pInfo->nAgg = pParse->nAgg;
danielk1977b3bce662005-01-29 08:32:43 +00002434 pParse->aAgg = 0;
2435 pParse->nAgg = 0;
danielk1977b3bce662005-01-29 08:32:43 +00002436}
2437
2438/*
2439** Copy aggregate related information from the AggregateInfo struct
2440** back into the Parse structure. The aggregate related information
2441** currently stored in the Parse structure is deleted.
2442*/
2443static void restoreAggregateInfo(Parse *pParse, AggregateInfo *pInfo){
2444 sqliteFree(pParse->aAgg);
2445 pParse->aAgg = pInfo->aAgg;
2446 pParse->nAgg = pInfo->nAgg;
danielk1977b3bce662005-01-29 08:32:43 +00002447}
2448
2449/*
drh9bb61fe2000-06-05 16:01:39 +00002450** Generate code for the given SELECT statement.
2451**
drhfef52082000-06-06 01:50:43 +00002452** The results are distributed in various ways depending on the
2453** value of eDest and iParm.
2454**
2455** eDest Value Result
2456** ------------ -------------------------------------------
2457** SRT_Callback Invoke the callback for each row of the result.
2458**
2459** SRT_Mem Store first result in memory cell iParm
2460**
danielk1977e014a832004-05-17 10:48:57 +00002461** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002462**
drh82c3d632000-06-06 21:56:07 +00002463** SRT_Union Store results as a key in a temporary table iParm
2464**
jplyon4b11c6d2004-01-19 04:57:53 +00002465** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002466**
2467** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002468**
drhe78e8282003-01-19 03:59:45 +00002469** The table above is incomplete. Additional eDist value have be added
2470** since this comment was written. See the selectInnerLoop() function for
2471** a complete listing of the allowed values of eDest and their meanings.
2472**
drh9bb61fe2000-06-05 16:01:39 +00002473** This routine returns the number of errors. If any errors are
2474** encountered, then an appropriate error message is left in
2475** pParse->zErrMsg.
2476**
2477** This routine does NOT free the Select structure passed in. The
2478** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002479**
2480** The pParent, parentTab, and *pParentAgg fields are filled in if this
2481** SELECT is a subquery. This routine may try to combine this SELECT
2482** with its parent to form a single flat query. In so doing, it might
2483** change the parent query from a non-aggregate to an aggregate query.
2484** For that reason, the pParentAgg flag is passed as a pointer, so it
2485** can be changed.
drhe78e8282003-01-19 03:59:45 +00002486**
2487** Example 1: The meaning of the pParent parameter.
2488**
2489** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2490** \ \_______ subquery _______/ /
2491** \ /
2492** \____________________ outer query ___________________/
2493**
2494** This routine is called for the outer query first. For that call,
2495** pParent will be NULL. During the processing of the outer query, this
2496** routine is called recursively to handle the subquery. For the recursive
2497** call, pParent will point to the outer query. Because the subquery is
2498** the second element in a three-way join, the parentTab parameter will
2499** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002500*/
danielk19774adee202004-05-08 08:23:19 +00002501int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002502 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002503 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002504 int eDest, /* How to dispose of the results */
2505 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002506 Select *pParent, /* Another SELECT for which this is a sub-query */
2507 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002508 int *pParentAgg, /* True if pParent uses aggregate functions */
danielk1977b3bce662005-01-29 08:32:43 +00002509 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002510){
drhd8bc7082000-06-07 23:51:50 +00002511 int i;
drhcce7d172000-05-31 15:34:51 +00002512 WhereInfo *pWInfo;
2513 Vdbe *v;
danielk1977b3bce662005-01-29 08:32:43 +00002514 int isAgg; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002515 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002516 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002517 Expr *pWhere; /* The WHERE clause. May be NULL */
2518 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002519 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2520 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002521 int isDistinct; /* True if the DISTINCT keyword is present */
2522 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002523 int rc = 1; /* Value to return from this function */
danielk1977b3bce662005-01-29 08:32:43 +00002524 AggregateInfo sAggInfo;
drh9bb61fe2000-06-05 16:01:39 +00002525
danielk19776f8a5032004-05-10 10:34:51 +00002526 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002527 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002528
drhb7f91642004-10-31 02:22:47 +00002529#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +00002530 /* If there is are a sequence of queries, do the earlier ones first.
2531 */
2532 if( p->pPrior ){
danielk197784ac9d02004-05-18 09:58:06 +00002533 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002534 }
drhb7f91642004-10-31 02:22:47 +00002535#endif
drh82c3d632000-06-06 21:56:07 +00002536
danielk1977b3bce662005-01-29 08:32:43 +00002537 saveAggregateInfo(pParse, &sAggInfo);
2538 pOrderBy = p->pOrderBy;
2539 if( eDest==SRT_Union || eDest==SRT_Except || eDest==SRT_Discard ){
2540 p->pOrderBy = 0;
2541 }
2542 if( sqlite3SelectResolve(pParse, p, 0) ){
2543 goto select_end;
2544 }
2545 p->pOrderBy = pOrderBy;
2546
drh82c3d632000-06-06 21:56:07 +00002547 /* Make local copies of the parameters for this query.
2548 */
drh9bb61fe2000-06-05 16:01:39 +00002549 pTabList = p->pSrc;
2550 pWhere = p->pWhere;
drh22827922000-06-06 17:27:05 +00002551 pGroupBy = p->pGroupBy;
2552 pHaving = p->pHaving;
danielk1977b3bce662005-01-29 08:32:43 +00002553 isAgg = p->isAgg;
drh19a775c2000-06-05 18:54:46 +00002554 isDistinct = p->isDistinct;
danielk1977b3bce662005-01-29 08:32:43 +00002555 pEList = p->pEList;
2556 if( pEList==0 ) goto select_end;
drh9bb61fe2000-06-05 16:01:39 +00002557
2558 /*
2559 ** Do not even attempt to generate any code if we have already seen
2560 ** errors before this routine starts.
2561 */
drh1d83f052002-02-17 00:30:36 +00002562 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002563
drh22827922000-06-06 17:27:05 +00002564 /* If writing to memory or generating a set
2565 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002566 */
drh51522cd2005-01-20 13:36:19 +00002567 assert( eDest!=SRT_Exists || pEList->nExpr==1 );
danielk197793758c82005-01-21 08:13:14 +00002568#ifndef SQLITE_OMIT_SUBQUERY
drhfef52082000-06-06 01:50:43 +00002569 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002570 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002571 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002572 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002573 }
danielk197793758c82005-01-21 08:13:14 +00002574#endif
drh19a775c2000-06-05 18:54:46 +00002575
drhc926afb2002-06-20 03:38:26 +00002576 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002577 */
drhc926afb2002-06-20 03:38:26 +00002578 switch( eDest ){
2579 case SRT_Union:
2580 case SRT_Except:
2581 case SRT_Discard:
2582 pOrderBy = 0;
2583 break;
2584 default:
2585 break;
drh22827922000-06-06 17:27:05 +00002586 }
2587
drhd820cb12002-02-18 03:21:45 +00002588 /* Begin generating code.
2589 */
danielk19774adee202004-05-08 08:23:19 +00002590 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002591 if( v==0 ) goto select_end;
2592
drhe78e8282003-01-19 03:59:45 +00002593 /* Identify column names if we will be using them in a callback. This
2594 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002595 */
2596 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002597 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002598 }
2599
drhd820cb12002-02-18 03:21:45 +00002600 /* Generate code for all sub-queries in the FROM clause
2601 */
drh51522cd2005-01-20 13:36:19 +00002602#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
drhad3cab52002-05-24 02:04:32 +00002603 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002604 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002605 int needRestoreContext;
2606
drha76b5df2002-02-23 02:32:10 +00002607 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002608 if( pTabList->a[i].zName!=0 ){
2609 zSavedAuthContext = pParse->zAuthContext;
2610 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002611 needRestoreContext = 1;
2612 }else{
2613 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002614 }
danielk19774adee202004-05-08 08:23:19 +00002615 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
danielk1977b3bce662005-01-29 08:32:43 +00002616 pTabList->a[i].iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002617 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002618 pParse->zAuthContext = zSavedAuthContext;
2619 }
drh1b2e0322002-03-03 02:49:51 +00002620 pTabList = p->pSrc;
2621 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002622 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002623 pOrderBy = p->pOrderBy;
2624 }
drh1b2e0322002-03-03 02:49:51 +00002625 pGroupBy = p->pGroupBy;
2626 pHaving = p->pHaving;
2627 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002628 }
drh51522cd2005-01-20 13:36:19 +00002629#endif
drhd820cb12002-02-18 03:21:45 +00002630
drh6e175292004-03-13 14:00:36 +00002631 /* Check for the special case of a min() or max() function by itself
2632 ** in the result set.
2633 */
2634 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2635 rc = 0;
2636 goto select_end;
2637 }
2638
drh832508b2002-03-02 17:04:07 +00002639 /* Check to see if this is a subquery that can be "flattened" into its parent.
2640 ** If flattening is a possiblity, do so and return immediately.
2641 */
drhb7f91642004-10-31 02:22:47 +00002642#ifndef SQLITE_OMIT_VIEW
drh1b2e0322002-03-03 02:49:51 +00002643 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002644 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002645 if( isAgg ) *pParentAgg = 1;
danielk1977b3bce662005-01-29 08:32:43 +00002646 goto select_end;
drh832508b2002-03-02 17:04:07 +00002647 }
drhb7f91642004-10-31 02:22:47 +00002648#endif
drh832508b2002-03-02 17:04:07 +00002649
danielk19777cedc8d2004-06-10 10:50:08 +00002650 /* If there is an ORDER BY clause, resolve any collation sequences
2651 ** names that have been explicitly specified.
2652 */
2653 if( pOrderBy ){
2654 for(i=0; i<pOrderBy->nExpr; i++){
2655 if( pOrderBy->a[i].zName ){
2656 pOrderBy->a[i].pExpr->pColl =
2657 sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1);
2658 }
2659 }
2660 if( pParse->nErr ){
2661 goto select_end;
2662 }
2663 }
2664
drh7b58dae2003-07-20 01:16:46 +00002665 /* Set the limiter.
2666 */
2667 computeLimitRegisters(pParse, p);
2668
drh2d0794e2002-03-03 03:03:52 +00002669 /* If the output is destined for a temporary table, open that table.
2670 */
2671 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002672 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002673 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002674 }
2675
drh22827922000-06-06 17:27:05 +00002676 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002677 */
drhbb999ef2003-02-02 12:41:25 +00002678 if( isAgg || pGroupBy ){
danielk1977a58fdfb2005-02-08 07:50:40 +00002679 NameContext sNC;
2680 memset(&sNC, 0, sizeof(sNC));
2681 sNC.pParse = pParse;
2682 sNC.pSrcList = pTabList;
2683
drh0bce8352002-02-28 00:41:10 +00002684 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002685 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002686 for(i=0; i<pEList->nExpr; i++){
danielk1977a58fdfb2005-02-08 07:50:40 +00002687 if( sqlite3ExprAnalyzeAggregates(&sNC, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002688 goto select_end;
drh22827922000-06-06 17:27:05 +00002689 }
2690 }
2691 if( pGroupBy ){
2692 for(i=0; i<pGroupBy->nExpr; i++){
danielk1977a58fdfb2005-02-08 07:50:40 +00002693 if( sqlite3ExprAnalyzeAggregates(&sNC, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002694 goto select_end;
drh22827922000-06-06 17:27:05 +00002695 }
2696 }
2697 }
danielk1977a58fdfb2005-02-08 07:50:40 +00002698 if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002699 goto select_end;
drh22827922000-06-06 17:27:05 +00002700 }
drh191b6902000-06-08 11:13:01 +00002701 if( pOrderBy ){
2702 for(i=0; i<pOrderBy->nExpr; i++){
danielk1977a58fdfb2005-02-08 07:50:40 +00002703 if( sqlite3ExprAnalyzeAggregates(&sNC, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002704 goto select_end;
drh191b6902000-06-08 11:13:01 +00002705 }
2706 }
2707 }
drhefb72512000-05-31 20:00:52 +00002708 }
2709
drh22827922000-06-06 17:27:05 +00002710 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002711 */
2712 if( isAgg ){
danielk1977e159fdf2004-06-21 10:45:06 +00002713 int addr = sqlite3VdbeAddOp(v, OP_AggReset, (pGroupBy?0:1), pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002714 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002715 FuncDef *pFunc;
2716 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drhf9b596e2004-05-26 16:54:42 +00002717 sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_FUNCDEF);
drhe5095352002-02-24 03:25:14 +00002718 }
2719 }
danielk1977e159fdf2004-06-21 10:45:06 +00002720 if( pGroupBy ){
danielk1977ce2663c2004-06-11 13:19:21 +00002721 int sz = sizeof(KeyInfo) + pGroupBy->nExpr*sizeof(CollSeq*);
2722 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(sz);
2723 if( 0==pKey ){
2724 goto select_end;
2725 }
2726 pKey->enc = pParse->db->enc;
2727 pKey->nField = pGroupBy->nExpr;
2728 for(i=0; i<pGroupBy->nExpr; i++){
2729 pKey->aColl[i] = sqlite3ExprCollSeq(pParse, pGroupBy->a[i].pExpr);
2730 if( !pKey->aColl[i] ){
2731 pKey->aColl[i] = pParse->db->pDfltColl;
2732 }
2733 }
2734 sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF);
drh1bee3d72001-10-15 00:44:35 +00002735 }
drhcce7d172000-05-31 15:34:51 +00002736 }
2737
drh51522cd2005-01-20 13:36:19 +00002738 /* Initialize the memory cell to NULL for SRT_Mem or 0 for SRT_Exists
drh19a775c2000-06-05 18:54:46 +00002739 */
drh51522cd2005-01-20 13:36:19 +00002740 if( eDest==SRT_Mem || eDest==SRT_Exists ){
2741 sqlite3VdbeAddOp(v, eDest==SRT_Mem ? OP_String8 : OP_Integer, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00002742 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002743 }
2744
drh832508b2002-03-02 17:04:07 +00002745 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002746 */
drh19a775c2000-06-05 18:54:46 +00002747 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002748 distinct = pParse->nTab++;
drhd3d39e92004-05-20 22:16:29 +00002749 openTempIndex(pParse, p, distinct, 0);
drh832508b2002-03-02 17:04:07 +00002750 }else{
2751 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002752 }
drh832508b2002-03-02 17:04:07 +00002753
2754 /* Begin the database scan
2755 */
drhe6f85e72004-12-25 01:03:13 +00002756 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,
drhe4e72072004-11-23 01:47:30 +00002757 pGroupBy ? 0 : &pOrderBy, p->pFetch);
drh1d83f052002-02-17 00:30:36 +00002758 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002759
drh22827922000-06-06 17:27:05 +00002760 /* Use the standard inner loop if we are not dealing with
2761 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002762 */
drhda9d6c42000-05-31 18:20:14 +00002763 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002764 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002765 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002766 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002767 }
drhcce7d172000-05-31 15:34:51 +00002768 }
drhefb72512000-05-31 20:00:52 +00002769
drhe3184742002-06-19 14:27:05 +00002770 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002771 ** processing.
drhefb72512000-05-31 20:00:52 +00002772 */
drh22827922000-06-06 17:27:05 +00002773 else{
drh268380c2004-02-25 13:47:31 +00002774 AggExpr *pAgg;
danielk1977a58fdfb2005-02-08 07:50:40 +00002775 int lbl1 = 0;
2776 pParse->fillAgg = 1;
drh22827922000-06-06 17:27:05 +00002777 if( pGroupBy ){
2778 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002779 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
drh22827922000-06-06 17:27:05 +00002780 }
danielk1977ededfd52004-06-17 07:53:01 +00002781 /* No affinity string is attached to the following OP_MakeRecord
drhd3d39e92004-05-20 22:16:29 +00002782 ** because we do not need to do any coercion of datatypes. */
danielk1977ededfd52004-06-17 07:53:01 +00002783 sqlite3VdbeAddOp(v, OP_MakeRecord, pGroupBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +00002784 lbl1 = sqlite3VdbeMakeLabel(v);
2785 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
danielk1977a58fdfb2005-02-08 07:50:40 +00002786 }
2787 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2788 if( pAgg->isAgg ) continue;
2789 sqlite3ExprCode(pParse, pAgg->pExpr);
2790 sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
2791 }
2792 pParse->fillAgg = 0;
2793 if( lbl1<0 ){
danielk19774adee202004-05-08 08:23:19 +00002794 sqlite3VdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002795 }
drh268380c2004-02-25 13:47:31 +00002796 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002797 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002798 int nExpr;
2799 FuncDef *pDef;
2800 if( !pAgg->isAgg ) continue;
2801 assert( pAgg->pFunc!=0 );
2802 assert( pAgg->pFunc->xStep!=0 );
2803 pDef = pAgg->pFunc;
2804 pE = pAgg->pExpr;
2805 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002806 assert( pE->op==TK_AGG_FUNCTION );
drhf9b596e2004-05-26 16:54:42 +00002807 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
danielk19774adee202004-05-08 08:23:19 +00002808 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
danielk1977dc1bdc42004-06-11 10:51:27 +00002809 if( pDef->needCollSeq ){
2810 CollSeq *pColl = 0;
2811 int j;
2812 for(j=0; !pColl && j<nExpr; j++){
2813 pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr);
2814 }
2815 if( !pColl ) pColl = pParse->db->pDfltColl;
2816 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2817 }
danielk19774adee202004-05-08 08:23:19 +00002818 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002819 }
drhcce7d172000-05-31 15:34:51 +00002820 }
2821
2822 /* End the database scan loop.
2823 */
danielk19774adee202004-05-08 08:23:19 +00002824 sqlite3WhereEnd(pWInfo);
drhcce7d172000-05-31 15:34:51 +00002825
drh22827922000-06-06 17:27:05 +00002826 /* If we are processing aggregates, we need to set up a second loop
2827 ** over all of the aggregate values and process them.
2828 */
2829 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002830 int endagg = sqlite3VdbeMakeLabel(v);
drh22827922000-06-06 17:27:05 +00002831 int startagg;
danielk19774adee202004-05-08 08:23:19 +00002832 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002833 if( pHaving ){
danielk19774adee202004-05-08 08:23:19 +00002834 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002835 }
drhdf199a22002-06-14 22:38:41 +00002836 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002837 iParm, startagg, endagg, aff) ){
drh1d83f052002-02-17 00:30:36 +00002838 goto select_end;
drh22827922000-06-06 17:27:05 +00002839 }
danielk19774adee202004-05-08 08:23:19 +00002840 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2841 sqlite3VdbeResolveLabel(v, endagg);
2842 sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002843 }
2844
drhcce7d172000-05-31 15:34:51 +00002845 /* If there is an ORDER BY clause, then we need to sort the results
2846 ** and send them to the callback one by one.
2847 */
2848 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00002849 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002850 }
drh6a535342001-10-19 16:44:56 +00002851
danielk197793758c82005-01-21 08:13:14 +00002852#ifndef SQLITE_OMIT_SUBQUERY
drhf620b4e2004-02-09 14:37:50 +00002853 /* If this was a subquery, we have now converted the subquery into a
2854 ** temporary table. So delete the subquery structure from the parent
2855 ** to prevent this subquery from being evaluated again and to force the
2856 ** the use of the temporary table.
2857 */
2858 if( pParent ){
2859 assert( pParent->pSrc->nSrc>parentTab );
2860 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00002861 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00002862 pParent->pSrc->a[parentTab].pSelect = 0;
2863 }
danielk197793758c82005-01-21 08:13:14 +00002864#endif
drhf620b4e2004-02-09 14:37:50 +00002865
drh1d83f052002-02-17 00:30:36 +00002866 /* The SELECT was successfully coded. Set the return code to 0
2867 ** to indicate no errors.
2868 */
2869 rc = 0;
2870
2871 /* Control jumps to here if an error is encountered above, or upon
2872 ** successful coding of the SELECT.
2873 */
2874select_end:
danielk1977b3bce662005-01-29 08:32:43 +00002875 restoreAggregateInfo(pParse, &sAggInfo);
drh1d83f052002-02-17 00:30:36 +00002876 return rc;
drhcce7d172000-05-31 15:34:51 +00002877}