blob: 149eecae12a86a7287b3f4f4d2ccf84241a0cc48 [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**
drhfcabd462004-02-20 14:50:58 +000015** $Id: select.c,v 1.157 2004/02/20 14:50:58 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;
341 sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0);
342 sqliteVdbeChangeP3(v, -1, zSortOrder, strlen(zSortOrder));
343 sqliteFree(zSortOrder);
344 sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
345}
346
347/*
drh38640e12002-07-05 21:42:36 +0000348** This routine adds a P3 argument to the last VDBE opcode that was
349** inserted. The P3 argument added is a string suitable for the
350** OP_MakeKey or OP_MakeIdxKey opcodes. The string consists of
351** characters 't' or 'n' depending on whether or not the various
352** fields of the key to be generated should be treated as numeric
353** or as text. See the OP_MakeKey and OP_MakeIdxKey opcode
354** documentation for additional information about the P3 string.
355** See also the sqliteAddIdxKeyType() routine.
356*/
357void sqliteAddKeyType(Vdbe *v, ExprList *pEList){
358 int nColumn = pEList->nExpr;
359 char *zType = sqliteMalloc( nColumn+1 );
360 int i;
361 if( zType==0 ) return;
362 for(i=0; i<nColumn; i++){
363 zType[i] = sqliteExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
364 }
365 zType[i] = 0;
366 sqliteVdbeChangeP3(v, -1, zType, nColumn);
367 sqliteFree(zType);
368}
369
370/*
drh22827922000-06-06 17:27:05 +0000371** This routine generates the code for the inside of the inner loop
372** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000373**
drh38640e12002-07-05 21:42:36 +0000374** If srcTab and nColumn are both zero, then the pEList expressions
375** are evaluated in order to get the data for this row. If nColumn>0
376** then data is pulled from srcTab and pEList is used only to get the
377** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000378*/
379static int selectInnerLoop(
380 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000381 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000382 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000383 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000384 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000385 ExprList *pOrderBy, /* If not NULL, sort results using this key */
386 int distinct, /* If >=0, make sure results are distinct */
387 int eDest, /* How to dispose of the results */
388 int iParm, /* An argument to the disposal method */
389 int iContinue, /* Jump here to continue with next row */
390 int iBreak /* Jump here to break out of the inner loop */
391){
392 Vdbe *v = pParse->pVdbe;
393 int i;
drh38640e12002-07-05 21:42:36 +0000394
drhdaffd0e2001-04-11 14:28:42 +0000395 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000396 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000397
drhdf199a22002-06-14 22:38:41 +0000398 /* If there was a LIMIT clause on the SELECT statement, then do the check
399 ** to see if this row should be output.
400 */
401 if( pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +0000402 if( p->iOffset>=0 ){
drhd11d3822002-06-21 23:01:49 +0000403 int addr = sqliteVdbeCurrentAddr(v);
drh7b58dae2003-07-20 01:16:46 +0000404 sqliteVdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2);
drhd11d3822002-06-21 23:01:49 +0000405 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
drhdf199a22002-06-14 22:38:41 +0000406 }
drh7b58dae2003-07-20 01:16:46 +0000407 if( p->iLimit>=0 ){
408 sqliteVdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhdf199a22002-06-14 22:38:41 +0000409 }
410 }
411
drh967e8b72000-06-21 13:59:10 +0000412 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000413 */
drh38640e12002-07-05 21:42:36 +0000414 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000415 for(i=0; i<nColumn; i++){
drh99fcd712001-10-13 01:06:47 +0000416 sqliteVdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000417 }
drh38640e12002-07-05 21:42:36 +0000418 }else{
419 nColumn = pEList->nExpr;
420 for(i=0; i<pEList->nExpr; i++){
421 sqliteExprCode(pParse, pEList->a[i].pExpr);
422 }
drh22827922000-06-06 17:27:05 +0000423 }
424
drhdaffd0e2001-04-11 14:28:42 +0000425 /* If the DISTINCT keyword was present on the SELECT statement
426 ** and this row has been seen before, then do not make this row
427 ** part of the result.
drh22827922000-06-06 17:27:05 +0000428 */
drhf5905aa2002-05-26 20:54:33 +0000429 if( distinct>=0 && pEList && pEList->nExpr>0 ){
drh0bd1f4e2002-06-06 18:54:39 +0000430#if NULL_ALWAYS_DISTINCT
431 sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7);
432#endif
drh99fcd712001-10-13 01:06:47 +0000433 sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
drh491791a2002-07-18 00:34:09 +0000434 if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pEList);
drhf5905aa2002-05-26 20:54:33 +0000435 sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
drh99fcd712001-10-13 01:06:47 +0000436 sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
437 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
drh99fcd712001-10-13 01:06:47 +0000438 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh6b125452002-01-28 15:53:03 +0000439 sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
drh22827922000-06-06 17:27:05 +0000440 }
drh82c3d632000-06-06 21:56:07 +0000441
drhc926afb2002-06-20 03:38:26 +0000442 switch( eDest ){
443 /* In this mode, write each query result to the key of the temporary
444 ** table iParm.
445 */
446 case SRT_Union: {
447 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
448 sqliteVdbeAddOp(v, OP_String, 0, 0);
449 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
450 break;
drh22827922000-06-06 17:27:05 +0000451 }
drh22827922000-06-06 17:27:05 +0000452
drhc926afb2002-06-20 03:38:26 +0000453 /* Store the result as data using a unique key.
454 */
455 case SRT_Table:
456 case SRT_TempTable: {
457 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
458 if( pOrderBy ){
459 pushOntoSorter(pParse, v, pOrderBy);
460 }else{
461 sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
462 sqliteVdbeAddOp(v, OP_Pull, 1, 0);
463 sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
464 }
465 break;
466 }
drh82c3d632000-06-06 21:56:07 +0000467
drhc926afb2002-06-20 03:38:26 +0000468 /* Construct a record from the query result, but instead of
469 ** saving that record, use it as a key to delete elements from
470 ** the temporary table iParm.
471 */
472 case SRT_Except: {
473 int addr;
474 addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
475 sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
476 sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
477 break;
478 }
drh5974a302000-06-07 14:42:26 +0000479
drhc926afb2002-06-20 03:38:26 +0000480 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
481 ** then there should be a single item on the stack. Write this
482 ** item into the set table with bogus data.
483 */
484 case SRT_Set: {
drh52b36ca2004-01-14 13:38:54 +0000485 int addr1 = sqliteVdbeCurrentAddr(v);
486 int addr2;
drhc926afb2002-06-20 03:38:26 +0000487 assert( nColumn==1 );
drh52b36ca2004-01-14 13:38:54 +0000488 sqliteVdbeAddOp(v, OP_NotNull, -1, addr1+3);
489 sqliteVdbeAddOp(v, OP_Pop, 1, 0);
490 addr2 = sqliteVdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000491 if( pOrderBy ){
492 pushOntoSorter(pParse, v, pOrderBy);
493 }else{
drha9f9d1c2002-06-29 02:20:08 +0000494 sqliteVdbeAddOp(v, OP_String, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000495 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
496 }
drh52b36ca2004-01-14 13:38:54 +0000497 sqliteVdbeChangeP2(v, addr2, sqliteVdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000498 break;
499 }
drh22827922000-06-06 17:27:05 +0000500
drhc926afb2002-06-20 03:38:26 +0000501 /* If this is a scalar select that is part of an expression, then
502 ** store the results in the appropriate memory cell and break out
503 ** of the scan loop.
504 */
505 case SRT_Mem: {
506 assert( nColumn==1 );
507 if( pOrderBy ){
508 pushOntoSorter(pParse, v, pOrderBy);
509 }else{
510 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
511 sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
512 }
513 break;
514 }
drh22827922000-06-06 17:27:05 +0000515
drhf46f9052002-06-22 02:33:38 +0000516 /* Send the data to the callback function.
517 */
518 case SRT_Callback:
519 case SRT_Sorter: {
520 if( pOrderBy ){
521 sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
522 pushOntoSorter(pParse, v, pOrderBy);
523 }else{
524 assert( eDest==SRT_Callback );
525 sqliteVdbeAddOp(v, OP_Callback, nColumn, 0);
526 }
527 break;
528 }
529
drh142e30d2002-08-28 03:00:58 +0000530 /* Invoke a subroutine to handle the results. The subroutine itself
531 ** is responsible for popping the results off of the stack.
532 */
533 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000534 if( pOrderBy ){
535 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
536 pushOntoSorter(pParse, v, pOrderBy);
537 }else{
538 sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
539 }
drh142e30d2002-08-28 03:00:58 +0000540 break;
541 }
542
drhc926afb2002-06-20 03:38:26 +0000543 /* Discard the results. This is used for SELECT statements inside
544 ** the body of a TRIGGER. The purpose of such selects is to call
545 ** user-defined functions that have side effects. We do not care
546 ** about the actual results of the select.
547 */
drhc926afb2002-06-20 03:38:26 +0000548 default: {
drhf46f9052002-06-22 02:33:38 +0000549 assert( eDest==SRT_Discard );
550 sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000551 break;
552 }
drh82c3d632000-06-06 21:56:07 +0000553 }
554 return 0;
555}
556
557/*
drhd8bc7082000-06-07 23:51:50 +0000558** If the inner loop was generated using a non-null pOrderBy argument,
559** then the results were placed in a sorter. After the loop is terminated
560** we need to run the sorter and output the results. The following
561** routine generates the code needed to do that.
562*/
drhc926afb2002-06-20 03:38:26 +0000563static void generateSortTail(
564 Select *p, /* The SELECT statement */
565 Vdbe *v, /* Generate code into this VDBE */
566 int nColumn, /* Number of columns of data */
567 int eDest, /* Write the sorted results here */
568 int iParm /* Optional parameter associated with eDest */
569){
drhd8bc7082000-06-07 23:51:50 +0000570 int end = sqliteVdbeMakeLabel(v);
571 int addr;
drhf46f9052002-06-22 02:33:38 +0000572 if( eDest==SRT_Sorter ) return;
drh99fcd712001-10-13 01:06:47 +0000573 sqliteVdbeAddOp(v, OP_Sort, 0, 0);
574 addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end);
drh7b58dae2003-07-20 01:16:46 +0000575 if( p->iOffset>=0 ){
576 sqliteVdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4);
drhd11d3822002-06-21 23:01:49 +0000577 sqliteVdbeAddOp(v, OP_Pop, 1, 0);
578 sqliteVdbeAddOp(v, OP_Goto, 0, addr);
drhdf199a22002-06-14 22:38:41 +0000579 }
drh7b58dae2003-07-20 01:16:46 +0000580 if( p->iLimit>=0 ){
581 sqliteVdbeAddOp(v, OP_MemIncr, p->iLimit, end);
drhdf199a22002-06-14 22:38:41 +0000582 }
drhc926afb2002-06-20 03:38:26 +0000583 switch( eDest ){
584 case SRT_Callback: {
585 sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0);
586 break;
587 }
588 case SRT_Table:
589 case SRT_TempTable: {
590 sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
591 sqliteVdbeAddOp(v, OP_Pull, 1, 0);
592 sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
593 break;
594 }
595 case SRT_Set: {
596 assert( nColumn==1 );
drh52b36ca2004-01-14 13:38:54 +0000597 sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
598 sqliteVdbeAddOp(v, OP_Pop, 1, 0);
599 sqliteVdbeAddOp(v, OP_Goto, 0, sqliteVdbeCurrentAddr(v)+3);
drhc926afb2002-06-20 03:38:26 +0000600 sqliteVdbeAddOp(v, OP_String, 0, 0);
601 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
602 break;
603 }
604 case SRT_Mem: {
605 assert( nColumn==1 );
606 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
607 sqliteVdbeAddOp(v, OP_Goto, 0, end);
608 break;
609 }
drhac82fcf2002-09-08 17:23:41 +0000610 case SRT_Subroutine: {
611 int i;
612 for(i=0; i<nColumn; i++){
613 sqliteVdbeAddOp(v, OP_Column, -1-i, i);
614 }
615 sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
616 sqliteVdbeAddOp(v, OP_Pop, 1, 0);
617 break;
618 }
drhc926afb2002-06-20 03:38:26 +0000619 default: {
drhf46f9052002-06-22 02:33:38 +0000620 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000621 break;
622 }
623 }
drh99fcd712001-10-13 01:06:47 +0000624 sqliteVdbeAddOp(v, OP_Goto, 0, addr);
625 sqliteVdbeResolveLabel(v, end);
drha8b38d22001-11-01 14:41:34 +0000626 sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000627}
628
629/*
drhfcb78a42003-01-18 20:11:05 +0000630** Generate code that will tell the VDBE the datatypes of
631** columns in the result set.
drhe78e8282003-01-19 03:59:45 +0000632**
633** This routine only generates code if the "PRAGMA show_datatypes=on"
634** has been executed. The datatypes are reported out in the azCol
635** parameter to the callback function. The first N azCol[] entries
636** are the names of the columns, and the second N entries are the
637** datatypes for the columns.
638**
639** The "datatype" for a result that is a column of a type is the
640** datatype definition extracted from the CREATE TABLE statement.
641** The datatype for an expression is either TEXT or NUMERIC. The
642** datatype for a ROWID field is INTEGER.
drhfcb78a42003-01-18 20:11:05 +0000643*/
644static void generateColumnTypes(
645 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000646 SrcList *pTabList, /* List of tables */
647 ExprList *pEList /* Expressions defining the result set */
648){
649 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000650 int i, j;
drhfcb78a42003-01-18 20:11:05 +0000651 for(i=0; i<pEList->nExpr; i++){
652 Expr *p = pEList->a[i].pExpr;
653 char *zType = 0;
654 if( p==0 ) continue;
655 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000656 Table *pTab;
drhfcb78a42003-01-18 20:11:05 +0000657 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000658 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
659 assert( j<pTabList->nSrc );
660 pTab = pTabList->a[j].pTab;
drhfcb78a42003-01-18 20:11:05 +0000661 if( iCol<0 ) iCol = pTab->iPKey;
662 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
663 if( iCol<0 ){
664 zType = "INTEGER";
665 }else{
666 zType = pTab->aCol[iCol].zType;
667 }
668 }else{
669 if( sqliteExprType(p)==SQLITE_SO_TEXT ){
670 zType = "TEXT";
671 }else{
672 zType = "NUMERIC";
673 }
674 }
675 sqliteVdbeAddOp(v, OP_ColumnName, i + pEList->nExpr, 0);
drh8ef83ff2004-02-12 15:31:21 +0000676 sqliteVdbeChangeP3(v, -1, zType, 0);
drhfcb78a42003-01-18 20:11:05 +0000677 }
678}
679
680/*
681** Generate code that will tell the VDBE the names of columns
682** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000683** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000684*/
drh832508b2002-03-02 17:04:07 +0000685static void generateColumnNames(
686 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000687 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000688 ExprList *pEList /* Expressions defining the result set */
689){
drhd8bc7082000-06-07 23:51:50 +0000690 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000691 int i, j;
drhfcabd462004-02-20 14:50:58 +0000692 sqlite *db = pParse->db;
693 int fullNames, shortNames;
694
drhd6502752004-02-16 03:44:01 +0000695 assert( v!=0 );
drhdaffd0e2001-04-11 14:28:42 +0000696 if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000697 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000698 fullNames = (db->flags & SQLITE_FullColNames)!=0;
699 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
drh82c3d632000-06-06 21:56:07 +0000700 for(i=0; i<pEList->nExpr; i++){
701 Expr *p;
drhd6502752004-02-16 03:44:01 +0000702 int p2 = i==pEList->nExpr-1;
drh5a387052003-01-11 14:19:51 +0000703 p = pEList->a[i].pExpr;
704 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000705 if( pEList->a[i].zName ){
706 char *zName = pEList->a[i].zName;
drhd6502752004-02-16 03:44:01 +0000707 sqliteVdbeAddOp(v, OP_ColumnName, i, p2);
drh99fcd712001-10-13 01:06:47 +0000708 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000709 continue;
710 }
drhfa173a72002-07-10 21:26:00 +0000711 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000712 Table *pTab;
drh97665872002-02-13 23:22:53 +0000713 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000714 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000715 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
716 assert( j<pTabList->nSrc );
717 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000718 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000719 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000720 if( iCol<0 ){
721 zCol = "_ROWID_";
drhb1363202002-06-26 02:45:03 +0000722 }else{
723 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000724 }
drhfcabd462004-02-20 14:50:58 +0000725 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
drhd6502752004-02-16 03:44:01 +0000726 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, p2);
drh6977fea2002-10-22 23:38:04 +0000727 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
drhfa173a72002-07-10 21:26:00 +0000728 sqliteVdbeCompressSpace(v, addr);
drhfcabd462004-02-20 14:50:58 +0000729 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000730 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000731 char *zTab;
732
drh6a3ea0e2003-05-02 14:32:12 +0000733 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000734 if( fullNames || zTab==0 ) zTab = pTab->zName;
drh97665872002-02-13 23:22:53 +0000735 sqliteSetString(&zName, zTab, ".", zCol, 0);
drhd6502752004-02-16 03:44:01 +0000736 sqliteVdbeAddOp(v, OP_ColumnName, i, p2);
drh99fcd712001-10-13 01:06:47 +0000737 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000738 sqliteFree(zName);
739 }else{
drhd6502752004-02-16 03:44:01 +0000740 sqliteVdbeAddOp(v, OP_ColumnName, i, p2);
drh22f70c32002-02-18 01:17:00 +0000741 sqliteVdbeChangeP3(v, -1, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000742 }
drh6977fea2002-10-22 23:38:04 +0000743 }else if( p->span.z && p->span.z[0] ){
drhd6502752004-02-16 03:44:01 +0000744 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, p2);
drh6977fea2002-10-22 23:38:04 +0000745 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
drh1bee3d72001-10-15 00:44:35 +0000746 sqliteVdbeCompressSpace(v, addr);
747 }else{
748 char zName[30];
749 assert( p->op!=TK_COLUMN || pTabList==0 );
750 sprintf(zName, "column%d", i+1);
drhd6502752004-02-16 03:44:01 +0000751 sqliteVdbeAddOp(v, OP_ColumnName, i, p2);
drh1bee3d72001-10-15 00:44:35 +0000752 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000753 }
754 }
755}
756
757/*
drhd8bc7082000-06-07 23:51:50 +0000758** Name of the connection operator, used for error messages.
759*/
760static const char *selectOpName(int id){
761 char *z;
762 switch( id ){
763 case TK_ALL: z = "UNION ALL"; break;
764 case TK_INTERSECT: z = "INTERSECT"; break;
765 case TK_EXCEPT: z = "EXCEPT"; break;
766 default: z = "UNION"; break;
767 }
768 return z;
769}
770
771/*
drh315555c2002-10-20 15:53:03 +0000772** Forward declaration
773*/
774static int fillInColumnList(Parse*, Select*);
775
776/*
drh22f70c32002-02-18 01:17:00 +0000777** Given a SELECT statement, generate a Table structure that describes
778** the result set of that SELECT.
779*/
780Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
781 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000782 int i, j;
drh22f70c32002-02-18 01:17:00 +0000783 ExprList *pEList;
drhb733d032004-01-24 20:18:12 +0000784 Column *aCol;
drh22f70c32002-02-18 01:17:00 +0000785
786 if( fillInColumnList(pParse, pSelect) ){
787 return 0;
788 }
789 pTab = sqliteMalloc( sizeof(Table) );
790 if( pTab==0 ){
791 return 0;
792 }
793 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
794 pEList = pSelect->pEList;
795 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000796 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000797 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh22f70c32002-02-18 01:17:00 +0000798 for(i=0; i<pTab->nCol; i++){
drhb733d032004-01-24 20:18:12 +0000799 Expr *p, *pR;
drh22f70c32002-02-18 01:17:00 +0000800 if( pEList->a[i].zName ){
drhb733d032004-01-24 20:18:12 +0000801 aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
802 }else if( (p=pEList->a[i].pExpr)->op==TK_DOT
803 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
804 int cnt;
805 sqliteSetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
806 for(j=cnt=0; j<i; j++){
807 if( sqliteStrICmp(aCol[j].zName, aCol[i].zName)==0 ){
808 int n;
809 char zBuf[30];
810 sprintf(zBuf,"_%d",++cnt);
811 n = strlen(zBuf);
812 sqliteSetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf, n,0);
813 j = -1;
814 }
815 }
816 }else if( p->span.z && p->span.z[0] ){
drh6977fea2002-10-22 23:38:04 +0000817 sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drh22f70c32002-02-18 01:17:00 +0000818 }else{
819 char zBuf[30];
820 sprintf(zBuf, "column%d", i+1);
821 pTab->aCol[i].zName = sqliteStrDup(zBuf);
822 }
823 }
824 pTab->iPKey = -1;
825 return pTab;
826}
827
828/*
drhad2d8302002-05-24 20:31:36 +0000829** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000830**
drhad3cab52002-05-24 02:04:32 +0000831** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh63eb5f22003-04-29 16:20:44 +0000832** defines the set of tables that should be scanned. For views,
833** fill pTabList->a[].pSelect with a copy of the SELECT statement
834** that implements the view. A copy is made of the view's SELECT
835** statement so that we can freely modify or delete that statement
836** without worrying about messing up the presistent representation
837** of the view.
drhd8bc7082000-06-07 23:51:50 +0000838**
drhad2d8302002-05-24 20:31:36 +0000839** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
840** on joins and the ON and USING clause of joins.
841**
842** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000843** for instances of the "*" operator or the TABLE.* operator.
844** If found, expand each "*" to be every column in every table
845** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000846**
847** Return 0 on success. If there are problems, leave an error message
848** in pParse and return non-zero.
849*/
850static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000851 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000852 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000853 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000854 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000855
856 if( p==0 || p->pSrc==0 ) return 1;
857 pTabList = p->pSrc;
858 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000859
860 /* Look up every table in the table list.
861 */
drhad3cab52002-05-24 02:04:32 +0000862 for(i=0; i<pTabList->nSrc; i++){
drhd8bc7082000-06-07 23:51:50 +0000863 if( pTabList->a[i].pTab ){
864 /* This routine has run before! No need to continue */
865 return 0;
866 }
drhdaffd0e2001-04-11 14:28:42 +0000867 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000868 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000869 assert( pTabList->a[i].pSelect!=0 );
drhad2d8302002-05-24 20:31:36 +0000870 if( pTabList->a[i].zAlias==0 ){
871 char zFakeName[60];
872 sprintf(zFakeName, "sqlite_subquery_%p_",
873 (void*)pTabList->a[i].pSelect);
874 sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
875 }
drh22f70c32002-02-18 01:17:00 +0000876 pTabList->a[i].pTab = pTab =
877 sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
878 pTabList->a[i].pSelect);
879 if( pTab==0 ){
880 return 1;
881 }
drh5cf590c2003-04-24 01:45:04 +0000882 /* The isTransient flag indicates that the Table structure has been
883 ** dynamically allocated and may be freed at any time. In other words,
884 ** pTab is not pointing to a persistent table structure that defines
885 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000886 pTab->isTransient = 1;
887 }else{
drha76b5df2002-02-23 02:32:10 +0000888 /* An ordinary table or view name in the FROM clause */
889 pTabList->a[i].pTab = pTab =
drha69d9162003-04-17 22:57:53 +0000890 sqliteLocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
drha76b5df2002-02-23 02:32:10 +0000891 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000892 return 1;
893 }
drha76b5df2002-02-23 02:32:10 +0000894 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +0000895 /* We reach here if the named table is a really a view */
drh417be792002-03-03 18:59:40 +0000896 if( sqliteViewGetColumnNames(pParse, pTab) ){
897 return 1;
898 }
drh63eb5f22003-04-29 16:20:44 +0000899 /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
900 ** view within a view. The SELECT structure has already been
901 ** copied by the outer view so we can skip the copy step here
902 ** in the inner view.
903 */
904 if( pTabList->a[i].pSelect==0 ){
905 pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
906 }
drha76b5df2002-02-23 02:32:10 +0000907 }
drhd8bc7082000-06-07 23:51:50 +0000908 }
909 }
910
drhad2d8302002-05-24 20:31:36 +0000911 /* Process NATURAL keywords, and ON and USING clauses of joins.
912 */
913 if( sqliteProcessJoin(pParse, p) ) return 1;
914
drh7c917d12001-12-16 20:05:05 +0000915 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000916 ** all columns in all tables. And for every TABLE.* insert the names
917 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000918 ** with the TK_ALL operator for each "*" that it found in the column list.
919 ** The following code just has to locate the TK_ALL expressions and expand
920 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000921 **
922 ** The first loop just checks to see if there are any "*" operators
923 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000924 */
drh7c917d12001-12-16 20:05:05 +0000925 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000926 Expr *pE = pEList->a[k].pExpr;
927 if( pE->op==TK_ALL ) break;
928 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
929 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000930 }
drh54473222002-04-04 02:10:55 +0000931 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000932 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000933 /*
934 ** If we get here it means the result set contains one or more "*"
935 ** operators that need to be expanded. Loop through each expression
936 ** in the result set and expand them one by one.
937 */
drh7c917d12001-12-16 20:05:05 +0000938 struct ExprList_item *a = pEList->a;
939 ExprList *pNew = 0;
940 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000941 Expr *pE = a[k].pExpr;
942 if( pE->op!=TK_ALL &&
943 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
944 /* This particular expression does not need to be expanded.
945 */
drh7c917d12001-12-16 20:05:05 +0000946 pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
947 pNew->a[pNew->nExpr-1].zName = a[k].zName;
948 a[k].pExpr = 0;
949 a[k].zName = 0;
950 }else{
drh54473222002-04-04 02:10:55 +0000951 /* This expression is a "*" or a "TABLE.*" and needs to be
952 ** expanded. */
953 int tableSeen = 0; /* Set to 1 when TABLE matches */
954 Token *pName; /* text of name of TABLE */
955 if( pE->op==TK_DOT && pE->pLeft ){
956 pName = &pE->pLeft->token;
957 }else{
958 pName = 0;
959 }
drhad3cab52002-05-24 02:04:32 +0000960 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000961 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000962 char *zTabName = pTabList->a[i].zAlias;
963 if( zTabName==0 || zTabName[0]==0 ){
964 zTabName = pTab->zName;
965 }
drhc754fa52002-05-27 03:25:51 +0000966 if( pName && (zTabName==0 || zTabName[0]==0 ||
967 sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
968 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +0000969 continue;
970 }
971 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +0000972 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000973 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +0000974 char *zName = pTab->aCol[j].zName;
975
976 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
977 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
978 /* In a NATURAL join, omit the join columns from the
979 ** table on the right */
980 continue;
981 }
982 if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
983 /* In a join with a USING clause, omit columns in the
984 ** using clause from the table on the right. */
985 continue;
986 }
drh22f70c32002-02-18 01:17:00 +0000987 pRight = sqliteExpr(TK_ID, 0, 0, 0);
988 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +0000989 pRight->token.z = zName;
990 pRight->token.n = strlen(zName);
drh4b59ab52002-08-24 18:24:51 +0000991 pRight->token.dyn = 0;
drh4b59ab52002-08-24 18:24:51 +0000992 if( zTabName && pTabList->nSrc>1 ){
drh22f70c32002-02-18 01:17:00 +0000993 pLeft = sqliteExpr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +0000994 pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
995 if( pExpr==0 ) break;
drh4b59ab52002-08-24 18:24:51 +0000996 pLeft->token.z = zTabName;
997 pLeft->token.n = strlen(zTabName);
998 pLeft->token.dyn = 0;
drh6977fea2002-10-22 23:38:04 +0000999 sqliteSetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
1000 pExpr->span.n = strlen(pExpr->span.z);
1001 pExpr->span.dyn = 1;
1002 pExpr->token.z = 0;
1003 pExpr->token.n = 0;
1004 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001005 }else{
drh22f70c32002-02-18 01:17:00 +00001006 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001007 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001008 }
drh7c917d12001-12-16 20:05:05 +00001009 pNew = sqliteExprListAppend(pNew, pExpr, 0);
1010 }
drh17e24df2001-11-06 14:10:41 +00001011 }
drh54473222002-04-04 02:10:55 +00001012 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +00001013 if( pName ){
drhda93d232003-03-31 02:12:46 +00001014 sqliteErrorMsg(pParse, "no such table: %T", pName);
drhf5db2d32002-06-06 23:42:27 +00001015 }else{
drhda93d232003-03-31 02:12:46 +00001016 sqliteErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001017 }
drh54473222002-04-04 02:10:55 +00001018 rc = 1;
1019 }
drhd8bc7082000-06-07 23:51:50 +00001020 }
1021 }
drh7c917d12001-12-16 20:05:05 +00001022 sqliteExprListDelete(pEList);
1023 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001024 }
drh54473222002-04-04 02:10:55 +00001025 return rc;
drhd8bc7082000-06-07 23:51:50 +00001026}
1027
1028/*
drhff78bd22002-02-27 01:47:11 +00001029** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1030** in a select structure. It just sets the pointers to NULL. This
1031** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1032** pointer is not NULL, this routine is called recursively on that pointer.
1033**
1034** This routine is called on the Select structure that defines a
1035** VIEW in order to undo any bindings to tables. This is necessary
1036** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001037** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1038** will be left pointing to a deallocated Table structure after the
1039** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001040*/
1041void sqliteSelectUnbind(Select *p){
1042 int i;
drhad3cab52002-05-24 02:04:32 +00001043 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +00001044 Table *pTab;
1045 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +00001046 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +00001047 if( (pTab = pSrc->a[i].pTab)!=0 ){
1048 if( pTab->isTransient ){
1049 sqliteDeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001050 }
1051 pSrc->a[i].pTab = 0;
1052 if( pSrc->a[i].pSelect ){
1053 sqliteSelectUnbind(pSrc->a[i].pSelect);
1054 }
1055 }
1056 }
1057}
1058
1059/*
drhd8bc7082000-06-07 23:51:50 +00001060** This routine associates entries in an ORDER BY expression list with
1061** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001062** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001063** the top-level node is filled in with column number and the iTable
1064** value of the top-level node is filled with iTable parameter.
1065**
1066** If there are prior SELECT clauses, they are processed first. A match
1067** in an earlier SELECT takes precedence over a later SELECT.
1068**
1069** Any entry that does not match is flagged as an error. The number
1070** of errors is returned.
drhfcb78a42003-01-18 20:11:05 +00001071**
1072** This routine does NOT correctly initialize the Expr.dataType field
1073** of the ORDER BY expressions. The multiSelectSortOrder() routine
1074** must be called to do that after the individual select statements
1075** have all been analyzed. This routine is unable to compute Expr.dataType
1076** because it must be called before the individual select statements
1077** have been analyzed.
drhd8bc7082000-06-07 23:51:50 +00001078*/
1079static int matchOrderbyToColumn(
1080 Parse *pParse, /* A place to leave error messages */
1081 Select *pSelect, /* Match to result columns of this SELECT */
1082 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001083 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001084 int mustComplete /* If TRUE all ORDER BYs must match */
1085){
1086 int nErr = 0;
1087 int i, j;
1088 ExprList *pEList;
1089
drhdaffd0e2001-04-11 14:28:42 +00001090 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001091 if( mustComplete ){
1092 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1093 }
1094 if( fillInColumnList(pParse, pSelect) ){
1095 return 1;
1096 }
1097 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001098 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1099 return 1;
1100 }
drhd8bc7082000-06-07 23:51:50 +00001101 }
1102 pEList = pSelect->pEList;
1103 for(i=0; i<pOrderBy->nExpr; i++){
1104 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001105 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001106 if( pOrderBy->a[i].done ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001107 if( sqliteExprIsInteger(pE, &iCol) ){
1108 if( iCol<=0 || iCol>pEList->nExpr ){
drhda93d232003-03-31 02:12:46 +00001109 sqliteErrorMsg(pParse,
1110 "ORDER BY position %d should be between 1 and %d",
1111 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001112 nErr++;
1113 break;
1114 }
drhfcb78a42003-01-18 20:11:05 +00001115 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001116 iCol--;
1117 }
1118 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001119 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001120 char *zName, *zLabel;
1121 zName = pEList->a[j].zName;
1122 assert( pE->token.z );
1123 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
drhd8bc7082000-06-07 23:51:50 +00001124 sqliteDequote(zLabel);
1125 if( sqliteStrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001126 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001127 }
drh6e142f52000-06-08 13:36:40 +00001128 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001129 }
drhe4de1fe2002-06-02 16:09:01 +00001130 if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
1131 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001132 }
1133 }
drhe4de1fe2002-06-02 16:09:01 +00001134 if( iCol>=0 ){
1135 pE->op = TK_COLUMN;
1136 pE->iColumn = iCol;
1137 pE->iTable = iTable;
1138 pOrderBy->a[i].done = 1;
1139 }
1140 if( iCol<0 && mustComplete ){
drhda93d232003-03-31 02:12:46 +00001141 sqliteErrorMsg(pParse,
1142 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001143 nErr++;
1144 break;
1145 }
1146 }
1147 return nErr;
1148}
1149
1150/*
1151** Get a VDBE for the given parser context. Create a new one if necessary.
1152** If an error occurs, return NULL and leave a message in pParse.
1153*/
1154Vdbe *sqliteGetVdbe(Parse *pParse){
1155 Vdbe *v = pParse->pVdbe;
1156 if( v==0 ){
drh4c504392000-10-16 22:06:40 +00001157 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001158 }
drhd8bc7082000-06-07 23:51:50 +00001159 return v;
1160}
drhfcb78a42003-01-18 20:11:05 +00001161
1162/*
1163** This routine sets the Expr.dataType field on all elements of
1164** the pOrderBy expression list. The pOrderBy list will have been
1165** set up by matchOrderbyToColumn(). Hence each expression has
1166** a TK_COLUMN as its root node. The Expr.iColumn refers to a
1167** column in the result set. The datatype is set to SQLITE_SO_TEXT
1168** if the corresponding column in p and every SELECT to the left of
1169** p has a datatype of SQLITE_SO_TEXT. If the cooressponding column
1170** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
1171** of the order-by expression is set to SQLITE_SO_NUM.
1172**
1173** Examples:
1174**
drhe78e8282003-01-19 03:59:45 +00001175** CREATE TABLE one(a INTEGER, b TEXT);
1176** CREATE TABLE two(c VARCHAR(5), d FLOAT);
1177**
1178** SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
1179**
1180** The primary sort key will use SQLITE_SO_NUM because the "d" in
1181** the second SELECT is numeric. The 1st column of the first SELECT
1182** is text but that does not matter because a numeric always overrides
1183** a text.
1184**
1185** The secondary key will use the SQLITE_SO_TEXT sort order because
1186** both the (second) "b" in the first SELECT and the "c" in the second
1187** SELECT have a datatype of text.
drhfcb78a42003-01-18 20:11:05 +00001188*/
1189static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
1190 int i;
1191 ExprList *pEList;
1192 if( pOrderBy==0 ) return;
1193 if( p==0 ){
1194 for(i=0; i<pOrderBy->nExpr; i++){
1195 pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
1196 }
1197 return;
1198 }
1199 multiSelectSortOrder(p->pPrior, pOrderBy);
1200 pEList = p->pEList;
1201 for(i=0; i<pOrderBy->nExpr; i++){
1202 Expr *pE = pOrderBy->a[i].pExpr;
1203 if( pE->dataType==SQLITE_SO_NUM ) continue;
1204 assert( pE->iColumn>=0 );
1205 if( pEList->nExpr>pE->iColumn ){
1206 pE->dataType = sqliteExprType(pEList->a[pE->iColumn].pExpr);
1207 }
1208 }
1209}
drhd8bc7082000-06-07 23:51:50 +00001210
1211/*
drh7b58dae2003-07-20 01:16:46 +00001212** Compute the iLimit and iOffset fields of the SELECT based on the
1213** nLimit and nOffset fields. nLimit and nOffset hold the integers
1214** that appear in the original SQL statement after the LIMIT and OFFSET
1215** keywords. Or that hold -1 and 0 if those keywords are omitted.
1216** iLimit and iOffset are the integer memory register numbers for
1217** counters used to compute the limit and offset. If there is no
1218** limit and/or offset, then iLimit and iOffset are negative.
1219**
1220** This routine changes the values if iLimit and iOffset only if
1221** a limit or offset is defined by nLimit and nOffset. iLimit and
1222** iOffset should have been preset to appropriate default values
1223** (usually but not always -1) prior to calling this routine.
1224** Only if nLimit>=0 or nOffset>0 do the limit registers get
1225** redefined. The UNION ALL operator uses this property to force
1226** the reuse of the same limit and offset registers across multiple
1227** SELECT statements.
1228*/
1229static void computeLimitRegisters(Parse *pParse, Select *p){
1230 /*
1231 ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
1232 ** all rows. It is the same as no limit. If the comparision is
1233 ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
1234 ** "LIMIT -1" always shows all rows. There is some
1235 ** contraversy about what the correct behavior should be.
1236 ** The current implementation interprets "LIMIT 0" to mean
1237 ** no rows.
1238 */
1239 if( p->nLimit>=0 ){
1240 int iMem = pParse->nMem++;
1241 Vdbe *v = sqliteGetVdbe(pParse);
1242 if( v==0 ) return;
1243 sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1244 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
1245 p->iLimit = iMem;
1246 }
1247 if( p->nOffset>0 ){
1248 int iMem = pParse->nMem++;
1249 Vdbe *v = sqliteGetVdbe(pParse);
1250 if( v==0 ) return;
1251 sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1252 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
1253 p->iOffset = iMem;
1254 }
1255}
1256
1257/*
drh82c3d632000-06-06 21:56:07 +00001258** This routine is called to process a query that is really the union
1259** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001260**
drhe78e8282003-01-19 03:59:45 +00001261** "p" points to the right-most of the two queries. the query on the
1262** left is p->pPrior. The left query could also be a compound query
1263** in which case this routine will be called recursively.
1264**
1265** The results of the total query are to be written into a destination
1266** of type eDest with parameter iParm.
1267**
1268** Example 1: Consider a three-way compound SQL statement.
1269**
1270** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1271**
1272** This statement is parsed up as follows:
1273**
1274** SELECT c FROM t3
1275** |
1276** `-----> SELECT b FROM t2
1277** |
jplyon4b11c6d2004-01-19 04:57:53 +00001278** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001279**
1280** The arrows in the diagram above represent the Select.pPrior pointer.
1281** So if this routine is called with p equal to the t3 query, then
1282** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1283**
1284** Notice that because of the way SQLite parses compound SELECTs, the
1285** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001286*/
1287static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
drh10e5e3c2000-06-08 00:19:02 +00001288 int rc; /* Success code from a subroutine */
1289 Select *pPrior; /* Another SELECT immediately to our left */
1290 Vdbe *v; /* Generate code to this VDBE */
drh82c3d632000-06-06 21:56:07 +00001291
drh7b58dae2003-07-20 01:16:46 +00001292 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
1293 ** the last SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001294 */
drhdaffd0e2001-04-11 14:28:42 +00001295 if( p==0 || p->pPrior==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001296 pPrior = p->pPrior;
1297 if( pPrior->pOrderBy ){
drhda93d232003-03-31 02:12:46 +00001298 sqliteErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1299 selectOpName(p->op));
drh82c3d632000-06-06 21:56:07 +00001300 return 1;
1301 }
drh7b58dae2003-07-20 01:16:46 +00001302 if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
1303 sqliteErrorMsg(pParse,"LIMIT clause should come after %s not before",
1304 selectOpName(p->op));
1305 return 1;
1306 }
drh82c3d632000-06-06 21:56:07 +00001307
drhd8bc7082000-06-07 23:51:50 +00001308 /* Make sure we have a valid query engine. If not, create a new one.
1309 */
1310 v = sqliteGetVdbe(pParse);
1311 if( v==0 ) return 1;
1312
drh1cc3d752002-03-23 00:31:29 +00001313 /* Create the destination temporary table if necessary
1314 */
1315 if( eDest==SRT_TempTable ){
1316 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
1317 eDest = SRT_Table;
1318 }
1319
drhf46f9052002-06-22 02:33:38 +00001320 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001321 */
drh82c3d632000-06-06 21:56:07 +00001322 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001323 case TK_ALL: {
1324 if( p->pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +00001325 pPrior->nLimit = p->nLimit;
1326 pPrior->nOffset = p->nOffset;
drhf46f9052002-06-22 02:33:38 +00001327 rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
1328 if( rc ) return rc;
1329 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001330 p->iLimit = pPrior->iLimit;
1331 p->iOffset = pPrior->iOffset;
1332 p->nLimit = -1;
1333 p->nOffset = 0;
drhf46f9052002-06-22 02:33:38 +00001334 rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
1335 p->pPrior = pPrior;
1336 if( rc ) return rc;
1337 break;
1338 }
1339 /* For UNION ALL ... ORDER BY fall through to the next case */
1340 }
drh82c3d632000-06-06 21:56:07 +00001341 case TK_EXCEPT:
1342 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001343 int unionTab; /* Cursor number of the temporary table holding result */
1344 int op; /* One of the SRT_ operations to apply to self */
1345 int priorOp; /* The SRT_ operation to apply to prior selects */
drh7b58dae2003-07-20 01:16:46 +00001346 int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
drhc926afb2002-06-20 03:38:26 +00001347 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
drh82c3d632000-06-06 21:56:07 +00001348
drhd8bc7082000-06-07 23:51:50 +00001349 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh7b58dae2003-07-20 01:16:46 +00001350 if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
drhd8bc7082000-06-07 23:51:50 +00001351 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001352 ** right.
drhd8bc7082000-06-07 23:51:50 +00001353 */
drh82c3d632000-06-06 21:56:07 +00001354 unionTab = iParm;
1355 }else{
drhd8bc7082000-06-07 23:51:50 +00001356 /* We will need to create our own temporary table to hold the
1357 ** intermediate results.
1358 */
1359 unionTab = pParse->nTab++;
1360 if( p->pOrderBy
1361 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1362 return 1;
1363 }
drhd8bc7082000-06-07 23:51:50 +00001364 if( p->op!=TK_ALL ){
drhc6b52df2002-01-04 03:09:29 +00001365 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
drh99fcd712001-10-13 01:06:47 +00001366 sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drh345fda32001-01-15 22:51:08 +00001367 }else{
drh99fcd712001-10-13 01:06:47 +00001368 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001369 }
drh82c3d632000-06-06 21:56:07 +00001370 }
drhd8bc7082000-06-07 23:51:50 +00001371
1372 /* Code the SELECT statements to our left
1373 */
drh832508b2002-03-02 17:04:07 +00001374 rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001375 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001376
1377 /* Code the current SELECT statement
1378 */
1379 switch( p->op ){
1380 case TK_EXCEPT: op = SRT_Except; break;
1381 case TK_UNION: op = SRT_Union; break;
1382 case TK_ALL: op = SRT_Table; break;
1383 }
drh82c3d632000-06-06 21:56:07 +00001384 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001385 pOrderBy = p->pOrderBy;
1386 p->pOrderBy = 0;
drh7b58dae2003-07-20 01:16:46 +00001387 nLimit = p->nLimit;
1388 p->nLimit = -1;
1389 nOffset = p->nOffset;
1390 p->nOffset = 0;
drh832508b2002-03-02 17:04:07 +00001391 rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001392 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001393 p->pOrderBy = pOrderBy;
drh7b58dae2003-07-20 01:16:46 +00001394 p->nLimit = nLimit;
1395 p->nOffset = nOffset;
drh82c3d632000-06-06 21:56:07 +00001396 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001397
1398 /* Convert the data in the temporary table into whatever form
1399 ** it is that we currently need.
1400 */
drhc926afb2002-06-20 03:38:26 +00001401 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001402 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001403 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001404 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001405 generateColumnNames(pParse, 0, p->pEList);
1406 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001407 }
drh82c3d632000-06-06 21:56:07 +00001408 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001409 iCont = sqliteVdbeMakeLabel(v);
1410 sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001411 computeLimitRegisters(pParse, p);
drh6b563442001-11-07 16:48:26 +00001412 iStart = sqliteVdbeCurrentAddr(v);
drhfcb78a42003-01-18 20:11:05 +00001413 multiSelectSortOrder(p, p->pOrderBy);
drh38640e12002-07-05 21:42:36 +00001414 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001415 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001416 iCont, iBreak);
1417 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001418 sqliteVdbeResolveLabel(v, iCont);
1419 sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
drh99fcd712001-10-13 01:06:47 +00001420 sqliteVdbeResolveLabel(v, iBreak);
1421 sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001422 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001423 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001424 }
drh82c3d632000-06-06 21:56:07 +00001425 }
1426 break;
1427 }
1428 case TK_INTERSECT: {
1429 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001430 int iCont, iBreak, iStart;
drh7b58dae2003-07-20 01:16:46 +00001431 int nLimit, nOffset;
drh82c3d632000-06-06 21:56:07 +00001432
drhd8bc7082000-06-07 23:51:50 +00001433 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001434 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001435 ** by allocating the tables we will need.
1436 */
drh82c3d632000-06-06 21:56:07 +00001437 tab1 = pParse->nTab++;
1438 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001439 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1440 return 1;
1441 }
drhc6b52df2002-01-04 03:09:29 +00001442 sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
drh99fcd712001-10-13 01:06:47 +00001443 sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
drhd8bc7082000-06-07 23:51:50 +00001444
1445 /* Code the SELECTs to our left into temporary table "tab1".
1446 */
drh832508b2002-03-02 17:04:07 +00001447 rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001448 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001449
1450 /* Code the current SELECT into temporary table "tab2"
1451 */
drhc6b52df2002-01-04 03:09:29 +00001452 sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
drh99fcd712001-10-13 01:06:47 +00001453 sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001454 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001455 nLimit = p->nLimit;
1456 p->nLimit = -1;
1457 nOffset = p->nOffset;
1458 p->nOffset = 0;
drh832508b2002-03-02 17:04:07 +00001459 rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001460 p->pPrior = pPrior;
drh7b58dae2003-07-20 01:16:46 +00001461 p->nLimit = nLimit;
1462 p->nOffset = nOffset;
drh82c3d632000-06-06 21:56:07 +00001463 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001464
1465 /* Generate code to take the intersection of the two temporary
1466 ** tables.
1467 */
drh82c3d632000-06-06 21:56:07 +00001468 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001469 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001470 generateColumnNames(pParse, 0, p->pEList);
1471 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001472 }
drh82c3d632000-06-06 21:56:07 +00001473 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001474 iCont = sqliteVdbeMakeLabel(v);
1475 sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001476 computeLimitRegisters(pParse, p);
drh6b563442001-11-07 16:48:26 +00001477 iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
drh99fcd712001-10-13 01:06:47 +00001478 sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
drhfcb78a42003-01-18 20:11:05 +00001479 multiSelectSortOrder(p, p->pOrderBy);
drh38640e12002-07-05 21:42:36 +00001480 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001481 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001482 iCont, iBreak);
1483 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001484 sqliteVdbeResolveLabel(v, iCont);
1485 sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
drh99fcd712001-10-13 01:06:47 +00001486 sqliteVdbeResolveLabel(v, iBreak);
1487 sqliteVdbeAddOp(v, OP_Close, tab2, 0);
1488 sqliteVdbeAddOp(v, OP_Close, tab1, 0);
drhd8bc7082000-06-07 23:51:50 +00001489 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001490 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001491 }
drh82c3d632000-06-06 21:56:07 +00001492 break;
1493 }
1494 }
1495 assert( p->pEList && pPrior->pEList );
1496 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
drhda93d232003-03-31 02:12:46 +00001497 sqliteErrorMsg(pParse, "SELECTs to the left and right of %s"
1498 " do not have the same number of result columns", selectOpName(p->op));
drh82c3d632000-06-06 21:56:07 +00001499 return 1;
drh22827922000-06-06 17:27:05 +00001500 }
1501 return 0;
1502}
1503
1504/*
drh832508b2002-03-02 17:04:07 +00001505** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001506** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001507** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001508** unchanged.)
drh832508b2002-03-02 17:04:07 +00001509**
1510** This routine is part of the flattening procedure. A subquery
1511** whose result set is defined by pEList appears as entry in the
1512** FROM clause of a SELECT such that the VDBE cursor assigned to that
1513** FORM clause entry is iTable. This routine make the necessary
1514** changes to pExpr so that it refers directly to the source table
1515** of the subquery rather the result set of the subquery.
1516*/
drh6a3ea0e2003-05-02 14:32:12 +00001517static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1518static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001519 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001520 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1521 if( pExpr->iColumn<0 ){
1522 pExpr->op = TK_NULL;
1523 }else{
1524 Expr *pNew;
1525 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1526 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1527 pNew = pEList->a[pExpr->iColumn].pExpr;
1528 assert( pNew!=0 );
1529 pExpr->op = pNew->op;
1530 pExpr->dataType = pNew->dataType;
1531 assert( pExpr->pLeft==0 );
1532 pExpr->pLeft = sqliteExprDup(pNew->pLeft);
1533 assert( pExpr->pRight==0 );
1534 pExpr->pRight = sqliteExprDup(pNew->pRight);
1535 assert( pExpr->pList==0 );
1536 pExpr->pList = sqliteExprListDup(pNew->pList);
1537 pExpr->iTable = pNew->iTable;
1538 pExpr->iColumn = pNew->iColumn;
1539 pExpr->iAgg = pNew->iAgg;
1540 sqliteTokenCopy(&pExpr->token, &pNew->token);
1541 sqliteTokenCopy(&pExpr->span, &pNew->span);
1542 }
drh832508b2002-03-02 17:04:07 +00001543 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001544 substExpr(pExpr->pLeft, iTable, pEList);
1545 substExpr(pExpr->pRight, iTable, pEList);
1546 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001547 }
1548}
1549static void
drh6a3ea0e2003-05-02 14:32:12 +00001550substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001551 int i;
1552 if( pList==0 ) return;
1553 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001554 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001555 }
1556}
1557
1558/*
drh1350b032002-02-27 19:00:20 +00001559** This routine attempts to flatten subqueries in order to speed
1560** execution. It returns 1 if it makes changes and 0 if no flattening
1561** occurs.
1562**
1563** To understand the concept of flattening, consider the following
1564** query:
1565**
1566** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1567**
1568** The default way of implementing this query is to execute the
1569** subquery first and store the results in a temporary table, then
1570** run the outer query on that temporary table. This requires two
1571** passes over the data. Furthermore, because the temporary table
1572** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001573** optimized.
drh1350b032002-02-27 19:00:20 +00001574**
drh832508b2002-03-02 17:04:07 +00001575** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001576** a single flat select, like this:
1577**
1578** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1579**
1580** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001581** but only has to scan the data once. And because indices might
1582** exist on the table t1, a complete scan of the data might be
1583** avoided.
drh1350b032002-02-27 19:00:20 +00001584**
drh832508b2002-03-02 17:04:07 +00001585** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001586**
drh832508b2002-03-02 17:04:07 +00001587** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001588**
drh832508b2002-03-02 17:04:07 +00001589** (2) The subquery is not an aggregate or the outer query is not a join.
1590**
drh8af4d3a2003-05-06 20:35:16 +00001591** (3) The subquery is not the right operand of a left outer join, or
1592** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001593**
1594** (4) The subquery is not DISTINCT or the outer query is not a join.
1595**
1596** (5) The subquery is not DISTINCT or the outer query does not use
1597** aggregates.
1598**
1599** (6) The subquery does not use aggregates or the outer query is not
1600** DISTINCT.
1601**
drh08192d52002-04-30 19:20:28 +00001602** (7) The subquery has a FROM clause.
1603**
drhdf199a22002-06-14 22:38:41 +00001604** (8) The subquery does not use LIMIT or the outer query is not a join.
1605**
1606** (9) The subquery does not use LIMIT or the outer query does not use
1607** aggregates.
1608**
1609** (10) The subquery does not use aggregates or the outer query does not
1610** use LIMIT.
1611**
drh174b6192002-12-03 02:22:52 +00001612** (11) The subquery and the outer query do not both have ORDER BY clauses.
1613**
drh3fc673e2003-06-16 00:40:34 +00001614** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1615** subquery has no WHERE clause. (added by ticket #350)
1616**
drh832508b2002-03-02 17:04:07 +00001617** In this routine, the "p" parameter is a pointer to the outer query.
1618** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1619** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1620**
drh665de472003-03-31 13:36:09 +00001621** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001622** If flattening is attempted this routine returns 1.
1623**
1624** All of the expression analysis must occur on both the outer query and
1625** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001626*/
drh8c74a8c2002-08-25 19:20:40 +00001627static int flattenSubquery(
1628 Parse *pParse, /* The parsing context */
1629 Select *p, /* The parent or outer SELECT statement */
1630 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1631 int isAgg, /* True if outer SELECT uses aggregate functions */
1632 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1633){
drh0bb28102002-05-08 11:54:14 +00001634 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001635 SrcList *pSrc; /* The FROM clause of the outer query */
1636 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001637 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001638 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh832508b2002-03-02 17:04:07 +00001639 int i;
drh832508b2002-03-02 17:04:07 +00001640 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001641
drh832508b2002-03-02 17:04:07 +00001642 /* Check to see if flattening is permitted. Return 0 if not.
1643 */
1644 if( p==0 ) return 0;
1645 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001646 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001647 pSub = pSrc->a[iFrom].pSelect;
1648 assert( pSub!=0 );
1649 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001650 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001651 pSubSrc = pSub->pSrc;
1652 assert( pSubSrc );
drhc31c2eb2003-05-02 16:04:17 +00001653 if( pSubSrc->nSrc==0 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001654 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1655 return 0;
1656 }
drhd11d3822002-06-21 23:01:49 +00001657 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001658 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001659
drh8af4d3a2003-05-06 20:35:16 +00001660 /* Restriction 3: If the subquery is a join, make sure the subquery is
1661 ** not used as the right operand of an outer join. Examples of why this
1662 ** is not allowed:
1663 **
1664 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1665 **
1666 ** If we flatten the above, we would get
1667 **
1668 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1669 **
1670 ** which is not at all the same thing.
1671 */
1672 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1673 return 0;
1674 }
1675
drh3fc673e2003-06-16 00:40:34 +00001676 /* Restriction 12: If the subquery is the right operand of a left outer
1677 ** join, make sure the subquery has no WHERE clause.
1678 ** An examples of why this is not allowed:
1679 **
1680 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1681 **
1682 ** If we flatten the above, we would get
1683 **
1684 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1685 **
1686 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1687 ** effectively converts the OUTER JOIN into an INNER JOIN.
1688 */
1689 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1690 && pSub->pWhere!=0 ){
1691 return 0;
1692 }
1693
drh0bb28102002-05-08 11:54:14 +00001694 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001695 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001696 */
drhc31c2eb2003-05-02 16:04:17 +00001697
1698 /* Move all of the FROM elements of the subquery into the
1699 ** the FROM clause of the outer query. Before doing this, remember
1700 ** the cursor number for the original outer query FROM element in
1701 ** iParent. The iParent cursor will never be used. Subsequent code
1702 ** will scan expressions looking for iParent references and replace
1703 ** those references with expressions that resolve to the subquery FROM
1704 ** elements we are now copying in.
1705 */
drh6a3ea0e2003-05-02 14:32:12 +00001706 iParent = pSrc->a[iFrom].iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001707 {
1708 int nSubSrc = pSubSrc->nSrc;
drh8af4d3a2003-05-06 20:35:16 +00001709 int jointype = pSrc->a[iFrom].jointype;
drhc31c2eb2003-05-02 16:04:17 +00001710
1711 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1712 sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1713 }
drhf26e09c2003-05-31 16:21:12 +00001714 sqliteFree(pSrc->a[iFrom].zDatabase);
drhc31c2eb2003-05-02 16:04:17 +00001715 sqliteFree(pSrc->a[iFrom].zName);
1716 sqliteFree(pSrc->a[iFrom].zAlias);
1717 if( nSubSrc>1 ){
1718 int extra = nSubSrc - 1;
1719 for(i=1; i<nSubSrc; i++){
1720 pSrc = sqliteSrcListAppend(pSrc, 0, 0);
1721 }
1722 p->pSrc = pSrc;
1723 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1724 pSrc->a[i] = pSrc->a[i-extra];
1725 }
1726 }
1727 for(i=0; i<nSubSrc; i++){
1728 pSrc->a[i+iFrom] = pSubSrc->a[i];
1729 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1730 }
drh8af4d3a2003-05-06 20:35:16 +00001731 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00001732 }
1733
1734 /* Now begin substituting subquery result set expressions for
1735 ** references to the iParent in the outer query.
1736 **
1737 ** Example:
1738 **
1739 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1740 ** \ \_____________ subquery __________/ /
1741 ** \_____________________ outer query ______________________________/
1742 **
1743 ** We look at every expression in the outer query and every place we see
1744 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1745 */
drh6a3ea0e2003-05-02 14:32:12 +00001746 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001747 pList = p->pEList;
1748 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001749 Expr *pExpr;
1750 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1751 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001752 }
1753 }
drh1b2e0322002-03-03 02:49:51 +00001754 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00001755 substExprList(p->pGroupBy, iParent, pSub->pEList);
1756 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001757 }
drh174b6192002-12-03 02:22:52 +00001758 if( pSub->pOrderBy ){
1759 assert( p->pOrderBy==0 );
1760 p->pOrderBy = pSub->pOrderBy;
1761 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00001762 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00001763 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00001764 }
drh832508b2002-03-02 17:04:07 +00001765 if( pSub->pWhere ){
1766 pWhere = sqliteExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00001767 }else{
1768 pWhere = 0;
1769 }
1770 if( subqueryIsAgg ){
1771 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001772 p->pHaving = p->pWhere;
1773 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00001774 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001775 if( pSub->pHaving ){
1776 Expr *pHaving = sqliteExprDup(pSub->pHaving);
drh1b2e0322002-03-03 02:49:51 +00001777 if( p->pHaving ){
1778 p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
1779 }else{
1780 p->pHaving = pHaving;
1781 }
1782 }
1783 assert( p->pGroupBy==0 );
1784 p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00001785 }else if( p->pWhere==0 ){
1786 p->pWhere = pWhere;
1787 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001788 substExpr(p->pWhere, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001789 if( pWhere ){
1790 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1791 }
1792 }
drhc31c2eb2003-05-02 16:04:17 +00001793
1794 /* The flattened query is distinct if either the inner or the
1795 ** outer query is distinct.
1796 */
drh832508b2002-03-02 17:04:07 +00001797 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00001798
drhc31c2eb2003-05-02 16:04:17 +00001799 /* Transfer the limit expression from the subquery to the outer
1800 ** query.
1801 */
drhdf199a22002-06-14 22:38:41 +00001802 if( pSub->nLimit>=0 ){
1803 if( p->nLimit<0 ){
1804 p->nLimit = pSub->nLimit;
1805 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1806 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1807 }
1808 }
1809 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00001810
drhc31c2eb2003-05-02 16:04:17 +00001811 /* Finially, delete what is left of the subquery and return
1812 ** success.
1813 */
drh832508b2002-03-02 17:04:07 +00001814 sqliteSelectDelete(pSub);
1815 return 1;
1816}
drh1350b032002-02-27 19:00:20 +00001817
1818/*
drh9562b552002-02-19 15:00:07 +00001819** Analyze the SELECT statement passed in as an argument to see if it
1820** is a simple min() or max() query. If it is and this query can be
1821** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00001822** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00001823** simple min() or max() query, then return 0;
1824**
1825** A simply min() or max() query looks like this:
1826**
1827** SELECT min(a) FROM table;
1828** SELECT max(a) FROM table;
1829**
1830** The query may have only a single table in its FROM argument. There
1831** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1832** be the min() or max() of a single column of the table. The column
1833** in the min() or max() function must be indexed.
1834**
1835** The parameters to this routine are the same as for sqliteSelect().
1836** See the header comment on that routine for additional information.
1837*/
1838static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1839 Expr *pExpr;
1840 int iCol;
1841 Table *pTab;
1842 Index *pIdx;
1843 int base;
1844 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00001845 int seekOp;
1846 int cont;
1847 ExprList eList;
1848 struct ExprList_item eListItem;
1849
1850 /* Check to see if this query is a simple min() or max() query. Return
1851 ** zero if it is not.
1852 */
1853 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drhad3cab52002-05-24 02:04:32 +00001854 if( p->pSrc->nSrc!=1 ) return 0;
drh9562b552002-02-19 15:00:07 +00001855 if( p->pEList->nExpr!=1 ) return 0;
1856 pExpr = p->pEList->a[0].pExpr;
1857 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
1858 if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00001859 if( pExpr->token.n!=3 ) return 0;
drh0bce8352002-02-28 00:41:10 +00001860 if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
1861 seekOp = OP_Rewind;
1862 }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
1863 seekOp = OP_Last;
1864 }else{
1865 return 0;
1866 }
drh9562b552002-02-19 15:00:07 +00001867 pExpr = pExpr->pList->a[0].pExpr;
1868 if( pExpr->op!=TK_COLUMN ) return 0;
1869 iCol = pExpr->iColumn;
1870 pTab = p->pSrc->a[0].pTab;
1871
1872 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00001873 ** Check to make sure we have an index and make pIdx point to the
1874 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
1875 ** key column, no index is necessary so set pIdx to NULL. If no
1876 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00001877 */
1878 if( iCol<0 ){
1879 pIdx = 0;
1880 }else{
1881 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1882 assert( pIdx->nColumn>=1 );
1883 if( pIdx->aiColumn[0]==iCol ) break;
1884 }
1885 if( pIdx==0 ) return 0;
1886 }
1887
drhe5f50722003-07-19 00:44:14 +00001888 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00001889 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00001890 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00001891 */
1892 v = sqliteGetVdbe(pParse);
1893 if( v==0 ) return 0;
1894 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001895 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh9562b552002-02-19 15:00:07 +00001896 }
1897
drh0c37e632004-01-30 02:01:03 +00001898 /* If the output is destined for a temporary table, open that table.
1899 */
1900 if( eDest==SRT_TempTable ){
1901 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
1902 }
1903
drh17f71932002-02-21 12:01:27 +00001904 /* Generating code to find the min or the max. Basically all we have
1905 ** to do is find the first or the last entry in the chosen index. If
1906 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
1907 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00001908 */
drh8bf8dc92003-05-17 17:35:10 +00001909 sqliteCodeVerifySchema(pParse, pTab->iDb);
drh6a3ea0e2003-05-02 14:32:12 +00001910 base = p->pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00001911 computeLimitRegisters(pParse, p);
drhd24cc422003-03-27 12:51:24 +00001912 sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
drh001bbcb2003-03-19 03:14:00 +00001913 sqliteVdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001914 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
drhd4d595f2003-04-17 12:44:23 +00001915 cont = sqliteVdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00001916 if( pIdx==0 ){
1917 sqliteVdbeAddOp(v, seekOp, base, 0);
1918 }else{
drhd24cc422003-03-27 12:51:24 +00001919 sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
drh001bbcb2003-03-19 03:14:00 +00001920 sqliteVdbeAddOp(v, OP_OpenRead, base+1, pIdx->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001921 sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
drh9562b552002-02-19 15:00:07 +00001922 sqliteVdbeAddOp(v, seekOp, base+1, 0);
1923 sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
1924 sqliteVdbeAddOp(v, OP_Close, base+1, 0);
1925 sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
1926 }
drh5cf8e8c2002-02-19 22:42:05 +00001927 eList.nExpr = 1;
1928 memset(&eListItem, 0, sizeof(eListItem));
1929 eList.a = &eListItem;
1930 eList.a[0].pExpr = pExpr;
drh38640e12002-07-05 21:42:36 +00001931 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
drh9562b552002-02-19 15:00:07 +00001932 sqliteVdbeResolveLabel(v, cont);
1933 sqliteVdbeAddOp(v, OP_Close, base, 0);
1934 return 1;
1935}
1936
1937/*
drh9bb61fe2000-06-05 16:01:39 +00001938** Generate code for the given SELECT statement.
1939**
drhfef52082000-06-06 01:50:43 +00001940** The results are distributed in various ways depending on the
1941** value of eDest and iParm.
1942**
1943** eDest Value Result
1944** ------------ -------------------------------------------
1945** SRT_Callback Invoke the callback for each row of the result.
1946**
1947** SRT_Mem Store first result in memory cell iParm
1948**
1949** SRT_Set Store results as keys of a table with cursor iParm
1950**
drh82c3d632000-06-06 21:56:07 +00001951** SRT_Union Store results as a key in a temporary table iParm
1952**
jplyon4b11c6d2004-01-19 04:57:53 +00001953** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00001954**
1955** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00001956**
drhe78e8282003-01-19 03:59:45 +00001957** The table above is incomplete. Additional eDist value have be added
1958** since this comment was written. See the selectInnerLoop() function for
1959** a complete listing of the allowed values of eDest and their meanings.
1960**
drh9bb61fe2000-06-05 16:01:39 +00001961** This routine returns the number of errors. If any errors are
1962** encountered, then an appropriate error message is left in
1963** pParse->zErrMsg.
1964**
1965** This routine does NOT free the Select structure passed in. The
1966** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00001967**
1968** The pParent, parentTab, and *pParentAgg fields are filled in if this
1969** SELECT is a subquery. This routine may try to combine this SELECT
1970** with its parent to form a single flat query. In so doing, it might
1971** change the parent query from a non-aggregate to an aggregate query.
1972** For that reason, the pParentAgg flag is passed as a pointer, so it
1973** can be changed.
drhe78e8282003-01-19 03:59:45 +00001974**
1975** Example 1: The meaning of the pParent parameter.
1976**
1977** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
1978** \ \_______ subquery _______/ /
1979** \ /
1980** \____________________ outer query ___________________/
1981**
1982** This routine is called for the outer query first. For that call,
1983** pParent will be NULL. During the processing of the outer query, this
1984** routine is called recursively to handle the subquery. For the recursive
1985** call, pParent will point to the outer query. Because the subquery is
1986** the second element in a three-way join, the parentTab parameter will
1987** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00001988*/
1989int sqliteSelect(
drhcce7d172000-05-31 15:34:51 +00001990 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00001991 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00001992 int eDest, /* How to dispose of the results */
1993 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00001994 Select *pParent, /* Another SELECT for which this is a sub-query */
1995 int parentTab, /* Index in pParent->pSrc of this query */
drh1b2e0322002-03-03 02:49:51 +00001996 int *pParentAgg /* True if pParent uses aggregate functions */
drhcce7d172000-05-31 15:34:51 +00001997){
drhd8bc7082000-06-07 23:51:50 +00001998 int i;
drhcce7d172000-05-31 15:34:51 +00001999 WhereInfo *pWInfo;
2000 Vdbe *v;
2001 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002002 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002003 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002004 Expr *pWhere; /* The WHERE clause. May be NULL */
2005 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002006 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2007 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002008 int isDistinct; /* True if the DISTINCT keyword is present */
2009 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002010 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00002011
drhdaffd0e2001-04-11 14:28:42 +00002012 if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
drhe22a3342003-04-22 20:30:37 +00002013 if( sqliteAuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002014
drh82c3d632000-06-06 21:56:07 +00002015 /* If there is are a sequence of queries, do the earlier ones first.
2016 */
2017 if( p->pPrior ){
2018 return multiSelect(pParse, p, eDest, iParm);
2019 }
2020
2021 /* Make local copies of the parameters for this query.
2022 */
drh9bb61fe2000-06-05 16:01:39 +00002023 pTabList = p->pSrc;
2024 pWhere = p->pWhere;
2025 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00002026 pGroupBy = p->pGroupBy;
2027 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00002028 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00002029
drh6a3ea0e2003-05-02 14:32:12 +00002030 /* Allocate VDBE cursors for each table in the FROM clause
drh10e5e3c2000-06-08 00:19:02 +00002031 */
drh6a3ea0e2003-05-02 14:32:12 +00002032 sqliteSrcListAssignCursors(pParse, pTabList);
drh10e5e3c2000-06-08 00:19:02 +00002033
drh9bb61fe2000-06-05 16:01:39 +00002034 /*
2035 ** Do not even attempt to generate any code if we have already seen
2036 ** errors before this routine starts.
2037 */
drh1d83f052002-02-17 00:30:36 +00002038 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002039
drhe78e8282003-01-19 03:59:45 +00002040 /* Expand any "*" terms in the result set. (For example the "*" in
2041 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
2042 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00002043 */
drhd8bc7082000-06-07 23:51:50 +00002044 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00002045 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002046 }
drhad2d8302002-05-24 20:31:36 +00002047 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00002048 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00002049 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002050
drh22827922000-06-06 17:27:05 +00002051 /* If writing to memory or generating a set
2052 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002053 */
drhfef52082000-06-06 01:50:43 +00002054 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
drhda93d232003-03-31 02:12:46 +00002055 sqliteErrorMsg(pParse, "only a single result allowed for "
2056 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002057 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002058 }
2059
drhc926afb2002-06-20 03:38:26 +00002060 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002061 */
drhc926afb2002-06-20 03:38:26 +00002062 switch( eDest ){
2063 case SRT_Union:
2064 case SRT_Except:
2065 case SRT_Discard:
2066 pOrderBy = 0;
2067 break;
2068 default:
2069 break;
drh22827922000-06-06 17:27:05 +00002070 }
2071
drh10e5e3c2000-06-08 00:19:02 +00002072 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002073 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002074 **
drh967e8b72000-06-21 13:59:10 +00002075 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002076 */
drh4794b982000-06-06 13:54:14 +00002077 for(i=0; i<pEList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00002078 if( sqliteExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002079 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002080 }
drh22827922000-06-06 17:27:05 +00002081 if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002082 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002083 }
2084 }
drhcce7d172000-05-31 15:34:51 +00002085 if( pWhere ){
drh6a3ea0e2003-05-02 14:32:12 +00002086 if( sqliteExprResolveIds(pParse, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00002087 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002088 }
2089 if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00002090 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002091 }
2092 }
drhc66c5a22002-12-03 02:34:49 +00002093 if( pHaving ){
2094 if( pGroupBy==0 ){
drhda93d232003-03-31 02:12:46 +00002095 sqliteErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
drhc66c5a22002-12-03 02:34:49 +00002096 goto select_end;
2097 }
drh6a3ea0e2003-05-02 14:32:12 +00002098 if( sqliteExprResolveIds(pParse, pTabList, pEList, pHaving) ){
drhc66c5a22002-12-03 02:34:49 +00002099 goto select_end;
2100 }
2101 if( sqliteExprCheck(pParse, pHaving, 1, &isAgg) ){
2102 goto select_end;
2103 }
2104 }
drhcce7d172000-05-31 15:34:51 +00002105 if( pOrderBy ){
2106 for(i=0; i<pOrderBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002107 int iCol;
drh22827922000-06-06 17:27:05 +00002108 Expr *pE = pOrderBy->a[i].pExpr;
drh88eee382003-01-31 17:16:36 +00002109 if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2110 sqliteExprDelete(pE);
2111 pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
2112 }
drh6a3ea0e2003-05-02 14:32:12 +00002113 if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
drh88eee382003-01-31 17:16:36 +00002114 goto select_end;
2115 }
2116 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
2117 goto select_end;
2118 }
drh92086432002-01-22 14:11:29 +00002119 if( sqliteExprIsConstant(pE) ){
drhe4de1fe2002-06-02 16:09:01 +00002120 if( sqliteExprIsInteger(pE, &iCol)==0 ){
drhda93d232003-03-31 02:12:46 +00002121 sqliteErrorMsg(pParse,
2122 "ORDER BY terms must not be non-integer constants");
drhe4de1fe2002-06-02 16:09:01 +00002123 goto select_end;
2124 }else if( iCol<=0 || iCol>pEList->nExpr ){
drhda93d232003-03-31 02:12:46 +00002125 sqliteErrorMsg(pParse,
2126 "ORDER BY column number %d out of range - should be "
drhe4de1fe2002-06-02 16:09:01 +00002127 "between 1 and %d", iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00002128 goto select_end;
2129 }
drhcce7d172000-05-31 15:34:51 +00002130 }
2131 }
2132 }
drh22827922000-06-06 17:27:05 +00002133 if( pGroupBy ){
2134 for(i=0; i<pGroupBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002135 int iCol;
drh22827922000-06-06 17:27:05 +00002136 Expr *pE = pGroupBy->a[i].pExpr;
drh88eee382003-01-31 17:16:36 +00002137 if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2138 sqliteExprDelete(pE);
2139 pE = pGroupBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00002140 }
drh6a3ea0e2003-05-02 14:32:12 +00002141 if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00002142 goto select_end;
drh22827922000-06-06 17:27:05 +00002143 }
2144 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00002145 goto select_end;
drh22827922000-06-06 17:27:05 +00002146 }
drh88eee382003-01-31 17:16:36 +00002147 if( sqliteExprIsConstant(pE) ){
2148 if( sqliteExprIsInteger(pE, &iCol)==0 ){
drhda93d232003-03-31 02:12:46 +00002149 sqliteErrorMsg(pParse,
2150 "GROUP BY terms must not be non-integer constants");
drh88eee382003-01-31 17:16:36 +00002151 goto select_end;
2152 }else if( iCol<=0 || iCol>pEList->nExpr ){
drhda93d232003-03-31 02:12:46 +00002153 sqliteErrorMsg(pParse,
2154 "GROUP BY column number %d out of range - should be "
drh88eee382003-01-31 17:16:36 +00002155 "between 1 and %d", iCol, pEList->nExpr);
drh88eee382003-01-31 17:16:36 +00002156 goto select_end;
2157 }
2158 }
drh22827922000-06-06 17:27:05 +00002159 }
2160 }
drhcce7d172000-05-31 15:34:51 +00002161
drhd820cb12002-02-18 03:21:45 +00002162 /* Begin generating code.
2163 */
2164 v = sqliteGetVdbe(pParse);
2165 if( v==0 ) goto select_end;
2166
drhe78e8282003-01-19 03:59:45 +00002167 /* Identify column names if we will be using them in a callback. This
2168 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002169 */
2170 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002171 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002172 }
2173
drhe5f50722003-07-19 00:44:14 +00002174 /* Check for the special case of a min() or max() function by itself
2175 ** in the result set.
2176 */
2177 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2178 rc = 0;
2179 goto select_end;
2180 }
2181
drhd820cb12002-02-18 03:21:45 +00002182 /* Generate code for all sub-queries in the FROM clause
2183 */
drhad3cab52002-05-24 02:04:32 +00002184 for(i=0; i<pTabList->nSrc; i++){
drh5cf590c2003-04-24 01:45:04 +00002185 const char *zSavedAuthContext;
drhc31c2eb2003-05-02 16:04:17 +00002186 int needRestoreContext;
2187
drha76b5df2002-02-23 02:32:10 +00002188 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002189 if( pTabList->a[i].zName!=0 ){
2190 zSavedAuthContext = pParse->zAuthContext;
2191 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002192 needRestoreContext = 1;
2193 }else{
2194 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002195 }
drh6a3ea0e2003-05-02 14:32:12 +00002196 sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable,
2197 pTabList->a[i].iCursor, p, i, &isAgg);
drhc31c2eb2003-05-02 16:04:17 +00002198 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002199 pParse->zAuthContext = zSavedAuthContext;
2200 }
drh1b2e0322002-03-03 02:49:51 +00002201 pTabList = p->pSrc;
2202 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002203 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002204 pOrderBy = p->pOrderBy;
2205 }
drh1b2e0322002-03-03 02:49:51 +00002206 pGroupBy = p->pGroupBy;
2207 pHaving = p->pHaving;
2208 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002209 }
2210
drh832508b2002-03-02 17:04:07 +00002211 /* Check to see if this is a subquery that can be "flattened" into its parent.
2212 ** If flattening is a possiblity, do so and return immediately.
2213 */
drh1b2e0322002-03-03 02:49:51 +00002214 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002215 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002216 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002217 return rc;
2218 }
drh832508b2002-03-02 17:04:07 +00002219
drh7b58dae2003-07-20 01:16:46 +00002220 /* Set the limiter.
2221 */
2222 computeLimitRegisters(pParse, p);
2223
drhe78e8282003-01-19 03:59:45 +00002224 /* Identify column types if we will be using a callback. This
2225 ** step is skipped if the output is going to a destination other
2226 ** than a callback.
drhe5f50722003-07-19 00:44:14 +00002227 **
2228 ** We have to do this separately from the creation of column names
2229 ** above because if the pTabList contains views then they will not
2230 ** have been resolved and we will not know the column types until
2231 ** now.
drhfcb78a42003-01-18 20:11:05 +00002232 */
2233 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002234 generateColumnTypes(pParse, pTabList, pEList);
drhfcb78a42003-01-18 20:11:05 +00002235 }
2236
drh2d0794e2002-03-03 03:03:52 +00002237 /* If the output is destined for a temporary table, open that table.
2238 */
2239 if( eDest==SRT_TempTable ){
2240 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
2241 }
2242
drh22827922000-06-06 17:27:05 +00002243 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002244 */
drhd820cb12002-02-18 03:21:45 +00002245 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002246 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002247 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002248 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002249 for(i=0; i<pEList->nExpr; i++){
2250 if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002251 goto select_end;
drh22827922000-06-06 17:27:05 +00002252 }
2253 }
2254 if( pGroupBy ){
2255 for(i=0; i<pGroupBy->nExpr; i++){
2256 if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002257 goto select_end;
drh22827922000-06-06 17:27:05 +00002258 }
2259 }
2260 }
2261 if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002262 goto select_end;
drh22827922000-06-06 17:27:05 +00002263 }
drh191b6902000-06-08 11:13:01 +00002264 if( pOrderBy ){
2265 for(i=0; i<pOrderBy->nExpr; i++){
2266 if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002267 goto select_end;
drh191b6902000-06-08 11:13:01 +00002268 }
2269 }
2270 }
drhefb72512000-05-31 20:00:52 +00002271 }
2272
drh22827922000-06-06 17:27:05 +00002273 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002274 */
2275 if( isAgg ){
drh99fcd712001-10-13 01:06:47 +00002276 sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002277 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002278 FuncDef *pFunc;
2279 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drh1350b032002-02-27 19:00:20 +00002280 sqliteVdbeAddOp(v, OP_AggInit, 0, i);
drh0bce8352002-02-28 00:41:10 +00002281 sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
drhe5095352002-02-24 03:25:14 +00002282 }
2283 }
drh1bee3d72001-10-15 00:44:35 +00002284 if( pGroupBy==0 ){
2285 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002286 sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002287 }
drhcce7d172000-05-31 15:34:51 +00002288 }
2289
drh19a775c2000-06-05 18:54:46 +00002290 /* Initialize the memory cell to NULL
2291 */
drhfef52082000-06-06 01:50:43 +00002292 if( eDest==SRT_Mem ){
drh99fcd712001-10-13 01:06:47 +00002293 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh8721ce42001-11-07 14:22:00 +00002294 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002295 }
2296
drh832508b2002-03-02 17:04:07 +00002297 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002298 */
drh19a775c2000-06-05 18:54:46 +00002299 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002300 distinct = pParse->nTab++;
drhc6b52df2002-01-04 03:09:29 +00002301 sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
drh832508b2002-03-02 17:04:07 +00002302 }else{
2303 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002304 }
drh832508b2002-03-02 17:04:07 +00002305
2306 /* Begin the database scan
2307 */
drh6a3ea0e2003-05-02 14:32:12 +00002308 pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 0,
drh68d2e592002-08-04 00:52:38 +00002309 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002310 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002311
drh22827922000-06-06 17:27:05 +00002312 /* Use the standard inner loop if we are not dealing with
2313 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002314 */
drhda9d6c42000-05-31 18:20:14 +00002315 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002316 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2317 iParm, pWInfo->iContinue, pWInfo->iBreak) ){
drh1d83f052002-02-17 00:30:36 +00002318 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002319 }
drhcce7d172000-05-31 15:34:51 +00002320 }
drhefb72512000-05-31 20:00:52 +00002321
drhe3184742002-06-19 14:27:05 +00002322 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002323 ** processing.
drhefb72512000-05-31 20:00:52 +00002324 */
drh22827922000-06-06 17:27:05 +00002325 else{
drh22827922000-06-06 17:27:05 +00002326 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002327 int lbl1;
drh22827922000-06-06 17:27:05 +00002328 for(i=0; i<pGroupBy->nExpr; i++){
2329 sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
2330 }
drh99fcd712001-10-13 01:06:47 +00002331 sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
drh491791a2002-07-18 00:34:09 +00002332 if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pGroupBy);
drh1bee3d72001-10-15 00:44:35 +00002333 lbl1 = sqliteVdbeMakeLabel(v);
drh99fcd712001-10-13 01:06:47 +00002334 sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh22827922000-06-06 17:27:05 +00002335 for(i=0; i<pParse->nAgg; i++){
2336 if( pParse->aAgg[i].isAgg ) continue;
2337 sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
drh99fcd712001-10-13 01:06:47 +00002338 sqliteVdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002339 }
drh22827922000-06-06 17:27:05 +00002340 sqliteVdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002341 }
drh22827922000-06-06 17:27:05 +00002342 for(i=0; i<pParse->nAgg; i++){
2343 Expr *pE;
drh0bce8352002-02-28 00:41:10 +00002344 int j;
drh22827922000-06-06 17:27:05 +00002345 if( !pParse->aAgg[i].isAgg ) continue;
2346 pE = pParse->aAgg[i].pExpr;
drh22827922000-06-06 17:27:05 +00002347 assert( pE->op==TK_AGG_FUNCTION );
drh0bce8352002-02-28 00:41:10 +00002348 if( pE->pList ){
2349 for(j=0; j<pE->pList->nExpr; j++){
2350 sqliteExprCode(pParse, pE->pList->a[j].pExpr);
2351 }
drhe5095352002-02-24 03:25:14 +00002352 }
drh0bce8352002-02-28 00:41:10 +00002353 sqliteVdbeAddOp(v, OP_Integer, i, 0);
drhf55f25f2002-02-28 01:46:11 +00002354 sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
drh0bce8352002-02-28 00:41:10 +00002355 assert( pParse->aAgg[i].pFunc!=0 );
2356 assert( pParse->aAgg[i].pFunc->xStep!=0 );
2357 sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002358 }
drhcce7d172000-05-31 15:34:51 +00002359 }
2360
2361 /* End the database scan loop.
2362 */
2363 sqliteWhereEnd(pWInfo);
2364
drh22827922000-06-06 17:27:05 +00002365 /* If we are processing aggregates, we need to set up a second loop
2366 ** over all of the aggregate values and process them.
2367 */
2368 if( isAgg ){
2369 int endagg = sqliteVdbeMakeLabel(v);
2370 int startagg;
drh99fcd712001-10-13 01:06:47 +00002371 startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002372 pParse->useAgg = 1;
2373 if( pHaving ){
drhf5905aa2002-05-26 20:54:33 +00002374 sqliteExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002375 }
drhdf199a22002-06-14 22:38:41 +00002376 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2377 iParm, startagg, endagg) ){
drh1d83f052002-02-17 00:30:36 +00002378 goto select_end;
drh22827922000-06-06 17:27:05 +00002379 }
drh99fcd712001-10-13 01:06:47 +00002380 sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
2381 sqliteVdbeResolveLabel(v, endagg);
2382 sqliteVdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002383 pParse->useAgg = 0;
2384 }
2385
drhcce7d172000-05-31 15:34:51 +00002386 /* If there is an ORDER BY clause, then we need to sort the results
2387 ** and send them to the callback one by one.
2388 */
2389 if( pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00002390 generateSortTail(p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002391 }
drh6a535342001-10-19 16:44:56 +00002392
drhf620b4e2004-02-09 14:37:50 +00002393 /* If this was a subquery, we have now converted the subquery into a
2394 ** temporary table. So delete the subquery structure from the parent
2395 ** to prevent this subquery from being evaluated again and to force the
2396 ** the use of the temporary table.
2397 */
2398 if( pParent ){
2399 assert( pParent->pSrc->nSrc>parentTab );
2400 assert( pParent->pSrc->a[parentTab].pSelect==p );
2401 sqliteSelectDelete(p);
2402 pParent->pSrc->a[parentTab].pSelect = 0;
2403 }
2404
drh1d83f052002-02-17 00:30:36 +00002405 /* The SELECT was successfully coded. Set the return code to 0
2406 ** to indicate no errors.
2407 */
2408 rc = 0;
2409
2410 /* Control jumps to here if an error is encountered above, or upon
2411 ** successful coding of the SELECT.
2412 */
2413select_end:
2414 sqliteAggregateInfoReset(pParse);
2415 return rc;
drhcce7d172000-05-31 15:34:51 +00002416}