blob: 01949aac8d254567be2dd979e9d634a1b2854c59 [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**
drh268380c2004-02-25 13:47:31 +000015** $Id: select.c,v 1.159 2004/02/25 13:47:33 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
drh315555c2002-10-20 15:53:03 +000019
drhcce7d172000-05-31 15:34:51 +000020/*
drh9bb61fe2000-06-05 16:01:39 +000021** Allocate a new Select structure and return a pointer to that
22** structure.
drhcce7d172000-05-31 15:34:51 +000023*/
drh9bb61fe2000-06-05 16:01:39 +000024Select *sqliteSelectNew(
drhdaffd0e2001-04-11 14:28:42 +000025 ExprList *pEList, /* which columns to include in the result */
drhad3cab52002-05-24 02:04:32 +000026 SrcList *pSrc, /* the FROM clause -- which tables to scan */
drhdaffd0e2001-04-11 14:28:42 +000027 Expr *pWhere, /* the WHERE clause */
28 ExprList *pGroupBy, /* the GROUP BY clause */
29 Expr *pHaving, /* the HAVING clause */
30 ExprList *pOrderBy, /* the ORDER BY clause */
drh9bbca4c2001-11-06 04:00:18 +000031 int isDistinct, /* true if the DISTINCT keyword is present */
32 int nLimit, /* LIMIT value. -1 means not used */
drhef0cae52003-07-16 02:19:37 +000033 int nOffset /* OFFSET value. 0 means no offset */
drh9bb61fe2000-06-05 16:01:39 +000034){
35 Select *pNew;
36 pNew = sqliteMalloc( sizeof(*pNew) );
drhdaffd0e2001-04-11 14:28:42 +000037 if( pNew==0 ){
38 sqliteExprListDelete(pEList);
drhad3cab52002-05-24 02:04:32 +000039 sqliteSrcListDelete(pSrc);
drhdaffd0e2001-04-11 14:28:42 +000040 sqliteExprDelete(pWhere);
41 sqliteExprListDelete(pGroupBy);
42 sqliteExprDelete(pHaving);
43 sqliteExprListDelete(pOrderBy);
44 }else{
drhb733d032004-01-24 20:18:12 +000045 if( pEList==0 ){
46 pEList = sqliteExprListAppend(0, sqliteExpr(TK_ALL,0,0,0), 0);
47 }
drhdaffd0e2001-04-11 14:28:42 +000048 pNew->pEList = pEList;
49 pNew->pSrc = pSrc;
50 pNew->pWhere = pWhere;
51 pNew->pGroupBy = pGroupBy;
52 pNew->pHaving = pHaving;
53 pNew->pOrderBy = pOrderBy;
54 pNew->isDistinct = isDistinct;
55 pNew->op = TK_SELECT;
drh9bbca4c2001-11-06 04:00:18 +000056 pNew->nLimit = nLimit;
57 pNew->nOffset = nOffset;
drh7b58dae2003-07-20 01:16:46 +000058 pNew->iLimit = -1;
59 pNew->iOffset = -1;
drhdaffd0e2001-04-11 14:28:42 +000060 }
drh9bb61fe2000-06-05 16:01:39 +000061 return pNew;
62}
63
64/*
drh01f3f252002-05-24 16:14:15 +000065** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
66** type of join. Return an integer constant that expresses that type
67** in terms of the following bit values:
68**
69** JT_INNER
70** JT_OUTER
71** JT_NATURAL
72** JT_LEFT
73** JT_RIGHT
74**
75** A full outer join is the combination of JT_LEFT and JT_RIGHT.
76**
77** If an illegal or unsupported join type is seen, then still return
78** a join type, but put an error in the pParse structure.
79*/
80int sqliteJoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
81 int jointype = 0;
82 Token *apAll[3];
83 Token *p;
84 static struct {
85 const char *zKeyword;
86 int nChar;
87 int code;
88 } keywords[] = {
89 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000090 { "left", 4, JT_LEFT|JT_OUTER },
91 { "right", 5, JT_RIGHT|JT_OUTER },
92 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +000093 { "outer", 5, JT_OUTER },
94 { "inner", 5, JT_INNER },
95 { "cross", 5, JT_INNER },
96 };
97 int i, j;
98 apAll[0] = pA;
99 apAll[1] = pB;
100 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +0000101 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +0000102 p = apAll[i];
103 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
104 if( p->n==keywords[j].nChar
105 && sqliteStrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
106 jointype |= keywords[j].code;
107 break;
108 }
109 }
110 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
111 jointype |= JT_ERROR;
112 break;
113 }
114 }
drhad2d8302002-05-24 20:31:36 +0000115 if(
116 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000117 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000118 ){
drh01f3f252002-05-24 16:14:15 +0000119 static Token dummy = { 0, 0 };
120 char *zSp1 = " ", *zSp2 = " ";
121 if( pB==0 ){ pB = &dummy; zSp1 = 0; }
122 if( pC==0 ){ pC = &dummy; zSp2 = 0; }
123 sqliteSetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
124 pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
125 pParse->nErr++;
126 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000127 }else if( jointype & JT_RIGHT ){
drhda93d232003-03-31 02:12:46 +0000128 sqliteErrorMsg(pParse,
129 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000130 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000131 }
132 return jointype;
133}
134
135/*
drhad2d8302002-05-24 20:31:36 +0000136** Return the index of a column in a table. Return -1 if the column
137** is not contained in the table.
138*/
139static int columnIndex(Table *pTab, const char *zCol){
140 int i;
141 for(i=0; i<pTab->nCol; i++){
142 if( sqliteStrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
143 }
144 return -1;
145}
146
147/*
148** Add a term to the WHERE expression in *ppExpr that requires the
149** zCol column to be equal in the two tables pTab1 and pTab2.
150*/
151static void addWhereTerm(
152 const char *zCol, /* Name of the column */
153 const Table *pTab1, /* First table */
154 const Table *pTab2, /* Second table */
155 Expr **ppExpr /* Add the equality term to this expression */
156){
157 Token dummy;
158 Expr *pE1a, *pE1b, *pE1c;
159 Expr *pE2a, *pE2b, *pE2c;
160 Expr *pE;
161
162 dummy.z = zCol;
163 dummy.n = strlen(zCol);
drh4b59ab52002-08-24 18:24:51 +0000164 dummy.dyn = 0;
drhad2d8302002-05-24 20:31:36 +0000165 pE1a = sqliteExpr(TK_ID, 0, 0, &dummy);
166 pE2a = sqliteExpr(TK_ID, 0, 0, &dummy);
167 dummy.z = pTab1->zName;
168 dummy.n = strlen(dummy.z);
169 pE1b = sqliteExpr(TK_ID, 0, 0, &dummy);
170 dummy.z = pTab2->zName;
171 dummy.n = strlen(dummy.z);
172 pE2b = sqliteExpr(TK_ID, 0, 0, &dummy);
173 pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0);
174 pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0);
175 pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000176 ExprSetProperty(pE, EP_FromJoin);
drhad2d8302002-05-24 20:31:36 +0000177 if( *ppExpr ){
178 *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0);
179 }else{
180 *ppExpr = pE;
181 }
182}
183
184/*
drh1f162302002-10-27 19:35:33 +0000185** Set the EP_FromJoin property on all terms of the given expression.
drh1cc093c2002-06-24 22:01:57 +0000186**
drhe78e8282003-01-19 03:59:45 +0000187** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000188** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000189** join restriction specified in the ON or USING clause and not a part
190** of the more general WHERE clause. These terms are moved over to the
191** WHERE clause during join processing but we need to remember that they
192** originated in the ON or USING clause.
drh1cc093c2002-06-24 22:01:57 +0000193*/
194static void setJoinExpr(Expr *p){
195 while( p ){
drh1f162302002-10-27 19:35:33 +0000196 ExprSetProperty(p, EP_FromJoin);
drh1cc093c2002-06-24 22:01:57 +0000197 setJoinExpr(p->pLeft);
198 p = p->pRight;
199 }
200}
201
202/*
drhad2d8302002-05-24 20:31:36 +0000203** This routine processes the join information for a SELECT statement.
204** ON and USING clauses are converted into extra terms of the WHERE clause.
205** NATURAL joins also create extra WHERE clause terms.
206**
207** This routine returns the number of errors encountered.
208*/
209static int sqliteProcessJoin(Parse *pParse, Select *p){
210 SrcList *pSrc;
211 int i, j;
212 pSrc = p->pSrc;
213 for(i=0; i<pSrc->nSrc-1; i++){
214 struct SrcList_item *pTerm = &pSrc->a[i];
215 struct SrcList_item *pOther = &pSrc->a[i+1];
216
217 if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
218
219 /* When the NATURAL keyword is present, add WHERE clause terms for
220 ** every column that the two tables have in common.
221 */
222 if( pTerm->jointype & JT_NATURAL ){
223 Table *pTab;
224 if( pTerm->pOn || pTerm->pUsing ){
drhda93d232003-03-31 02:12:46 +0000225 sqliteErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000226 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000227 return 1;
228 }
229 pTab = pTerm->pTab;
230 for(j=0; j<pTab->nCol; j++){
231 if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
232 addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
233 }
234 }
235 }
236
237 /* Disallow both ON and USING clauses in the same join
238 */
239 if( pTerm->pOn && pTerm->pUsing ){
drhda93d232003-03-31 02:12:46 +0000240 sqliteErrorMsg(pParse, "cannot have both ON and USING "
241 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000242 return 1;
243 }
244
245 /* Add the ON clause to the end of the WHERE clause, connected by
246 ** and AND operator.
247 */
248 if( pTerm->pOn ){
drh1cc093c2002-06-24 22:01:57 +0000249 setJoinExpr(pTerm->pOn);
drhad2d8302002-05-24 20:31:36 +0000250 if( p->pWhere==0 ){
251 p->pWhere = pTerm->pOn;
252 }else{
253 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0);
254 }
255 pTerm->pOn = 0;
256 }
257
258 /* Create extra terms on the WHERE clause for each column named
259 ** in the USING clause. Example: If the two tables to be joined are
260 ** A and B and the USING clause names X, Y, and Z, then add this
261 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
262 ** Report an error if any column mentioned in the USING clause is
263 ** not contained in both tables to be joined.
264 */
265 if( pTerm->pUsing ){
266 IdList *pList;
267 int j;
268 assert( i<pSrc->nSrc-1 );
269 pList = pTerm->pUsing;
270 for(j=0; j<pList->nId; j++){
drhbf5cd972002-06-24 12:20:23 +0000271 if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
272 columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
drhda93d232003-03-31 02:12:46 +0000273 sqliteErrorMsg(pParse, "cannot join using column %s - column "
274 "not present in both tables", pList->a[j].zName);
drhad2d8302002-05-24 20:31:36 +0000275 return 1;
276 }
drhbf5cd972002-06-24 12:20:23 +0000277 addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000278 }
279 }
280 }
281 return 0;
282}
283
284/*
drh9bb61fe2000-06-05 16:01:39 +0000285** Delete the given Select structure and all of its substructures.
286*/
287void sqliteSelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000288 if( p==0 ) return;
drh9bb61fe2000-06-05 16:01:39 +0000289 sqliteExprListDelete(p->pEList);
drhad3cab52002-05-24 02:04:32 +0000290 sqliteSrcListDelete(p->pSrc);
drh9bb61fe2000-06-05 16:01:39 +0000291 sqliteExprDelete(p->pWhere);
292 sqliteExprListDelete(p->pGroupBy);
293 sqliteExprDelete(p->pHaving);
294 sqliteExprListDelete(p->pOrderBy);
drh82c3d632000-06-06 21:56:07 +0000295 sqliteSelectDelete(p->pPrior);
drha76b5df2002-02-23 02:32:10 +0000296 sqliteFree(p->zSelect);
drh9bb61fe2000-06-05 16:01:39 +0000297 sqliteFree(p);
298}
299
300/*
drh22827922000-06-06 17:27:05 +0000301** Delete the aggregate information from the parse structure.
302*/
drh1d83f052002-02-17 00:30:36 +0000303static void sqliteAggregateInfoReset(Parse *pParse){
drh22827922000-06-06 17:27:05 +0000304 sqliteFree(pParse->aAgg);
305 pParse->aAgg = 0;
306 pParse->nAgg = 0;
drh22827922000-06-06 17:27:05 +0000307 pParse->useAgg = 0;
308}
309
310/*
drhc926afb2002-06-20 03:38:26 +0000311** Insert code into "v" that will push the record on the top of the
312** stack into the sorter.
313*/
314static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
315 char *zSortOrder;
316 int i;
317 zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
318 if( zSortOrder==0 ) return;
319 for(i=0; i<pOrderBy->nExpr; i++){
drh38640e12002-07-05 21:42:36 +0000320 int order = pOrderBy->a[i].sortOrder;
321 int type;
322 int c;
323 if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
324 type = SQLITE_SO_TEXT;
325 }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
326 type = SQLITE_SO_NUM;
drh491791a2002-07-18 00:34:09 +0000327 }else if( pParse->db->file_format>=4 ){
drh38640e12002-07-05 21:42:36 +0000328 type = sqliteExprType(pOrderBy->a[i].pExpr);
329 }else{
330 type = SQLITE_SO_NUM;
331 }
332 if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
333 c = type==SQLITE_SO_TEXT ? 'A' : '+';
334 }else{
335 c = type==SQLITE_SO_TEXT ? 'D' : '-';
336 }
337 zSortOrder[i] = c;
drhc926afb2002-06-20 03:38:26 +0000338 sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
339 }
340 zSortOrder[pOrderBy->nExpr] = 0;
drh701a0ae2004-02-22 20:05:00 +0000341 sqliteVdbeOp3(v, OP_SortMakeKey, pOrderBy->nExpr, 0, zSortOrder, P3_DYNAMIC);
drhc926afb2002-06-20 03:38:26 +0000342 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;
drh701a0ae2004-02-22 20:05:00 +0000364 sqliteVdbeChangeP3(v, -1, zType, P3_DYNAMIC);
drh38640e12002-07-05 21:42:36 +0000365}
366
367/*
drh22827922000-06-06 17:27:05 +0000368** This routine generates the code for the inside of the inner loop
369** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000370**
drh38640e12002-07-05 21:42:36 +0000371** If srcTab and nColumn are both zero, then the pEList expressions
372** are evaluated in order to get the data for this row. If nColumn>0
373** then data is pulled from srcTab and pEList is used only to get the
374** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000375*/
376static int selectInnerLoop(
377 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000378 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000379 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000380 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000381 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000382 ExprList *pOrderBy, /* If not NULL, sort results using this key */
383 int distinct, /* If >=0, make sure results are distinct */
384 int eDest, /* How to dispose of the results */
385 int iParm, /* An argument to the disposal method */
386 int iContinue, /* Jump here to continue with next row */
387 int iBreak /* Jump here to break out of the inner loop */
388){
389 Vdbe *v = pParse->pVdbe;
390 int i;
drh38640e12002-07-05 21:42:36 +0000391
drhdaffd0e2001-04-11 14:28:42 +0000392 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000393 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000394
drhdf199a22002-06-14 22:38:41 +0000395 /* If there was a LIMIT clause on the SELECT statement, then do the check
396 ** to see if this row should be output.
397 */
398 if( pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +0000399 if( p->iOffset>=0 ){
drhd11d3822002-06-21 23:01:49 +0000400 int addr = sqliteVdbeCurrentAddr(v);
drh7b58dae2003-07-20 01:16:46 +0000401 sqliteVdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2);
drhd11d3822002-06-21 23:01:49 +0000402 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
drhdf199a22002-06-14 22:38:41 +0000403 }
drh7b58dae2003-07-20 01:16:46 +0000404 if( p->iLimit>=0 ){
405 sqliteVdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhdf199a22002-06-14 22:38:41 +0000406 }
407 }
408
drh967e8b72000-06-21 13:59:10 +0000409 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000410 */
drh38640e12002-07-05 21:42:36 +0000411 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000412 for(i=0; i<nColumn; i++){
drh99fcd712001-10-13 01:06:47 +0000413 sqliteVdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000414 }
drh38640e12002-07-05 21:42:36 +0000415 }else{
416 nColumn = pEList->nExpr;
417 for(i=0; i<pEList->nExpr; i++){
418 sqliteExprCode(pParse, pEList->a[i].pExpr);
419 }
drh22827922000-06-06 17:27:05 +0000420 }
421
drhdaffd0e2001-04-11 14:28:42 +0000422 /* If the DISTINCT keyword was present on the SELECT statement
423 ** and this row has been seen before, then do not make this row
424 ** part of the result.
drh22827922000-06-06 17:27:05 +0000425 */
drhf5905aa2002-05-26 20:54:33 +0000426 if( distinct>=0 && pEList && pEList->nExpr>0 ){
drh0bd1f4e2002-06-06 18:54:39 +0000427#if NULL_ALWAYS_DISTINCT
428 sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7);
429#endif
drh99fcd712001-10-13 01:06:47 +0000430 sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
drh491791a2002-07-18 00:34:09 +0000431 if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pEList);
drhf5905aa2002-05-26 20:54:33 +0000432 sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
drh99fcd712001-10-13 01:06:47 +0000433 sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
434 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
drh99fcd712001-10-13 01:06:47 +0000435 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh6b125452002-01-28 15:53:03 +0000436 sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
drh22827922000-06-06 17:27:05 +0000437 }
drh82c3d632000-06-06 21:56:07 +0000438
drhc926afb2002-06-20 03:38:26 +0000439 switch( eDest ){
440 /* In this mode, write each query result to the key of the temporary
441 ** table iParm.
442 */
443 case SRT_Union: {
444 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
445 sqliteVdbeAddOp(v, OP_String, 0, 0);
446 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
447 break;
drh22827922000-06-06 17:27:05 +0000448 }
drh22827922000-06-06 17:27:05 +0000449
drhc926afb2002-06-20 03:38:26 +0000450 /* Store the result as data using a unique key.
451 */
452 case SRT_Table:
453 case SRT_TempTable: {
454 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
455 if( pOrderBy ){
456 pushOntoSorter(pParse, v, pOrderBy);
457 }else{
458 sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
459 sqliteVdbeAddOp(v, OP_Pull, 1, 0);
460 sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
461 }
462 break;
463 }
drh82c3d632000-06-06 21:56:07 +0000464
drhc926afb2002-06-20 03:38:26 +0000465 /* Construct a record from the query result, but instead of
466 ** saving that record, use it as a key to delete elements from
467 ** the temporary table iParm.
468 */
469 case SRT_Except: {
470 int addr;
471 addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
472 sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
473 sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
474 break;
475 }
drh5974a302000-06-07 14:42:26 +0000476
drhc926afb2002-06-20 03:38:26 +0000477 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
478 ** then there should be a single item on the stack. Write this
479 ** item into the set table with bogus data.
480 */
481 case SRT_Set: {
drh52b36ca2004-01-14 13:38:54 +0000482 int addr1 = sqliteVdbeCurrentAddr(v);
483 int addr2;
drhc926afb2002-06-20 03:38:26 +0000484 assert( nColumn==1 );
drh52b36ca2004-01-14 13:38:54 +0000485 sqliteVdbeAddOp(v, OP_NotNull, -1, addr1+3);
486 sqliteVdbeAddOp(v, OP_Pop, 1, 0);
487 addr2 = sqliteVdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000488 if( pOrderBy ){
489 pushOntoSorter(pParse, v, pOrderBy);
490 }else{
drha9f9d1c2002-06-29 02:20:08 +0000491 sqliteVdbeAddOp(v, OP_String, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000492 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
493 }
drh52b36ca2004-01-14 13:38:54 +0000494 sqliteVdbeChangeP2(v, addr2, sqliteVdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000495 break;
496 }
drh22827922000-06-06 17:27:05 +0000497
drhc926afb2002-06-20 03:38:26 +0000498 /* If this is a scalar select that is part of an expression, then
499 ** store the results in the appropriate memory cell and break out
500 ** of the scan loop.
501 */
502 case SRT_Mem: {
503 assert( nColumn==1 );
504 if( pOrderBy ){
505 pushOntoSorter(pParse, v, pOrderBy);
506 }else{
507 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
508 sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
509 }
510 break;
511 }
drh22827922000-06-06 17:27:05 +0000512
drhf46f9052002-06-22 02:33:38 +0000513 /* Send the data to the callback function.
514 */
515 case SRT_Callback:
516 case SRT_Sorter: {
517 if( pOrderBy ){
518 sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
519 pushOntoSorter(pParse, v, pOrderBy);
520 }else{
521 assert( eDest==SRT_Callback );
522 sqliteVdbeAddOp(v, OP_Callback, nColumn, 0);
523 }
524 break;
525 }
526
drh142e30d2002-08-28 03:00:58 +0000527 /* Invoke a subroutine to handle the results. The subroutine itself
528 ** is responsible for popping the results off of the stack.
529 */
530 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000531 if( pOrderBy ){
532 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
533 pushOntoSorter(pParse, v, pOrderBy);
534 }else{
535 sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
536 }
drh142e30d2002-08-28 03:00:58 +0000537 break;
538 }
539
drhc926afb2002-06-20 03:38:26 +0000540 /* Discard the results. This is used for SELECT statements inside
541 ** the body of a TRIGGER. The purpose of such selects is to call
542 ** user-defined functions that have side effects. We do not care
543 ** about the actual results of the select.
544 */
drhc926afb2002-06-20 03:38:26 +0000545 default: {
drhf46f9052002-06-22 02:33:38 +0000546 assert( eDest==SRT_Discard );
547 sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000548 break;
549 }
drh82c3d632000-06-06 21:56:07 +0000550 }
551 return 0;
552}
553
554/*
drhd8bc7082000-06-07 23:51:50 +0000555** If the inner loop was generated using a non-null pOrderBy argument,
556** then the results were placed in a sorter. After the loop is terminated
557** we need to run the sorter and output the results. The following
558** routine generates the code needed to do that.
559*/
drhc926afb2002-06-20 03:38:26 +0000560static void generateSortTail(
561 Select *p, /* The SELECT statement */
562 Vdbe *v, /* Generate code into this VDBE */
563 int nColumn, /* Number of columns of data */
564 int eDest, /* Write the sorted results here */
565 int iParm /* Optional parameter associated with eDest */
566){
drhd8bc7082000-06-07 23:51:50 +0000567 int end = sqliteVdbeMakeLabel(v);
568 int addr;
drhf46f9052002-06-22 02:33:38 +0000569 if( eDest==SRT_Sorter ) return;
drh99fcd712001-10-13 01:06:47 +0000570 sqliteVdbeAddOp(v, OP_Sort, 0, 0);
571 addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end);
drh7b58dae2003-07-20 01:16:46 +0000572 if( p->iOffset>=0 ){
573 sqliteVdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4);
drhd11d3822002-06-21 23:01:49 +0000574 sqliteVdbeAddOp(v, OP_Pop, 1, 0);
575 sqliteVdbeAddOp(v, OP_Goto, 0, addr);
drhdf199a22002-06-14 22:38:41 +0000576 }
drh7b58dae2003-07-20 01:16:46 +0000577 if( p->iLimit>=0 ){
578 sqliteVdbeAddOp(v, OP_MemIncr, p->iLimit, end);
drhdf199a22002-06-14 22:38:41 +0000579 }
drhc926afb2002-06-20 03:38:26 +0000580 switch( eDest ){
581 case SRT_Callback: {
582 sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0);
583 break;
584 }
585 case SRT_Table:
586 case SRT_TempTable: {
587 sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
588 sqliteVdbeAddOp(v, OP_Pull, 1, 0);
589 sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
590 break;
591 }
592 case SRT_Set: {
593 assert( nColumn==1 );
drh52b36ca2004-01-14 13:38:54 +0000594 sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
595 sqliteVdbeAddOp(v, OP_Pop, 1, 0);
596 sqliteVdbeAddOp(v, OP_Goto, 0, sqliteVdbeCurrentAddr(v)+3);
drhc926afb2002-06-20 03:38:26 +0000597 sqliteVdbeAddOp(v, OP_String, 0, 0);
598 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
599 break;
600 }
601 case SRT_Mem: {
602 assert( nColumn==1 );
603 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
604 sqliteVdbeAddOp(v, OP_Goto, 0, end);
605 break;
606 }
drhac82fcf2002-09-08 17:23:41 +0000607 case SRT_Subroutine: {
608 int i;
609 for(i=0; i<nColumn; i++){
610 sqliteVdbeAddOp(v, OP_Column, -1-i, i);
611 }
612 sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
613 sqliteVdbeAddOp(v, OP_Pop, 1, 0);
614 break;
615 }
drhc926afb2002-06-20 03:38:26 +0000616 default: {
drhf46f9052002-06-22 02:33:38 +0000617 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000618 break;
619 }
620 }
drh99fcd712001-10-13 01:06:47 +0000621 sqliteVdbeAddOp(v, OP_Goto, 0, addr);
622 sqliteVdbeResolveLabel(v, end);
drha8b38d22001-11-01 14:41:34 +0000623 sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000624}
625
626/*
drhfcb78a42003-01-18 20:11:05 +0000627** Generate code that will tell the VDBE the datatypes of
628** columns in the result set.
drhe78e8282003-01-19 03:59:45 +0000629**
630** This routine only generates code if the "PRAGMA show_datatypes=on"
631** has been executed. The datatypes are reported out in the azCol
632** parameter to the callback function. The first N azCol[] entries
633** are the names of the columns, and the second N entries are the
634** datatypes for the columns.
635**
636** The "datatype" for a result that is a column of a type is the
637** datatype definition extracted from the CREATE TABLE statement.
638** The datatype for an expression is either TEXT or NUMERIC. The
639** datatype for a ROWID field is INTEGER.
drhfcb78a42003-01-18 20:11:05 +0000640*/
641static void generateColumnTypes(
642 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000643 SrcList *pTabList, /* List of tables */
644 ExprList *pEList /* Expressions defining the result set */
645){
646 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000647 int i, j;
drhfcb78a42003-01-18 20:11:05 +0000648 for(i=0; i<pEList->nExpr; i++){
649 Expr *p = pEList->a[i].pExpr;
650 char *zType = 0;
651 if( p==0 ) continue;
652 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000653 Table *pTab;
drhfcb78a42003-01-18 20:11:05 +0000654 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000655 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
656 assert( j<pTabList->nSrc );
657 pTab = pTabList->a[j].pTab;
drhfcb78a42003-01-18 20:11:05 +0000658 if( iCol<0 ) iCol = pTab->iPKey;
659 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
660 if( iCol<0 ){
661 zType = "INTEGER";
662 }else{
663 zType = pTab->aCol[iCol].zType;
664 }
665 }else{
666 if( sqliteExprType(p)==SQLITE_SO_TEXT ){
667 zType = "TEXT";
668 }else{
669 zType = "NUMERIC";
670 }
671 }
drh701a0ae2004-02-22 20:05:00 +0000672 sqliteVdbeOp3(v, OP_ColumnName, i + pEList->nExpr, 0, zType, 0);
drhfcb78a42003-01-18 20:11:05 +0000673 }
674}
675
676/*
677** Generate code that will tell the VDBE the names of columns
678** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000679** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000680*/
drh832508b2002-03-02 17:04:07 +0000681static void generateColumnNames(
682 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000683 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000684 ExprList *pEList /* Expressions defining the result set */
685){
drhd8bc7082000-06-07 23:51:50 +0000686 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000687 int i, j;
drhfcabd462004-02-20 14:50:58 +0000688 sqlite *db = pParse->db;
689 int fullNames, shortNames;
690
drhd6502752004-02-16 03:44:01 +0000691 assert( v!=0 );
drhdaffd0e2001-04-11 14:28:42 +0000692 if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000693 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000694 fullNames = (db->flags & SQLITE_FullColNames)!=0;
695 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
drh82c3d632000-06-06 21:56:07 +0000696 for(i=0; i<pEList->nExpr; i++){
697 Expr *p;
drhd6502752004-02-16 03:44:01 +0000698 int p2 = i==pEList->nExpr-1;
drh5a387052003-01-11 14:19:51 +0000699 p = pEList->a[i].pExpr;
700 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000701 if( pEList->a[i].zName ){
702 char *zName = pEList->a[i].zName;
drh701a0ae2004-02-22 20:05:00 +0000703 sqliteVdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000704 continue;
705 }
drhfa173a72002-07-10 21:26:00 +0000706 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000707 Table *pTab;
drh97665872002-02-13 23:22:53 +0000708 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000709 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000710 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
711 assert( j<pTabList->nSrc );
712 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000713 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000714 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000715 if( iCol<0 ){
716 zCol = "_ROWID_";
drhb1363202002-06-26 02:45:03 +0000717 }else{
718 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000719 }
drhfcabd462004-02-20 14:50:58 +0000720 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
drh701a0ae2004-02-22 20:05:00 +0000721 int addr = sqliteVdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
drhfa173a72002-07-10 21:26:00 +0000722 sqliteVdbeCompressSpace(v, addr);
drhfcabd462004-02-20 14:50:58 +0000723 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000724 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000725 char *zTab;
726
drh6a3ea0e2003-05-02 14:32:12 +0000727 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000728 if( fullNames || zTab==0 ) zTab = pTab->zName;
drh97665872002-02-13 23:22:53 +0000729 sqliteSetString(&zName, zTab, ".", zCol, 0);
drh701a0ae2004-02-22 20:05:00 +0000730 sqliteVdbeOp3(v, OP_ColumnName, i, p2, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000731 }else{
drh701a0ae2004-02-22 20:05:00 +0000732 sqliteVdbeOp3(v, OP_ColumnName, i, p2, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000733 }
drh6977fea2002-10-22 23:38:04 +0000734 }else if( p->span.z && p->span.z[0] ){
drh701a0ae2004-02-22 20:05:00 +0000735 int addr = sqliteVdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
drh1bee3d72001-10-15 00:44:35 +0000736 sqliteVdbeCompressSpace(v, addr);
737 }else{
738 char zName[30];
739 assert( p->op!=TK_COLUMN || pTabList==0 );
740 sprintf(zName, "column%d", i+1);
drh701a0ae2004-02-22 20:05:00 +0000741 sqliteVdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000742 }
743 }
744}
745
746/*
drhd8bc7082000-06-07 23:51:50 +0000747** Name of the connection operator, used for error messages.
748*/
749static const char *selectOpName(int id){
750 char *z;
751 switch( id ){
752 case TK_ALL: z = "UNION ALL"; break;
753 case TK_INTERSECT: z = "INTERSECT"; break;
754 case TK_EXCEPT: z = "EXCEPT"; break;
755 default: z = "UNION"; break;
756 }
757 return z;
758}
759
760/*
drh315555c2002-10-20 15:53:03 +0000761** Forward declaration
762*/
763static int fillInColumnList(Parse*, Select*);
764
765/*
drh22f70c32002-02-18 01:17:00 +0000766** Given a SELECT statement, generate a Table structure that describes
767** the result set of that SELECT.
768*/
769Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
770 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000771 int i, j;
drh22f70c32002-02-18 01:17:00 +0000772 ExprList *pEList;
drhb733d032004-01-24 20:18:12 +0000773 Column *aCol;
drh22f70c32002-02-18 01:17:00 +0000774
775 if( fillInColumnList(pParse, pSelect) ){
776 return 0;
777 }
778 pTab = sqliteMalloc( sizeof(Table) );
779 if( pTab==0 ){
780 return 0;
781 }
782 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
783 pEList = pSelect->pEList;
784 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000785 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000786 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh22f70c32002-02-18 01:17:00 +0000787 for(i=0; i<pTab->nCol; i++){
drhb733d032004-01-24 20:18:12 +0000788 Expr *p, *pR;
drh22f70c32002-02-18 01:17:00 +0000789 if( pEList->a[i].zName ){
drhb733d032004-01-24 20:18:12 +0000790 aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
791 }else if( (p=pEList->a[i].pExpr)->op==TK_DOT
792 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
793 int cnt;
794 sqliteSetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
795 for(j=cnt=0; j<i; j++){
796 if( sqliteStrICmp(aCol[j].zName, aCol[i].zName)==0 ){
797 int n;
798 char zBuf[30];
799 sprintf(zBuf,"_%d",++cnt);
800 n = strlen(zBuf);
801 sqliteSetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf, n,0);
802 j = -1;
803 }
804 }
805 }else if( p->span.z && p->span.z[0] ){
drh6977fea2002-10-22 23:38:04 +0000806 sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drh22f70c32002-02-18 01:17:00 +0000807 }else{
808 char zBuf[30];
809 sprintf(zBuf, "column%d", i+1);
810 pTab->aCol[i].zName = sqliteStrDup(zBuf);
811 }
812 }
813 pTab->iPKey = -1;
814 return pTab;
815}
816
817/*
drhad2d8302002-05-24 20:31:36 +0000818** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000819**
drhad3cab52002-05-24 02:04:32 +0000820** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh63eb5f22003-04-29 16:20:44 +0000821** defines the set of tables that should be scanned. For views,
822** fill pTabList->a[].pSelect with a copy of the SELECT statement
823** that implements the view. A copy is made of the view's SELECT
824** statement so that we can freely modify or delete that statement
825** without worrying about messing up the presistent representation
826** of the view.
drhd8bc7082000-06-07 23:51:50 +0000827**
drhad2d8302002-05-24 20:31:36 +0000828** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
829** on joins and the ON and USING clause of joins.
830**
831** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000832** for instances of the "*" operator or the TABLE.* operator.
833** If found, expand each "*" to be every column in every table
834** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000835**
836** Return 0 on success. If there are problems, leave an error message
837** in pParse and return non-zero.
838*/
839static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000840 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000841 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000842 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000843 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000844
845 if( p==0 || p->pSrc==0 ) return 1;
846 pTabList = p->pSrc;
847 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000848
849 /* Look up every table in the table list.
850 */
drhad3cab52002-05-24 02:04:32 +0000851 for(i=0; i<pTabList->nSrc; i++){
drhd8bc7082000-06-07 23:51:50 +0000852 if( pTabList->a[i].pTab ){
853 /* This routine has run before! No need to continue */
854 return 0;
855 }
drhdaffd0e2001-04-11 14:28:42 +0000856 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000857 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000858 assert( pTabList->a[i].pSelect!=0 );
drhad2d8302002-05-24 20:31:36 +0000859 if( pTabList->a[i].zAlias==0 ){
860 char zFakeName[60];
861 sprintf(zFakeName, "sqlite_subquery_%p_",
862 (void*)pTabList->a[i].pSelect);
863 sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
864 }
drh22f70c32002-02-18 01:17:00 +0000865 pTabList->a[i].pTab = pTab =
866 sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
867 pTabList->a[i].pSelect);
868 if( pTab==0 ){
869 return 1;
870 }
drh5cf590c2003-04-24 01:45:04 +0000871 /* The isTransient flag indicates that the Table structure has been
872 ** dynamically allocated and may be freed at any time. In other words,
873 ** pTab is not pointing to a persistent table structure that defines
874 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000875 pTab->isTransient = 1;
876 }else{
drha76b5df2002-02-23 02:32:10 +0000877 /* An ordinary table or view name in the FROM clause */
878 pTabList->a[i].pTab = pTab =
drha69d9162003-04-17 22:57:53 +0000879 sqliteLocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
drha76b5df2002-02-23 02:32:10 +0000880 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000881 return 1;
882 }
drha76b5df2002-02-23 02:32:10 +0000883 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +0000884 /* We reach here if the named table is a really a view */
drh417be792002-03-03 18:59:40 +0000885 if( sqliteViewGetColumnNames(pParse, pTab) ){
886 return 1;
887 }
drh63eb5f22003-04-29 16:20:44 +0000888 /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
889 ** view within a view. The SELECT structure has already been
890 ** copied by the outer view so we can skip the copy step here
891 ** in the inner view.
892 */
893 if( pTabList->a[i].pSelect==0 ){
894 pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
895 }
drha76b5df2002-02-23 02:32:10 +0000896 }
drhd8bc7082000-06-07 23:51:50 +0000897 }
898 }
899
drhad2d8302002-05-24 20:31:36 +0000900 /* Process NATURAL keywords, and ON and USING clauses of joins.
901 */
902 if( sqliteProcessJoin(pParse, p) ) return 1;
903
drh7c917d12001-12-16 20:05:05 +0000904 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000905 ** all columns in all tables. And for every TABLE.* insert the names
906 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000907 ** with the TK_ALL operator for each "*" that it found in the column list.
908 ** The following code just has to locate the TK_ALL expressions and expand
909 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000910 **
911 ** The first loop just checks to see if there are any "*" operators
912 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000913 */
drh7c917d12001-12-16 20:05:05 +0000914 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000915 Expr *pE = pEList->a[k].pExpr;
916 if( pE->op==TK_ALL ) break;
917 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
918 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000919 }
drh54473222002-04-04 02:10:55 +0000920 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000921 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000922 /*
923 ** If we get here it means the result set contains one or more "*"
924 ** operators that need to be expanded. Loop through each expression
925 ** in the result set and expand them one by one.
926 */
drh7c917d12001-12-16 20:05:05 +0000927 struct ExprList_item *a = pEList->a;
928 ExprList *pNew = 0;
929 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000930 Expr *pE = a[k].pExpr;
931 if( pE->op!=TK_ALL &&
932 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
933 /* This particular expression does not need to be expanded.
934 */
drh7c917d12001-12-16 20:05:05 +0000935 pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
936 pNew->a[pNew->nExpr-1].zName = a[k].zName;
937 a[k].pExpr = 0;
938 a[k].zName = 0;
939 }else{
drh54473222002-04-04 02:10:55 +0000940 /* This expression is a "*" or a "TABLE.*" and needs to be
941 ** expanded. */
942 int tableSeen = 0; /* Set to 1 when TABLE matches */
943 Token *pName; /* text of name of TABLE */
944 if( pE->op==TK_DOT && pE->pLeft ){
945 pName = &pE->pLeft->token;
946 }else{
947 pName = 0;
948 }
drhad3cab52002-05-24 02:04:32 +0000949 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000950 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000951 char *zTabName = pTabList->a[i].zAlias;
952 if( zTabName==0 || zTabName[0]==0 ){
953 zTabName = pTab->zName;
954 }
drhc754fa52002-05-27 03:25:51 +0000955 if( pName && (zTabName==0 || zTabName[0]==0 ||
956 sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
957 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +0000958 continue;
959 }
960 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +0000961 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000962 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +0000963 char *zName = pTab->aCol[j].zName;
964
965 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
966 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
967 /* In a NATURAL join, omit the join columns from the
968 ** table on the right */
969 continue;
970 }
971 if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
972 /* In a join with a USING clause, omit columns in the
973 ** using clause from the table on the right. */
974 continue;
975 }
drh22f70c32002-02-18 01:17:00 +0000976 pRight = sqliteExpr(TK_ID, 0, 0, 0);
977 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +0000978 pRight->token.z = zName;
979 pRight->token.n = strlen(zName);
drh4b59ab52002-08-24 18:24:51 +0000980 pRight->token.dyn = 0;
drh4b59ab52002-08-24 18:24:51 +0000981 if( zTabName && pTabList->nSrc>1 ){
drh22f70c32002-02-18 01:17:00 +0000982 pLeft = sqliteExpr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +0000983 pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
984 if( pExpr==0 ) break;
drh4b59ab52002-08-24 18:24:51 +0000985 pLeft->token.z = zTabName;
986 pLeft->token.n = strlen(zTabName);
987 pLeft->token.dyn = 0;
drh6977fea2002-10-22 23:38:04 +0000988 sqliteSetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
989 pExpr->span.n = strlen(pExpr->span.z);
990 pExpr->span.dyn = 1;
991 pExpr->token.z = 0;
992 pExpr->token.n = 0;
993 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +0000994 }else{
drh22f70c32002-02-18 01:17:00 +0000995 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +0000996 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +0000997 }
drh7c917d12001-12-16 20:05:05 +0000998 pNew = sqliteExprListAppend(pNew, pExpr, 0);
999 }
drh17e24df2001-11-06 14:10:41 +00001000 }
drh54473222002-04-04 02:10:55 +00001001 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +00001002 if( pName ){
drhda93d232003-03-31 02:12:46 +00001003 sqliteErrorMsg(pParse, "no such table: %T", pName);
drhf5db2d32002-06-06 23:42:27 +00001004 }else{
drhda93d232003-03-31 02:12:46 +00001005 sqliteErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001006 }
drh54473222002-04-04 02:10:55 +00001007 rc = 1;
1008 }
drhd8bc7082000-06-07 23:51:50 +00001009 }
1010 }
drh7c917d12001-12-16 20:05:05 +00001011 sqliteExprListDelete(pEList);
1012 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001013 }
drh54473222002-04-04 02:10:55 +00001014 return rc;
drhd8bc7082000-06-07 23:51:50 +00001015}
1016
1017/*
drhff78bd22002-02-27 01:47:11 +00001018** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1019** in a select structure. It just sets the pointers to NULL. This
1020** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1021** pointer is not NULL, this routine is called recursively on that pointer.
1022**
1023** This routine is called on the Select structure that defines a
1024** VIEW in order to undo any bindings to tables. This is necessary
1025** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001026** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1027** will be left pointing to a deallocated Table structure after the
1028** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001029*/
1030void sqliteSelectUnbind(Select *p){
1031 int i;
drhad3cab52002-05-24 02:04:32 +00001032 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +00001033 Table *pTab;
1034 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +00001035 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +00001036 if( (pTab = pSrc->a[i].pTab)!=0 ){
1037 if( pTab->isTransient ){
1038 sqliteDeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001039 }
1040 pSrc->a[i].pTab = 0;
1041 if( pSrc->a[i].pSelect ){
1042 sqliteSelectUnbind(pSrc->a[i].pSelect);
1043 }
1044 }
1045 }
1046}
1047
1048/*
drhd8bc7082000-06-07 23:51:50 +00001049** This routine associates entries in an ORDER BY expression list with
1050** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001051** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001052** the top-level node is filled in with column number and the iTable
1053** value of the top-level node is filled with iTable parameter.
1054**
1055** If there are prior SELECT clauses, they are processed first. A match
1056** in an earlier SELECT takes precedence over a later SELECT.
1057**
1058** Any entry that does not match is flagged as an error. The number
1059** of errors is returned.
drhfcb78a42003-01-18 20:11:05 +00001060**
1061** This routine does NOT correctly initialize the Expr.dataType field
1062** of the ORDER BY expressions. The multiSelectSortOrder() routine
1063** must be called to do that after the individual select statements
1064** have all been analyzed. This routine is unable to compute Expr.dataType
1065** because it must be called before the individual select statements
1066** have been analyzed.
drhd8bc7082000-06-07 23:51:50 +00001067*/
1068static int matchOrderbyToColumn(
1069 Parse *pParse, /* A place to leave error messages */
1070 Select *pSelect, /* Match to result columns of this SELECT */
1071 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001072 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001073 int mustComplete /* If TRUE all ORDER BYs must match */
1074){
1075 int nErr = 0;
1076 int i, j;
1077 ExprList *pEList;
1078
drhdaffd0e2001-04-11 14:28:42 +00001079 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001080 if( mustComplete ){
1081 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1082 }
1083 if( fillInColumnList(pParse, pSelect) ){
1084 return 1;
1085 }
1086 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001087 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1088 return 1;
1089 }
drhd8bc7082000-06-07 23:51:50 +00001090 }
1091 pEList = pSelect->pEList;
1092 for(i=0; i<pOrderBy->nExpr; i++){
1093 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001094 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001095 if( pOrderBy->a[i].done ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001096 if( sqliteExprIsInteger(pE, &iCol) ){
1097 if( iCol<=0 || iCol>pEList->nExpr ){
drhda93d232003-03-31 02:12:46 +00001098 sqliteErrorMsg(pParse,
1099 "ORDER BY position %d should be between 1 and %d",
1100 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001101 nErr++;
1102 break;
1103 }
drhfcb78a42003-01-18 20:11:05 +00001104 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001105 iCol--;
1106 }
1107 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001108 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001109 char *zName, *zLabel;
1110 zName = pEList->a[j].zName;
1111 assert( pE->token.z );
1112 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
drhd8bc7082000-06-07 23:51:50 +00001113 sqliteDequote(zLabel);
1114 if( sqliteStrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001115 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001116 }
drh6e142f52000-06-08 13:36:40 +00001117 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001118 }
drhe4de1fe2002-06-02 16:09:01 +00001119 if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
1120 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001121 }
1122 }
drhe4de1fe2002-06-02 16:09:01 +00001123 if( iCol>=0 ){
1124 pE->op = TK_COLUMN;
1125 pE->iColumn = iCol;
1126 pE->iTable = iTable;
1127 pOrderBy->a[i].done = 1;
1128 }
1129 if( iCol<0 && mustComplete ){
drhda93d232003-03-31 02:12:46 +00001130 sqliteErrorMsg(pParse,
1131 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001132 nErr++;
1133 break;
1134 }
1135 }
1136 return nErr;
1137}
1138
1139/*
1140** Get a VDBE for the given parser context. Create a new one if necessary.
1141** If an error occurs, return NULL and leave a message in pParse.
1142*/
1143Vdbe *sqliteGetVdbe(Parse *pParse){
1144 Vdbe *v = pParse->pVdbe;
1145 if( v==0 ){
drh4c504392000-10-16 22:06:40 +00001146 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001147 }
drhd8bc7082000-06-07 23:51:50 +00001148 return v;
1149}
drhfcb78a42003-01-18 20:11:05 +00001150
1151/*
1152** This routine sets the Expr.dataType field on all elements of
1153** the pOrderBy expression list. The pOrderBy list will have been
1154** set up by matchOrderbyToColumn(). Hence each expression has
1155** a TK_COLUMN as its root node. The Expr.iColumn refers to a
1156** column in the result set. The datatype is set to SQLITE_SO_TEXT
1157** if the corresponding column in p and every SELECT to the left of
1158** p has a datatype of SQLITE_SO_TEXT. If the cooressponding column
1159** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
1160** of the order-by expression is set to SQLITE_SO_NUM.
1161**
1162** Examples:
1163**
drhe78e8282003-01-19 03:59:45 +00001164** CREATE TABLE one(a INTEGER, b TEXT);
1165** CREATE TABLE two(c VARCHAR(5), d FLOAT);
1166**
1167** SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
1168**
1169** The primary sort key will use SQLITE_SO_NUM because the "d" in
1170** the second SELECT is numeric. The 1st column of the first SELECT
1171** is text but that does not matter because a numeric always overrides
1172** a text.
1173**
1174** The secondary key will use the SQLITE_SO_TEXT sort order because
1175** both the (second) "b" in the first SELECT and the "c" in the second
1176** SELECT have a datatype of text.
drhfcb78a42003-01-18 20:11:05 +00001177*/
1178static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
1179 int i;
1180 ExprList *pEList;
1181 if( pOrderBy==0 ) return;
1182 if( p==0 ){
1183 for(i=0; i<pOrderBy->nExpr; i++){
1184 pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
1185 }
1186 return;
1187 }
1188 multiSelectSortOrder(p->pPrior, pOrderBy);
1189 pEList = p->pEList;
1190 for(i=0; i<pOrderBy->nExpr; i++){
1191 Expr *pE = pOrderBy->a[i].pExpr;
1192 if( pE->dataType==SQLITE_SO_NUM ) continue;
1193 assert( pE->iColumn>=0 );
1194 if( pEList->nExpr>pE->iColumn ){
1195 pE->dataType = sqliteExprType(pEList->a[pE->iColumn].pExpr);
1196 }
1197 }
1198}
drhd8bc7082000-06-07 23:51:50 +00001199
1200/*
drh7b58dae2003-07-20 01:16:46 +00001201** Compute the iLimit and iOffset fields of the SELECT based on the
1202** nLimit and nOffset fields. nLimit and nOffset hold the integers
1203** that appear in the original SQL statement after the LIMIT and OFFSET
1204** keywords. Or that hold -1 and 0 if those keywords are omitted.
1205** iLimit and iOffset are the integer memory register numbers for
1206** counters used to compute the limit and offset. If there is no
1207** limit and/or offset, then iLimit and iOffset are negative.
1208**
1209** This routine changes the values if iLimit and iOffset only if
1210** a limit or offset is defined by nLimit and nOffset. iLimit and
1211** iOffset should have been preset to appropriate default values
1212** (usually but not always -1) prior to calling this routine.
1213** Only if nLimit>=0 or nOffset>0 do the limit registers get
1214** redefined. The UNION ALL operator uses this property to force
1215** the reuse of the same limit and offset registers across multiple
1216** SELECT statements.
1217*/
1218static void computeLimitRegisters(Parse *pParse, Select *p){
1219 /*
1220 ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
1221 ** all rows. It is the same as no limit. If the comparision is
1222 ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
1223 ** "LIMIT -1" always shows all rows. There is some
1224 ** contraversy about what the correct behavior should be.
1225 ** The current implementation interprets "LIMIT 0" to mean
1226 ** no rows.
1227 */
1228 if( p->nLimit>=0 ){
1229 int iMem = pParse->nMem++;
1230 Vdbe *v = sqliteGetVdbe(pParse);
1231 if( v==0 ) return;
1232 sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1233 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
1234 p->iLimit = iMem;
1235 }
1236 if( p->nOffset>0 ){
1237 int iMem = pParse->nMem++;
1238 Vdbe *v = sqliteGetVdbe(pParse);
1239 if( v==0 ) return;
1240 sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1241 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
1242 p->iOffset = iMem;
1243 }
1244}
1245
1246/*
drh82c3d632000-06-06 21:56:07 +00001247** This routine is called to process a query that is really the union
1248** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001249**
drhe78e8282003-01-19 03:59:45 +00001250** "p" points to the right-most of the two queries. the query on the
1251** left is p->pPrior. The left query could also be a compound query
1252** in which case this routine will be called recursively.
1253**
1254** The results of the total query are to be written into a destination
1255** of type eDest with parameter iParm.
1256**
1257** Example 1: Consider a three-way compound SQL statement.
1258**
1259** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1260**
1261** This statement is parsed up as follows:
1262**
1263** SELECT c FROM t3
1264** |
1265** `-----> SELECT b FROM t2
1266** |
jplyon4b11c6d2004-01-19 04:57:53 +00001267** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001268**
1269** The arrows in the diagram above represent the Select.pPrior pointer.
1270** So if this routine is called with p equal to the t3 query, then
1271** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1272**
1273** Notice that because of the way SQLite parses compound SELECTs, the
1274** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001275*/
1276static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
drh10e5e3c2000-06-08 00:19:02 +00001277 int rc; /* Success code from a subroutine */
1278 Select *pPrior; /* Another SELECT immediately to our left */
1279 Vdbe *v; /* Generate code to this VDBE */
drh82c3d632000-06-06 21:56:07 +00001280
drh7b58dae2003-07-20 01:16:46 +00001281 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
1282 ** the last SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001283 */
drhdaffd0e2001-04-11 14:28:42 +00001284 if( p==0 || p->pPrior==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001285 pPrior = p->pPrior;
1286 if( pPrior->pOrderBy ){
drhda93d232003-03-31 02:12:46 +00001287 sqliteErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1288 selectOpName(p->op));
drh82c3d632000-06-06 21:56:07 +00001289 return 1;
1290 }
drh7b58dae2003-07-20 01:16:46 +00001291 if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
1292 sqliteErrorMsg(pParse,"LIMIT clause should come after %s not before",
1293 selectOpName(p->op));
1294 return 1;
1295 }
drh82c3d632000-06-06 21:56:07 +00001296
drhd8bc7082000-06-07 23:51:50 +00001297 /* Make sure we have a valid query engine. If not, create a new one.
1298 */
1299 v = sqliteGetVdbe(pParse);
1300 if( v==0 ) return 1;
1301
drh1cc3d752002-03-23 00:31:29 +00001302 /* Create the destination temporary table if necessary
1303 */
1304 if( eDest==SRT_TempTable ){
1305 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
1306 eDest = SRT_Table;
1307 }
1308
drhf46f9052002-06-22 02:33:38 +00001309 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001310 */
drh82c3d632000-06-06 21:56:07 +00001311 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001312 case TK_ALL: {
1313 if( p->pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +00001314 pPrior->nLimit = p->nLimit;
1315 pPrior->nOffset = p->nOffset;
drhf46f9052002-06-22 02:33:38 +00001316 rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
1317 if( rc ) return rc;
1318 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001319 p->iLimit = pPrior->iLimit;
1320 p->iOffset = pPrior->iOffset;
1321 p->nLimit = -1;
1322 p->nOffset = 0;
drhf46f9052002-06-22 02:33:38 +00001323 rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
1324 p->pPrior = pPrior;
1325 if( rc ) return rc;
1326 break;
1327 }
1328 /* For UNION ALL ... ORDER BY fall through to the next case */
1329 }
drh82c3d632000-06-06 21:56:07 +00001330 case TK_EXCEPT:
1331 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001332 int unionTab; /* Cursor number of the temporary table holding result */
1333 int op; /* One of the SRT_ operations to apply to self */
1334 int priorOp; /* The SRT_ operation to apply to prior selects */
drh7b58dae2003-07-20 01:16:46 +00001335 int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
drhc926afb2002-06-20 03:38:26 +00001336 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
drh82c3d632000-06-06 21:56:07 +00001337
drhd8bc7082000-06-07 23:51:50 +00001338 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh7b58dae2003-07-20 01:16:46 +00001339 if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
drhd8bc7082000-06-07 23:51:50 +00001340 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001341 ** right.
drhd8bc7082000-06-07 23:51:50 +00001342 */
drh82c3d632000-06-06 21:56:07 +00001343 unionTab = iParm;
1344 }else{
drhd8bc7082000-06-07 23:51:50 +00001345 /* We will need to create our own temporary table to hold the
1346 ** intermediate results.
1347 */
1348 unionTab = pParse->nTab++;
1349 if( p->pOrderBy
1350 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1351 return 1;
1352 }
drhd8bc7082000-06-07 23:51:50 +00001353 if( p->op!=TK_ALL ){
drhc6b52df2002-01-04 03:09:29 +00001354 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
drh99fcd712001-10-13 01:06:47 +00001355 sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drh345fda32001-01-15 22:51:08 +00001356 }else{
drh99fcd712001-10-13 01:06:47 +00001357 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001358 }
drh82c3d632000-06-06 21:56:07 +00001359 }
drhd8bc7082000-06-07 23:51:50 +00001360
1361 /* Code the SELECT statements to our left
1362 */
drh832508b2002-03-02 17:04:07 +00001363 rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001364 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001365
1366 /* Code the current SELECT statement
1367 */
1368 switch( p->op ){
1369 case TK_EXCEPT: op = SRT_Except; break;
1370 case TK_UNION: op = SRT_Union; break;
1371 case TK_ALL: op = SRT_Table; break;
1372 }
drh82c3d632000-06-06 21:56:07 +00001373 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001374 pOrderBy = p->pOrderBy;
1375 p->pOrderBy = 0;
drh7b58dae2003-07-20 01:16:46 +00001376 nLimit = p->nLimit;
1377 p->nLimit = -1;
1378 nOffset = p->nOffset;
1379 p->nOffset = 0;
drh832508b2002-03-02 17:04:07 +00001380 rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001381 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001382 p->pOrderBy = pOrderBy;
drh7b58dae2003-07-20 01:16:46 +00001383 p->nLimit = nLimit;
1384 p->nOffset = nOffset;
drh82c3d632000-06-06 21:56:07 +00001385 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001386
1387 /* Convert the data in the temporary table into whatever form
1388 ** it is that we currently need.
1389 */
drhc926afb2002-06-20 03:38:26 +00001390 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001391 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001392 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001393 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001394 generateColumnNames(pParse, 0, p->pEList);
1395 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001396 }
drh82c3d632000-06-06 21:56:07 +00001397 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001398 iCont = sqliteVdbeMakeLabel(v);
1399 sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001400 computeLimitRegisters(pParse, p);
drh6b563442001-11-07 16:48:26 +00001401 iStart = sqliteVdbeCurrentAddr(v);
drhfcb78a42003-01-18 20:11:05 +00001402 multiSelectSortOrder(p, p->pOrderBy);
drh38640e12002-07-05 21:42:36 +00001403 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001404 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001405 iCont, iBreak);
1406 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001407 sqliteVdbeResolveLabel(v, iCont);
1408 sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
drh99fcd712001-10-13 01:06:47 +00001409 sqliteVdbeResolveLabel(v, iBreak);
1410 sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001411 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001412 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001413 }
drh82c3d632000-06-06 21:56:07 +00001414 }
1415 break;
1416 }
1417 case TK_INTERSECT: {
1418 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001419 int iCont, iBreak, iStart;
drh7b58dae2003-07-20 01:16:46 +00001420 int nLimit, nOffset;
drh82c3d632000-06-06 21:56:07 +00001421
drhd8bc7082000-06-07 23:51:50 +00001422 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001423 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001424 ** by allocating the tables we will need.
1425 */
drh82c3d632000-06-06 21:56:07 +00001426 tab1 = pParse->nTab++;
1427 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001428 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1429 return 1;
1430 }
drhc6b52df2002-01-04 03:09:29 +00001431 sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
drh99fcd712001-10-13 01:06:47 +00001432 sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
drhd8bc7082000-06-07 23:51:50 +00001433
1434 /* Code the SELECTs to our left into temporary table "tab1".
1435 */
drh832508b2002-03-02 17:04:07 +00001436 rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001437 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001438
1439 /* Code the current SELECT into temporary table "tab2"
1440 */
drhc6b52df2002-01-04 03:09:29 +00001441 sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
drh99fcd712001-10-13 01:06:47 +00001442 sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001443 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001444 nLimit = p->nLimit;
1445 p->nLimit = -1;
1446 nOffset = p->nOffset;
1447 p->nOffset = 0;
drh832508b2002-03-02 17:04:07 +00001448 rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001449 p->pPrior = pPrior;
drh7b58dae2003-07-20 01:16:46 +00001450 p->nLimit = nLimit;
1451 p->nOffset = nOffset;
drh82c3d632000-06-06 21:56:07 +00001452 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001453
1454 /* Generate code to take the intersection of the two temporary
1455 ** tables.
1456 */
drh82c3d632000-06-06 21:56:07 +00001457 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001458 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001459 generateColumnNames(pParse, 0, p->pEList);
1460 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001461 }
drh82c3d632000-06-06 21:56:07 +00001462 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001463 iCont = sqliteVdbeMakeLabel(v);
1464 sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001465 computeLimitRegisters(pParse, p);
drh6b563442001-11-07 16:48:26 +00001466 iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
drh99fcd712001-10-13 01:06:47 +00001467 sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
drhfcb78a42003-01-18 20:11:05 +00001468 multiSelectSortOrder(p, p->pOrderBy);
drh38640e12002-07-05 21:42:36 +00001469 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001470 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001471 iCont, iBreak);
1472 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001473 sqliteVdbeResolveLabel(v, iCont);
1474 sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
drh99fcd712001-10-13 01:06:47 +00001475 sqliteVdbeResolveLabel(v, iBreak);
1476 sqliteVdbeAddOp(v, OP_Close, tab2, 0);
1477 sqliteVdbeAddOp(v, OP_Close, tab1, 0);
drhd8bc7082000-06-07 23:51:50 +00001478 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001479 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001480 }
drh82c3d632000-06-06 21:56:07 +00001481 break;
1482 }
1483 }
1484 assert( p->pEList && pPrior->pEList );
1485 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
drhda93d232003-03-31 02:12:46 +00001486 sqliteErrorMsg(pParse, "SELECTs to the left and right of %s"
1487 " do not have the same number of result columns", selectOpName(p->op));
drh82c3d632000-06-06 21:56:07 +00001488 return 1;
drh22827922000-06-06 17:27:05 +00001489 }
1490 return 0;
1491}
1492
1493/*
drh832508b2002-03-02 17:04:07 +00001494** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001495** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001496** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001497** unchanged.)
drh832508b2002-03-02 17:04:07 +00001498**
1499** This routine is part of the flattening procedure. A subquery
1500** whose result set is defined by pEList appears as entry in the
1501** FROM clause of a SELECT such that the VDBE cursor assigned to that
1502** FORM clause entry is iTable. This routine make the necessary
1503** changes to pExpr so that it refers directly to the source table
1504** of the subquery rather the result set of the subquery.
1505*/
drh6a3ea0e2003-05-02 14:32:12 +00001506static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1507static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001508 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001509 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1510 if( pExpr->iColumn<0 ){
1511 pExpr->op = TK_NULL;
1512 }else{
1513 Expr *pNew;
1514 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1515 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1516 pNew = pEList->a[pExpr->iColumn].pExpr;
1517 assert( pNew!=0 );
1518 pExpr->op = pNew->op;
1519 pExpr->dataType = pNew->dataType;
1520 assert( pExpr->pLeft==0 );
1521 pExpr->pLeft = sqliteExprDup(pNew->pLeft);
1522 assert( pExpr->pRight==0 );
1523 pExpr->pRight = sqliteExprDup(pNew->pRight);
1524 assert( pExpr->pList==0 );
1525 pExpr->pList = sqliteExprListDup(pNew->pList);
1526 pExpr->iTable = pNew->iTable;
1527 pExpr->iColumn = pNew->iColumn;
1528 pExpr->iAgg = pNew->iAgg;
1529 sqliteTokenCopy(&pExpr->token, &pNew->token);
1530 sqliteTokenCopy(&pExpr->span, &pNew->span);
1531 }
drh832508b2002-03-02 17:04:07 +00001532 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001533 substExpr(pExpr->pLeft, iTable, pEList);
1534 substExpr(pExpr->pRight, iTable, pEList);
1535 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001536 }
1537}
1538static void
drh6a3ea0e2003-05-02 14:32:12 +00001539substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001540 int i;
1541 if( pList==0 ) return;
1542 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001543 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001544 }
1545}
1546
1547/*
drh1350b032002-02-27 19:00:20 +00001548** This routine attempts to flatten subqueries in order to speed
1549** execution. It returns 1 if it makes changes and 0 if no flattening
1550** occurs.
1551**
1552** To understand the concept of flattening, consider the following
1553** query:
1554**
1555** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1556**
1557** The default way of implementing this query is to execute the
1558** subquery first and store the results in a temporary table, then
1559** run the outer query on that temporary table. This requires two
1560** passes over the data. Furthermore, because the temporary table
1561** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001562** optimized.
drh1350b032002-02-27 19:00:20 +00001563**
drh832508b2002-03-02 17:04:07 +00001564** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001565** a single flat select, like this:
1566**
1567** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1568**
1569** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001570** but only has to scan the data once. And because indices might
1571** exist on the table t1, a complete scan of the data might be
1572** avoided.
drh1350b032002-02-27 19:00:20 +00001573**
drh832508b2002-03-02 17:04:07 +00001574** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001575**
drh832508b2002-03-02 17:04:07 +00001576** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001577**
drh832508b2002-03-02 17:04:07 +00001578** (2) The subquery is not an aggregate or the outer query is not a join.
1579**
drh8af4d3a2003-05-06 20:35:16 +00001580** (3) The subquery is not the right operand of a left outer join, or
1581** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001582**
1583** (4) The subquery is not DISTINCT or the outer query is not a join.
1584**
1585** (5) The subquery is not DISTINCT or the outer query does not use
1586** aggregates.
1587**
1588** (6) The subquery does not use aggregates or the outer query is not
1589** DISTINCT.
1590**
drh08192d52002-04-30 19:20:28 +00001591** (7) The subquery has a FROM clause.
1592**
drhdf199a22002-06-14 22:38:41 +00001593** (8) The subquery does not use LIMIT or the outer query is not a join.
1594**
1595** (9) The subquery does not use LIMIT or the outer query does not use
1596** aggregates.
1597**
1598** (10) The subquery does not use aggregates or the outer query does not
1599** use LIMIT.
1600**
drh174b6192002-12-03 02:22:52 +00001601** (11) The subquery and the outer query do not both have ORDER BY clauses.
1602**
drh3fc673e2003-06-16 00:40:34 +00001603** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1604** subquery has no WHERE clause. (added by ticket #350)
1605**
drh832508b2002-03-02 17:04:07 +00001606** In this routine, the "p" parameter is a pointer to the outer query.
1607** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1608** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1609**
drh665de472003-03-31 13:36:09 +00001610** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001611** If flattening is attempted this routine returns 1.
1612**
1613** All of the expression analysis must occur on both the outer query and
1614** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001615*/
drh8c74a8c2002-08-25 19:20:40 +00001616static int flattenSubquery(
1617 Parse *pParse, /* The parsing context */
1618 Select *p, /* The parent or outer SELECT statement */
1619 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1620 int isAgg, /* True if outer SELECT uses aggregate functions */
1621 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1622){
drh0bb28102002-05-08 11:54:14 +00001623 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001624 SrcList *pSrc; /* The FROM clause of the outer query */
1625 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001626 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001627 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh832508b2002-03-02 17:04:07 +00001628 int i;
drh832508b2002-03-02 17:04:07 +00001629 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001630
drh832508b2002-03-02 17:04:07 +00001631 /* Check to see if flattening is permitted. Return 0 if not.
1632 */
1633 if( p==0 ) return 0;
1634 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001635 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001636 pSub = pSrc->a[iFrom].pSelect;
1637 assert( pSub!=0 );
1638 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001639 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001640 pSubSrc = pSub->pSrc;
1641 assert( pSubSrc );
drhc31c2eb2003-05-02 16:04:17 +00001642 if( pSubSrc->nSrc==0 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001643 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1644 return 0;
1645 }
drhd11d3822002-06-21 23:01:49 +00001646 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001647 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001648
drh8af4d3a2003-05-06 20:35:16 +00001649 /* Restriction 3: If the subquery is a join, make sure the subquery is
1650 ** not used as the right operand of an outer join. Examples of why this
1651 ** is not allowed:
1652 **
1653 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1654 **
1655 ** If we flatten the above, we would get
1656 **
1657 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1658 **
1659 ** which is not at all the same thing.
1660 */
1661 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1662 return 0;
1663 }
1664
drh3fc673e2003-06-16 00:40:34 +00001665 /* Restriction 12: If the subquery is the right operand of a left outer
1666 ** join, make sure the subquery has no WHERE clause.
1667 ** An examples of why this is not allowed:
1668 **
1669 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1670 **
1671 ** If we flatten the above, we would get
1672 **
1673 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1674 **
1675 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1676 ** effectively converts the OUTER JOIN into an INNER JOIN.
1677 */
1678 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1679 && pSub->pWhere!=0 ){
1680 return 0;
1681 }
1682
drh0bb28102002-05-08 11:54:14 +00001683 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001684 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001685 */
drhc31c2eb2003-05-02 16:04:17 +00001686
1687 /* Move all of the FROM elements of the subquery into the
1688 ** the FROM clause of the outer query. Before doing this, remember
1689 ** the cursor number for the original outer query FROM element in
1690 ** iParent. The iParent cursor will never be used. Subsequent code
1691 ** will scan expressions looking for iParent references and replace
1692 ** those references with expressions that resolve to the subquery FROM
1693 ** elements we are now copying in.
1694 */
drh6a3ea0e2003-05-02 14:32:12 +00001695 iParent = pSrc->a[iFrom].iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001696 {
1697 int nSubSrc = pSubSrc->nSrc;
drh8af4d3a2003-05-06 20:35:16 +00001698 int jointype = pSrc->a[iFrom].jointype;
drhc31c2eb2003-05-02 16:04:17 +00001699
1700 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1701 sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1702 }
drhf26e09c2003-05-31 16:21:12 +00001703 sqliteFree(pSrc->a[iFrom].zDatabase);
drhc31c2eb2003-05-02 16:04:17 +00001704 sqliteFree(pSrc->a[iFrom].zName);
1705 sqliteFree(pSrc->a[iFrom].zAlias);
1706 if( nSubSrc>1 ){
1707 int extra = nSubSrc - 1;
1708 for(i=1; i<nSubSrc; i++){
1709 pSrc = sqliteSrcListAppend(pSrc, 0, 0);
1710 }
1711 p->pSrc = pSrc;
1712 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1713 pSrc->a[i] = pSrc->a[i-extra];
1714 }
1715 }
1716 for(i=0; i<nSubSrc; i++){
1717 pSrc->a[i+iFrom] = pSubSrc->a[i];
1718 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1719 }
drh8af4d3a2003-05-06 20:35:16 +00001720 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00001721 }
1722
1723 /* Now begin substituting subquery result set expressions for
1724 ** references to the iParent in the outer query.
1725 **
1726 ** Example:
1727 **
1728 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1729 ** \ \_____________ subquery __________/ /
1730 ** \_____________________ outer query ______________________________/
1731 **
1732 ** We look at every expression in the outer query and every place we see
1733 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1734 */
drh6a3ea0e2003-05-02 14:32:12 +00001735 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001736 pList = p->pEList;
1737 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001738 Expr *pExpr;
1739 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1740 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001741 }
1742 }
drh1b2e0322002-03-03 02:49:51 +00001743 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00001744 substExprList(p->pGroupBy, iParent, pSub->pEList);
1745 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001746 }
drh174b6192002-12-03 02:22:52 +00001747 if( pSub->pOrderBy ){
1748 assert( p->pOrderBy==0 );
1749 p->pOrderBy = pSub->pOrderBy;
1750 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00001751 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00001752 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00001753 }
drh832508b2002-03-02 17:04:07 +00001754 if( pSub->pWhere ){
1755 pWhere = sqliteExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00001756 }else{
1757 pWhere = 0;
1758 }
1759 if( subqueryIsAgg ){
1760 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001761 p->pHaving = p->pWhere;
1762 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00001763 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001764 if( pSub->pHaving ){
1765 Expr *pHaving = sqliteExprDup(pSub->pHaving);
drh1b2e0322002-03-03 02:49:51 +00001766 if( p->pHaving ){
1767 p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
1768 }else{
1769 p->pHaving = pHaving;
1770 }
1771 }
1772 assert( p->pGroupBy==0 );
1773 p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00001774 }else if( p->pWhere==0 ){
1775 p->pWhere = pWhere;
1776 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001777 substExpr(p->pWhere, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001778 if( pWhere ){
1779 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1780 }
1781 }
drhc31c2eb2003-05-02 16:04:17 +00001782
1783 /* The flattened query is distinct if either the inner or the
1784 ** outer query is distinct.
1785 */
drh832508b2002-03-02 17:04:07 +00001786 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00001787
drhc31c2eb2003-05-02 16:04:17 +00001788 /* Transfer the limit expression from the subquery to the outer
1789 ** query.
1790 */
drhdf199a22002-06-14 22:38:41 +00001791 if( pSub->nLimit>=0 ){
1792 if( p->nLimit<0 ){
1793 p->nLimit = pSub->nLimit;
1794 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1795 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1796 }
1797 }
1798 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00001799
drhc31c2eb2003-05-02 16:04:17 +00001800 /* Finially, delete what is left of the subquery and return
1801 ** success.
1802 */
drh832508b2002-03-02 17:04:07 +00001803 sqliteSelectDelete(pSub);
1804 return 1;
1805}
drh1350b032002-02-27 19:00:20 +00001806
1807/*
drh9562b552002-02-19 15:00:07 +00001808** Analyze the SELECT statement passed in as an argument to see if it
1809** is a simple min() or max() query. If it is and this query can be
1810** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00001811** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00001812** simple min() or max() query, then return 0;
1813**
1814** A simply min() or max() query looks like this:
1815**
1816** SELECT min(a) FROM table;
1817** SELECT max(a) FROM table;
1818**
1819** The query may have only a single table in its FROM argument. There
1820** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1821** be the min() or max() of a single column of the table. The column
1822** in the min() or max() function must be indexed.
1823**
1824** The parameters to this routine are the same as for sqliteSelect().
1825** See the header comment on that routine for additional information.
1826*/
1827static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1828 Expr *pExpr;
1829 int iCol;
1830 Table *pTab;
1831 Index *pIdx;
1832 int base;
1833 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00001834 int seekOp;
1835 int cont;
1836 ExprList eList;
1837 struct ExprList_item eListItem;
1838
1839 /* Check to see if this query is a simple min() or max() query. Return
1840 ** zero if it is not.
1841 */
1842 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drhad3cab52002-05-24 02:04:32 +00001843 if( p->pSrc->nSrc!=1 ) return 0;
drh9562b552002-02-19 15:00:07 +00001844 if( p->pEList->nExpr!=1 ) return 0;
1845 pExpr = p->pEList->a[0].pExpr;
1846 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
1847 if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00001848 if( pExpr->token.n!=3 ) return 0;
drh0bce8352002-02-28 00:41:10 +00001849 if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
1850 seekOp = OP_Rewind;
1851 }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
1852 seekOp = OP_Last;
1853 }else{
1854 return 0;
1855 }
drh9562b552002-02-19 15:00:07 +00001856 pExpr = pExpr->pList->a[0].pExpr;
1857 if( pExpr->op!=TK_COLUMN ) return 0;
1858 iCol = pExpr->iColumn;
1859 pTab = p->pSrc->a[0].pTab;
1860
1861 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00001862 ** Check to make sure we have an index and make pIdx point to the
1863 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
1864 ** key column, no index is necessary so set pIdx to NULL. If no
1865 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00001866 */
1867 if( iCol<0 ){
1868 pIdx = 0;
1869 }else{
1870 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1871 assert( pIdx->nColumn>=1 );
1872 if( pIdx->aiColumn[0]==iCol ) break;
1873 }
1874 if( pIdx==0 ) return 0;
1875 }
1876
drhe5f50722003-07-19 00:44:14 +00001877 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00001878 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00001879 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00001880 */
1881 v = sqliteGetVdbe(pParse);
1882 if( v==0 ) return 0;
1883 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001884 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh9562b552002-02-19 15:00:07 +00001885 }
1886
drh0c37e632004-01-30 02:01:03 +00001887 /* If the output is destined for a temporary table, open that table.
1888 */
1889 if( eDest==SRT_TempTable ){
1890 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
1891 }
1892
drh17f71932002-02-21 12:01:27 +00001893 /* Generating code to find the min or the max. Basically all we have
1894 ** to do is find the first or the last entry in the chosen index. If
1895 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
1896 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00001897 */
drh8bf8dc92003-05-17 17:35:10 +00001898 sqliteCodeVerifySchema(pParse, pTab->iDb);
drh6a3ea0e2003-05-02 14:32:12 +00001899 base = p->pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00001900 computeLimitRegisters(pParse, p);
drhd24cc422003-03-27 12:51:24 +00001901 sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
drh701a0ae2004-02-22 20:05:00 +00001902 sqliteVdbeOp3(v, OP_OpenRead, base, pTab->tnum, pTab->zName, 0);
drhd4d595f2003-04-17 12:44:23 +00001903 cont = sqliteVdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00001904 if( pIdx==0 ){
1905 sqliteVdbeAddOp(v, seekOp, base, 0);
1906 }else{
drhd24cc422003-03-27 12:51:24 +00001907 sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
drh701a0ae2004-02-22 20:05:00 +00001908 sqliteVdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum, pIdx->zName, P3_STATIC);
drh9562b552002-02-19 15:00:07 +00001909 sqliteVdbeAddOp(v, seekOp, base+1, 0);
1910 sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
1911 sqliteVdbeAddOp(v, OP_Close, base+1, 0);
1912 sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
1913 }
drh5cf8e8c2002-02-19 22:42:05 +00001914 eList.nExpr = 1;
1915 memset(&eListItem, 0, sizeof(eListItem));
1916 eList.a = &eListItem;
1917 eList.a[0].pExpr = pExpr;
drh38640e12002-07-05 21:42:36 +00001918 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
drh9562b552002-02-19 15:00:07 +00001919 sqliteVdbeResolveLabel(v, cont);
1920 sqliteVdbeAddOp(v, OP_Close, base, 0);
1921 return 1;
1922}
1923
1924/*
drh9bb61fe2000-06-05 16:01:39 +00001925** Generate code for the given SELECT statement.
1926**
drhfef52082000-06-06 01:50:43 +00001927** The results are distributed in various ways depending on the
1928** value of eDest and iParm.
1929**
1930** eDest Value Result
1931** ------------ -------------------------------------------
1932** SRT_Callback Invoke the callback for each row of the result.
1933**
1934** SRT_Mem Store first result in memory cell iParm
1935**
1936** SRT_Set Store results as keys of a table with cursor iParm
1937**
drh82c3d632000-06-06 21:56:07 +00001938** SRT_Union Store results as a key in a temporary table iParm
1939**
jplyon4b11c6d2004-01-19 04:57:53 +00001940** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00001941**
1942** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00001943**
drhe78e8282003-01-19 03:59:45 +00001944** The table above is incomplete. Additional eDist value have be added
1945** since this comment was written. See the selectInnerLoop() function for
1946** a complete listing of the allowed values of eDest and their meanings.
1947**
drh9bb61fe2000-06-05 16:01:39 +00001948** This routine returns the number of errors. If any errors are
1949** encountered, then an appropriate error message is left in
1950** pParse->zErrMsg.
1951**
1952** This routine does NOT free the Select structure passed in. The
1953** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00001954**
1955** The pParent, parentTab, and *pParentAgg fields are filled in if this
1956** SELECT is a subquery. This routine may try to combine this SELECT
1957** with its parent to form a single flat query. In so doing, it might
1958** change the parent query from a non-aggregate to an aggregate query.
1959** For that reason, the pParentAgg flag is passed as a pointer, so it
1960** can be changed.
drhe78e8282003-01-19 03:59:45 +00001961**
1962** Example 1: The meaning of the pParent parameter.
1963**
1964** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
1965** \ \_______ subquery _______/ /
1966** \ /
1967** \____________________ outer query ___________________/
1968**
1969** This routine is called for the outer query first. For that call,
1970** pParent will be NULL. During the processing of the outer query, this
1971** routine is called recursively to handle the subquery. For the recursive
1972** call, pParent will point to the outer query. Because the subquery is
1973** the second element in a three-way join, the parentTab parameter will
1974** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00001975*/
1976int sqliteSelect(
drhcce7d172000-05-31 15:34:51 +00001977 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00001978 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00001979 int eDest, /* How to dispose of the results */
1980 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00001981 Select *pParent, /* Another SELECT for which this is a sub-query */
1982 int parentTab, /* Index in pParent->pSrc of this query */
drh1b2e0322002-03-03 02:49:51 +00001983 int *pParentAgg /* True if pParent uses aggregate functions */
drhcce7d172000-05-31 15:34:51 +00001984){
drhd8bc7082000-06-07 23:51:50 +00001985 int i;
drhcce7d172000-05-31 15:34:51 +00001986 WhereInfo *pWInfo;
1987 Vdbe *v;
1988 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00001989 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00001990 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00001991 Expr *pWhere; /* The WHERE clause. May be NULL */
1992 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00001993 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
1994 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00001995 int isDistinct; /* True if the DISTINCT keyword is present */
1996 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00001997 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00001998
drhdaffd0e2001-04-11 14:28:42 +00001999 if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
drhe22a3342003-04-22 20:30:37 +00002000 if( sqliteAuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002001
drh82c3d632000-06-06 21:56:07 +00002002 /* If there is are a sequence of queries, do the earlier ones first.
2003 */
2004 if( p->pPrior ){
2005 return multiSelect(pParse, p, eDest, iParm);
2006 }
2007
2008 /* Make local copies of the parameters for this query.
2009 */
drh9bb61fe2000-06-05 16:01:39 +00002010 pTabList = p->pSrc;
2011 pWhere = p->pWhere;
2012 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00002013 pGroupBy = p->pGroupBy;
2014 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00002015 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00002016
drh6a3ea0e2003-05-02 14:32:12 +00002017 /* Allocate VDBE cursors for each table in the FROM clause
drh10e5e3c2000-06-08 00:19:02 +00002018 */
drh6a3ea0e2003-05-02 14:32:12 +00002019 sqliteSrcListAssignCursors(pParse, pTabList);
drh10e5e3c2000-06-08 00:19:02 +00002020
drh9bb61fe2000-06-05 16:01:39 +00002021 /*
2022 ** Do not even attempt to generate any code if we have already seen
2023 ** errors before this routine starts.
2024 */
drh1d83f052002-02-17 00:30:36 +00002025 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002026
drhe78e8282003-01-19 03:59:45 +00002027 /* Expand any "*" terms in the result set. (For example the "*" in
2028 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
2029 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00002030 */
drhd8bc7082000-06-07 23:51:50 +00002031 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00002032 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002033 }
drhad2d8302002-05-24 20:31:36 +00002034 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00002035 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00002036 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002037
drh22827922000-06-06 17:27:05 +00002038 /* If writing to memory or generating a set
2039 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002040 */
drhfef52082000-06-06 01:50:43 +00002041 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
drhda93d232003-03-31 02:12:46 +00002042 sqliteErrorMsg(pParse, "only a single result allowed for "
2043 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002044 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002045 }
2046
drhc926afb2002-06-20 03:38:26 +00002047 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002048 */
drhc926afb2002-06-20 03:38:26 +00002049 switch( eDest ){
2050 case SRT_Union:
2051 case SRT_Except:
2052 case SRT_Discard:
2053 pOrderBy = 0;
2054 break;
2055 default:
2056 break;
drh22827922000-06-06 17:27:05 +00002057 }
2058
drh10e5e3c2000-06-08 00:19:02 +00002059 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002060 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002061 **
drh967e8b72000-06-21 13:59:10 +00002062 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002063 */
drh4794b982000-06-06 13:54:14 +00002064 for(i=0; i<pEList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00002065 if( sqliteExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002066 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002067 }
drh22827922000-06-06 17:27:05 +00002068 if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002069 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002070 }
2071 }
drhcce7d172000-05-31 15:34:51 +00002072 if( pWhere ){
drh6a3ea0e2003-05-02 14:32:12 +00002073 if( sqliteExprResolveIds(pParse, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00002074 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002075 }
2076 if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00002077 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002078 }
2079 }
drhc66c5a22002-12-03 02:34:49 +00002080 if( pHaving ){
2081 if( pGroupBy==0 ){
drhda93d232003-03-31 02:12:46 +00002082 sqliteErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
drhc66c5a22002-12-03 02:34:49 +00002083 goto select_end;
2084 }
drh6a3ea0e2003-05-02 14:32:12 +00002085 if( sqliteExprResolveIds(pParse, pTabList, pEList, pHaving) ){
drhc66c5a22002-12-03 02:34:49 +00002086 goto select_end;
2087 }
2088 if( sqliteExprCheck(pParse, pHaving, 1, &isAgg) ){
2089 goto select_end;
2090 }
2091 }
drhcce7d172000-05-31 15:34:51 +00002092 if( pOrderBy ){
2093 for(i=0; i<pOrderBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002094 int iCol;
drh22827922000-06-06 17:27:05 +00002095 Expr *pE = pOrderBy->a[i].pExpr;
drh88eee382003-01-31 17:16:36 +00002096 if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2097 sqliteExprDelete(pE);
2098 pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
2099 }
drh6a3ea0e2003-05-02 14:32:12 +00002100 if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
drh88eee382003-01-31 17:16:36 +00002101 goto select_end;
2102 }
2103 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
2104 goto select_end;
2105 }
drh92086432002-01-22 14:11:29 +00002106 if( sqliteExprIsConstant(pE) ){
drhe4de1fe2002-06-02 16:09:01 +00002107 if( sqliteExprIsInteger(pE, &iCol)==0 ){
drhda93d232003-03-31 02:12:46 +00002108 sqliteErrorMsg(pParse,
2109 "ORDER BY terms must not be non-integer constants");
drhe4de1fe2002-06-02 16:09:01 +00002110 goto select_end;
2111 }else if( iCol<=0 || iCol>pEList->nExpr ){
drhda93d232003-03-31 02:12:46 +00002112 sqliteErrorMsg(pParse,
2113 "ORDER BY column number %d out of range - should be "
drhe4de1fe2002-06-02 16:09:01 +00002114 "between 1 and %d", iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00002115 goto select_end;
2116 }
drhcce7d172000-05-31 15:34:51 +00002117 }
2118 }
2119 }
drh22827922000-06-06 17:27:05 +00002120 if( pGroupBy ){
2121 for(i=0; i<pGroupBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002122 int iCol;
drh22827922000-06-06 17:27:05 +00002123 Expr *pE = pGroupBy->a[i].pExpr;
drh88eee382003-01-31 17:16:36 +00002124 if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2125 sqliteExprDelete(pE);
2126 pE = pGroupBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00002127 }
drh6a3ea0e2003-05-02 14:32:12 +00002128 if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00002129 goto select_end;
drh22827922000-06-06 17:27:05 +00002130 }
2131 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00002132 goto select_end;
drh22827922000-06-06 17:27:05 +00002133 }
drh88eee382003-01-31 17:16:36 +00002134 if( sqliteExprIsConstant(pE) ){
2135 if( sqliteExprIsInteger(pE, &iCol)==0 ){
drhda93d232003-03-31 02:12:46 +00002136 sqliteErrorMsg(pParse,
2137 "GROUP BY terms must not be non-integer constants");
drh88eee382003-01-31 17:16:36 +00002138 goto select_end;
2139 }else if( iCol<=0 || iCol>pEList->nExpr ){
drhda93d232003-03-31 02:12:46 +00002140 sqliteErrorMsg(pParse,
2141 "GROUP BY column number %d out of range - should be "
drh88eee382003-01-31 17:16:36 +00002142 "between 1 and %d", iCol, pEList->nExpr);
drh88eee382003-01-31 17:16:36 +00002143 goto select_end;
2144 }
2145 }
drh22827922000-06-06 17:27:05 +00002146 }
2147 }
drhcce7d172000-05-31 15:34:51 +00002148
drhd820cb12002-02-18 03:21:45 +00002149 /* Begin generating code.
2150 */
2151 v = sqliteGetVdbe(pParse);
2152 if( v==0 ) goto select_end;
2153
drhe78e8282003-01-19 03:59:45 +00002154 /* Identify column names if we will be using them in a callback. This
2155 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002156 */
2157 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002158 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002159 }
2160
drhe5f50722003-07-19 00:44:14 +00002161 /* Check for the special case of a min() or max() function by itself
2162 ** in the result set.
2163 */
2164 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2165 rc = 0;
2166 goto select_end;
2167 }
2168
drhd820cb12002-02-18 03:21:45 +00002169 /* Generate code for all sub-queries in the FROM clause
2170 */
drhad3cab52002-05-24 02:04:32 +00002171 for(i=0; i<pTabList->nSrc; i++){
drh5cf590c2003-04-24 01:45:04 +00002172 const char *zSavedAuthContext;
drhc31c2eb2003-05-02 16:04:17 +00002173 int needRestoreContext;
2174
drha76b5df2002-02-23 02:32:10 +00002175 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002176 if( pTabList->a[i].zName!=0 ){
2177 zSavedAuthContext = pParse->zAuthContext;
2178 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002179 needRestoreContext = 1;
2180 }else{
2181 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002182 }
drh6a3ea0e2003-05-02 14:32:12 +00002183 sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable,
2184 pTabList->a[i].iCursor, p, i, &isAgg);
drhc31c2eb2003-05-02 16:04:17 +00002185 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002186 pParse->zAuthContext = zSavedAuthContext;
2187 }
drh1b2e0322002-03-03 02:49:51 +00002188 pTabList = p->pSrc;
2189 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002190 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002191 pOrderBy = p->pOrderBy;
2192 }
drh1b2e0322002-03-03 02:49:51 +00002193 pGroupBy = p->pGroupBy;
2194 pHaving = p->pHaving;
2195 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002196 }
2197
drh832508b2002-03-02 17:04:07 +00002198 /* Check to see if this is a subquery that can be "flattened" into its parent.
2199 ** If flattening is a possiblity, do so and return immediately.
2200 */
drh1b2e0322002-03-03 02:49:51 +00002201 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002202 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002203 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002204 return rc;
2205 }
drh832508b2002-03-02 17:04:07 +00002206
drh7b58dae2003-07-20 01:16:46 +00002207 /* Set the limiter.
2208 */
2209 computeLimitRegisters(pParse, p);
2210
drhe78e8282003-01-19 03:59:45 +00002211 /* Identify column types if we will be using a callback. This
2212 ** step is skipped if the output is going to a destination other
2213 ** than a callback.
drhe5f50722003-07-19 00:44:14 +00002214 **
2215 ** We have to do this separately from the creation of column names
2216 ** above because if the pTabList contains views then they will not
2217 ** have been resolved and we will not know the column types until
2218 ** now.
drhfcb78a42003-01-18 20:11:05 +00002219 */
2220 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002221 generateColumnTypes(pParse, pTabList, pEList);
drhfcb78a42003-01-18 20:11:05 +00002222 }
2223
drh2d0794e2002-03-03 03:03:52 +00002224 /* If the output is destined for a temporary table, open that table.
2225 */
2226 if( eDest==SRT_TempTable ){
2227 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
2228 }
2229
drh22827922000-06-06 17:27:05 +00002230 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002231 */
drhd820cb12002-02-18 03:21:45 +00002232 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002233 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002234 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002235 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002236 for(i=0; i<pEList->nExpr; i++){
2237 if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002238 goto select_end;
drh22827922000-06-06 17:27:05 +00002239 }
2240 }
2241 if( pGroupBy ){
2242 for(i=0; i<pGroupBy->nExpr; i++){
2243 if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002244 goto select_end;
drh22827922000-06-06 17:27:05 +00002245 }
2246 }
2247 }
2248 if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002249 goto select_end;
drh22827922000-06-06 17:27:05 +00002250 }
drh191b6902000-06-08 11:13:01 +00002251 if( pOrderBy ){
2252 for(i=0; i<pOrderBy->nExpr; i++){
2253 if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002254 goto select_end;
drh191b6902000-06-08 11:13:01 +00002255 }
2256 }
2257 }
drhefb72512000-05-31 20:00:52 +00002258 }
2259
drh22827922000-06-06 17:27:05 +00002260 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002261 */
2262 if( isAgg ){
drh99fcd712001-10-13 01:06:47 +00002263 sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002264 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002265 FuncDef *pFunc;
2266 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drh701a0ae2004-02-22 20:05:00 +00002267 sqliteVdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_POINTER);
drhe5095352002-02-24 03:25:14 +00002268 }
2269 }
drh1bee3d72001-10-15 00:44:35 +00002270 if( pGroupBy==0 ){
2271 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002272 sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002273 }
drhcce7d172000-05-31 15:34:51 +00002274 }
2275
drh19a775c2000-06-05 18:54:46 +00002276 /* Initialize the memory cell to NULL
2277 */
drhfef52082000-06-06 01:50:43 +00002278 if( eDest==SRT_Mem ){
drh99fcd712001-10-13 01:06:47 +00002279 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh8721ce42001-11-07 14:22:00 +00002280 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002281 }
2282
drh832508b2002-03-02 17:04:07 +00002283 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002284 */
drh19a775c2000-06-05 18:54:46 +00002285 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002286 distinct = pParse->nTab++;
drhc6b52df2002-01-04 03:09:29 +00002287 sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
drh832508b2002-03-02 17:04:07 +00002288 }else{
2289 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002290 }
drh832508b2002-03-02 17:04:07 +00002291
2292 /* Begin the database scan
2293 */
drh6a3ea0e2003-05-02 14:32:12 +00002294 pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 0,
drh68d2e592002-08-04 00:52:38 +00002295 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002296 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002297
drh22827922000-06-06 17:27:05 +00002298 /* Use the standard inner loop if we are not dealing with
2299 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002300 */
drhda9d6c42000-05-31 18:20:14 +00002301 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002302 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2303 iParm, pWInfo->iContinue, pWInfo->iBreak) ){
drh1d83f052002-02-17 00:30:36 +00002304 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002305 }
drhcce7d172000-05-31 15:34:51 +00002306 }
drhefb72512000-05-31 20:00:52 +00002307
drhe3184742002-06-19 14:27:05 +00002308 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002309 ** processing.
drhefb72512000-05-31 20:00:52 +00002310 */
drh22827922000-06-06 17:27:05 +00002311 else{
drh268380c2004-02-25 13:47:31 +00002312 AggExpr *pAgg;
drh22827922000-06-06 17:27:05 +00002313 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002314 int lbl1;
drh22827922000-06-06 17:27:05 +00002315 for(i=0; i<pGroupBy->nExpr; i++){
2316 sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
2317 }
drh99fcd712001-10-13 01:06:47 +00002318 sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
drh491791a2002-07-18 00:34:09 +00002319 if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pGroupBy);
drh1bee3d72001-10-15 00:44:35 +00002320 lbl1 = sqliteVdbeMakeLabel(v);
drh99fcd712001-10-13 01:06:47 +00002321 sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh268380c2004-02-25 13:47:31 +00002322 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2323 if( pAgg->isAgg ) continue;
2324 sqliteExprCode(pParse, pAgg->pExpr);
drh99fcd712001-10-13 01:06:47 +00002325 sqliteVdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002326 }
drh22827922000-06-06 17:27:05 +00002327 sqliteVdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002328 }
drh268380c2004-02-25 13:47:31 +00002329 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002330 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002331 int nExpr;
2332 FuncDef *pDef;
2333 if( !pAgg->isAgg ) continue;
2334 assert( pAgg->pFunc!=0 );
2335 assert( pAgg->pFunc->xStep!=0 );
2336 pDef = pAgg->pFunc;
2337 pE = pAgg->pExpr;
2338 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002339 assert( pE->op==TK_AGG_FUNCTION );
drh268380c2004-02-25 13:47:31 +00002340 nExpr = sqliteExprCodeExprList(pParse, pE->pList, pDef->includeTypes);
drh0bce8352002-02-28 00:41:10 +00002341 sqliteVdbeAddOp(v, OP_Integer, i, 0);
drh268380c2004-02-25 13:47:31 +00002342 sqliteVdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002343 }
drhcce7d172000-05-31 15:34:51 +00002344 }
2345
2346 /* End the database scan loop.
2347 */
2348 sqliteWhereEnd(pWInfo);
2349
drh22827922000-06-06 17:27:05 +00002350 /* If we are processing aggregates, we need to set up a second loop
2351 ** over all of the aggregate values and process them.
2352 */
2353 if( isAgg ){
2354 int endagg = sqliteVdbeMakeLabel(v);
2355 int startagg;
drh99fcd712001-10-13 01:06:47 +00002356 startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002357 pParse->useAgg = 1;
2358 if( pHaving ){
drhf5905aa2002-05-26 20:54:33 +00002359 sqliteExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002360 }
drhdf199a22002-06-14 22:38:41 +00002361 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2362 iParm, startagg, endagg) ){
drh1d83f052002-02-17 00:30:36 +00002363 goto select_end;
drh22827922000-06-06 17:27:05 +00002364 }
drh99fcd712001-10-13 01:06:47 +00002365 sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
2366 sqliteVdbeResolveLabel(v, endagg);
2367 sqliteVdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002368 pParse->useAgg = 0;
2369 }
2370
drhcce7d172000-05-31 15:34:51 +00002371 /* If there is an ORDER BY clause, then we need to sort the results
2372 ** and send them to the callback one by one.
2373 */
2374 if( pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00002375 generateSortTail(p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002376 }
drh6a535342001-10-19 16:44:56 +00002377
drhf620b4e2004-02-09 14:37:50 +00002378 /* If this was a subquery, we have now converted the subquery into a
2379 ** temporary table. So delete the subquery structure from the parent
2380 ** to prevent this subquery from being evaluated again and to force the
2381 ** the use of the temporary table.
2382 */
2383 if( pParent ){
2384 assert( pParent->pSrc->nSrc>parentTab );
2385 assert( pParent->pSrc->a[parentTab].pSelect==p );
2386 sqliteSelectDelete(p);
2387 pParent->pSrc->a[parentTab].pSelect = 0;
2388 }
2389
drh1d83f052002-02-17 00:30:36 +00002390 /* The SELECT was successfully coded. Set the return code to 0
2391 ** to indicate no errors.
2392 */
2393 rc = 0;
2394
2395 /* Control jumps to here if an error is encountered above, or upon
2396 ** successful coding of the SELECT.
2397 */
2398select_end:
2399 sqliteAggregateInfoReset(pParse);
2400 return rc;
drhcce7d172000-05-31 15:34:51 +00002401}