blob: a889fc58eb71342a515ccefbf9e60e62980bfc4b [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**
drhe6f85e72004-12-25 01:03:13 +000015** $Id: select.c,v 1.219 2004/12/25 01:03:14 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
drh315555c2002-10-20 15:53:03 +000019
drhcce7d172000-05-31 15:34:51 +000020/*
drh9bb61fe2000-06-05 16:01:39 +000021** Allocate a new Select structure and return a pointer to that
22** structure.
drhcce7d172000-05-31 15:34:51 +000023*/
danielk19774adee202004-05-08 08:23:19 +000024Select *sqlite3SelectNew(
drhdaffd0e2001-04-11 14:28:42 +000025 ExprList *pEList, /* which columns to include in the result */
drhad3cab52002-05-24 02:04:32 +000026 SrcList *pSrc, /* the FROM clause -- which tables to scan */
drhdaffd0e2001-04-11 14:28:42 +000027 Expr *pWhere, /* the WHERE clause */
28 ExprList *pGroupBy, /* the GROUP BY clause */
29 Expr *pHaving, /* the HAVING clause */
30 ExprList *pOrderBy, /* the ORDER BY clause */
drh9bbca4c2001-11-06 04:00:18 +000031 int isDistinct, /* true if the DISTINCT keyword is present */
32 int nLimit, /* LIMIT value. -1 means not used */
drhef0cae52003-07-16 02:19:37 +000033 int nOffset /* OFFSET value. 0 means no offset */
drh9bb61fe2000-06-05 16:01:39 +000034){
35 Select *pNew;
36 pNew = sqliteMalloc( sizeof(*pNew) );
drhdaffd0e2001-04-11 14:28:42 +000037 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +000038 sqlite3ExprListDelete(pEList);
39 sqlite3SrcListDelete(pSrc);
40 sqlite3ExprDelete(pWhere);
41 sqlite3ExprListDelete(pGroupBy);
42 sqlite3ExprDelete(pHaving);
43 sqlite3ExprListDelete(pOrderBy);
drhdaffd0e2001-04-11 14:28:42 +000044 }else{
drhb733d032004-01-24 20:18:12 +000045 if( pEList==0 ){
danielk19774adee202004-05-08 08:23:19 +000046 pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
drhb733d032004-01-24 20:18:12 +000047 }
drhdaffd0e2001-04-11 14:28:42 +000048 pNew->pEList = pEList;
49 pNew->pSrc = pSrc;
50 pNew->pWhere = pWhere;
51 pNew->pGroupBy = pGroupBy;
52 pNew->pHaving = pHaving;
53 pNew->pOrderBy = pOrderBy;
54 pNew->isDistinct = isDistinct;
55 pNew->op = TK_SELECT;
drh9bbca4c2001-11-06 04:00:18 +000056 pNew->nLimit = nLimit;
57 pNew->nOffset = nOffset;
drh7b58dae2003-07-20 01:16:46 +000058 pNew->iLimit = -1;
59 pNew->iOffset = -1;
drhdaffd0e2001-04-11 14:28:42 +000060 }
drh9bb61fe2000-06-05 16:01:39 +000061 return pNew;
62}
63
64/*
drh01f3f252002-05-24 16:14:15 +000065** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
66** type of join. Return an integer constant that expresses that type
67** in terms of the following bit values:
68**
69** JT_INNER
70** JT_OUTER
71** JT_NATURAL
72** JT_LEFT
73** JT_RIGHT
74**
75** A full outer join is the combination of JT_LEFT and JT_RIGHT.
76**
77** If an illegal or unsupported join type is seen, then still return
78** a join type, but put an error in the pParse structure.
79*/
danielk19774adee202004-05-08 08:23:19 +000080int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
drh01f3f252002-05-24 16:14:15 +000081 int jointype = 0;
82 Token *apAll[3];
83 Token *p;
drh57196282004-10-06 15:41:16 +000084 static const struct {
drh01f3f252002-05-24 16:14:15 +000085 const char *zKeyword;
drh290c1942004-08-21 17:54:45 +000086 u8 nChar;
87 u8 code;
drh01f3f252002-05-24 16:14:15 +000088 } keywords[] = {
89 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000090 { "left", 4, JT_LEFT|JT_OUTER },
91 { "right", 5, JT_RIGHT|JT_OUTER },
92 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +000093 { "outer", 5, JT_OUTER },
94 { "inner", 5, JT_INNER },
95 { "cross", 5, JT_INNER },
96 };
97 int i, j;
98 apAll[0] = pA;
99 apAll[1] = pB;
100 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +0000101 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +0000102 p = apAll[i];
103 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
104 if( p->n==keywords[j].nChar
danielk19774adee202004-05-08 08:23:19 +0000105 && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
drh01f3f252002-05-24 16:14:15 +0000106 jointype |= keywords[j].code;
107 break;
108 }
109 }
110 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
111 jointype |= JT_ERROR;
112 break;
113 }
114 }
drhad2d8302002-05-24 20:31:36 +0000115 if(
116 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000117 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000118 ){
drhae29ffb2004-09-25 14:39:18 +0000119 const char *zSp1 = " ";
120 const char *zSp2 = " ";
121 if( pB==0 ){ zSp1++; }
122 if( pC==0 ){ zSp2++; }
123 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
124 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
drh01f3f252002-05-24 16:14:15 +0000125 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000126 }else if( jointype & JT_RIGHT ){
danielk19774adee202004-05-08 08:23:19 +0000127 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000128 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000129 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000130 }
131 return jointype;
132}
133
134/*
drhad2d8302002-05-24 20:31:36 +0000135** Return the index of a column in a table. Return -1 if the column
136** is not contained in the table.
137*/
138static int columnIndex(Table *pTab, const char *zCol){
139 int i;
140 for(i=0; i<pTab->nCol; i++){
danielk19774adee202004-05-08 08:23:19 +0000141 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
drhad2d8302002-05-24 20:31:36 +0000142 }
143 return -1;
144}
145
146/*
drh91bb0ee2004-09-01 03:06:34 +0000147** Set the value of a token to a '\000'-terminated string.
148*/
149static void setToken(Token *p, const char *z){
150 p->z = z;
151 p->n = strlen(z);
152 p->dyn = 0;
153}
154
155
156/*
drhad2d8302002-05-24 20:31:36 +0000157** Add a term to the WHERE expression in *ppExpr that requires the
158** zCol column to be equal in the two tables pTab1 and pTab2.
159*/
160static void addWhereTerm(
161 const char *zCol, /* Name of the column */
162 const Table *pTab1, /* First table */
163 const Table *pTab2, /* Second table */
164 Expr **ppExpr /* Add the equality term to this expression */
165){
166 Token dummy;
167 Expr *pE1a, *pE1b, *pE1c;
168 Expr *pE2a, *pE2b, *pE2c;
169 Expr *pE;
170
drh91bb0ee2004-09-01 03:06:34 +0000171 setToken(&dummy, zCol);
danielk19774adee202004-05-08 08:23:19 +0000172 pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy);
173 pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy);
drh91bb0ee2004-09-01 03:06:34 +0000174 setToken(&dummy, pTab1->zName);
danielk19774adee202004-05-08 08:23:19 +0000175 pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy);
drh91bb0ee2004-09-01 03:06:34 +0000176 setToken(&dummy, pTab2->zName);
danielk19774adee202004-05-08 08:23:19 +0000177 pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy);
178 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
179 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
180 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000181 ExprSetProperty(pE, EP_FromJoin);
drh91bb0ee2004-09-01 03:06:34 +0000182 *ppExpr = sqlite3ExprAnd(*ppExpr, pE);
drhad2d8302002-05-24 20:31:36 +0000183}
184
185/*
drh1f162302002-10-27 19:35:33 +0000186** Set the EP_FromJoin property on all terms of the given expression.
drh1cc093c2002-06-24 22:01:57 +0000187**
drhe78e8282003-01-19 03:59:45 +0000188** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000189** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000190** join restriction specified in the ON or USING clause and not a part
191** of the more general WHERE clause. These terms are moved over to the
192** WHERE clause during join processing but we need to remember that they
193** originated in the ON or USING clause.
drh1cc093c2002-06-24 22:01:57 +0000194*/
195static void setJoinExpr(Expr *p){
196 while( p ){
drh1f162302002-10-27 19:35:33 +0000197 ExprSetProperty(p, EP_FromJoin);
drh1cc093c2002-06-24 22:01:57 +0000198 setJoinExpr(p->pLeft);
199 p = p->pRight;
200 }
201}
202
203/*
drhad2d8302002-05-24 20:31:36 +0000204** This routine processes the join information for a SELECT statement.
205** ON and USING clauses are converted into extra terms of the WHERE clause.
206** NATURAL joins also create extra WHERE clause terms.
207**
drh91bb0ee2004-09-01 03:06:34 +0000208** The terms of a FROM clause are contained in the Select.pSrc structure.
209** The left most table is the first entry in Select.pSrc. The right-most
210** table is the last entry. The join operator is held in the entry to
211** the left. Thus entry 0 contains the join operator for the join between
212** entries 0 and 1. Any ON or USING clauses associated with the join are
213** also attached to the left entry.
214**
drhad2d8302002-05-24 20:31:36 +0000215** This routine returns the number of errors encountered.
216*/
217static int sqliteProcessJoin(Parse *pParse, Select *p){
drh91bb0ee2004-09-01 03:06:34 +0000218 SrcList *pSrc; /* All tables in the FROM clause */
219 int i, j; /* Loop counters */
220 struct SrcList_item *pLeft; /* Left table being joined */
221 struct SrcList_item *pRight; /* Right table being joined */
drhad2d8302002-05-24 20:31:36 +0000222
drh91bb0ee2004-09-01 03:06:34 +0000223 pSrc = p->pSrc;
224 pLeft = &pSrc->a[0];
225 pRight = &pLeft[1];
226 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
227 Table *pLeftTab = pLeft->pTab;
228 Table *pRightTab = pRight->pTab;
229
230 if( pLeftTab==0 || pRightTab==0 ) continue;
drhad2d8302002-05-24 20:31:36 +0000231
232 /* When the NATURAL keyword is present, add WHERE clause terms for
233 ** every column that the two tables have in common.
234 */
drh91bb0ee2004-09-01 03:06:34 +0000235 if( pLeft->jointype & JT_NATURAL ){
236 if( pLeft->pOn || pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000237 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000238 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000239 return 1;
240 }
drh91bb0ee2004-09-01 03:06:34 +0000241 for(j=0; j<pLeftTab->nCol; j++){
242 char *zName = pLeftTab->aCol[j].zName;
243 if( columnIndex(pRightTab, zName)>=0 ){
244 addWhereTerm(zName, pLeftTab, pRightTab, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000245 }
246 }
247 }
248
249 /* Disallow both ON and USING clauses in the same join
250 */
drh91bb0ee2004-09-01 03:06:34 +0000251 if( pLeft->pOn && pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000252 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
drhda93d232003-03-31 02:12:46 +0000253 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000254 return 1;
255 }
256
257 /* Add the ON clause to the end of the WHERE clause, connected by
drh91bb0ee2004-09-01 03:06:34 +0000258 ** an AND operator.
drhad2d8302002-05-24 20:31:36 +0000259 */
drh91bb0ee2004-09-01 03:06:34 +0000260 if( pLeft->pOn ){
261 setJoinExpr(pLeft->pOn);
262 p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn);
263 pLeft->pOn = 0;
drhad2d8302002-05-24 20:31:36 +0000264 }
265
266 /* Create extra terms on the WHERE clause for each column named
267 ** in the USING clause. Example: If the two tables to be joined are
268 ** A and B and the USING clause names X, Y, and Z, then add this
269 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
270 ** Report an error if any column mentioned in the USING clause is
271 ** not contained in both tables to be joined.
272 */
drh91bb0ee2004-09-01 03:06:34 +0000273 if( pLeft->pUsing ){
274 IdList *pList = pLeft->pUsing;
drhad2d8302002-05-24 20:31:36 +0000275 for(j=0; j<pList->nId; j++){
drh91bb0ee2004-09-01 03:06:34 +0000276 char *zName = pList->a[j].zName;
277 if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
danielk19774adee202004-05-08 08:23:19 +0000278 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
drh91bb0ee2004-09-01 03:06:34 +0000279 "not present in both tables", zName);
drhad2d8302002-05-24 20:31:36 +0000280 return 1;
281 }
drh91bb0ee2004-09-01 03:06:34 +0000282 addWhereTerm(zName, pLeftTab, pRightTab, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000283 }
284 }
285 }
286 return 0;
287}
288
289/*
drh9bb61fe2000-06-05 16:01:39 +0000290** Delete the given Select structure and all of its substructures.
291*/
danielk19774adee202004-05-08 08:23:19 +0000292void sqlite3SelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000293 if( p==0 ) return;
danielk19774adee202004-05-08 08:23:19 +0000294 sqlite3ExprListDelete(p->pEList);
295 sqlite3SrcListDelete(p->pSrc);
296 sqlite3ExprDelete(p->pWhere);
297 sqlite3ExprListDelete(p->pGroupBy);
298 sqlite3ExprDelete(p->pHaving);
299 sqlite3ExprListDelete(p->pOrderBy);
300 sqlite3SelectDelete(p->pPrior);
drh9bb61fe2000-06-05 16:01:39 +0000301 sqliteFree(p);
302}
303
304/*
drh22827922000-06-06 17:27:05 +0000305** Delete the aggregate information from the parse structure.
306*/
drh1d83f052002-02-17 00:30:36 +0000307static void sqliteAggregateInfoReset(Parse *pParse){
drh22827922000-06-06 17:27:05 +0000308 sqliteFree(pParse->aAgg);
309 pParse->aAgg = 0;
310 pParse->nAgg = 0;
drh22827922000-06-06 17:27:05 +0000311 pParse->useAgg = 0;
312}
313
314/*
drhc926afb2002-06-20 03:38:26 +0000315** Insert code into "v" that will push the record on the top of the
316** stack into the sorter.
317*/
318static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
drhc926afb2002-06-20 03:38:26 +0000319 int i;
drhc926afb2002-06-20 03:38:26 +0000320 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000321 sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
drhc926afb2002-06-20 03:38:26 +0000322 }
danielk1977ededfd52004-06-17 07:53:01 +0000323 sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +0000324 sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000325}
326
327/*
drhea48eb22004-07-19 23:16:38 +0000328** Add code to implement the OFFSET and LIMIT
329*/
330static void codeLimiter(
drhbab39e12004-07-19 23:38:11 +0000331 Vdbe *v, /* Generate code into this VM */
drhea48eb22004-07-19 23:16:38 +0000332 Select *p, /* The SELECT statement being coded */
333 int iContinue, /* Jump here to skip the current record */
334 int iBreak, /* Jump here to end the loop */
335 int nPop /* Number of times to pop stack when jumping */
336){
drhea48eb22004-07-19 23:16:38 +0000337 if( p->iOffset>=0 ){
338 int addr = sqlite3VdbeCurrentAddr(v) + 2;
339 if( nPop>0 ) addr++;
340 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr);
341 if( nPop>0 ){
342 sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
343 }
344 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000345 VdbeComment((v, "# skip OFFSET records"));
drhea48eb22004-07-19 23:16:38 +0000346 }
347 if( p->iLimit>=0 ){
348 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhad6d9462004-09-19 02:15:24 +0000349 VdbeComment((v, "# exit when LIMIT reached"));
drhea48eb22004-07-19 23:16:38 +0000350 }
351}
352
353/*
drh22827922000-06-06 17:27:05 +0000354** This routine generates the code for the inside of the inner loop
355** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000356**
drh38640e12002-07-05 21:42:36 +0000357** If srcTab and nColumn are both zero, then the pEList expressions
358** are evaluated in order to get the data for this row. If nColumn>0
359** then data is pulled from srcTab and pEList is used only to get the
360** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000361*/
362static int selectInnerLoop(
363 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000364 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000365 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000366 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000367 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000368 ExprList *pOrderBy, /* If not NULL, sort results using this key */
369 int distinct, /* If >=0, make sure results are distinct */
370 int eDest, /* How to dispose of the results */
371 int iParm, /* An argument to the disposal method */
372 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000373 int iBreak, /* Jump here to break out of the inner loop */
374 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000375){
376 Vdbe *v = pParse->pVdbe;
377 int i;
drhea48eb22004-07-19 23:16:38 +0000378 int hasDistinct; /* True if the DISTINCT keyword is present */
drh38640e12002-07-05 21:42:36 +0000379
drhdaffd0e2001-04-11 14:28:42 +0000380 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000381 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000382
drhdf199a22002-06-14 22:38:41 +0000383 /* If there was a LIMIT clause on the SELECT statement, then do the check
384 ** to see if this row should be output.
385 */
drhea48eb22004-07-19 23:16:38 +0000386 hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
387 if( pOrderBy==0 && !hasDistinct ){
drhbab39e12004-07-19 23:38:11 +0000388 codeLimiter(v, p, iContinue, iBreak, 0);
drhdf199a22002-06-14 22:38:41 +0000389 }
390
drh967e8b72000-06-21 13:59:10 +0000391 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000392 */
drh38640e12002-07-05 21:42:36 +0000393 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000394 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000395 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000396 }
drh38640e12002-07-05 21:42:36 +0000397 }else{
398 nColumn = pEList->nExpr;
399 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000400 sqlite3ExprCode(pParse, pEList->a[i].pExpr);
drh38640e12002-07-05 21:42:36 +0000401 }
drh22827922000-06-06 17:27:05 +0000402 }
403
drhdaffd0e2001-04-11 14:28:42 +0000404 /* If the DISTINCT keyword was present on the SELECT statement
405 ** and this row has been seen before, then do not make this row
406 ** part of the result.
drh22827922000-06-06 17:27:05 +0000407 */
drhea48eb22004-07-19 23:16:38 +0000408 if( hasDistinct ){
drh0bd1f4e2002-06-06 18:54:39 +0000409#if NULL_ALWAYS_DISTINCT
danielk19774adee202004-05-08 08:23:19 +0000410 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
drh0bd1f4e2002-06-06 18:54:39 +0000411#endif
danielk1977ededfd52004-06-17 07:53:01 +0000412 /* Deliberately leave the affinity string off of the following
413 ** OP_MakeRecord */
414 sqlite3VdbeAddOp(v, OP_MakeRecord, pEList->nExpr * -1, 0);
danielk19774adee202004-05-08 08:23:19 +0000415 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
416 sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
417 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000418 VdbeComment((v, "# skip indistinct records"));
danielk19770f69c1e2004-05-29 11:24:50 +0000419 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000420 sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
drhea48eb22004-07-19 23:16:38 +0000421 if( pOrderBy==0 ){
drhbab39e12004-07-19 23:38:11 +0000422 codeLimiter(v, p, iContinue, iBreak, nColumn);
drhea48eb22004-07-19 23:16:38 +0000423 }
drh22827922000-06-06 17:27:05 +0000424 }
drh82c3d632000-06-06 21:56:07 +0000425
drhc926afb2002-06-20 03:38:26 +0000426 switch( eDest ){
427 /* In this mode, write each query result to the key of the temporary
428 ** table iParm.
429 */
430 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000431 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000432 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000433 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000434 sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000435 break;
drh22827922000-06-06 17:27:05 +0000436 }
drh22827922000-06-06 17:27:05 +0000437
drhc926afb2002-06-20 03:38:26 +0000438 /* Store the result as data using a unique key.
439 */
440 case SRT_Table:
441 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000442 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000443 if( pOrderBy ){
444 pushOntoSorter(pParse, v, pOrderBy);
445 }else{
danielk19774adee202004-05-08 08:23:19 +0000446 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
447 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
448 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000449 }
450 break;
451 }
drh82c3d632000-06-06 21:56:07 +0000452
drhc926afb2002-06-20 03:38:26 +0000453 /* Construct a record from the query result, but instead of
454 ** saving that record, use it as a key to delete elements from
455 ** the temporary table iParm.
456 */
457 case SRT_Except: {
458 int addr;
danielk19774adee202004-05-08 08:23:19 +0000459 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000460 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000461 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
462 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000463 break;
464 }
drh5974a302000-06-07 14:42:26 +0000465
drhc926afb2002-06-20 03:38:26 +0000466 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
467 ** then there should be a single item on the stack. Write this
468 ** item into the set table with bogus data.
469 */
470 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000471 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000472 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000473
drhc926afb2002-06-20 03:38:26 +0000474 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000475 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
476 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
477 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000478 if( pOrderBy ){
479 pushOntoSorter(pParse, v, pOrderBy);
480 }else{
danielk1977e014a832004-05-17 10:48:57 +0000481 char aff = (iParm>>16)&0xFF;
482 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
drh94a11212004-09-25 13:12:14 +0000483 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1);
danielk19770f69c1e2004-05-29 11:24:50 +0000484 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000485 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000486 }
danielk19774adee202004-05-08 08:23:19 +0000487 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000488 break;
489 }
drh22827922000-06-06 17:27:05 +0000490
drhc926afb2002-06-20 03:38:26 +0000491 /* If this is a scalar select that is part of an expression, then
492 ** store the results in the appropriate memory cell and break out
493 ** of the scan loop.
494 */
495 case SRT_Mem: {
496 assert( nColumn==1 );
497 if( pOrderBy ){
498 pushOntoSorter(pParse, v, pOrderBy);
499 }else{
danielk19774adee202004-05-08 08:23:19 +0000500 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
501 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000502 }
503 break;
504 }
drh22827922000-06-06 17:27:05 +0000505
drhf46f9052002-06-22 02:33:38 +0000506 /* Send the data to the callback function.
507 */
508 case SRT_Callback:
509 case SRT_Sorter: {
510 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000511 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000512 pushOntoSorter(pParse, v, pOrderBy);
513 }else{
514 assert( eDest==SRT_Callback );
danielk19774adee202004-05-08 08:23:19 +0000515 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000516 }
517 break;
518 }
519
drh142e30d2002-08-28 03:00:58 +0000520 /* Invoke a subroutine to handle the results. The subroutine itself
521 ** is responsible for popping the results off of the stack.
522 */
523 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000524 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000525 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000526 pushOntoSorter(pParse, v, pOrderBy);
527 }else{
danielk19774adee202004-05-08 08:23:19 +0000528 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhac82fcf2002-09-08 17:23:41 +0000529 }
drh142e30d2002-08-28 03:00:58 +0000530 break;
531 }
532
drhc926afb2002-06-20 03:38:26 +0000533 /* Discard the results. This is used for SELECT statements inside
534 ** the body of a TRIGGER. The purpose of such selects is to call
535 ** user-defined functions that have side effects. We do not care
536 ** about the actual results of the select.
537 */
drhc926afb2002-06-20 03:38:26 +0000538 default: {
drhf46f9052002-06-22 02:33:38 +0000539 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000540 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000541 break;
542 }
drh82c3d632000-06-06 21:56:07 +0000543 }
544 return 0;
545}
546
547/*
drhd8bc7082000-06-07 23:51:50 +0000548** If the inner loop was generated using a non-null pOrderBy argument,
549** then the results were placed in a sorter. After the loop is terminated
550** we need to run the sorter and output the results. The following
551** routine generates the code needed to do that.
552*/
drhc926afb2002-06-20 03:38:26 +0000553static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000554 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000555 Select *p, /* The SELECT statement */
556 Vdbe *v, /* Generate code into this VDBE */
557 int nColumn, /* Number of columns of data */
558 int eDest, /* Write the sorted results here */
559 int iParm /* Optional parameter associated with eDest */
560){
danielk19774adee202004-05-08 08:23:19 +0000561 int end1 = sqlite3VdbeMakeLabel(v);
562 int end2 = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000563 int addr;
drhffbc3082004-05-21 01:29:06 +0000564 KeyInfo *pInfo;
565 ExprList *pOrderBy;
566 int nCol, i;
drh9bb575f2004-09-06 17:24:11 +0000567 sqlite3 *db = pParse->db;
drhffbc3082004-05-21 01:29:06 +0000568
drhf46f9052002-06-22 02:33:38 +0000569 if( eDest==SRT_Sorter ) return;
drhffbc3082004-05-21 01:29:06 +0000570 pOrderBy = p->pOrderBy;
571 nCol = pOrderBy->nExpr;
572 pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
573 if( pInfo==0 ) return;
574 pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
575 pInfo->nField = nCol;
576 for(i=0; i<nCol; i++){
danielk19770202b292004-06-09 09:55:16 +0000577 /* If a collation sequence was specified explicity, then it
578 ** is stored in pOrderBy->a[i].zName. Otherwise, use the default
579 ** collation type for the expression.
580 */
danielk19777cedc8d2004-06-10 10:50:08 +0000581 pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr);
danielk19770202b292004-06-09 09:55:16 +0000582 if( !pInfo->aColl[i] ){
583 pInfo->aColl[i] = db->pDfltColl;
584 }
drhffbc3082004-05-21 01:29:06 +0000585 pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
586 }
587 sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
danielk19774adee202004-05-08 08:23:19 +0000588 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
drhbab39e12004-07-19 23:38:11 +0000589 codeLimiter(v, p, addr, end2, 1);
drhc926afb2002-06-20 03:38:26 +0000590 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000591 case SRT_Table:
592 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000593 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
594 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
595 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000596 break;
597 }
598 case SRT_Set: {
599 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000600 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
601 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
602 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
danielk1977ededfd52004-06-17 07:53:01 +0000603 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000604 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000605 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000606 break;
607 }
608 case SRT_Mem: {
609 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000610 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
611 sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
drhc926afb2002-06-20 03:38:26 +0000612 break;
613 }
drhce665cf2004-05-21 03:01:58 +0000614 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000615 case SRT_Subroutine: {
616 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000617 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
618 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000619 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000620 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000621 }
drhce665cf2004-05-21 03:01:58 +0000622 if( eDest==SRT_Callback ){
623 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
624 }else{
625 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
626 }
danielk197784ac9d02004-05-18 09:58:06 +0000627 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000628 break;
629 }
drhc926afb2002-06-20 03:38:26 +0000630 default: {
drhf46f9052002-06-22 02:33:38 +0000631 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000632 break;
633 }
634 }
danielk19774adee202004-05-08 08:23:19 +0000635 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
636 sqlite3VdbeResolveLabel(v, end2);
637 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
638 sqlite3VdbeResolveLabel(v, end1);
639 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000640}
641
642/*
danielk1977517eb642004-06-07 10:00:31 +0000643** Return a pointer to a string containing the 'declaration type' of the
644** expression pExpr. The string may be treated as static by the caller.
drhe78e8282003-01-19 03:59:45 +0000645**
danielk1977517eb642004-06-07 10:00:31 +0000646** If the declaration type is the exact datatype definition extracted from
647** the original CREATE TABLE statement if the expression is a column.
648**
649** The declaration type for an expression is either TEXT, NUMERIC or ANY.
650** The declaration type for a ROWID field is INTEGER.
651*/
652static const char *columnType(Parse *pParse, SrcList *pTabList, Expr *pExpr){
danielk197700e279d2004-06-21 07:36:32 +0000653 char const *zType;
danielk1977517eb642004-06-07 10:00:31 +0000654 int j;
danielk197700e279d2004-06-21 07:36:32 +0000655 if( pExpr==0 || pTabList==0 ) return 0;
656
657 switch( pExpr->op ){
658 case TK_COLUMN: {
659 Table *pTab;
660 int iCol = pExpr->iColumn;
661 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable; j++){}
662 assert( j<pTabList->nSrc );
663 pTab = pTabList->a[j].pTab;
664 if( iCol<0 ) iCol = pTab->iPKey;
665 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
666 if( iCol<0 ){
667 zType = "INTEGER";
668 }else{
669 zType = pTab->aCol[iCol].zType;
670 }
671 break;
danielk1977517eb642004-06-07 10:00:31 +0000672 }
danielk197700e279d2004-06-21 07:36:32 +0000673 case TK_AS:
674 zType = columnType(pParse, pTabList, pExpr->pLeft);
675 break;
676 case TK_SELECT: {
677 Select *pS = pExpr->pSelect;
678 zType = columnType(pParse, pS->pSrc, pS->pEList->a[0].pExpr);
679 break;
danielk1977517eb642004-06-07 10:00:31 +0000680 }
danielk197700e279d2004-06-21 07:36:32 +0000681 default:
682 zType = 0;
danielk1977517eb642004-06-07 10:00:31 +0000683 }
danielk197700e279d2004-06-21 07:36:32 +0000684
danielk1977517eb642004-06-07 10:00:31 +0000685 return zType;
686}
687
688/*
689** Generate code that will tell the VDBE the declaration types of columns
690** in the result set.
drhfcb78a42003-01-18 20:11:05 +0000691*/
692static void generateColumnTypes(
693 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000694 SrcList *pTabList, /* List of tables */
695 ExprList *pEList /* Expressions defining the result set */
696){
697 Vdbe *v = pParse->pVdbe;
danielk1977517eb642004-06-07 10:00:31 +0000698 int i;
drhfcb78a42003-01-18 20:11:05 +0000699 for(i=0; i<pEList->nExpr; i++){
700 Expr *p = pEList->a[i].pExpr;
danielk1977517eb642004-06-07 10:00:31 +0000701 const char *zType = columnType(pParse, pTabList, p);
danielk197700e279d2004-06-21 07:36:32 +0000702 if( zType==0 ) continue;
danielk1977fbcd5852004-06-15 02:44:18 +0000703 /* The vdbe must make it's own copy of the column-type, in case the
704 ** schema is reset before this virtual machine is deleted.
705 */
706 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
drhfcb78a42003-01-18 20:11:05 +0000707 }
708}
709
710/*
711** Generate code that will tell the VDBE the names of columns
712** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000713** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000714*/
drh832508b2002-03-02 17:04:07 +0000715static void generateColumnNames(
716 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000717 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000718 ExprList *pEList /* Expressions defining the result set */
719){
drhd8bc7082000-06-07 23:51:50 +0000720 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000721 int i, j;
drh9bb575f2004-09-06 17:24:11 +0000722 sqlite3 *db = pParse->db;
drhfcabd462004-02-20 14:50:58 +0000723 int fullNames, shortNames;
724
danielk19773cf86062004-05-26 10:11:05 +0000725 /* If this is an EXPLAIN, skip this step */
726 if( pParse->explain ){
danielk197761de0d12004-05-27 23:56:16 +0000727 return;
danielk19773cf86062004-05-26 10:11:05 +0000728 }
729
drhd6502752004-02-16 03:44:01 +0000730 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000731 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000732 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000733 fullNames = (db->flags & SQLITE_FullColNames)!=0;
734 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
danielk197722322fd2004-05-25 23:35:17 +0000735 sqlite3VdbeSetNumCols(v, pEList->nExpr);
drh82c3d632000-06-06 21:56:07 +0000736 for(i=0; i<pEList->nExpr; i++){
737 Expr *p;
drh5a387052003-01-11 14:19:51 +0000738 p = pEList->a[i].pExpr;
739 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000740 if( pEList->a[i].zName ){
741 char *zName = pEList->a[i].zName;
danielk1977d8123362004-06-12 09:25:12 +0000742 sqlite3VdbeSetColName(v, i, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000743 continue;
744 }
drhfa173a72002-07-10 21:26:00 +0000745 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000746 Table *pTab;
drh97665872002-02-13 23:22:53 +0000747 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000748 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000749 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
750 assert( j<pTabList->nSrc );
751 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000752 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000753 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000754 if( iCol<0 ){
755 zCol = "_ROWID_";
drhb1363202002-06-26 02:45:03 +0000756 }else{
757 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000758 }
drhfcabd462004-02-20 14:50:58 +0000759 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000760 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
drhfcabd462004-02-20 14:50:58 +0000761 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000762 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000763 char *zTab;
764
drh6a3ea0e2003-05-02 14:32:12 +0000765 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000766 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000767 sqlite3SetString(&zName, zTab, ".", zCol, 0);
danielk19773cf86062004-05-26 10:11:05 +0000768 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000769 }else{
danielk19773cf86062004-05-26 10:11:05 +0000770 sqlite3VdbeSetColName(v, i, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000771 }
drh6977fea2002-10-22 23:38:04 +0000772 }else if( p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000773 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
774 /* sqlite3VdbeCompressSpace(v, addr); */
drh1bee3d72001-10-15 00:44:35 +0000775 }else{
776 char zName[30];
777 assert( p->op!=TK_COLUMN || pTabList==0 );
778 sprintf(zName, "column%d", i+1);
danielk19773cf86062004-05-26 10:11:05 +0000779 sqlite3VdbeSetColName(v, i, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000780 }
781 }
danielk197776d505b2004-05-28 13:13:02 +0000782 generateColumnTypes(pParse, pTabList, pEList);
drh82c3d632000-06-06 21:56:07 +0000783}
784
785/*
drhd8bc7082000-06-07 23:51:50 +0000786** Name of the connection operator, used for error messages.
787*/
788static const char *selectOpName(int id){
789 char *z;
790 switch( id ){
791 case TK_ALL: z = "UNION ALL"; break;
792 case TK_INTERSECT: z = "INTERSECT"; break;
793 case TK_EXCEPT: z = "EXCEPT"; break;
794 default: z = "UNION"; break;
795 }
796 return z;
797}
798
799/*
drh315555c2002-10-20 15:53:03 +0000800** Forward declaration
801*/
802static int fillInColumnList(Parse*, Select*);
803
804/*
drh22f70c32002-02-18 01:17:00 +0000805** Given a SELECT statement, generate a Table structure that describes
806** the result set of that SELECT.
807*/
danielk19774adee202004-05-08 08:23:19 +0000808Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000809 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000810 int i, j;
drh22f70c32002-02-18 01:17:00 +0000811 ExprList *pEList;
drh290c1942004-08-21 17:54:45 +0000812 Column *aCol, *pCol;
drh22f70c32002-02-18 01:17:00 +0000813
814 if( fillInColumnList(pParse, pSelect) ){
815 return 0;
816 }
817 pTab = sqliteMalloc( sizeof(Table) );
818 if( pTab==0 ){
819 return 0;
820 }
821 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
822 pEList = pSelect->pEList;
823 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000824 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000825 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh290c1942004-08-21 17:54:45 +0000826 for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
danielk1977517eb642004-06-07 10:00:31 +0000827 Expr *pR;
828 char *zType;
drh91bb0ee2004-09-01 03:06:34 +0000829 char *zName;
danielk1977517eb642004-06-07 10:00:31 +0000830 Expr *p = pEList->a[i].pExpr;
drh290c1942004-08-21 17:54:45 +0000831 assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
drh91bb0ee2004-09-01 03:06:34 +0000832 if( (zName = pEList->a[i].zName)!=0 ){
833 zName = sqliteStrDup(zName);
danielk1977517eb642004-06-07 10:00:31 +0000834 }else if( p->op==TK_DOT
drhb733d032004-01-24 20:18:12 +0000835 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
836 int cnt;
drh91bb0ee2004-09-01 03:06:34 +0000837 zName = sqlite3MPrintf("%T", &pR->token);
drhb733d032004-01-24 20:18:12 +0000838 for(j=cnt=0; j<i; j++){
drh91bb0ee2004-09-01 03:06:34 +0000839 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
840 sqliteFree(zName);
841 zName = sqlite3MPrintf("%T_%d", &pR->token, ++cnt);
drhb733d032004-01-24 20:18:12 +0000842 j = -1;
843 }
844 }
845 }else if( p->span.z && p->span.z[0] ){
drh91bb0ee2004-09-01 03:06:34 +0000846 zName = sqlite3MPrintf("%T", &p->span);
drh22f70c32002-02-18 01:17:00 +0000847 }else{
drh91bb0ee2004-09-01 03:06:34 +0000848 zName = sqlite3MPrintf("column%d", i+1);
drh22f70c32002-02-18 01:17:00 +0000849 }
drh91bb0ee2004-09-01 03:06:34 +0000850 sqlite3Dequote(zName);
851 pCol->zName = zName;
danielk1977517eb642004-06-07 10:00:31 +0000852
853 zType = sqliteStrDup(columnType(pParse, pSelect->pSrc ,p));
drh290c1942004-08-21 17:54:45 +0000854 pCol->zType = zType;
855 pCol->affinity = SQLITE_AFF_NUMERIC;
danielk1977517eb642004-06-07 10:00:31 +0000856 if( zType ){
drh290c1942004-08-21 17:54:45 +0000857 pCol->affinity = sqlite3AffinityType(zType, strlen(zType));
danielk1977517eb642004-06-07 10:00:31 +0000858 }
drh290c1942004-08-21 17:54:45 +0000859 pCol->pColl = sqlite3ExprCollSeq(pParse, p);
860 if( !pCol->pColl ){
861 pCol->pColl = pParse->db->pDfltColl;
danielk19770202b292004-06-09 09:55:16 +0000862 }
drh22f70c32002-02-18 01:17:00 +0000863 }
864 pTab->iPKey = -1;
865 return pTab;
866}
867
868/*
drhad2d8302002-05-24 20:31:36 +0000869** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000870**
drhad3cab52002-05-24 02:04:32 +0000871** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh63eb5f22003-04-29 16:20:44 +0000872** defines the set of tables that should be scanned. For views,
873** fill pTabList->a[].pSelect with a copy of the SELECT statement
874** that implements the view. A copy is made of the view's SELECT
875** statement so that we can freely modify or delete that statement
876** without worrying about messing up the presistent representation
877** of the view.
drhd8bc7082000-06-07 23:51:50 +0000878**
drhad2d8302002-05-24 20:31:36 +0000879** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
880** on joins and the ON and USING clause of joins.
881**
882** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000883** for instances of the "*" operator or the TABLE.* operator.
884** If found, expand each "*" to be every column in every table
885** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000886**
887** Return 0 on success. If there are problems, leave an error message
888** in pParse and return non-zero.
889*/
890static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000891 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000892 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000893 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000894 Table *pTab;
drh290c1942004-08-21 17:54:45 +0000895 struct SrcList_item *pFrom;
drhdaffd0e2001-04-11 14:28:42 +0000896
897 if( p==0 || p->pSrc==0 ) return 1;
898 pTabList = p->pSrc;
899 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000900
901 /* Look up every table in the table list.
902 */
drh290c1942004-08-21 17:54:45 +0000903 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
904 if( pFrom->pTab ){
drhd8bc7082000-06-07 23:51:50 +0000905 /* This routine has run before! No need to continue */
906 return 0;
907 }
drh290c1942004-08-21 17:54:45 +0000908 if( pFrom->zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000909 /* A sub-query in the FROM clause of a SELECT */
drh290c1942004-08-21 17:54:45 +0000910 assert( pFrom->pSelect!=0 );
911 if( pFrom->zAlias==0 ){
drh91bb0ee2004-09-01 03:06:34 +0000912 pFrom->zAlias =
913 sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
drhad2d8302002-05-24 20:31:36 +0000914 }
drh290c1942004-08-21 17:54:45 +0000915 pFrom->pTab = pTab =
916 sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
drh22f70c32002-02-18 01:17:00 +0000917 if( pTab==0 ){
918 return 1;
919 }
drh5cf590c2003-04-24 01:45:04 +0000920 /* The isTransient flag indicates that the Table structure has been
921 ** dynamically allocated and may be freed at any time. In other words,
922 ** pTab is not pointing to a persistent table structure that defines
923 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000924 pTab->isTransient = 1;
925 }else{
drha76b5df2002-02-23 02:32:10 +0000926 /* An ordinary table or view name in the FROM clause */
drh290c1942004-08-21 17:54:45 +0000927 pFrom->pTab = pTab =
928 sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
drha76b5df2002-02-23 02:32:10 +0000929 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000930 return 1;
931 }
drha76b5df2002-02-23 02:32:10 +0000932 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +0000933 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +0000934 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +0000935 return 1;
936 }
drh290c1942004-08-21 17:54:45 +0000937 /* If pFrom->pSelect!=0 it means we are dealing with a
drh63eb5f22003-04-29 16:20:44 +0000938 ** view within a view. The SELECT structure has already been
939 ** copied by the outer view so we can skip the copy step here
940 ** in the inner view.
941 */
drh290c1942004-08-21 17:54:45 +0000942 if( pFrom->pSelect==0 ){
943 pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +0000944 }
drha76b5df2002-02-23 02:32:10 +0000945 }
drhd8bc7082000-06-07 23:51:50 +0000946 }
947 }
948
drhad2d8302002-05-24 20:31:36 +0000949 /* Process NATURAL keywords, and ON and USING clauses of joins.
950 */
951 if( sqliteProcessJoin(pParse, p) ) return 1;
952
drh7c917d12001-12-16 20:05:05 +0000953 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000954 ** all columns in all tables. And for every TABLE.* insert the names
955 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000956 ** with the TK_ALL operator for each "*" that it found in the column list.
957 ** The following code just has to locate the TK_ALL expressions and expand
958 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000959 **
960 ** The first loop just checks to see if there are any "*" operators
961 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000962 */
drh7c917d12001-12-16 20:05:05 +0000963 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000964 Expr *pE = pEList->a[k].pExpr;
965 if( pE->op==TK_ALL ) break;
966 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
967 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000968 }
drh54473222002-04-04 02:10:55 +0000969 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000970 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000971 /*
972 ** If we get here it means the result set contains one or more "*"
973 ** operators that need to be expanded. Loop through each expression
974 ** in the result set and expand them one by one.
975 */
drh7c917d12001-12-16 20:05:05 +0000976 struct ExprList_item *a = pEList->a;
977 ExprList *pNew = 0;
978 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000979 Expr *pE = a[k].pExpr;
980 if( pE->op!=TK_ALL &&
981 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
982 /* This particular expression does not need to be expanded.
983 */
danielk19774adee202004-05-08 08:23:19 +0000984 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +0000985 pNew->a[pNew->nExpr-1].zName = a[k].zName;
986 a[k].pExpr = 0;
987 a[k].zName = 0;
988 }else{
drh54473222002-04-04 02:10:55 +0000989 /* This expression is a "*" or a "TABLE.*" and needs to be
990 ** expanded. */
991 int tableSeen = 0; /* Set to 1 when TABLE matches */
drhcf55b7a2004-07-20 01:45:19 +0000992 char *zTName; /* text of name of TABLE */
drh54473222002-04-04 02:10:55 +0000993 if( pE->op==TK_DOT && pE->pLeft ){
drhcf55b7a2004-07-20 01:45:19 +0000994 zTName = sqlite3NameFromToken(&pE->pLeft->token);
drh54473222002-04-04 02:10:55 +0000995 }else{
drhcf55b7a2004-07-20 01:45:19 +0000996 zTName = 0;
drh54473222002-04-04 02:10:55 +0000997 }
drh290c1942004-08-21 17:54:45 +0000998 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
999 Table *pTab = pFrom->pTab;
1000 char *zTabName = pFrom->zAlias;
drh54473222002-04-04 02:10:55 +00001001 if( zTabName==0 || zTabName[0]==0 ){
1002 zTabName = pTab->zName;
1003 }
drhcf55b7a2004-07-20 01:45:19 +00001004 if( zTName && (zTabName==0 || zTabName[0]==0 ||
1005 sqlite3StrICmp(zTName, zTabName)!=0) ){
drh54473222002-04-04 02:10:55 +00001006 continue;
1007 }
1008 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001009 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001010 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001011 char *zName = pTab->aCol[j].zName;
1012
drh91bb0ee2004-09-01 03:06:34 +00001013 if( i>0 ){
1014 struct SrcList_item *pLeft = &pTabList->a[i-1];
1015 if( (pLeft->jointype & JT_NATURAL)!=0 &&
1016 columnIndex(pLeft->pTab, zName)>=0 ){
1017 /* In a NATURAL join, omit the join columns from the
1018 ** table on the right */
1019 continue;
1020 }
1021 if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1022 /* In a join with a USING clause, omit columns in the
1023 ** using clause from the table on the right. */
1024 continue;
1025 }
drhad2d8302002-05-24 20:31:36 +00001026 }
danielk19774adee202004-05-08 08:23:19 +00001027 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001028 if( pRight==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001029 setToken(&pRight->token, zName);
drh4b59ab52002-08-24 18:24:51 +00001030 if( zTabName && pTabList->nSrc>1 ){
danielk19774adee202004-05-08 08:23:19 +00001031 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1032 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001033 if( pExpr==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001034 setToken(&pLeft->token, zTabName);
1035 setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
drh6977fea2002-10-22 23:38:04 +00001036 pExpr->span.dyn = 1;
1037 pExpr->token.z = 0;
1038 pExpr->token.n = 0;
1039 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001040 }else{
drh22f70c32002-02-18 01:17:00 +00001041 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001042 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001043 }
danielk19774adee202004-05-08 08:23:19 +00001044 pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001045 }
drh17e24df2001-11-06 14:10:41 +00001046 }
drh54473222002-04-04 02:10:55 +00001047 if( !tableSeen ){
drhcf55b7a2004-07-20 01:45:19 +00001048 if( zTName ){
1049 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
drhf5db2d32002-06-06 23:42:27 +00001050 }else{
danielk19774adee202004-05-08 08:23:19 +00001051 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001052 }
drh54473222002-04-04 02:10:55 +00001053 rc = 1;
1054 }
drhcf55b7a2004-07-20 01:45:19 +00001055 sqliteFree(zTName);
drhd8bc7082000-06-07 23:51:50 +00001056 }
1057 }
danielk19774adee202004-05-08 08:23:19 +00001058 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001059 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001060 }
drh54473222002-04-04 02:10:55 +00001061 return rc;
drhd8bc7082000-06-07 23:51:50 +00001062}
1063
1064/*
drhff78bd22002-02-27 01:47:11 +00001065** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1066** in a select structure. It just sets the pointers to NULL. This
1067** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1068** pointer is not NULL, this routine is called recursively on that pointer.
1069**
1070** This routine is called on the Select structure that defines a
1071** VIEW in order to undo any bindings to tables. This is necessary
1072** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001073** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1074** will be left pointing to a deallocated Table structure after the
1075** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001076*/
danielk19774adee202004-05-08 08:23:19 +00001077void sqlite3SelectUnbind(Select *p){
drhff78bd22002-02-27 01:47:11 +00001078 int i;
drhad3cab52002-05-24 02:04:32 +00001079 SrcList *pSrc = p->pSrc;
drh91bb0ee2004-09-01 03:06:34 +00001080 struct SrcList_item *pItem;
drhff78bd22002-02-27 01:47:11 +00001081 Table *pTab;
1082 if( p==0 ) return;
drh91bb0ee2004-09-01 03:06:34 +00001083 for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
1084 if( (pTab = pItem->pTab)!=0 ){
drhff78bd22002-02-27 01:47:11 +00001085 if( pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001086 sqlite3DeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001087 }
drh91bb0ee2004-09-01 03:06:34 +00001088 pItem->pTab = 0;
1089 if( pItem->pSelect ){
1090 sqlite3SelectUnbind(pItem->pSelect);
drhff78bd22002-02-27 01:47:11 +00001091 }
1092 }
1093 }
1094}
1095
1096/*
drhd8bc7082000-06-07 23:51:50 +00001097** This routine associates entries in an ORDER BY expression list with
1098** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001099** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001100** the top-level node is filled in with column number and the iTable
1101** value of the top-level node is filled with iTable parameter.
1102**
1103** If there are prior SELECT clauses, they are processed first. A match
1104** in an earlier SELECT takes precedence over a later SELECT.
1105**
1106** Any entry that does not match is flagged as an error. The number
1107** of errors is returned.
1108*/
1109static int matchOrderbyToColumn(
1110 Parse *pParse, /* A place to leave error messages */
1111 Select *pSelect, /* Match to result columns of this SELECT */
1112 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001113 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001114 int mustComplete /* If TRUE all ORDER BYs must match */
1115){
1116 int nErr = 0;
1117 int i, j;
1118 ExprList *pEList;
1119
drhdaffd0e2001-04-11 14:28:42 +00001120 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001121 if( mustComplete ){
1122 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1123 }
1124 if( fillInColumnList(pParse, pSelect) ){
1125 return 1;
1126 }
1127 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001128 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1129 return 1;
1130 }
drhd8bc7082000-06-07 23:51:50 +00001131 }
1132 pEList = pSelect->pEList;
1133 for(i=0; i<pOrderBy->nExpr; i++){
1134 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001135 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001136 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001137 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001138 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001139 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001140 "ORDER BY position %d should be between 1 and %d",
1141 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001142 nErr++;
1143 break;
1144 }
drhfcb78a42003-01-18 20:11:05 +00001145 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001146 iCol--;
1147 }
1148 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001149 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001150 char *zName, *zLabel;
1151 zName = pEList->a[j].zName;
drha99db3b2004-06-19 14:49:12 +00001152 zLabel = sqlite3NameFromToken(&pE->token);
1153 assert( zLabel!=0 );
danielk19774adee202004-05-08 08:23:19 +00001154 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001155 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001156 }
drh6e142f52000-06-08 13:36:40 +00001157 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001158 }
danielk19774adee202004-05-08 08:23:19 +00001159 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001160 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001161 }
1162 }
drhe4de1fe2002-06-02 16:09:01 +00001163 if( iCol>=0 ){
1164 pE->op = TK_COLUMN;
1165 pE->iColumn = iCol;
1166 pE->iTable = iTable;
1167 pOrderBy->a[i].done = 1;
1168 }
1169 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001170 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001171 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001172 nErr++;
1173 break;
1174 }
1175 }
1176 return nErr;
1177}
1178
1179/*
1180** Get a VDBE for the given parser context. Create a new one if necessary.
1181** If an error occurs, return NULL and leave a message in pParse.
1182*/
danielk19774adee202004-05-08 08:23:19 +00001183Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001184 Vdbe *v = pParse->pVdbe;
1185 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001186 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001187 }
drhd8bc7082000-06-07 23:51:50 +00001188 return v;
1189}
drhfcb78a42003-01-18 20:11:05 +00001190
drhd8bc7082000-06-07 23:51:50 +00001191/*
drh7b58dae2003-07-20 01:16:46 +00001192** Compute the iLimit and iOffset fields of the SELECT based on the
1193** nLimit and nOffset fields. nLimit and nOffset hold the integers
1194** that appear in the original SQL statement after the LIMIT and OFFSET
1195** keywords. Or that hold -1 and 0 if those keywords are omitted.
1196** iLimit and iOffset are the integer memory register numbers for
1197** counters used to compute the limit and offset. If there is no
1198** limit and/or offset, then iLimit and iOffset are negative.
1199**
1200** This routine changes the values if iLimit and iOffset only if
1201** a limit or offset is defined by nLimit and nOffset. iLimit and
1202** iOffset should have been preset to appropriate default values
1203** (usually but not always -1) prior to calling this routine.
1204** Only if nLimit>=0 or nOffset>0 do the limit registers get
1205** redefined. The UNION ALL operator uses this property to force
1206** the reuse of the same limit and offset registers across multiple
1207** SELECT statements.
1208*/
1209static void computeLimitRegisters(Parse *pParse, Select *p){
1210 /*
1211 ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
1212 ** all rows. It is the same as no limit. If the comparision is
1213 ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
1214 ** "LIMIT -1" always shows all rows. There is some
1215 ** contraversy about what the correct behavior should be.
1216 ** The current implementation interprets "LIMIT 0" to mean
1217 ** no rows.
1218 */
1219 if( p->nLimit>=0 ){
1220 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001221 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001222 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001223 sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1224 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001225 VdbeComment((v, "# LIMIT counter"));
drh7b58dae2003-07-20 01:16:46 +00001226 p->iLimit = iMem;
1227 }
1228 if( p->nOffset>0 ){
1229 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001230 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001231 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001232 sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1233 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001234 VdbeComment((v, "# OFFSET counter"));
drh7b58dae2003-07-20 01:16:46 +00001235 p->iOffset = iMem;
1236 }
1237}
1238
1239/*
drhd3d39e92004-05-20 22:16:29 +00001240** Generate VDBE instructions that will open a transient table that
1241** will be used for an index or to store keyed results for a compound
1242** select. In other words, open a transient table that needs a
1243** KeyInfo structure. The number of columns in the KeyInfo is determined
1244** by the result set of the SELECT statement in the second argument.
1245**
danielk1977dc1bdc42004-06-11 10:51:27 +00001246** Specifically, this routine is called to open an index table for
1247** DISTINCT, UNION, INTERSECT and EXCEPT select statements (but not
1248** UNION ALL).
1249**
drhd3d39e92004-05-20 22:16:29 +00001250** Make the new table a KeyAsData table if keyAsData is true.
danielk1977dc1bdc42004-06-11 10:51:27 +00001251**
1252** The value returned is the address of the OP_OpenTemp instruction.
drhd3d39e92004-05-20 22:16:29 +00001253*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001254static int openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
drhd3d39e92004-05-20 22:16:29 +00001255 KeyInfo *pKeyInfo;
drh736c22b2004-05-21 02:14:24 +00001256 int nColumn;
drh9bb575f2004-09-06 17:24:11 +00001257 sqlite3 *db = pParse->db;
drhd3d39e92004-05-20 22:16:29 +00001258 int i;
1259 Vdbe *v = pParse->pVdbe;
danielk1977dc1bdc42004-06-11 10:51:27 +00001260 int addr;
drhd3d39e92004-05-20 22:16:29 +00001261
drh736c22b2004-05-21 02:14:24 +00001262 if( fillInColumnList(pParse, p) ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001263 return 0;
drh736c22b2004-05-21 02:14:24 +00001264 }
1265 nColumn = p->pEList->nExpr;
drhd3d39e92004-05-20 22:16:29 +00001266 pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
danielk1977dc1bdc42004-06-11 10:51:27 +00001267 if( pKeyInfo==0 ) return 0;
drh91bb0ee2004-09-01 03:06:34 +00001268 pKeyInfo->enc = db->enc;
drhd3d39e92004-05-20 22:16:29 +00001269 pKeyInfo->nField = nColumn;
1270 for(i=0; i<nColumn; i++){
danielk1977dc1bdc42004-06-11 10:51:27 +00001271 pKeyInfo->aColl[i] = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
1272 if( !pKeyInfo->aColl[i] ){
1273 pKeyInfo->aColl[i] = db->pDfltColl;
1274 }
drhd3d39e92004-05-20 22:16:29 +00001275 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001276 addr = sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0,
1277 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drhd3d39e92004-05-20 22:16:29 +00001278 if( keyAsData ){
1279 sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1280 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001281 return addr;
1282}
1283
drhb7f91642004-10-31 02:22:47 +00001284#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001285/*
drh8cdbf832004-08-29 16:25:03 +00001286** Add the address "addr" to the set of all OpenTemp opcode addresses
1287** that are being accumulated in p->ppOpenTemp.
drhfbc4ee72004-08-29 01:31:05 +00001288*/
drh8cdbf832004-08-29 16:25:03 +00001289static int multiSelectOpenTempAddr(Select *p, int addr){
1290 IdList *pList = *p->ppOpenTemp = sqlite3IdListAppend(*p->ppOpenTemp, 0);
drhfbc4ee72004-08-29 01:31:05 +00001291 if( pList==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001292 return SQLITE_NOMEM;
1293 }
drhfbc4ee72004-08-29 01:31:05 +00001294 pList->a[pList->nId-1].idx = addr;
danielk1977dc1bdc42004-06-11 10:51:27 +00001295 return SQLITE_OK;
1296}
drhb7f91642004-10-31 02:22:47 +00001297#endif /* SQLITE_OMIT_COMPOUND_SELECT */
danielk1977dc1bdc42004-06-11 10:51:27 +00001298
drhb7f91642004-10-31 02:22:47 +00001299#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001300/*
1301** Return the appropriate collating sequence for the iCol-th column of
1302** the result set for the compound-select statement "p". Return NULL if
1303** the column has no default collating sequence.
1304**
1305** The collating sequence for the compound select is taken from the
1306** left-most term of the select that has a collating sequence.
1307*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001308static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
drhfbc4ee72004-08-29 01:31:05 +00001309 CollSeq *pRet;
danielk1977dc1bdc42004-06-11 10:51:27 +00001310 if( p->pPrior ){
1311 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
drhfbc4ee72004-08-29 01:31:05 +00001312 }else{
1313 pRet = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001314 }
drhfbc4ee72004-08-29 01:31:05 +00001315 if( pRet==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001316 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1317 }
1318 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001319}
drhb7f91642004-10-31 02:22:47 +00001320#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd3d39e92004-05-20 22:16:29 +00001321
drhb7f91642004-10-31 02:22:47 +00001322#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhd3d39e92004-05-20 22:16:29 +00001323/*
drh82c3d632000-06-06 21:56:07 +00001324** This routine is called to process a query that is really the union
1325** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001326**
drhe78e8282003-01-19 03:59:45 +00001327** "p" points to the right-most of the two queries. the query on the
1328** left is p->pPrior. The left query could also be a compound query
1329** in which case this routine will be called recursively.
1330**
1331** The results of the total query are to be written into a destination
1332** of type eDest with parameter iParm.
1333**
1334** Example 1: Consider a three-way compound SQL statement.
1335**
1336** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1337**
1338** This statement is parsed up as follows:
1339**
1340** SELECT c FROM t3
1341** |
1342** `-----> SELECT b FROM t2
1343** |
jplyon4b11c6d2004-01-19 04:57:53 +00001344** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001345**
1346** The arrows in the diagram above represent the Select.pPrior pointer.
1347** So if this routine is called with p equal to the t3 query, then
1348** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1349**
1350** Notice that because of the way SQLite parses compound SELECTs, the
1351** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001352*/
danielk197784ac9d02004-05-18 09:58:06 +00001353static int multiSelect(
drhfbc4ee72004-08-29 01:31:05 +00001354 Parse *pParse, /* Parsing context */
1355 Select *p, /* The right-most of SELECTs to be coded */
1356 int eDest, /* \___ Store query results as specified */
1357 int iParm, /* / by these two parameters. */
1358 char *aff /* If eDest is SRT_Union, the affinity string */
danielk197784ac9d02004-05-18 09:58:06 +00001359){
drhfbc4ee72004-08-29 01:31:05 +00001360 int rc = SQLITE_OK; /* Success code from a subroutine */
1361 Select *pPrior; /* Another SELECT immediately to our left */
1362 Vdbe *v; /* Generate code to this VDBE */
1363 IdList *pOpenTemp = 0;/* OP_OpenTemp opcodes that need a KeyInfo */
drh8cdbf832004-08-29 16:25:03 +00001364 int aAddr[5]; /* Addresses of SetNumColumns operators */
1365 int nAddr = 0; /* Number used */
1366 int nCol; /* Number of columns in the result set */
drh82c3d632000-06-06 21:56:07 +00001367
drh7b58dae2003-07-20 01:16:46 +00001368 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
drhfbc4ee72004-08-29 01:31:05 +00001369 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001370 */
danielk197784ac9d02004-05-18 09:58:06 +00001371 if( p==0 || p->pPrior==0 ){
1372 rc = 1;
1373 goto multi_select_end;
1374 }
drhd8bc7082000-06-07 23:51:50 +00001375 pPrior = p->pPrior;
1376 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001377 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001378 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001379 rc = 1;
1380 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001381 }
drh7b58dae2003-07-20 01:16:46 +00001382 if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
danielk19774adee202004-05-08 08:23:19 +00001383 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001384 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001385 rc = 1;
1386 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001387 }
drh82c3d632000-06-06 21:56:07 +00001388
drhd8bc7082000-06-07 23:51:50 +00001389 /* Make sure we have a valid query engine. If not, create a new one.
1390 */
danielk19774adee202004-05-08 08:23:19 +00001391 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001392 if( v==0 ){
1393 rc = 1;
1394 goto multi_select_end;
1395 }
drhd8bc7082000-06-07 23:51:50 +00001396
drh8cdbf832004-08-29 16:25:03 +00001397 /* If *p this is the right-most select statement, then initialize
1398 ** p->ppOpenTemp to point to pOpenTemp. If *p is not the right most
1399 ** statement then p->ppOpenTemp will have already been initialized
1400 ** by a prior call to this same procedure. Pass along the pOpenTemp
1401 ** pointer to pPrior, the next statement to our left.
drhfbc4ee72004-08-29 01:31:05 +00001402 */
1403 if( p->ppOpenTemp==0 ){
1404 p->ppOpenTemp = &pOpenTemp;
1405 }
1406 pPrior->ppOpenTemp = p->ppOpenTemp;
1407
drh1cc3d752002-03-23 00:31:29 +00001408 /* Create the destination temporary table if necessary
1409 */
1410 if( eDest==SRT_TempTable ){
danielk1977b4964b72004-05-18 01:23:38 +00001411 assert( p->pEList );
danielk19774adee202004-05-08 08:23:19 +00001412 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
drh8cdbf832004-08-29 16:25:03 +00001413 assert( nAddr==0 );
1414 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 0);
drh1cc3d752002-03-23 00:31:29 +00001415 eDest = SRT_Table;
1416 }
1417
drhf46f9052002-06-22 02:33:38 +00001418 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001419 */
drh82c3d632000-06-06 21:56:07 +00001420 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001421 case TK_ALL: {
1422 if( p->pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +00001423 pPrior->nLimit = p->nLimit;
1424 pPrior->nOffset = p->nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001425 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1426 if( rc ){
1427 goto multi_select_end;
1428 }
drhf46f9052002-06-22 02:33:38 +00001429 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001430 p->iLimit = pPrior->iLimit;
1431 p->iOffset = pPrior->iOffset;
1432 p->nLimit = -1;
1433 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001434 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001435 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001436 if( rc ){
1437 goto multi_select_end;
1438 }
drhf46f9052002-06-22 02:33:38 +00001439 break;
1440 }
1441 /* For UNION ALL ... ORDER BY fall through to the next case */
1442 }
drh82c3d632000-06-06 21:56:07 +00001443 case TK_EXCEPT:
1444 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001445 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001446 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001447 int priorOp; /* The SRT_ operation to apply to prior selects */
drh7b58dae2003-07-20 01:16:46 +00001448 int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
drhc926afb2002-06-20 03:38:26 +00001449 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
danielk1977dc1bdc42004-06-11 10:51:27 +00001450 int addr;
drh82c3d632000-06-06 21:56:07 +00001451
drhd8bc7082000-06-07 23:51:50 +00001452 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh7b58dae2003-07-20 01:16:46 +00001453 if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
drhd8bc7082000-06-07 23:51:50 +00001454 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001455 ** right.
drhd8bc7082000-06-07 23:51:50 +00001456 */
drh82c3d632000-06-06 21:56:07 +00001457 unionTab = iParm;
1458 }else{
drhd8bc7082000-06-07 23:51:50 +00001459 /* We will need to create our own temporary table to hold the
1460 ** intermediate results.
1461 */
1462 unionTab = pParse->nTab++;
1463 if( p->pOrderBy
1464 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001465 rc = 1;
1466 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001467 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001468 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001469 if( p->op!=TK_ALL ){
drh8cdbf832004-08-29 16:25:03 +00001470 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001471 if( rc!=SQLITE_OK ){
1472 goto multi_select_end;
1473 }
1474 sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drhd8bc7082000-06-07 23:51:50 +00001475 }
drh8cdbf832004-08-29 16:25:03 +00001476 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1477 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, 0);
danielk197784ac9d02004-05-18 09:58:06 +00001478 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001479 }
drhd8bc7082000-06-07 23:51:50 +00001480
1481 /* Code the SELECT statements to our left
1482 */
danielk197784ac9d02004-05-18 09:58:06 +00001483 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
1484 if( rc ){
1485 goto multi_select_end;
1486 }
drhd8bc7082000-06-07 23:51:50 +00001487
1488 /* Code the current SELECT statement
1489 */
1490 switch( p->op ){
1491 case TK_EXCEPT: op = SRT_Except; break;
1492 case TK_UNION: op = SRT_Union; break;
1493 case TK_ALL: op = SRT_Table; break;
1494 }
drh82c3d632000-06-06 21:56:07 +00001495 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001496 pOrderBy = p->pOrderBy;
1497 p->pOrderBy = 0;
drh7b58dae2003-07-20 01:16:46 +00001498 nLimit = p->nLimit;
1499 p->nLimit = -1;
1500 nOffset = p->nOffset;
1501 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001502 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001503 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001504 p->pOrderBy = pOrderBy;
drh7b58dae2003-07-20 01:16:46 +00001505 p->nLimit = nLimit;
1506 p->nOffset = nOffset;
drhbe5fd492004-12-16 21:09:16 +00001507 p->iLimit = -1;
1508 p->iOffset = -1;
danielk197784ac9d02004-05-18 09:58:06 +00001509 if( rc ){
1510 goto multi_select_end;
1511 }
1512
drhd8bc7082000-06-07 23:51:50 +00001513
1514 /* Convert the data in the temporary table into whatever form
1515 ** it is that we currently need.
1516 */
drhc926afb2002-06-20 03:38:26 +00001517 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001518 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001519 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001520 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001521 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001522 }
danielk19774adee202004-05-08 08:23:19 +00001523 iBreak = sqlite3VdbeMakeLabel(v);
1524 iCont = sqlite3VdbeMakeLabel(v);
1525 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001526 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001527 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001528 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001529 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001530 iCont, iBreak, 0);
1531 if( rc ){
1532 rc = 1;
1533 goto multi_select_end;
1534 }
danielk19774adee202004-05-08 08:23:19 +00001535 sqlite3VdbeResolveLabel(v, iCont);
1536 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1537 sqlite3VdbeResolveLabel(v, iBreak);
1538 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001539 }
1540 break;
1541 }
1542 case TK_INTERSECT: {
1543 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001544 int iCont, iBreak, iStart;
drh7b58dae2003-07-20 01:16:46 +00001545 int nLimit, nOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001546 int addr;
drh82c3d632000-06-06 21:56:07 +00001547
drhd8bc7082000-06-07 23:51:50 +00001548 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001549 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001550 ** by allocating the tables we will need.
1551 */
drh82c3d632000-06-06 21:56:07 +00001552 tab1 = pParse->nTab++;
1553 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001554 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001555 rc = 1;
1556 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001557 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001558
1559 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 0);
drh8cdbf832004-08-29 16:25:03 +00001560 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001561 if( rc!=SQLITE_OK ){
1562 goto multi_select_end;
1563 }
1564 sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
drh8cdbf832004-08-29 16:25:03 +00001565 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1566 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab1, 0);
danielk197784ac9d02004-05-18 09:58:06 +00001567 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001568
1569 /* Code the SELECTs to our left into temporary table "tab1".
1570 */
danielk197784ac9d02004-05-18 09:58:06 +00001571 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
1572 if( rc ){
1573 goto multi_select_end;
1574 }
drhd8bc7082000-06-07 23:51:50 +00001575
1576 /* Code the current SELECT into temporary table "tab2"
1577 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001578 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0);
drh8cdbf832004-08-29 16:25:03 +00001579 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001580 if( rc!=SQLITE_OK ){
1581 goto multi_select_end;
1582 }
1583 sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh8cdbf832004-08-29 16:25:03 +00001584 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1585 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab2, 0);
drh82c3d632000-06-06 21:56:07 +00001586 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001587 nLimit = p->nLimit;
1588 p->nLimit = -1;
1589 nOffset = p->nOffset;
1590 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001591 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001592 p->pPrior = pPrior;
drh7b58dae2003-07-20 01:16:46 +00001593 p->nLimit = nLimit;
1594 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001595 if( rc ){
1596 goto multi_select_end;
1597 }
drhd8bc7082000-06-07 23:51:50 +00001598
1599 /* Generate code to take the intersection of the two temporary
1600 ** tables.
1601 */
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, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001609 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001610 iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
1611 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001612 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001613 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001614 iCont, iBreak, 0);
1615 if( rc ){
1616 rc = 1;
1617 goto multi_select_end;
1618 }
danielk19774adee202004-05-08 08:23:19 +00001619 sqlite3VdbeResolveLabel(v, iCont);
1620 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1621 sqlite3VdbeResolveLabel(v, iBreak);
1622 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1623 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001624 break;
1625 }
1626 }
drh8cdbf832004-08-29 16:25:03 +00001627
1628 /* Make sure all SELECTs in the statement have the same number of elements
1629 ** in their result sets.
1630 */
drh82c3d632000-06-06 21:56:07 +00001631 assert( p->pEList && pPrior->pEList );
1632 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001633 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001634 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001635 rc = 1;
1636 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001637 }
danielk197784ac9d02004-05-18 09:58:06 +00001638
drh8cdbf832004-08-29 16:25:03 +00001639 /* Set the number of columns in temporary tables
1640 */
1641 nCol = p->pEList->nExpr;
1642 while( nAddr>0 ){
1643 nAddr--;
1644 sqlite3VdbeChangeP2(v, aAddr[nAddr], nCol);
1645 }
1646
drhfbc4ee72004-08-29 01:31:05 +00001647 /* Compute collating sequences used by either the ORDER BY clause or
1648 ** by any temporary tables needed to implement the compound select.
1649 ** Attach the KeyInfo structure to all temporary tables. Invoke the
1650 ** ORDER BY processing if there is an ORDER BY clause.
drh8cdbf832004-08-29 16:25:03 +00001651 **
1652 ** This section is run by the right-most SELECT statement only.
1653 ** SELECT statements to the left always skip this part. The right-most
1654 ** SELECT might also skip this part if it has no ORDER BY clause and
1655 ** no temp tables are required.
drhfbc4ee72004-08-29 01:31:05 +00001656 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001657 if( p->pOrderBy || (pOpenTemp && pOpenTemp->nId>0) ){
drhfbc4ee72004-08-29 01:31:05 +00001658 int i; /* Loop counter */
1659 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
1660
drh8cdbf832004-08-29 16:25:03 +00001661 assert( p->ppOpenTemp == &pOpenTemp );
drhfbc4ee72004-08-29 01:31:05 +00001662 pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*sizeof(CollSeq*));
danielk1977dc1bdc42004-06-11 10:51:27 +00001663 if( !pKeyInfo ){
1664 rc = SQLITE_NOMEM;
1665 goto multi_select_end;
1666 }
1667
1668 pKeyInfo->enc = pParse->db->enc;
1669 pKeyInfo->nField = nCol;
1670
1671 for(i=0; i<nCol; i++){
1672 pKeyInfo->aColl[i] = multiSelectCollSeq(pParse, p, i);
1673 if( !pKeyInfo->aColl[i] ){
1674 pKeyInfo->aColl[i] = pParse->db->pDfltColl;
1675 }
1676 }
1677
1678 for(i=0; pOpenTemp && i<pOpenTemp->nId; i++){
1679 int p3type = (i==0?P3_KEYINFO_HANDOFF:P3_KEYINFO);
1680 int addr = pOpenTemp->a[i].idx;
1681 sqlite3VdbeChangeP3(v, addr, (char *)pKeyInfo, p3type);
1682 }
1683
1684 if( p->pOrderBy ){
drhfbc4ee72004-08-29 01:31:05 +00001685 struct ExprList_item *pOrderByTerm = p->pOrderBy->a;
1686 for(i=0; i<p->pOrderBy->nExpr; i++, pOrderByTerm++){
1687 Expr *pExpr = pOrderByTerm->pExpr;
1688 char *zName = pOrderByTerm->zName;
danielk1977dc1bdc42004-06-11 10:51:27 +00001689 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
1690 assert( !pExpr->pColl );
1691 if( zName ){
1692 pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1);
1693 }else{
1694 pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn];
1695 }
1696 }
1697 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1698 }
1699
1700 if( !pOpenTemp ){
1701 /* This happens for UNION ALL ... ORDER BY */
1702 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001703 }
1704 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001705
1706multi_select_end:
1707 if( pOpenTemp ){
1708 sqlite3IdListDelete(pOpenTemp);
1709 }
1710 p->ppOpenTemp = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001711 return rc;
drh22827922000-06-06 17:27:05 +00001712}
drhb7f91642004-10-31 02:22:47 +00001713#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drh22827922000-06-06 17:27:05 +00001714
drhb7f91642004-10-31 02:22:47 +00001715#ifndef SQLITE_OMIT_VIEW
drh22827922000-06-06 17:27:05 +00001716/*
drh832508b2002-03-02 17:04:07 +00001717** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001718** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001719** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001720** unchanged.)
drh832508b2002-03-02 17:04:07 +00001721**
1722** This routine is part of the flattening procedure. A subquery
1723** whose result set is defined by pEList appears as entry in the
1724** FROM clause of a SELECT such that the VDBE cursor assigned to that
1725** FORM clause entry is iTable. This routine make the necessary
1726** changes to pExpr so that it refers directly to the source table
1727** of the subquery rather the result set of the subquery.
1728*/
drh6a3ea0e2003-05-02 14:32:12 +00001729static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1730static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001731 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001732 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1733 if( pExpr->iColumn<0 ){
1734 pExpr->op = TK_NULL;
1735 }else{
1736 Expr *pNew;
1737 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1738 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1739 pNew = pEList->a[pExpr->iColumn].pExpr;
1740 assert( pNew!=0 );
1741 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001742 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001743 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001744 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001745 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001746 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001747 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001748 pExpr->iTable = pNew->iTable;
1749 pExpr->iColumn = pNew->iColumn;
1750 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001751 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1752 sqlite3TokenCopy(&pExpr->span, &pNew->span);
drh50350a12004-02-13 16:22:22 +00001753 }
drh832508b2002-03-02 17:04:07 +00001754 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001755 substExpr(pExpr->pLeft, iTable, pEList);
1756 substExpr(pExpr->pRight, iTable, pEList);
1757 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001758 }
1759}
1760static void
drh6a3ea0e2003-05-02 14:32:12 +00001761substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001762 int i;
1763 if( pList==0 ) return;
1764 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001765 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001766 }
1767}
drhb7f91642004-10-31 02:22:47 +00001768#endif /* !defined(SQLITE_OMIT_VIEW) */
drh832508b2002-03-02 17:04:07 +00001769
drhb7f91642004-10-31 02:22:47 +00001770#ifndef SQLITE_OMIT_VIEW
drh832508b2002-03-02 17:04:07 +00001771/*
drh1350b032002-02-27 19:00:20 +00001772** This routine attempts to flatten subqueries in order to speed
1773** execution. It returns 1 if it makes changes and 0 if no flattening
1774** occurs.
1775**
1776** To understand the concept of flattening, consider the following
1777** query:
1778**
1779** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1780**
1781** The default way of implementing this query is to execute the
1782** subquery first and store the results in a temporary table, then
1783** run the outer query on that temporary table. This requires two
1784** passes over the data. Furthermore, because the temporary table
1785** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001786** optimized.
drh1350b032002-02-27 19:00:20 +00001787**
drh832508b2002-03-02 17:04:07 +00001788** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001789** a single flat select, like this:
1790**
1791** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1792**
1793** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001794** but only has to scan the data once. And because indices might
1795** exist on the table t1, a complete scan of the data might be
1796** avoided.
drh1350b032002-02-27 19:00:20 +00001797**
drh832508b2002-03-02 17:04:07 +00001798** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001799**
drh832508b2002-03-02 17:04:07 +00001800** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001801**
drh832508b2002-03-02 17:04:07 +00001802** (2) The subquery is not an aggregate or the outer query is not a join.
1803**
drh8af4d3a2003-05-06 20:35:16 +00001804** (3) The subquery is not the right operand of a left outer join, or
1805** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001806**
1807** (4) The subquery is not DISTINCT or the outer query is not a join.
1808**
1809** (5) The subquery is not DISTINCT or the outer query does not use
1810** aggregates.
1811**
1812** (6) The subquery does not use aggregates or the outer query is not
1813** DISTINCT.
1814**
drh08192d52002-04-30 19:20:28 +00001815** (7) The subquery has a FROM clause.
1816**
drhdf199a22002-06-14 22:38:41 +00001817** (8) The subquery does not use LIMIT or the outer query is not a join.
1818**
1819** (9) The subquery does not use LIMIT or the outer query does not use
1820** aggregates.
1821**
1822** (10) The subquery does not use aggregates or the outer query does not
1823** use LIMIT.
1824**
drh174b6192002-12-03 02:22:52 +00001825** (11) The subquery and the outer query do not both have ORDER BY clauses.
1826**
drh3fc673e2003-06-16 00:40:34 +00001827** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1828** subquery has no WHERE clause. (added by ticket #350)
1829**
drh832508b2002-03-02 17:04:07 +00001830** In this routine, the "p" parameter is a pointer to the outer query.
1831** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1832** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1833**
drh665de472003-03-31 13:36:09 +00001834** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001835** If flattening is attempted this routine returns 1.
1836**
1837** All of the expression analysis must occur on both the outer query and
1838** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001839*/
drh8c74a8c2002-08-25 19:20:40 +00001840static int flattenSubquery(
1841 Parse *pParse, /* The parsing context */
1842 Select *p, /* The parent or outer SELECT statement */
1843 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1844 int isAgg, /* True if outer SELECT uses aggregate functions */
1845 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1846){
drh0bb28102002-05-08 11:54:14 +00001847 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001848 SrcList *pSrc; /* The FROM clause of the outer query */
1849 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001850 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001851 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh91bb0ee2004-09-01 03:06:34 +00001852 int i; /* Loop counter */
1853 Expr *pWhere; /* The WHERE clause */
1854 struct SrcList_item *pSubitem; /* The subquery */
drh1350b032002-02-27 19:00:20 +00001855
drh832508b2002-03-02 17:04:07 +00001856 /* Check to see if flattening is permitted. Return 0 if not.
1857 */
1858 if( p==0 ) return 0;
1859 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001860 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh91bb0ee2004-09-01 03:06:34 +00001861 pSubitem = &pSrc->a[iFrom];
1862 pSub = pSubitem->pSelect;
drh832508b2002-03-02 17:04:07 +00001863 assert( pSub!=0 );
1864 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001865 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001866 pSubSrc = pSub->pSrc;
1867 assert( pSubSrc );
drhc31c2eb2003-05-02 16:04:17 +00001868 if( pSubSrc->nSrc==0 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001869 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1870 return 0;
1871 }
drhd11d3822002-06-21 23:01:49 +00001872 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001873 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001874
drh8af4d3a2003-05-06 20:35:16 +00001875 /* Restriction 3: If the subquery is a join, make sure the subquery is
1876 ** not used as the right operand of an outer join. Examples of why this
1877 ** is not allowed:
1878 **
1879 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1880 **
1881 ** If we flatten the above, we would get
1882 **
1883 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1884 **
1885 ** which is not at all the same thing.
1886 */
1887 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1888 return 0;
1889 }
1890
drh3fc673e2003-06-16 00:40:34 +00001891 /* Restriction 12: If the subquery is the right operand of a left outer
1892 ** join, make sure the subquery has no WHERE clause.
1893 ** An examples of why this is not allowed:
1894 **
1895 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1896 **
1897 ** If we flatten the above, we would get
1898 **
1899 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1900 **
1901 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1902 ** effectively converts the OUTER JOIN into an INNER JOIN.
1903 */
1904 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1905 && pSub->pWhere!=0 ){
1906 return 0;
1907 }
1908
drh0bb28102002-05-08 11:54:14 +00001909 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001910 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001911 */
drhc31c2eb2003-05-02 16:04:17 +00001912
1913 /* Move all of the FROM elements of the subquery into the
1914 ** the FROM clause of the outer query. Before doing this, remember
1915 ** the cursor number for the original outer query FROM element in
1916 ** iParent. The iParent cursor will never be used. Subsequent code
1917 ** will scan expressions looking for iParent references and replace
1918 ** those references with expressions that resolve to the subquery FROM
1919 ** elements we are now copying in.
1920 */
drh91bb0ee2004-09-01 03:06:34 +00001921 iParent = pSubitem->iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001922 {
1923 int nSubSrc = pSubSrc->nSrc;
drh91bb0ee2004-09-01 03:06:34 +00001924 int jointype = pSubitem->jointype;
1925 Table *pTab = pSubitem->pTab;
drhc31c2eb2003-05-02 16:04:17 +00001926
drh91bb0ee2004-09-01 03:06:34 +00001927 if( pTab && pTab->isTransient ){
1928 sqlite3DeleteTable(0, pSubitem->pTab);
drhc31c2eb2003-05-02 16:04:17 +00001929 }
drh91bb0ee2004-09-01 03:06:34 +00001930 sqliteFree(pSubitem->zDatabase);
1931 sqliteFree(pSubitem->zName);
1932 sqliteFree(pSubitem->zAlias);
drhc31c2eb2003-05-02 16:04:17 +00001933 if( nSubSrc>1 ){
1934 int extra = nSubSrc - 1;
1935 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00001936 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00001937 }
1938 p->pSrc = pSrc;
1939 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1940 pSrc->a[i] = pSrc->a[i-extra];
1941 }
1942 }
1943 for(i=0; i<nSubSrc; i++){
1944 pSrc->a[i+iFrom] = pSubSrc->a[i];
1945 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1946 }
drh8af4d3a2003-05-06 20:35:16 +00001947 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00001948 }
1949
1950 /* Now begin substituting subquery result set expressions for
1951 ** references to the iParent in the outer query.
1952 **
1953 ** Example:
1954 **
1955 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1956 ** \ \_____________ subquery __________/ /
1957 ** \_____________________ outer query ______________________________/
1958 **
1959 ** We look at every expression in the outer query and every place we see
1960 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1961 */
drh6a3ea0e2003-05-02 14:32:12 +00001962 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001963 pList = p->pEList;
1964 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001965 Expr *pExpr;
1966 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1967 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001968 }
1969 }
drh1b2e0322002-03-03 02:49:51 +00001970 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00001971 substExprList(p->pGroupBy, iParent, pSub->pEList);
1972 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001973 }
drh174b6192002-12-03 02:22:52 +00001974 if( pSub->pOrderBy ){
1975 assert( p->pOrderBy==0 );
1976 p->pOrderBy = pSub->pOrderBy;
1977 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00001978 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00001979 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00001980 }
drh832508b2002-03-02 17:04:07 +00001981 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001982 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00001983 }else{
1984 pWhere = 0;
1985 }
1986 if( subqueryIsAgg ){
1987 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001988 p->pHaving = p->pWhere;
1989 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00001990 substExpr(p->pHaving, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00001991 p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
drh1b2e0322002-03-03 02:49:51 +00001992 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00001993 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00001994 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001995 substExpr(p->pWhere, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00001996 p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
drh832508b2002-03-02 17:04:07 +00001997 }
drhc31c2eb2003-05-02 16:04:17 +00001998
1999 /* The flattened query is distinct if either the inner or the
2000 ** outer query is distinct.
2001 */
drh832508b2002-03-02 17:04:07 +00002002 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00002003
drhc31c2eb2003-05-02 16:04:17 +00002004 /* Transfer the limit expression from the subquery to the outer
2005 ** query.
2006 */
drhdf199a22002-06-14 22:38:41 +00002007 if( pSub->nLimit>=0 ){
2008 if( p->nLimit<0 ){
2009 p->nLimit = pSub->nLimit;
2010 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
2011 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
2012 }
2013 }
2014 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00002015
drhc31c2eb2003-05-02 16:04:17 +00002016 /* Finially, delete what is left of the subquery and return
2017 ** success.
2018 */
danielk19774adee202004-05-08 08:23:19 +00002019 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00002020 return 1;
2021}
drhb7f91642004-10-31 02:22:47 +00002022#endif /* SQLITE_OMIT_VIEW */
drh1350b032002-02-27 19:00:20 +00002023
2024/*
drh9562b552002-02-19 15:00:07 +00002025** Analyze the SELECT statement passed in as an argument to see if it
2026** is a simple min() or max() query. If it is and this query can be
2027** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00002028** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00002029** simple min() or max() query, then return 0;
2030**
2031** A simply min() or max() query looks like this:
2032**
2033** SELECT min(a) FROM table;
2034** SELECT max(a) FROM table;
2035**
2036** The query may have only a single table in its FROM argument. There
2037** can be no GROUP BY or HAVING or WHERE clauses. The result set must
2038** be the min() or max() of a single column of the table. The column
2039** in the min() or max() function must be indexed.
2040**
danielk19774adee202004-05-08 08:23:19 +00002041** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00002042** See the header comment on that routine for additional information.
2043*/
2044static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2045 Expr *pExpr;
2046 int iCol;
2047 Table *pTab;
2048 Index *pIdx;
2049 int base;
2050 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00002051 int seekOp;
2052 int cont;
drh6e175292004-03-13 14:00:36 +00002053 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00002054 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00002055 SrcList *pSrc;
2056
drh9562b552002-02-19 15:00:07 +00002057
2058 /* Check to see if this query is a simple min() or max() query. Return
2059 ** zero if it is not.
2060 */
2061 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00002062 pSrc = p->pSrc;
2063 if( pSrc->nSrc!=1 ) return 0;
2064 pEList = p->pEList;
2065 if( pEList->nExpr!=1 ) return 0;
2066 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002067 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002068 pList = pExpr->pList;
2069 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002070 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00002071 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002072 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00002073 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002074 seekOp = OP_Last;
2075 }else{
2076 return 0;
2077 }
drh6e175292004-03-13 14:00:36 +00002078 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002079 if( pExpr->op!=TK_COLUMN ) return 0;
2080 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002081 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002082
2083 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002084 ** Check to make sure we have an index and make pIdx point to the
2085 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2086 ** key column, no index is necessary so set pIdx to NULL. If no
2087 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002088 */
2089 if( iCol<0 ){
2090 pIdx = 0;
2091 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002092 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002093 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2094 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002095 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002096 }
2097 if( pIdx==0 ) return 0;
2098 }
2099
drhe5f50722003-07-19 00:44:14 +00002100 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002101 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002102 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002103 */
danielk19774adee202004-05-08 08:23:19 +00002104 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002105 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002106
drh0c37e632004-01-30 02:01:03 +00002107 /* If the output is destined for a temporary table, open that table.
2108 */
2109 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002110 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002111 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002112 }
2113
drh17f71932002-02-21 12:01:27 +00002114 /* Generating code to find the min or the max. Basically all we have
2115 ** to do is find the first or the last entry in the chosen index. If
2116 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2117 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002118 */
danielk19774adee202004-05-08 08:23:19 +00002119 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00002120 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00002121 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00002122 if( pSrc->a[0].pSelect==0 ){
drhad6d9462004-09-19 02:15:24 +00002123 sqlite3OpenTableForReading(v, base, pTab);
drh6e175292004-03-13 14:00:36 +00002124 }
danielk19774adee202004-05-08 08:23:19 +00002125 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00002126 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002127 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002128 }else{
danielk19774adee202004-05-08 08:23:19 +00002129 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00002130 sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum,
2131 (char*)&pIdx->keyInfo, P3_KEYINFO);
drh9eb516c2004-07-18 20:52:32 +00002132 if( seekOp==OP_Rewind ){
drh1af3fdb2004-07-18 21:33:01 +00002133 sqlite3VdbeAddOp(v, OP_String, 0, 0);
2134 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2135 seekOp = OP_MoveGt;
drh9eb516c2004-07-18 20:52:32 +00002136 }
drh1af3fdb2004-07-18 21:33:01 +00002137 sqlite3VdbeAddOp(v, seekOp, base+1, 0);
danielk19774adee202004-05-08 08:23:19 +00002138 sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
2139 sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002140 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002141 }
drh5cf8e8c2002-02-19 22:42:05 +00002142 eList.nExpr = 1;
2143 memset(&eListItem, 0, sizeof(eListItem));
2144 eList.a = &eListItem;
2145 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00002146 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00002147 sqlite3VdbeResolveLabel(v, cont);
2148 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002149
drh9562b552002-02-19 15:00:07 +00002150 return 1;
2151}
2152
2153/*
drh290c1942004-08-21 17:54:45 +00002154** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
2155** the number of errors seen.
2156**
2157** An ORDER BY or GROUP BY is a list of expressions. If any expression
2158** is an integer constant, then that expression is replaced by the
2159** corresponding entry in the result set.
2160*/
2161static int processOrderGroupBy(
2162 Parse *pParse, /* Parsing context */
2163 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
2164 SrcList *pTabList, /* The FROM clause */
2165 ExprList *pEList, /* The result set */
2166 int isAgg, /* True if aggregate functions are involved */
2167 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
2168){
2169 int i;
2170 if( pOrderBy==0 ) return 0;
2171 for(i=0; i<pOrderBy->nExpr; i++){
2172 int iCol;
2173 Expr *pE = pOrderBy->a[i].pExpr;
2174 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2175 sqlite3ExprDelete(pE);
2176 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2177 }
2178 if( sqlite3ExprResolveAndCheck(pParse, pTabList, pEList, pE, isAgg, 0) ){
2179 return 1;
2180 }
2181 if( sqlite3ExprIsConstant(pE) ){
2182 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2183 sqlite3ErrorMsg(pParse,
2184 "%s BY terms must not be non-integer constants", zType);
2185 return 1;
2186 }else if( iCol<=0 || iCol>pEList->nExpr ){
2187 sqlite3ErrorMsg(pParse,
2188 "%s BY column number %d out of range - should be "
2189 "between 1 and %d", zType, iCol, pEList->nExpr);
2190 return 1;
2191 }
2192 }
2193 }
2194 return 0;
2195}
2196
2197/*
drh9bb61fe2000-06-05 16:01:39 +00002198** Generate code for the given SELECT statement.
2199**
drhfef52082000-06-06 01:50:43 +00002200** The results are distributed in various ways depending on the
2201** value of eDest and iParm.
2202**
2203** eDest Value Result
2204** ------------ -------------------------------------------
2205** SRT_Callback Invoke the callback for each row of the result.
2206**
2207** SRT_Mem Store first result in memory cell iParm
2208**
danielk1977e014a832004-05-17 10:48:57 +00002209** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002210**
drh82c3d632000-06-06 21:56:07 +00002211** SRT_Union Store results as a key in a temporary table iParm
2212**
jplyon4b11c6d2004-01-19 04:57:53 +00002213** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002214**
2215** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002216**
drhe78e8282003-01-19 03:59:45 +00002217** The table above is incomplete. Additional eDist value have be added
2218** since this comment was written. See the selectInnerLoop() function for
2219** a complete listing of the allowed values of eDest and their meanings.
2220**
drh9bb61fe2000-06-05 16:01:39 +00002221** This routine returns the number of errors. If any errors are
2222** encountered, then an appropriate error message is left in
2223** pParse->zErrMsg.
2224**
2225** This routine does NOT free the Select structure passed in. The
2226** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002227**
2228** The pParent, parentTab, and *pParentAgg fields are filled in if this
2229** SELECT is a subquery. This routine may try to combine this SELECT
2230** with its parent to form a single flat query. In so doing, it might
2231** change the parent query from a non-aggregate to an aggregate query.
2232** For that reason, the pParentAgg flag is passed as a pointer, so it
2233** can be changed.
drhe78e8282003-01-19 03:59:45 +00002234**
2235** Example 1: The meaning of the pParent parameter.
2236**
2237** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2238** \ \_______ subquery _______/ /
2239** \ /
2240** \____________________ outer query ___________________/
2241**
2242** This routine is called for the outer query first. For that call,
2243** pParent will be NULL. During the processing of the outer query, this
2244** routine is called recursively to handle the subquery. For the recursive
2245** call, pParent will point to the outer query. Because the subquery is
2246** the second element in a three-way join, the parentTab parameter will
2247** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002248*/
danielk19774adee202004-05-08 08:23:19 +00002249int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002250 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002251 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002252 int eDest, /* How to dispose of the results */
2253 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002254 Select *pParent, /* Another SELECT for which this is a sub-query */
2255 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002256 int *pParentAgg, /* True if pParent uses aggregate functions */
2257 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002258){
drhd8bc7082000-06-07 23:51:50 +00002259 int i;
drhcce7d172000-05-31 15:34:51 +00002260 WhereInfo *pWInfo;
2261 Vdbe *v;
2262 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002263 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002264 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002265 Expr *pWhere; /* The WHERE clause. May be NULL */
2266 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002267 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2268 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002269 int isDistinct; /* True if the DISTINCT keyword is present */
2270 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002271 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00002272
danielk19776f8a5032004-05-10 10:34:51 +00002273 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002274 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002275
drhb7f91642004-10-31 02:22:47 +00002276#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +00002277 /* If there is are a sequence of queries, do the earlier ones first.
2278 */
2279 if( p->pPrior ){
drhb6c29892004-11-22 19:12:19 +00002280#ifndef SQLITE_OMIT_CURSOR
2281 if( p->pFetch ){
2282 sqlite3ErrorMsg(pParse, "cursors cannot be used on compound queries");
2283 goto select_end;
2284 }
2285#endif
danielk197784ac9d02004-05-18 09:58:06 +00002286 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002287 }
drhb7f91642004-10-31 02:22:47 +00002288#endif
drh82c3d632000-06-06 21:56:07 +00002289
2290 /* Make local copies of the parameters for this query.
2291 */
drh9bb61fe2000-06-05 16:01:39 +00002292 pTabList = p->pSrc;
2293 pWhere = p->pWhere;
2294 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00002295 pGroupBy = p->pGroupBy;
2296 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00002297 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00002298
drh6a3ea0e2003-05-02 14:32:12 +00002299 /* Allocate VDBE cursors for each table in the FROM clause
drh10e5e3c2000-06-08 00:19:02 +00002300 */
danielk19774adee202004-05-08 08:23:19 +00002301 sqlite3SrcListAssignCursors(pParse, pTabList);
drh10e5e3c2000-06-08 00:19:02 +00002302
drh9bb61fe2000-06-05 16:01:39 +00002303 /*
2304 ** Do not even attempt to generate any code if we have already seen
2305 ** errors before this routine starts.
2306 */
drh1d83f052002-02-17 00:30:36 +00002307 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002308
drhe78e8282003-01-19 03:59:45 +00002309 /* Expand any "*" terms in the result set. (For example the "*" in
2310 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
2311 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00002312 */
drhd8bc7082000-06-07 23:51:50 +00002313 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00002314 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002315 }
drhad2d8302002-05-24 20:31:36 +00002316 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00002317 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00002318 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002319
drh22827922000-06-06 17:27:05 +00002320 /* If writing to memory or generating a set
2321 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002322 */
drhfef52082000-06-06 01:50:43 +00002323 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002324 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002325 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002326 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002327 }
2328
drhc926afb2002-06-20 03:38:26 +00002329 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002330 */
drhc926afb2002-06-20 03:38:26 +00002331 switch( eDest ){
2332 case SRT_Union:
2333 case SRT_Except:
2334 case SRT_Discard:
2335 pOrderBy = 0;
2336 break;
2337 default:
2338 break;
drh22827922000-06-06 17:27:05 +00002339 }
2340
drh10e5e3c2000-06-08 00:19:02 +00002341 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002342 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002343 **
drh967e8b72000-06-21 13:59:10 +00002344 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002345 */
drh4794b982000-06-06 13:54:14 +00002346 for(i=0; i<pEList->nExpr; i++){
drh290c1942004-08-21 17:54:45 +00002347 if( sqlite3ExprResolveAndCheck(pParse, pTabList, 0, pEList->a[i].pExpr,
2348 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002349 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002350 }
2351 }
drh290c1942004-08-21 17:54:45 +00002352 if( sqlite3ExprResolveAndCheck(pParse, pTabList, pEList, pWhere, 0, 0) ){
2353 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002354 }
drhc66c5a22002-12-03 02:34:49 +00002355 if( pHaving ){
2356 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002357 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
drhc66c5a22002-12-03 02:34:49 +00002358 goto select_end;
2359 }
drh290c1942004-08-21 17:54:45 +00002360 if( sqlite3ExprResolveAndCheck(pParse, pTabList, pEList,pHaving,1,&isAgg) ){
drhc66c5a22002-12-03 02:34:49 +00002361 goto select_end;
2362 }
2363 }
drh290c1942004-08-21 17:54:45 +00002364 if( processOrderGroupBy(pParse, pOrderBy, pTabList, pEList, isAgg, "ORDER")
2365 || processOrderGroupBy(pParse, pGroupBy, pTabList, pEList, isAgg, "GROUP")
2366 ){
2367 goto select_end;
drh22827922000-06-06 17:27:05 +00002368 }
drhcce7d172000-05-31 15:34:51 +00002369
drhb6c29892004-11-22 19:12:19 +00002370 /* We cannot use a SQL cursor on a join or on a DISTINCT query
2371 */
2372#ifndef SQLITE_OMIT_CURSOR
2373 if( p->pFetch ){
2374 if( p->isDistinct ){
2375 sqlite3ErrorMsg(pParse, "cursors cannot be used on DISTINCT queries");
2376 goto select_end;
2377 }
2378 if( pTabList->nSrc>0 ){
2379 sqlite3ErrorMsg(pParse, "cursors cannot be used on joins");
2380 goto select_end;
2381 }
2382 if( pTabList->a[0].pSelect ){
2383 sqlite3ErrorMsg(pParse, "cursor cannot be used with nested queries "
2384 "or views");
2385 goto select_end;
2386 }
2387 }
2388#endif
2389
drhd820cb12002-02-18 03:21:45 +00002390 /* Begin generating code.
2391 */
danielk19774adee202004-05-08 08:23:19 +00002392 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002393 if( v==0 ) goto select_end;
2394
drhe78e8282003-01-19 03:59:45 +00002395 /* Identify column names if we will be using them in a callback. This
2396 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002397 */
2398 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002399 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002400 }
2401
drhd820cb12002-02-18 03:21:45 +00002402 /* Generate code for all sub-queries in the FROM clause
2403 */
drhad3cab52002-05-24 02:04:32 +00002404 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002405 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002406 int needRestoreContext;
2407
drha76b5df2002-02-23 02:32:10 +00002408 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002409 if( pTabList->a[i].zName!=0 ){
2410 zSavedAuthContext = pParse->zAuthContext;
2411 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002412 needRestoreContext = 1;
2413 }else{
2414 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002415 }
danielk19774adee202004-05-08 08:23:19 +00002416 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
danielk197784ac9d02004-05-18 09:58:06 +00002417 pTabList->a[i].iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002418 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002419 pParse->zAuthContext = zSavedAuthContext;
2420 }
drh1b2e0322002-03-03 02:49:51 +00002421 pTabList = p->pSrc;
2422 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002423 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002424 pOrderBy = p->pOrderBy;
2425 }
drh1b2e0322002-03-03 02:49:51 +00002426 pGroupBy = p->pGroupBy;
2427 pHaving = p->pHaving;
2428 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002429 }
2430
drh6e175292004-03-13 14:00:36 +00002431 /* Check for the special case of a min() or max() function by itself
2432 ** in the result set.
2433 */
2434 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2435 rc = 0;
2436 goto select_end;
2437 }
2438
drh832508b2002-03-02 17:04:07 +00002439 /* Check to see if this is a subquery that can be "flattened" into its parent.
2440 ** If flattening is a possiblity, do so and return immediately.
2441 */
drhb7f91642004-10-31 02:22:47 +00002442#ifndef SQLITE_OMIT_VIEW
drh1b2e0322002-03-03 02:49:51 +00002443 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002444 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002445 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002446 return rc;
2447 }
drhb7f91642004-10-31 02:22:47 +00002448#endif
drh832508b2002-03-02 17:04:07 +00002449
danielk19777cedc8d2004-06-10 10:50:08 +00002450 /* If there is an ORDER BY clause, resolve any collation sequences
2451 ** names that have been explicitly specified.
2452 */
2453 if( pOrderBy ){
2454 for(i=0; i<pOrderBy->nExpr; i++){
2455 if( pOrderBy->a[i].zName ){
2456 pOrderBy->a[i].pExpr->pColl =
2457 sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1);
2458 }
2459 }
2460 if( pParse->nErr ){
2461 goto select_end;
2462 }
2463 }
2464
drh7b58dae2003-07-20 01:16:46 +00002465 /* Set the limiter.
2466 */
2467 computeLimitRegisters(pParse, p);
2468
drh2d0794e2002-03-03 03:03:52 +00002469 /* If the output is destined for a temporary table, open that table.
2470 */
2471 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002472 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002473 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002474 }
2475
drh22827922000-06-06 17:27:05 +00002476 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002477 */
drhd820cb12002-02-18 03:21:45 +00002478 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002479 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002480 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002481 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002482 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002483 if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002484 goto select_end;
drh22827922000-06-06 17:27:05 +00002485 }
2486 }
2487 if( pGroupBy ){
2488 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002489 if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002490 goto select_end;
drh22827922000-06-06 17:27:05 +00002491 }
2492 }
2493 }
danielk19774adee202004-05-08 08:23:19 +00002494 if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002495 goto select_end;
drh22827922000-06-06 17:27:05 +00002496 }
drh191b6902000-06-08 11:13:01 +00002497 if( pOrderBy ){
2498 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002499 if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002500 goto select_end;
drh191b6902000-06-08 11:13:01 +00002501 }
2502 }
2503 }
drhefb72512000-05-31 20:00:52 +00002504 }
2505
drh22827922000-06-06 17:27:05 +00002506 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002507 */
2508 if( isAgg ){
danielk1977e159fdf2004-06-21 10:45:06 +00002509 int addr = sqlite3VdbeAddOp(v, OP_AggReset, (pGroupBy?0:1), pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002510 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002511 FuncDef *pFunc;
2512 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drhf9b596e2004-05-26 16:54:42 +00002513 sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_FUNCDEF);
drhe5095352002-02-24 03:25:14 +00002514 }
2515 }
danielk1977e159fdf2004-06-21 10:45:06 +00002516 if( pGroupBy ){
danielk1977ce2663c2004-06-11 13:19:21 +00002517 int sz = sizeof(KeyInfo) + pGroupBy->nExpr*sizeof(CollSeq*);
2518 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(sz);
2519 if( 0==pKey ){
2520 goto select_end;
2521 }
2522 pKey->enc = pParse->db->enc;
2523 pKey->nField = pGroupBy->nExpr;
2524 for(i=0; i<pGroupBy->nExpr; i++){
2525 pKey->aColl[i] = sqlite3ExprCollSeq(pParse, pGroupBy->a[i].pExpr);
2526 if( !pKey->aColl[i] ){
2527 pKey->aColl[i] = pParse->db->pDfltColl;
2528 }
2529 }
2530 sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF);
drh1bee3d72001-10-15 00:44:35 +00002531 }
drhcce7d172000-05-31 15:34:51 +00002532 }
2533
drh19a775c2000-06-05 18:54:46 +00002534 /* Initialize the memory cell to NULL
2535 */
drhfef52082000-06-06 01:50:43 +00002536 if( eDest==SRT_Mem ){
danielk19770f69c1e2004-05-29 11:24:50 +00002537 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00002538 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002539 }
2540
drh832508b2002-03-02 17:04:07 +00002541 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002542 */
drh19a775c2000-06-05 18:54:46 +00002543 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002544 distinct = pParse->nTab++;
drhd3d39e92004-05-20 22:16:29 +00002545 openTempIndex(pParse, p, distinct, 0);
drh832508b2002-03-02 17:04:07 +00002546 }else{
2547 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002548 }
drh832508b2002-03-02 17:04:07 +00002549
2550 /* Begin the database scan
2551 */
drhe6f85e72004-12-25 01:03:13 +00002552 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,
drhe4e72072004-11-23 01:47:30 +00002553 pGroupBy ? 0 : &pOrderBy, p->pFetch);
drh1d83f052002-02-17 00:30:36 +00002554 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002555
drh22827922000-06-06 17:27:05 +00002556 /* Use the standard inner loop if we are not dealing with
2557 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002558 */
drhda9d6c42000-05-31 18:20:14 +00002559 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002560 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002561 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002562 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002563 }
drhcce7d172000-05-31 15:34:51 +00002564 }
drhefb72512000-05-31 20:00:52 +00002565
drhe3184742002-06-19 14:27:05 +00002566 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002567 ** processing.
drhefb72512000-05-31 20:00:52 +00002568 */
drh22827922000-06-06 17:27:05 +00002569 else{
drh268380c2004-02-25 13:47:31 +00002570 AggExpr *pAgg;
drh22827922000-06-06 17:27:05 +00002571 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002572 int lbl1;
drh22827922000-06-06 17:27:05 +00002573 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002574 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
drh22827922000-06-06 17:27:05 +00002575 }
danielk1977ededfd52004-06-17 07:53:01 +00002576 /* No affinity string is attached to the following OP_MakeRecord
drhd3d39e92004-05-20 22:16:29 +00002577 ** because we do not need to do any coercion of datatypes. */
danielk1977ededfd52004-06-17 07:53:01 +00002578 sqlite3VdbeAddOp(v, OP_MakeRecord, pGroupBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +00002579 lbl1 = sqlite3VdbeMakeLabel(v);
2580 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh268380c2004-02-25 13:47:31 +00002581 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2582 if( pAgg->isAgg ) continue;
danielk19774adee202004-05-08 08:23:19 +00002583 sqlite3ExprCode(pParse, pAgg->pExpr);
2584 sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002585 }
danielk19774adee202004-05-08 08:23:19 +00002586 sqlite3VdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002587 }
drh268380c2004-02-25 13:47:31 +00002588 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002589 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002590 int nExpr;
2591 FuncDef *pDef;
2592 if( !pAgg->isAgg ) continue;
2593 assert( pAgg->pFunc!=0 );
2594 assert( pAgg->pFunc->xStep!=0 );
2595 pDef = pAgg->pFunc;
2596 pE = pAgg->pExpr;
2597 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002598 assert( pE->op==TK_AGG_FUNCTION );
drhf9b596e2004-05-26 16:54:42 +00002599 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
danielk19774adee202004-05-08 08:23:19 +00002600 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
danielk1977dc1bdc42004-06-11 10:51:27 +00002601 if( pDef->needCollSeq ){
2602 CollSeq *pColl = 0;
2603 int j;
2604 for(j=0; !pColl && j<nExpr; j++){
2605 pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr);
2606 }
2607 if( !pColl ) pColl = pParse->db->pDfltColl;
2608 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2609 }
danielk19774adee202004-05-08 08:23:19 +00002610 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002611 }
drhcce7d172000-05-31 15:34:51 +00002612 }
2613
2614 /* End the database scan loop.
2615 */
danielk19774adee202004-05-08 08:23:19 +00002616 sqlite3WhereEnd(pWInfo);
drhcce7d172000-05-31 15:34:51 +00002617
drh22827922000-06-06 17:27:05 +00002618 /* If we are processing aggregates, we need to set up a second loop
2619 ** over all of the aggregate values and process them.
2620 */
2621 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002622 int endagg = sqlite3VdbeMakeLabel(v);
drh22827922000-06-06 17:27:05 +00002623 int startagg;
danielk19774adee202004-05-08 08:23:19 +00002624 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002625 pParse->useAgg = 1;
2626 if( pHaving ){
danielk19774adee202004-05-08 08:23:19 +00002627 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002628 }
drhdf199a22002-06-14 22:38:41 +00002629 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002630 iParm, startagg, endagg, aff) ){
drh1d83f052002-02-17 00:30:36 +00002631 goto select_end;
drh22827922000-06-06 17:27:05 +00002632 }
danielk19774adee202004-05-08 08:23:19 +00002633 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2634 sqlite3VdbeResolveLabel(v, endagg);
2635 sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002636 pParse->useAgg = 0;
2637 }
2638
drhcce7d172000-05-31 15:34:51 +00002639 /* If there is an ORDER BY clause, then we need to sort the results
2640 ** and send them to the callback one by one.
2641 */
2642 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00002643 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002644 }
drh6a535342001-10-19 16:44:56 +00002645
drhf620b4e2004-02-09 14:37:50 +00002646 /* If this was a subquery, we have now converted the subquery into a
2647 ** temporary table. So delete the subquery structure from the parent
2648 ** to prevent this subquery from being evaluated again and to force the
2649 ** the use of the temporary table.
2650 */
2651 if( pParent ){
2652 assert( pParent->pSrc->nSrc>parentTab );
2653 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00002654 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00002655 pParent->pSrc->a[parentTab].pSelect = 0;
2656 }
2657
drh1d83f052002-02-17 00:30:36 +00002658 /* The SELECT was successfully coded. Set the return code to 0
2659 ** to indicate no errors.
2660 */
2661 rc = 0;
2662
2663 /* Control jumps to here if an error is encountered above, or upon
2664 ** successful coding of the SELECT.
2665 */
2666select_end:
2667 sqliteAggregateInfoReset(pParse);
2668 return rc;
drhcce7d172000-05-31 15:34:51 +00002669}