blob: 48283550f36c734d024cca4691ed446734d58157 [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**
drhd24cc422003-03-27 12:51:24 +000015** $Id: select.c,v 1.128 2003/03/27 12:51:25 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 =
drhd24cc422003-03-27 12:51:24 +0000915 sqliteFindTable(pParse->db, pTabList->a[i].zName,
916 pTabList->a[i].zDatabase);
drha76b5df2002-02-23 02:32:10 +0000917 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000918 sqliteSetString(&pParse->zErrMsg, "no such table: ",
919 pTabList->a[i].zName, 0);
920 pParse->nErr++;
921 return 1;
922 }
drha76b5df2002-02-23 02:32:10 +0000923 if( pTab->pSelect ){
drh417be792002-03-03 18:59:40 +0000924 if( sqliteViewGetColumnNames(pParse, pTab) ){
925 return 1;
926 }
drhd94a6692002-08-25 18:29:11 +0000927 sqliteSelectDelete(pTabList->a[i].pSelect);
drhff78bd22002-02-27 01:47:11 +0000928 pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
drha76b5df2002-02-23 02:32:10 +0000929 }
drhd8bc7082000-06-07 23:51:50 +0000930 }
931 }
932
drhad2d8302002-05-24 20:31:36 +0000933 /* Process NATURAL keywords, and ON and USING clauses of joins.
934 */
935 if( sqliteProcessJoin(pParse, p) ) return 1;
936
drh7c917d12001-12-16 20:05:05 +0000937 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000938 ** all columns in all tables. And for every TABLE.* insert the names
939 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000940 ** with the TK_ALL operator for each "*" that it found in the column list.
941 ** The following code just has to locate the TK_ALL expressions and expand
942 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000943 **
944 ** The first loop just checks to see if there are any "*" operators
945 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000946 */
drh7c917d12001-12-16 20:05:05 +0000947 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000948 Expr *pE = pEList->a[k].pExpr;
949 if( pE->op==TK_ALL ) break;
950 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
951 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000952 }
drh54473222002-04-04 02:10:55 +0000953 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000954 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000955 /*
956 ** If we get here it means the result set contains one or more "*"
957 ** operators that need to be expanded. Loop through each expression
958 ** in the result set and expand them one by one.
959 */
drh7c917d12001-12-16 20:05:05 +0000960 struct ExprList_item *a = pEList->a;
961 ExprList *pNew = 0;
962 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000963 Expr *pE = a[k].pExpr;
964 if( pE->op!=TK_ALL &&
965 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
966 /* This particular expression does not need to be expanded.
967 */
drh7c917d12001-12-16 20:05:05 +0000968 pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
969 pNew->a[pNew->nExpr-1].zName = a[k].zName;
970 a[k].pExpr = 0;
971 a[k].zName = 0;
972 }else{
drh54473222002-04-04 02:10:55 +0000973 /* This expression is a "*" or a "TABLE.*" and needs to be
974 ** expanded. */
975 int tableSeen = 0; /* Set to 1 when TABLE matches */
976 Token *pName; /* text of name of TABLE */
977 if( pE->op==TK_DOT && pE->pLeft ){
978 pName = &pE->pLeft->token;
979 }else{
980 pName = 0;
981 }
drhad3cab52002-05-24 02:04:32 +0000982 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000983 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000984 char *zTabName = pTabList->a[i].zAlias;
985 if( zTabName==0 || zTabName[0]==0 ){
986 zTabName = pTab->zName;
987 }
drhc754fa52002-05-27 03:25:51 +0000988 if( pName && (zTabName==0 || zTabName[0]==0 ||
989 sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
990 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +0000991 continue;
992 }
993 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +0000994 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000995 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +0000996 char *zName = pTab->aCol[j].zName;
997
998 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
999 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
1000 /* In a NATURAL join, omit the join columns from the
1001 ** table on the right */
1002 continue;
1003 }
1004 if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
1005 /* In a join with a USING clause, omit columns in the
1006 ** using clause from the table on the right. */
1007 continue;
1008 }
drh22f70c32002-02-18 01:17:00 +00001009 pRight = sqliteExpr(TK_ID, 0, 0, 0);
1010 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +00001011 pRight->token.z = zName;
1012 pRight->token.n = strlen(zName);
drh4b59ab52002-08-24 18:24:51 +00001013 pRight->token.dyn = 0;
drh4b59ab52002-08-24 18:24:51 +00001014 if( zTabName && pTabList->nSrc>1 ){
drh22f70c32002-02-18 01:17:00 +00001015 pLeft = sqliteExpr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001016 pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
1017 if( pExpr==0 ) break;
drh4b59ab52002-08-24 18:24:51 +00001018 pLeft->token.z = zTabName;
1019 pLeft->token.n = strlen(zTabName);
1020 pLeft->token.dyn = 0;
drh6977fea2002-10-22 23:38:04 +00001021 sqliteSetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
1022 pExpr->span.n = strlen(pExpr->span.z);
1023 pExpr->span.dyn = 1;
1024 pExpr->token.z = 0;
1025 pExpr->token.n = 0;
1026 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001027 }else{
drh22f70c32002-02-18 01:17:00 +00001028 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001029 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001030 }
drh7c917d12001-12-16 20:05:05 +00001031 pNew = sqliteExprListAppend(pNew, pExpr, 0);
1032 }
drh17e24df2001-11-06 14:10:41 +00001033 }
drh54473222002-04-04 02:10:55 +00001034 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +00001035 if( pName ){
1036 sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1,
1037 pName->z, pName->n, 0);
1038 }else{
1039 sqliteSetString(&pParse->zErrMsg, "no tables specified", 0);
1040 }
drh54473222002-04-04 02:10:55 +00001041 rc = 1;
1042 }
drhd8bc7082000-06-07 23:51:50 +00001043 }
1044 }
drh7c917d12001-12-16 20:05:05 +00001045 sqliteExprListDelete(pEList);
1046 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001047 }
drh54473222002-04-04 02:10:55 +00001048 return rc;
drhd8bc7082000-06-07 23:51:50 +00001049}
1050
1051/*
drhff78bd22002-02-27 01:47:11 +00001052** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1053** in a select structure. It just sets the pointers to NULL. This
1054** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1055** pointer is not NULL, this routine is called recursively on that pointer.
1056**
1057** This routine is called on the Select structure that defines a
1058** VIEW in order to undo any bindings to tables. This is necessary
1059** because those tables might be DROPed by a subsequent SQL command.
1060*/
1061void sqliteSelectUnbind(Select *p){
1062 int i;
drhad3cab52002-05-24 02:04:32 +00001063 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +00001064 Table *pTab;
1065 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +00001066 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +00001067 if( (pTab = pSrc->a[i].pTab)!=0 ){
1068 if( pTab->isTransient ){
1069 sqliteDeleteTable(0, pTab);
drh4b59ab52002-08-24 18:24:51 +00001070#if 0
drhff78bd22002-02-27 01:47:11 +00001071 sqliteSelectDelete(pSrc->a[i].pSelect);
1072 pSrc->a[i].pSelect = 0;
drh4b59ab52002-08-24 18:24:51 +00001073#endif
drhff78bd22002-02-27 01:47:11 +00001074 }
1075 pSrc->a[i].pTab = 0;
1076 if( pSrc->a[i].pSelect ){
1077 sqliteSelectUnbind(pSrc->a[i].pSelect);
1078 }
1079 }
1080 }
1081}
1082
1083/*
drhd8bc7082000-06-07 23:51:50 +00001084** This routine associates entries in an ORDER BY expression list with
1085** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001086** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001087** the top-level node is filled in with column number and the iTable
1088** value of the top-level node is filled with iTable parameter.
1089**
1090** If there are prior SELECT clauses, they are processed first. A match
1091** in an earlier SELECT takes precedence over a later SELECT.
1092**
1093** Any entry that does not match is flagged as an error. The number
1094** of errors is returned.
drhfcb78a42003-01-18 20:11:05 +00001095**
1096** This routine does NOT correctly initialize the Expr.dataType field
1097** of the ORDER BY expressions. The multiSelectSortOrder() routine
1098** must be called to do that after the individual select statements
1099** have all been analyzed. This routine is unable to compute Expr.dataType
1100** because it must be called before the individual select statements
1101** have been analyzed.
drhd8bc7082000-06-07 23:51:50 +00001102*/
1103static int matchOrderbyToColumn(
1104 Parse *pParse, /* A place to leave error messages */
1105 Select *pSelect, /* Match to result columns of this SELECT */
1106 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001107 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001108 int mustComplete /* If TRUE all ORDER BYs must match */
1109){
1110 int nErr = 0;
1111 int i, j;
1112 ExprList *pEList;
1113
drhdaffd0e2001-04-11 14:28:42 +00001114 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001115 if( mustComplete ){
1116 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1117 }
1118 if( fillInColumnList(pParse, pSelect) ){
1119 return 1;
1120 }
1121 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001122 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1123 return 1;
1124 }
drhd8bc7082000-06-07 23:51:50 +00001125 }
1126 pEList = pSelect->pEList;
1127 for(i=0; i<pOrderBy->nExpr; i++){
1128 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001129 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001130 if( pOrderBy->a[i].done ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001131 if( sqliteExprIsInteger(pE, &iCol) ){
1132 if( iCol<=0 || iCol>pEList->nExpr ){
1133 char zBuf[200];
1134 sprintf(zBuf,"ORDER BY position %d should be between 1 and %d",
1135 iCol, pEList->nExpr);
1136 sqliteSetString(&pParse->zErrMsg, zBuf, 0);
1137 pParse->nErr++;
1138 nErr++;
1139 break;
1140 }
drhfcb78a42003-01-18 20:11:05 +00001141 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001142 iCol--;
1143 }
1144 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001145 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001146 char *zName, *zLabel;
1147 zName = pEList->a[j].zName;
1148 assert( pE->token.z );
1149 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
drhd8bc7082000-06-07 23:51:50 +00001150 sqliteDequote(zLabel);
1151 if( sqliteStrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001152 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001153 }
drh6e142f52000-06-08 13:36:40 +00001154 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001155 }
drhe4de1fe2002-06-02 16:09:01 +00001156 if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
1157 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001158 }
1159 }
drhe4de1fe2002-06-02 16:09:01 +00001160 if( iCol>=0 ){
1161 pE->op = TK_COLUMN;
1162 pE->iColumn = iCol;
1163 pE->iTable = iTable;
1164 pOrderBy->a[i].done = 1;
1165 }
1166 if( iCol<0 && mustComplete ){
drhd8bc7082000-06-07 23:51:50 +00001167 char zBuf[30];
1168 sprintf(zBuf,"%d",i+1);
1169 sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf,
1170 " does not match any result column", 0);
1171 pParse->nErr++;
1172 nErr++;
1173 break;
1174 }
1175 }
1176 return nErr;
1177}
1178
1179/*
1180** Get a VDBE for the given parser context. Create a new one if necessary.
1181** If an error occurs, return NULL and leave a message in pParse.
1182*/
1183Vdbe *sqliteGetVdbe(Parse *pParse){
1184 Vdbe *v = pParse->pVdbe;
1185 if( v==0 ){
drh4c504392000-10-16 22:06:40 +00001186 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001187 }
drhd8bc7082000-06-07 23:51:50 +00001188 return v;
1189}
drhfcb78a42003-01-18 20:11:05 +00001190
1191/*
1192** This routine sets the Expr.dataType field on all elements of
1193** the pOrderBy expression list. The pOrderBy list will have been
1194** set up by matchOrderbyToColumn(). Hence each expression has
1195** a TK_COLUMN as its root node. The Expr.iColumn refers to a
1196** column in the result set. The datatype is set to SQLITE_SO_TEXT
1197** if the corresponding column in p and every SELECT to the left of
1198** p has a datatype of SQLITE_SO_TEXT. If the cooressponding column
1199** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
1200** of the order-by expression is set to SQLITE_SO_NUM.
1201**
1202** Examples:
1203**
drhe78e8282003-01-19 03:59:45 +00001204** CREATE TABLE one(a INTEGER, b TEXT);
1205** CREATE TABLE two(c VARCHAR(5), d FLOAT);
1206**
1207** SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
1208**
1209** The primary sort key will use SQLITE_SO_NUM because the "d" in
1210** the second SELECT is numeric. The 1st column of the first SELECT
1211** is text but that does not matter because a numeric always overrides
1212** a text.
1213**
1214** The secondary key will use the SQLITE_SO_TEXT sort order because
1215** both the (second) "b" in the first SELECT and the "c" in the second
1216** SELECT have a datatype of text.
drhfcb78a42003-01-18 20:11:05 +00001217*/
1218static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
1219 int i;
1220 ExprList *pEList;
1221 if( pOrderBy==0 ) return;
1222 if( p==0 ){
1223 for(i=0; i<pOrderBy->nExpr; i++){
1224 pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
1225 }
1226 return;
1227 }
1228 multiSelectSortOrder(p->pPrior, pOrderBy);
1229 pEList = p->pEList;
1230 for(i=0; i<pOrderBy->nExpr; i++){
1231 Expr *pE = pOrderBy->a[i].pExpr;
1232 if( pE->dataType==SQLITE_SO_NUM ) continue;
1233 assert( pE->iColumn>=0 );
1234 if( pEList->nExpr>pE->iColumn ){
1235 pE->dataType = sqliteExprType(pEList->a[pE->iColumn].pExpr);
1236 }
1237 }
1238}
drhd8bc7082000-06-07 23:51:50 +00001239
1240/*
drh82c3d632000-06-06 21:56:07 +00001241** This routine is called to process a query that is really the union
1242** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001243**
drhe78e8282003-01-19 03:59:45 +00001244** "p" points to the right-most of the two queries. the query on the
1245** left is p->pPrior. The left query could also be a compound query
1246** in which case this routine will be called recursively.
1247**
1248** The results of the total query are to be written into a destination
1249** of type eDest with parameter iParm.
1250**
1251** Example 1: Consider a three-way compound SQL statement.
1252**
1253** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1254**
1255** This statement is parsed up as follows:
1256**
1257** SELECT c FROM t3
1258** |
1259** `-----> SELECT b FROM t2
1260** |
1261** `------> SELECT c FROM t1
1262**
1263** The arrows in the diagram above represent the Select.pPrior pointer.
1264** So if this routine is called with p equal to the t3 query, then
1265** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1266**
1267** Notice that because of the way SQLite parses compound SELECTs, the
1268** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001269*/
1270static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
drh10e5e3c2000-06-08 00:19:02 +00001271 int rc; /* Success code from a subroutine */
1272 Select *pPrior; /* Another SELECT immediately to our left */
1273 Vdbe *v; /* Generate code to this VDBE */
drh82c3d632000-06-06 21:56:07 +00001274
drhd8bc7082000-06-07 23:51:50 +00001275 /* Make sure there is no ORDER BY clause on prior SELECTs. Only the
1276 ** last SELECT in the series may have an ORDER BY.
drh82c3d632000-06-06 21:56:07 +00001277 */
drhdaffd0e2001-04-11 14:28:42 +00001278 if( p==0 || p->pPrior==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001279 pPrior = p->pPrior;
1280 if( pPrior->pOrderBy ){
1281 sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
1282 selectOpName(p->op), " not before", 0);
drh82c3d632000-06-06 21:56:07 +00001283 pParse->nErr++;
1284 return 1;
1285 }
1286
drhd8bc7082000-06-07 23:51:50 +00001287 /* Make sure we have a valid query engine. If not, create a new one.
1288 */
1289 v = sqliteGetVdbe(pParse);
1290 if( v==0 ) return 1;
1291
drh1cc3d752002-03-23 00:31:29 +00001292 /* Create the destination temporary table if necessary
1293 */
1294 if( eDest==SRT_TempTable ){
1295 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
1296 eDest = SRT_Table;
1297 }
1298
drhf46f9052002-06-22 02:33:38 +00001299 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001300 */
drh82c3d632000-06-06 21:56:07 +00001301 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001302 case TK_ALL: {
1303 if( p->pOrderBy==0 ){
1304 rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
1305 if( rc ) return rc;
1306 p->pPrior = 0;
1307 rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
1308 p->pPrior = pPrior;
1309 if( rc ) return rc;
1310 break;
1311 }
1312 /* For UNION ALL ... ORDER BY fall through to the next case */
1313 }
drh82c3d632000-06-06 21:56:07 +00001314 case TK_EXCEPT:
1315 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001316 int unionTab; /* Cursor number of the temporary table holding result */
1317 int op; /* One of the SRT_ operations to apply to self */
1318 int priorOp; /* The SRT_ operation to apply to prior selects */
drhc926afb2002-06-20 03:38:26 +00001319 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
drh82c3d632000-06-06 21:56:07 +00001320
drhd8bc7082000-06-07 23:51:50 +00001321 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drhc926afb2002-06-20 03:38:26 +00001322 if( eDest==priorOp && p->pOrderBy==0 ){
drhd8bc7082000-06-07 23:51:50 +00001323 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001324 ** right.
drhd8bc7082000-06-07 23:51:50 +00001325 */
drh82c3d632000-06-06 21:56:07 +00001326 unionTab = iParm;
1327 }else{
drhd8bc7082000-06-07 23:51:50 +00001328 /* We will need to create our own temporary table to hold the
1329 ** intermediate results.
1330 */
1331 unionTab = pParse->nTab++;
1332 if( p->pOrderBy
1333 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1334 return 1;
1335 }
drhd8bc7082000-06-07 23:51:50 +00001336 if( p->op!=TK_ALL ){
drhc6b52df2002-01-04 03:09:29 +00001337 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
drh99fcd712001-10-13 01:06:47 +00001338 sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drh345fda32001-01-15 22:51:08 +00001339 }else{
drh99fcd712001-10-13 01:06:47 +00001340 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001341 }
drh82c3d632000-06-06 21:56:07 +00001342 }
drhd8bc7082000-06-07 23:51:50 +00001343
1344 /* Code the SELECT statements to our left
1345 */
drh832508b2002-03-02 17:04:07 +00001346 rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001347 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001348
1349 /* Code the current SELECT statement
1350 */
1351 switch( p->op ){
1352 case TK_EXCEPT: op = SRT_Except; break;
1353 case TK_UNION: op = SRT_Union; break;
1354 case TK_ALL: op = SRT_Table; break;
1355 }
drh82c3d632000-06-06 21:56:07 +00001356 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001357 pOrderBy = p->pOrderBy;
1358 p->pOrderBy = 0;
drh832508b2002-03-02 17:04:07 +00001359 rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001360 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001361 p->pOrderBy = pOrderBy;
drh82c3d632000-06-06 21:56:07 +00001362 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001363
1364 /* Convert the data in the temporary table into whatever form
1365 ** it is that we currently need.
1366 */
drhc926afb2002-06-20 03:38:26 +00001367 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001368 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001369 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001370 if( eDest==SRT_Callback ){
1371 generateColumnNames(pParse, p->base, 0, p->pEList);
drhfcb78a42003-01-18 20:11:05 +00001372 generateColumnTypes(pParse, p->base, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001373 }
drh82c3d632000-06-06 21:56:07 +00001374 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001375 iCont = sqliteVdbeMakeLabel(v);
1376 sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
1377 iStart = sqliteVdbeCurrentAddr(v);
drhfcb78a42003-01-18 20:11:05 +00001378 multiSelectSortOrder(p, p->pOrderBy);
drh38640e12002-07-05 21:42:36 +00001379 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001380 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001381 iCont, iBreak);
1382 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001383 sqliteVdbeResolveLabel(v, iCont);
1384 sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
drh99fcd712001-10-13 01:06:47 +00001385 sqliteVdbeResolveLabel(v, iBreak);
1386 sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001387 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001388 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001389 }
drh82c3d632000-06-06 21:56:07 +00001390 }
1391 break;
1392 }
1393 case TK_INTERSECT: {
1394 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001395 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001396
drhd8bc7082000-06-07 23:51:50 +00001397 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001398 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001399 ** by allocating the tables we will need.
1400 */
drh82c3d632000-06-06 21:56:07 +00001401 tab1 = pParse->nTab++;
1402 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001403 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1404 return 1;
1405 }
drhc6b52df2002-01-04 03:09:29 +00001406 sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
drh99fcd712001-10-13 01:06:47 +00001407 sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
drhd8bc7082000-06-07 23:51:50 +00001408
1409 /* Code the SELECTs to our left into temporary table "tab1".
1410 */
drh832508b2002-03-02 17:04:07 +00001411 rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001412 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001413
1414 /* Code the current SELECT into temporary table "tab2"
1415 */
drhc6b52df2002-01-04 03:09:29 +00001416 sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
drh99fcd712001-10-13 01:06:47 +00001417 sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001418 p->pPrior = 0;
drh832508b2002-03-02 17:04:07 +00001419 rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001420 p->pPrior = pPrior;
1421 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001422
1423 /* Generate code to take the intersection of the two temporary
1424 ** tables.
1425 */
drh82c3d632000-06-06 21:56:07 +00001426 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001427 if( eDest==SRT_Callback ){
1428 generateColumnNames(pParse, p->base, 0, p->pEList);
drhfcb78a42003-01-18 20:11:05 +00001429 generateColumnTypes(pParse, p->base, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001430 }
drh82c3d632000-06-06 21:56:07 +00001431 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001432 iCont = sqliteVdbeMakeLabel(v);
1433 sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
1434 iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
drh99fcd712001-10-13 01:06:47 +00001435 sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
drhfcb78a42003-01-18 20:11:05 +00001436 multiSelectSortOrder(p, p->pOrderBy);
drh38640e12002-07-05 21:42:36 +00001437 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001438 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001439 iCont, iBreak);
1440 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001441 sqliteVdbeResolveLabel(v, iCont);
1442 sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
drh99fcd712001-10-13 01:06:47 +00001443 sqliteVdbeResolveLabel(v, iBreak);
1444 sqliteVdbeAddOp(v, OP_Close, tab2, 0);
1445 sqliteVdbeAddOp(v, OP_Close, tab1, 0);
drhd8bc7082000-06-07 23:51:50 +00001446 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001447 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001448 }
drh82c3d632000-06-06 21:56:07 +00001449 break;
1450 }
1451 }
1452 assert( p->pEList && pPrior->pEList );
1453 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
drhd8bc7082000-06-07 23:51:50 +00001454 sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ",
1455 selectOpName(p->op), " do not have the same number of result columns", 0);
drh82c3d632000-06-06 21:56:07 +00001456 pParse->nErr++;
1457 return 1;
drh22827922000-06-06 17:27:05 +00001458 }
drhfcb78a42003-01-18 20:11:05 +00001459
1460 /* Issue a null callback if that is what the user wants.
1461 */
drh326dce72003-01-29 14:06:07 +00001462 if( eDest==SRT_Callback &&
1463 (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
1464 ){
drhfcb78a42003-01-18 20:11:05 +00001465 sqliteVdbeAddOp(v, OP_NullCallback, p->pEList->nExpr, 0);
1466 }
drh22827922000-06-06 17:27:05 +00001467 return 0;
1468}
1469
1470/*
drh832508b2002-03-02 17:04:07 +00001471** Recursively scan through an expression tree. For every reference
1472** to a column in table number iFrom, change that reference to the
1473** same column in table number iTo.
1474*/
drh315555c2002-10-20 15:53:03 +00001475static void changeTablesInList(ExprList*, int, int); /* Forward Declaration */
drh832508b2002-03-02 17:04:07 +00001476static void changeTables(Expr *pExpr, int iFrom, int iTo){
1477 if( pExpr==0 ) return;
1478 if( pExpr->op==TK_COLUMN && pExpr->iTable==iFrom ){
1479 pExpr->iTable = iTo;
1480 }else{
1481 changeTables(pExpr->pLeft, iFrom, iTo);
1482 changeTables(pExpr->pRight, iFrom, iTo);
drh1b2e0322002-03-03 02:49:51 +00001483 changeTablesInList(pExpr->pList, iFrom, iTo);
1484 }
1485}
1486static void changeTablesInList(ExprList *pList, int iFrom, int iTo){
1487 if( pList ){
1488 int i;
1489 for(i=0; i<pList->nExpr; i++){
1490 changeTables(pList->a[i].pExpr, iFrom, iTo);
drh832508b2002-03-02 17:04:07 +00001491 }
1492 }
1493}
1494
1495/*
1496** Scan through the expression pExpr. Replace every reference to
1497** a column in table number iTable with a copy of the corresponding
drh84e59202002-03-14 14:33:31 +00001498** entry in pEList. (But leave references to the ROWID column
1499** unchanged.) When making a copy of an expression in pEList, change
1500** references to columns in table iSub into references to table iTable.
drh832508b2002-03-02 17:04:07 +00001501**
1502** This routine is part of the flattening procedure. A subquery
1503** whose result set is defined by pEList appears as entry in the
1504** FROM clause of a SELECT such that the VDBE cursor assigned to that
1505** FORM clause entry is iTable. This routine make the necessary
1506** changes to pExpr so that it refers directly to the source table
1507** of the subquery rather the result set of the subquery.
1508*/
drh315555c2002-10-20 15:53:03 +00001509static void substExprList(ExprList*,int,ExprList*,int); /* Forward Decl */
drh832508b2002-03-02 17:04:07 +00001510static void substExpr(Expr *pExpr, int iTable, ExprList *pEList, int iSub){
1511 if( pExpr==0 ) return;
drh84e59202002-03-14 14:33:31 +00001512 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){
drh832508b2002-03-02 17:04:07 +00001513 Expr *pNew;
drh84e59202002-03-14 14:33:31 +00001514 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
drh832508b2002-03-02 17:04:07 +00001515 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1516 pNew = pEList->a[pExpr->iColumn].pExpr;
1517 assert( pNew!=0 );
1518 pExpr->op = pNew->op;
drhfcb78a42003-01-18 20:11:05 +00001519 pExpr->dataType = pNew->dataType;
drhd94a6692002-08-25 18:29:11 +00001520 assert( pExpr->pLeft==0 );
drh832508b2002-03-02 17:04:07 +00001521 pExpr->pLeft = sqliteExprDup(pNew->pLeft);
drhd94a6692002-08-25 18:29:11 +00001522 assert( pExpr->pRight==0 );
drh832508b2002-03-02 17:04:07 +00001523 pExpr->pRight = sqliteExprDup(pNew->pRight);
drhd94a6692002-08-25 18:29:11 +00001524 assert( pExpr->pList==0 );
drh832508b2002-03-02 17:04:07 +00001525 pExpr->pList = sqliteExprListDup(pNew->pList);
1526 pExpr->iTable = pNew->iTable;
1527 pExpr->iColumn = pNew->iColumn;
1528 pExpr->iAgg = pNew->iAgg;
drh4b59ab52002-08-24 18:24:51 +00001529 sqliteTokenCopy(&pExpr->token, &pNew->token);
drh6977fea2002-10-22 23:38:04 +00001530 sqliteTokenCopy(&pExpr->span, &pNew->span);
drh832508b2002-03-02 17:04:07 +00001531 if( iSub!=iTable ){
1532 changeTables(pExpr, iSub, iTable);
1533 }
1534 }else{
drh832508b2002-03-02 17:04:07 +00001535 substExpr(pExpr->pLeft, iTable, pEList, iSub);
1536 substExpr(pExpr->pRight, iTable, pEList, iSub);
1537 substExprList(pExpr->pList, iTable, pEList, iSub);
1538 }
1539}
1540static void
1541substExprList(ExprList *pList, int iTable, ExprList *pEList, int iSub){
1542 int i;
1543 if( pList==0 ) return;
1544 for(i=0; i<pList->nExpr; i++){
1545 substExpr(pList->a[i].pExpr, iTable, pEList, iSub);
1546 }
1547}
1548
1549/*
drh1350b032002-02-27 19:00:20 +00001550** This routine attempts to flatten subqueries in order to speed
1551** execution. It returns 1 if it makes changes and 0 if no flattening
1552** occurs.
1553**
1554** To understand the concept of flattening, consider the following
1555** query:
1556**
1557** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1558**
1559** The default way of implementing this query is to execute the
1560** subquery first and store the results in a temporary table, then
1561** run the outer query on that temporary table. This requires two
1562** passes over the data. Furthermore, because the temporary table
1563** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001564** optimized.
drh1350b032002-02-27 19:00:20 +00001565**
drh832508b2002-03-02 17:04:07 +00001566** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001567** a single flat select, like this:
1568**
1569** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1570**
1571** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001572** but only has to scan the data once. And because indices might
1573** exist on the table t1, a complete scan of the data might be
1574** avoided.
drh1350b032002-02-27 19:00:20 +00001575**
drh832508b2002-03-02 17:04:07 +00001576** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001577**
drh832508b2002-03-02 17:04:07 +00001578** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001579**
drh832508b2002-03-02 17:04:07 +00001580** (2) The subquery is not an aggregate or the outer query is not a join.
1581**
1582** (3) The subquery is not a join.
1583**
1584** (4) The subquery is not DISTINCT or the outer query is not a join.
1585**
1586** (5) The subquery is not DISTINCT or the outer query does not use
1587** aggregates.
1588**
1589** (6) The subquery does not use aggregates or the outer query is not
1590** DISTINCT.
1591**
drh08192d52002-04-30 19:20:28 +00001592** (7) The subquery has a FROM clause.
1593**
drhdf199a22002-06-14 22:38:41 +00001594** (8) The subquery does not use LIMIT or the outer query is not a join.
1595**
1596** (9) The subquery does not use LIMIT or the outer query does not use
1597** aggregates.
1598**
1599** (10) The subquery does not use aggregates or the outer query does not
1600** use LIMIT.
1601**
drh174b6192002-12-03 02:22:52 +00001602** (11) The subquery and the outer query do not both have ORDER BY clauses.
1603**
drh832508b2002-03-02 17:04:07 +00001604** In this routine, the "p" parameter is a pointer to the outer query.
1605** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1606** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1607**
1608** If flattening is not attempted, this routine is a no-op and return 0.
1609** If flattening is attempted this routine returns 1.
1610**
1611** All of the expression analysis must occur on both the outer query and
1612** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001613*/
drh8c74a8c2002-08-25 19:20:40 +00001614static int flattenSubquery(
1615 Parse *pParse, /* The parsing context */
1616 Select *p, /* The parent or outer SELECT statement */
1617 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1618 int isAgg, /* True if outer SELECT uses aggregate functions */
1619 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1620){
drh0bb28102002-05-08 11:54:14 +00001621 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001622 SrcList *pSrc; /* The FROM clause of the outer query */
1623 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001624 ExprList *pList; /* The result set of the outer query */
drh832508b2002-03-02 17:04:07 +00001625 int i;
1626 int iParent, iSub;
1627 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001628
drh832508b2002-03-02 17:04:07 +00001629 /* Check to see if flattening is permitted. Return 0 if not.
1630 */
1631 if( p==0 ) return 0;
1632 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001633 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001634 pSub = pSrc->a[iFrom].pSelect;
1635 assert( pSub!=0 );
1636 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001637 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001638 pSubSrc = pSub->pSrc;
1639 assert( pSubSrc );
drhad3cab52002-05-24 02:04:32 +00001640 if( pSubSrc->nSrc!=1 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001641 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1642 return 0;
1643 }
drhd11d3822002-06-21 23:01:49 +00001644 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001645 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001646
drh0bb28102002-05-08 11:54:14 +00001647 /* If we reach this point, it means flattening is permitted for the
drh832508b2002-03-02 17:04:07 +00001648 ** i-th entry of the FROM clause in the outer query.
1649 */
1650 iParent = p->base + iFrom;
1651 iSub = pSub->base;
1652 substExprList(p->pEList, iParent, pSub->pEList, iSub);
1653 pList = p->pEList;
1654 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001655 Expr *pExpr;
1656 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1657 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001658 }
1659 }
drh1b2e0322002-03-03 02:49:51 +00001660 if( isAgg ){
1661 substExprList(p->pGroupBy, iParent, pSub->pEList, iSub);
1662 substExpr(p->pHaving, iParent, pSub->pEList, iSub);
1663 }
drh174b6192002-12-03 02:22:52 +00001664 if( pSub->pOrderBy ){
1665 assert( p->pOrderBy==0 );
1666 p->pOrderBy = pSub->pOrderBy;
1667 pSub->pOrderBy = 0;
1668 changeTablesInList(p->pOrderBy, iSub, iParent);
1669 }else if( p->pOrderBy ){
1670 substExprList(p->pOrderBy, iParent, pSub->pEList, iSub);
1671 }
drh832508b2002-03-02 17:04:07 +00001672 if( pSub->pWhere ){
1673 pWhere = sqliteExprDup(pSub->pWhere);
1674 if( iParent!=iSub ){
1675 changeTables(pWhere, iSub, iParent);
1676 }
1677 }else{
1678 pWhere = 0;
1679 }
1680 if( subqueryIsAgg ){
1681 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001682 p->pHaving = p->pWhere;
1683 p->pWhere = pWhere;
drh832508b2002-03-02 17:04:07 +00001684 substExpr(p->pHaving, iParent, pSub->pEList, iSub);
drh1b2e0322002-03-03 02:49:51 +00001685 if( pSub->pHaving ){
1686 Expr *pHaving = sqliteExprDup(pSub->pHaving);
1687 if( iParent!=iSub ){
1688 changeTables(pHaving, iSub, iParent);
1689 }
1690 if( p->pHaving ){
1691 p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
1692 }else{
1693 p->pHaving = pHaving;
1694 }
1695 }
1696 assert( p->pGroupBy==0 );
1697 p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
1698 if( iParent!=iSub ){
1699 changeTablesInList(p->pGroupBy, iSub, iParent);
1700 }
drh832508b2002-03-02 17:04:07 +00001701 }else if( p->pWhere==0 ){
1702 p->pWhere = pWhere;
1703 }else{
1704 substExpr(p->pWhere, iParent, pSub->pEList, iSub);
1705 if( pWhere ){
1706 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1707 }
1708 }
1709 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00001710
drhdf199a22002-06-14 22:38:41 +00001711 if( pSub->nLimit>=0 ){
1712 if( p->nLimit<0 ){
1713 p->nLimit = pSub->nLimit;
1714 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1715 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1716 }
1717 }
1718 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00001719
1720 /* If the subquery contains subqueries of its own, that were not
1721 ** flattened, then code will have already been generated to put
1722 ** the results of those sub-subqueries into VDBE cursors relative
1723 ** to the subquery. We must translate the cursor number into values
1724 ** suitable for use by the outer query.
1725 */
1726 for(i=0; i<pSubSrc->nSrc; i++){
1727 Vdbe *v;
1728 if( pSubSrc->a[i].pSelect==0 ) continue;
1729 v = sqliteGetVdbe(pParse);
1730 sqliteVdbeAddOp(v, OP_RenameCursor, pSub->base+i, p->base+i);
1731 }
1732
drh832508b2002-03-02 17:04:07 +00001733 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1734 sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1735 }
1736 pSrc->a[iFrom].pTab = pSubSrc->a[0].pTab;
1737 pSubSrc->a[0].pTab = 0;
drhd94a6692002-08-25 18:29:11 +00001738 assert( pSrc->a[iFrom].pSelect==pSub );
drh832508b2002-03-02 17:04:07 +00001739 pSrc->a[iFrom].pSelect = pSubSrc->a[0].pSelect;
1740 pSubSrc->a[0].pSelect = 0;
1741 sqliteSelectDelete(pSub);
1742 return 1;
1743}
drh1350b032002-02-27 19:00:20 +00001744
1745/*
drh9562b552002-02-19 15:00:07 +00001746** Analyze the SELECT statement passed in as an argument to see if it
1747** is a simple min() or max() query. If it is and this query can be
1748** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00001749** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00001750** simple min() or max() query, then return 0;
1751**
1752** A simply min() or max() query looks like this:
1753**
1754** SELECT min(a) FROM table;
1755** SELECT max(a) FROM table;
1756**
1757** The query may have only a single table in its FROM argument. There
1758** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1759** be the min() or max() of a single column of the table. The column
1760** in the min() or max() function must be indexed.
1761**
1762** The parameters to this routine are the same as for sqliteSelect().
1763** See the header comment on that routine for additional information.
1764*/
1765static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1766 Expr *pExpr;
1767 int iCol;
1768 Table *pTab;
1769 Index *pIdx;
1770 int base;
1771 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00001772 int seekOp;
1773 int cont;
1774 ExprList eList;
1775 struct ExprList_item eListItem;
1776
1777 /* Check to see if this query is a simple min() or max() query. Return
1778 ** zero if it is not.
1779 */
1780 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drhad3cab52002-05-24 02:04:32 +00001781 if( p->pSrc->nSrc!=1 ) return 0;
drh9562b552002-02-19 15:00:07 +00001782 if( p->pEList->nExpr!=1 ) return 0;
1783 pExpr = p->pEList->a[0].pExpr;
1784 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
1785 if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00001786 if( pExpr->token.n!=3 ) return 0;
drh0bce8352002-02-28 00:41:10 +00001787 if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
1788 seekOp = OP_Rewind;
1789 }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
1790 seekOp = OP_Last;
1791 }else{
1792 return 0;
1793 }
drh9562b552002-02-19 15:00:07 +00001794 pExpr = pExpr->pList->a[0].pExpr;
1795 if( pExpr->op!=TK_COLUMN ) return 0;
1796 iCol = pExpr->iColumn;
1797 pTab = p->pSrc->a[0].pTab;
1798
1799 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00001800 ** Check to make sure we have an index and make pIdx point to the
1801 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
1802 ** key column, no index is necessary so set pIdx to NULL. If no
1803 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00001804 */
1805 if( iCol<0 ){
1806 pIdx = 0;
1807 }else{
1808 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1809 assert( pIdx->nColumn>=1 );
1810 if( pIdx->aiColumn[0]==iCol ) break;
1811 }
1812 if( pIdx==0 ) return 0;
1813 }
1814
drh17f71932002-02-21 12:01:27 +00001815 /* Identify column names if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00001816 ** step is skipped if the output is going to a table or a memory cell.
1817 */
1818 v = sqliteGetVdbe(pParse);
1819 if( v==0 ) return 0;
1820 if( eDest==SRT_Callback ){
drh832508b2002-03-02 17:04:07 +00001821 generateColumnNames(pParse, p->base, p->pSrc, p->pEList);
drhfcb78a42003-01-18 20:11:05 +00001822 generateColumnTypes(pParse, p->base, p->pSrc, p->pEList);
drh9562b552002-02-19 15:00:07 +00001823 }
1824
drh17f71932002-02-21 12:01:27 +00001825 /* Generating code to find the min or the max. Basically all we have
1826 ** to do is find the first or the last entry in the chosen index. If
1827 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
1828 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00001829 */
drh5cf8e8c2002-02-19 22:42:05 +00001830 if( !pParse->schemaVerified && (pParse->db->flags & SQLITE_InTrans)==0 ){
drh001bbcb2003-03-19 03:14:00 +00001831 sqliteCodeVerifySchema(pParse);
drh5cf8e8c2002-02-19 22:42:05 +00001832 }
drh832508b2002-03-02 17:04:07 +00001833 base = p->base;
drhd24cc422003-03-27 12:51:24 +00001834 sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
drh001bbcb2003-03-19 03:14:00 +00001835 sqliteVdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001836 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
drh9562b552002-02-19 15:00:07 +00001837 if( pIdx==0 ){
1838 sqliteVdbeAddOp(v, seekOp, base, 0);
1839 }else{
drhd24cc422003-03-27 12:51:24 +00001840 sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
drh001bbcb2003-03-19 03:14:00 +00001841 sqliteVdbeAddOp(v, OP_OpenRead, base+1, pIdx->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001842 sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
drh9562b552002-02-19 15:00:07 +00001843 sqliteVdbeAddOp(v, seekOp, base+1, 0);
1844 sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
1845 sqliteVdbeAddOp(v, OP_Close, base+1, 0);
1846 sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
1847 }
drh5cf8e8c2002-02-19 22:42:05 +00001848 eList.nExpr = 1;
1849 memset(&eListItem, 0, sizeof(eListItem));
1850 eList.a = &eListItem;
1851 eList.a[0].pExpr = pExpr;
drh9562b552002-02-19 15:00:07 +00001852 cont = sqliteVdbeMakeLabel(v);
drh38640e12002-07-05 21:42:36 +00001853 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
drh9562b552002-02-19 15:00:07 +00001854 sqliteVdbeResolveLabel(v, cont);
1855 sqliteVdbeAddOp(v, OP_Close, base, 0);
1856 return 1;
1857}
1858
1859/*
drh9bb61fe2000-06-05 16:01:39 +00001860** Generate code for the given SELECT statement.
1861**
drhfef52082000-06-06 01:50:43 +00001862** The results are distributed in various ways depending on the
1863** value of eDest and iParm.
1864**
1865** eDest Value Result
1866** ------------ -------------------------------------------
1867** SRT_Callback Invoke the callback for each row of the result.
1868**
1869** SRT_Mem Store first result in memory cell iParm
1870**
1871** SRT_Set Store results as keys of a table with cursor iParm
1872**
drh82c3d632000-06-06 21:56:07 +00001873** SRT_Union Store results as a key in a temporary table iParm
1874**
drhc4a3c772001-04-04 11:48:57 +00001875** SRT_Except Remove results form the temporary table iParm.
1876**
1877** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00001878**
drhe78e8282003-01-19 03:59:45 +00001879** The table above is incomplete. Additional eDist value have be added
1880** since this comment was written. See the selectInnerLoop() function for
1881** a complete listing of the allowed values of eDest and their meanings.
1882**
drh9bb61fe2000-06-05 16:01:39 +00001883** This routine returns the number of errors. If any errors are
1884** encountered, then an appropriate error message is left in
1885** pParse->zErrMsg.
1886**
1887** This routine does NOT free the Select structure passed in. The
1888** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00001889**
1890** The pParent, parentTab, and *pParentAgg fields are filled in if this
1891** SELECT is a subquery. This routine may try to combine this SELECT
1892** with its parent to form a single flat query. In so doing, it might
1893** change the parent query from a non-aggregate to an aggregate query.
1894** For that reason, the pParentAgg flag is passed as a pointer, so it
1895** can be changed.
drhe78e8282003-01-19 03:59:45 +00001896**
1897** Example 1: The meaning of the pParent parameter.
1898**
1899** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
1900** \ \_______ subquery _______/ /
1901** \ /
1902** \____________________ outer query ___________________/
1903**
1904** This routine is called for the outer query first. For that call,
1905** pParent will be NULL. During the processing of the outer query, this
1906** routine is called recursively to handle the subquery. For the recursive
1907** call, pParent will point to the outer query. Because the subquery is
1908** the second element in a three-way join, the parentTab parameter will
1909** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00001910*/
1911int sqliteSelect(
drhcce7d172000-05-31 15:34:51 +00001912 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00001913 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00001914 int eDest, /* How to dispose of the results */
1915 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00001916 Select *pParent, /* Another SELECT for which this is a sub-query */
1917 int parentTab, /* Index in pParent->pSrc of this query */
drh1b2e0322002-03-03 02:49:51 +00001918 int *pParentAgg /* True if pParent uses aggregate functions */
drhcce7d172000-05-31 15:34:51 +00001919){
drhd8bc7082000-06-07 23:51:50 +00001920 int i;
drhcce7d172000-05-31 15:34:51 +00001921 WhereInfo *pWInfo;
1922 Vdbe *v;
1923 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00001924 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00001925 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00001926 Expr *pWhere; /* The WHERE clause. May be NULL */
1927 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00001928 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
1929 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00001930 int isDistinct; /* True if the DISTINCT keyword is present */
1931 int distinct; /* Table to use for the distinct set */
drh10e5e3c2000-06-08 00:19:02 +00001932 int base; /* First cursor available for use */
drh1d83f052002-02-17 00:30:36 +00001933 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00001934
drhdaffd0e2001-04-11 14:28:42 +00001935 if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
drhe5f9c642003-01-13 23:27:31 +00001936 if( sqliteAuthCheck(pParse, SQLITE_SELECT, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00001937
drh82c3d632000-06-06 21:56:07 +00001938 /* If there is are a sequence of queries, do the earlier ones first.
1939 */
1940 if( p->pPrior ){
1941 return multiSelect(pParse, p, eDest, iParm);
1942 }
1943
1944 /* Make local copies of the parameters for this query.
1945 */
drh9bb61fe2000-06-05 16:01:39 +00001946 pTabList = p->pSrc;
1947 pWhere = p->pWhere;
1948 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00001949 pGroupBy = p->pGroupBy;
1950 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00001951 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00001952
drh832508b2002-03-02 17:04:07 +00001953 /* Allocate a block of VDBE cursors, one for each table in the FROM clause.
1954 ** The WHERE processing requires that the cursors for the tables in the
1955 ** FROM clause be consecutive.
drh10e5e3c2000-06-08 00:19:02 +00001956 */
drh832508b2002-03-02 17:04:07 +00001957 base = p->base = pParse->nTab;
drhad3cab52002-05-24 02:04:32 +00001958 pParse->nTab += pTabList->nSrc;
drh10e5e3c2000-06-08 00:19:02 +00001959
drh9bb61fe2000-06-05 16:01:39 +00001960 /*
1961 ** Do not even attempt to generate any code if we have already seen
1962 ** errors before this routine starts.
1963 */
drh1d83f052002-02-17 00:30:36 +00001964 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001965
drhe78e8282003-01-19 03:59:45 +00001966 /* Expand any "*" terms in the result set. (For example the "*" in
1967 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
1968 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00001969 */
drhd8bc7082000-06-07 23:51:50 +00001970 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00001971 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001972 }
drhad2d8302002-05-24 20:31:36 +00001973 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00001974 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00001975 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001976
drh22827922000-06-06 17:27:05 +00001977 /* If writing to memory or generating a set
1978 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00001979 */
drhfef52082000-06-06 01:50:43 +00001980 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
drh19a775c2000-06-05 18:54:46 +00001981 sqliteSetString(&pParse->zErrMsg, "only a single result allowed for "
1982 "a SELECT that is part of an expression", 0);
1983 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +00001984 goto select_end;
drh19a775c2000-06-05 18:54:46 +00001985 }
1986
drhc926afb2002-06-20 03:38:26 +00001987 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00001988 */
drhc926afb2002-06-20 03:38:26 +00001989 switch( eDest ){
1990 case SRT_Union:
1991 case SRT_Except:
1992 case SRT_Discard:
1993 pOrderBy = 0;
1994 break;
1995 default:
1996 break;
drh22827922000-06-06 17:27:05 +00001997 }
1998
drh10e5e3c2000-06-08 00:19:02 +00001999 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002000 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002001 **
drh967e8b72000-06-21 13:59:10 +00002002 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002003 */
drh4794b982000-06-06 13:54:14 +00002004 for(i=0; i<pEList->nExpr; i++){
drh832508b2002-03-02 17:04:07 +00002005 if( sqliteExprResolveIds(pParse, base, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002006 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002007 }
drh22827922000-06-06 17:27:05 +00002008 if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002009 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002010 }
2011 }
drhcce7d172000-05-31 15:34:51 +00002012 if( pWhere ){
drh832508b2002-03-02 17:04:07 +00002013 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00002014 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002015 }
2016 if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00002017 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002018 }
drh1f162302002-10-27 19:35:33 +00002019 sqliteOracle8JoinFixup(base, pTabList, pWhere);
drhcce7d172000-05-31 15:34:51 +00002020 }
drhc66c5a22002-12-03 02:34:49 +00002021 if( pHaving ){
2022 if( pGroupBy==0 ){
2023 sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required "
2024 "before HAVING", 0);
2025 pParse->nErr++;
2026 goto select_end;
2027 }
2028 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pHaving) ){
2029 goto select_end;
2030 }
2031 if( sqliteExprCheck(pParse, pHaving, 1, &isAgg) ){
2032 goto select_end;
2033 }
2034 }
drhcce7d172000-05-31 15:34:51 +00002035 if( pOrderBy ){
2036 for(i=0; i<pOrderBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002037 int iCol;
drh22827922000-06-06 17:27:05 +00002038 Expr *pE = pOrderBy->a[i].pExpr;
drh88eee382003-01-31 17:16:36 +00002039 if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2040 sqliteExprDelete(pE);
2041 pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
2042 }
2043 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
2044 goto select_end;
2045 }
2046 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
2047 goto select_end;
2048 }
drh92086432002-01-22 14:11:29 +00002049 if( sqliteExprIsConstant(pE) ){
drhe4de1fe2002-06-02 16:09:01 +00002050 if( sqliteExprIsInteger(pE, &iCol)==0 ){
2051 sqliteSetString(&pParse->zErrMsg,
2052 "ORDER BY terms must not be non-integer constants", 0);
2053 pParse->nErr++;
2054 goto select_end;
2055 }else if( iCol<=0 || iCol>pEList->nExpr ){
2056 char zBuf[2000];
2057 sprintf(zBuf,"ORDER BY column number %d out of range - should be "
2058 "between 1 and %d", iCol, pEList->nExpr);
2059 sqliteSetString(&pParse->zErrMsg, zBuf, 0);
2060 pParse->nErr++;
2061 goto select_end;
2062 }
drhcce7d172000-05-31 15:34:51 +00002063 }
2064 }
2065 }
drh22827922000-06-06 17:27:05 +00002066 if( pGroupBy ){
2067 for(i=0; i<pGroupBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002068 int iCol;
drh22827922000-06-06 17:27:05 +00002069 Expr *pE = pGroupBy->a[i].pExpr;
drh88eee382003-01-31 17:16:36 +00002070 if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2071 sqliteExprDelete(pE);
2072 pE = pGroupBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00002073 }
drh832508b2002-03-02 17:04:07 +00002074 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00002075 goto select_end;
drh22827922000-06-06 17:27:05 +00002076 }
2077 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00002078 goto select_end;
drh22827922000-06-06 17:27:05 +00002079 }
drh88eee382003-01-31 17:16:36 +00002080 if( sqliteExprIsConstant(pE) ){
2081 if( sqliteExprIsInteger(pE, &iCol)==0 ){
2082 sqliteSetString(&pParse->zErrMsg,
2083 "GROUP BY terms must not be non-integer constants", 0);
2084 pParse->nErr++;
2085 goto select_end;
2086 }else if( iCol<=0 || iCol>pEList->nExpr ){
2087 char zBuf[2000];
2088 sprintf(zBuf,"GROUP BY column number %d out of range - should be "
2089 "between 1 and %d", iCol, pEList->nExpr);
2090 sqliteSetString(&pParse->zErrMsg, zBuf, 0);
2091 pParse->nErr++;
2092 goto select_end;
2093 }
2094 }
drh22827922000-06-06 17:27:05 +00002095 }
2096 }
drhcce7d172000-05-31 15:34:51 +00002097
drh9562b552002-02-19 15:00:07 +00002098 /* Check for the special case of a min() or max() function by itself
2099 ** in the result set.
2100 */
2101 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
drh5cf8e8c2002-02-19 22:42:05 +00002102 rc = 0;
drh9562b552002-02-19 15:00:07 +00002103 goto select_end;
2104 }
2105
drhd820cb12002-02-18 03:21:45 +00002106 /* Begin generating code.
2107 */
2108 v = sqliteGetVdbe(pParse);
2109 if( v==0 ) goto select_end;
2110
drhe78e8282003-01-19 03:59:45 +00002111 /* Identify column names if we will be using them in a callback. This
2112 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002113 */
2114 if( eDest==SRT_Callback ){
2115 generateColumnNames(pParse, p->base, pTabList, pEList);
2116 }
2117
2118 /* Set the limiter
2119 */
2120 if( p->nLimit<=0 ){
drhd11d3822002-06-21 23:01:49 +00002121 p->nLimit = -1;
drh0bb28102002-05-08 11:54:14 +00002122 p->nOffset = 0;
2123 }else{
drhd11d3822002-06-21 23:01:49 +00002124 int iMem = pParse->nMem++;
2125 sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
drhbf5cd972002-06-24 12:20:23 +00002126 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
drhd11d3822002-06-21 23:01:49 +00002127 p->nLimit = iMem;
2128 if( p->nOffset<=0 ){
2129 p->nOffset = 0;
2130 }else{
2131 iMem = pParse->nMem++;
2132 sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
drhbf5cd972002-06-24 12:20:23 +00002133 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
drhd11d3822002-06-21 23:01:49 +00002134 p->nOffset = iMem;
2135 }
drh0bb28102002-05-08 11:54:14 +00002136 }
2137
drhd820cb12002-02-18 03:21:45 +00002138 /* Generate code for all sub-queries in the FROM clause
2139 */
drhad3cab52002-05-24 02:04:32 +00002140 for(i=0; i<pTabList->nSrc; i++){
drha76b5df2002-02-23 02:32:10 +00002141 if( pTabList->a[i].pSelect==0 ) continue;
drh2d0794e2002-03-03 03:03:52 +00002142 sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable, base+i,
drh1b2e0322002-03-03 02:49:51 +00002143 p, i, &isAgg);
2144 pTabList = p->pSrc;
2145 pWhere = p->pWhere;
drhacd4c692002-03-07 02:02:51 +00002146 if( eDest==SRT_Callback ){
2147 pOrderBy = p->pOrderBy;
2148 }
drh1b2e0322002-03-03 02:49:51 +00002149 pGroupBy = p->pGroupBy;
2150 pHaving = p->pHaving;
2151 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002152 }
2153
drh832508b2002-03-02 17:04:07 +00002154 /* Check to see if this is a subquery that can be "flattened" into its parent.
2155 ** If flattening is a possiblity, do so and return immediately.
2156 */
drh1b2e0322002-03-03 02:49:51 +00002157 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002158 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002159 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002160 return rc;
2161 }
drh832508b2002-03-02 17:04:07 +00002162
drhe78e8282003-01-19 03:59:45 +00002163 /* Identify column types if we will be using a callback. This
2164 ** step is skipped if the output is going to a destination other
2165 ** than a callback.
drhfcb78a42003-01-18 20:11:05 +00002166 */
2167 if( eDest==SRT_Callback ){
2168 generateColumnTypes(pParse, p->base, pTabList, pEList);
2169 }
2170
drh2d0794e2002-03-03 03:03:52 +00002171 /* If the output is destined for a temporary table, open that table.
2172 */
2173 if( eDest==SRT_TempTable ){
2174 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
2175 }
2176
drh22827922000-06-06 17:27:05 +00002177 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002178 */
drhd820cb12002-02-18 03:21:45 +00002179 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002180 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002181 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002182 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002183 for(i=0; i<pEList->nExpr; i++){
2184 if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002185 goto select_end;
drh22827922000-06-06 17:27:05 +00002186 }
2187 }
2188 if( pGroupBy ){
2189 for(i=0; i<pGroupBy->nExpr; i++){
2190 if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002191 goto select_end;
drh22827922000-06-06 17:27:05 +00002192 }
2193 }
2194 }
2195 if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002196 goto select_end;
drh22827922000-06-06 17:27:05 +00002197 }
drh191b6902000-06-08 11:13:01 +00002198 if( pOrderBy ){
2199 for(i=0; i<pOrderBy->nExpr; i++){
2200 if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002201 goto select_end;
drh191b6902000-06-08 11:13:01 +00002202 }
2203 }
2204 }
drhefb72512000-05-31 20:00:52 +00002205 }
2206
drh22827922000-06-06 17:27:05 +00002207 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002208 */
2209 if( isAgg ){
drh99fcd712001-10-13 01:06:47 +00002210 sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002211 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002212 FuncDef *pFunc;
2213 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drh1350b032002-02-27 19:00:20 +00002214 sqliteVdbeAddOp(v, OP_AggInit, 0, i);
drh0bce8352002-02-28 00:41:10 +00002215 sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
drhe5095352002-02-24 03:25:14 +00002216 }
2217 }
drh1bee3d72001-10-15 00:44:35 +00002218 if( pGroupBy==0 ){
2219 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002220 sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002221 }
drhcce7d172000-05-31 15:34:51 +00002222 }
2223
drh19a775c2000-06-05 18:54:46 +00002224 /* Initialize the memory cell to NULL
2225 */
drhfef52082000-06-06 01:50:43 +00002226 if( eDest==SRT_Mem ){
drh99fcd712001-10-13 01:06:47 +00002227 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh8721ce42001-11-07 14:22:00 +00002228 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002229 }
2230
drh832508b2002-03-02 17:04:07 +00002231 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002232 */
drh19a775c2000-06-05 18:54:46 +00002233 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002234 distinct = pParse->nTab++;
drhc6b52df2002-01-04 03:09:29 +00002235 sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
drh832508b2002-03-02 17:04:07 +00002236 }else{
2237 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002238 }
drh832508b2002-03-02 17:04:07 +00002239
2240 /* Begin the database scan
2241 */
drh68d2e592002-08-04 00:52:38 +00002242 pWInfo = sqliteWhereBegin(pParse, p->base, pTabList, pWhere, 0,
2243 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002244 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002245
drh22827922000-06-06 17:27:05 +00002246 /* Use the standard inner loop if we are not dealing with
2247 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002248 */
drhda9d6c42000-05-31 18:20:14 +00002249 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002250 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2251 iParm, pWInfo->iContinue, pWInfo->iBreak) ){
drh1d83f052002-02-17 00:30:36 +00002252 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002253 }
drhcce7d172000-05-31 15:34:51 +00002254 }
drhefb72512000-05-31 20:00:52 +00002255
drhe3184742002-06-19 14:27:05 +00002256 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002257 ** processing.
drhefb72512000-05-31 20:00:52 +00002258 */
drh22827922000-06-06 17:27:05 +00002259 else{
drh22827922000-06-06 17:27:05 +00002260 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002261 int lbl1;
drh22827922000-06-06 17:27:05 +00002262 for(i=0; i<pGroupBy->nExpr; i++){
2263 sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
2264 }
drh99fcd712001-10-13 01:06:47 +00002265 sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
drh491791a2002-07-18 00:34:09 +00002266 if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pGroupBy);
drh1bee3d72001-10-15 00:44:35 +00002267 lbl1 = sqliteVdbeMakeLabel(v);
drh99fcd712001-10-13 01:06:47 +00002268 sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh22827922000-06-06 17:27:05 +00002269 for(i=0; i<pParse->nAgg; i++){
2270 if( pParse->aAgg[i].isAgg ) continue;
2271 sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
drh99fcd712001-10-13 01:06:47 +00002272 sqliteVdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002273 }
drh22827922000-06-06 17:27:05 +00002274 sqliteVdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002275 }
drh22827922000-06-06 17:27:05 +00002276 for(i=0; i<pParse->nAgg; i++){
2277 Expr *pE;
drh0bce8352002-02-28 00:41:10 +00002278 int j;
drh22827922000-06-06 17:27:05 +00002279 if( !pParse->aAgg[i].isAgg ) continue;
2280 pE = pParse->aAgg[i].pExpr;
drh22827922000-06-06 17:27:05 +00002281 assert( pE->op==TK_AGG_FUNCTION );
drh0bce8352002-02-28 00:41:10 +00002282 if( pE->pList ){
2283 for(j=0; j<pE->pList->nExpr; j++){
2284 sqliteExprCode(pParse, pE->pList->a[j].pExpr);
2285 }
drhe5095352002-02-24 03:25:14 +00002286 }
drh0bce8352002-02-28 00:41:10 +00002287 sqliteVdbeAddOp(v, OP_Integer, i, 0);
drhf55f25f2002-02-28 01:46:11 +00002288 sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
drh0bce8352002-02-28 00:41:10 +00002289 assert( pParse->aAgg[i].pFunc!=0 );
2290 assert( pParse->aAgg[i].pFunc->xStep!=0 );
2291 sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002292 }
drhcce7d172000-05-31 15:34:51 +00002293 }
2294
2295 /* End the database scan loop.
2296 */
2297 sqliteWhereEnd(pWInfo);
2298
drh22827922000-06-06 17:27:05 +00002299 /* If we are processing aggregates, we need to set up a second loop
2300 ** over all of the aggregate values and process them.
2301 */
2302 if( isAgg ){
2303 int endagg = sqliteVdbeMakeLabel(v);
2304 int startagg;
drh99fcd712001-10-13 01:06:47 +00002305 startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002306 pParse->useAgg = 1;
2307 if( pHaving ){
drhf5905aa2002-05-26 20:54:33 +00002308 sqliteExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002309 }
drhdf199a22002-06-14 22:38:41 +00002310 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2311 iParm, startagg, endagg) ){
drh1d83f052002-02-17 00:30:36 +00002312 goto select_end;
drh22827922000-06-06 17:27:05 +00002313 }
drh99fcd712001-10-13 01:06:47 +00002314 sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
2315 sqliteVdbeResolveLabel(v, endagg);
2316 sqliteVdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002317 pParse->useAgg = 0;
2318 }
2319
drhcce7d172000-05-31 15:34:51 +00002320 /* If there is an ORDER BY clause, then we need to sort the results
2321 ** and send them to the callback one by one.
2322 */
2323 if( pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00002324 generateSortTail(p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002325 }
drh6a535342001-10-19 16:44:56 +00002326
2327
2328 /* Issue a null callback if that is what the user wants.
2329 */
drh326dce72003-01-29 14:06:07 +00002330 if( eDest==SRT_Callback &&
2331 (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
2332 ){
drh6a535342001-10-19 16:44:56 +00002333 sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
2334 }
2335
drh1d83f052002-02-17 00:30:36 +00002336 /* The SELECT was successfully coded. Set the return code to 0
2337 ** to indicate no errors.
2338 */
2339 rc = 0;
2340
2341 /* Control jumps to here if an error is encountered above, or upon
2342 ** successful coding of the SELECT.
2343 */
2344select_end:
2345 sqliteAggregateInfoReset(pParse);
2346 return rc;
drhcce7d172000-05-31 15:34:51 +00002347}