blob: 882e8885c3c0fe3dab2419aed314bb172aded4f8 [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**
drh38640e12002-07-05 21:42:36 +000015** $Id: select.c,v 1.103 2002/07/05 21:42:37 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;
629 if( p->span.z && p->span.z[0] && !showFullNames ){
drh99fcd712001-10-13 01:06:47 +0000630 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
631 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
drhe1b6a5b2000-07-29 13:06:59 +0000632 sqliteVdbeCompressSpace(v, addr);
drh1bee3d72001-10-15 00:44:35 +0000633 }else if( p->op==TK_COLUMN && pTabList ){
drh832508b2002-03-02 17:04:07 +0000634 Table *pTab = pTabList->a[p->iTable - base].pTab;
drh97665872002-02-13 23:22:53 +0000635 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000636 int iCol = p->iColumn;
637 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000638 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000639 if( iCol<0 ){
640 zCol = "_ROWID_";
641 zType = "INTEGER";
642 }else{
643 zCol = pTab->aCol[iCol].zName;
644 zType = pTab->aCol[iCol].zType;
645 }
drhad3cab52002-05-24 02:04:32 +0000646 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 }
drh1bee3d72001-10-15 00:44:35 +0000660 }else if( p->span.z && p->span.z[0] ){
661 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
662 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
663 sqliteVdbeCompressSpace(v, addr);
664 }else{
665 char zName[30];
666 assert( p->op!=TK_COLUMN || pTabList==0 );
667 sprintf(zName, "column%d", i+1);
668 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
669 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000670 }
drhb1363202002-06-26 02:45:03 +0000671 if( zType==0 ){
672 if( sqliteExprType(p)==SQLITE_SO_TEXT ){
673 zType = "TEXT";
674 }else{
675 zType = "NUMERIC";
676 }
677 }
678 sqliteVdbeAddOp(v, OP_ColumnName, i + pEList->nExpr + 1, 0);
679 sqliteVdbeChangeP3(v, -1, zType, P3_STATIC);
drh82c3d632000-06-06 21:56:07 +0000680 }
681}
682
683/*
drhd8bc7082000-06-07 23:51:50 +0000684** Name of the connection operator, used for error messages.
685*/
686static const char *selectOpName(int id){
687 char *z;
688 switch( id ){
689 case TK_ALL: z = "UNION ALL"; break;
690 case TK_INTERSECT: z = "INTERSECT"; break;
691 case TK_EXCEPT: z = "EXCEPT"; break;
692 default: z = "UNION"; break;
693 }
694 return z;
695}
696
697/*
drh22f70c32002-02-18 01:17:00 +0000698** Given a SELECT statement, generate a Table structure that describes
699** the result set of that SELECT.
700*/
701Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
702 Table *pTab;
703 int i;
704 ExprList *pEList;
705 static int fillInColumnList(Parse*, Select*);
706
707 if( fillInColumnList(pParse, pSelect) ){
708 return 0;
709 }
710 pTab = sqliteMalloc( sizeof(Table) );
711 if( pTab==0 ){
712 return 0;
713 }
714 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
715 pEList = pSelect->pEList;
716 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000717 assert( pTab->nCol>0 );
drh22f70c32002-02-18 01:17:00 +0000718 pTab->aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
719 for(i=0; i<pTab->nCol; i++){
720 Expr *p;
721 if( pEList->a[i].zName ){
722 pTab->aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
723 }else if( (p=pEList->a[i].pExpr)->span.z && p->span.z[0] ){
724 sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drhd820cb12002-02-18 03:21:45 +0000725 }else if( p->op==TK_DOT && p->pRight && p->pRight->token.z &&
726 p->pRight->token.z[0] ){
727 sqliteSetNString(&pTab->aCol[i].zName,
728 p->pRight->token.z, p->pRight->token.n, 0);
drh22f70c32002-02-18 01:17:00 +0000729 }else{
730 char zBuf[30];
731 sprintf(zBuf, "column%d", i+1);
732 pTab->aCol[i].zName = sqliteStrDup(zBuf);
733 }
734 }
735 pTab->iPKey = -1;
736 return pTab;
737}
738
739/*
drhad2d8302002-05-24 20:31:36 +0000740** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000741**
drhad3cab52002-05-24 02:04:32 +0000742** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh22f70c32002-02-18 01:17:00 +0000743** defines the set of tables that should be scanned.
drhd8bc7082000-06-07 23:51:50 +0000744**
drhad2d8302002-05-24 20:31:36 +0000745** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
746** on joins and the ON and USING clause of joins.
747**
748** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000749** for instances of the "*" operator or the TABLE.* operator.
750** If found, expand each "*" to be every column in every table
751** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000752**
753** Return 0 on success. If there are problems, leave an error message
754** in pParse and return non-zero.
755*/
756static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000757 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000758 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000759 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000760 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000761
762 if( p==0 || p->pSrc==0 ) return 1;
763 pTabList = p->pSrc;
764 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000765
766 /* Look up every table in the table list.
767 */
drhad3cab52002-05-24 02:04:32 +0000768 for(i=0; i<pTabList->nSrc; i++){
drhd8bc7082000-06-07 23:51:50 +0000769 if( pTabList->a[i].pTab ){
770 /* This routine has run before! No need to continue */
771 return 0;
772 }
drhdaffd0e2001-04-11 14:28:42 +0000773 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000774 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000775 assert( pTabList->a[i].pSelect!=0 );
drhad2d8302002-05-24 20:31:36 +0000776 if( pTabList->a[i].zAlias==0 ){
777 char zFakeName[60];
778 sprintf(zFakeName, "sqlite_subquery_%p_",
779 (void*)pTabList->a[i].pSelect);
780 sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
781 }
drh22f70c32002-02-18 01:17:00 +0000782 pTabList->a[i].pTab = pTab =
783 sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
784 pTabList->a[i].pSelect);
785 if( pTab==0 ){
786 return 1;
787 }
788 pTab->isTransient = 1;
789 }else{
drha76b5df2002-02-23 02:32:10 +0000790 /* An ordinary table or view name in the FROM clause */
791 pTabList->a[i].pTab = pTab =
792 sqliteFindTable(pParse->db, pTabList->a[i].zName);
793 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000794 sqliteSetString(&pParse->zErrMsg, "no such table: ",
795 pTabList->a[i].zName, 0);
796 pParse->nErr++;
797 return 1;
798 }
drha76b5df2002-02-23 02:32:10 +0000799 if( pTab->pSelect ){
drh417be792002-03-03 18:59:40 +0000800 if( sqliteViewGetColumnNames(pParse, pTab) ){
801 return 1;
802 }
drhff78bd22002-02-27 01:47:11 +0000803 pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
drha76b5df2002-02-23 02:32:10 +0000804 }
drhd8bc7082000-06-07 23:51:50 +0000805 }
806 }
807
drhad2d8302002-05-24 20:31:36 +0000808 /* Process NATURAL keywords, and ON and USING clauses of joins.
809 */
810 if( sqliteProcessJoin(pParse, p) ) return 1;
811
drh7c917d12001-12-16 20:05:05 +0000812 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000813 ** all columns in all tables. And for every TABLE.* insert the names
814 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000815 ** with the TK_ALL operator for each "*" that it found in the column list.
816 ** The following code just has to locate the TK_ALL expressions and expand
817 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000818 **
819 ** The first loop just checks to see if there are any "*" operators
820 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000821 */
drh7c917d12001-12-16 20:05:05 +0000822 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000823 Expr *pE = pEList->a[k].pExpr;
824 if( pE->op==TK_ALL ) break;
825 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
826 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000827 }
drh54473222002-04-04 02:10:55 +0000828 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000829 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000830 /*
831 ** If we get here it means the result set contains one or more "*"
832 ** operators that need to be expanded. Loop through each expression
833 ** in the result set and expand them one by one.
834 */
drh7c917d12001-12-16 20:05:05 +0000835 struct ExprList_item *a = pEList->a;
836 ExprList *pNew = 0;
837 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000838 Expr *pE = a[k].pExpr;
839 if( pE->op!=TK_ALL &&
840 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
841 /* This particular expression does not need to be expanded.
842 */
drh7c917d12001-12-16 20:05:05 +0000843 pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
844 pNew->a[pNew->nExpr-1].zName = a[k].zName;
845 a[k].pExpr = 0;
846 a[k].zName = 0;
847 }else{
drh54473222002-04-04 02:10:55 +0000848 /* This expression is a "*" or a "TABLE.*" and needs to be
849 ** expanded. */
850 int tableSeen = 0; /* Set to 1 when TABLE matches */
851 Token *pName; /* text of name of TABLE */
852 if( pE->op==TK_DOT && pE->pLeft ){
853 pName = &pE->pLeft->token;
854 }else{
855 pName = 0;
856 }
drhad3cab52002-05-24 02:04:32 +0000857 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000858 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000859 char *zTabName = pTabList->a[i].zAlias;
860 if( zTabName==0 || zTabName[0]==0 ){
861 zTabName = pTab->zName;
862 }
drhc754fa52002-05-27 03:25:51 +0000863 if( pName && (zTabName==0 || zTabName[0]==0 ||
864 sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
865 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +0000866 continue;
867 }
868 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +0000869 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000870 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +0000871 char *zName = pTab->aCol[j].zName;
872
873 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
874 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
875 /* In a NATURAL join, omit the join columns from the
876 ** table on the right */
877 continue;
878 }
879 if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
880 /* In a join with a USING clause, omit columns in the
881 ** using clause from the table on the right. */
882 continue;
883 }
drh22f70c32002-02-18 01:17:00 +0000884 pRight = sqliteExpr(TK_ID, 0, 0, 0);
885 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +0000886 pRight->token.z = zName;
887 pRight->token.n = strlen(zName);
drh54473222002-04-04 02:10:55 +0000888 if( zTabName ){
drh22f70c32002-02-18 01:17:00 +0000889 pLeft = sqliteExpr(TK_ID, 0, 0, 0);
890 if( pLeft==0 ) break;
drh54473222002-04-04 02:10:55 +0000891 pLeft->token.z = zTabName;
892 pLeft->token.n = strlen(zTabName);
drh22f70c32002-02-18 01:17:00 +0000893 pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
894 if( pExpr==0 ) break;
drh7c917d12001-12-16 20:05:05 +0000895 }else{
drh22f70c32002-02-18 01:17:00 +0000896 pExpr = pRight;
897 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +0000898 }
drh7c917d12001-12-16 20:05:05 +0000899 pNew = sqliteExprListAppend(pNew, pExpr, 0);
900 }
drh17e24df2001-11-06 14:10:41 +0000901 }
drh54473222002-04-04 02:10:55 +0000902 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +0000903 if( pName ){
904 sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1,
905 pName->z, pName->n, 0);
906 }else{
907 sqliteSetString(&pParse->zErrMsg, "no tables specified", 0);
908 }
drh54473222002-04-04 02:10:55 +0000909 rc = 1;
910 }
drhd8bc7082000-06-07 23:51:50 +0000911 }
912 }
drh7c917d12001-12-16 20:05:05 +0000913 sqliteExprListDelete(pEList);
914 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +0000915 }
drh54473222002-04-04 02:10:55 +0000916 return rc;
drhd8bc7082000-06-07 23:51:50 +0000917}
918
919/*
drhff78bd22002-02-27 01:47:11 +0000920** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
921** in a select structure. It just sets the pointers to NULL. This
922** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
923** pointer is not NULL, this routine is called recursively on that pointer.
924**
925** This routine is called on the Select structure that defines a
926** VIEW in order to undo any bindings to tables. This is necessary
927** because those tables might be DROPed by a subsequent SQL command.
928*/
929void sqliteSelectUnbind(Select *p){
930 int i;
drhad3cab52002-05-24 02:04:32 +0000931 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +0000932 Table *pTab;
933 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +0000934 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +0000935 if( (pTab = pSrc->a[i].pTab)!=0 ){
936 if( pTab->isTransient ){
937 sqliteDeleteTable(0, pTab);
938 sqliteSelectDelete(pSrc->a[i].pSelect);
939 pSrc->a[i].pSelect = 0;
940 }
941 pSrc->a[i].pTab = 0;
942 if( pSrc->a[i].pSelect ){
943 sqliteSelectUnbind(pSrc->a[i].pSelect);
944 }
945 }
946 }
947}
948
949/*
drhd8bc7082000-06-07 23:51:50 +0000950** This routine associates entries in an ORDER BY expression list with
951** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +0000952** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +0000953** the top-level node is filled in with column number and the iTable
954** value of the top-level node is filled with iTable parameter.
955**
956** If there are prior SELECT clauses, they are processed first. A match
957** in an earlier SELECT takes precedence over a later SELECT.
958**
959** Any entry that does not match is flagged as an error. The number
960** of errors is returned.
961*/
962static int matchOrderbyToColumn(
963 Parse *pParse, /* A place to leave error messages */
964 Select *pSelect, /* Match to result columns of this SELECT */
965 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +0000966 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +0000967 int mustComplete /* If TRUE all ORDER BYs must match */
968){
969 int nErr = 0;
970 int i, j;
971 ExprList *pEList;
972
drhdaffd0e2001-04-11 14:28:42 +0000973 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +0000974 if( mustComplete ){
975 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
976 }
977 if( fillInColumnList(pParse, pSelect) ){
978 return 1;
979 }
980 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +0000981 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
982 return 1;
983 }
drhd8bc7082000-06-07 23:51:50 +0000984 }
985 pEList = pSelect->pEList;
986 for(i=0; i<pOrderBy->nExpr; i++){
987 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +0000988 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +0000989 if( pOrderBy->a[i].done ) continue;
drhe4de1fe2002-06-02 16:09:01 +0000990 if( sqliteExprIsInteger(pE, &iCol) ){
991 if( iCol<=0 || iCol>pEList->nExpr ){
992 char zBuf[200];
993 sprintf(zBuf,"ORDER BY position %d should be between 1 and %d",
994 iCol, pEList->nExpr);
995 sqliteSetString(&pParse->zErrMsg, zBuf, 0);
996 pParse->nErr++;
997 nErr++;
998 break;
999 }
1000 iCol--;
1001 }
1002 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001003 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001004 char *zName, *zLabel;
1005 zName = pEList->a[j].zName;
1006 assert( pE->token.z );
1007 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
drhd8bc7082000-06-07 23:51:50 +00001008 sqliteDequote(zLabel);
1009 if( sqliteStrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001010 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001011 }
drh6e142f52000-06-08 13:36:40 +00001012 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001013 }
drhe4de1fe2002-06-02 16:09:01 +00001014 if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
1015 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001016 }
1017 }
drhe4de1fe2002-06-02 16:09:01 +00001018 if( iCol>=0 ){
1019 pE->op = TK_COLUMN;
1020 pE->iColumn = iCol;
1021 pE->iTable = iTable;
1022 pOrderBy->a[i].done = 1;
1023 }
1024 if( iCol<0 && mustComplete ){
drhd8bc7082000-06-07 23:51:50 +00001025 char zBuf[30];
1026 sprintf(zBuf,"%d",i+1);
1027 sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf,
1028 " does not match any result column", 0);
1029 pParse->nErr++;
1030 nErr++;
1031 break;
1032 }
1033 }
1034 return nErr;
1035}
1036
1037/*
1038** Get a VDBE for the given parser context. Create a new one if necessary.
1039** If an error occurs, return NULL and leave a message in pParse.
1040*/
1041Vdbe *sqliteGetVdbe(Parse *pParse){
1042 Vdbe *v = pParse->pVdbe;
1043 if( v==0 ){
drh4c504392000-10-16 22:06:40 +00001044 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001045 }
drhd8bc7082000-06-07 23:51:50 +00001046 return v;
1047}
1048
1049
1050/*
drh82c3d632000-06-06 21:56:07 +00001051** This routine is called to process a query that is really the union
1052** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001053**
1054** "p" points to the right-most of the two queries. The results should
1055** be stored in eDest with parameter iParm.
drh82c3d632000-06-06 21:56:07 +00001056*/
1057static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
drh10e5e3c2000-06-08 00:19:02 +00001058 int rc; /* Success code from a subroutine */
1059 Select *pPrior; /* Another SELECT immediately to our left */
1060 Vdbe *v; /* Generate code to this VDBE */
1061 int base; /* Baseline value for pParse->nTab */
drh82c3d632000-06-06 21:56:07 +00001062
drhd8bc7082000-06-07 23:51:50 +00001063 /* Make sure there is no ORDER BY clause on prior SELECTs. Only the
1064 ** last SELECT in the series may have an ORDER BY.
drh82c3d632000-06-06 21:56:07 +00001065 */
drhdaffd0e2001-04-11 14:28:42 +00001066 if( p==0 || p->pPrior==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001067 pPrior = p->pPrior;
1068 if( pPrior->pOrderBy ){
1069 sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
1070 selectOpName(p->op), " not before", 0);
drh82c3d632000-06-06 21:56:07 +00001071 pParse->nErr++;
1072 return 1;
1073 }
1074
drhd8bc7082000-06-07 23:51:50 +00001075 /* Make sure we have a valid query engine. If not, create a new one.
1076 */
1077 v = sqliteGetVdbe(pParse);
1078 if( v==0 ) return 1;
1079
drh1cc3d752002-03-23 00:31:29 +00001080 /* Create the destination temporary table if necessary
1081 */
1082 if( eDest==SRT_TempTable ){
1083 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
1084 eDest = SRT_Table;
1085 }
1086
drhf46f9052002-06-22 02:33:38 +00001087 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001088 */
drh10e5e3c2000-06-08 00:19:02 +00001089 base = pParse->nTab;
drh82c3d632000-06-06 21:56:07 +00001090 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001091 case TK_ALL: {
1092 if( p->pOrderBy==0 ){
1093 rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
1094 if( rc ) return rc;
1095 p->pPrior = 0;
1096 rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
1097 p->pPrior = pPrior;
1098 if( rc ) return rc;
1099 break;
1100 }
1101 /* For UNION ALL ... ORDER BY fall through to the next case */
1102 }
drh82c3d632000-06-06 21:56:07 +00001103 case TK_EXCEPT:
1104 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001105 int unionTab; /* Cursor number of the temporary table holding result */
1106 int op; /* One of the SRT_ operations to apply to self */
1107 int priorOp; /* The SRT_ operation to apply to prior selects */
drhc926afb2002-06-20 03:38:26 +00001108 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
drh82c3d632000-06-06 21:56:07 +00001109
drhd8bc7082000-06-07 23:51:50 +00001110 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drhc926afb2002-06-20 03:38:26 +00001111 if( eDest==priorOp && p->pOrderBy==0 ){
drhd8bc7082000-06-07 23:51:50 +00001112 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001113 ** right.
drhd8bc7082000-06-07 23:51:50 +00001114 */
drh82c3d632000-06-06 21:56:07 +00001115 unionTab = iParm;
1116 }else{
drhd8bc7082000-06-07 23:51:50 +00001117 /* We will need to create our own temporary table to hold the
1118 ** intermediate results.
1119 */
1120 unionTab = pParse->nTab++;
1121 if( p->pOrderBy
1122 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1123 return 1;
1124 }
drhd8bc7082000-06-07 23:51:50 +00001125 if( p->op!=TK_ALL ){
drhc6b52df2002-01-04 03:09:29 +00001126 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
drh99fcd712001-10-13 01:06:47 +00001127 sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drh345fda32001-01-15 22:51:08 +00001128 }else{
drh99fcd712001-10-13 01:06:47 +00001129 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001130 }
drh82c3d632000-06-06 21:56:07 +00001131 }
drhd8bc7082000-06-07 23:51:50 +00001132
1133 /* Code the SELECT statements to our left
1134 */
drh832508b2002-03-02 17:04:07 +00001135 rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001136 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001137
1138 /* Code the current SELECT statement
1139 */
1140 switch( p->op ){
1141 case TK_EXCEPT: op = SRT_Except; break;
1142 case TK_UNION: op = SRT_Union; break;
1143 case TK_ALL: op = SRT_Table; break;
1144 }
drh82c3d632000-06-06 21:56:07 +00001145 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001146 pOrderBy = p->pOrderBy;
1147 p->pOrderBy = 0;
drh832508b2002-03-02 17:04:07 +00001148 rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001149 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001150 p->pOrderBy = pOrderBy;
drh82c3d632000-06-06 21:56:07 +00001151 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001152
1153 /* Convert the data in the temporary table into whatever form
1154 ** it is that we currently need.
1155 */
drhc926afb2002-06-20 03:38:26 +00001156 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001157 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001158 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001159 if( eDest==SRT_Callback ){
1160 generateColumnNames(pParse, p->base, 0, p->pEList);
1161 }
drh82c3d632000-06-06 21:56:07 +00001162 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001163 iCont = sqliteVdbeMakeLabel(v);
1164 sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
1165 iStart = sqliteVdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001166 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001167 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001168 iCont, iBreak);
1169 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001170 sqliteVdbeResolveLabel(v, iCont);
1171 sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
drh99fcd712001-10-13 01:06:47 +00001172 sqliteVdbeResolveLabel(v, iBreak);
1173 sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001174 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001175 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001176 }
drh82c3d632000-06-06 21:56:07 +00001177 }
1178 break;
1179 }
1180 case TK_INTERSECT: {
1181 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001182 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001183
drhd8bc7082000-06-07 23:51:50 +00001184 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001185 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001186 ** by allocating the tables we will need.
1187 */
drh82c3d632000-06-06 21:56:07 +00001188 tab1 = pParse->nTab++;
1189 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001190 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1191 return 1;
1192 }
drhc6b52df2002-01-04 03:09:29 +00001193 sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
drh99fcd712001-10-13 01:06:47 +00001194 sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
drhd8bc7082000-06-07 23:51:50 +00001195
1196 /* Code the SELECTs to our left into temporary table "tab1".
1197 */
drh832508b2002-03-02 17:04:07 +00001198 rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001199 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001200
1201 /* Code the current SELECT into temporary table "tab2"
1202 */
drhc6b52df2002-01-04 03:09:29 +00001203 sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
drh99fcd712001-10-13 01:06:47 +00001204 sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001205 p->pPrior = 0;
drh832508b2002-03-02 17:04:07 +00001206 rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001207 p->pPrior = pPrior;
1208 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001209
1210 /* Generate code to take the intersection of the two temporary
1211 ** tables.
1212 */
drh82c3d632000-06-06 21:56:07 +00001213 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001214 if( eDest==SRT_Callback ){
1215 generateColumnNames(pParse, p->base, 0, p->pEList);
1216 }
drh82c3d632000-06-06 21:56:07 +00001217 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001218 iCont = sqliteVdbeMakeLabel(v);
1219 sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
1220 iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
drh99fcd712001-10-13 01:06:47 +00001221 sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001222 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001223 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001224 iCont, iBreak);
1225 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001226 sqliteVdbeResolveLabel(v, iCont);
1227 sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
drh99fcd712001-10-13 01:06:47 +00001228 sqliteVdbeResolveLabel(v, iBreak);
1229 sqliteVdbeAddOp(v, OP_Close, tab2, 0);
1230 sqliteVdbeAddOp(v, OP_Close, tab1, 0);
drhd8bc7082000-06-07 23:51:50 +00001231 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001232 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001233 }
drh82c3d632000-06-06 21:56:07 +00001234 break;
1235 }
1236 }
1237 assert( p->pEList && pPrior->pEList );
1238 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
drhd8bc7082000-06-07 23:51:50 +00001239 sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ",
1240 selectOpName(p->op), " do not have the same number of result columns", 0);
drh82c3d632000-06-06 21:56:07 +00001241 pParse->nErr++;
1242 return 1;
drh22827922000-06-06 17:27:05 +00001243 }
drh10e5e3c2000-06-08 00:19:02 +00001244 pParse->nTab = base;
drh22827922000-06-06 17:27:05 +00001245 return 0;
1246}
1247
1248/*
drh832508b2002-03-02 17:04:07 +00001249** Recursively scan through an expression tree. For every reference
1250** to a column in table number iFrom, change that reference to the
1251** same column in table number iTo.
1252*/
1253static void changeTables(Expr *pExpr, int iFrom, int iTo){
1254 if( pExpr==0 ) return;
1255 if( pExpr->op==TK_COLUMN && pExpr->iTable==iFrom ){
1256 pExpr->iTable = iTo;
1257 }else{
drh1b2e0322002-03-03 02:49:51 +00001258 static void changeTablesInList(ExprList*, int, int);
drh832508b2002-03-02 17:04:07 +00001259 changeTables(pExpr->pLeft, iFrom, iTo);
1260 changeTables(pExpr->pRight, iFrom, iTo);
drh1b2e0322002-03-03 02:49:51 +00001261 changeTablesInList(pExpr->pList, iFrom, iTo);
1262 }
1263}
1264static void changeTablesInList(ExprList *pList, int iFrom, int iTo){
1265 if( pList ){
1266 int i;
1267 for(i=0; i<pList->nExpr; i++){
1268 changeTables(pList->a[i].pExpr, iFrom, iTo);
drh832508b2002-03-02 17:04:07 +00001269 }
1270 }
1271}
1272
1273/*
1274** Scan through the expression pExpr. Replace every reference to
1275** a column in table number iTable with a copy of the corresponding
drh84e59202002-03-14 14:33:31 +00001276** entry in pEList. (But leave references to the ROWID column
1277** unchanged.) When making a copy of an expression in pEList, change
1278** references to columns in table iSub into references to table iTable.
drh832508b2002-03-02 17:04:07 +00001279**
1280** This routine is part of the flattening procedure. A subquery
1281** whose result set is defined by pEList appears as entry in the
1282** FROM clause of a SELECT such that the VDBE cursor assigned to that
1283** FORM clause entry is iTable. This routine make the necessary
1284** changes to pExpr so that it refers directly to the source table
1285** of the subquery rather the result set of the subquery.
1286*/
1287static void substExpr(Expr *pExpr, int iTable, ExprList *pEList, int iSub){
1288 if( pExpr==0 ) return;
drh84e59202002-03-14 14:33:31 +00001289 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){
drh832508b2002-03-02 17:04:07 +00001290 Expr *pNew;
drh84e59202002-03-14 14:33:31 +00001291 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
drh832508b2002-03-02 17:04:07 +00001292 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1293 pNew = pEList->a[pExpr->iColumn].pExpr;
1294 assert( pNew!=0 );
1295 pExpr->op = pNew->op;
1296 pExpr->pLeft = sqliteExprDup(pNew->pLeft);
1297 pExpr->pRight = sqliteExprDup(pNew->pRight);
1298 pExpr->pList = sqliteExprListDup(pNew->pList);
1299 pExpr->iTable = pNew->iTable;
1300 pExpr->iColumn = pNew->iColumn;
1301 pExpr->iAgg = pNew->iAgg;
drh1b2e0322002-03-03 02:49:51 +00001302 pExpr->token = pNew->token;
drh832508b2002-03-02 17:04:07 +00001303 if( iSub!=iTable ){
1304 changeTables(pExpr, iSub, iTable);
1305 }
1306 }else{
1307 static void substExprList(ExprList*,int,ExprList*,int);
1308 substExpr(pExpr->pLeft, iTable, pEList, iSub);
1309 substExpr(pExpr->pRight, iTable, pEList, iSub);
1310 substExprList(pExpr->pList, iTable, pEList, iSub);
1311 }
1312}
1313static void
1314substExprList(ExprList *pList, int iTable, ExprList *pEList, int iSub){
1315 int i;
1316 if( pList==0 ) return;
1317 for(i=0; i<pList->nExpr; i++){
1318 substExpr(pList->a[i].pExpr, iTable, pEList, iSub);
1319 }
1320}
1321
1322/*
drh1350b032002-02-27 19:00:20 +00001323** This routine attempts to flatten subqueries in order to speed
1324** execution. It returns 1 if it makes changes and 0 if no flattening
1325** occurs.
1326**
1327** To understand the concept of flattening, consider the following
1328** query:
1329**
1330** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1331**
1332** The default way of implementing this query is to execute the
1333** subquery first and store the results in a temporary table, then
1334** run the outer query on that temporary table. This requires two
1335** passes over the data. Furthermore, because the temporary table
1336** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001337** optimized.
drh1350b032002-02-27 19:00:20 +00001338**
drh832508b2002-03-02 17:04:07 +00001339** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001340** a single flat select, like this:
1341**
1342** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1343**
1344** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001345** but only has to scan the data once. And because indices might
1346** exist on the table t1, a complete scan of the data might be
1347** avoided.
drh1350b032002-02-27 19:00:20 +00001348**
drh832508b2002-03-02 17:04:07 +00001349** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001350**
drh832508b2002-03-02 17:04:07 +00001351** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001352**
drh832508b2002-03-02 17:04:07 +00001353** (2) The subquery is not an aggregate or the outer query is not a join.
1354**
1355** (3) The subquery is not a join.
1356**
1357** (4) The subquery is not DISTINCT or the outer query is not a join.
1358**
1359** (5) The subquery is not DISTINCT or the outer query does not use
1360** aggregates.
1361**
1362** (6) The subquery does not use aggregates or the outer query is not
1363** DISTINCT.
1364**
drh08192d52002-04-30 19:20:28 +00001365** (7) The subquery has a FROM clause.
1366**
drhdf199a22002-06-14 22:38:41 +00001367** (8) The subquery does not use LIMIT or the outer query is not a join.
1368**
1369** (9) The subquery does not use LIMIT or the outer query does not use
1370** aggregates.
1371**
1372** (10) The subquery does not use aggregates or the outer query does not
1373** use LIMIT.
1374**
drh832508b2002-03-02 17:04:07 +00001375** In this routine, the "p" parameter is a pointer to the outer query.
1376** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1377** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1378**
1379** If flattening is not attempted, this routine is a no-op and return 0.
1380** If flattening is attempted this routine returns 1.
1381**
1382** All of the expression analysis must occur on both the outer query and
1383** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001384*/
drh832508b2002-03-02 17:04:07 +00001385int flattenSubquery(Select *p, int iFrom, int isAgg, int subqueryIsAgg){
drh0bb28102002-05-08 11:54:14 +00001386 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001387 SrcList *pSrc; /* The FROM clause of the outer query */
1388 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001389 ExprList *pList; /* The result set of the outer query */
drh832508b2002-03-02 17:04:07 +00001390 int i;
1391 int iParent, iSub;
1392 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001393
drh832508b2002-03-02 17:04:07 +00001394 /* Check to see if flattening is permitted. Return 0 if not.
1395 */
1396 if( p==0 ) return 0;
1397 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001398 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001399 pSub = pSrc->a[iFrom].pSelect;
1400 assert( pSub!=0 );
1401 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001402 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001403 pSubSrc = pSub->pSrc;
1404 assert( pSubSrc );
drhad3cab52002-05-24 02:04:32 +00001405 if( pSubSrc->nSrc!=1 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001406 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1407 return 0;
1408 }
drhd11d3822002-06-21 23:01:49 +00001409 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh832508b2002-03-02 17:04:07 +00001410
drh0bb28102002-05-08 11:54:14 +00001411 /* If we reach this point, it means flattening is permitted for the
drh832508b2002-03-02 17:04:07 +00001412 ** i-th entry of the FROM clause in the outer query.
1413 */
1414 iParent = p->base + iFrom;
1415 iSub = pSub->base;
1416 substExprList(p->pEList, iParent, pSub->pEList, iSub);
1417 pList = p->pEList;
1418 for(i=0; i<pList->nExpr; i++){
1419 if( pList->a[i].zName==0 ){
1420 Expr *pExpr = pList->a[i].pExpr;
1421 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
1422 }
1423 }
drh1b2e0322002-03-03 02:49:51 +00001424 if( isAgg ){
1425 substExprList(p->pGroupBy, iParent, pSub->pEList, iSub);
1426 substExpr(p->pHaving, iParent, pSub->pEList, iSub);
1427 }
drh832508b2002-03-02 17:04:07 +00001428 substExprList(p->pOrderBy, iParent, pSub->pEList, iSub);
1429 if( pSub->pWhere ){
1430 pWhere = sqliteExprDup(pSub->pWhere);
1431 if( iParent!=iSub ){
1432 changeTables(pWhere, iSub, iParent);
1433 }
1434 }else{
1435 pWhere = 0;
1436 }
1437 if( subqueryIsAgg ){
1438 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001439 p->pHaving = p->pWhere;
1440 p->pWhere = pWhere;
drh832508b2002-03-02 17:04:07 +00001441 substExpr(p->pHaving, iParent, pSub->pEList, iSub);
drh1b2e0322002-03-03 02:49:51 +00001442 if( pSub->pHaving ){
1443 Expr *pHaving = sqliteExprDup(pSub->pHaving);
1444 if( iParent!=iSub ){
1445 changeTables(pHaving, iSub, iParent);
1446 }
1447 if( p->pHaving ){
1448 p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
1449 }else{
1450 p->pHaving = pHaving;
1451 }
1452 }
1453 assert( p->pGroupBy==0 );
1454 p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
1455 if( iParent!=iSub ){
1456 changeTablesInList(p->pGroupBy, iSub, iParent);
1457 }
drh832508b2002-03-02 17:04:07 +00001458 }else if( p->pWhere==0 ){
1459 p->pWhere = pWhere;
1460 }else{
1461 substExpr(p->pWhere, iParent, pSub->pEList, iSub);
1462 if( pWhere ){
1463 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1464 }
1465 }
1466 p->isDistinct = p->isDistinct || pSub->isDistinct;
drhdf199a22002-06-14 22:38:41 +00001467 if( pSub->nLimit>=0 ){
1468 if( p->nLimit<0 ){
1469 p->nLimit = pSub->nLimit;
1470 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1471 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1472 }
1473 }
1474 p->nOffset += pSub->nOffset;
drh832508b2002-03-02 17:04:07 +00001475 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1476 sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1477 }
1478 pSrc->a[iFrom].pTab = pSubSrc->a[0].pTab;
1479 pSubSrc->a[0].pTab = 0;
1480 pSrc->a[iFrom].pSelect = pSubSrc->a[0].pSelect;
1481 pSubSrc->a[0].pSelect = 0;
1482 sqliteSelectDelete(pSub);
1483 return 1;
1484}
drh1350b032002-02-27 19:00:20 +00001485
1486/*
drh9562b552002-02-19 15:00:07 +00001487** Analyze the SELECT statement passed in as an argument to see if it
1488** is a simple min() or max() query. If it is and this query can be
1489** satisfied using a single seek to the beginning or end of an index,
1490** then generate the code for this SELECT return 1. If this is not a
1491** simple min() or max() query, then return 0;
1492**
1493** A simply min() or max() query looks like this:
1494**
1495** SELECT min(a) FROM table;
1496** SELECT max(a) FROM table;
1497**
1498** The query may have only a single table in its FROM argument. There
1499** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1500** be the min() or max() of a single column of the table. The column
1501** in the min() or max() function must be indexed.
1502**
1503** The parameters to this routine are the same as for sqliteSelect().
1504** See the header comment on that routine for additional information.
1505*/
1506static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1507 Expr *pExpr;
1508 int iCol;
1509 Table *pTab;
1510 Index *pIdx;
1511 int base;
1512 Vdbe *v;
1513 int openOp;
1514 int seekOp;
1515 int cont;
1516 ExprList eList;
1517 struct ExprList_item eListItem;
1518
1519 /* Check to see if this query is a simple min() or max() query. Return
1520 ** zero if it is not.
1521 */
1522 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drhad3cab52002-05-24 02:04:32 +00001523 if( p->pSrc->nSrc!=1 ) return 0;
drh9562b552002-02-19 15:00:07 +00001524 if( p->pEList->nExpr!=1 ) return 0;
1525 pExpr = p->pEList->a[0].pExpr;
1526 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
1527 if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
drh0bce8352002-02-28 00:41:10 +00001528 if( pExpr->token.n!=3 ) return 0;
1529 if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
1530 seekOp = OP_Rewind;
1531 }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
1532 seekOp = OP_Last;
1533 }else{
1534 return 0;
1535 }
drh9562b552002-02-19 15:00:07 +00001536 pExpr = pExpr->pList->a[0].pExpr;
1537 if( pExpr->op!=TK_COLUMN ) return 0;
1538 iCol = pExpr->iColumn;
1539 pTab = p->pSrc->a[0].pTab;
1540
1541 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00001542 ** Check to make sure we have an index and make pIdx point to the
1543 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
1544 ** key column, no index is necessary so set pIdx to NULL. If no
1545 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00001546 */
1547 if( iCol<0 ){
1548 pIdx = 0;
1549 }else{
1550 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1551 assert( pIdx->nColumn>=1 );
1552 if( pIdx->aiColumn[0]==iCol ) break;
1553 }
1554 if( pIdx==0 ) return 0;
1555 }
1556
drh17f71932002-02-21 12:01:27 +00001557 /* Identify column names if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00001558 ** step is skipped if the output is going to a table or a memory cell.
1559 */
1560 v = sqliteGetVdbe(pParse);
1561 if( v==0 ) return 0;
1562 if( eDest==SRT_Callback ){
drh832508b2002-03-02 17:04:07 +00001563 generateColumnNames(pParse, p->base, p->pSrc, p->pEList);
drh9562b552002-02-19 15:00:07 +00001564 }
1565
drh17f71932002-02-21 12:01:27 +00001566 /* Generating code to find the min or the max. Basically all we have
1567 ** to do is find the first or the last entry in the chosen index. If
1568 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
1569 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00001570 */
drh5cf8e8c2002-02-19 22:42:05 +00001571 if( !pParse->schemaVerified && (pParse->db->flags & SQLITE_InTrans)==0 ){
1572 sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
1573 pParse->schemaVerified = 1;
1574 }
drh9562b552002-02-19 15:00:07 +00001575 openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
drh832508b2002-03-02 17:04:07 +00001576 base = p->base;
drh9562b552002-02-19 15:00:07 +00001577 sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001578 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
drh9562b552002-02-19 15:00:07 +00001579 if( pIdx==0 ){
1580 sqliteVdbeAddOp(v, seekOp, base, 0);
1581 }else{
1582 sqliteVdbeAddOp(v, openOp, base+1, pIdx->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001583 sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
drh9562b552002-02-19 15:00:07 +00001584 sqliteVdbeAddOp(v, seekOp, base+1, 0);
1585 sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
1586 sqliteVdbeAddOp(v, OP_Close, base+1, 0);
1587 sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
1588 }
drh5cf8e8c2002-02-19 22:42:05 +00001589 eList.nExpr = 1;
1590 memset(&eListItem, 0, sizeof(eListItem));
1591 eList.a = &eListItem;
1592 eList.a[0].pExpr = pExpr;
drh9562b552002-02-19 15:00:07 +00001593 cont = sqliteVdbeMakeLabel(v);
drh38640e12002-07-05 21:42:36 +00001594 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
drh9562b552002-02-19 15:00:07 +00001595 sqliteVdbeResolveLabel(v, cont);
1596 sqliteVdbeAddOp(v, OP_Close, base, 0);
1597 return 1;
1598}
1599
1600/*
drh9bb61fe2000-06-05 16:01:39 +00001601** Generate code for the given SELECT statement.
1602**
drhfef52082000-06-06 01:50:43 +00001603** The results are distributed in various ways depending on the
1604** value of eDest and iParm.
1605**
1606** eDest Value Result
1607** ------------ -------------------------------------------
1608** SRT_Callback Invoke the callback for each row of the result.
1609**
1610** SRT_Mem Store first result in memory cell iParm
1611**
1612** SRT_Set Store results as keys of a table with cursor iParm
1613**
drh82c3d632000-06-06 21:56:07 +00001614** SRT_Union Store results as a key in a temporary table iParm
1615**
drhc4a3c772001-04-04 11:48:57 +00001616** SRT_Except Remove results form the temporary table iParm.
1617**
1618** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00001619**
1620** This routine returns the number of errors. If any errors are
1621** encountered, then an appropriate error message is left in
1622** pParse->zErrMsg.
1623**
1624** This routine does NOT free the Select structure passed in. The
1625** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00001626**
1627** The pParent, parentTab, and *pParentAgg fields are filled in if this
1628** SELECT is a subquery. This routine may try to combine this SELECT
1629** with its parent to form a single flat query. In so doing, it might
1630** change the parent query from a non-aggregate to an aggregate query.
1631** For that reason, the pParentAgg flag is passed as a pointer, so it
1632** can be changed.
drh9bb61fe2000-06-05 16:01:39 +00001633*/
1634int sqliteSelect(
drhcce7d172000-05-31 15:34:51 +00001635 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00001636 Select *p, /* The SELECT statement being coded. */
drh82c3d632000-06-06 21:56:07 +00001637 int eDest, /* One of: SRT_Callback Mem Set Union Except */
drh832508b2002-03-02 17:04:07 +00001638 int iParm, /* Save result in this memory location, if >=0 */
1639 Select *pParent, /* Another SELECT for which this is a sub-query */
1640 int parentTab, /* Index in pParent->pSrc of this query */
drh1b2e0322002-03-03 02:49:51 +00001641 int *pParentAgg /* True if pParent uses aggregate functions */
drhcce7d172000-05-31 15:34:51 +00001642){
drhd8bc7082000-06-07 23:51:50 +00001643 int i;
drhcce7d172000-05-31 15:34:51 +00001644 WhereInfo *pWInfo;
1645 Vdbe *v;
1646 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00001647 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00001648 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00001649 Expr *pWhere; /* The WHERE clause. May be NULL */
1650 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00001651 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
1652 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00001653 int isDistinct; /* True if the DISTINCT keyword is present */
1654 int distinct; /* Table to use for the distinct set */
drh10e5e3c2000-06-08 00:19:02 +00001655 int base; /* First cursor available for use */
drh1d83f052002-02-17 00:30:36 +00001656 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00001657
drhdaffd0e2001-04-11 14:28:42 +00001658 if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
1659
drh82c3d632000-06-06 21:56:07 +00001660 /* If there is are a sequence of queries, do the earlier ones first.
1661 */
1662 if( p->pPrior ){
1663 return multiSelect(pParse, p, eDest, iParm);
1664 }
1665
1666 /* Make local copies of the parameters for this query.
1667 */
drh9bb61fe2000-06-05 16:01:39 +00001668 pTabList = p->pSrc;
1669 pWhere = p->pWhere;
1670 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00001671 pGroupBy = p->pGroupBy;
1672 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00001673 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00001674
drh832508b2002-03-02 17:04:07 +00001675 /* Allocate a block of VDBE cursors, one for each table in the FROM clause.
1676 ** The WHERE processing requires that the cursors for the tables in the
1677 ** FROM clause be consecutive.
drh10e5e3c2000-06-08 00:19:02 +00001678 */
drh832508b2002-03-02 17:04:07 +00001679 base = p->base = pParse->nTab;
drhad3cab52002-05-24 02:04:32 +00001680 pParse->nTab += pTabList->nSrc;
drh10e5e3c2000-06-08 00:19:02 +00001681
drh9bb61fe2000-06-05 16:01:39 +00001682 /*
1683 ** Do not even attempt to generate any code if we have already seen
1684 ** errors before this routine starts.
1685 */
drh1d83f052002-02-17 00:30:36 +00001686 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001687
drhd8bc7082000-06-07 23:51:50 +00001688 /* Look up every table in the table list and create an appropriate
1689 ** columnlist in pEList if there isn't one already. (The parser leaves
drh967e8b72000-06-21 13:59:10 +00001690 ** a NULL in the p->pEList if the SQL said "SELECT * FROM ...")
drhcce7d172000-05-31 15:34:51 +00001691 */
drhd8bc7082000-06-07 23:51:50 +00001692 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00001693 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001694 }
drhad2d8302002-05-24 20:31:36 +00001695 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00001696 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00001697 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001698
drh22827922000-06-06 17:27:05 +00001699 /* If writing to memory or generating a set
1700 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00001701 */
drhfef52082000-06-06 01:50:43 +00001702 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
drh19a775c2000-06-05 18:54:46 +00001703 sqliteSetString(&pParse->zErrMsg, "only a single result allowed for "
1704 "a SELECT that is part of an expression", 0);
1705 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +00001706 goto select_end;
drh19a775c2000-06-05 18:54:46 +00001707 }
1708
drhc926afb2002-06-20 03:38:26 +00001709 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00001710 */
drhc926afb2002-06-20 03:38:26 +00001711 switch( eDest ){
1712 case SRT_Union:
1713 case SRT_Except:
1714 case SRT_Discard:
1715 pOrderBy = 0;
1716 break;
1717 default:
1718 break;
drh22827922000-06-06 17:27:05 +00001719 }
1720
drh10e5e3c2000-06-08 00:19:02 +00001721 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00001722 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00001723 **
drh967e8b72000-06-21 13:59:10 +00001724 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00001725 */
drh4794b982000-06-06 13:54:14 +00001726 for(i=0; i<pEList->nExpr; i++){
drh832508b2002-03-02 17:04:07 +00001727 if( sqliteExprResolveIds(pParse, base, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001728 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001729 }
drh22827922000-06-06 17:27:05 +00001730 if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00001731 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001732 }
1733 }
drhcce7d172000-05-31 15:34:51 +00001734 if( pWhere ){
drh832508b2002-03-02 17:04:07 +00001735 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00001736 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001737 }
1738 if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00001739 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001740 }
1741 }
1742 if( pOrderBy ){
1743 for(i=0; i<pOrderBy->nExpr; i++){
drh22827922000-06-06 17:27:05 +00001744 Expr *pE = pOrderBy->a[i].pExpr;
drh92086432002-01-22 14:11:29 +00001745 if( sqliteExprIsConstant(pE) ){
drhe4de1fe2002-06-02 16:09:01 +00001746 int iCol;
1747 if( sqliteExprIsInteger(pE, &iCol)==0 ){
1748 sqliteSetString(&pParse->zErrMsg,
1749 "ORDER BY terms must not be non-integer constants", 0);
1750 pParse->nErr++;
1751 goto select_end;
1752 }else if( iCol<=0 || iCol>pEList->nExpr ){
1753 char zBuf[2000];
1754 sprintf(zBuf,"ORDER BY column number %d out of range - should be "
1755 "between 1 and %d", iCol, pEList->nExpr);
1756 sqliteSetString(&pParse->zErrMsg, zBuf, 0);
1757 pParse->nErr++;
1758 goto select_end;
1759 }
1760 sqliteExprDelete(pE);
1761 pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00001762 }
drh832508b2002-03-02 17:04:07 +00001763 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00001764 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001765 }
drh22827922000-06-06 17:27:05 +00001766 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00001767 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001768 }
1769 }
1770 }
drh22827922000-06-06 17:27:05 +00001771 if( pGroupBy ){
1772 for(i=0; i<pGroupBy->nExpr; i++){
1773 Expr *pE = pGroupBy->a[i].pExpr;
drh92086432002-01-22 14:11:29 +00001774 if( sqliteExprIsConstant(pE) ){
1775 sqliteSetString(&pParse->zErrMsg,
1776 "GROUP BY expressions should not be constant", 0);
1777 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +00001778 goto select_end;
drh92086432002-01-22 14:11:29 +00001779 }
drh832508b2002-03-02 17:04:07 +00001780 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00001781 goto select_end;
drh22827922000-06-06 17:27:05 +00001782 }
1783 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00001784 goto select_end;
drh22827922000-06-06 17:27:05 +00001785 }
1786 }
1787 }
1788 if( pHaving ){
1789 if( pGroupBy==0 ){
drhda932812000-06-06 18:00:15 +00001790 sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required "
1791 "before HAVING", 0);
drh22827922000-06-06 17:27:05 +00001792 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +00001793 goto select_end;
drh22827922000-06-06 17:27:05 +00001794 }
drh832508b2002-03-02 17:04:07 +00001795 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00001796 goto select_end;
drh22827922000-06-06 17:27:05 +00001797 }
drhda932812000-06-06 18:00:15 +00001798 if( sqliteExprCheck(pParse, pHaving, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00001799 goto select_end;
drh22827922000-06-06 17:27:05 +00001800 }
drhcce7d172000-05-31 15:34:51 +00001801 }
1802
drh9562b552002-02-19 15:00:07 +00001803 /* Check for the special case of a min() or max() function by itself
1804 ** in the result set.
1805 */
1806 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
drh5cf8e8c2002-02-19 22:42:05 +00001807 rc = 0;
drh9562b552002-02-19 15:00:07 +00001808 goto select_end;
1809 }
1810
drhd820cb12002-02-18 03:21:45 +00001811 /* Begin generating code.
1812 */
1813 v = sqliteGetVdbe(pParse);
1814 if( v==0 ) goto select_end;
1815
drh0bb28102002-05-08 11:54:14 +00001816 /* Identify column names if we will be using in the callback. This
1817 ** step is skipped if the output is going to a table or a memory cell.
1818 */
1819 if( eDest==SRT_Callback ){
1820 generateColumnNames(pParse, p->base, pTabList, pEList);
1821 }
1822
1823 /* Set the limiter
1824 */
1825 if( p->nLimit<=0 ){
drhd11d3822002-06-21 23:01:49 +00001826 p->nLimit = -1;
drh0bb28102002-05-08 11:54:14 +00001827 p->nOffset = 0;
1828 }else{
drhd11d3822002-06-21 23:01:49 +00001829 int iMem = pParse->nMem++;
1830 sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
drhbf5cd972002-06-24 12:20:23 +00001831 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
drhd11d3822002-06-21 23:01:49 +00001832 p->nLimit = iMem;
1833 if( p->nOffset<=0 ){
1834 p->nOffset = 0;
1835 }else{
1836 iMem = pParse->nMem++;
1837 sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
drhbf5cd972002-06-24 12:20:23 +00001838 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
drhd11d3822002-06-21 23:01:49 +00001839 p->nOffset = iMem;
1840 }
drh0bb28102002-05-08 11:54:14 +00001841 }
1842
drhd820cb12002-02-18 03:21:45 +00001843 /* Generate code for all sub-queries in the FROM clause
1844 */
drhad3cab52002-05-24 02:04:32 +00001845 for(i=0; i<pTabList->nSrc; i++){
drha76b5df2002-02-23 02:32:10 +00001846 if( pTabList->a[i].pSelect==0 ) continue;
drh2d0794e2002-03-03 03:03:52 +00001847 sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable, base+i,
drh1b2e0322002-03-03 02:49:51 +00001848 p, i, &isAgg);
1849 pTabList = p->pSrc;
1850 pWhere = p->pWhere;
drhacd4c692002-03-07 02:02:51 +00001851 if( eDest==SRT_Callback ){
1852 pOrderBy = p->pOrderBy;
1853 }
drh1b2e0322002-03-03 02:49:51 +00001854 pGroupBy = p->pGroupBy;
1855 pHaving = p->pHaving;
1856 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00001857 }
1858
drh832508b2002-03-02 17:04:07 +00001859 /* Check to see if this is a subquery that can be "flattened" into its parent.
1860 ** If flattening is a possiblity, do so and return immediately.
1861 */
drh1b2e0322002-03-03 02:49:51 +00001862 if( pParent && pParentAgg &&
1863 flattenSubquery(pParent, parentTab, *pParentAgg, isAgg) ){
1864 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00001865 return rc;
1866 }
drh832508b2002-03-02 17:04:07 +00001867
drh2d0794e2002-03-03 03:03:52 +00001868 /* If the output is destined for a temporary table, open that table.
1869 */
1870 if( eDest==SRT_TempTable ){
1871 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
1872 }
1873
drh22827922000-06-06 17:27:05 +00001874 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00001875 */
drhd820cb12002-02-18 03:21:45 +00001876 sqliteAggregateInfoReset(pParse);
drh22827922000-06-06 17:27:05 +00001877 if( isAgg ){
drh0bce8352002-02-28 00:41:10 +00001878 assert( pParse->nAgg==0 );
drh22827922000-06-06 17:27:05 +00001879 for(i=0; i<pEList->nExpr; i++){
1880 if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001881 goto select_end;
drh22827922000-06-06 17:27:05 +00001882 }
1883 }
1884 if( pGroupBy ){
1885 for(i=0; i<pGroupBy->nExpr; i++){
1886 if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001887 goto select_end;
drh22827922000-06-06 17:27:05 +00001888 }
1889 }
1890 }
1891 if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00001892 goto select_end;
drh22827922000-06-06 17:27:05 +00001893 }
drh191b6902000-06-08 11:13:01 +00001894 if( pOrderBy ){
1895 for(i=0; i<pOrderBy->nExpr; i++){
1896 if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001897 goto select_end;
drh191b6902000-06-08 11:13:01 +00001898 }
1899 }
1900 }
drhefb72512000-05-31 20:00:52 +00001901 }
1902
drh22827922000-06-06 17:27:05 +00001903 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00001904 */
1905 if( isAgg ){
drh99fcd712001-10-13 01:06:47 +00001906 sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00001907 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00001908 FuncDef *pFunc;
1909 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drh1350b032002-02-27 19:00:20 +00001910 sqliteVdbeAddOp(v, OP_AggInit, 0, i);
drh0bce8352002-02-28 00:41:10 +00001911 sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
drhe5095352002-02-24 03:25:14 +00001912 }
1913 }
drh1bee3d72001-10-15 00:44:35 +00001914 if( pGroupBy==0 ){
1915 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00001916 sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00001917 }
drhcce7d172000-05-31 15:34:51 +00001918 }
1919
drh19a775c2000-06-05 18:54:46 +00001920 /* Initialize the memory cell to NULL
1921 */
drhfef52082000-06-06 01:50:43 +00001922 if( eDest==SRT_Mem ){
drh99fcd712001-10-13 01:06:47 +00001923 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh8721ce42001-11-07 14:22:00 +00001924 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00001925 }
1926
drh832508b2002-03-02 17:04:07 +00001927 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00001928 */
drh19a775c2000-06-05 18:54:46 +00001929 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00001930 distinct = pParse->nTab++;
drhc6b52df2002-01-04 03:09:29 +00001931 sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
drh832508b2002-03-02 17:04:07 +00001932 }else{
1933 distinct = -1;
drhefb72512000-05-31 20:00:52 +00001934 }
drh832508b2002-03-02 17:04:07 +00001935
1936 /* Begin the database scan
1937 */
drhe3184742002-06-19 14:27:05 +00001938 pWInfo = sqliteWhereBegin(pParse, p->base, pTabList, pWhere, 0, &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00001939 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001940
drh22827922000-06-06 17:27:05 +00001941 /* Use the standard inner loop if we are not dealing with
1942 ** aggregates
drhcce7d172000-05-31 15:34:51 +00001943 */
drhda9d6c42000-05-31 18:20:14 +00001944 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00001945 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
1946 iParm, pWInfo->iContinue, pWInfo->iBreak) ){
drh1d83f052002-02-17 00:30:36 +00001947 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00001948 }
drhcce7d172000-05-31 15:34:51 +00001949 }
drhefb72512000-05-31 20:00:52 +00001950
drhe3184742002-06-19 14:27:05 +00001951 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00001952 ** processing.
drhefb72512000-05-31 20:00:52 +00001953 */
drh22827922000-06-06 17:27:05 +00001954 else{
drh22827922000-06-06 17:27:05 +00001955 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00001956 int lbl1;
drh22827922000-06-06 17:27:05 +00001957 for(i=0; i<pGroupBy->nExpr; i++){
1958 sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
1959 }
drh99fcd712001-10-13 01:06:47 +00001960 sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
drh38640e12002-07-05 21:42:36 +00001961 if( pParse->db->file_format>=3 ) sqliteAddKeyType(v, pGroupBy);
drh1bee3d72001-10-15 00:44:35 +00001962 lbl1 = sqliteVdbeMakeLabel(v);
drh99fcd712001-10-13 01:06:47 +00001963 sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh22827922000-06-06 17:27:05 +00001964 for(i=0; i<pParse->nAgg; i++){
1965 if( pParse->aAgg[i].isAgg ) continue;
1966 sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
drh99fcd712001-10-13 01:06:47 +00001967 sqliteVdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00001968 }
drh22827922000-06-06 17:27:05 +00001969 sqliteVdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00001970 }
drh22827922000-06-06 17:27:05 +00001971 for(i=0; i<pParse->nAgg; i++){
1972 Expr *pE;
drh0bce8352002-02-28 00:41:10 +00001973 int j;
drh22827922000-06-06 17:27:05 +00001974 if( !pParse->aAgg[i].isAgg ) continue;
1975 pE = pParse->aAgg[i].pExpr;
drh22827922000-06-06 17:27:05 +00001976 assert( pE->op==TK_AGG_FUNCTION );
drh0bce8352002-02-28 00:41:10 +00001977 if( pE->pList ){
1978 for(j=0; j<pE->pList->nExpr; j++){
1979 sqliteExprCode(pParse, pE->pList->a[j].pExpr);
1980 }
drhe5095352002-02-24 03:25:14 +00001981 }
drh0bce8352002-02-28 00:41:10 +00001982 sqliteVdbeAddOp(v, OP_Integer, i, 0);
drhf55f25f2002-02-28 01:46:11 +00001983 sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
drh0bce8352002-02-28 00:41:10 +00001984 assert( pParse->aAgg[i].pFunc!=0 );
1985 assert( pParse->aAgg[i].pFunc->xStep!=0 );
1986 sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
drh22827922000-06-06 17:27:05 +00001987 }
drhcce7d172000-05-31 15:34:51 +00001988 }
1989
1990 /* End the database scan loop.
1991 */
1992 sqliteWhereEnd(pWInfo);
1993
drh22827922000-06-06 17:27:05 +00001994 /* If we are processing aggregates, we need to set up a second loop
1995 ** over all of the aggregate values and process them.
1996 */
1997 if( isAgg ){
1998 int endagg = sqliteVdbeMakeLabel(v);
1999 int startagg;
drh99fcd712001-10-13 01:06:47 +00002000 startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002001 pParse->useAgg = 1;
2002 if( pHaving ){
drhf5905aa2002-05-26 20:54:33 +00002003 sqliteExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002004 }
drhdf199a22002-06-14 22:38:41 +00002005 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2006 iParm, startagg, endagg) ){
drh1d83f052002-02-17 00:30:36 +00002007 goto select_end;
drh22827922000-06-06 17:27:05 +00002008 }
drh99fcd712001-10-13 01:06:47 +00002009 sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
2010 sqliteVdbeResolveLabel(v, endagg);
2011 sqliteVdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002012 pParse->useAgg = 0;
2013 }
2014
drhcce7d172000-05-31 15:34:51 +00002015 /* If there is an ORDER BY clause, then we need to sort the results
2016 ** and send them to the callback one by one.
2017 */
2018 if( pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00002019 generateSortTail(p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002020 }
drh6a535342001-10-19 16:44:56 +00002021
2022
2023 /* Issue a null callback if that is what the user wants.
2024 */
2025 if( (pParse->db->flags & SQLITE_NullCallback)!=0 && eDest==SRT_Callback ){
2026 sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
2027 }
2028
drh1d83f052002-02-17 00:30:36 +00002029 /* The SELECT was successfully coded. Set the return code to 0
2030 ** to indicate no errors.
2031 */
2032 rc = 0;
2033
2034 /* Control jumps to here if an error is encountered above, or upon
2035 ** successful coding of the SELECT.
2036 */
2037select_end:
drh832508b2002-03-02 17:04:07 +00002038 pParse->nTab = base;
drh1d83f052002-02-17 00:30:36 +00002039 sqliteAggregateInfoReset(pParse);
2040 return rc;
drhcce7d172000-05-31 15:34:51 +00002041}