blob: 73c1f6a3db62d44478c057aac9c092b62c225357 [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**
drhfa173a72002-07-10 21:26:00 +000015** $Id: select.c,v 1.104 2002/07/10 21:26:01 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
drhcce7d172000-05-31 15:34:51 +000019/*
drh9bb61fe2000-06-05 16:01:39 +000020** Allocate a new Select structure and return a pointer to that
21** structure.
drhcce7d172000-05-31 15:34:51 +000022*/
drh9bb61fe2000-06-05 16:01:39 +000023Select *sqliteSelectNew(
drhdaffd0e2001-04-11 14:28:42 +000024 ExprList *pEList, /* which columns to include in the result */
drhad3cab52002-05-24 02:04:32 +000025 SrcList *pSrc, /* the FROM clause -- which tables to scan */
drhdaffd0e2001-04-11 14:28:42 +000026 Expr *pWhere, /* the WHERE clause */
27 ExprList *pGroupBy, /* the GROUP BY clause */
28 Expr *pHaving, /* the HAVING clause */
29 ExprList *pOrderBy, /* the ORDER BY clause */
drh9bbca4c2001-11-06 04:00:18 +000030 int isDistinct, /* true if the DISTINCT keyword is present */
31 int nLimit, /* LIMIT value. -1 means not used */
32 int nOffset /* OFFSET value. -1 means not used */
drh9bb61fe2000-06-05 16:01:39 +000033){
34 Select *pNew;
35 pNew = sqliteMalloc( sizeof(*pNew) );
drhdaffd0e2001-04-11 14:28:42 +000036 if( pNew==0 ){
37 sqliteExprListDelete(pEList);
drhad3cab52002-05-24 02:04:32 +000038 sqliteSrcListDelete(pSrc);
drhdaffd0e2001-04-11 14:28:42 +000039 sqliteExprDelete(pWhere);
40 sqliteExprListDelete(pGroupBy);
41 sqliteExprDelete(pHaving);
42 sqliteExprListDelete(pOrderBy);
43 }else{
44 pNew->pEList = pEList;
45 pNew->pSrc = pSrc;
46 pNew->pWhere = pWhere;
47 pNew->pGroupBy = pGroupBy;
48 pNew->pHaving = pHaving;
49 pNew->pOrderBy = pOrderBy;
50 pNew->isDistinct = isDistinct;
51 pNew->op = TK_SELECT;
drh9bbca4c2001-11-06 04:00:18 +000052 pNew->nLimit = nLimit;
53 pNew->nOffset = nOffset;
drhdaffd0e2001-04-11 14:28:42 +000054 }
drh9bb61fe2000-06-05 16:01:39 +000055 return pNew;
56}
57
58/*
drh01f3f252002-05-24 16:14:15 +000059** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
60** type of join. Return an integer constant that expresses that type
61** in terms of the following bit values:
62**
63** JT_INNER
64** JT_OUTER
65** JT_NATURAL
66** JT_LEFT
67** JT_RIGHT
68**
69** A full outer join is the combination of JT_LEFT and JT_RIGHT.
70**
71** If an illegal or unsupported join type is seen, then still return
72** a join type, but put an error in the pParse structure.
73*/
74int sqliteJoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
75 int jointype = 0;
76 Token *apAll[3];
77 Token *p;
78 static struct {
79 const char *zKeyword;
80 int nChar;
81 int code;
82 } keywords[] = {
83 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000084 { "left", 4, JT_LEFT|JT_OUTER },
85 { "right", 5, JT_RIGHT|JT_OUTER },
86 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +000087 { "outer", 5, JT_OUTER },
88 { "inner", 5, JT_INNER },
89 { "cross", 5, JT_INNER },
90 };
91 int i, j;
92 apAll[0] = pA;
93 apAll[1] = pB;
94 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +000095 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +000096 p = apAll[i];
97 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
98 if( p->n==keywords[j].nChar
99 && sqliteStrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
100 jointype |= keywords[j].code;
101 break;
102 }
103 }
104 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
105 jointype |= JT_ERROR;
106 break;
107 }
108 }
drhad2d8302002-05-24 20:31:36 +0000109 if(
110 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000111 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000112 ){
drh01f3f252002-05-24 16:14:15 +0000113 static Token dummy = { 0, 0 };
114 char *zSp1 = " ", *zSp2 = " ";
115 if( pB==0 ){ pB = &dummy; zSp1 = 0; }
116 if( pC==0 ){ pC = &dummy; zSp2 = 0; }
117 sqliteSetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
118 pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
119 pParse->nErr++;
120 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000121 }else if( jointype & JT_RIGHT ){
122 sqliteSetString(&pParse->zErrMsg,
123 "RIGHT and FULL OUTER JOINs are not currently supported", 0);
124 pParse->nErr++;
125 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000126 }
127 return jointype;
128}
129
130/*
drhad2d8302002-05-24 20:31:36 +0000131** Return the index of a column in a table. Return -1 if the column
132** is not contained in the table.
133*/
134static int columnIndex(Table *pTab, const char *zCol){
135 int i;
136 for(i=0; i<pTab->nCol; i++){
137 if( sqliteStrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
138 }
139 return -1;
140}
141
142/*
143** Add a term to the WHERE expression in *ppExpr that requires the
144** zCol column to be equal in the two tables pTab1 and pTab2.
145*/
146static void addWhereTerm(
147 const char *zCol, /* Name of the column */
148 const Table *pTab1, /* First table */
149 const Table *pTab2, /* Second table */
150 Expr **ppExpr /* Add the equality term to this expression */
151){
152 Token dummy;
153 Expr *pE1a, *pE1b, *pE1c;
154 Expr *pE2a, *pE2b, *pE2c;
155 Expr *pE;
156
157 dummy.z = zCol;
158 dummy.n = strlen(zCol);
159 pE1a = sqliteExpr(TK_ID, 0, 0, &dummy);
drh3b167c72002-06-28 12:18:47 +0000160 pE1a->staticToken = 1;
drhad2d8302002-05-24 20:31:36 +0000161 pE2a = sqliteExpr(TK_ID, 0, 0, &dummy);
drh3b167c72002-06-28 12:18:47 +0000162 pE2a->staticToken = 1;
drhad2d8302002-05-24 20:31:36 +0000163 dummy.z = pTab1->zName;
164 dummy.n = strlen(dummy.z);
165 pE1b = sqliteExpr(TK_ID, 0, 0, &dummy);
drh3b167c72002-06-28 12:18:47 +0000166 pE1b->staticToken = 1;
drhad2d8302002-05-24 20:31:36 +0000167 dummy.z = pTab2->zName;
168 dummy.n = strlen(dummy.z);
169 pE2b = sqliteExpr(TK_ID, 0, 0, &dummy);
drh3b167c72002-06-28 12:18:47 +0000170 pE2b->staticToken = 1;
drhad2d8302002-05-24 20:31:36 +0000171 pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0);
172 pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0);
173 pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0);
drh1cc093c2002-06-24 22:01:57 +0000174 pE->isJoinExpr = 1;
drhad2d8302002-05-24 20:31:36 +0000175 if( *ppExpr ){
176 *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0);
177 }else{
178 *ppExpr = pE;
179 }
180}
181
182/*
drh1cc093c2002-06-24 22:01:57 +0000183** Set the Expr.isJoinExpr flag on all terms of the given expression.
184**
185** The Expr.isJoinExpr flag is used at on terms of an expression to tell
186** the LEFT OUTER JOIN processing logic that this term is part of the
187** join restriction and not a part of the more general WHERE clause.
188*/
189static void setJoinExpr(Expr *p){
190 while( p ){
191 p->isJoinExpr = 1;
192 setJoinExpr(p->pLeft);
193 p = p->pRight;
194 }
195}
196
197/*
drhad2d8302002-05-24 20:31:36 +0000198** This routine processes the join information for a SELECT statement.
199** ON and USING clauses are converted into extra terms of the WHERE clause.
200** NATURAL joins also create extra WHERE clause terms.
201**
202** This routine returns the number of errors encountered.
203*/
204static int sqliteProcessJoin(Parse *pParse, Select *p){
205 SrcList *pSrc;
206 int i, j;
207 pSrc = p->pSrc;
208 for(i=0; i<pSrc->nSrc-1; i++){
209 struct SrcList_item *pTerm = &pSrc->a[i];
210 struct SrcList_item *pOther = &pSrc->a[i+1];
211
212 if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
213
214 /* When the NATURAL keyword is present, add WHERE clause terms for
215 ** every column that the two tables have in common.
216 */
217 if( pTerm->jointype & JT_NATURAL ){
218 Table *pTab;
219 if( pTerm->pOn || pTerm->pUsing ){
220 sqliteSetString(&pParse->zErrMsg, "a NATURAL join may not have "
221 "an ON or USING clause", 0);
222 pParse->nErr++;
223 return 1;
224 }
225 pTab = pTerm->pTab;
226 for(j=0; j<pTab->nCol; j++){
227 if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
228 addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
229 }
230 }
231 }
232
233 /* Disallow both ON and USING clauses in the same join
234 */
235 if( pTerm->pOn && pTerm->pUsing ){
236 sqliteSetString(&pParse->zErrMsg, "cannot have both ON and USING "
237 "clauses in the same join", 0);
238 pParse->nErr++;
239 return 1;
240 }
241
242 /* Add the ON clause to the end of the WHERE clause, connected by
243 ** and AND operator.
244 */
245 if( pTerm->pOn ){
drh1cc093c2002-06-24 22:01:57 +0000246 setJoinExpr(pTerm->pOn);
drhad2d8302002-05-24 20:31:36 +0000247 if( p->pWhere==0 ){
248 p->pWhere = pTerm->pOn;
249 }else{
250 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0);
251 }
252 pTerm->pOn = 0;
253 }
254
255 /* Create extra terms on the WHERE clause for each column named
256 ** in the USING clause. Example: If the two tables to be joined are
257 ** A and B and the USING clause names X, Y, and Z, then add this
258 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
259 ** Report an error if any column mentioned in the USING clause is
260 ** not contained in both tables to be joined.
261 */
262 if( pTerm->pUsing ){
263 IdList *pList;
264 int j;
265 assert( i<pSrc->nSrc-1 );
266 pList = pTerm->pUsing;
267 for(j=0; j<pList->nId; j++){
drhbf5cd972002-06-24 12:20:23 +0000268 if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
269 columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
drhad2d8302002-05-24 20:31:36 +0000270 sqliteSetString(&pParse->zErrMsg, "cannot join using column ",
drhbf5cd972002-06-24 12:20:23 +0000271 pList->a[j].zName, " - column not present in both tables", 0);
drhad2d8302002-05-24 20:31:36 +0000272 pParse->nErr++;
273 return 1;
274 }
drhbf5cd972002-06-24 12:20:23 +0000275 addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000276 }
277 }
278 }
279 return 0;
280}
281
282/*
drh9bb61fe2000-06-05 16:01:39 +0000283** Delete the given Select structure and all of its substructures.
284*/
285void sqliteSelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000286 if( p==0 ) return;
drh9bb61fe2000-06-05 16:01:39 +0000287 sqliteExprListDelete(p->pEList);
drhad3cab52002-05-24 02:04:32 +0000288 sqliteSrcListDelete(p->pSrc);
drh9bb61fe2000-06-05 16:01:39 +0000289 sqliteExprDelete(p->pWhere);
290 sqliteExprListDelete(p->pGroupBy);
291 sqliteExprDelete(p->pHaving);
292 sqliteExprListDelete(p->pOrderBy);
drh82c3d632000-06-06 21:56:07 +0000293 sqliteSelectDelete(p->pPrior);
drha76b5df2002-02-23 02:32:10 +0000294 sqliteFree(p->zSelect);
drh9bb61fe2000-06-05 16:01:39 +0000295 sqliteFree(p);
296}
297
298/*
drh22827922000-06-06 17:27:05 +0000299** Delete the aggregate information from the parse structure.
300*/
drh1d83f052002-02-17 00:30:36 +0000301static void sqliteAggregateInfoReset(Parse *pParse){
drh22827922000-06-06 17:27:05 +0000302 sqliteFree(pParse->aAgg);
303 pParse->aAgg = 0;
304 pParse->nAgg = 0;
drh22827922000-06-06 17:27:05 +0000305 pParse->useAgg = 0;
306}
307
308/*
drhc926afb2002-06-20 03:38:26 +0000309** Insert code into "v" that will push the record on the top of the
310** stack into the sorter.
311*/
312static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
313 char *zSortOrder;
314 int i;
315 zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
316 if( zSortOrder==0 ) return;
317 for(i=0; i<pOrderBy->nExpr; i++){
drh38640e12002-07-05 21:42:36 +0000318 int order = pOrderBy->a[i].sortOrder;
319 int type;
320 int c;
321 if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
322 type = SQLITE_SO_TEXT;
323 }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
324 type = SQLITE_SO_NUM;
325 }else if( pParse->db->file_format>=3 ){
326 type = sqliteExprType(pOrderBy->a[i].pExpr);
327 }else{
328 type = SQLITE_SO_NUM;
329 }
330 if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
331 c = type==SQLITE_SO_TEXT ? 'A' : '+';
332 }else{
333 c = type==SQLITE_SO_TEXT ? 'D' : '-';
334 }
335 zSortOrder[i] = c;
drhc926afb2002-06-20 03:38:26 +0000336 sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
337 }
338 zSortOrder[pOrderBy->nExpr] = 0;
339 sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0);
340 sqliteVdbeChangeP3(v, -1, zSortOrder, strlen(zSortOrder));
341 sqliteFree(zSortOrder);
342 sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
343}
344
345/*
drh38640e12002-07-05 21:42:36 +0000346** This routine adds a P3 argument to the last VDBE opcode that was
347** inserted. The P3 argument added is a string suitable for the
348** OP_MakeKey or OP_MakeIdxKey opcodes. The string consists of
349** characters 't' or 'n' depending on whether or not the various
350** fields of the key to be generated should be treated as numeric
351** or as text. See the OP_MakeKey and OP_MakeIdxKey opcode
352** documentation for additional information about the P3 string.
353** See also the sqliteAddIdxKeyType() routine.
354*/
355void sqliteAddKeyType(Vdbe *v, ExprList *pEList){
356 int nColumn = pEList->nExpr;
357 char *zType = sqliteMalloc( nColumn+1 );
358 int i;
359 if( zType==0 ) return;
360 for(i=0; i<nColumn; i++){
361 zType[i] = sqliteExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
362 }
363 zType[i] = 0;
364 sqliteVdbeChangeP3(v, -1, zType, nColumn);
365 sqliteFree(zType);
366}
367
368/*
drh22827922000-06-06 17:27:05 +0000369** This routine generates the code for the inside of the inner loop
370** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000371**
drh38640e12002-07-05 21:42:36 +0000372** If srcTab and nColumn are both zero, then the pEList expressions
373** are evaluated in order to get the data for this row. If nColumn>0
374** then data is pulled from srcTab and pEList is used only to get the
375** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000376*/
377static int selectInnerLoop(
378 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000379 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000380 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000381 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000382 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000383 ExprList *pOrderBy, /* If not NULL, sort results using this key */
384 int distinct, /* If >=0, make sure results are distinct */
385 int eDest, /* How to dispose of the results */
386 int iParm, /* An argument to the disposal method */
387 int iContinue, /* Jump here to continue with next row */
388 int iBreak /* Jump here to break out of the inner loop */
389){
390 Vdbe *v = pParse->pVdbe;
391 int i;
drh38640e12002-07-05 21:42:36 +0000392
drhdaffd0e2001-04-11 14:28:42 +0000393 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000394 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000395
drhdf199a22002-06-14 22:38:41 +0000396 /* If there was a LIMIT clause on the SELECT statement, then do the check
397 ** to see if this row should be output.
398 */
399 if( pOrderBy==0 ){
400 if( p->nOffset>0 ){
drhd11d3822002-06-21 23:01:49 +0000401 int addr = sqliteVdbeCurrentAddr(v);
402 sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+2);
403 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
drhdf199a22002-06-14 22:38:41 +0000404 }
drhd11d3822002-06-21 23:01:49 +0000405 if( p->nLimit>=0 ){
406 sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, iBreak);
drhdf199a22002-06-14 22:38:41 +0000407 }
408 }
409
drh967e8b72000-06-21 13:59:10 +0000410 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000411 */
drh38640e12002-07-05 21:42:36 +0000412 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000413 for(i=0; i<nColumn; i++){
drh99fcd712001-10-13 01:06:47 +0000414 sqliteVdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000415 }
drh38640e12002-07-05 21:42:36 +0000416 }else{
417 nColumn = pEList->nExpr;
418 for(i=0; i<pEList->nExpr; i++){
419 sqliteExprCode(pParse, pEList->a[i].pExpr);
420 }
drh22827922000-06-06 17:27:05 +0000421 }
422
drhdaffd0e2001-04-11 14:28:42 +0000423 /* If the DISTINCT keyword was present on the SELECT statement
424 ** and this row has been seen before, then do not make this row
425 ** part of the result.
drh22827922000-06-06 17:27:05 +0000426 */
drhf5905aa2002-05-26 20:54:33 +0000427 if( distinct>=0 && pEList && pEList->nExpr>0 ){
drh0bd1f4e2002-06-06 18:54:39 +0000428#if NULL_ALWAYS_DISTINCT
429 sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7);
430#endif
drh99fcd712001-10-13 01:06:47 +0000431 sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
drh38640e12002-07-05 21:42:36 +0000432 if( pParse->db->file_format>=3 ) sqliteAddKeyType(v, pEList);
drhf5905aa2002-05-26 20:54:33 +0000433 sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
drh99fcd712001-10-13 01:06:47 +0000434 sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
435 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
drh99fcd712001-10-13 01:06:47 +0000436 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh6b125452002-01-28 15:53:03 +0000437 sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
drh22827922000-06-06 17:27:05 +0000438 }
drh82c3d632000-06-06 21:56:07 +0000439
drhc926afb2002-06-20 03:38:26 +0000440 switch( eDest ){
441 /* In this mode, write each query result to the key of the temporary
442 ** table iParm.
443 */
444 case SRT_Union: {
445 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
446 sqliteVdbeAddOp(v, OP_String, 0, 0);
447 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
448 break;
drh22827922000-06-06 17:27:05 +0000449 }
drh22827922000-06-06 17:27:05 +0000450
drhc926afb2002-06-20 03:38:26 +0000451 /* Store the result as data using a unique key.
452 */
453 case SRT_Table:
454 case SRT_TempTable: {
455 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
456 if( pOrderBy ){
457 pushOntoSorter(pParse, v, pOrderBy);
458 }else{
459 sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
460 sqliteVdbeAddOp(v, OP_Pull, 1, 0);
461 sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
462 }
463 break;
464 }
drh82c3d632000-06-06 21:56:07 +0000465
drhc926afb2002-06-20 03:38:26 +0000466 /* Construct a record from the query result, but instead of
467 ** saving that record, use it as a key to delete elements from
468 ** the temporary table iParm.
469 */
470 case SRT_Except: {
471 int addr;
472 addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
473 sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
474 sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
475 break;
476 }
drh5974a302000-06-07 14:42:26 +0000477
drhc926afb2002-06-20 03:38:26 +0000478 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
479 ** then there should be a single item on the stack. Write this
480 ** item into the set table with bogus data.
481 */
482 case SRT_Set: {
drha9f9d1c2002-06-29 02:20:08 +0000483 int lbl = sqliteVdbeMakeLabel(v);
drhc926afb2002-06-20 03:38:26 +0000484 assert( nColumn==1 );
drha9f9d1c2002-06-29 02:20:08 +0000485 sqliteVdbeAddOp(v, OP_IsNull, -1, lbl);
drhc926afb2002-06-20 03:38:26 +0000486 if( pOrderBy ){
487 pushOntoSorter(pParse, v, pOrderBy);
488 }else{
drha9f9d1c2002-06-29 02:20:08 +0000489 sqliteVdbeAddOp(v, OP_String, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000490 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
491 }
drha9f9d1c2002-06-29 02:20:08 +0000492 sqliteVdbeResolveLabel(v, lbl);
drhc926afb2002-06-20 03:38:26 +0000493 break;
494 }
drh22827922000-06-06 17:27:05 +0000495
drhc926afb2002-06-20 03:38:26 +0000496 /* If this is a scalar select that is part of an expression, then
497 ** store the results in the appropriate memory cell and break out
498 ** of the scan loop.
499 */
500 case SRT_Mem: {
501 assert( nColumn==1 );
502 if( pOrderBy ){
503 pushOntoSorter(pParse, v, pOrderBy);
504 }else{
505 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
506 sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
507 }
508 break;
509 }
drh22827922000-06-06 17:27:05 +0000510
drhf46f9052002-06-22 02:33:38 +0000511 /* Send the data to the callback function.
512 */
513 case SRT_Callback:
514 case SRT_Sorter: {
515 if( pOrderBy ){
516 sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
517 pushOntoSorter(pParse, v, pOrderBy);
518 }else{
519 assert( eDest==SRT_Callback );
520 sqliteVdbeAddOp(v, OP_Callback, nColumn, 0);
521 }
522 break;
523 }
524
drhc926afb2002-06-20 03:38:26 +0000525 /* Discard the results. This is used for SELECT statements inside
526 ** the body of a TRIGGER. The purpose of such selects is to call
527 ** user-defined functions that have side effects. We do not care
528 ** about the actual results of the select.
529 */
drhc926afb2002-06-20 03:38:26 +0000530 default: {
drhf46f9052002-06-22 02:33:38 +0000531 assert( eDest==SRT_Discard );
532 sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000533 break;
534 }
drh82c3d632000-06-06 21:56:07 +0000535 }
536 return 0;
537}
538
539/*
drhd8bc7082000-06-07 23:51:50 +0000540** If the inner loop was generated using a non-null pOrderBy argument,
541** then the results were placed in a sorter. After the loop is terminated
542** we need to run the sorter and output the results. The following
543** routine generates the code needed to do that.
544*/
drhc926afb2002-06-20 03:38:26 +0000545static void generateSortTail(
546 Select *p, /* The SELECT statement */
547 Vdbe *v, /* Generate code into this VDBE */
548 int nColumn, /* Number of columns of data */
549 int eDest, /* Write the sorted results here */
550 int iParm /* Optional parameter associated with eDest */
551){
drhd8bc7082000-06-07 23:51:50 +0000552 int end = sqliteVdbeMakeLabel(v);
553 int addr;
drhf46f9052002-06-22 02:33:38 +0000554 if( eDest==SRT_Sorter ) return;
drh99fcd712001-10-13 01:06:47 +0000555 sqliteVdbeAddOp(v, OP_Sort, 0, 0);
556 addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end);
drhdf199a22002-06-14 22:38:41 +0000557 if( p->nOffset>0 ){
drhd11d3822002-06-21 23:01:49 +0000558 sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+4);
559 sqliteVdbeAddOp(v, OP_Pop, 1, 0);
560 sqliteVdbeAddOp(v, OP_Goto, 0, addr);
drhdf199a22002-06-14 22:38:41 +0000561 }
drhd11d3822002-06-21 23:01:49 +0000562 if( p->nLimit>=0 ){
563 sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, end);
drhdf199a22002-06-14 22:38:41 +0000564 }
drhc926afb2002-06-20 03:38:26 +0000565 switch( eDest ){
566 case SRT_Callback: {
567 sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0);
568 break;
569 }
570 case SRT_Table:
571 case SRT_TempTable: {
572 sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
573 sqliteVdbeAddOp(v, OP_Pull, 1, 0);
574 sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
575 break;
576 }
577 case SRT_Set: {
578 assert( nColumn==1 );
579 sqliteVdbeAddOp(v, OP_IsNull, -1, sqliteVdbeCurrentAddr(v)+3);
580 sqliteVdbeAddOp(v, OP_String, 0, 0);
581 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
582 break;
583 }
584 case SRT_Mem: {
585 assert( nColumn==1 );
586 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
587 sqliteVdbeAddOp(v, OP_Goto, 0, end);
588 break;
589 }
590 default: {
drhf46f9052002-06-22 02:33:38 +0000591 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000592 break;
593 }
594 }
drh99fcd712001-10-13 01:06:47 +0000595 sqliteVdbeAddOp(v, OP_Goto, 0, addr);
596 sqliteVdbeResolveLabel(v, end);
drha8b38d22001-11-01 14:41:34 +0000597 sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000598}
599
600/*
drh82c3d632000-06-06 21:56:07 +0000601** Generate code that will tell the VDBE how many columns there
602** are in the result and the name for each column. This information
603** is used to provide "argc" and "azCol[]" values in the callback.
604*/
drh832508b2002-03-02 17:04:07 +0000605static void generateColumnNames(
606 Parse *pParse, /* Parser context */
607 int base, /* VDBE cursor corresponding to first entry in pTabList */
drhad3cab52002-05-24 02:04:32 +0000608 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000609 ExprList *pEList /* Expressions defining the result set */
610){
drhd8bc7082000-06-07 23:51:50 +0000611 Vdbe *v = pParse->pVdbe;
drh82c3d632000-06-06 21:56:07 +0000612 int i;
drhdaffd0e2001-04-11 14:28:42 +0000613 if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000614 pParse->colNamesSet = 1;
drhb1363202002-06-26 02:45:03 +0000615 sqliteVdbeAddOp(v, OP_ColumnCount, pEList->nExpr*2+1, 0);
drh82c3d632000-06-06 21:56:07 +0000616 for(i=0; i<pEList->nExpr; i++){
617 Expr *p;
drhb1363202002-06-26 02:45:03 +0000618 char *zType = 0;
drh1bee3d72001-10-15 00:44:35 +0000619 int showFullNames;
drh82c3d632000-06-06 21:56:07 +0000620 if( pEList->a[i].zName ){
621 char *zName = pEList->a[i].zName;
drh99fcd712001-10-13 01:06:47 +0000622 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
623 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000624 continue;
625 }
626 p = pEList->a[i].pExpr;
drhdaffd0e2001-04-11 14:28:42 +0000627 if( p==0 ) continue;
drh1bee3d72001-10-15 00:44:35 +0000628 showFullNames = (pParse->db->flags & SQLITE_FullColNames)!=0;
drhfa173a72002-07-10 21:26:00 +0000629 if( p->op==TK_COLUMN && pTabList ){
drh832508b2002-03-02 17:04:07 +0000630 Table *pTab = pTabList->a[p->iTable - base].pTab;
drh97665872002-02-13 23:22:53 +0000631 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000632 int iCol = p->iColumn;
633 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000634 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000635 if( iCol<0 ){
636 zCol = "_ROWID_";
637 zType = "INTEGER";
638 }else{
639 zCol = pTab->aCol[iCol].zName;
640 zType = pTab->aCol[iCol].zType;
641 }
drhfa173a72002-07-10 21:26:00 +0000642 if( p->span.z && p->span.z[0] && !showFullNames ){
643 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
644 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
645 sqliteVdbeCompressSpace(v, addr);
646 }else if( pTabList->nSrc>1 || showFullNames ){
drh82c3d632000-06-06 21:56:07 +0000647 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000648 char *zTab;
649
drh832508b2002-03-02 17:04:07 +0000650 zTab = pTabList->a[p->iTable - base].zAlias;
drh01a34662001-10-20 12:30:10 +0000651 if( showFullNames || zTab==0 ) zTab = pTab->zName;
drh97665872002-02-13 23:22:53 +0000652 sqliteSetString(&zName, zTab, ".", zCol, 0);
drh99fcd712001-10-13 01:06:47 +0000653 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
654 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000655 sqliteFree(zName);
656 }else{
drh99fcd712001-10-13 01:06:47 +0000657 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
drh22f70c32002-02-18 01:17:00 +0000658 sqliteVdbeChangeP3(v, -1, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000659 }
drhfa173a72002-07-10 21:26:00 +0000660 }else if( p->span.z && p->span.z[0] && !showFullNames ){
661 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
662 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
663 sqliteVdbeCompressSpace(v, addr);
drh1bee3d72001-10-15 00:44:35 +0000664 }else if( p->span.z && p->span.z[0] ){
665 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
666 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
667 sqliteVdbeCompressSpace(v, addr);
668 }else{
669 char zName[30];
670 assert( p->op!=TK_COLUMN || pTabList==0 );
671 sprintf(zName, "column%d", i+1);
672 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
673 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000674 }
drhb1363202002-06-26 02:45:03 +0000675 if( zType==0 ){
676 if( sqliteExprType(p)==SQLITE_SO_TEXT ){
677 zType = "TEXT";
678 }else{
679 zType = "NUMERIC";
680 }
681 }
682 sqliteVdbeAddOp(v, OP_ColumnName, i + pEList->nExpr + 1, 0);
683 sqliteVdbeChangeP3(v, -1, zType, P3_STATIC);
drh82c3d632000-06-06 21:56:07 +0000684 }
685}
686
687/*
drhd8bc7082000-06-07 23:51:50 +0000688** Name of the connection operator, used for error messages.
689*/
690static const char *selectOpName(int id){
691 char *z;
692 switch( id ){
693 case TK_ALL: z = "UNION ALL"; break;
694 case TK_INTERSECT: z = "INTERSECT"; break;
695 case TK_EXCEPT: z = "EXCEPT"; break;
696 default: z = "UNION"; break;
697 }
698 return z;
699}
700
701/*
drh22f70c32002-02-18 01:17:00 +0000702** Given a SELECT statement, generate a Table structure that describes
703** the result set of that SELECT.
704*/
705Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
706 Table *pTab;
707 int i;
708 ExprList *pEList;
709 static int fillInColumnList(Parse*, Select*);
710
711 if( fillInColumnList(pParse, pSelect) ){
712 return 0;
713 }
714 pTab = sqliteMalloc( sizeof(Table) );
715 if( pTab==0 ){
716 return 0;
717 }
718 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
719 pEList = pSelect->pEList;
720 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000721 assert( pTab->nCol>0 );
drh22f70c32002-02-18 01:17:00 +0000722 pTab->aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
723 for(i=0; i<pTab->nCol; i++){
724 Expr *p;
725 if( pEList->a[i].zName ){
726 pTab->aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
727 }else if( (p=pEList->a[i].pExpr)->span.z && p->span.z[0] ){
728 sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drhd820cb12002-02-18 03:21:45 +0000729 }else if( p->op==TK_DOT && p->pRight && p->pRight->token.z &&
730 p->pRight->token.z[0] ){
731 sqliteSetNString(&pTab->aCol[i].zName,
732 p->pRight->token.z, p->pRight->token.n, 0);
drh22f70c32002-02-18 01:17:00 +0000733 }else{
734 char zBuf[30];
735 sprintf(zBuf, "column%d", i+1);
736 pTab->aCol[i].zName = sqliteStrDup(zBuf);
737 }
738 }
739 pTab->iPKey = -1;
740 return pTab;
741}
742
743/*
drhad2d8302002-05-24 20:31:36 +0000744** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000745**
drhad3cab52002-05-24 02:04:32 +0000746** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh22f70c32002-02-18 01:17:00 +0000747** defines the set of tables that should be scanned.
drhd8bc7082000-06-07 23:51:50 +0000748**
drhad2d8302002-05-24 20:31:36 +0000749** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
750** on joins and the ON and USING clause of joins.
751**
752** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000753** for instances of the "*" operator or the TABLE.* operator.
754** If found, expand each "*" to be every column in every table
755** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000756**
757** Return 0 on success. If there are problems, leave an error message
758** in pParse and return non-zero.
759*/
760static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000761 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000762 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000763 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000764 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000765
766 if( p==0 || p->pSrc==0 ) return 1;
767 pTabList = p->pSrc;
768 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000769
770 /* Look up every table in the table list.
771 */
drhad3cab52002-05-24 02:04:32 +0000772 for(i=0; i<pTabList->nSrc; i++){
drhd8bc7082000-06-07 23:51:50 +0000773 if( pTabList->a[i].pTab ){
774 /* This routine has run before! No need to continue */
775 return 0;
776 }
drhdaffd0e2001-04-11 14:28:42 +0000777 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000778 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000779 assert( pTabList->a[i].pSelect!=0 );
drhad2d8302002-05-24 20:31:36 +0000780 if( pTabList->a[i].zAlias==0 ){
781 char zFakeName[60];
782 sprintf(zFakeName, "sqlite_subquery_%p_",
783 (void*)pTabList->a[i].pSelect);
784 sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
785 }
drh22f70c32002-02-18 01:17:00 +0000786 pTabList->a[i].pTab = pTab =
787 sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
788 pTabList->a[i].pSelect);
789 if( pTab==0 ){
790 return 1;
791 }
792 pTab->isTransient = 1;
793 }else{
drha76b5df2002-02-23 02:32:10 +0000794 /* An ordinary table or view name in the FROM clause */
795 pTabList->a[i].pTab = pTab =
796 sqliteFindTable(pParse->db, pTabList->a[i].zName);
797 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000798 sqliteSetString(&pParse->zErrMsg, "no such table: ",
799 pTabList->a[i].zName, 0);
800 pParse->nErr++;
801 return 1;
802 }
drha76b5df2002-02-23 02:32:10 +0000803 if( pTab->pSelect ){
drh417be792002-03-03 18:59:40 +0000804 if( sqliteViewGetColumnNames(pParse, pTab) ){
805 return 1;
806 }
drhff78bd22002-02-27 01:47:11 +0000807 pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
drha76b5df2002-02-23 02:32:10 +0000808 }
drhd8bc7082000-06-07 23:51:50 +0000809 }
810 }
811
drhad2d8302002-05-24 20:31:36 +0000812 /* Process NATURAL keywords, and ON and USING clauses of joins.
813 */
814 if( sqliteProcessJoin(pParse, p) ) return 1;
815
drh7c917d12001-12-16 20:05:05 +0000816 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000817 ** all columns in all tables. And for every TABLE.* insert the names
818 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000819 ** with the TK_ALL operator for each "*" that it found in the column list.
820 ** The following code just has to locate the TK_ALL expressions and expand
821 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000822 **
823 ** The first loop just checks to see if there are any "*" operators
824 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000825 */
drh7c917d12001-12-16 20:05:05 +0000826 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000827 Expr *pE = pEList->a[k].pExpr;
828 if( pE->op==TK_ALL ) break;
829 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
830 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000831 }
drh54473222002-04-04 02:10:55 +0000832 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000833 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000834 /*
835 ** If we get here it means the result set contains one or more "*"
836 ** operators that need to be expanded. Loop through each expression
837 ** in the result set and expand them one by one.
838 */
drh7c917d12001-12-16 20:05:05 +0000839 struct ExprList_item *a = pEList->a;
840 ExprList *pNew = 0;
841 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000842 Expr *pE = a[k].pExpr;
843 if( pE->op!=TK_ALL &&
844 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
845 /* This particular expression does not need to be expanded.
846 */
drh7c917d12001-12-16 20:05:05 +0000847 pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
848 pNew->a[pNew->nExpr-1].zName = a[k].zName;
849 a[k].pExpr = 0;
850 a[k].zName = 0;
851 }else{
drh54473222002-04-04 02:10:55 +0000852 /* This expression is a "*" or a "TABLE.*" and needs to be
853 ** expanded. */
854 int tableSeen = 0; /* Set to 1 when TABLE matches */
855 Token *pName; /* text of name of TABLE */
856 if( pE->op==TK_DOT && pE->pLeft ){
857 pName = &pE->pLeft->token;
858 }else{
859 pName = 0;
860 }
drhad3cab52002-05-24 02:04:32 +0000861 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000862 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000863 char *zTabName = pTabList->a[i].zAlias;
864 if( zTabName==0 || zTabName[0]==0 ){
865 zTabName = pTab->zName;
866 }
drhc754fa52002-05-27 03:25:51 +0000867 if( pName && (zTabName==0 || zTabName[0]==0 ||
868 sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
869 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +0000870 continue;
871 }
872 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +0000873 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000874 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +0000875 char *zName = pTab->aCol[j].zName;
876
877 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
878 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
879 /* In a NATURAL join, omit the join columns from the
880 ** table on the right */
881 continue;
882 }
883 if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
884 /* In a join with a USING clause, omit columns in the
885 ** using clause from the table on the right. */
886 continue;
887 }
drh22f70c32002-02-18 01:17:00 +0000888 pRight = sqliteExpr(TK_ID, 0, 0, 0);
889 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +0000890 pRight->token.z = zName;
891 pRight->token.n = strlen(zName);
drh54473222002-04-04 02:10:55 +0000892 if( zTabName ){
drh22f70c32002-02-18 01:17:00 +0000893 pLeft = sqliteExpr(TK_ID, 0, 0, 0);
894 if( pLeft==0 ) break;
drh54473222002-04-04 02:10:55 +0000895 pLeft->token.z = zTabName;
896 pLeft->token.n = strlen(zTabName);
drh22f70c32002-02-18 01:17:00 +0000897 pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
898 if( pExpr==0 ) break;
drh7c917d12001-12-16 20:05:05 +0000899 }else{
drh22f70c32002-02-18 01:17:00 +0000900 pExpr = pRight;
901 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +0000902 }
drh7c917d12001-12-16 20:05:05 +0000903 pNew = sqliteExprListAppend(pNew, pExpr, 0);
904 }
drh17e24df2001-11-06 14:10:41 +0000905 }
drh54473222002-04-04 02:10:55 +0000906 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +0000907 if( pName ){
908 sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1,
909 pName->z, pName->n, 0);
910 }else{
911 sqliteSetString(&pParse->zErrMsg, "no tables specified", 0);
912 }
drh54473222002-04-04 02:10:55 +0000913 rc = 1;
914 }
drhd8bc7082000-06-07 23:51:50 +0000915 }
916 }
drh7c917d12001-12-16 20:05:05 +0000917 sqliteExprListDelete(pEList);
918 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +0000919 }
drh54473222002-04-04 02:10:55 +0000920 return rc;
drhd8bc7082000-06-07 23:51:50 +0000921}
922
923/*
drhff78bd22002-02-27 01:47:11 +0000924** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
925** in a select structure. It just sets the pointers to NULL. This
926** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
927** pointer is not NULL, this routine is called recursively on that pointer.
928**
929** This routine is called on the Select structure that defines a
930** VIEW in order to undo any bindings to tables. This is necessary
931** because those tables might be DROPed by a subsequent SQL command.
932*/
933void sqliteSelectUnbind(Select *p){
934 int i;
drhad3cab52002-05-24 02:04:32 +0000935 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +0000936 Table *pTab;
937 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +0000938 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +0000939 if( (pTab = pSrc->a[i].pTab)!=0 ){
940 if( pTab->isTransient ){
941 sqliteDeleteTable(0, pTab);
942 sqliteSelectDelete(pSrc->a[i].pSelect);
943 pSrc->a[i].pSelect = 0;
944 }
945 pSrc->a[i].pTab = 0;
946 if( pSrc->a[i].pSelect ){
947 sqliteSelectUnbind(pSrc->a[i].pSelect);
948 }
949 }
950 }
951}
952
953/*
drhd8bc7082000-06-07 23:51:50 +0000954** This routine associates entries in an ORDER BY expression list with
955** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +0000956** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +0000957** the top-level node is filled in with column number and the iTable
958** value of the top-level node is filled with iTable parameter.
959**
960** If there are prior SELECT clauses, they are processed first. A match
961** in an earlier SELECT takes precedence over a later SELECT.
962**
963** Any entry that does not match is flagged as an error. The number
964** of errors is returned.
965*/
966static int matchOrderbyToColumn(
967 Parse *pParse, /* A place to leave error messages */
968 Select *pSelect, /* Match to result columns of this SELECT */
969 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +0000970 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +0000971 int mustComplete /* If TRUE all ORDER BYs must match */
972){
973 int nErr = 0;
974 int i, j;
975 ExprList *pEList;
976
drhdaffd0e2001-04-11 14:28:42 +0000977 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +0000978 if( mustComplete ){
979 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
980 }
981 if( fillInColumnList(pParse, pSelect) ){
982 return 1;
983 }
984 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +0000985 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
986 return 1;
987 }
drhd8bc7082000-06-07 23:51:50 +0000988 }
989 pEList = pSelect->pEList;
990 for(i=0; i<pOrderBy->nExpr; i++){
991 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +0000992 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +0000993 if( pOrderBy->a[i].done ) continue;
drhe4de1fe2002-06-02 16:09:01 +0000994 if( sqliteExprIsInteger(pE, &iCol) ){
995 if( iCol<=0 || iCol>pEList->nExpr ){
996 char zBuf[200];
997 sprintf(zBuf,"ORDER BY position %d should be between 1 and %d",
998 iCol, pEList->nExpr);
999 sqliteSetString(&pParse->zErrMsg, zBuf, 0);
1000 pParse->nErr++;
1001 nErr++;
1002 break;
1003 }
1004 iCol--;
1005 }
1006 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001007 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001008 char *zName, *zLabel;
1009 zName = pEList->a[j].zName;
1010 assert( pE->token.z );
1011 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
drhd8bc7082000-06-07 23:51:50 +00001012 sqliteDequote(zLabel);
1013 if( sqliteStrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001014 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001015 }
drh6e142f52000-06-08 13:36:40 +00001016 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001017 }
drhe4de1fe2002-06-02 16:09:01 +00001018 if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
1019 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001020 }
1021 }
drhe4de1fe2002-06-02 16:09:01 +00001022 if( iCol>=0 ){
1023 pE->op = TK_COLUMN;
1024 pE->iColumn = iCol;
1025 pE->iTable = iTable;
1026 pOrderBy->a[i].done = 1;
1027 }
1028 if( iCol<0 && mustComplete ){
drhd8bc7082000-06-07 23:51:50 +00001029 char zBuf[30];
1030 sprintf(zBuf,"%d",i+1);
1031 sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf,
1032 " does not match any result column", 0);
1033 pParse->nErr++;
1034 nErr++;
1035 break;
1036 }
1037 }
1038 return nErr;
1039}
1040
1041/*
1042** Get a VDBE for the given parser context. Create a new one if necessary.
1043** If an error occurs, return NULL and leave a message in pParse.
1044*/
1045Vdbe *sqliteGetVdbe(Parse *pParse){
1046 Vdbe *v = pParse->pVdbe;
1047 if( v==0 ){
drh4c504392000-10-16 22:06:40 +00001048 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001049 }
drhd8bc7082000-06-07 23:51:50 +00001050 return v;
1051}
1052
1053
1054/*
drh82c3d632000-06-06 21:56:07 +00001055** This routine is called to process a query that is really the union
1056** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001057**
1058** "p" points to the right-most of the two queries. The results should
1059** be stored in eDest with parameter iParm.
drh82c3d632000-06-06 21:56:07 +00001060*/
1061static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
drh10e5e3c2000-06-08 00:19:02 +00001062 int rc; /* Success code from a subroutine */
1063 Select *pPrior; /* Another SELECT immediately to our left */
1064 Vdbe *v; /* Generate code to this VDBE */
1065 int base; /* Baseline value for pParse->nTab */
drh82c3d632000-06-06 21:56:07 +00001066
drhd8bc7082000-06-07 23:51:50 +00001067 /* Make sure there is no ORDER BY clause on prior SELECTs. Only the
1068 ** last SELECT in the series may have an ORDER BY.
drh82c3d632000-06-06 21:56:07 +00001069 */
drhdaffd0e2001-04-11 14:28:42 +00001070 if( p==0 || p->pPrior==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001071 pPrior = p->pPrior;
1072 if( pPrior->pOrderBy ){
1073 sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
1074 selectOpName(p->op), " not before", 0);
drh82c3d632000-06-06 21:56:07 +00001075 pParse->nErr++;
1076 return 1;
1077 }
1078
drhd8bc7082000-06-07 23:51:50 +00001079 /* Make sure we have a valid query engine. If not, create a new one.
1080 */
1081 v = sqliteGetVdbe(pParse);
1082 if( v==0 ) return 1;
1083
drh1cc3d752002-03-23 00:31:29 +00001084 /* Create the destination temporary table if necessary
1085 */
1086 if( eDest==SRT_TempTable ){
1087 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
1088 eDest = SRT_Table;
1089 }
1090
drhf46f9052002-06-22 02:33:38 +00001091 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001092 */
drh10e5e3c2000-06-08 00:19:02 +00001093 base = pParse->nTab;
drh82c3d632000-06-06 21:56:07 +00001094 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001095 case TK_ALL: {
1096 if( p->pOrderBy==0 ){
1097 rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
1098 if( rc ) return rc;
1099 p->pPrior = 0;
1100 rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
1101 p->pPrior = pPrior;
1102 if( rc ) return rc;
1103 break;
1104 }
1105 /* For UNION ALL ... ORDER BY fall through to the next case */
1106 }
drh82c3d632000-06-06 21:56:07 +00001107 case TK_EXCEPT:
1108 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001109 int unionTab; /* Cursor number of the temporary table holding result */
1110 int op; /* One of the SRT_ operations to apply to self */
1111 int priorOp; /* The SRT_ operation to apply to prior selects */
drhc926afb2002-06-20 03:38:26 +00001112 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
drh82c3d632000-06-06 21:56:07 +00001113
drhd8bc7082000-06-07 23:51:50 +00001114 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drhc926afb2002-06-20 03:38:26 +00001115 if( eDest==priorOp && p->pOrderBy==0 ){
drhd8bc7082000-06-07 23:51:50 +00001116 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001117 ** right.
drhd8bc7082000-06-07 23:51:50 +00001118 */
drh82c3d632000-06-06 21:56:07 +00001119 unionTab = iParm;
1120 }else{
drhd8bc7082000-06-07 23:51:50 +00001121 /* We will need to create our own temporary table to hold the
1122 ** intermediate results.
1123 */
1124 unionTab = pParse->nTab++;
1125 if( p->pOrderBy
1126 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1127 return 1;
1128 }
drhd8bc7082000-06-07 23:51:50 +00001129 if( p->op!=TK_ALL ){
drhc6b52df2002-01-04 03:09:29 +00001130 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
drh99fcd712001-10-13 01:06:47 +00001131 sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drh345fda32001-01-15 22:51:08 +00001132 }else{
drh99fcd712001-10-13 01:06:47 +00001133 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001134 }
drh82c3d632000-06-06 21:56:07 +00001135 }
drhd8bc7082000-06-07 23:51:50 +00001136
1137 /* Code the SELECT statements to our left
1138 */
drh832508b2002-03-02 17:04:07 +00001139 rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001140 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001141
1142 /* Code the current SELECT statement
1143 */
1144 switch( p->op ){
1145 case TK_EXCEPT: op = SRT_Except; break;
1146 case TK_UNION: op = SRT_Union; break;
1147 case TK_ALL: op = SRT_Table; break;
1148 }
drh82c3d632000-06-06 21:56:07 +00001149 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001150 pOrderBy = p->pOrderBy;
1151 p->pOrderBy = 0;
drh832508b2002-03-02 17:04:07 +00001152 rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001153 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001154 p->pOrderBy = pOrderBy;
drh82c3d632000-06-06 21:56:07 +00001155 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001156
1157 /* Convert the data in the temporary table into whatever form
1158 ** it is that we currently need.
1159 */
drhc926afb2002-06-20 03:38:26 +00001160 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001161 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001162 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001163 if( eDest==SRT_Callback ){
1164 generateColumnNames(pParse, p->base, 0, p->pEList);
1165 }
drh82c3d632000-06-06 21:56:07 +00001166 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001167 iCont = sqliteVdbeMakeLabel(v);
1168 sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
1169 iStart = sqliteVdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001170 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001171 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001172 iCont, iBreak);
1173 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001174 sqliteVdbeResolveLabel(v, iCont);
1175 sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
drh99fcd712001-10-13 01:06:47 +00001176 sqliteVdbeResolveLabel(v, iBreak);
1177 sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001178 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001179 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001180 }
drh82c3d632000-06-06 21:56:07 +00001181 }
1182 break;
1183 }
1184 case TK_INTERSECT: {
1185 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001186 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001187
drhd8bc7082000-06-07 23:51:50 +00001188 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001189 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001190 ** by allocating the tables we will need.
1191 */
drh82c3d632000-06-06 21:56:07 +00001192 tab1 = pParse->nTab++;
1193 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001194 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1195 return 1;
1196 }
drhc6b52df2002-01-04 03:09:29 +00001197 sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
drh99fcd712001-10-13 01:06:47 +00001198 sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
drhd8bc7082000-06-07 23:51:50 +00001199
1200 /* Code the SELECTs to our left into temporary table "tab1".
1201 */
drh832508b2002-03-02 17:04:07 +00001202 rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001203 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001204
1205 /* Code the current SELECT into temporary table "tab2"
1206 */
drhc6b52df2002-01-04 03:09:29 +00001207 sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
drh99fcd712001-10-13 01:06:47 +00001208 sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001209 p->pPrior = 0;
drh832508b2002-03-02 17:04:07 +00001210 rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001211 p->pPrior = pPrior;
1212 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001213
1214 /* Generate code to take the intersection of the two temporary
1215 ** tables.
1216 */
drh82c3d632000-06-06 21:56:07 +00001217 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001218 if( eDest==SRT_Callback ){
1219 generateColumnNames(pParse, p->base, 0, p->pEList);
1220 }
drh82c3d632000-06-06 21:56:07 +00001221 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001222 iCont = sqliteVdbeMakeLabel(v);
1223 sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
1224 iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
drh99fcd712001-10-13 01:06:47 +00001225 sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001226 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001227 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001228 iCont, iBreak);
1229 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001230 sqliteVdbeResolveLabel(v, iCont);
1231 sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
drh99fcd712001-10-13 01:06:47 +00001232 sqliteVdbeResolveLabel(v, iBreak);
1233 sqliteVdbeAddOp(v, OP_Close, tab2, 0);
1234 sqliteVdbeAddOp(v, OP_Close, tab1, 0);
drhd8bc7082000-06-07 23:51:50 +00001235 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001236 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001237 }
drh82c3d632000-06-06 21:56:07 +00001238 break;
1239 }
1240 }
1241 assert( p->pEList && pPrior->pEList );
1242 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
drhd8bc7082000-06-07 23:51:50 +00001243 sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ",
1244 selectOpName(p->op), " do not have the same number of result columns", 0);
drh82c3d632000-06-06 21:56:07 +00001245 pParse->nErr++;
1246 return 1;
drh22827922000-06-06 17:27:05 +00001247 }
drh10e5e3c2000-06-08 00:19:02 +00001248 pParse->nTab = base;
drh22827922000-06-06 17:27:05 +00001249 return 0;
1250}
1251
1252/*
drh832508b2002-03-02 17:04:07 +00001253** Recursively scan through an expression tree. For every reference
1254** to a column in table number iFrom, change that reference to the
1255** same column in table number iTo.
1256*/
1257static void changeTables(Expr *pExpr, int iFrom, int iTo){
1258 if( pExpr==0 ) return;
1259 if( pExpr->op==TK_COLUMN && pExpr->iTable==iFrom ){
1260 pExpr->iTable = iTo;
1261 }else{
drh1b2e0322002-03-03 02:49:51 +00001262 static void changeTablesInList(ExprList*, int, int);
drh832508b2002-03-02 17:04:07 +00001263 changeTables(pExpr->pLeft, iFrom, iTo);
1264 changeTables(pExpr->pRight, iFrom, iTo);
drh1b2e0322002-03-03 02:49:51 +00001265 changeTablesInList(pExpr->pList, iFrom, iTo);
1266 }
1267}
1268static void changeTablesInList(ExprList *pList, int iFrom, int iTo){
1269 if( pList ){
1270 int i;
1271 for(i=0; i<pList->nExpr; i++){
1272 changeTables(pList->a[i].pExpr, iFrom, iTo);
drh832508b2002-03-02 17:04:07 +00001273 }
1274 }
1275}
1276
1277/*
1278** Scan through the expression pExpr. Replace every reference to
1279** a column in table number iTable with a copy of the corresponding
drh84e59202002-03-14 14:33:31 +00001280** entry in pEList. (But leave references to the ROWID column
1281** unchanged.) When making a copy of an expression in pEList, change
1282** references to columns in table iSub into references to table iTable.
drh832508b2002-03-02 17:04:07 +00001283**
1284** This routine is part of the flattening procedure. A subquery
1285** whose result set is defined by pEList appears as entry in the
1286** FROM clause of a SELECT such that the VDBE cursor assigned to that
1287** FORM clause entry is iTable. This routine make the necessary
1288** changes to pExpr so that it refers directly to the source table
1289** of the subquery rather the result set of the subquery.
1290*/
1291static void substExpr(Expr *pExpr, int iTable, ExprList *pEList, int iSub){
1292 if( pExpr==0 ) return;
drh84e59202002-03-14 14:33:31 +00001293 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){
drh832508b2002-03-02 17:04:07 +00001294 Expr *pNew;
drh84e59202002-03-14 14:33:31 +00001295 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
drh832508b2002-03-02 17:04:07 +00001296 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1297 pNew = pEList->a[pExpr->iColumn].pExpr;
1298 assert( pNew!=0 );
1299 pExpr->op = pNew->op;
1300 pExpr->pLeft = sqliteExprDup(pNew->pLeft);
1301 pExpr->pRight = sqliteExprDup(pNew->pRight);
1302 pExpr->pList = sqliteExprListDup(pNew->pList);
1303 pExpr->iTable = pNew->iTable;
1304 pExpr->iColumn = pNew->iColumn;
1305 pExpr->iAgg = pNew->iAgg;
drh1b2e0322002-03-03 02:49:51 +00001306 pExpr->token = pNew->token;
drh832508b2002-03-02 17:04:07 +00001307 if( iSub!=iTable ){
1308 changeTables(pExpr, iSub, iTable);
1309 }
1310 }else{
1311 static void substExprList(ExprList*,int,ExprList*,int);
1312 substExpr(pExpr->pLeft, iTable, pEList, iSub);
1313 substExpr(pExpr->pRight, iTable, pEList, iSub);
1314 substExprList(pExpr->pList, iTable, pEList, iSub);
1315 }
1316}
1317static void
1318substExprList(ExprList *pList, int iTable, ExprList *pEList, int iSub){
1319 int i;
1320 if( pList==0 ) return;
1321 for(i=0; i<pList->nExpr; i++){
1322 substExpr(pList->a[i].pExpr, iTable, pEList, iSub);
1323 }
1324}
1325
1326/*
drh1350b032002-02-27 19:00:20 +00001327** This routine attempts to flatten subqueries in order to speed
1328** execution. It returns 1 if it makes changes and 0 if no flattening
1329** occurs.
1330**
1331** To understand the concept of flattening, consider the following
1332** query:
1333**
1334** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1335**
1336** The default way of implementing this query is to execute the
1337** subquery first and store the results in a temporary table, then
1338** run the outer query on that temporary table. This requires two
1339** passes over the data. Furthermore, because the temporary table
1340** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001341** optimized.
drh1350b032002-02-27 19:00:20 +00001342**
drh832508b2002-03-02 17:04:07 +00001343** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001344** a single flat select, like this:
1345**
1346** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1347**
1348** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001349** but only has to scan the data once. And because indices might
1350** exist on the table t1, a complete scan of the data might be
1351** avoided.
drh1350b032002-02-27 19:00:20 +00001352**
drh832508b2002-03-02 17:04:07 +00001353** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001354**
drh832508b2002-03-02 17:04:07 +00001355** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001356**
drh832508b2002-03-02 17:04:07 +00001357** (2) The subquery is not an aggregate or the outer query is not a join.
1358**
1359** (3) The subquery is not a join.
1360**
1361** (4) The subquery is not DISTINCT or the outer query is not a join.
1362**
1363** (5) The subquery is not DISTINCT or the outer query does not use
1364** aggregates.
1365**
1366** (6) The subquery does not use aggregates or the outer query is not
1367** DISTINCT.
1368**
drh08192d52002-04-30 19:20:28 +00001369** (7) The subquery has a FROM clause.
1370**
drhdf199a22002-06-14 22:38:41 +00001371** (8) The subquery does not use LIMIT or the outer query is not a join.
1372**
1373** (9) The subquery does not use LIMIT or the outer query does not use
1374** aggregates.
1375**
1376** (10) The subquery does not use aggregates or the outer query does not
1377** use LIMIT.
1378**
drh832508b2002-03-02 17:04:07 +00001379** In this routine, the "p" parameter is a pointer to the outer query.
1380** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1381** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1382**
1383** If flattening is not attempted, this routine is a no-op and return 0.
1384** If flattening is attempted this routine returns 1.
1385**
1386** All of the expression analysis must occur on both the outer query and
1387** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001388*/
drh832508b2002-03-02 17:04:07 +00001389int flattenSubquery(Select *p, int iFrom, int isAgg, int subqueryIsAgg){
drh0bb28102002-05-08 11:54:14 +00001390 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001391 SrcList *pSrc; /* The FROM clause of the outer query */
1392 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001393 ExprList *pList; /* The result set of the outer query */
drh832508b2002-03-02 17:04:07 +00001394 int i;
1395 int iParent, iSub;
1396 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001397
drh832508b2002-03-02 17:04:07 +00001398 /* Check to see if flattening is permitted. Return 0 if not.
1399 */
1400 if( p==0 ) return 0;
1401 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001402 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001403 pSub = pSrc->a[iFrom].pSelect;
1404 assert( pSub!=0 );
1405 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001406 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001407 pSubSrc = pSub->pSrc;
1408 assert( pSubSrc );
drhad3cab52002-05-24 02:04:32 +00001409 if( pSubSrc->nSrc!=1 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001410 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1411 return 0;
1412 }
drhd11d3822002-06-21 23:01:49 +00001413 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh832508b2002-03-02 17:04:07 +00001414
drh0bb28102002-05-08 11:54:14 +00001415 /* If we reach this point, it means flattening is permitted for the
drh832508b2002-03-02 17:04:07 +00001416 ** i-th entry of the FROM clause in the outer query.
1417 */
1418 iParent = p->base + iFrom;
1419 iSub = pSub->base;
1420 substExprList(p->pEList, iParent, pSub->pEList, iSub);
1421 pList = p->pEList;
1422 for(i=0; i<pList->nExpr; i++){
1423 if( pList->a[i].zName==0 ){
1424 Expr *pExpr = pList->a[i].pExpr;
1425 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
1426 }
1427 }
drh1b2e0322002-03-03 02:49:51 +00001428 if( isAgg ){
1429 substExprList(p->pGroupBy, iParent, pSub->pEList, iSub);
1430 substExpr(p->pHaving, iParent, pSub->pEList, iSub);
1431 }
drh832508b2002-03-02 17:04:07 +00001432 substExprList(p->pOrderBy, iParent, pSub->pEList, iSub);
1433 if( pSub->pWhere ){
1434 pWhere = sqliteExprDup(pSub->pWhere);
1435 if( iParent!=iSub ){
1436 changeTables(pWhere, iSub, iParent);
1437 }
1438 }else{
1439 pWhere = 0;
1440 }
1441 if( subqueryIsAgg ){
1442 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001443 p->pHaving = p->pWhere;
1444 p->pWhere = pWhere;
drh832508b2002-03-02 17:04:07 +00001445 substExpr(p->pHaving, iParent, pSub->pEList, iSub);
drh1b2e0322002-03-03 02:49:51 +00001446 if( pSub->pHaving ){
1447 Expr *pHaving = sqliteExprDup(pSub->pHaving);
1448 if( iParent!=iSub ){
1449 changeTables(pHaving, iSub, iParent);
1450 }
1451 if( p->pHaving ){
1452 p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
1453 }else{
1454 p->pHaving = pHaving;
1455 }
1456 }
1457 assert( p->pGroupBy==0 );
1458 p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
1459 if( iParent!=iSub ){
1460 changeTablesInList(p->pGroupBy, iSub, iParent);
1461 }
drh832508b2002-03-02 17:04:07 +00001462 }else if( p->pWhere==0 ){
1463 p->pWhere = pWhere;
1464 }else{
1465 substExpr(p->pWhere, iParent, pSub->pEList, iSub);
1466 if( pWhere ){
1467 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1468 }
1469 }
1470 p->isDistinct = p->isDistinct || pSub->isDistinct;
drhdf199a22002-06-14 22:38:41 +00001471 if( pSub->nLimit>=0 ){
1472 if( p->nLimit<0 ){
1473 p->nLimit = pSub->nLimit;
1474 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1475 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1476 }
1477 }
1478 p->nOffset += pSub->nOffset;
drh832508b2002-03-02 17:04:07 +00001479 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1480 sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1481 }
1482 pSrc->a[iFrom].pTab = pSubSrc->a[0].pTab;
1483 pSubSrc->a[0].pTab = 0;
1484 pSrc->a[iFrom].pSelect = pSubSrc->a[0].pSelect;
1485 pSubSrc->a[0].pSelect = 0;
1486 sqliteSelectDelete(pSub);
1487 return 1;
1488}
drh1350b032002-02-27 19:00:20 +00001489
1490/*
drh9562b552002-02-19 15:00:07 +00001491** Analyze the SELECT statement passed in as an argument to see if it
1492** is a simple min() or max() query. If it is and this query can be
1493** satisfied using a single seek to the beginning or end of an index,
1494** then generate the code for this SELECT return 1. If this is not a
1495** simple min() or max() query, then return 0;
1496**
1497** A simply min() or max() query looks like this:
1498**
1499** SELECT min(a) FROM table;
1500** SELECT max(a) FROM table;
1501**
1502** The query may have only a single table in its FROM argument. There
1503** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1504** be the min() or max() of a single column of the table. The column
1505** in the min() or max() function must be indexed.
1506**
1507** The parameters to this routine are the same as for sqliteSelect().
1508** See the header comment on that routine for additional information.
1509*/
1510static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1511 Expr *pExpr;
1512 int iCol;
1513 Table *pTab;
1514 Index *pIdx;
1515 int base;
1516 Vdbe *v;
1517 int openOp;
1518 int seekOp;
1519 int cont;
1520 ExprList eList;
1521 struct ExprList_item eListItem;
1522
1523 /* Check to see if this query is a simple min() or max() query. Return
1524 ** zero if it is not.
1525 */
1526 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drhad3cab52002-05-24 02:04:32 +00001527 if( p->pSrc->nSrc!=1 ) return 0;
drh9562b552002-02-19 15:00:07 +00001528 if( p->pEList->nExpr!=1 ) return 0;
1529 pExpr = p->pEList->a[0].pExpr;
1530 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
1531 if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
drh0bce8352002-02-28 00:41:10 +00001532 if( pExpr->token.n!=3 ) return 0;
1533 if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
1534 seekOp = OP_Rewind;
1535 }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
1536 seekOp = OP_Last;
1537 }else{
1538 return 0;
1539 }
drh9562b552002-02-19 15:00:07 +00001540 pExpr = pExpr->pList->a[0].pExpr;
1541 if( pExpr->op!=TK_COLUMN ) return 0;
1542 iCol = pExpr->iColumn;
1543 pTab = p->pSrc->a[0].pTab;
1544
1545 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00001546 ** Check to make sure we have an index and make pIdx point to the
1547 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
1548 ** key column, no index is necessary so set pIdx to NULL. If no
1549 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00001550 */
1551 if( iCol<0 ){
1552 pIdx = 0;
1553 }else{
1554 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1555 assert( pIdx->nColumn>=1 );
1556 if( pIdx->aiColumn[0]==iCol ) break;
1557 }
1558 if( pIdx==0 ) return 0;
1559 }
1560
drh17f71932002-02-21 12:01:27 +00001561 /* Identify column names if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00001562 ** step is skipped if the output is going to a table or a memory cell.
1563 */
1564 v = sqliteGetVdbe(pParse);
1565 if( v==0 ) return 0;
1566 if( eDest==SRT_Callback ){
drh832508b2002-03-02 17:04:07 +00001567 generateColumnNames(pParse, p->base, p->pSrc, p->pEList);
drh9562b552002-02-19 15:00:07 +00001568 }
1569
drh17f71932002-02-21 12:01:27 +00001570 /* Generating code to find the min or the max. Basically all we have
1571 ** to do is find the first or the last entry in the chosen index. If
1572 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
1573 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00001574 */
drh5cf8e8c2002-02-19 22:42:05 +00001575 if( !pParse->schemaVerified && (pParse->db->flags & SQLITE_InTrans)==0 ){
1576 sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
1577 pParse->schemaVerified = 1;
1578 }
drh9562b552002-02-19 15:00:07 +00001579 openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
drh832508b2002-03-02 17:04:07 +00001580 base = p->base;
drh9562b552002-02-19 15:00:07 +00001581 sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001582 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
drh9562b552002-02-19 15:00:07 +00001583 if( pIdx==0 ){
1584 sqliteVdbeAddOp(v, seekOp, base, 0);
1585 }else{
1586 sqliteVdbeAddOp(v, openOp, base+1, pIdx->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001587 sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
drh9562b552002-02-19 15:00:07 +00001588 sqliteVdbeAddOp(v, seekOp, base+1, 0);
1589 sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
1590 sqliteVdbeAddOp(v, OP_Close, base+1, 0);
1591 sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
1592 }
drh5cf8e8c2002-02-19 22:42:05 +00001593 eList.nExpr = 1;
1594 memset(&eListItem, 0, sizeof(eListItem));
1595 eList.a = &eListItem;
1596 eList.a[0].pExpr = pExpr;
drh9562b552002-02-19 15:00:07 +00001597 cont = sqliteVdbeMakeLabel(v);
drh38640e12002-07-05 21:42:36 +00001598 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
drh9562b552002-02-19 15:00:07 +00001599 sqliteVdbeResolveLabel(v, cont);
1600 sqliteVdbeAddOp(v, OP_Close, base, 0);
1601 return 1;
1602}
1603
1604/*
drh9bb61fe2000-06-05 16:01:39 +00001605** Generate code for the given SELECT statement.
1606**
drhfef52082000-06-06 01:50:43 +00001607** The results are distributed in various ways depending on the
1608** value of eDest and iParm.
1609**
1610** eDest Value Result
1611** ------------ -------------------------------------------
1612** SRT_Callback Invoke the callback for each row of the result.
1613**
1614** SRT_Mem Store first result in memory cell iParm
1615**
1616** SRT_Set Store results as keys of a table with cursor iParm
1617**
drh82c3d632000-06-06 21:56:07 +00001618** SRT_Union Store results as a key in a temporary table iParm
1619**
drhc4a3c772001-04-04 11:48:57 +00001620** SRT_Except Remove results form the temporary table iParm.
1621**
1622** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00001623**
1624** This routine returns the number of errors. If any errors are
1625** encountered, then an appropriate error message is left in
1626** pParse->zErrMsg.
1627**
1628** This routine does NOT free the Select structure passed in. The
1629** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00001630**
1631** The pParent, parentTab, and *pParentAgg fields are filled in if this
1632** SELECT is a subquery. This routine may try to combine this SELECT
1633** with its parent to form a single flat query. In so doing, it might
1634** change the parent query from a non-aggregate to an aggregate query.
1635** For that reason, the pParentAgg flag is passed as a pointer, so it
1636** can be changed.
drh9bb61fe2000-06-05 16:01:39 +00001637*/
1638int sqliteSelect(
drhcce7d172000-05-31 15:34:51 +00001639 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00001640 Select *p, /* The SELECT statement being coded. */
drh82c3d632000-06-06 21:56:07 +00001641 int eDest, /* One of: SRT_Callback Mem Set Union Except */
drh832508b2002-03-02 17:04:07 +00001642 int iParm, /* Save result in this memory location, if >=0 */
1643 Select *pParent, /* Another SELECT for which this is a sub-query */
1644 int parentTab, /* Index in pParent->pSrc of this query */
drh1b2e0322002-03-03 02:49:51 +00001645 int *pParentAgg /* True if pParent uses aggregate functions */
drhcce7d172000-05-31 15:34:51 +00001646){
drhd8bc7082000-06-07 23:51:50 +00001647 int i;
drhcce7d172000-05-31 15:34:51 +00001648 WhereInfo *pWInfo;
1649 Vdbe *v;
1650 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00001651 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00001652 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00001653 Expr *pWhere; /* The WHERE clause. May be NULL */
1654 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00001655 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
1656 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00001657 int isDistinct; /* True if the DISTINCT keyword is present */
1658 int distinct; /* Table to use for the distinct set */
drh10e5e3c2000-06-08 00:19:02 +00001659 int base; /* First cursor available for use */
drh1d83f052002-02-17 00:30:36 +00001660 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00001661
drhdaffd0e2001-04-11 14:28:42 +00001662 if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
1663
drh82c3d632000-06-06 21:56:07 +00001664 /* If there is are a sequence of queries, do the earlier ones first.
1665 */
1666 if( p->pPrior ){
1667 return multiSelect(pParse, p, eDest, iParm);
1668 }
1669
1670 /* Make local copies of the parameters for this query.
1671 */
drh9bb61fe2000-06-05 16:01:39 +00001672 pTabList = p->pSrc;
1673 pWhere = p->pWhere;
1674 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00001675 pGroupBy = p->pGroupBy;
1676 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00001677 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00001678
drh832508b2002-03-02 17:04:07 +00001679 /* Allocate a block of VDBE cursors, one for each table in the FROM clause.
1680 ** The WHERE processing requires that the cursors for the tables in the
1681 ** FROM clause be consecutive.
drh10e5e3c2000-06-08 00:19:02 +00001682 */
drh832508b2002-03-02 17:04:07 +00001683 base = p->base = pParse->nTab;
drhad3cab52002-05-24 02:04:32 +00001684 pParse->nTab += pTabList->nSrc;
drh10e5e3c2000-06-08 00:19:02 +00001685
drh9bb61fe2000-06-05 16:01:39 +00001686 /*
1687 ** Do not even attempt to generate any code if we have already seen
1688 ** errors before this routine starts.
1689 */
drh1d83f052002-02-17 00:30:36 +00001690 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001691
drhd8bc7082000-06-07 23:51:50 +00001692 /* Look up every table in the table list and create an appropriate
1693 ** columnlist in pEList if there isn't one already. (The parser leaves
drh967e8b72000-06-21 13:59:10 +00001694 ** a NULL in the p->pEList if the SQL said "SELECT * FROM ...")
drhcce7d172000-05-31 15:34:51 +00001695 */
drhd8bc7082000-06-07 23:51:50 +00001696 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00001697 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001698 }
drhad2d8302002-05-24 20:31:36 +00001699 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00001700 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00001701 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001702
drh22827922000-06-06 17:27:05 +00001703 /* If writing to memory or generating a set
1704 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00001705 */
drhfef52082000-06-06 01:50:43 +00001706 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
drh19a775c2000-06-05 18:54:46 +00001707 sqliteSetString(&pParse->zErrMsg, "only a single result allowed for "
1708 "a SELECT that is part of an expression", 0);
1709 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +00001710 goto select_end;
drh19a775c2000-06-05 18:54:46 +00001711 }
1712
drhc926afb2002-06-20 03:38:26 +00001713 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00001714 */
drhc926afb2002-06-20 03:38:26 +00001715 switch( eDest ){
1716 case SRT_Union:
1717 case SRT_Except:
1718 case SRT_Discard:
1719 pOrderBy = 0;
1720 break;
1721 default:
1722 break;
drh22827922000-06-06 17:27:05 +00001723 }
1724
drh10e5e3c2000-06-08 00:19:02 +00001725 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00001726 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00001727 **
drh967e8b72000-06-21 13:59:10 +00001728 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00001729 */
drh4794b982000-06-06 13:54:14 +00001730 for(i=0; i<pEList->nExpr; i++){
drh832508b2002-03-02 17:04:07 +00001731 if( sqliteExprResolveIds(pParse, base, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001732 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001733 }
drh22827922000-06-06 17:27:05 +00001734 if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00001735 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001736 }
1737 }
drhcce7d172000-05-31 15:34:51 +00001738 if( pWhere ){
drh832508b2002-03-02 17:04:07 +00001739 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00001740 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001741 }
1742 if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00001743 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001744 }
1745 }
1746 if( pOrderBy ){
1747 for(i=0; i<pOrderBy->nExpr; i++){
drh22827922000-06-06 17:27:05 +00001748 Expr *pE = pOrderBy->a[i].pExpr;
drh92086432002-01-22 14:11:29 +00001749 if( sqliteExprIsConstant(pE) ){
drhe4de1fe2002-06-02 16:09:01 +00001750 int iCol;
1751 if( sqliteExprIsInteger(pE, &iCol)==0 ){
1752 sqliteSetString(&pParse->zErrMsg,
1753 "ORDER BY terms must not be non-integer constants", 0);
1754 pParse->nErr++;
1755 goto select_end;
1756 }else if( iCol<=0 || iCol>pEList->nExpr ){
1757 char zBuf[2000];
1758 sprintf(zBuf,"ORDER BY column number %d out of range - should be "
1759 "between 1 and %d", iCol, pEList->nExpr);
1760 sqliteSetString(&pParse->zErrMsg, zBuf, 0);
1761 pParse->nErr++;
1762 goto select_end;
1763 }
1764 sqliteExprDelete(pE);
1765 pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00001766 }
drh832508b2002-03-02 17:04:07 +00001767 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00001768 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001769 }
drh22827922000-06-06 17:27:05 +00001770 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00001771 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001772 }
1773 }
1774 }
drh22827922000-06-06 17:27:05 +00001775 if( pGroupBy ){
1776 for(i=0; i<pGroupBy->nExpr; i++){
1777 Expr *pE = pGroupBy->a[i].pExpr;
drh92086432002-01-22 14:11:29 +00001778 if( sqliteExprIsConstant(pE) ){
1779 sqliteSetString(&pParse->zErrMsg,
1780 "GROUP BY expressions should not be constant", 0);
1781 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +00001782 goto select_end;
drh92086432002-01-22 14:11:29 +00001783 }
drh832508b2002-03-02 17:04:07 +00001784 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00001785 goto select_end;
drh22827922000-06-06 17:27:05 +00001786 }
1787 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00001788 goto select_end;
drh22827922000-06-06 17:27:05 +00001789 }
1790 }
1791 }
1792 if( pHaving ){
1793 if( pGroupBy==0 ){
drhda932812000-06-06 18:00:15 +00001794 sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required "
1795 "before HAVING", 0);
drh22827922000-06-06 17:27:05 +00001796 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +00001797 goto select_end;
drh22827922000-06-06 17:27:05 +00001798 }
drh832508b2002-03-02 17:04:07 +00001799 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00001800 goto select_end;
drh22827922000-06-06 17:27:05 +00001801 }
drhda932812000-06-06 18:00:15 +00001802 if( sqliteExprCheck(pParse, pHaving, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00001803 goto select_end;
drh22827922000-06-06 17:27:05 +00001804 }
drhcce7d172000-05-31 15:34:51 +00001805 }
1806
drh9562b552002-02-19 15:00:07 +00001807 /* Check for the special case of a min() or max() function by itself
1808 ** in the result set.
1809 */
1810 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
drh5cf8e8c2002-02-19 22:42:05 +00001811 rc = 0;
drh9562b552002-02-19 15:00:07 +00001812 goto select_end;
1813 }
1814
drhd820cb12002-02-18 03:21:45 +00001815 /* Begin generating code.
1816 */
1817 v = sqliteGetVdbe(pParse);
1818 if( v==0 ) goto select_end;
1819
drh0bb28102002-05-08 11:54:14 +00001820 /* Identify column names if we will be using in the callback. This
1821 ** step is skipped if the output is going to a table or a memory cell.
1822 */
1823 if( eDest==SRT_Callback ){
1824 generateColumnNames(pParse, p->base, pTabList, pEList);
1825 }
1826
1827 /* Set the limiter
1828 */
1829 if( p->nLimit<=0 ){
drhd11d3822002-06-21 23:01:49 +00001830 p->nLimit = -1;
drh0bb28102002-05-08 11:54:14 +00001831 p->nOffset = 0;
1832 }else{
drhd11d3822002-06-21 23:01:49 +00001833 int iMem = pParse->nMem++;
1834 sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
drhbf5cd972002-06-24 12:20:23 +00001835 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
drhd11d3822002-06-21 23:01:49 +00001836 p->nLimit = iMem;
1837 if( p->nOffset<=0 ){
1838 p->nOffset = 0;
1839 }else{
1840 iMem = pParse->nMem++;
1841 sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
drhbf5cd972002-06-24 12:20:23 +00001842 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
drhd11d3822002-06-21 23:01:49 +00001843 p->nOffset = iMem;
1844 }
drh0bb28102002-05-08 11:54:14 +00001845 }
1846
drhd820cb12002-02-18 03:21:45 +00001847 /* Generate code for all sub-queries in the FROM clause
1848 */
drhad3cab52002-05-24 02:04:32 +00001849 for(i=0; i<pTabList->nSrc; i++){
drha76b5df2002-02-23 02:32:10 +00001850 if( pTabList->a[i].pSelect==0 ) continue;
drh2d0794e2002-03-03 03:03:52 +00001851 sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable, base+i,
drh1b2e0322002-03-03 02:49:51 +00001852 p, i, &isAgg);
1853 pTabList = p->pSrc;
1854 pWhere = p->pWhere;
drhacd4c692002-03-07 02:02:51 +00001855 if( eDest==SRT_Callback ){
1856 pOrderBy = p->pOrderBy;
1857 }
drh1b2e0322002-03-03 02:49:51 +00001858 pGroupBy = p->pGroupBy;
1859 pHaving = p->pHaving;
1860 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00001861 }
1862
drh832508b2002-03-02 17:04:07 +00001863 /* Check to see if this is a subquery that can be "flattened" into its parent.
1864 ** If flattening is a possiblity, do so and return immediately.
1865 */
drh1b2e0322002-03-03 02:49:51 +00001866 if( pParent && pParentAgg &&
1867 flattenSubquery(pParent, parentTab, *pParentAgg, isAgg) ){
1868 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00001869 return rc;
1870 }
drh832508b2002-03-02 17:04:07 +00001871
drh2d0794e2002-03-03 03:03:52 +00001872 /* If the output is destined for a temporary table, open that table.
1873 */
1874 if( eDest==SRT_TempTable ){
1875 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
1876 }
1877
drh22827922000-06-06 17:27:05 +00001878 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00001879 */
drhd820cb12002-02-18 03:21:45 +00001880 sqliteAggregateInfoReset(pParse);
drh22827922000-06-06 17:27:05 +00001881 if( isAgg ){
drh0bce8352002-02-28 00:41:10 +00001882 assert( pParse->nAgg==0 );
drh22827922000-06-06 17:27:05 +00001883 for(i=0; i<pEList->nExpr; i++){
1884 if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001885 goto select_end;
drh22827922000-06-06 17:27:05 +00001886 }
1887 }
1888 if( pGroupBy ){
1889 for(i=0; i<pGroupBy->nExpr; i++){
1890 if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001891 goto select_end;
drh22827922000-06-06 17:27:05 +00001892 }
1893 }
1894 }
1895 if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00001896 goto select_end;
drh22827922000-06-06 17:27:05 +00001897 }
drh191b6902000-06-08 11:13:01 +00001898 if( pOrderBy ){
1899 for(i=0; i<pOrderBy->nExpr; i++){
1900 if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001901 goto select_end;
drh191b6902000-06-08 11:13:01 +00001902 }
1903 }
1904 }
drhefb72512000-05-31 20:00:52 +00001905 }
1906
drh22827922000-06-06 17:27:05 +00001907 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00001908 */
1909 if( isAgg ){
drh99fcd712001-10-13 01:06:47 +00001910 sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00001911 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00001912 FuncDef *pFunc;
1913 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drh1350b032002-02-27 19:00:20 +00001914 sqliteVdbeAddOp(v, OP_AggInit, 0, i);
drh0bce8352002-02-28 00:41:10 +00001915 sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
drhe5095352002-02-24 03:25:14 +00001916 }
1917 }
drh1bee3d72001-10-15 00:44:35 +00001918 if( pGroupBy==0 ){
1919 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00001920 sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00001921 }
drhcce7d172000-05-31 15:34:51 +00001922 }
1923
drh19a775c2000-06-05 18:54:46 +00001924 /* Initialize the memory cell to NULL
1925 */
drhfef52082000-06-06 01:50:43 +00001926 if( eDest==SRT_Mem ){
drh99fcd712001-10-13 01:06:47 +00001927 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh8721ce42001-11-07 14:22:00 +00001928 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00001929 }
1930
drh832508b2002-03-02 17:04:07 +00001931 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00001932 */
drh19a775c2000-06-05 18:54:46 +00001933 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00001934 distinct = pParse->nTab++;
drhc6b52df2002-01-04 03:09:29 +00001935 sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
drh832508b2002-03-02 17:04:07 +00001936 }else{
1937 distinct = -1;
drhefb72512000-05-31 20:00:52 +00001938 }
drh832508b2002-03-02 17:04:07 +00001939
1940 /* Begin the database scan
1941 */
drhe3184742002-06-19 14:27:05 +00001942 pWInfo = sqliteWhereBegin(pParse, p->base, pTabList, pWhere, 0, &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00001943 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001944
drh22827922000-06-06 17:27:05 +00001945 /* Use the standard inner loop if we are not dealing with
1946 ** aggregates
drhcce7d172000-05-31 15:34:51 +00001947 */
drhda9d6c42000-05-31 18:20:14 +00001948 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00001949 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
1950 iParm, pWInfo->iContinue, pWInfo->iBreak) ){
drh1d83f052002-02-17 00:30:36 +00001951 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00001952 }
drhcce7d172000-05-31 15:34:51 +00001953 }
drhefb72512000-05-31 20:00:52 +00001954
drhe3184742002-06-19 14:27:05 +00001955 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00001956 ** processing.
drhefb72512000-05-31 20:00:52 +00001957 */
drh22827922000-06-06 17:27:05 +00001958 else{
drh22827922000-06-06 17:27:05 +00001959 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00001960 int lbl1;
drh22827922000-06-06 17:27:05 +00001961 for(i=0; i<pGroupBy->nExpr; i++){
1962 sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
1963 }
drh99fcd712001-10-13 01:06:47 +00001964 sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
drh38640e12002-07-05 21:42:36 +00001965 if( pParse->db->file_format>=3 ) sqliteAddKeyType(v, pGroupBy);
drh1bee3d72001-10-15 00:44:35 +00001966 lbl1 = sqliteVdbeMakeLabel(v);
drh99fcd712001-10-13 01:06:47 +00001967 sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh22827922000-06-06 17:27:05 +00001968 for(i=0; i<pParse->nAgg; i++){
1969 if( pParse->aAgg[i].isAgg ) continue;
1970 sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
drh99fcd712001-10-13 01:06:47 +00001971 sqliteVdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00001972 }
drh22827922000-06-06 17:27:05 +00001973 sqliteVdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00001974 }
drh22827922000-06-06 17:27:05 +00001975 for(i=0; i<pParse->nAgg; i++){
1976 Expr *pE;
drh0bce8352002-02-28 00:41:10 +00001977 int j;
drh22827922000-06-06 17:27:05 +00001978 if( !pParse->aAgg[i].isAgg ) continue;
1979 pE = pParse->aAgg[i].pExpr;
drh22827922000-06-06 17:27:05 +00001980 assert( pE->op==TK_AGG_FUNCTION );
drh0bce8352002-02-28 00:41:10 +00001981 if( pE->pList ){
1982 for(j=0; j<pE->pList->nExpr; j++){
1983 sqliteExprCode(pParse, pE->pList->a[j].pExpr);
1984 }
drhe5095352002-02-24 03:25:14 +00001985 }
drh0bce8352002-02-28 00:41:10 +00001986 sqliteVdbeAddOp(v, OP_Integer, i, 0);
drhf55f25f2002-02-28 01:46:11 +00001987 sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
drh0bce8352002-02-28 00:41:10 +00001988 assert( pParse->aAgg[i].pFunc!=0 );
1989 assert( pParse->aAgg[i].pFunc->xStep!=0 );
1990 sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
drh22827922000-06-06 17:27:05 +00001991 }
drhcce7d172000-05-31 15:34:51 +00001992 }
1993
1994 /* End the database scan loop.
1995 */
1996 sqliteWhereEnd(pWInfo);
1997
drh22827922000-06-06 17:27:05 +00001998 /* If we are processing aggregates, we need to set up a second loop
1999 ** over all of the aggregate values and process them.
2000 */
2001 if( isAgg ){
2002 int endagg = sqliteVdbeMakeLabel(v);
2003 int startagg;
drh99fcd712001-10-13 01:06:47 +00002004 startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002005 pParse->useAgg = 1;
2006 if( pHaving ){
drhf5905aa2002-05-26 20:54:33 +00002007 sqliteExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002008 }
drhdf199a22002-06-14 22:38:41 +00002009 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2010 iParm, startagg, endagg) ){
drh1d83f052002-02-17 00:30:36 +00002011 goto select_end;
drh22827922000-06-06 17:27:05 +00002012 }
drh99fcd712001-10-13 01:06:47 +00002013 sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
2014 sqliteVdbeResolveLabel(v, endagg);
2015 sqliteVdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002016 pParse->useAgg = 0;
2017 }
2018
drhcce7d172000-05-31 15:34:51 +00002019 /* If there is an ORDER BY clause, then we need to sort the results
2020 ** and send them to the callback one by one.
2021 */
2022 if( pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00002023 generateSortTail(p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002024 }
drh6a535342001-10-19 16:44:56 +00002025
2026
2027 /* Issue a null callback if that is what the user wants.
2028 */
2029 if( (pParse->db->flags & SQLITE_NullCallback)!=0 && eDest==SRT_Callback ){
2030 sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
2031 }
2032
drh1d83f052002-02-17 00:30:36 +00002033 /* The SELECT was successfully coded. Set the return code to 0
2034 ** to indicate no errors.
2035 */
2036 rc = 0;
2037
2038 /* Control jumps to here if an error is encountered above, or upon
2039 ** successful coding of the SELECT.
2040 */
2041select_end:
drh832508b2002-03-02 17:04:07 +00002042 pParse->nTab = base;
drh1d83f052002-02-17 00:30:36 +00002043 sqliteAggregateInfoReset(pParse);
2044 return rc;
drhcce7d172000-05-31 15:34:51 +00002045}