blob: eb2892f24348098ece8bbfc446cb6fa744b61989 [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**
drh001bbcb2003-03-19 03:14:00 +000015** $Id: select.c,v 1.127 2003/03/19 03:14:02 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*/
drh9bb61fe2000-06-05 16:01:39 +000024Select *sqliteSelectNew(
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 */
33 int nOffset /* OFFSET value. -1 means not used */
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 ){
38 sqliteExprListDelete(pEList);
drhad3cab52002-05-24 02:04:32 +000039 sqliteSrcListDelete(pSrc);
drhdaffd0e2001-04-11 14:28:42 +000040 sqliteExprDelete(pWhere);
41 sqliteExprListDelete(pGroupBy);
42 sqliteExprDelete(pHaving);
43 sqliteExprListDelete(pOrderBy);
44 }else{
45 pNew->pEList = pEList;
46 pNew->pSrc = pSrc;
47 pNew->pWhere = pWhere;
48 pNew->pGroupBy = pGroupBy;
49 pNew->pHaving = pHaving;
50 pNew->pOrderBy = pOrderBy;
51 pNew->isDistinct = isDistinct;
52 pNew->op = TK_SELECT;
drh9bbca4c2001-11-06 04:00:18 +000053 pNew->nLimit = nLimit;
54 pNew->nOffset = nOffset;
drhdaffd0e2001-04-11 14:28:42 +000055 }
drh9bb61fe2000-06-05 16:01:39 +000056 return pNew;
57}
58
59/*
drh01f3f252002-05-24 16:14:15 +000060** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
61** type of join. Return an integer constant that expresses that type
62** in terms of the following bit values:
63**
64** JT_INNER
65** JT_OUTER
66** JT_NATURAL
67** JT_LEFT
68** JT_RIGHT
69**
70** A full outer join is the combination of JT_LEFT and JT_RIGHT.
71**
72** If an illegal or unsupported join type is seen, then still return
73** a join type, but put an error in the pParse structure.
74*/
75int sqliteJoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
76 int jointype = 0;
77 Token *apAll[3];
78 Token *p;
79 static struct {
80 const char *zKeyword;
81 int nChar;
82 int code;
83 } keywords[] = {
84 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000085 { "left", 4, JT_LEFT|JT_OUTER },
86 { "right", 5, JT_RIGHT|JT_OUTER },
87 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +000088 { "outer", 5, JT_OUTER },
89 { "inner", 5, JT_INNER },
90 { "cross", 5, JT_INNER },
91 };
92 int i, j;
93 apAll[0] = pA;
94 apAll[1] = pB;
95 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +000096 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +000097 p = apAll[i];
98 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
99 if( p->n==keywords[j].nChar
100 && sqliteStrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
101 jointype |= keywords[j].code;
102 break;
103 }
104 }
105 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
106 jointype |= JT_ERROR;
107 break;
108 }
109 }
drhad2d8302002-05-24 20:31:36 +0000110 if(
111 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000112 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000113 ){
drh01f3f252002-05-24 16:14:15 +0000114 static Token dummy = { 0, 0 };
115 char *zSp1 = " ", *zSp2 = " ";
116 if( pB==0 ){ pB = &dummy; zSp1 = 0; }
117 if( pC==0 ){ pC = &dummy; zSp2 = 0; }
118 sqliteSetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
119 pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
120 pParse->nErr++;
121 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000122 }else if( jointype & JT_RIGHT ){
123 sqliteSetString(&pParse->zErrMsg,
124 "RIGHT and FULL OUTER JOINs are not currently supported", 0);
125 pParse->nErr++;
126 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000127 }
128 return jointype;
129}
130
131/*
drhad2d8302002-05-24 20:31:36 +0000132** Return the index of a column in a table. Return -1 if the column
133** is not contained in the table.
134*/
135static int columnIndex(Table *pTab, const char *zCol){
136 int i;
137 for(i=0; i<pTab->nCol; i++){
138 if( sqliteStrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
139 }
140 return -1;
141}
142
143/*
144** Add a term to the WHERE expression in *ppExpr that requires the
145** zCol column to be equal in the two tables pTab1 and pTab2.
146*/
147static void addWhereTerm(
148 const char *zCol, /* Name of the column */
149 const Table *pTab1, /* First table */
150 const Table *pTab2, /* Second table */
151 Expr **ppExpr /* Add the equality term to this expression */
152){
153 Token dummy;
154 Expr *pE1a, *pE1b, *pE1c;
155 Expr *pE2a, *pE2b, *pE2c;
156 Expr *pE;
157
158 dummy.z = zCol;
159 dummy.n = strlen(zCol);
drh4b59ab52002-08-24 18:24:51 +0000160 dummy.dyn = 0;
drhad2d8302002-05-24 20:31:36 +0000161 pE1a = sqliteExpr(TK_ID, 0, 0, &dummy);
162 pE2a = sqliteExpr(TK_ID, 0, 0, &dummy);
163 dummy.z = pTab1->zName;
164 dummy.n = strlen(dummy.z);
165 pE1b = sqliteExpr(TK_ID, 0, 0, &dummy);
166 dummy.z = pTab2->zName;
167 dummy.n = strlen(dummy.z);
168 pE2b = sqliteExpr(TK_ID, 0, 0, &dummy);
169 pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0);
170 pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0);
171 pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000172 ExprSetProperty(pE, EP_FromJoin);
drhad2d8302002-05-24 20:31:36 +0000173 if( *ppExpr ){
174 *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0);
175 }else{
176 *ppExpr = pE;
177 }
178}
179
180/*
drh1f162302002-10-27 19:35:33 +0000181** Set the EP_FromJoin property on all terms of the given expression.
drh1cc093c2002-06-24 22:01:57 +0000182**
drhe78e8282003-01-19 03:59:45 +0000183** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000184** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000185** join restriction specified in the ON or USING clause and not a part
186** of the more general WHERE clause. These terms are moved over to the
187** WHERE clause during join processing but we need to remember that they
188** originated in the ON or USING clause.
drh1cc093c2002-06-24 22:01:57 +0000189*/
190static void setJoinExpr(Expr *p){
191 while( p ){
drh1f162302002-10-27 19:35:33 +0000192 ExprSetProperty(p, EP_FromJoin);
drh1cc093c2002-06-24 22:01:57 +0000193 setJoinExpr(p->pLeft);
194 p = p->pRight;
195 }
196}
197
198/*
drhad2d8302002-05-24 20:31:36 +0000199** This routine processes the join information for a SELECT statement.
200** ON and USING clauses are converted into extra terms of the WHERE clause.
201** NATURAL joins also create extra WHERE clause terms.
202**
203** This routine returns the number of errors encountered.
204*/
205static int sqliteProcessJoin(Parse *pParse, Select *p){
206 SrcList *pSrc;
207 int i, j;
208 pSrc = p->pSrc;
209 for(i=0; i<pSrc->nSrc-1; i++){
210 struct SrcList_item *pTerm = &pSrc->a[i];
211 struct SrcList_item *pOther = &pSrc->a[i+1];
212
213 if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
214
215 /* When the NATURAL keyword is present, add WHERE clause terms for
216 ** every column that the two tables have in common.
217 */
218 if( pTerm->jointype & JT_NATURAL ){
219 Table *pTab;
220 if( pTerm->pOn || pTerm->pUsing ){
221 sqliteSetString(&pParse->zErrMsg, "a NATURAL join may not have "
222 "an ON or USING clause", 0);
223 pParse->nErr++;
224 return 1;
225 }
226 pTab = pTerm->pTab;
227 for(j=0; j<pTab->nCol; j++){
228 if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
229 addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
230 }
231 }
232 }
233
234 /* Disallow both ON and USING clauses in the same join
235 */
236 if( pTerm->pOn && pTerm->pUsing ){
237 sqliteSetString(&pParse->zErrMsg, "cannot have both ON and USING "
238 "clauses in the same join", 0);
239 pParse->nErr++;
240 return 1;
241 }
242
243 /* Add the ON clause to the end of the WHERE clause, connected by
244 ** and AND operator.
245 */
246 if( pTerm->pOn ){
drh1cc093c2002-06-24 22:01:57 +0000247 setJoinExpr(pTerm->pOn);
drhad2d8302002-05-24 20:31:36 +0000248 if( p->pWhere==0 ){
249 p->pWhere = pTerm->pOn;
250 }else{
251 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0);
252 }
253 pTerm->pOn = 0;
254 }
255
256 /* Create extra terms on the WHERE clause for each column named
257 ** in the USING clause. Example: If the two tables to be joined are
258 ** A and B and the USING clause names X, Y, and Z, then add this
259 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
260 ** Report an error if any column mentioned in the USING clause is
261 ** not contained in both tables to be joined.
262 */
263 if( pTerm->pUsing ){
264 IdList *pList;
265 int j;
266 assert( i<pSrc->nSrc-1 );
267 pList = pTerm->pUsing;
268 for(j=0; j<pList->nId; j++){
drhbf5cd972002-06-24 12:20:23 +0000269 if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
270 columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
drhad2d8302002-05-24 20:31:36 +0000271 sqliteSetString(&pParse->zErrMsg, "cannot join using column ",
drhbf5cd972002-06-24 12:20:23 +0000272 pList->a[j].zName, " - column not present in both tables", 0);
drhad2d8302002-05-24 20:31:36 +0000273 pParse->nErr++;
274 return 1;
275 }
drhbf5cd972002-06-24 12:20:23 +0000276 addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000277 }
278 }
279 }
280 return 0;
281}
282
283/*
drh1f162302002-10-27 19:35:33 +0000284** This routine implements a minimal Oracle8 join syntax immulation.
285** The precise oracle8 syntax is not implemented - it is easy enough
286** to get this routine confused. But this routine does make it possible
287** to write a single SQL statement that does a left outer join in both
288** oracle8 and in SQLite.
289**
290** This routine looks for TK_COLUMN expression nodes that are marked
291** with the EP_Oracle8Join property. Such nodes are generated by a
292** column name (either "column" or "table.column") that is followed by
293** the special "(+)" operator. If the table of the column marked with
294** the (+) operator is the second are subsequent table in a join, then
295** that table becomes the left table in a LEFT OUTER JOIN. The expression
296** that uses that table becomes part of the ON clause for the join.
297**
298** It is important to enphasize that this is not exactly how oracle8
299** works. But it is close enough so that one can construct queries that
300** will work correctly for both SQLite and Oracle8.
301*/
302static int sqliteOracle8JoinFixup(
303 int base, /* VDBE cursor number for first table in pSrc */
304 SrcList *pSrc, /* List of tables being joined */
305 Expr *pWhere /* The WHERE clause of the SELECT statement */
306){
307 int rc = 0;
308 if( ExprHasProperty(pWhere, EP_Oracle8Join) && pWhere->op==TK_COLUMN ){
309 int idx = pWhere->iTable - base;
310 assert( idx>=0 && idx<pSrc->nSrc );
311 if( idx>0 ){
312 pSrc->a[idx-1].jointype &= ~JT_INNER;
313 pSrc->a[idx-1].jointype |= JT_OUTER|JT_LEFT;
314 return 1;
315 }
316 }
317 if( pWhere->pRight ){
318 rc = sqliteOracle8JoinFixup(base, pSrc, pWhere->pRight);
319 }
320 if( pWhere->pLeft ){
321 rc |= sqliteOracle8JoinFixup(base, pSrc, pWhere->pLeft);
322 }
323 if( pWhere->pList ){
324 int i;
325 ExprList *pList = pWhere->pList;
326 for(i=0; i<pList->nExpr && rc==0; i++){
327 rc |= sqliteOracle8JoinFixup(base, pSrc, pList->a[i].pExpr);
328 }
329 }
330 if( rc==1 && (pWhere->op==TK_AND || pWhere->op==TK_EQ) ){
331 setJoinExpr(pWhere);
332 rc = 0;
333 }
334 return rc;
335}
336
337/*
drh9bb61fe2000-06-05 16:01:39 +0000338** Delete the given Select structure and all of its substructures.
339*/
340void sqliteSelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000341 if( p==0 ) return;
drh9bb61fe2000-06-05 16:01:39 +0000342 sqliteExprListDelete(p->pEList);
drhad3cab52002-05-24 02:04:32 +0000343 sqliteSrcListDelete(p->pSrc);
drh9bb61fe2000-06-05 16:01:39 +0000344 sqliteExprDelete(p->pWhere);
345 sqliteExprListDelete(p->pGroupBy);
346 sqliteExprDelete(p->pHaving);
347 sqliteExprListDelete(p->pOrderBy);
drh82c3d632000-06-06 21:56:07 +0000348 sqliteSelectDelete(p->pPrior);
drha76b5df2002-02-23 02:32:10 +0000349 sqliteFree(p->zSelect);
drh9bb61fe2000-06-05 16:01:39 +0000350 sqliteFree(p);
351}
352
353/*
drh22827922000-06-06 17:27:05 +0000354** Delete the aggregate information from the parse structure.
355*/
drh1d83f052002-02-17 00:30:36 +0000356static void sqliteAggregateInfoReset(Parse *pParse){
drh22827922000-06-06 17:27:05 +0000357 sqliteFree(pParse->aAgg);
358 pParse->aAgg = 0;
359 pParse->nAgg = 0;
drh22827922000-06-06 17:27:05 +0000360 pParse->useAgg = 0;
361}
362
363/*
drhc926afb2002-06-20 03:38:26 +0000364** Insert code into "v" that will push the record on the top of the
365** stack into the sorter.
366*/
367static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
368 char *zSortOrder;
369 int i;
370 zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
371 if( zSortOrder==0 ) return;
372 for(i=0; i<pOrderBy->nExpr; i++){
drh38640e12002-07-05 21:42:36 +0000373 int order = pOrderBy->a[i].sortOrder;
374 int type;
375 int c;
376 if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
377 type = SQLITE_SO_TEXT;
378 }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
379 type = SQLITE_SO_NUM;
drh491791a2002-07-18 00:34:09 +0000380 }else if( pParse->db->file_format>=4 ){
drh38640e12002-07-05 21:42:36 +0000381 type = sqliteExprType(pOrderBy->a[i].pExpr);
382 }else{
383 type = SQLITE_SO_NUM;
384 }
385 if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
386 c = type==SQLITE_SO_TEXT ? 'A' : '+';
387 }else{
388 c = type==SQLITE_SO_TEXT ? 'D' : '-';
389 }
390 zSortOrder[i] = c;
drhc926afb2002-06-20 03:38:26 +0000391 sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
392 }
393 zSortOrder[pOrderBy->nExpr] = 0;
394 sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0);
395 sqliteVdbeChangeP3(v, -1, zSortOrder, strlen(zSortOrder));
396 sqliteFree(zSortOrder);
397 sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
398}
399
400/*
drh38640e12002-07-05 21:42:36 +0000401** This routine adds a P3 argument to the last VDBE opcode that was
402** inserted. The P3 argument added is a string suitable for the
403** OP_MakeKey or OP_MakeIdxKey opcodes. The string consists of
404** characters 't' or 'n' depending on whether or not the various
405** fields of the key to be generated should be treated as numeric
406** or as text. See the OP_MakeKey and OP_MakeIdxKey opcode
407** documentation for additional information about the P3 string.
408** See also the sqliteAddIdxKeyType() routine.
409*/
410void sqliteAddKeyType(Vdbe *v, ExprList *pEList){
411 int nColumn = pEList->nExpr;
412 char *zType = sqliteMalloc( nColumn+1 );
413 int i;
414 if( zType==0 ) return;
415 for(i=0; i<nColumn; i++){
416 zType[i] = sqliteExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
417 }
418 zType[i] = 0;
419 sqliteVdbeChangeP3(v, -1, zType, nColumn);
420 sqliteFree(zType);
421}
422
423/*
drh22827922000-06-06 17:27:05 +0000424** This routine generates the code for the inside of the inner loop
425** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000426**
drh38640e12002-07-05 21:42:36 +0000427** If srcTab and nColumn are both zero, then the pEList expressions
428** are evaluated in order to get the data for this row. If nColumn>0
429** then data is pulled from srcTab and pEList is used only to get the
430** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000431*/
432static int selectInnerLoop(
433 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000434 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000435 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000436 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000437 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000438 ExprList *pOrderBy, /* If not NULL, sort results using this key */
439 int distinct, /* If >=0, make sure results are distinct */
440 int eDest, /* How to dispose of the results */
441 int iParm, /* An argument to the disposal method */
442 int iContinue, /* Jump here to continue with next row */
443 int iBreak /* Jump here to break out of the inner loop */
444){
445 Vdbe *v = pParse->pVdbe;
446 int i;
drh38640e12002-07-05 21:42:36 +0000447
drhdaffd0e2001-04-11 14:28:42 +0000448 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000449 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000450
drhdf199a22002-06-14 22:38:41 +0000451 /* If there was a LIMIT clause on the SELECT statement, then do the check
452 ** to see if this row should be output.
453 */
454 if( pOrderBy==0 ){
455 if( p->nOffset>0 ){
drhd11d3822002-06-21 23:01:49 +0000456 int addr = sqliteVdbeCurrentAddr(v);
457 sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+2);
458 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
drhdf199a22002-06-14 22:38:41 +0000459 }
drhd11d3822002-06-21 23:01:49 +0000460 if( p->nLimit>=0 ){
461 sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, iBreak);
drhdf199a22002-06-14 22:38:41 +0000462 }
463 }
464
drh967e8b72000-06-21 13:59:10 +0000465 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000466 */
drh38640e12002-07-05 21:42:36 +0000467 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000468 for(i=0; i<nColumn; i++){
drh99fcd712001-10-13 01:06:47 +0000469 sqliteVdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000470 }
drh38640e12002-07-05 21:42:36 +0000471 }else{
472 nColumn = pEList->nExpr;
473 for(i=0; i<pEList->nExpr; i++){
474 sqliteExprCode(pParse, pEList->a[i].pExpr);
475 }
drh22827922000-06-06 17:27:05 +0000476 }
477
drhdaffd0e2001-04-11 14:28:42 +0000478 /* If the DISTINCT keyword was present on the SELECT statement
479 ** and this row has been seen before, then do not make this row
480 ** part of the result.
drh22827922000-06-06 17:27:05 +0000481 */
drhf5905aa2002-05-26 20:54:33 +0000482 if( distinct>=0 && pEList && pEList->nExpr>0 ){
drh0bd1f4e2002-06-06 18:54:39 +0000483#if NULL_ALWAYS_DISTINCT
484 sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7);
485#endif
drh99fcd712001-10-13 01:06:47 +0000486 sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
drh491791a2002-07-18 00:34:09 +0000487 if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pEList);
drhf5905aa2002-05-26 20:54:33 +0000488 sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
drh99fcd712001-10-13 01:06:47 +0000489 sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
490 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
drh99fcd712001-10-13 01:06:47 +0000491 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh6b125452002-01-28 15:53:03 +0000492 sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
drh22827922000-06-06 17:27:05 +0000493 }
drh82c3d632000-06-06 21:56:07 +0000494
drhc926afb2002-06-20 03:38:26 +0000495 switch( eDest ){
496 /* In this mode, write each query result to the key of the temporary
497 ** table iParm.
498 */
499 case SRT_Union: {
500 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
501 sqliteVdbeAddOp(v, OP_String, 0, 0);
502 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
503 break;
drh22827922000-06-06 17:27:05 +0000504 }
drh22827922000-06-06 17:27:05 +0000505
drhc926afb2002-06-20 03:38:26 +0000506 /* Store the result as data using a unique key.
507 */
508 case SRT_Table:
509 case SRT_TempTable: {
510 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
511 if( pOrderBy ){
512 pushOntoSorter(pParse, v, pOrderBy);
513 }else{
514 sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
515 sqliteVdbeAddOp(v, OP_Pull, 1, 0);
516 sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
517 }
518 break;
519 }
drh82c3d632000-06-06 21:56:07 +0000520
drhc926afb2002-06-20 03:38:26 +0000521 /* Construct a record from the query result, but instead of
522 ** saving that record, use it as a key to delete elements from
523 ** the temporary table iParm.
524 */
525 case SRT_Except: {
526 int addr;
527 addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
528 sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
529 sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
530 break;
531 }
drh5974a302000-06-07 14:42:26 +0000532
drhc926afb2002-06-20 03:38:26 +0000533 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
534 ** then there should be a single item on the stack. Write this
535 ** item into the set table with bogus data.
536 */
537 case SRT_Set: {
drha9f9d1c2002-06-29 02:20:08 +0000538 int lbl = sqliteVdbeMakeLabel(v);
drhc926afb2002-06-20 03:38:26 +0000539 assert( nColumn==1 );
drha9f9d1c2002-06-29 02:20:08 +0000540 sqliteVdbeAddOp(v, OP_IsNull, -1, lbl);
drhc926afb2002-06-20 03:38:26 +0000541 if( pOrderBy ){
542 pushOntoSorter(pParse, v, pOrderBy);
543 }else{
drha9f9d1c2002-06-29 02:20:08 +0000544 sqliteVdbeAddOp(v, OP_String, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000545 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
546 }
drha9f9d1c2002-06-29 02:20:08 +0000547 sqliteVdbeResolveLabel(v, lbl);
drhc926afb2002-06-20 03:38:26 +0000548 break;
549 }
drh22827922000-06-06 17:27:05 +0000550
drhc926afb2002-06-20 03:38:26 +0000551 /* If this is a scalar select that is part of an expression, then
552 ** store the results in the appropriate memory cell and break out
553 ** of the scan loop.
554 */
555 case SRT_Mem: {
556 assert( nColumn==1 );
557 if( pOrderBy ){
558 pushOntoSorter(pParse, v, pOrderBy);
559 }else{
560 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
561 sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
562 }
563 break;
564 }
drh22827922000-06-06 17:27:05 +0000565
drhf46f9052002-06-22 02:33:38 +0000566 /* Send the data to the callback function.
567 */
568 case SRT_Callback:
569 case SRT_Sorter: {
570 if( pOrderBy ){
571 sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
572 pushOntoSorter(pParse, v, pOrderBy);
573 }else{
574 assert( eDest==SRT_Callback );
575 sqliteVdbeAddOp(v, OP_Callback, nColumn, 0);
576 }
577 break;
578 }
579
drh142e30d2002-08-28 03:00:58 +0000580 /* Invoke a subroutine to handle the results. The subroutine itself
581 ** is responsible for popping the results off of the stack.
582 */
583 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000584 if( pOrderBy ){
585 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
586 pushOntoSorter(pParse, v, pOrderBy);
587 }else{
588 sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
589 }
drh142e30d2002-08-28 03:00:58 +0000590 break;
591 }
592
drhc926afb2002-06-20 03:38:26 +0000593 /* Discard the results. This is used for SELECT statements inside
594 ** the body of a TRIGGER. The purpose of such selects is to call
595 ** user-defined functions that have side effects. We do not care
596 ** about the actual results of the select.
597 */
drhc926afb2002-06-20 03:38:26 +0000598 default: {
drhf46f9052002-06-22 02:33:38 +0000599 assert( eDest==SRT_Discard );
600 sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000601 break;
602 }
drh82c3d632000-06-06 21:56:07 +0000603 }
604 return 0;
605}
606
607/*
drhd8bc7082000-06-07 23:51:50 +0000608** If the inner loop was generated using a non-null pOrderBy argument,
609** then the results were placed in a sorter. After the loop is terminated
610** we need to run the sorter and output the results. The following
611** routine generates the code needed to do that.
612*/
drhc926afb2002-06-20 03:38:26 +0000613static void generateSortTail(
614 Select *p, /* The SELECT statement */
615 Vdbe *v, /* Generate code into this VDBE */
616 int nColumn, /* Number of columns of data */
617 int eDest, /* Write the sorted results here */
618 int iParm /* Optional parameter associated with eDest */
619){
drhd8bc7082000-06-07 23:51:50 +0000620 int end = sqliteVdbeMakeLabel(v);
621 int addr;
drhf46f9052002-06-22 02:33:38 +0000622 if( eDest==SRT_Sorter ) return;
drh99fcd712001-10-13 01:06:47 +0000623 sqliteVdbeAddOp(v, OP_Sort, 0, 0);
624 addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end);
drhdf199a22002-06-14 22:38:41 +0000625 if( p->nOffset>0 ){
drhd11d3822002-06-21 23:01:49 +0000626 sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+4);
627 sqliteVdbeAddOp(v, OP_Pop, 1, 0);
628 sqliteVdbeAddOp(v, OP_Goto, 0, addr);
drhdf199a22002-06-14 22:38:41 +0000629 }
drhd11d3822002-06-21 23:01:49 +0000630 if( p->nLimit>=0 ){
631 sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, end);
drhdf199a22002-06-14 22:38:41 +0000632 }
drhc926afb2002-06-20 03:38:26 +0000633 switch( eDest ){
634 case SRT_Callback: {
635 sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0);
636 break;
637 }
638 case SRT_Table:
639 case SRT_TempTable: {
640 sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
641 sqliteVdbeAddOp(v, OP_Pull, 1, 0);
642 sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
643 break;
644 }
645 case SRT_Set: {
646 assert( nColumn==1 );
647 sqliteVdbeAddOp(v, OP_IsNull, -1, sqliteVdbeCurrentAddr(v)+3);
648 sqliteVdbeAddOp(v, OP_String, 0, 0);
649 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
650 break;
651 }
652 case SRT_Mem: {
653 assert( nColumn==1 );
654 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
655 sqliteVdbeAddOp(v, OP_Goto, 0, end);
656 break;
657 }
drhac82fcf2002-09-08 17:23:41 +0000658 case SRT_Subroutine: {
659 int i;
660 for(i=0; i<nColumn; i++){
661 sqliteVdbeAddOp(v, OP_Column, -1-i, i);
662 }
663 sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
664 sqliteVdbeAddOp(v, OP_Pop, 1, 0);
665 break;
666 }
drhc926afb2002-06-20 03:38:26 +0000667 default: {
drhf46f9052002-06-22 02:33:38 +0000668 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000669 break;
670 }
671 }
drh99fcd712001-10-13 01:06:47 +0000672 sqliteVdbeAddOp(v, OP_Goto, 0, addr);
673 sqliteVdbeResolveLabel(v, end);
drha8b38d22001-11-01 14:41:34 +0000674 sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000675}
676
677/*
drhfcb78a42003-01-18 20:11:05 +0000678** Generate code that will tell the VDBE the datatypes of
679** columns in the result set.
drhe78e8282003-01-19 03:59:45 +0000680**
681** This routine only generates code if the "PRAGMA show_datatypes=on"
682** has been executed. The datatypes are reported out in the azCol
683** parameter to the callback function. The first N azCol[] entries
684** are the names of the columns, and the second N entries are the
685** datatypes for the columns.
686**
687** The "datatype" for a result that is a column of a type is the
688** datatype definition extracted from the CREATE TABLE statement.
689** The datatype for an expression is either TEXT or NUMERIC. The
690** datatype for a ROWID field is INTEGER.
drhfcb78a42003-01-18 20:11:05 +0000691*/
692static void generateColumnTypes(
693 Parse *pParse, /* Parser context */
694 int base, /* VDBE cursor corresponding to first entry in pTabList */
695 SrcList *pTabList, /* List of tables */
696 ExprList *pEList /* Expressions defining the result set */
697){
698 Vdbe *v = pParse->pVdbe;
699 int i;
drh326dce72003-01-29 14:06:07 +0000700 if( pParse->useCallback && (pParse->db->flags & SQLITE_ReportTypes)==0 ){
701 return;
702 }
drhfcb78a42003-01-18 20:11:05 +0000703 for(i=0; i<pEList->nExpr; i++){
704 Expr *p = pEList->a[i].pExpr;
705 char *zType = 0;
706 if( p==0 ) continue;
707 if( p->op==TK_COLUMN && pTabList ){
708 Table *pTab = pTabList->a[p->iTable - base].pTab;
709 int iCol = p->iColumn;
710 if( iCol<0 ) iCol = pTab->iPKey;
711 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
712 if( iCol<0 ){
713 zType = "INTEGER";
714 }else{
715 zType = pTab->aCol[iCol].zType;
716 }
717 }else{
718 if( sqliteExprType(p)==SQLITE_SO_TEXT ){
719 zType = "TEXT";
720 }else{
721 zType = "NUMERIC";
722 }
723 }
724 sqliteVdbeAddOp(v, OP_ColumnName, i + pEList->nExpr, 0);
725 sqliteVdbeChangeP3(v, -1, zType, P3_STATIC);
726 }
727}
728
729/*
730** Generate code that will tell the VDBE the names of columns
731** in the result set. This information is used to provide the
732** azCol[] vaolues in the callback.
drh82c3d632000-06-06 21:56:07 +0000733*/
drh832508b2002-03-02 17:04:07 +0000734static void generateColumnNames(
735 Parse *pParse, /* Parser context */
736 int base, /* VDBE cursor corresponding to first entry in pTabList */
drhad3cab52002-05-24 02:04:32 +0000737 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000738 ExprList *pEList /* Expressions defining the result set */
739){
drhd8bc7082000-06-07 23:51:50 +0000740 Vdbe *v = pParse->pVdbe;
drh82c3d632000-06-06 21:56:07 +0000741 int i;
drhdaffd0e2001-04-11 14:28:42 +0000742 if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000743 pParse->colNamesSet = 1;
drh82c3d632000-06-06 21:56:07 +0000744 for(i=0; i<pEList->nExpr; i++){
745 Expr *p;
drhb1363202002-06-26 02:45:03 +0000746 char *zType = 0;
drh1bee3d72001-10-15 00:44:35 +0000747 int showFullNames;
drh5a387052003-01-11 14:19:51 +0000748 p = pEList->a[i].pExpr;
749 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000750 if( pEList->a[i].zName ){
751 char *zName = pEList->a[i].zName;
drh99fcd712001-10-13 01:06:47 +0000752 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
753 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000754 continue;
755 }
drh1bee3d72001-10-15 00:44:35 +0000756 showFullNames = (pParse->db->flags & SQLITE_FullColNames)!=0;
drhfa173a72002-07-10 21:26:00 +0000757 if( p->op==TK_COLUMN && pTabList ){
drh832508b2002-03-02 17:04:07 +0000758 Table *pTab = pTabList->a[p->iTable - base].pTab;
drh97665872002-02-13 23:22:53 +0000759 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000760 int iCol = p->iColumn;
761 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000762 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000763 if( iCol<0 ){
764 zCol = "_ROWID_";
765 zType = "INTEGER";
766 }else{
767 zCol = pTab->aCol[iCol].zName;
768 zType = pTab->aCol[iCol].zType;
769 }
drh6977fea2002-10-22 23:38:04 +0000770 if( p->span.z && p->span.z[0] && !showFullNames ){
drhfa173a72002-07-10 21:26:00 +0000771 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
drh6977fea2002-10-22 23:38:04 +0000772 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
drhfa173a72002-07-10 21:26:00 +0000773 sqliteVdbeCompressSpace(v, addr);
774 }else if( pTabList->nSrc>1 || showFullNames ){
drh82c3d632000-06-06 21:56:07 +0000775 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000776 char *zTab;
777
drh832508b2002-03-02 17:04:07 +0000778 zTab = pTabList->a[p->iTable - base].zAlias;
drh01a34662001-10-20 12:30:10 +0000779 if( showFullNames || zTab==0 ) zTab = pTab->zName;
drh97665872002-02-13 23:22:53 +0000780 sqliteSetString(&zName, zTab, ".", zCol, 0);
drh99fcd712001-10-13 01:06:47 +0000781 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
782 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000783 sqliteFree(zName);
784 }else{
drh99fcd712001-10-13 01:06:47 +0000785 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
drh22f70c32002-02-18 01:17:00 +0000786 sqliteVdbeChangeP3(v, -1, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000787 }
drh6977fea2002-10-22 23:38:04 +0000788 }else if( p->span.z && p->span.z[0] ){
drhfa173a72002-07-10 21:26:00 +0000789 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
drh6977fea2002-10-22 23:38:04 +0000790 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
drh1bee3d72001-10-15 00:44:35 +0000791 sqliteVdbeCompressSpace(v, addr);
792 }else{
793 char zName[30];
794 assert( p->op!=TK_COLUMN || pTabList==0 );
795 sprintf(zName, "column%d", i+1);
796 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
797 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000798 }
799 }
800}
801
802/*
drhd8bc7082000-06-07 23:51:50 +0000803** Name of the connection operator, used for error messages.
804*/
805static const char *selectOpName(int id){
806 char *z;
807 switch( id ){
808 case TK_ALL: z = "UNION ALL"; break;
809 case TK_INTERSECT: z = "INTERSECT"; break;
810 case TK_EXCEPT: z = "EXCEPT"; break;
811 default: z = "UNION"; break;
812 }
813 return z;
814}
815
816/*
drh315555c2002-10-20 15:53:03 +0000817** Forward declaration
818*/
819static int fillInColumnList(Parse*, Select*);
820
821/*
drh22f70c32002-02-18 01:17:00 +0000822** Given a SELECT statement, generate a Table structure that describes
823** the result set of that SELECT.
824*/
825Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
826 Table *pTab;
827 int i;
828 ExprList *pEList;
drh22f70c32002-02-18 01:17:00 +0000829
830 if( fillInColumnList(pParse, pSelect) ){
831 return 0;
832 }
833 pTab = sqliteMalloc( sizeof(Table) );
834 if( pTab==0 ){
835 return 0;
836 }
837 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
838 pEList = pSelect->pEList;
839 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000840 assert( pTab->nCol>0 );
drh22f70c32002-02-18 01:17:00 +0000841 pTab->aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
842 for(i=0; i<pTab->nCol; i++){
843 Expr *p;
844 if( pEList->a[i].zName ){
845 pTab->aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
drh6977fea2002-10-22 23:38:04 +0000846 }else if( (p=pEList->a[i].pExpr)->span.z && p->span.z[0] ){
847 sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drhd820cb12002-02-18 03:21:45 +0000848 }else if( p->op==TK_DOT && p->pRight && p->pRight->token.z &&
849 p->pRight->token.z[0] ){
850 sqliteSetNString(&pTab->aCol[i].zName,
851 p->pRight->token.z, p->pRight->token.n, 0);
drh22f70c32002-02-18 01:17:00 +0000852 }else{
853 char zBuf[30];
854 sprintf(zBuf, "column%d", i+1);
855 pTab->aCol[i].zName = sqliteStrDup(zBuf);
856 }
857 }
858 pTab->iPKey = -1;
859 return pTab;
860}
861
862/*
drhad2d8302002-05-24 20:31:36 +0000863** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000864**
drhad3cab52002-05-24 02:04:32 +0000865** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh22f70c32002-02-18 01:17:00 +0000866** defines the set of tables that should be scanned.
drhd8bc7082000-06-07 23:51:50 +0000867**
drhad2d8302002-05-24 20:31:36 +0000868** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
869** on joins and the ON and USING clause of joins.
870**
871** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000872** for instances of the "*" operator or the TABLE.* operator.
873** If found, expand each "*" to be every column in every table
874** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000875**
876** Return 0 on success. If there are problems, leave an error message
877** in pParse and return non-zero.
878*/
879static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000880 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000881 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000882 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000883 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000884
885 if( p==0 || p->pSrc==0 ) return 1;
886 pTabList = p->pSrc;
887 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000888
889 /* Look up every table in the table list.
890 */
drhad3cab52002-05-24 02:04:32 +0000891 for(i=0; i<pTabList->nSrc; i++){
drhd8bc7082000-06-07 23:51:50 +0000892 if( pTabList->a[i].pTab ){
893 /* This routine has run before! No need to continue */
894 return 0;
895 }
drhdaffd0e2001-04-11 14:28:42 +0000896 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000897 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000898 assert( pTabList->a[i].pSelect!=0 );
drhad2d8302002-05-24 20:31:36 +0000899 if( pTabList->a[i].zAlias==0 ){
900 char zFakeName[60];
901 sprintf(zFakeName, "sqlite_subquery_%p_",
902 (void*)pTabList->a[i].pSelect);
903 sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
904 }
drh22f70c32002-02-18 01:17:00 +0000905 pTabList->a[i].pTab = pTab =
906 sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
907 pTabList->a[i].pSelect);
908 if( pTab==0 ){
909 return 1;
910 }
911 pTab->isTransient = 1;
912 }else{
drha76b5df2002-02-23 02:32:10 +0000913 /* An ordinary table or view name in the FROM clause */
914 pTabList->a[i].pTab = pTab =
915 sqliteFindTable(pParse->db, pTabList->a[i].zName);
916 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000917 sqliteSetString(&pParse->zErrMsg, "no such table: ",
918 pTabList->a[i].zName, 0);
919 pParse->nErr++;
920 return 1;
921 }
drha76b5df2002-02-23 02:32:10 +0000922 if( pTab->pSelect ){
drh417be792002-03-03 18:59:40 +0000923 if( sqliteViewGetColumnNames(pParse, pTab) ){
924 return 1;
925 }
drhd94a6692002-08-25 18:29:11 +0000926 sqliteSelectDelete(pTabList->a[i].pSelect);
drhff78bd22002-02-27 01:47:11 +0000927 pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
drha76b5df2002-02-23 02:32:10 +0000928 }
drhd8bc7082000-06-07 23:51:50 +0000929 }
930 }
931
drhad2d8302002-05-24 20:31:36 +0000932 /* Process NATURAL keywords, and ON and USING clauses of joins.
933 */
934 if( sqliteProcessJoin(pParse, p) ) return 1;
935
drh7c917d12001-12-16 20:05:05 +0000936 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000937 ** all columns in all tables. And for every TABLE.* insert the names
938 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000939 ** with the TK_ALL operator for each "*" that it found in the column list.
940 ** The following code just has to locate the TK_ALL expressions and expand
941 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000942 **
943 ** The first loop just checks to see if there are any "*" operators
944 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000945 */
drh7c917d12001-12-16 20:05:05 +0000946 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000947 Expr *pE = pEList->a[k].pExpr;
948 if( pE->op==TK_ALL ) break;
949 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
950 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000951 }
drh54473222002-04-04 02:10:55 +0000952 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000953 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000954 /*
955 ** If we get here it means the result set contains one or more "*"
956 ** operators that need to be expanded. Loop through each expression
957 ** in the result set and expand them one by one.
958 */
drh7c917d12001-12-16 20:05:05 +0000959 struct ExprList_item *a = pEList->a;
960 ExprList *pNew = 0;
961 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000962 Expr *pE = a[k].pExpr;
963 if( pE->op!=TK_ALL &&
964 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
965 /* This particular expression does not need to be expanded.
966 */
drh7c917d12001-12-16 20:05:05 +0000967 pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
968 pNew->a[pNew->nExpr-1].zName = a[k].zName;
969 a[k].pExpr = 0;
970 a[k].zName = 0;
971 }else{
drh54473222002-04-04 02:10:55 +0000972 /* This expression is a "*" or a "TABLE.*" and needs to be
973 ** expanded. */
974 int tableSeen = 0; /* Set to 1 when TABLE matches */
975 Token *pName; /* text of name of TABLE */
976 if( pE->op==TK_DOT && pE->pLeft ){
977 pName = &pE->pLeft->token;
978 }else{
979 pName = 0;
980 }
drhad3cab52002-05-24 02:04:32 +0000981 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000982 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000983 char *zTabName = pTabList->a[i].zAlias;
984 if( zTabName==0 || zTabName[0]==0 ){
985 zTabName = pTab->zName;
986 }
drhc754fa52002-05-27 03:25:51 +0000987 if( pName && (zTabName==0 || zTabName[0]==0 ||
988 sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
989 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +0000990 continue;
991 }
992 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +0000993 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000994 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +0000995 char *zName = pTab->aCol[j].zName;
996
997 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
998 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
999 /* In a NATURAL join, omit the join columns from the
1000 ** table on the right */
1001 continue;
1002 }
1003 if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
1004 /* In a join with a USING clause, omit columns in the
1005 ** using clause from the table on the right. */
1006 continue;
1007 }
drh22f70c32002-02-18 01:17:00 +00001008 pRight = sqliteExpr(TK_ID, 0, 0, 0);
1009 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +00001010 pRight->token.z = zName;
1011 pRight->token.n = strlen(zName);
drh4b59ab52002-08-24 18:24:51 +00001012 pRight->token.dyn = 0;
drh4b59ab52002-08-24 18:24:51 +00001013 if( zTabName && pTabList->nSrc>1 ){
drh22f70c32002-02-18 01:17:00 +00001014 pLeft = sqliteExpr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001015 pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
1016 if( pExpr==0 ) break;
drh4b59ab52002-08-24 18:24:51 +00001017 pLeft->token.z = zTabName;
1018 pLeft->token.n = strlen(zTabName);
1019 pLeft->token.dyn = 0;
drh6977fea2002-10-22 23:38:04 +00001020 sqliteSetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
1021 pExpr->span.n = strlen(pExpr->span.z);
1022 pExpr->span.dyn = 1;
1023 pExpr->token.z = 0;
1024 pExpr->token.n = 0;
1025 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001026 }else{
drh22f70c32002-02-18 01:17:00 +00001027 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001028 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001029 }
drh7c917d12001-12-16 20:05:05 +00001030 pNew = sqliteExprListAppend(pNew, pExpr, 0);
1031 }
drh17e24df2001-11-06 14:10:41 +00001032 }
drh54473222002-04-04 02:10:55 +00001033 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +00001034 if( pName ){
1035 sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1,
1036 pName->z, pName->n, 0);
1037 }else{
1038 sqliteSetString(&pParse->zErrMsg, "no tables specified", 0);
1039 }
drh54473222002-04-04 02:10:55 +00001040 rc = 1;
1041 }
drhd8bc7082000-06-07 23:51:50 +00001042 }
1043 }
drh7c917d12001-12-16 20:05:05 +00001044 sqliteExprListDelete(pEList);
1045 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001046 }
drh54473222002-04-04 02:10:55 +00001047 return rc;
drhd8bc7082000-06-07 23:51:50 +00001048}
1049
1050/*
drhff78bd22002-02-27 01:47:11 +00001051** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1052** in a select structure. It just sets the pointers to NULL. This
1053** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1054** pointer is not NULL, this routine is called recursively on that pointer.
1055**
1056** This routine is called on the Select structure that defines a
1057** VIEW in order to undo any bindings to tables. This is necessary
1058** because those tables might be DROPed by a subsequent SQL command.
1059*/
1060void sqliteSelectUnbind(Select *p){
1061 int i;
drhad3cab52002-05-24 02:04:32 +00001062 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +00001063 Table *pTab;
1064 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +00001065 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +00001066 if( (pTab = pSrc->a[i].pTab)!=0 ){
1067 if( pTab->isTransient ){
1068 sqliteDeleteTable(0, pTab);
drh4b59ab52002-08-24 18:24:51 +00001069#if 0
drhff78bd22002-02-27 01:47:11 +00001070 sqliteSelectDelete(pSrc->a[i].pSelect);
1071 pSrc->a[i].pSelect = 0;
drh4b59ab52002-08-24 18:24:51 +00001072#endif
drhff78bd22002-02-27 01:47:11 +00001073 }
1074 pSrc->a[i].pTab = 0;
1075 if( pSrc->a[i].pSelect ){
1076 sqliteSelectUnbind(pSrc->a[i].pSelect);
1077 }
1078 }
1079 }
1080}
1081
1082/*
drhd8bc7082000-06-07 23:51:50 +00001083** This routine associates entries in an ORDER BY expression list with
1084** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001085** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001086** the top-level node is filled in with column number and the iTable
1087** value of the top-level node is filled with iTable parameter.
1088**
1089** If there are prior SELECT clauses, they are processed first. A match
1090** in an earlier SELECT takes precedence over a later SELECT.
1091**
1092** Any entry that does not match is flagged as an error. The number
1093** of errors is returned.
drhfcb78a42003-01-18 20:11:05 +00001094**
1095** This routine does NOT correctly initialize the Expr.dataType field
1096** of the ORDER BY expressions. The multiSelectSortOrder() routine
1097** must be called to do that after the individual select statements
1098** have all been analyzed. This routine is unable to compute Expr.dataType
1099** because it must be called before the individual select statements
1100** have been analyzed.
drhd8bc7082000-06-07 23:51:50 +00001101*/
1102static int matchOrderbyToColumn(
1103 Parse *pParse, /* A place to leave error messages */
1104 Select *pSelect, /* Match to result columns of this SELECT */
1105 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001106 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001107 int mustComplete /* If TRUE all ORDER BYs must match */
1108){
1109 int nErr = 0;
1110 int i, j;
1111 ExprList *pEList;
1112
drhdaffd0e2001-04-11 14:28:42 +00001113 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001114 if( mustComplete ){
1115 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1116 }
1117 if( fillInColumnList(pParse, pSelect) ){
1118 return 1;
1119 }
1120 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001121 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1122 return 1;
1123 }
drhd8bc7082000-06-07 23:51:50 +00001124 }
1125 pEList = pSelect->pEList;
1126 for(i=0; i<pOrderBy->nExpr; i++){
1127 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001128 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001129 if( pOrderBy->a[i].done ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001130 if( sqliteExprIsInteger(pE, &iCol) ){
1131 if( iCol<=0 || iCol>pEList->nExpr ){
1132 char zBuf[200];
1133 sprintf(zBuf,"ORDER BY position %d should be between 1 and %d",
1134 iCol, pEList->nExpr);
1135 sqliteSetString(&pParse->zErrMsg, zBuf, 0);
1136 pParse->nErr++;
1137 nErr++;
1138 break;
1139 }
drhfcb78a42003-01-18 20:11:05 +00001140 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001141 iCol--;
1142 }
1143 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001144 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001145 char *zName, *zLabel;
1146 zName = pEList->a[j].zName;
1147 assert( pE->token.z );
1148 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
drhd8bc7082000-06-07 23:51:50 +00001149 sqliteDequote(zLabel);
1150 if( sqliteStrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001151 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001152 }
drh6e142f52000-06-08 13:36:40 +00001153 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001154 }
drhe4de1fe2002-06-02 16:09:01 +00001155 if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
1156 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001157 }
1158 }
drhe4de1fe2002-06-02 16:09:01 +00001159 if( iCol>=0 ){
1160 pE->op = TK_COLUMN;
1161 pE->iColumn = iCol;
1162 pE->iTable = iTable;
1163 pOrderBy->a[i].done = 1;
1164 }
1165 if( iCol<0 && mustComplete ){
drhd8bc7082000-06-07 23:51:50 +00001166 char zBuf[30];
1167 sprintf(zBuf,"%d",i+1);
1168 sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf,
1169 " does not match any result column", 0);
1170 pParse->nErr++;
1171 nErr++;
1172 break;
1173 }
1174 }
1175 return nErr;
1176}
1177
1178/*
1179** Get a VDBE for the given parser context. Create a new one if necessary.
1180** If an error occurs, return NULL and leave a message in pParse.
1181*/
1182Vdbe *sqliteGetVdbe(Parse *pParse){
1183 Vdbe *v = pParse->pVdbe;
1184 if( v==0 ){
drh4c504392000-10-16 22:06:40 +00001185 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001186 }
drhd8bc7082000-06-07 23:51:50 +00001187 return v;
1188}
drhfcb78a42003-01-18 20:11:05 +00001189
1190/*
1191** This routine sets the Expr.dataType field on all elements of
1192** the pOrderBy expression list. The pOrderBy list will have been
1193** set up by matchOrderbyToColumn(). Hence each expression has
1194** a TK_COLUMN as its root node. The Expr.iColumn refers to a
1195** column in the result set. The datatype is set to SQLITE_SO_TEXT
1196** if the corresponding column in p and every SELECT to the left of
1197** p has a datatype of SQLITE_SO_TEXT. If the cooressponding column
1198** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
1199** of the order-by expression is set to SQLITE_SO_NUM.
1200**
1201** Examples:
1202**
drhe78e8282003-01-19 03:59:45 +00001203** CREATE TABLE one(a INTEGER, b TEXT);
1204** CREATE TABLE two(c VARCHAR(5), d FLOAT);
1205**
1206** SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
1207**
1208** The primary sort key will use SQLITE_SO_NUM because the "d" in
1209** the second SELECT is numeric. The 1st column of the first SELECT
1210** is text but that does not matter because a numeric always overrides
1211** a text.
1212**
1213** The secondary key will use the SQLITE_SO_TEXT sort order because
1214** both the (second) "b" in the first SELECT and the "c" in the second
1215** SELECT have a datatype of text.
drhfcb78a42003-01-18 20:11:05 +00001216*/
1217static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
1218 int i;
1219 ExprList *pEList;
1220 if( pOrderBy==0 ) return;
1221 if( p==0 ){
1222 for(i=0; i<pOrderBy->nExpr; i++){
1223 pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
1224 }
1225 return;
1226 }
1227 multiSelectSortOrder(p->pPrior, pOrderBy);
1228 pEList = p->pEList;
1229 for(i=0; i<pOrderBy->nExpr; i++){
1230 Expr *pE = pOrderBy->a[i].pExpr;
1231 if( pE->dataType==SQLITE_SO_NUM ) continue;
1232 assert( pE->iColumn>=0 );
1233 if( pEList->nExpr>pE->iColumn ){
1234 pE->dataType = sqliteExprType(pEList->a[pE->iColumn].pExpr);
1235 }
1236 }
1237}
drhd8bc7082000-06-07 23:51:50 +00001238
1239/*
drh82c3d632000-06-06 21:56:07 +00001240** This routine is called to process a query that is really the union
1241** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001242**
drhe78e8282003-01-19 03:59:45 +00001243** "p" points to the right-most of the two queries. the query on the
1244** left is p->pPrior. The left query could also be a compound query
1245** in which case this routine will be called recursively.
1246**
1247** The results of the total query are to be written into a destination
1248** of type eDest with parameter iParm.
1249**
1250** Example 1: Consider a three-way compound SQL statement.
1251**
1252** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1253**
1254** This statement is parsed up as follows:
1255**
1256** SELECT c FROM t3
1257** |
1258** `-----> SELECT b FROM t2
1259** |
1260** `------> SELECT c FROM t1
1261**
1262** The arrows in the diagram above represent the Select.pPrior pointer.
1263** So if this routine is called with p equal to the t3 query, then
1264** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1265**
1266** Notice that because of the way SQLite parses compound SELECTs, the
1267** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001268*/
1269static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
drh10e5e3c2000-06-08 00:19:02 +00001270 int rc; /* Success code from a subroutine */
1271 Select *pPrior; /* Another SELECT immediately to our left */
1272 Vdbe *v; /* Generate code to this VDBE */
drh82c3d632000-06-06 21:56:07 +00001273
drhd8bc7082000-06-07 23:51:50 +00001274 /* Make sure there is no ORDER BY clause on prior SELECTs. Only the
1275 ** last SELECT in the series may have an ORDER BY.
drh82c3d632000-06-06 21:56:07 +00001276 */
drhdaffd0e2001-04-11 14:28:42 +00001277 if( p==0 || p->pPrior==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001278 pPrior = p->pPrior;
1279 if( pPrior->pOrderBy ){
1280 sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
1281 selectOpName(p->op), " not before", 0);
drh82c3d632000-06-06 21:56:07 +00001282 pParse->nErr++;
1283 return 1;
1284 }
1285
drhd8bc7082000-06-07 23:51:50 +00001286 /* Make sure we have a valid query engine. If not, create a new one.
1287 */
1288 v = sqliteGetVdbe(pParse);
1289 if( v==0 ) return 1;
1290
drh1cc3d752002-03-23 00:31:29 +00001291 /* Create the destination temporary table if necessary
1292 */
1293 if( eDest==SRT_TempTable ){
1294 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
1295 eDest = SRT_Table;
1296 }
1297
drhf46f9052002-06-22 02:33:38 +00001298 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001299 */
drh82c3d632000-06-06 21:56:07 +00001300 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001301 case TK_ALL: {
1302 if( p->pOrderBy==0 ){
1303 rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
1304 if( rc ) return rc;
1305 p->pPrior = 0;
1306 rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
1307 p->pPrior = pPrior;
1308 if( rc ) return rc;
1309 break;
1310 }
1311 /* For UNION ALL ... ORDER BY fall through to the next case */
1312 }
drh82c3d632000-06-06 21:56:07 +00001313 case TK_EXCEPT:
1314 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001315 int unionTab; /* Cursor number of the temporary table holding result */
1316 int op; /* One of the SRT_ operations to apply to self */
1317 int priorOp; /* The SRT_ operation to apply to prior selects */
drhc926afb2002-06-20 03:38:26 +00001318 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
drh82c3d632000-06-06 21:56:07 +00001319
drhd8bc7082000-06-07 23:51:50 +00001320 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drhc926afb2002-06-20 03:38:26 +00001321 if( eDest==priorOp && p->pOrderBy==0 ){
drhd8bc7082000-06-07 23:51:50 +00001322 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001323 ** right.
drhd8bc7082000-06-07 23:51:50 +00001324 */
drh82c3d632000-06-06 21:56:07 +00001325 unionTab = iParm;
1326 }else{
drhd8bc7082000-06-07 23:51:50 +00001327 /* We will need to create our own temporary table to hold the
1328 ** intermediate results.
1329 */
1330 unionTab = pParse->nTab++;
1331 if( p->pOrderBy
1332 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1333 return 1;
1334 }
drhd8bc7082000-06-07 23:51:50 +00001335 if( p->op!=TK_ALL ){
drhc6b52df2002-01-04 03:09:29 +00001336 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
drh99fcd712001-10-13 01:06:47 +00001337 sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drh345fda32001-01-15 22:51:08 +00001338 }else{
drh99fcd712001-10-13 01:06:47 +00001339 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001340 }
drh82c3d632000-06-06 21:56:07 +00001341 }
drhd8bc7082000-06-07 23:51:50 +00001342
1343 /* Code the SELECT statements to our left
1344 */
drh832508b2002-03-02 17:04:07 +00001345 rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001346 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001347
1348 /* Code the current SELECT statement
1349 */
1350 switch( p->op ){
1351 case TK_EXCEPT: op = SRT_Except; break;
1352 case TK_UNION: op = SRT_Union; break;
1353 case TK_ALL: op = SRT_Table; break;
1354 }
drh82c3d632000-06-06 21:56:07 +00001355 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001356 pOrderBy = p->pOrderBy;
1357 p->pOrderBy = 0;
drh832508b2002-03-02 17:04:07 +00001358 rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001359 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001360 p->pOrderBy = pOrderBy;
drh82c3d632000-06-06 21:56:07 +00001361 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001362
1363 /* Convert the data in the temporary table into whatever form
1364 ** it is that we currently need.
1365 */
drhc926afb2002-06-20 03:38:26 +00001366 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001367 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001368 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001369 if( eDest==SRT_Callback ){
1370 generateColumnNames(pParse, p->base, 0, p->pEList);
drhfcb78a42003-01-18 20:11:05 +00001371 generateColumnTypes(pParse, p->base, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001372 }
drh82c3d632000-06-06 21:56:07 +00001373 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001374 iCont = sqliteVdbeMakeLabel(v);
1375 sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
1376 iStart = sqliteVdbeCurrentAddr(v);
drhfcb78a42003-01-18 20:11:05 +00001377 multiSelectSortOrder(p, p->pOrderBy);
drh38640e12002-07-05 21:42:36 +00001378 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001379 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001380 iCont, iBreak);
1381 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001382 sqliteVdbeResolveLabel(v, iCont);
1383 sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
drh99fcd712001-10-13 01:06:47 +00001384 sqliteVdbeResolveLabel(v, iBreak);
1385 sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001386 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001387 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001388 }
drh82c3d632000-06-06 21:56:07 +00001389 }
1390 break;
1391 }
1392 case TK_INTERSECT: {
1393 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001394 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001395
drhd8bc7082000-06-07 23:51:50 +00001396 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001397 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001398 ** by allocating the tables we will need.
1399 */
drh82c3d632000-06-06 21:56:07 +00001400 tab1 = pParse->nTab++;
1401 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001402 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1403 return 1;
1404 }
drhc6b52df2002-01-04 03:09:29 +00001405 sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
drh99fcd712001-10-13 01:06:47 +00001406 sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
drhd8bc7082000-06-07 23:51:50 +00001407
1408 /* Code the SELECTs to our left into temporary table "tab1".
1409 */
drh832508b2002-03-02 17:04:07 +00001410 rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001411 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001412
1413 /* Code the current SELECT into temporary table "tab2"
1414 */
drhc6b52df2002-01-04 03:09:29 +00001415 sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
drh99fcd712001-10-13 01:06:47 +00001416 sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001417 p->pPrior = 0;
drh832508b2002-03-02 17:04:07 +00001418 rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001419 p->pPrior = pPrior;
1420 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001421
1422 /* Generate code to take the intersection of the two temporary
1423 ** tables.
1424 */
drh82c3d632000-06-06 21:56:07 +00001425 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001426 if( eDest==SRT_Callback ){
1427 generateColumnNames(pParse, p->base, 0, p->pEList);
drhfcb78a42003-01-18 20:11:05 +00001428 generateColumnTypes(pParse, p->base, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001429 }
drh82c3d632000-06-06 21:56:07 +00001430 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001431 iCont = sqliteVdbeMakeLabel(v);
1432 sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
1433 iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
drh99fcd712001-10-13 01:06:47 +00001434 sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
drhfcb78a42003-01-18 20:11:05 +00001435 multiSelectSortOrder(p, p->pOrderBy);
drh38640e12002-07-05 21:42:36 +00001436 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001437 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001438 iCont, iBreak);
1439 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001440 sqliteVdbeResolveLabel(v, iCont);
1441 sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
drh99fcd712001-10-13 01:06:47 +00001442 sqliteVdbeResolveLabel(v, iBreak);
1443 sqliteVdbeAddOp(v, OP_Close, tab2, 0);
1444 sqliteVdbeAddOp(v, OP_Close, tab1, 0);
drhd8bc7082000-06-07 23:51:50 +00001445 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001446 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001447 }
drh82c3d632000-06-06 21:56:07 +00001448 break;
1449 }
1450 }
1451 assert( p->pEList && pPrior->pEList );
1452 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
drhd8bc7082000-06-07 23:51:50 +00001453 sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ",
1454 selectOpName(p->op), " do not have the same number of result columns", 0);
drh82c3d632000-06-06 21:56:07 +00001455 pParse->nErr++;
1456 return 1;
drh22827922000-06-06 17:27:05 +00001457 }
drhfcb78a42003-01-18 20:11:05 +00001458
1459 /* Issue a null callback if that is what the user wants.
1460 */
drh326dce72003-01-29 14:06:07 +00001461 if( eDest==SRT_Callback &&
1462 (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
1463 ){
drhfcb78a42003-01-18 20:11:05 +00001464 sqliteVdbeAddOp(v, OP_NullCallback, p->pEList->nExpr, 0);
1465 }
drh22827922000-06-06 17:27:05 +00001466 return 0;
1467}
1468
1469/*
drh832508b2002-03-02 17:04:07 +00001470** Recursively scan through an expression tree. For every reference
1471** to a column in table number iFrom, change that reference to the
1472** same column in table number iTo.
1473*/
drh315555c2002-10-20 15:53:03 +00001474static void changeTablesInList(ExprList*, int, int); /* Forward Declaration */
drh832508b2002-03-02 17:04:07 +00001475static void changeTables(Expr *pExpr, int iFrom, int iTo){
1476 if( pExpr==0 ) return;
1477 if( pExpr->op==TK_COLUMN && pExpr->iTable==iFrom ){
1478 pExpr->iTable = iTo;
1479 }else{
1480 changeTables(pExpr->pLeft, iFrom, iTo);
1481 changeTables(pExpr->pRight, iFrom, iTo);
drh1b2e0322002-03-03 02:49:51 +00001482 changeTablesInList(pExpr->pList, iFrom, iTo);
1483 }
1484}
1485static void changeTablesInList(ExprList *pList, int iFrom, int iTo){
1486 if( pList ){
1487 int i;
1488 for(i=0; i<pList->nExpr; i++){
1489 changeTables(pList->a[i].pExpr, iFrom, iTo);
drh832508b2002-03-02 17:04:07 +00001490 }
1491 }
1492}
1493
1494/*
1495** Scan through the expression pExpr. Replace every reference to
1496** a column in table number iTable with a copy of the corresponding
drh84e59202002-03-14 14:33:31 +00001497** entry in pEList. (But leave references to the ROWID column
1498** unchanged.) When making a copy of an expression in pEList, change
1499** references to columns in table iSub into references to table iTable.
drh832508b2002-03-02 17:04:07 +00001500**
1501** This routine is part of the flattening procedure. A subquery
1502** whose result set is defined by pEList appears as entry in the
1503** FROM clause of a SELECT such that the VDBE cursor assigned to that
1504** FORM clause entry is iTable. This routine make the necessary
1505** changes to pExpr so that it refers directly to the source table
1506** of the subquery rather the result set of the subquery.
1507*/
drh315555c2002-10-20 15:53:03 +00001508static void substExprList(ExprList*,int,ExprList*,int); /* Forward Decl */
drh832508b2002-03-02 17:04:07 +00001509static void substExpr(Expr *pExpr, int iTable, ExprList *pEList, int iSub){
1510 if( pExpr==0 ) return;
drh84e59202002-03-14 14:33:31 +00001511 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){
drh832508b2002-03-02 17:04:07 +00001512 Expr *pNew;
drh84e59202002-03-14 14:33:31 +00001513 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
drh832508b2002-03-02 17:04:07 +00001514 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1515 pNew = pEList->a[pExpr->iColumn].pExpr;
1516 assert( pNew!=0 );
1517 pExpr->op = pNew->op;
drhfcb78a42003-01-18 20:11:05 +00001518 pExpr->dataType = pNew->dataType;
drhd94a6692002-08-25 18:29:11 +00001519 assert( pExpr->pLeft==0 );
drh832508b2002-03-02 17:04:07 +00001520 pExpr->pLeft = sqliteExprDup(pNew->pLeft);
drhd94a6692002-08-25 18:29:11 +00001521 assert( pExpr->pRight==0 );
drh832508b2002-03-02 17:04:07 +00001522 pExpr->pRight = sqliteExprDup(pNew->pRight);
drhd94a6692002-08-25 18:29:11 +00001523 assert( pExpr->pList==0 );
drh832508b2002-03-02 17:04:07 +00001524 pExpr->pList = sqliteExprListDup(pNew->pList);
1525 pExpr->iTable = pNew->iTable;
1526 pExpr->iColumn = pNew->iColumn;
1527 pExpr->iAgg = pNew->iAgg;
drh4b59ab52002-08-24 18:24:51 +00001528 sqliteTokenCopy(&pExpr->token, &pNew->token);
drh6977fea2002-10-22 23:38:04 +00001529 sqliteTokenCopy(&pExpr->span, &pNew->span);
drh832508b2002-03-02 17:04:07 +00001530 if( iSub!=iTable ){
1531 changeTables(pExpr, iSub, iTable);
1532 }
1533 }else{
drh832508b2002-03-02 17:04:07 +00001534 substExpr(pExpr->pLeft, iTable, pEList, iSub);
1535 substExpr(pExpr->pRight, iTable, pEList, iSub);
1536 substExprList(pExpr->pList, iTable, pEList, iSub);
1537 }
1538}
1539static void
1540substExprList(ExprList *pList, int iTable, ExprList *pEList, int iSub){
1541 int i;
1542 if( pList==0 ) return;
1543 for(i=0; i<pList->nExpr; i++){
1544 substExpr(pList->a[i].pExpr, iTable, pEList, iSub);
1545 }
1546}
1547
1548/*
drh1350b032002-02-27 19:00:20 +00001549** This routine attempts to flatten subqueries in order to speed
1550** execution. It returns 1 if it makes changes and 0 if no flattening
1551** occurs.
1552**
1553** To understand the concept of flattening, consider the following
1554** query:
1555**
1556** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1557**
1558** The default way of implementing this query is to execute the
1559** subquery first and store the results in a temporary table, then
1560** run the outer query on that temporary table. This requires two
1561** passes over the data. Furthermore, because the temporary table
1562** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001563** optimized.
drh1350b032002-02-27 19:00:20 +00001564**
drh832508b2002-03-02 17:04:07 +00001565** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001566** a single flat select, like this:
1567**
1568** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1569**
1570** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001571** but only has to scan the data once. And because indices might
1572** exist on the table t1, a complete scan of the data might be
1573** avoided.
drh1350b032002-02-27 19:00:20 +00001574**
drh832508b2002-03-02 17:04:07 +00001575** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001576**
drh832508b2002-03-02 17:04:07 +00001577** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001578**
drh832508b2002-03-02 17:04:07 +00001579** (2) The subquery is not an aggregate or the outer query is not a join.
1580**
1581** (3) The subquery is not a join.
1582**
1583** (4) The subquery is not DISTINCT or the outer query is not a join.
1584**
1585** (5) The subquery is not DISTINCT or the outer query does not use
1586** aggregates.
1587**
1588** (6) The subquery does not use aggregates or the outer query is not
1589** DISTINCT.
1590**
drh08192d52002-04-30 19:20:28 +00001591** (7) The subquery has a FROM clause.
1592**
drhdf199a22002-06-14 22:38:41 +00001593** (8) The subquery does not use LIMIT or the outer query is not a join.
1594**
1595** (9) The subquery does not use LIMIT or the outer query does not use
1596** aggregates.
1597**
1598** (10) The subquery does not use aggregates or the outer query does not
1599** use LIMIT.
1600**
drh174b6192002-12-03 02:22:52 +00001601** (11) The subquery and the outer query do not both have ORDER BY clauses.
1602**
drh832508b2002-03-02 17:04:07 +00001603** In this routine, the "p" parameter is a pointer to the outer query.
1604** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1605** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1606**
1607** If flattening is not attempted, this routine is a no-op and return 0.
1608** If flattening is attempted this routine returns 1.
1609**
1610** All of the expression analysis must occur on both the outer query and
1611** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001612*/
drh8c74a8c2002-08-25 19:20:40 +00001613static int flattenSubquery(
1614 Parse *pParse, /* The parsing context */
1615 Select *p, /* The parent or outer SELECT statement */
1616 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1617 int isAgg, /* True if outer SELECT uses aggregate functions */
1618 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1619){
drh0bb28102002-05-08 11:54:14 +00001620 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001621 SrcList *pSrc; /* The FROM clause of the outer query */
1622 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001623 ExprList *pList; /* The result set of the outer query */
drh832508b2002-03-02 17:04:07 +00001624 int i;
1625 int iParent, iSub;
1626 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001627
drh832508b2002-03-02 17:04:07 +00001628 /* Check to see if flattening is permitted. Return 0 if not.
1629 */
1630 if( p==0 ) return 0;
1631 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001632 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001633 pSub = pSrc->a[iFrom].pSelect;
1634 assert( pSub!=0 );
1635 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001636 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001637 pSubSrc = pSub->pSrc;
1638 assert( pSubSrc );
drhad3cab52002-05-24 02:04:32 +00001639 if( pSubSrc->nSrc!=1 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001640 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1641 return 0;
1642 }
drhd11d3822002-06-21 23:01:49 +00001643 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001644 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001645
drh0bb28102002-05-08 11:54:14 +00001646 /* If we reach this point, it means flattening is permitted for the
drh832508b2002-03-02 17:04:07 +00001647 ** i-th entry of the FROM clause in the outer query.
1648 */
1649 iParent = p->base + iFrom;
1650 iSub = pSub->base;
1651 substExprList(p->pEList, iParent, pSub->pEList, iSub);
1652 pList = p->pEList;
1653 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001654 Expr *pExpr;
1655 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1656 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001657 }
1658 }
drh1b2e0322002-03-03 02:49:51 +00001659 if( isAgg ){
1660 substExprList(p->pGroupBy, iParent, pSub->pEList, iSub);
1661 substExpr(p->pHaving, iParent, pSub->pEList, iSub);
1662 }
drh174b6192002-12-03 02:22:52 +00001663 if( pSub->pOrderBy ){
1664 assert( p->pOrderBy==0 );
1665 p->pOrderBy = pSub->pOrderBy;
1666 pSub->pOrderBy = 0;
1667 changeTablesInList(p->pOrderBy, iSub, iParent);
1668 }else if( p->pOrderBy ){
1669 substExprList(p->pOrderBy, iParent, pSub->pEList, iSub);
1670 }
drh832508b2002-03-02 17:04:07 +00001671 if( pSub->pWhere ){
1672 pWhere = sqliteExprDup(pSub->pWhere);
1673 if( iParent!=iSub ){
1674 changeTables(pWhere, iSub, iParent);
1675 }
1676 }else{
1677 pWhere = 0;
1678 }
1679 if( subqueryIsAgg ){
1680 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001681 p->pHaving = p->pWhere;
1682 p->pWhere = pWhere;
drh832508b2002-03-02 17:04:07 +00001683 substExpr(p->pHaving, iParent, pSub->pEList, iSub);
drh1b2e0322002-03-03 02:49:51 +00001684 if( pSub->pHaving ){
1685 Expr *pHaving = sqliteExprDup(pSub->pHaving);
1686 if( iParent!=iSub ){
1687 changeTables(pHaving, iSub, iParent);
1688 }
1689 if( p->pHaving ){
1690 p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
1691 }else{
1692 p->pHaving = pHaving;
1693 }
1694 }
1695 assert( p->pGroupBy==0 );
1696 p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
1697 if( iParent!=iSub ){
1698 changeTablesInList(p->pGroupBy, iSub, iParent);
1699 }
drh832508b2002-03-02 17:04:07 +00001700 }else if( p->pWhere==0 ){
1701 p->pWhere = pWhere;
1702 }else{
1703 substExpr(p->pWhere, iParent, pSub->pEList, iSub);
1704 if( pWhere ){
1705 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1706 }
1707 }
1708 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00001709
drhdf199a22002-06-14 22:38:41 +00001710 if( pSub->nLimit>=0 ){
1711 if( p->nLimit<0 ){
1712 p->nLimit = pSub->nLimit;
1713 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1714 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1715 }
1716 }
1717 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00001718
1719 /* If the subquery contains subqueries of its own, that were not
1720 ** flattened, then code will have already been generated to put
1721 ** the results of those sub-subqueries into VDBE cursors relative
1722 ** to the subquery. We must translate the cursor number into values
1723 ** suitable for use by the outer query.
1724 */
1725 for(i=0; i<pSubSrc->nSrc; i++){
1726 Vdbe *v;
1727 if( pSubSrc->a[i].pSelect==0 ) continue;
1728 v = sqliteGetVdbe(pParse);
1729 sqliteVdbeAddOp(v, OP_RenameCursor, pSub->base+i, p->base+i);
1730 }
1731
drh832508b2002-03-02 17:04:07 +00001732 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1733 sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1734 }
1735 pSrc->a[iFrom].pTab = pSubSrc->a[0].pTab;
1736 pSubSrc->a[0].pTab = 0;
drhd94a6692002-08-25 18:29:11 +00001737 assert( pSrc->a[iFrom].pSelect==pSub );
drh832508b2002-03-02 17:04:07 +00001738 pSrc->a[iFrom].pSelect = pSubSrc->a[0].pSelect;
1739 pSubSrc->a[0].pSelect = 0;
1740 sqliteSelectDelete(pSub);
1741 return 1;
1742}
drh1350b032002-02-27 19:00:20 +00001743
1744/*
drh9562b552002-02-19 15:00:07 +00001745** Analyze the SELECT statement passed in as an argument to see if it
1746** is a simple min() or max() query. If it is and this query can be
1747** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00001748** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00001749** simple min() or max() query, then return 0;
1750**
1751** A simply min() or max() query looks like this:
1752**
1753** SELECT min(a) FROM table;
1754** SELECT max(a) FROM table;
1755**
1756** The query may have only a single table in its FROM argument. There
1757** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1758** be the min() or max() of a single column of the table. The column
1759** in the min() or max() function must be indexed.
1760**
1761** The parameters to this routine are the same as for sqliteSelect().
1762** See the header comment on that routine for additional information.
1763*/
1764static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1765 Expr *pExpr;
1766 int iCol;
1767 Table *pTab;
1768 Index *pIdx;
1769 int base;
1770 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00001771 int seekOp;
1772 int cont;
1773 ExprList eList;
1774 struct ExprList_item eListItem;
1775
1776 /* Check to see if this query is a simple min() or max() query. Return
1777 ** zero if it is not.
1778 */
1779 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drhad3cab52002-05-24 02:04:32 +00001780 if( p->pSrc->nSrc!=1 ) return 0;
drh9562b552002-02-19 15:00:07 +00001781 if( p->pEList->nExpr!=1 ) return 0;
1782 pExpr = p->pEList->a[0].pExpr;
1783 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
1784 if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00001785 if( pExpr->token.n!=3 ) return 0;
drh0bce8352002-02-28 00:41:10 +00001786 if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
1787 seekOp = OP_Rewind;
1788 }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
1789 seekOp = OP_Last;
1790 }else{
1791 return 0;
1792 }
drh9562b552002-02-19 15:00:07 +00001793 pExpr = pExpr->pList->a[0].pExpr;
1794 if( pExpr->op!=TK_COLUMN ) return 0;
1795 iCol = pExpr->iColumn;
1796 pTab = p->pSrc->a[0].pTab;
1797
1798 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00001799 ** Check to make sure we have an index and make pIdx point to the
1800 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
1801 ** key column, no index is necessary so set pIdx to NULL. If no
1802 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00001803 */
1804 if( iCol<0 ){
1805 pIdx = 0;
1806 }else{
1807 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1808 assert( pIdx->nColumn>=1 );
1809 if( pIdx->aiColumn[0]==iCol ) break;
1810 }
1811 if( pIdx==0 ) return 0;
1812 }
1813
drh17f71932002-02-21 12:01:27 +00001814 /* Identify column names if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00001815 ** step is skipped if the output is going to a table or a memory cell.
1816 */
1817 v = sqliteGetVdbe(pParse);
1818 if( v==0 ) return 0;
1819 if( eDest==SRT_Callback ){
drh832508b2002-03-02 17:04:07 +00001820 generateColumnNames(pParse, p->base, p->pSrc, p->pEList);
drhfcb78a42003-01-18 20:11:05 +00001821 generateColumnTypes(pParse, p->base, p->pSrc, p->pEList);
drh9562b552002-02-19 15:00:07 +00001822 }
1823
drh17f71932002-02-21 12:01:27 +00001824 /* Generating code to find the min or the max. Basically all we have
1825 ** to do is find the first or the last entry in the chosen index. If
1826 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
1827 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00001828 */
drh5cf8e8c2002-02-19 22:42:05 +00001829 if( !pParse->schemaVerified && (pParse->db->flags & SQLITE_InTrans)==0 ){
drh001bbcb2003-03-19 03:14:00 +00001830 sqliteCodeVerifySchema(pParse);
drh5cf8e8c2002-02-19 22:42:05 +00001831 }
drh832508b2002-03-02 17:04:07 +00001832 base = p->base;
drh001bbcb2003-03-19 03:14:00 +00001833 sqliteVdbeAddOp(v, OP_Integer, pTab->isTemp, 0);
1834 sqliteVdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001835 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
drh9562b552002-02-19 15:00:07 +00001836 if( pIdx==0 ){
1837 sqliteVdbeAddOp(v, seekOp, base, 0);
1838 }else{
drh001bbcb2003-03-19 03:14:00 +00001839 sqliteVdbeAddOp(v, OP_Integer, pTab->isTemp, 0);
1840 sqliteVdbeAddOp(v, OP_OpenRead, base+1, pIdx->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001841 sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
drh9562b552002-02-19 15:00:07 +00001842 sqliteVdbeAddOp(v, seekOp, base+1, 0);
1843 sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
1844 sqliteVdbeAddOp(v, OP_Close, base+1, 0);
1845 sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
1846 }
drh5cf8e8c2002-02-19 22:42:05 +00001847 eList.nExpr = 1;
1848 memset(&eListItem, 0, sizeof(eListItem));
1849 eList.a = &eListItem;
1850 eList.a[0].pExpr = pExpr;
drh9562b552002-02-19 15:00:07 +00001851 cont = sqliteVdbeMakeLabel(v);
drh38640e12002-07-05 21:42:36 +00001852 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
drh9562b552002-02-19 15:00:07 +00001853 sqliteVdbeResolveLabel(v, cont);
1854 sqliteVdbeAddOp(v, OP_Close, base, 0);
1855 return 1;
1856}
1857
1858/*
drh9bb61fe2000-06-05 16:01:39 +00001859** Generate code for the given SELECT statement.
1860**
drhfef52082000-06-06 01:50:43 +00001861** The results are distributed in various ways depending on the
1862** value of eDest and iParm.
1863**
1864** eDest Value Result
1865** ------------ -------------------------------------------
1866** SRT_Callback Invoke the callback for each row of the result.
1867**
1868** SRT_Mem Store first result in memory cell iParm
1869**
1870** SRT_Set Store results as keys of a table with cursor iParm
1871**
drh82c3d632000-06-06 21:56:07 +00001872** SRT_Union Store results as a key in a temporary table iParm
1873**
drhc4a3c772001-04-04 11:48:57 +00001874** SRT_Except Remove results form the temporary table iParm.
1875**
1876** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00001877**
drhe78e8282003-01-19 03:59:45 +00001878** The table above is incomplete. Additional eDist value have be added
1879** since this comment was written. See the selectInnerLoop() function for
1880** a complete listing of the allowed values of eDest and their meanings.
1881**
drh9bb61fe2000-06-05 16:01:39 +00001882** This routine returns the number of errors. If any errors are
1883** encountered, then an appropriate error message is left in
1884** pParse->zErrMsg.
1885**
1886** This routine does NOT free the Select structure passed in. The
1887** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00001888**
1889** The pParent, parentTab, and *pParentAgg fields are filled in if this
1890** SELECT is a subquery. This routine may try to combine this SELECT
1891** with its parent to form a single flat query. In so doing, it might
1892** change the parent query from a non-aggregate to an aggregate query.
1893** For that reason, the pParentAgg flag is passed as a pointer, so it
1894** can be changed.
drhe78e8282003-01-19 03:59:45 +00001895**
1896** Example 1: The meaning of the pParent parameter.
1897**
1898** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
1899** \ \_______ subquery _______/ /
1900** \ /
1901** \____________________ outer query ___________________/
1902**
1903** This routine is called for the outer query first. For that call,
1904** pParent will be NULL. During the processing of the outer query, this
1905** routine is called recursively to handle the subquery. For the recursive
1906** call, pParent will point to the outer query. Because the subquery is
1907** the second element in a three-way join, the parentTab parameter will
1908** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00001909*/
1910int sqliteSelect(
drhcce7d172000-05-31 15:34:51 +00001911 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00001912 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00001913 int eDest, /* How to dispose of the results */
1914 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00001915 Select *pParent, /* Another SELECT for which this is a sub-query */
1916 int parentTab, /* Index in pParent->pSrc of this query */
drh1b2e0322002-03-03 02:49:51 +00001917 int *pParentAgg /* True if pParent uses aggregate functions */
drhcce7d172000-05-31 15:34:51 +00001918){
drhd8bc7082000-06-07 23:51:50 +00001919 int i;
drhcce7d172000-05-31 15:34:51 +00001920 WhereInfo *pWInfo;
1921 Vdbe *v;
1922 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00001923 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00001924 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00001925 Expr *pWhere; /* The WHERE clause. May be NULL */
1926 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00001927 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
1928 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00001929 int isDistinct; /* True if the DISTINCT keyword is present */
1930 int distinct; /* Table to use for the distinct set */
drh10e5e3c2000-06-08 00:19:02 +00001931 int base; /* First cursor available for use */
drh1d83f052002-02-17 00:30:36 +00001932 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00001933
drhdaffd0e2001-04-11 14:28:42 +00001934 if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
drhe5f9c642003-01-13 23:27:31 +00001935 if( sqliteAuthCheck(pParse, SQLITE_SELECT, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00001936
drh82c3d632000-06-06 21:56:07 +00001937 /* If there is are a sequence of queries, do the earlier ones first.
1938 */
1939 if( p->pPrior ){
1940 return multiSelect(pParse, p, eDest, iParm);
1941 }
1942
1943 /* Make local copies of the parameters for this query.
1944 */
drh9bb61fe2000-06-05 16:01:39 +00001945 pTabList = p->pSrc;
1946 pWhere = p->pWhere;
1947 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00001948 pGroupBy = p->pGroupBy;
1949 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00001950 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00001951
drh832508b2002-03-02 17:04:07 +00001952 /* Allocate a block of VDBE cursors, one for each table in the FROM clause.
1953 ** The WHERE processing requires that the cursors for the tables in the
1954 ** FROM clause be consecutive.
drh10e5e3c2000-06-08 00:19:02 +00001955 */
drh832508b2002-03-02 17:04:07 +00001956 base = p->base = pParse->nTab;
drhad3cab52002-05-24 02:04:32 +00001957 pParse->nTab += pTabList->nSrc;
drh10e5e3c2000-06-08 00:19:02 +00001958
drh9bb61fe2000-06-05 16:01:39 +00001959 /*
1960 ** Do not even attempt to generate any code if we have already seen
1961 ** errors before this routine starts.
1962 */
drh1d83f052002-02-17 00:30:36 +00001963 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001964
drhe78e8282003-01-19 03:59:45 +00001965 /* Expand any "*" terms in the result set. (For example the "*" in
1966 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
1967 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00001968 */
drhd8bc7082000-06-07 23:51:50 +00001969 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00001970 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001971 }
drhad2d8302002-05-24 20:31:36 +00001972 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00001973 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00001974 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001975
drh22827922000-06-06 17:27:05 +00001976 /* If writing to memory or generating a set
1977 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00001978 */
drhfef52082000-06-06 01:50:43 +00001979 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
drh19a775c2000-06-05 18:54:46 +00001980 sqliteSetString(&pParse->zErrMsg, "only a single result allowed for "
1981 "a SELECT that is part of an expression", 0);
1982 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +00001983 goto select_end;
drh19a775c2000-06-05 18:54:46 +00001984 }
1985
drhc926afb2002-06-20 03:38:26 +00001986 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00001987 */
drhc926afb2002-06-20 03:38:26 +00001988 switch( eDest ){
1989 case SRT_Union:
1990 case SRT_Except:
1991 case SRT_Discard:
1992 pOrderBy = 0;
1993 break;
1994 default:
1995 break;
drh22827922000-06-06 17:27:05 +00001996 }
1997
drh10e5e3c2000-06-08 00:19:02 +00001998 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00001999 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002000 **
drh967e8b72000-06-21 13:59:10 +00002001 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002002 */
drh4794b982000-06-06 13:54:14 +00002003 for(i=0; i<pEList->nExpr; i++){
drh832508b2002-03-02 17:04:07 +00002004 if( sqliteExprResolveIds(pParse, base, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002005 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002006 }
drh22827922000-06-06 17:27:05 +00002007 if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002008 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002009 }
2010 }
drhcce7d172000-05-31 15:34:51 +00002011 if( pWhere ){
drh832508b2002-03-02 17:04:07 +00002012 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00002013 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002014 }
2015 if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00002016 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002017 }
drh1f162302002-10-27 19:35:33 +00002018 sqliteOracle8JoinFixup(base, pTabList, pWhere);
drhcce7d172000-05-31 15:34:51 +00002019 }
drhc66c5a22002-12-03 02:34:49 +00002020 if( pHaving ){
2021 if( pGroupBy==0 ){
2022 sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required "
2023 "before HAVING", 0);
2024 pParse->nErr++;
2025 goto select_end;
2026 }
2027 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pHaving) ){
2028 goto select_end;
2029 }
2030 if( sqliteExprCheck(pParse, pHaving, 1, &isAgg) ){
2031 goto select_end;
2032 }
2033 }
drhcce7d172000-05-31 15:34:51 +00002034 if( pOrderBy ){
2035 for(i=0; i<pOrderBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002036 int iCol;
drh22827922000-06-06 17:27:05 +00002037 Expr *pE = pOrderBy->a[i].pExpr;
drh88eee382003-01-31 17:16:36 +00002038 if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2039 sqliteExprDelete(pE);
2040 pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
2041 }
2042 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
2043 goto select_end;
2044 }
2045 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
2046 goto select_end;
2047 }
drh92086432002-01-22 14:11:29 +00002048 if( sqliteExprIsConstant(pE) ){
drhe4de1fe2002-06-02 16:09:01 +00002049 if( sqliteExprIsInteger(pE, &iCol)==0 ){
2050 sqliteSetString(&pParse->zErrMsg,
2051 "ORDER BY terms must not be non-integer constants", 0);
2052 pParse->nErr++;
2053 goto select_end;
2054 }else if( iCol<=0 || iCol>pEList->nExpr ){
2055 char zBuf[2000];
2056 sprintf(zBuf,"ORDER BY column number %d out of range - should be "
2057 "between 1 and %d", iCol, pEList->nExpr);
2058 sqliteSetString(&pParse->zErrMsg, zBuf, 0);
2059 pParse->nErr++;
2060 goto select_end;
2061 }
drhcce7d172000-05-31 15:34:51 +00002062 }
2063 }
2064 }
drh22827922000-06-06 17:27:05 +00002065 if( pGroupBy ){
2066 for(i=0; i<pGroupBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002067 int iCol;
drh22827922000-06-06 17:27:05 +00002068 Expr *pE = pGroupBy->a[i].pExpr;
drh88eee382003-01-31 17:16:36 +00002069 if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2070 sqliteExprDelete(pE);
2071 pE = pGroupBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00002072 }
drh832508b2002-03-02 17:04:07 +00002073 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00002074 goto select_end;
drh22827922000-06-06 17:27:05 +00002075 }
2076 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00002077 goto select_end;
drh22827922000-06-06 17:27:05 +00002078 }
drh88eee382003-01-31 17:16:36 +00002079 if( sqliteExprIsConstant(pE) ){
2080 if( sqliteExprIsInteger(pE, &iCol)==0 ){
2081 sqliteSetString(&pParse->zErrMsg,
2082 "GROUP BY terms must not be non-integer constants", 0);
2083 pParse->nErr++;
2084 goto select_end;
2085 }else if( iCol<=0 || iCol>pEList->nExpr ){
2086 char zBuf[2000];
2087 sprintf(zBuf,"GROUP BY column number %d out of range - should be "
2088 "between 1 and %d", iCol, pEList->nExpr);
2089 sqliteSetString(&pParse->zErrMsg, zBuf, 0);
2090 pParse->nErr++;
2091 goto select_end;
2092 }
2093 }
drh22827922000-06-06 17:27:05 +00002094 }
2095 }
drhcce7d172000-05-31 15:34:51 +00002096
drh9562b552002-02-19 15:00:07 +00002097 /* Check for the special case of a min() or max() function by itself
2098 ** in the result set.
2099 */
2100 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
drh5cf8e8c2002-02-19 22:42:05 +00002101 rc = 0;
drh9562b552002-02-19 15:00:07 +00002102 goto select_end;
2103 }
2104
drhd820cb12002-02-18 03:21:45 +00002105 /* Begin generating code.
2106 */
2107 v = sqliteGetVdbe(pParse);
2108 if( v==0 ) goto select_end;
2109
drhe78e8282003-01-19 03:59:45 +00002110 /* Identify column names if we will be using them in a callback. This
2111 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002112 */
2113 if( eDest==SRT_Callback ){
2114 generateColumnNames(pParse, p->base, pTabList, pEList);
2115 }
2116
2117 /* Set the limiter
2118 */
2119 if( p->nLimit<=0 ){
drhd11d3822002-06-21 23:01:49 +00002120 p->nLimit = -1;
drh0bb28102002-05-08 11:54:14 +00002121 p->nOffset = 0;
2122 }else{
drhd11d3822002-06-21 23:01:49 +00002123 int iMem = pParse->nMem++;
2124 sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
drhbf5cd972002-06-24 12:20:23 +00002125 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
drhd11d3822002-06-21 23:01:49 +00002126 p->nLimit = iMem;
2127 if( p->nOffset<=0 ){
2128 p->nOffset = 0;
2129 }else{
2130 iMem = pParse->nMem++;
2131 sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
drhbf5cd972002-06-24 12:20:23 +00002132 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
drhd11d3822002-06-21 23:01:49 +00002133 p->nOffset = iMem;
2134 }
drh0bb28102002-05-08 11:54:14 +00002135 }
2136
drhd820cb12002-02-18 03:21:45 +00002137 /* Generate code for all sub-queries in the FROM clause
2138 */
drhad3cab52002-05-24 02:04:32 +00002139 for(i=0; i<pTabList->nSrc; i++){
drha76b5df2002-02-23 02:32:10 +00002140 if( pTabList->a[i].pSelect==0 ) continue;
drh2d0794e2002-03-03 03:03:52 +00002141 sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable, base+i,
drh1b2e0322002-03-03 02:49:51 +00002142 p, i, &isAgg);
2143 pTabList = p->pSrc;
2144 pWhere = p->pWhere;
drhacd4c692002-03-07 02:02:51 +00002145 if( eDest==SRT_Callback ){
2146 pOrderBy = p->pOrderBy;
2147 }
drh1b2e0322002-03-03 02:49:51 +00002148 pGroupBy = p->pGroupBy;
2149 pHaving = p->pHaving;
2150 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002151 }
2152
drh832508b2002-03-02 17:04:07 +00002153 /* Check to see if this is a subquery that can be "flattened" into its parent.
2154 ** If flattening is a possiblity, do so and return immediately.
2155 */
drh1b2e0322002-03-03 02:49:51 +00002156 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002157 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002158 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002159 return rc;
2160 }
drh832508b2002-03-02 17:04:07 +00002161
drhe78e8282003-01-19 03:59:45 +00002162 /* Identify column types if we will be using a callback. This
2163 ** step is skipped if the output is going to a destination other
2164 ** than a callback.
drhfcb78a42003-01-18 20:11:05 +00002165 */
2166 if( eDest==SRT_Callback ){
2167 generateColumnTypes(pParse, p->base, pTabList, pEList);
2168 }
2169
drh2d0794e2002-03-03 03:03:52 +00002170 /* If the output is destined for a temporary table, open that table.
2171 */
2172 if( eDest==SRT_TempTable ){
2173 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
2174 }
2175
drh22827922000-06-06 17:27:05 +00002176 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002177 */
drhd820cb12002-02-18 03:21:45 +00002178 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002179 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002180 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002181 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002182 for(i=0; i<pEList->nExpr; i++){
2183 if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002184 goto select_end;
drh22827922000-06-06 17:27:05 +00002185 }
2186 }
2187 if( pGroupBy ){
2188 for(i=0; i<pGroupBy->nExpr; i++){
2189 if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002190 goto select_end;
drh22827922000-06-06 17:27:05 +00002191 }
2192 }
2193 }
2194 if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002195 goto select_end;
drh22827922000-06-06 17:27:05 +00002196 }
drh191b6902000-06-08 11:13:01 +00002197 if( pOrderBy ){
2198 for(i=0; i<pOrderBy->nExpr; i++){
2199 if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002200 goto select_end;
drh191b6902000-06-08 11:13:01 +00002201 }
2202 }
2203 }
drhefb72512000-05-31 20:00:52 +00002204 }
2205
drh22827922000-06-06 17:27:05 +00002206 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002207 */
2208 if( isAgg ){
drh99fcd712001-10-13 01:06:47 +00002209 sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002210 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002211 FuncDef *pFunc;
2212 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drh1350b032002-02-27 19:00:20 +00002213 sqliteVdbeAddOp(v, OP_AggInit, 0, i);
drh0bce8352002-02-28 00:41:10 +00002214 sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
drhe5095352002-02-24 03:25:14 +00002215 }
2216 }
drh1bee3d72001-10-15 00:44:35 +00002217 if( pGroupBy==0 ){
2218 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002219 sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002220 }
drhcce7d172000-05-31 15:34:51 +00002221 }
2222
drh19a775c2000-06-05 18:54:46 +00002223 /* Initialize the memory cell to NULL
2224 */
drhfef52082000-06-06 01:50:43 +00002225 if( eDest==SRT_Mem ){
drh99fcd712001-10-13 01:06:47 +00002226 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh8721ce42001-11-07 14:22:00 +00002227 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002228 }
2229
drh832508b2002-03-02 17:04:07 +00002230 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002231 */
drh19a775c2000-06-05 18:54:46 +00002232 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002233 distinct = pParse->nTab++;
drhc6b52df2002-01-04 03:09:29 +00002234 sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
drh832508b2002-03-02 17:04:07 +00002235 }else{
2236 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002237 }
drh832508b2002-03-02 17:04:07 +00002238
2239 /* Begin the database scan
2240 */
drh68d2e592002-08-04 00:52:38 +00002241 pWInfo = sqliteWhereBegin(pParse, p->base, pTabList, pWhere, 0,
2242 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002243 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002244
drh22827922000-06-06 17:27:05 +00002245 /* Use the standard inner loop if we are not dealing with
2246 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002247 */
drhda9d6c42000-05-31 18:20:14 +00002248 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002249 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2250 iParm, pWInfo->iContinue, pWInfo->iBreak) ){
drh1d83f052002-02-17 00:30:36 +00002251 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002252 }
drhcce7d172000-05-31 15:34:51 +00002253 }
drhefb72512000-05-31 20:00:52 +00002254
drhe3184742002-06-19 14:27:05 +00002255 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002256 ** processing.
drhefb72512000-05-31 20:00:52 +00002257 */
drh22827922000-06-06 17:27:05 +00002258 else{
drh22827922000-06-06 17:27:05 +00002259 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002260 int lbl1;
drh22827922000-06-06 17:27:05 +00002261 for(i=0; i<pGroupBy->nExpr; i++){
2262 sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
2263 }
drh99fcd712001-10-13 01:06:47 +00002264 sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
drh491791a2002-07-18 00:34:09 +00002265 if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pGroupBy);
drh1bee3d72001-10-15 00:44:35 +00002266 lbl1 = sqliteVdbeMakeLabel(v);
drh99fcd712001-10-13 01:06:47 +00002267 sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh22827922000-06-06 17:27:05 +00002268 for(i=0; i<pParse->nAgg; i++){
2269 if( pParse->aAgg[i].isAgg ) continue;
2270 sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
drh99fcd712001-10-13 01:06:47 +00002271 sqliteVdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002272 }
drh22827922000-06-06 17:27:05 +00002273 sqliteVdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002274 }
drh22827922000-06-06 17:27:05 +00002275 for(i=0; i<pParse->nAgg; i++){
2276 Expr *pE;
drh0bce8352002-02-28 00:41:10 +00002277 int j;
drh22827922000-06-06 17:27:05 +00002278 if( !pParse->aAgg[i].isAgg ) continue;
2279 pE = pParse->aAgg[i].pExpr;
drh22827922000-06-06 17:27:05 +00002280 assert( pE->op==TK_AGG_FUNCTION );
drh0bce8352002-02-28 00:41:10 +00002281 if( pE->pList ){
2282 for(j=0; j<pE->pList->nExpr; j++){
2283 sqliteExprCode(pParse, pE->pList->a[j].pExpr);
2284 }
drhe5095352002-02-24 03:25:14 +00002285 }
drh0bce8352002-02-28 00:41:10 +00002286 sqliteVdbeAddOp(v, OP_Integer, i, 0);
drhf55f25f2002-02-28 01:46:11 +00002287 sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
drh0bce8352002-02-28 00:41:10 +00002288 assert( pParse->aAgg[i].pFunc!=0 );
2289 assert( pParse->aAgg[i].pFunc->xStep!=0 );
2290 sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002291 }
drhcce7d172000-05-31 15:34:51 +00002292 }
2293
2294 /* End the database scan loop.
2295 */
2296 sqliteWhereEnd(pWInfo);
2297
drh22827922000-06-06 17:27:05 +00002298 /* If we are processing aggregates, we need to set up a second loop
2299 ** over all of the aggregate values and process them.
2300 */
2301 if( isAgg ){
2302 int endagg = sqliteVdbeMakeLabel(v);
2303 int startagg;
drh99fcd712001-10-13 01:06:47 +00002304 startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002305 pParse->useAgg = 1;
2306 if( pHaving ){
drhf5905aa2002-05-26 20:54:33 +00002307 sqliteExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002308 }
drhdf199a22002-06-14 22:38:41 +00002309 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2310 iParm, startagg, endagg) ){
drh1d83f052002-02-17 00:30:36 +00002311 goto select_end;
drh22827922000-06-06 17:27:05 +00002312 }
drh99fcd712001-10-13 01:06:47 +00002313 sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
2314 sqliteVdbeResolveLabel(v, endagg);
2315 sqliteVdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002316 pParse->useAgg = 0;
2317 }
2318
drhcce7d172000-05-31 15:34:51 +00002319 /* If there is an ORDER BY clause, then we need to sort the results
2320 ** and send them to the callback one by one.
2321 */
2322 if( pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00002323 generateSortTail(p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002324 }
drh6a535342001-10-19 16:44:56 +00002325
2326
2327 /* Issue a null callback if that is what the user wants.
2328 */
drh326dce72003-01-29 14:06:07 +00002329 if( eDest==SRT_Callback &&
2330 (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
2331 ){
drh6a535342001-10-19 16:44:56 +00002332 sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
2333 }
2334
drh1d83f052002-02-17 00:30:36 +00002335 /* The SELECT was successfully coded. Set the return code to 0
2336 ** to indicate no errors.
2337 */
2338 rc = 0;
2339
2340 /* Control jumps to here if an error is encountered above, or upon
2341 ** successful coding of the SELECT.
2342 */
2343select_end:
2344 sqliteAggregateInfoReset(pParse);
2345 return rc;
drhcce7d172000-05-31 15:34:51 +00002346}