blob: 22df1d15eebac609d00df37021bdcc83cce6b52a [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**
drhef0cae52003-07-16 02:19:37 +000015** $Id: select.c,v 1.142 2003/07/16 02:19:38 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{
45 pNew->pEList = pEList;
46 pNew->pSrc = pSrc;
47 pNew->pWhere = pWhere;
48 pNew->pGroupBy = pGroupBy;
49 pNew->pHaving = pHaving;
50 pNew->pOrderBy = pOrderBy;
51 pNew->isDistinct = isDistinct;
52 pNew->op = TK_SELECT;
drh9bbca4c2001-11-06 04:00:18 +000053 pNew->nLimit = nLimit;
54 pNew->nOffset = nOffset;
drhdaffd0e2001-04-11 14:28:42 +000055 }
drh9bb61fe2000-06-05 16:01:39 +000056 return pNew;
57}
58
59/*
drh01f3f252002-05-24 16:14:15 +000060** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
61** type of join. Return an integer constant that expresses that type
62** in terms of the following bit values:
63**
64** JT_INNER
65** JT_OUTER
66** JT_NATURAL
67** JT_LEFT
68** JT_RIGHT
69**
70** A full outer join is the combination of JT_LEFT and JT_RIGHT.
71**
72** If an illegal or unsupported join type is seen, then still return
73** a join type, but put an error in the pParse structure.
74*/
75int sqliteJoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
76 int jointype = 0;
77 Token *apAll[3];
78 Token *p;
79 static struct {
80 const char *zKeyword;
81 int nChar;
82 int code;
83 } keywords[] = {
84 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000085 { "left", 4, JT_LEFT|JT_OUTER },
86 { "right", 5, JT_RIGHT|JT_OUTER },
87 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +000088 { "outer", 5, JT_OUTER },
89 { "inner", 5, JT_INNER },
90 { "cross", 5, JT_INNER },
91 };
92 int i, j;
93 apAll[0] = pA;
94 apAll[1] = pB;
95 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +000096 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +000097 p = apAll[i];
98 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
99 if( p->n==keywords[j].nChar
100 && sqliteStrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
101 jointype |= keywords[j].code;
102 break;
103 }
104 }
105 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
106 jointype |= JT_ERROR;
107 break;
108 }
109 }
drhad2d8302002-05-24 20:31:36 +0000110 if(
111 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000112 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000113 ){
drh01f3f252002-05-24 16:14:15 +0000114 static Token dummy = { 0, 0 };
115 char *zSp1 = " ", *zSp2 = " ";
116 if( pB==0 ){ pB = &dummy; zSp1 = 0; }
117 if( pC==0 ){ pC = &dummy; zSp2 = 0; }
118 sqliteSetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
119 pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
120 pParse->nErr++;
121 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000122 }else if( jointype & JT_RIGHT ){
drhda93d232003-03-31 02:12:46 +0000123 sqliteErrorMsg(pParse,
124 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000125 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000126 }
127 return jointype;
128}
129
130/*
drhad2d8302002-05-24 20:31:36 +0000131** Return the index of a column in a table. Return -1 if the column
132** is not contained in the table.
133*/
134static int columnIndex(Table *pTab, const char *zCol){
135 int i;
136 for(i=0; i<pTab->nCol; i++){
137 if( sqliteStrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
138 }
139 return -1;
140}
141
142/*
143** Add a term to the WHERE expression in *ppExpr that requires the
144** zCol column to be equal in the two tables pTab1 and pTab2.
145*/
146static void addWhereTerm(
147 const char *zCol, /* Name of the column */
148 const Table *pTab1, /* First table */
149 const Table *pTab2, /* Second table */
150 Expr **ppExpr /* Add the equality term to this expression */
151){
152 Token dummy;
153 Expr *pE1a, *pE1b, *pE1c;
154 Expr *pE2a, *pE2b, *pE2c;
155 Expr *pE;
156
157 dummy.z = zCol;
158 dummy.n = strlen(zCol);
drh4b59ab52002-08-24 18:24:51 +0000159 dummy.dyn = 0;
drhad2d8302002-05-24 20:31:36 +0000160 pE1a = sqliteExpr(TK_ID, 0, 0, &dummy);
161 pE2a = sqliteExpr(TK_ID, 0, 0, &dummy);
162 dummy.z = pTab1->zName;
163 dummy.n = strlen(dummy.z);
164 pE1b = sqliteExpr(TK_ID, 0, 0, &dummy);
165 dummy.z = pTab2->zName;
166 dummy.n = strlen(dummy.z);
167 pE2b = sqliteExpr(TK_ID, 0, 0, &dummy);
168 pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0);
169 pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0);
170 pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000171 ExprSetProperty(pE, EP_FromJoin);
drhad2d8302002-05-24 20:31:36 +0000172 if( *ppExpr ){
173 *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0);
174 }else{
175 *ppExpr = pE;
176 }
177}
178
179/*
drh1f162302002-10-27 19:35:33 +0000180** Set the EP_FromJoin property on all terms of the given expression.
drh1cc093c2002-06-24 22:01:57 +0000181**
drhe78e8282003-01-19 03:59:45 +0000182** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000183** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000184** join restriction specified in the ON or USING clause and not a part
185** of the more general WHERE clause. These terms are moved over to the
186** WHERE clause during join processing but we need to remember that they
187** originated in the ON or USING clause.
drh1cc093c2002-06-24 22:01:57 +0000188*/
189static void setJoinExpr(Expr *p){
190 while( p ){
drh1f162302002-10-27 19:35:33 +0000191 ExprSetProperty(p, EP_FromJoin);
drh1cc093c2002-06-24 22:01:57 +0000192 setJoinExpr(p->pLeft);
193 p = p->pRight;
194 }
195}
196
197/*
drhad2d8302002-05-24 20:31:36 +0000198** This routine processes the join information for a SELECT statement.
199** ON and USING clauses are converted into extra terms of the WHERE clause.
200** NATURAL joins also create extra WHERE clause terms.
201**
202** This routine returns the number of errors encountered.
203*/
204static int sqliteProcessJoin(Parse *pParse, Select *p){
205 SrcList *pSrc;
206 int i, j;
207 pSrc = p->pSrc;
208 for(i=0; i<pSrc->nSrc-1; i++){
209 struct SrcList_item *pTerm = &pSrc->a[i];
210 struct SrcList_item *pOther = &pSrc->a[i+1];
211
212 if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
213
214 /* When the NATURAL keyword is present, add WHERE clause terms for
215 ** every column that the two tables have in common.
216 */
217 if( pTerm->jointype & JT_NATURAL ){
218 Table *pTab;
219 if( pTerm->pOn || pTerm->pUsing ){
drhda93d232003-03-31 02:12:46 +0000220 sqliteErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000221 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000222 return 1;
223 }
224 pTab = pTerm->pTab;
225 for(j=0; j<pTab->nCol; j++){
226 if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
227 addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
228 }
229 }
230 }
231
232 /* Disallow both ON and USING clauses in the same join
233 */
234 if( pTerm->pOn && pTerm->pUsing ){
drhda93d232003-03-31 02:12:46 +0000235 sqliteErrorMsg(pParse, "cannot have both ON and USING "
236 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000237 return 1;
238 }
239
240 /* Add the ON clause to the end of the WHERE clause, connected by
241 ** and AND operator.
242 */
243 if( pTerm->pOn ){
drh1cc093c2002-06-24 22:01:57 +0000244 setJoinExpr(pTerm->pOn);
drhad2d8302002-05-24 20:31:36 +0000245 if( p->pWhere==0 ){
246 p->pWhere = pTerm->pOn;
247 }else{
248 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0);
249 }
250 pTerm->pOn = 0;
251 }
252
253 /* Create extra terms on the WHERE clause for each column named
254 ** in the USING clause. Example: If the two tables to be joined are
255 ** A and B and the USING clause names X, Y, and Z, then add this
256 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
257 ** Report an error if any column mentioned in the USING clause is
258 ** not contained in both tables to be joined.
259 */
260 if( pTerm->pUsing ){
261 IdList *pList;
262 int j;
263 assert( i<pSrc->nSrc-1 );
264 pList = pTerm->pUsing;
265 for(j=0; j<pList->nId; j++){
drhbf5cd972002-06-24 12:20:23 +0000266 if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
267 columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
drhda93d232003-03-31 02:12:46 +0000268 sqliteErrorMsg(pParse, "cannot join using column %s - column "
269 "not present in both tables", pList->a[j].zName);
drhad2d8302002-05-24 20:31:36 +0000270 return 1;
271 }
drhbf5cd972002-06-24 12:20:23 +0000272 addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000273 }
274 }
275 }
276 return 0;
277}
278
279/*
drh1f162302002-10-27 19:35:33 +0000280** This routine implements a minimal Oracle8 join syntax immulation.
281** The precise oracle8 syntax is not implemented - it is easy enough
282** to get this routine confused. But this routine does make it possible
283** to write a single SQL statement that does a left outer join in both
284** oracle8 and in SQLite.
285**
286** This routine looks for TK_COLUMN expression nodes that are marked
287** with the EP_Oracle8Join property. Such nodes are generated by a
288** column name (either "column" or "table.column") that is followed by
289** the special "(+)" operator. If the table of the column marked with
290** the (+) operator is the second are subsequent table in a join, then
291** that table becomes the left table in a LEFT OUTER JOIN. The expression
292** that uses that table becomes part of the ON clause for the join.
293**
294** It is important to enphasize that this is not exactly how oracle8
295** works. But it is close enough so that one can construct queries that
296** will work correctly for both SQLite and Oracle8.
297*/
298static int sqliteOracle8JoinFixup(
drh1f162302002-10-27 19:35:33 +0000299 SrcList *pSrc, /* List of tables being joined */
300 Expr *pWhere /* The WHERE clause of the SELECT statement */
301){
302 int rc = 0;
303 if( ExprHasProperty(pWhere, EP_Oracle8Join) && pWhere->op==TK_COLUMN ){
drh6a3ea0e2003-05-02 14:32:12 +0000304 int idx;
305 for(idx=0; idx<pSrc->nSrc; idx++){
306 if( pSrc->a[idx].iCursor==pWhere->iTable ) break;
307 }
drh1f162302002-10-27 19:35:33 +0000308 assert( idx>=0 && idx<pSrc->nSrc );
309 if( idx>0 ){
310 pSrc->a[idx-1].jointype &= ~JT_INNER;
311 pSrc->a[idx-1].jointype |= JT_OUTER|JT_LEFT;
312 return 1;
313 }
314 }
315 if( pWhere->pRight ){
drh6a3ea0e2003-05-02 14:32:12 +0000316 rc = sqliteOracle8JoinFixup(pSrc, pWhere->pRight);
drh1f162302002-10-27 19:35:33 +0000317 }
318 if( pWhere->pLeft ){
drh6a3ea0e2003-05-02 14:32:12 +0000319 rc |= sqliteOracle8JoinFixup(pSrc, pWhere->pLeft);
drh1f162302002-10-27 19:35:33 +0000320 }
321 if( pWhere->pList ){
322 int i;
323 ExprList *pList = pWhere->pList;
324 for(i=0; i<pList->nExpr && rc==0; i++){
drh6a3ea0e2003-05-02 14:32:12 +0000325 rc |= sqliteOracle8JoinFixup(pSrc, pList->a[i].pExpr);
drh1f162302002-10-27 19:35:33 +0000326 }
327 }
328 if( rc==1 && (pWhere->op==TK_AND || pWhere->op==TK_EQ) ){
329 setJoinExpr(pWhere);
330 rc = 0;
331 }
332 return rc;
333}
334
335/*
drh9bb61fe2000-06-05 16:01:39 +0000336** Delete the given Select structure and all of its substructures.
337*/
338void sqliteSelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000339 if( p==0 ) return;
drh9bb61fe2000-06-05 16:01:39 +0000340 sqliteExprListDelete(p->pEList);
drhad3cab52002-05-24 02:04:32 +0000341 sqliteSrcListDelete(p->pSrc);
drh9bb61fe2000-06-05 16:01:39 +0000342 sqliteExprDelete(p->pWhere);
343 sqliteExprListDelete(p->pGroupBy);
344 sqliteExprDelete(p->pHaving);
345 sqliteExprListDelete(p->pOrderBy);
drh82c3d632000-06-06 21:56:07 +0000346 sqliteSelectDelete(p->pPrior);
drha76b5df2002-02-23 02:32:10 +0000347 sqliteFree(p->zSelect);
drh9bb61fe2000-06-05 16:01:39 +0000348 sqliteFree(p);
349}
350
351/*
drh22827922000-06-06 17:27:05 +0000352** Delete the aggregate information from the parse structure.
353*/
drh1d83f052002-02-17 00:30:36 +0000354static void sqliteAggregateInfoReset(Parse *pParse){
drh22827922000-06-06 17:27:05 +0000355 sqliteFree(pParse->aAgg);
356 pParse->aAgg = 0;
357 pParse->nAgg = 0;
drh22827922000-06-06 17:27:05 +0000358 pParse->useAgg = 0;
359}
360
361/*
drhc926afb2002-06-20 03:38:26 +0000362** Insert code into "v" that will push the record on the top of the
363** stack into the sorter.
364*/
365static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
366 char *zSortOrder;
367 int i;
368 zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
369 if( zSortOrder==0 ) return;
370 for(i=0; i<pOrderBy->nExpr; i++){
drh38640e12002-07-05 21:42:36 +0000371 int order = pOrderBy->a[i].sortOrder;
372 int type;
373 int c;
374 if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
375 type = SQLITE_SO_TEXT;
376 }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
377 type = SQLITE_SO_NUM;
drh491791a2002-07-18 00:34:09 +0000378 }else if( pParse->db->file_format>=4 ){
drh38640e12002-07-05 21:42:36 +0000379 type = sqliteExprType(pOrderBy->a[i].pExpr);
380 }else{
381 type = SQLITE_SO_NUM;
382 }
383 if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
384 c = type==SQLITE_SO_TEXT ? 'A' : '+';
385 }else{
386 c = type==SQLITE_SO_TEXT ? 'D' : '-';
387 }
388 zSortOrder[i] = c;
drhc926afb2002-06-20 03:38:26 +0000389 sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
390 }
391 zSortOrder[pOrderBy->nExpr] = 0;
392 sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0);
393 sqliteVdbeChangeP3(v, -1, zSortOrder, strlen(zSortOrder));
394 sqliteFree(zSortOrder);
395 sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
396}
397
398/*
drh38640e12002-07-05 21:42:36 +0000399** This routine adds a P3 argument to the last VDBE opcode that was
400** inserted. The P3 argument added is a string suitable for the
401** OP_MakeKey or OP_MakeIdxKey opcodes. The string consists of
402** characters 't' or 'n' depending on whether or not the various
403** fields of the key to be generated should be treated as numeric
404** or as text. See the OP_MakeKey and OP_MakeIdxKey opcode
405** documentation for additional information about the P3 string.
406** See also the sqliteAddIdxKeyType() routine.
407*/
408void sqliteAddKeyType(Vdbe *v, ExprList *pEList){
409 int nColumn = pEList->nExpr;
410 char *zType = sqliteMalloc( nColumn+1 );
411 int i;
412 if( zType==0 ) return;
413 for(i=0; i<nColumn; i++){
414 zType[i] = sqliteExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
415 }
416 zType[i] = 0;
417 sqliteVdbeChangeP3(v, -1, zType, nColumn);
418 sqliteFree(zType);
419}
420
421/*
drh22827922000-06-06 17:27:05 +0000422** This routine generates the code for the inside of the inner loop
423** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000424**
drh38640e12002-07-05 21:42:36 +0000425** If srcTab and nColumn are both zero, then the pEList expressions
426** are evaluated in order to get the data for this row. If nColumn>0
427** then data is pulled from srcTab and pEList is used only to get the
428** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000429*/
430static int selectInnerLoop(
431 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000432 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000433 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000434 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000435 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000436 ExprList *pOrderBy, /* If not NULL, sort results using this key */
437 int distinct, /* If >=0, make sure results are distinct */
438 int eDest, /* How to dispose of the results */
439 int iParm, /* An argument to the disposal method */
440 int iContinue, /* Jump here to continue with next row */
441 int iBreak /* Jump here to break out of the inner loop */
442){
443 Vdbe *v = pParse->pVdbe;
444 int i;
drh38640e12002-07-05 21:42:36 +0000445
drhdaffd0e2001-04-11 14:28:42 +0000446 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000447 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000448
drhdf199a22002-06-14 22:38:41 +0000449 /* If there was a LIMIT clause on the SELECT statement, then do the check
450 ** to see if this row should be output.
451 */
452 if( pOrderBy==0 ){
453 if( p->nOffset>0 ){
drhd11d3822002-06-21 23:01:49 +0000454 int addr = sqliteVdbeCurrentAddr(v);
455 sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+2);
456 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
drhdf199a22002-06-14 22:38:41 +0000457 }
drhd11d3822002-06-21 23:01:49 +0000458 if( p->nLimit>=0 ){
459 sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, iBreak);
drhdf199a22002-06-14 22:38:41 +0000460 }
461 }
462
drh967e8b72000-06-21 13:59:10 +0000463 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000464 */
drh38640e12002-07-05 21:42:36 +0000465 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000466 for(i=0; i<nColumn; i++){
drh99fcd712001-10-13 01:06:47 +0000467 sqliteVdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000468 }
drh38640e12002-07-05 21:42:36 +0000469 }else{
470 nColumn = pEList->nExpr;
471 for(i=0; i<pEList->nExpr; i++){
472 sqliteExprCode(pParse, pEList->a[i].pExpr);
473 }
drh22827922000-06-06 17:27:05 +0000474 }
475
drhdaffd0e2001-04-11 14:28:42 +0000476 /* If the DISTINCT keyword was present on the SELECT statement
477 ** and this row has been seen before, then do not make this row
478 ** part of the result.
drh22827922000-06-06 17:27:05 +0000479 */
drhf5905aa2002-05-26 20:54:33 +0000480 if( distinct>=0 && pEList && pEList->nExpr>0 ){
drh0bd1f4e2002-06-06 18:54:39 +0000481#if NULL_ALWAYS_DISTINCT
482 sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7);
483#endif
drh99fcd712001-10-13 01:06:47 +0000484 sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
drh491791a2002-07-18 00:34:09 +0000485 if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pEList);
drhf5905aa2002-05-26 20:54:33 +0000486 sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
drh99fcd712001-10-13 01:06:47 +0000487 sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
488 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
drh99fcd712001-10-13 01:06:47 +0000489 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh6b125452002-01-28 15:53:03 +0000490 sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
drh22827922000-06-06 17:27:05 +0000491 }
drh82c3d632000-06-06 21:56:07 +0000492
drhc926afb2002-06-20 03:38:26 +0000493 switch( eDest ){
494 /* In this mode, write each query result to the key of the temporary
495 ** table iParm.
496 */
497 case SRT_Union: {
498 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
499 sqliteVdbeAddOp(v, OP_String, 0, 0);
500 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
501 break;
drh22827922000-06-06 17:27:05 +0000502 }
drh22827922000-06-06 17:27:05 +0000503
drhc926afb2002-06-20 03:38:26 +0000504 /* Store the result as data using a unique key.
505 */
506 case SRT_Table:
507 case SRT_TempTable: {
508 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
509 if( pOrderBy ){
510 pushOntoSorter(pParse, v, pOrderBy);
511 }else{
512 sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
513 sqliteVdbeAddOp(v, OP_Pull, 1, 0);
514 sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
515 }
516 break;
517 }
drh82c3d632000-06-06 21:56:07 +0000518
drhc926afb2002-06-20 03:38:26 +0000519 /* Construct a record from the query result, but instead of
520 ** saving that record, use it as a key to delete elements from
521 ** the temporary table iParm.
522 */
523 case SRT_Except: {
524 int addr;
525 addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
526 sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
527 sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
528 break;
529 }
drh5974a302000-06-07 14:42:26 +0000530
drhc926afb2002-06-20 03:38:26 +0000531 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
532 ** then there should be a single item on the stack. Write this
533 ** item into the set table with bogus data.
534 */
535 case SRT_Set: {
drha9f9d1c2002-06-29 02:20:08 +0000536 int lbl = sqliteVdbeMakeLabel(v);
drhc926afb2002-06-20 03:38:26 +0000537 assert( nColumn==1 );
drha9f9d1c2002-06-29 02:20:08 +0000538 sqliteVdbeAddOp(v, OP_IsNull, -1, lbl);
drhc926afb2002-06-20 03:38:26 +0000539 if( pOrderBy ){
540 pushOntoSorter(pParse, v, pOrderBy);
541 }else{
drha9f9d1c2002-06-29 02:20:08 +0000542 sqliteVdbeAddOp(v, OP_String, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000543 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
544 }
drha9f9d1c2002-06-29 02:20:08 +0000545 sqliteVdbeResolveLabel(v, lbl);
drhc926afb2002-06-20 03:38:26 +0000546 break;
547 }
drh22827922000-06-06 17:27:05 +0000548
drhc926afb2002-06-20 03:38:26 +0000549 /* If this is a scalar select that is part of an expression, then
550 ** store the results in the appropriate memory cell and break out
551 ** of the scan loop.
552 */
553 case SRT_Mem: {
554 assert( nColumn==1 );
555 if( pOrderBy ){
556 pushOntoSorter(pParse, v, pOrderBy);
557 }else{
558 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
559 sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
560 }
561 break;
562 }
drh22827922000-06-06 17:27:05 +0000563
drhf46f9052002-06-22 02:33:38 +0000564 /* Send the data to the callback function.
565 */
566 case SRT_Callback:
567 case SRT_Sorter: {
568 if( pOrderBy ){
569 sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
570 pushOntoSorter(pParse, v, pOrderBy);
571 }else{
572 assert( eDest==SRT_Callback );
573 sqliteVdbeAddOp(v, OP_Callback, nColumn, 0);
574 }
575 break;
576 }
577
drh142e30d2002-08-28 03:00:58 +0000578 /* Invoke a subroutine to handle the results. The subroutine itself
579 ** is responsible for popping the results off of the stack.
580 */
581 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000582 if( pOrderBy ){
583 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
584 pushOntoSorter(pParse, v, pOrderBy);
585 }else{
586 sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
587 }
drh142e30d2002-08-28 03:00:58 +0000588 break;
589 }
590
drhc926afb2002-06-20 03:38:26 +0000591 /* Discard the results. This is used for SELECT statements inside
592 ** the body of a TRIGGER. The purpose of such selects is to call
593 ** user-defined functions that have side effects. We do not care
594 ** about the actual results of the select.
595 */
drhc926afb2002-06-20 03:38:26 +0000596 default: {
drhf46f9052002-06-22 02:33:38 +0000597 assert( eDest==SRT_Discard );
598 sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000599 break;
600 }
drh82c3d632000-06-06 21:56:07 +0000601 }
602 return 0;
603}
604
605/*
drhd8bc7082000-06-07 23:51:50 +0000606** If the inner loop was generated using a non-null pOrderBy argument,
607** then the results were placed in a sorter. After the loop is terminated
608** we need to run the sorter and output the results. The following
609** routine generates the code needed to do that.
610*/
drhc926afb2002-06-20 03:38:26 +0000611static void generateSortTail(
612 Select *p, /* The SELECT statement */
613 Vdbe *v, /* Generate code into this VDBE */
614 int nColumn, /* Number of columns of data */
615 int eDest, /* Write the sorted results here */
616 int iParm /* Optional parameter associated with eDest */
617){
drhd8bc7082000-06-07 23:51:50 +0000618 int end = sqliteVdbeMakeLabel(v);
619 int addr;
drhf46f9052002-06-22 02:33:38 +0000620 if( eDest==SRT_Sorter ) return;
drh99fcd712001-10-13 01:06:47 +0000621 sqliteVdbeAddOp(v, OP_Sort, 0, 0);
622 addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end);
drhdf199a22002-06-14 22:38:41 +0000623 if( p->nOffset>0 ){
drhd11d3822002-06-21 23:01:49 +0000624 sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+4);
625 sqliteVdbeAddOp(v, OP_Pop, 1, 0);
626 sqliteVdbeAddOp(v, OP_Goto, 0, addr);
drhdf199a22002-06-14 22:38:41 +0000627 }
drhd11d3822002-06-21 23:01:49 +0000628 if( p->nLimit>=0 ){
629 sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, end);
drhdf199a22002-06-14 22:38:41 +0000630 }
drhc926afb2002-06-20 03:38:26 +0000631 switch( eDest ){
632 case SRT_Callback: {
633 sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0);
634 break;
635 }
636 case SRT_Table:
637 case SRT_TempTable: {
638 sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
639 sqliteVdbeAddOp(v, OP_Pull, 1, 0);
640 sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
641 break;
642 }
643 case SRT_Set: {
644 assert( nColumn==1 );
645 sqliteVdbeAddOp(v, OP_IsNull, -1, sqliteVdbeCurrentAddr(v)+3);
646 sqliteVdbeAddOp(v, OP_String, 0, 0);
647 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
648 break;
649 }
650 case SRT_Mem: {
651 assert( nColumn==1 );
652 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
653 sqliteVdbeAddOp(v, OP_Goto, 0, end);
654 break;
655 }
drhac82fcf2002-09-08 17:23:41 +0000656 case SRT_Subroutine: {
657 int i;
658 for(i=0; i<nColumn; i++){
659 sqliteVdbeAddOp(v, OP_Column, -1-i, i);
660 }
661 sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
662 sqliteVdbeAddOp(v, OP_Pop, 1, 0);
663 break;
664 }
drhc926afb2002-06-20 03:38:26 +0000665 default: {
drhf46f9052002-06-22 02:33:38 +0000666 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000667 break;
668 }
669 }
drh99fcd712001-10-13 01:06:47 +0000670 sqliteVdbeAddOp(v, OP_Goto, 0, addr);
671 sqliteVdbeResolveLabel(v, end);
drha8b38d22001-11-01 14:41:34 +0000672 sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000673}
674
675/*
drhfcb78a42003-01-18 20:11:05 +0000676** Generate code that will tell the VDBE the datatypes of
677** columns in the result set.
drhe78e8282003-01-19 03:59:45 +0000678**
679** This routine only generates code if the "PRAGMA show_datatypes=on"
680** has been executed. The datatypes are reported out in the azCol
681** parameter to the callback function. The first N azCol[] entries
682** are the names of the columns, and the second N entries are the
683** datatypes for the columns.
684**
685** The "datatype" for a result that is a column of a type is the
686** datatype definition extracted from the CREATE TABLE statement.
687** The datatype for an expression is either TEXT or NUMERIC. The
688** datatype for a ROWID field is INTEGER.
drhfcb78a42003-01-18 20:11:05 +0000689*/
690static void generateColumnTypes(
691 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000692 SrcList *pTabList, /* List of tables */
693 ExprList *pEList /* Expressions defining the result set */
694){
695 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000696 int i, j;
drh326dce72003-01-29 14:06:07 +0000697 if( pParse->useCallback && (pParse->db->flags & SQLITE_ReportTypes)==0 ){
698 return;
699 }
drhfcb78a42003-01-18 20:11:05 +0000700 for(i=0; i<pEList->nExpr; i++){
701 Expr *p = pEList->a[i].pExpr;
702 char *zType = 0;
703 if( p==0 ) continue;
704 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000705 Table *pTab;
drhfcb78a42003-01-18 20:11:05 +0000706 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000707 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
708 assert( j<pTabList->nSrc );
709 pTab = pTabList->a[j].pTab;
drhfcb78a42003-01-18 20:11:05 +0000710 if( iCol<0 ) iCol = pTab->iPKey;
711 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
712 if( iCol<0 ){
713 zType = "INTEGER";
714 }else{
715 zType = pTab->aCol[iCol].zType;
716 }
717 }else{
718 if( sqliteExprType(p)==SQLITE_SO_TEXT ){
719 zType = "TEXT";
720 }else{
721 zType = "NUMERIC";
722 }
723 }
724 sqliteVdbeAddOp(v, OP_ColumnName, i + pEList->nExpr, 0);
725 sqliteVdbeChangeP3(v, -1, zType, P3_STATIC);
726 }
727}
728
729/*
730** Generate code that will tell the VDBE the names of columns
731** in the result set. This information is used to provide the
732** azCol[] vaolues in the callback.
drh82c3d632000-06-06 21:56:07 +0000733*/
drh832508b2002-03-02 17:04:07 +0000734static void generateColumnNames(
735 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000736 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000737 ExprList *pEList /* Expressions defining the result set */
738){
drhd8bc7082000-06-07 23:51:50 +0000739 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000740 int i, j;
drhdaffd0e2001-04-11 14:28:42 +0000741 if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000742 pParse->colNamesSet = 1;
drh82c3d632000-06-06 21:56:07 +0000743 for(i=0; i<pEList->nExpr; i++){
744 Expr *p;
drhb1363202002-06-26 02:45:03 +0000745 char *zType = 0;
drh1bee3d72001-10-15 00:44:35 +0000746 int showFullNames;
drh5a387052003-01-11 14:19:51 +0000747 p = pEList->a[i].pExpr;
748 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000749 if( pEList->a[i].zName ){
750 char *zName = pEList->a[i].zName;
drh99fcd712001-10-13 01:06:47 +0000751 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
752 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000753 continue;
754 }
drh1bee3d72001-10-15 00:44:35 +0000755 showFullNames = (pParse->db->flags & SQLITE_FullColNames)!=0;
drhfa173a72002-07-10 21:26:00 +0000756 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000757 Table *pTab;
drh97665872002-02-13 23:22:53 +0000758 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000759 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000760 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
761 assert( j<pTabList->nSrc );
762 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000763 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000764 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000765 if( iCol<0 ){
766 zCol = "_ROWID_";
767 zType = "INTEGER";
768 }else{
769 zCol = pTab->aCol[iCol].zName;
770 zType = pTab->aCol[iCol].zType;
771 }
drh6977fea2002-10-22 23:38:04 +0000772 if( p->span.z && p->span.z[0] && !showFullNames ){
drhfa173a72002-07-10 21:26:00 +0000773 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
drh6977fea2002-10-22 23:38:04 +0000774 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
drhfa173a72002-07-10 21:26:00 +0000775 sqliteVdbeCompressSpace(v, addr);
776 }else if( pTabList->nSrc>1 || showFullNames ){
drh82c3d632000-06-06 21:56:07 +0000777 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000778 char *zTab;
779
drh6a3ea0e2003-05-02 14:32:12 +0000780 zTab = pTabList->a[j].zAlias;
drh01a34662001-10-20 12:30:10 +0000781 if( showFullNames || zTab==0 ) zTab = pTab->zName;
drh97665872002-02-13 23:22:53 +0000782 sqliteSetString(&zName, zTab, ".", zCol, 0);
drh99fcd712001-10-13 01:06:47 +0000783 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
784 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000785 sqliteFree(zName);
786 }else{
drh99fcd712001-10-13 01:06:47 +0000787 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
drh22f70c32002-02-18 01:17:00 +0000788 sqliteVdbeChangeP3(v, -1, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000789 }
drh6977fea2002-10-22 23:38:04 +0000790 }else if( p->span.z && p->span.z[0] ){
drhfa173a72002-07-10 21:26:00 +0000791 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
drh6977fea2002-10-22 23:38:04 +0000792 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
drh1bee3d72001-10-15 00:44:35 +0000793 sqliteVdbeCompressSpace(v, addr);
794 }else{
795 char zName[30];
796 assert( p->op!=TK_COLUMN || pTabList==0 );
797 sprintf(zName, "column%d", i+1);
798 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
799 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000800 }
801 }
802}
803
804/*
drhd8bc7082000-06-07 23:51:50 +0000805** Name of the connection operator, used for error messages.
806*/
807static const char *selectOpName(int id){
808 char *z;
809 switch( id ){
810 case TK_ALL: z = "UNION ALL"; break;
811 case TK_INTERSECT: z = "INTERSECT"; break;
812 case TK_EXCEPT: z = "EXCEPT"; break;
813 default: z = "UNION"; break;
814 }
815 return z;
816}
817
818/*
drh315555c2002-10-20 15:53:03 +0000819** Forward declaration
820*/
821static int fillInColumnList(Parse*, Select*);
822
823/*
drh22f70c32002-02-18 01:17:00 +0000824** Given a SELECT statement, generate a Table structure that describes
825** the result set of that SELECT.
826*/
827Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
828 Table *pTab;
829 int i;
830 ExprList *pEList;
drh22f70c32002-02-18 01:17:00 +0000831
832 if( fillInColumnList(pParse, pSelect) ){
833 return 0;
834 }
835 pTab = sqliteMalloc( sizeof(Table) );
836 if( pTab==0 ){
837 return 0;
838 }
839 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
840 pEList = pSelect->pEList;
841 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000842 assert( pTab->nCol>0 );
drh22f70c32002-02-18 01:17:00 +0000843 pTab->aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
844 for(i=0; i<pTab->nCol; i++){
845 Expr *p;
846 if( pEList->a[i].zName ){
847 pTab->aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
drh6977fea2002-10-22 23:38:04 +0000848 }else if( (p=pEList->a[i].pExpr)->span.z && p->span.z[0] ){
849 sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drhd820cb12002-02-18 03:21:45 +0000850 }else if( p->op==TK_DOT && p->pRight && p->pRight->token.z &&
851 p->pRight->token.z[0] ){
852 sqliteSetNString(&pTab->aCol[i].zName,
853 p->pRight->token.z, p->pRight->token.n, 0);
drh22f70c32002-02-18 01:17:00 +0000854 }else{
855 char zBuf[30];
856 sprintf(zBuf, "column%d", i+1);
857 pTab->aCol[i].zName = sqliteStrDup(zBuf);
858 }
859 }
860 pTab->iPKey = -1;
861 return pTab;
862}
863
864/*
drhad2d8302002-05-24 20:31:36 +0000865** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000866**
drhad3cab52002-05-24 02:04:32 +0000867** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh63eb5f22003-04-29 16:20:44 +0000868** defines the set of tables that should be scanned. For views,
869** fill pTabList->a[].pSelect with a copy of the SELECT statement
870** that implements the view. A copy is made of the view's SELECT
871** statement so that we can freely modify or delete that statement
872** without worrying about messing up the presistent representation
873** of the view.
drhd8bc7082000-06-07 23:51:50 +0000874**
drhad2d8302002-05-24 20:31:36 +0000875** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
876** on joins and the ON and USING clause of joins.
877**
878** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000879** for instances of the "*" operator or the TABLE.* operator.
880** If found, expand each "*" to be every column in every table
881** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000882**
883** Return 0 on success. If there are problems, leave an error message
884** in pParse and return non-zero.
885*/
886static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000887 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000888 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000889 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000890 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000891
892 if( p==0 || p->pSrc==0 ) return 1;
893 pTabList = p->pSrc;
894 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000895
896 /* Look up every table in the table list.
897 */
drhad3cab52002-05-24 02:04:32 +0000898 for(i=0; i<pTabList->nSrc; i++){
drhd8bc7082000-06-07 23:51:50 +0000899 if( pTabList->a[i].pTab ){
900 /* This routine has run before! No need to continue */
901 return 0;
902 }
drhdaffd0e2001-04-11 14:28:42 +0000903 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000904 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000905 assert( pTabList->a[i].pSelect!=0 );
drhad2d8302002-05-24 20:31:36 +0000906 if( pTabList->a[i].zAlias==0 ){
907 char zFakeName[60];
908 sprintf(zFakeName, "sqlite_subquery_%p_",
909 (void*)pTabList->a[i].pSelect);
910 sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
911 }
drh22f70c32002-02-18 01:17:00 +0000912 pTabList->a[i].pTab = pTab =
913 sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
914 pTabList->a[i].pSelect);
915 if( pTab==0 ){
916 return 1;
917 }
drh5cf590c2003-04-24 01:45:04 +0000918 /* The isTransient flag indicates that the Table structure has been
919 ** dynamically allocated and may be freed at any time. In other words,
920 ** pTab is not pointing to a persistent table structure that defines
921 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000922 pTab->isTransient = 1;
923 }else{
drha76b5df2002-02-23 02:32:10 +0000924 /* An ordinary table or view name in the FROM clause */
925 pTabList->a[i].pTab = pTab =
drha69d9162003-04-17 22:57:53 +0000926 sqliteLocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
drha76b5df2002-02-23 02:32:10 +0000927 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000928 return 1;
929 }
drha76b5df2002-02-23 02:32:10 +0000930 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +0000931 /* We reach here if the named table is a really a view */
drh417be792002-03-03 18:59:40 +0000932 if( sqliteViewGetColumnNames(pParse, pTab) ){
933 return 1;
934 }
drh63eb5f22003-04-29 16:20:44 +0000935 /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
936 ** view within a view. The SELECT structure has already been
937 ** copied by the outer view so we can skip the copy step here
938 ** in the inner view.
939 */
940 if( pTabList->a[i].pSelect==0 ){
941 pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
942 }
drha76b5df2002-02-23 02:32:10 +0000943 }
drhd8bc7082000-06-07 23:51:50 +0000944 }
945 }
946
drhad2d8302002-05-24 20:31:36 +0000947 /* Process NATURAL keywords, and ON and USING clauses of joins.
948 */
949 if( sqliteProcessJoin(pParse, p) ) return 1;
950
drh7c917d12001-12-16 20:05:05 +0000951 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000952 ** all columns in all tables. And for every TABLE.* insert the names
953 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000954 ** with the TK_ALL operator for each "*" that it found in the column list.
955 ** The following code just has to locate the TK_ALL expressions and expand
956 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000957 **
958 ** The first loop just checks to see if there are any "*" operators
959 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000960 */
drh7c917d12001-12-16 20:05:05 +0000961 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000962 Expr *pE = pEList->a[k].pExpr;
963 if( pE->op==TK_ALL ) break;
964 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
965 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000966 }
drh54473222002-04-04 02:10:55 +0000967 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000968 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000969 /*
970 ** If we get here it means the result set contains one or more "*"
971 ** operators that need to be expanded. Loop through each expression
972 ** in the result set and expand them one by one.
973 */
drh7c917d12001-12-16 20:05:05 +0000974 struct ExprList_item *a = pEList->a;
975 ExprList *pNew = 0;
976 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000977 Expr *pE = a[k].pExpr;
978 if( pE->op!=TK_ALL &&
979 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
980 /* This particular expression does not need to be expanded.
981 */
drh7c917d12001-12-16 20:05:05 +0000982 pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
983 pNew->a[pNew->nExpr-1].zName = a[k].zName;
984 a[k].pExpr = 0;
985 a[k].zName = 0;
986 }else{
drh54473222002-04-04 02:10:55 +0000987 /* This expression is a "*" or a "TABLE.*" and needs to be
988 ** expanded. */
989 int tableSeen = 0; /* Set to 1 when TABLE matches */
990 Token *pName; /* text of name of TABLE */
991 if( pE->op==TK_DOT && pE->pLeft ){
992 pName = &pE->pLeft->token;
993 }else{
994 pName = 0;
995 }
drhad3cab52002-05-24 02:04:32 +0000996 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000997 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000998 char *zTabName = pTabList->a[i].zAlias;
999 if( zTabName==0 || zTabName[0]==0 ){
1000 zTabName = pTab->zName;
1001 }
drhc754fa52002-05-27 03:25:51 +00001002 if( pName && (zTabName==0 || zTabName[0]==0 ||
1003 sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
1004 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +00001005 continue;
1006 }
1007 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001008 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001009 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001010 char *zName = pTab->aCol[j].zName;
1011
1012 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
1013 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
1014 /* In a NATURAL join, omit the join columns from the
1015 ** table on the right */
1016 continue;
1017 }
1018 if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
1019 /* In a join with a USING clause, omit columns in the
1020 ** using clause from the table on the right. */
1021 continue;
1022 }
drh22f70c32002-02-18 01:17:00 +00001023 pRight = sqliteExpr(TK_ID, 0, 0, 0);
1024 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +00001025 pRight->token.z = zName;
1026 pRight->token.n = strlen(zName);
drh4b59ab52002-08-24 18:24:51 +00001027 pRight->token.dyn = 0;
drh4b59ab52002-08-24 18:24:51 +00001028 if( zTabName && pTabList->nSrc>1 ){
drh22f70c32002-02-18 01:17:00 +00001029 pLeft = sqliteExpr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001030 pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
1031 if( pExpr==0 ) break;
drh4b59ab52002-08-24 18:24:51 +00001032 pLeft->token.z = zTabName;
1033 pLeft->token.n = strlen(zTabName);
1034 pLeft->token.dyn = 0;
drh6977fea2002-10-22 23:38:04 +00001035 sqliteSetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
1036 pExpr->span.n = strlen(pExpr->span.z);
1037 pExpr->span.dyn = 1;
1038 pExpr->token.z = 0;
1039 pExpr->token.n = 0;
1040 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001041 }else{
drh22f70c32002-02-18 01:17:00 +00001042 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001043 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001044 }
drh7c917d12001-12-16 20:05:05 +00001045 pNew = sqliteExprListAppend(pNew, pExpr, 0);
1046 }
drh17e24df2001-11-06 14:10:41 +00001047 }
drh54473222002-04-04 02:10:55 +00001048 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +00001049 if( pName ){
drhda93d232003-03-31 02:12:46 +00001050 sqliteErrorMsg(pParse, "no such table: %T", pName);
drhf5db2d32002-06-06 23:42:27 +00001051 }else{
drhda93d232003-03-31 02:12:46 +00001052 sqliteErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001053 }
drh54473222002-04-04 02:10:55 +00001054 rc = 1;
1055 }
drhd8bc7082000-06-07 23:51:50 +00001056 }
1057 }
drh7c917d12001-12-16 20:05:05 +00001058 sqliteExprListDelete(pEList);
1059 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001060 }
drh54473222002-04-04 02:10:55 +00001061 return rc;
drhd8bc7082000-06-07 23:51:50 +00001062}
1063
1064/*
drhff78bd22002-02-27 01:47:11 +00001065** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1066** in a select structure. It just sets the pointers to NULL. This
1067** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1068** pointer is not NULL, this routine is called recursively on that pointer.
1069**
1070** This routine is called on the Select structure that defines a
1071** VIEW in order to undo any bindings to tables. This is necessary
1072** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001073** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1074** will be left pointing to a deallocated Table structure after the
1075** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001076*/
1077void sqliteSelectUnbind(Select *p){
1078 int i;
drhad3cab52002-05-24 02:04:32 +00001079 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +00001080 Table *pTab;
1081 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +00001082 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +00001083 if( (pTab = pSrc->a[i].pTab)!=0 ){
1084 if( pTab->isTransient ){
1085 sqliteDeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001086 }
1087 pSrc->a[i].pTab = 0;
1088 if( pSrc->a[i].pSelect ){
1089 sqliteSelectUnbind(pSrc->a[i].pSelect);
1090 }
1091 }
1092 }
1093}
1094
1095/*
drhd8bc7082000-06-07 23:51:50 +00001096** This routine associates entries in an ORDER BY expression list with
1097** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001098** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001099** the top-level node is filled in with column number and the iTable
1100** value of the top-level node is filled with iTable parameter.
1101**
1102** If there are prior SELECT clauses, they are processed first. A match
1103** in an earlier SELECT takes precedence over a later SELECT.
1104**
1105** Any entry that does not match is flagged as an error. The number
1106** of errors is returned.
drhfcb78a42003-01-18 20:11:05 +00001107**
1108** This routine does NOT correctly initialize the Expr.dataType field
1109** of the ORDER BY expressions. The multiSelectSortOrder() routine
1110** must be called to do that after the individual select statements
1111** have all been analyzed. This routine is unable to compute Expr.dataType
1112** because it must be called before the individual select statements
1113** have been analyzed.
drhd8bc7082000-06-07 23:51:50 +00001114*/
1115static int matchOrderbyToColumn(
1116 Parse *pParse, /* A place to leave error messages */
1117 Select *pSelect, /* Match to result columns of this SELECT */
1118 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001119 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001120 int mustComplete /* If TRUE all ORDER BYs must match */
1121){
1122 int nErr = 0;
1123 int i, j;
1124 ExprList *pEList;
1125
drhdaffd0e2001-04-11 14:28:42 +00001126 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001127 if( mustComplete ){
1128 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1129 }
1130 if( fillInColumnList(pParse, pSelect) ){
1131 return 1;
1132 }
1133 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001134 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1135 return 1;
1136 }
drhd8bc7082000-06-07 23:51:50 +00001137 }
1138 pEList = pSelect->pEList;
1139 for(i=0; i<pOrderBy->nExpr; i++){
1140 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001141 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001142 if( pOrderBy->a[i].done ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001143 if( sqliteExprIsInteger(pE, &iCol) ){
1144 if( iCol<=0 || iCol>pEList->nExpr ){
drhda93d232003-03-31 02:12:46 +00001145 sqliteErrorMsg(pParse,
1146 "ORDER BY position %d should be between 1 and %d",
1147 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001148 nErr++;
1149 break;
1150 }
drhfcb78a42003-01-18 20:11:05 +00001151 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001152 iCol--;
1153 }
1154 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001155 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001156 char *zName, *zLabel;
1157 zName = pEList->a[j].zName;
1158 assert( pE->token.z );
1159 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
drhd8bc7082000-06-07 23:51:50 +00001160 sqliteDequote(zLabel);
1161 if( sqliteStrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001162 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001163 }
drh6e142f52000-06-08 13:36:40 +00001164 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001165 }
drhe4de1fe2002-06-02 16:09:01 +00001166 if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
1167 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001168 }
1169 }
drhe4de1fe2002-06-02 16:09:01 +00001170 if( iCol>=0 ){
1171 pE->op = TK_COLUMN;
1172 pE->iColumn = iCol;
1173 pE->iTable = iTable;
1174 pOrderBy->a[i].done = 1;
1175 }
1176 if( iCol<0 && mustComplete ){
drhda93d232003-03-31 02:12:46 +00001177 sqliteErrorMsg(pParse,
1178 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001179 nErr++;
1180 break;
1181 }
1182 }
1183 return nErr;
1184}
1185
1186/*
1187** Get a VDBE for the given parser context. Create a new one if necessary.
1188** If an error occurs, return NULL and leave a message in pParse.
1189*/
1190Vdbe *sqliteGetVdbe(Parse *pParse){
1191 Vdbe *v = pParse->pVdbe;
1192 if( v==0 ){
drh4c504392000-10-16 22:06:40 +00001193 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001194 }
drhd8bc7082000-06-07 23:51:50 +00001195 return v;
1196}
drhfcb78a42003-01-18 20:11:05 +00001197
1198/*
1199** This routine sets the Expr.dataType field on all elements of
1200** the pOrderBy expression list. The pOrderBy list will have been
1201** set up by matchOrderbyToColumn(). Hence each expression has
1202** a TK_COLUMN as its root node. The Expr.iColumn refers to a
1203** column in the result set. The datatype is set to SQLITE_SO_TEXT
1204** if the corresponding column in p and every SELECT to the left of
1205** p has a datatype of SQLITE_SO_TEXT. If the cooressponding column
1206** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
1207** of the order-by expression is set to SQLITE_SO_NUM.
1208**
1209** Examples:
1210**
drhe78e8282003-01-19 03:59:45 +00001211** CREATE TABLE one(a INTEGER, b TEXT);
1212** CREATE TABLE two(c VARCHAR(5), d FLOAT);
1213**
1214** SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
1215**
1216** The primary sort key will use SQLITE_SO_NUM because the "d" in
1217** the second SELECT is numeric. The 1st column of the first SELECT
1218** is text but that does not matter because a numeric always overrides
1219** a text.
1220**
1221** The secondary key will use the SQLITE_SO_TEXT sort order because
1222** both the (second) "b" in the first SELECT and the "c" in the second
1223** SELECT have a datatype of text.
drhfcb78a42003-01-18 20:11:05 +00001224*/
1225static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
1226 int i;
1227 ExprList *pEList;
1228 if( pOrderBy==0 ) return;
1229 if( p==0 ){
1230 for(i=0; i<pOrderBy->nExpr; i++){
1231 pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
1232 }
1233 return;
1234 }
1235 multiSelectSortOrder(p->pPrior, pOrderBy);
1236 pEList = p->pEList;
1237 for(i=0; i<pOrderBy->nExpr; i++){
1238 Expr *pE = pOrderBy->a[i].pExpr;
1239 if( pE->dataType==SQLITE_SO_NUM ) continue;
1240 assert( pE->iColumn>=0 );
1241 if( pEList->nExpr>pE->iColumn ){
1242 pE->dataType = sqliteExprType(pEList->a[pE->iColumn].pExpr);
1243 }
1244 }
1245}
drhd8bc7082000-06-07 23:51:50 +00001246
1247/*
drh82c3d632000-06-06 21:56:07 +00001248** This routine is called to process a query that is really the union
1249** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001250**
drhe78e8282003-01-19 03:59:45 +00001251** "p" points to the right-most of the two queries. the query on the
1252** left is p->pPrior. The left query could also be a compound query
1253** in which case this routine will be called recursively.
1254**
1255** The results of the total query are to be written into a destination
1256** of type eDest with parameter iParm.
1257**
1258** Example 1: Consider a three-way compound SQL statement.
1259**
1260** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1261**
1262** This statement is parsed up as follows:
1263**
1264** SELECT c FROM t3
1265** |
1266** `-----> SELECT b FROM t2
1267** |
1268** `------> SELECT c FROM t1
1269**
1270** The arrows in the diagram above represent the Select.pPrior pointer.
1271** So if this routine is called with p equal to the t3 query, then
1272** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1273**
1274** Notice that because of the way SQLite parses compound SELECTs, the
1275** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001276*/
1277static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
drh10e5e3c2000-06-08 00:19:02 +00001278 int rc; /* Success code from a subroutine */
1279 Select *pPrior; /* Another SELECT immediately to our left */
1280 Vdbe *v; /* Generate code to this VDBE */
drh82c3d632000-06-06 21:56:07 +00001281
drhd8bc7082000-06-07 23:51:50 +00001282 /* Make sure there is no ORDER BY clause on prior SELECTs. Only the
1283 ** last SELECT in the series may have an ORDER BY.
drh82c3d632000-06-06 21:56:07 +00001284 */
drhdaffd0e2001-04-11 14:28:42 +00001285 if( p==0 || p->pPrior==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001286 pPrior = p->pPrior;
1287 if( pPrior->pOrderBy ){
drhda93d232003-03-31 02:12:46 +00001288 sqliteErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1289 selectOpName(p->op));
drh82c3d632000-06-06 21:56:07 +00001290 return 1;
1291 }
1292
drhd8bc7082000-06-07 23:51:50 +00001293 /* Make sure we have a valid query engine. If not, create a new one.
1294 */
1295 v = sqliteGetVdbe(pParse);
1296 if( v==0 ) return 1;
1297
drh1cc3d752002-03-23 00:31:29 +00001298 /* Create the destination temporary table if necessary
1299 */
1300 if( eDest==SRT_TempTable ){
1301 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
1302 eDest = SRT_Table;
1303 }
1304
drhf46f9052002-06-22 02:33:38 +00001305 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001306 */
drh82c3d632000-06-06 21:56:07 +00001307 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001308 case TK_ALL: {
1309 if( p->pOrderBy==0 ){
1310 rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
1311 if( rc ) return rc;
1312 p->pPrior = 0;
1313 rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
1314 p->pPrior = pPrior;
1315 if( rc ) return rc;
1316 break;
1317 }
1318 /* For UNION ALL ... ORDER BY fall through to the next case */
1319 }
drh82c3d632000-06-06 21:56:07 +00001320 case TK_EXCEPT:
1321 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001322 int unionTab; /* Cursor number of the temporary table holding result */
1323 int op; /* One of the SRT_ operations to apply to self */
1324 int priorOp; /* The SRT_ operation to apply to prior selects */
drhc926afb2002-06-20 03:38:26 +00001325 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
drh82c3d632000-06-06 21:56:07 +00001326
drhd8bc7082000-06-07 23:51:50 +00001327 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drhc926afb2002-06-20 03:38:26 +00001328 if( eDest==priorOp && p->pOrderBy==0 ){
drhd8bc7082000-06-07 23:51:50 +00001329 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001330 ** right.
drhd8bc7082000-06-07 23:51:50 +00001331 */
drh82c3d632000-06-06 21:56:07 +00001332 unionTab = iParm;
1333 }else{
drhd8bc7082000-06-07 23:51:50 +00001334 /* We will need to create our own temporary table to hold the
1335 ** intermediate results.
1336 */
1337 unionTab = pParse->nTab++;
1338 if( p->pOrderBy
1339 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
1340 return 1;
1341 }
drhd8bc7082000-06-07 23:51:50 +00001342 if( p->op!=TK_ALL ){
drhc6b52df2002-01-04 03:09:29 +00001343 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
drh99fcd712001-10-13 01:06:47 +00001344 sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drh345fda32001-01-15 22:51:08 +00001345 }else{
drh99fcd712001-10-13 01:06:47 +00001346 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001347 }
drh82c3d632000-06-06 21:56:07 +00001348 }
drhd8bc7082000-06-07 23:51:50 +00001349
1350 /* Code the SELECT statements to our left
1351 */
drh832508b2002-03-02 17:04:07 +00001352 rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001353 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001354
1355 /* Code the current SELECT statement
1356 */
1357 switch( p->op ){
1358 case TK_EXCEPT: op = SRT_Except; break;
1359 case TK_UNION: op = SRT_Union; break;
1360 case TK_ALL: op = SRT_Table; break;
1361 }
drh82c3d632000-06-06 21:56:07 +00001362 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001363 pOrderBy = p->pOrderBy;
1364 p->pOrderBy = 0;
drh832508b2002-03-02 17:04:07 +00001365 rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001366 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001367 p->pOrderBy = pOrderBy;
drh82c3d632000-06-06 21:56:07 +00001368 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001369
1370 /* Convert the data in the temporary table into whatever form
1371 ** it is that we currently need.
1372 */
drhc926afb2002-06-20 03:38:26 +00001373 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001374 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001375 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001376 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001377 generateColumnNames(pParse, 0, p->pEList);
1378 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001379 }
drh82c3d632000-06-06 21:56:07 +00001380 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001381 iCont = sqliteVdbeMakeLabel(v);
1382 sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
1383 iStart = sqliteVdbeCurrentAddr(v);
drhfcb78a42003-01-18 20:11:05 +00001384 multiSelectSortOrder(p, p->pOrderBy);
drh38640e12002-07-05 21:42:36 +00001385 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001386 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001387 iCont, iBreak);
1388 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001389 sqliteVdbeResolveLabel(v, iCont);
1390 sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
drh99fcd712001-10-13 01:06:47 +00001391 sqliteVdbeResolveLabel(v, iBreak);
1392 sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001393 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001394 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001395 }
drh82c3d632000-06-06 21:56:07 +00001396 }
1397 break;
1398 }
1399 case TK_INTERSECT: {
1400 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001401 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001402
drhd8bc7082000-06-07 23:51:50 +00001403 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001404 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001405 ** by allocating the tables we will need.
1406 */
drh82c3d632000-06-06 21:56:07 +00001407 tab1 = pParse->nTab++;
1408 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001409 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
1410 return 1;
1411 }
drhc6b52df2002-01-04 03:09:29 +00001412 sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
drh99fcd712001-10-13 01:06:47 +00001413 sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
drhd8bc7082000-06-07 23:51:50 +00001414
1415 /* Code the SELECTs to our left into temporary table "tab1".
1416 */
drh832508b2002-03-02 17:04:07 +00001417 rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001418 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001419
1420 /* Code the current SELECT into temporary table "tab2"
1421 */
drhc6b52df2002-01-04 03:09:29 +00001422 sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
drh99fcd712001-10-13 01:06:47 +00001423 sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001424 p->pPrior = 0;
drh832508b2002-03-02 17:04:07 +00001425 rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +00001426 p->pPrior = pPrior;
1427 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +00001428
1429 /* Generate code to take the intersection of the two temporary
1430 ** tables.
1431 */
drh82c3d632000-06-06 21:56:07 +00001432 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001433 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001434 generateColumnNames(pParse, 0, p->pEList);
1435 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001436 }
drh82c3d632000-06-06 21:56:07 +00001437 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +00001438 iCont = sqliteVdbeMakeLabel(v);
1439 sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
1440 iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
drh99fcd712001-10-13 01:06:47 +00001441 sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
drhfcb78a42003-01-18 20:11:05 +00001442 multiSelectSortOrder(p, p->pOrderBy);
drh38640e12002-07-05 21:42:36 +00001443 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001444 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +00001445 iCont, iBreak);
1446 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +00001447 sqliteVdbeResolveLabel(v, iCont);
1448 sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
drh99fcd712001-10-13 01:06:47 +00001449 sqliteVdbeResolveLabel(v, iBreak);
1450 sqliteVdbeAddOp(v, OP_Close, tab2, 0);
1451 sqliteVdbeAddOp(v, OP_Close, tab1, 0);
drhd8bc7082000-06-07 23:51:50 +00001452 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001453 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001454 }
drh82c3d632000-06-06 21:56:07 +00001455 break;
1456 }
1457 }
1458 assert( p->pEList && pPrior->pEList );
1459 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
drhda93d232003-03-31 02:12:46 +00001460 sqliteErrorMsg(pParse, "SELECTs to the left and right of %s"
1461 " do not have the same number of result columns", selectOpName(p->op));
drh82c3d632000-06-06 21:56:07 +00001462 return 1;
drh22827922000-06-06 17:27:05 +00001463 }
drhfcb78a42003-01-18 20:11:05 +00001464
1465 /* Issue a null callback if that is what the user wants.
1466 */
drh326dce72003-01-29 14:06:07 +00001467 if( eDest==SRT_Callback &&
1468 (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
1469 ){
drhfcb78a42003-01-18 20:11:05 +00001470 sqliteVdbeAddOp(v, OP_NullCallback, p->pEList->nExpr, 0);
1471 }
drh22827922000-06-06 17:27:05 +00001472 return 0;
1473}
1474
1475/*
drh832508b2002-03-02 17:04:07 +00001476** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001477** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001478** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001479** unchanged.)
drh832508b2002-03-02 17:04:07 +00001480**
1481** This routine is part of the flattening procedure. A subquery
1482** whose result set is defined by pEList appears as entry in the
1483** FROM clause of a SELECT such that the VDBE cursor assigned to that
1484** FORM clause entry is iTable. This routine make the necessary
1485** changes to pExpr so that it refers directly to the source table
1486** of the subquery rather the result set of the subquery.
1487*/
drh6a3ea0e2003-05-02 14:32:12 +00001488static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1489static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001490 if( pExpr==0 ) return;
drh84e59202002-03-14 14:33:31 +00001491 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){
drh832508b2002-03-02 17:04:07 +00001492 Expr *pNew;
drh84e59202002-03-14 14:33:31 +00001493 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
drh832508b2002-03-02 17:04:07 +00001494 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1495 pNew = pEList->a[pExpr->iColumn].pExpr;
1496 assert( pNew!=0 );
1497 pExpr->op = pNew->op;
drhfcb78a42003-01-18 20:11:05 +00001498 pExpr->dataType = pNew->dataType;
drhd94a6692002-08-25 18:29:11 +00001499 assert( pExpr->pLeft==0 );
drh832508b2002-03-02 17:04:07 +00001500 pExpr->pLeft = sqliteExprDup(pNew->pLeft);
drhd94a6692002-08-25 18:29:11 +00001501 assert( pExpr->pRight==0 );
drh832508b2002-03-02 17:04:07 +00001502 pExpr->pRight = sqliteExprDup(pNew->pRight);
drhd94a6692002-08-25 18:29:11 +00001503 assert( pExpr->pList==0 );
drh832508b2002-03-02 17:04:07 +00001504 pExpr->pList = sqliteExprListDup(pNew->pList);
1505 pExpr->iTable = pNew->iTable;
1506 pExpr->iColumn = pNew->iColumn;
1507 pExpr->iAgg = pNew->iAgg;
drh4b59ab52002-08-24 18:24:51 +00001508 sqliteTokenCopy(&pExpr->token, &pNew->token);
drh6977fea2002-10-22 23:38:04 +00001509 sqliteTokenCopy(&pExpr->span, &pNew->span);
drh832508b2002-03-02 17:04:07 +00001510 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001511 substExpr(pExpr->pLeft, iTable, pEList);
1512 substExpr(pExpr->pRight, iTable, pEList);
1513 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001514 }
1515}
1516static void
drh6a3ea0e2003-05-02 14:32:12 +00001517substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001518 int i;
1519 if( pList==0 ) return;
1520 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001521 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001522 }
1523}
1524
1525/*
drh1350b032002-02-27 19:00:20 +00001526** This routine attempts to flatten subqueries in order to speed
1527** execution. It returns 1 if it makes changes and 0 if no flattening
1528** occurs.
1529**
1530** To understand the concept of flattening, consider the following
1531** query:
1532**
1533** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1534**
1535** The default way of implementing this query is to execute the
1536** subquery first and store the results in a temporary table, then
1537** run the outer query on that temporary table. This requires two
1538** passes over the data. Furthermore, because the temporary table
1539** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001540** optimized.
drh1350b032002-02-27 19:00:20 +00001541**
drh832508b2002-03-02 17:04:07 +00001542** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001543** a single flat select, like this:
1544**
1545** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1546**
1547** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001548** but only has to scan the data once. And because indices might
1549** exist on the table t1, a complete scan of the data might be
1550** avoided.
drh1350b032002-02-27 19:00:20 +00001551**
drh832508b2002-03-02 17:04:07 +00001552** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001553**
drh832508b2002-03-02 17:04:07 +00001554** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001555**
drh832508b2002-03-02 17:04:07 +00001556** (2) The subquery is not an aggregate or the outer query is not a join.
1557**
drh8af4d3a2003-05-06 20:35:16 +00001558** (3) The subquery is not the right operand of a left outer join, or
1559** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001560**
1561** (4) The subquery is not DISTINCT or the outer query is not a join.
1562**
1563** (5) The subquery is not DISTINCT or the outer query does not use
1564** aggregates.
1565**
1566** (6) The subquery does not use aggregates or the outer query is not
1567** DISTINCT.
1568**
drh08192d52002-04-30 19:20:28 +00001569** (7) The subquery has a FROM clause.
1570**
drhdf199a22002-06-14 22:38:41 +00001571** (8) The subquery does not use LIMIT or the outer query is not a join.
1572**
1573** (9) The subquery does not use LIMIT or the outer query does not use
1574** aggregates.
1575**
1576** (10) The subquery does not use aggregates or the outer query does not
1577** use LIMIT.
1578**
drh174b6192002-12-03 02:22:52 +00001579** (11) The subquery and the outer query do not both have ORDER BY clauses.
1580**
drh3fc673e2003-06-16 00:40:34 +00001581** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1582** subquery has no WHERE clause. (added by ticket #350)
1583**
drh832508b2002-03-02 17:04:07 +00001584** In this routine, the "p" parameter is a pointer to the outer query.
1585** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1586** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1587**
drh665de472003-03-31 13:36:09 +00001588** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001589** If flattening is attempted this routine returns 1.
1590**
1591** All of the expression analysis must occur on both the outer query and
1592** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001593*/
drh8c74a8c2002-08-25 19:20:40 +00001594static int flattenSubquery(
1595 Parse *pParse, /* The parsing context */
1596 Select *p, /* The parent or outer SELECT statement */
1597 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1598 int isAgg, /* True if outer SELECT uses aggregate functions */
1599 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1600){
drh0bb28102002-05-08 11:54:14 +00001601 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001602 SrcList *pSrc; /* The FROM clause of the outer query */
1603 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001604 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001605 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh832508b2002-03-02 17:04:07 +00001606 int i;
drh832508b2002-03-02 17:04:07 +00001607 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001608
drh832508b2002-03-02 17:04:07 +00001609 /* Check to see if flattening is permitted. Return 0 if not.
1610 */
1611 if( p==0 ) return 0;
1612 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001613 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001614 pSub = pSrc->a[iFrom].pSelect;
1615 assert( pSub!=0 );
1616 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001617 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001618 pSubSrc = pSub->pSrc;
1619 assert( pSubSrc );
drhc31c2eb2003-05-02 16:04:17 +00001620 if( pSubSrc->nSrc==0 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001621 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1622 return 0;
1623 }
drhd11d3822002-06-21 23:01:49 +00001624 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001625 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001626
drh8af4d3a2003-05-06 20:35:16 +00001627 /* Restriction 3: If the subquery is a join, make sure the subquery is
1628 ** not used as the right operand of an outer join. Examples of why this
1629 ** is not allowed:
1630 **
1631 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1632 **
1633 ** If we flatten the above, we would get
1634 **
1635 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1636 **
1637 ** which is not at all the same thing.
1638 */
1639 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1640 return 0;
1641 }
1642
drh3fc673e2003-06-16 00:40:34 +00001643 /* Restriction 12: If the subquery is the right operand of a left outer
1644 ** join, make sure the subquery has no WHERE clause.
1645 ** An examples of why this is not allowed:
1646 **
1647 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1648 **
1649 ** If we flatten the above, we would get
1650 **
1651 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1652 **
1653 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1654 ** effectively converts the OUTER JOIN into an INNER JOIN.
1655 */
1656 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1657 && pSub->pWhere!=0 ){
1658 return 0;
1659 }
1660
drh0bb28102002-05-08 11:54:14 +00001661 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001662 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001663 */
drhc31c2eb2003-05-02 16:04:17 +00001664
1665 /* Move all of the FROM elements of the subquery into the
1666 ** the FROM clause of the outer query. Before doing this, remember
1667 ** the cursor number for the original outer query FROM element in
1668 ** iParent. The iParent cursor will never be used. Subsequent code
1669 ** will scan expressions looking for iParent references and replace
1670 ** those references with expressions that resolve to the subquery FROM
1671 ** elements we are now copying in.
1672 */
drh6a3ea0e2003-05-02 14:32:12 +00001673 iParent = pSrc->a[iFrom].iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001674 {
1675 int nSubSrc = pSubSrc->nSrc;
drh8af4d3a2003-05-06 20:35:16 +00001676 int jointype = pSrc->a[iFrom].jointype;
drhc31c2eb2003-05-02 16:04:17 +00001677
1678 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1679 sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1680 }
drhf26e09c2003-05-31 16:21:12 +00001681 sqliteFree(pSrc->a[iFrom].zDatabase);
drhc31c2eb2003-05-02 16:04:17 +00001682 sqliteFree(pSrc->a[iFrom].zName);
1683 sqliteFree(pSrc->a[iFrom].zAlias);
1684 if( nSubSrc>1 ){
1685 int extra = nSubSrc - 1;
1686 for(i=1; i<nSubSrc; i++){
1687 pSrc = sqliteSrcListAppend(pSrc, 0, 0);
1688 }
1689 p->pSrc = pSrc;
1690 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1691 pSrc->a[i] = pSrc->a[i-extra];
1692 }
1693 }
1694 for(i=0; i<nSubSrc; i++){
1695 pSrc->a[i+iFrom] = pSubSrc->a[i];
1696 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1697 }
drh8af4d3a2003-05-06 20:35:16 +00001698 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00001699 }
1700
1701 /* Now begin substituting subquery result set expressions for
1702 ** references to the iParent in the outer query.
1703 **
1704 ** Example:
1705 **
1706 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1707 ** \ \_____________ subquery __________/ /
1708 ** \_____________________ outer query ______________________________/
1709 **
1710 ** We look at every expression in the outer query and every place we see
1711 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1712 */
drh6a3ea0e2003-05-02 14:32:12 +00001713 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001714 pList = p->pEList;
1715 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001716 Expr *pExpr;
1717 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1718 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001719 }
1720 }
drh1b2e0322002-03-03 02:49:51 +00001721 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00001722 substExprList(p->pGroupBy, iParent, pSub->pEList);
1723 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001724 }
drh174b6192002-12-03 02:22:52 +00001725 if( pSub->pOrderBy ){
1726 assert( p->pOrderBy==0 );
1727 p->pOrderBy = pSub->pOrderBy;
1728 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00001729 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00001730 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00001731 }
drh832508b2002-03-02 17:04:07 +00001732 if( pSub->pWhere ){
1733 pWhere = sqliteExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00001734 }else{
1735 pWhere = 0;
1736 }
1737 if( subqueryIsAgg ){
1738 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001739 p->pHaving = p->pWhere;
1740 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00001741 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001742 if( pSub->pHaving ){
1743 Expr *pHaving = sqliteExprDup(pSub->pHaving);
drh1b2e0322002-03-03 02:49:51 +00001744 if( p->pHaving ){
1745 p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
1746 }else{
1747 p->pHaving = pHaving;
1748 }
1749 }
1750 assert( p->pGroupBy==0 );
1751 p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00001752 }else if( p->pWhere==0 ){
1753 p->pWhere = pWhere;
1754 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001755 substExpr(p->pWhere, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001756 if( pWhere ){
1757 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1758 }
1759 }
drhc31c2eb2003-05-02 16:04:17 +00001760
1761 /* The flattened query is distinct if either the inner or the
1762 ** outer query is distinct.
1763 */
drh832508b2002-03-02 17:04:07 +00001764 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00001765
drhc31c2eb2003-05-02 16:04:17 +00001766 /* Transfer the limit expression from the subquery to the outer
1767 ** query.
1768 */
drhdf199a22002-06-14 22:38:41 +00001769 if( pSub->nLimit>=0 ){
1770 if( p->nLimit<0 ){
1771 p->nLimit = pSub->nLimit;
1772 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1773 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1774 }
1775 }
1776 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00001777
drhc31c2eb2003-05-02 16:04:17 +00001778 /* Finially, delete what is left of the subquery and return
1779 ** success.
1780 */
drh832508b2002-03-02 17:04:07 +00001781 sqliteSelectDelete(pSub);
1782 return 1;
1783}
drh1350b032002-02-27 19:00:20 +00001784
1785/*
drh9562b552002-02-19 15:00:07 +00001786** Analyze the SELECT statement passed in as an argument to see if it
1787** is a simple min() or max() query. If it is and this query can be
1788** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00001789** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00001790** simple min() or max() query, then return 0;
1791**
1792** A simply min() or max() query looks like this:
1793**
1794** SELECT min(a) FROM table;
1795** SELECT max(a) FROM table;
1796**
1797** The query may have only a single table in its FROM argument. There
1798** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1799** be the min() or max() of a single column of the table. The column
1800** in the min() or max() function must be indexed.
1801**
1802** The parameters to this routine are the same as for sqliteSelect().
1803** See the header comment on that routine for additional information.
1804*/
1805static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1806 Expr *pExpr;
1807 int iCol;
1808 Table *pTab;
1809 Index *pIdx;
1810 int base;
1811 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00001812 int seekOp;
1813 int cont;
1814 ExprList eList;
1815 struct ExprList_item eListItem;
1816
1817 /* Check to see if this query is a simple min() or max() query. Return
1818 ** zero if it is not.
1819 */
1820 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drhad3cab52002-05-24 02:04:32 +00001821 if( p->pSrc->nSrc!=1 ) return 0;
drh9562b552002-02-19 15:00:07 +00001822 if( p->pEList->nExpr!=1 ) return 0;
1823 pExpr = p->pEList->a[0].pExpr;
1824 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
1825 if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00001826 if( pExpr->token.n!=3 ) return 0;
drh0bce8352002-02-28 00:41:10 +00001827 if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
1828 seekOp = OP_Rewind;
1829 }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
1830 seekOp = OP_Last;
1831 }else{
1832 return 0;
1833 }
drh9562b552002-02-19 15:00:07 +00001834 pExpr = pExpr->pList->a[0].pExpr;
1835 if( pExpr->op!=TK_COLUMN ) return 0;
1836 iCol = pExpr->iColumn;
1837 pTab = p->pSrc->a[0].pTab;
1838
1839 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00001840 ** Check to make sure we have an index and make pIdx point to the
1841 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
1842 ** key column, no index is necessary so set pIdx to NULL. If no
1843 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00001844 */
1845 if( iCol<0 ){
1846 pIdx = 0;
1847 }else{
1848 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1849 assert( pIdx->nColumn>=1 );
1850 if( pIdx->aiColumn[0]==iCol ) break;
1851 }
1852 if( pIdx==0 ) return 0;
1853 }
1854
drh17f71932002-02-21 12:01:27 +00001855 /* Identify column names if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00001856 ** step is skipped if the output is going to a table or a memory cell.
1857 */
1858 v = sqliteGetVdbe(pParse);
1859 if( v==0 ) return 0;
1860 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001861 generateColumnNames(pParse, p->pSrc, p->pEList);
1862 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh9562b552002-02-19 15:00:07 +00001863 }
1864
drh17f71932002-02-21 12:01:27 +00001865 /* Generating code to find the min or the max. Basically all we have
1866 ** to do is find the first or the last entry in the chosen index. If
1867 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
1868 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00001869 */
drh8bf8dc92003-05-17 17:35:10 +00001870 sqliteCodeVerifySchema(pParse, pTab->iDb);
drh6a3ea0e2003-05-02 14:32:12 +00001871 base = p->pSrc->a[0].iCursor;
drhd24cc422003-03-27 12:51:24 +00001872 sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
drh001bbcb2003-03-19 03:14:00 +00001873 sqliteVdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001874 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
drhd4d595f2003-04-17 12:44:23 +00001875 cont = sqliteVdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00001876 if( pIdx==0 ){
1877 sqliteVdbeAddOp(v, seekOp, base, 0);
1878 }else{
drhd24cc422003-03-27 12:51:24 +00001879 sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
drh001bbcb2003-03-19 03:14:00 +00001880 sqliteVdbeAddOp(v, OP_OpenRead, base+1, pIdx->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001881 sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
drh9562b552002-02-19 15:00:07 +00001882 sqliteVdbeAddOp(v, seekOp, base+1, 0);
1883 sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
1884 sqliteVdbeAddOp(v, OP_Close, base+1, 0);
1885 sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
1886 }
drh5cf8e8c2002-02-19 22:42:05 +00001887 eList.nExpr = 1;
1888 memset(&eListItem, 0, sizeof(eListItem));
1889 eList.a = &eListItem;
1890 eList.a[0].pExpr = pExpr;
drh38640e12002-07-05 21:42:36 +00001891 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
drh9562b552002-02-19 15:00:07 +00001892 sqliteVdbeResolveLabel(v, cont);
1893 sqliteVdbeAddOp(v, OP_Close, base, 0);
1894 return 1;
1895}
1896
1897/*
drh9bb61fe2000-06-05 16:01:39 +00001898** Generate code for the given SELECT statement.
1899**
drhfef52082000-06-06 01:50:43 +00001900** The results are distributed in various ways depending on the
1901** value of eDest and iParm.
1902**
1903** eDest Value Result
1904** ------------ -------------------------------------------
1905** SRT_Callback Invoke the callback for each row of the result.
1906**
1907** SRT_Mem Store first result in memory cell iParm
1908**
1909** SRT_Set Store results as keys of a table with cursor iParm
1910**
drh82c3d632000-06-06 21:56:07 +00001911** SRT_Union Store results as a key in a temporary table iParm
1912**
drhc4a3c772001-04-04 11:48:57 +00001913** SRT_Except Remove results form the temporary table iParm.
1914**
1915** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00001916**
drhe78e8282003-01-19 03:59:45 +00001917** The table above is incomplete. Additional eDist value have be added
1918** since this comment was written. See the selectInnerLoop() function for
1919** a complete listing of the allowed values of eDest and their meanings.
1920**
drh9bb61fe2000-06-05 16:01:39 +00001921** This routine returns the number of errors. If any errors are
1922** encountered, then an appropriate error message is left in
1923** pParse->zErrMsg.
1924**
1925** This routine does NOT free the Select structure passed in. The
1926** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00001927**
1928** The pParent, parentTab, and *pParentAgg fields are filled in if this
1929** SELECT is a subquery. This routine may try to combine this SELECT
1930** with its parent to form a single flat query. In so doing, it might
1931** change the parent query from a non-aggregate to an aggregate query.
1932** For that reason, the pParentAgg flag is passed as a pointer, so it
1933** can be changed.
drhe78e8282003-01-19 03:59:45 +00001934**
1935** Example 1: The meaning of the pParent parameter.
1936**
1937** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
1938** \ \_______ subquery _______/ /
1939** \ /
1940** \____________________ outer query ___________________/
1941**
1942** This routine is called for the outer query first. For that call,
1943** pParent will be NULL. During the processing of the outer query, this
1944** routine is called recursively to handle the subquery. For the recursive
1945** call, pParent will point to the outer query. Because the subquery is
1946** the second element in a three-way join, the parentTab parameter will
1947** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00001948*/
1949int sqliteSelect(
drhcce7d172000-05-31 15:34:51 +00001950 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00001951 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00001952 int eDest, /* How to dispose of the results */
1953 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00001954 Select *pParent, /* Another SELECT for which this is a sub-query */
1955 int parentTab, /* Index in pParent->pSrc of this query */
drh1b2e0322002-03-03 02:49:51 +00001956 int *pParentAgg /* True if pParent uses aggregate functions */
drhcce7d172000-05-31 15:34:51 +00001957){
drhd8bc7082000-06-07 23:51:50 +00001958 int i;
drhcce7d172000-05-31 15:34:51 +00001959 WhereInfo *pWInfo;
1960 Vdbe *v;
1961 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00001962 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00001963 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00001964 Expr *pWhere; /* The WHERE clause. May be NULL */
1965 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00001966 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
1967 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00001968 int isDistinct; /* True if the DISTINCT keyword is present */
1969 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00001970 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00001971
drhdaffd0e2001-04-11 14:28:42 +00001972 if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
drhe22a3342003-04-22 20:30:37 +00001973 if( sqliteAuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00001974
drh82c3d632000-06-06 21:56:07 +00001975 /* If there is are a sequence of queries, do the earlier ones first.
1976 */
1977 if( p->pPrior ){
1978 return multiSelect(pParse, p, eDest, iParm);
1979 }
1980
1981 /* Make local copies of the parameters for this query.
1982 */
drh9bb61fe2000-06-05 16:01:39 +00001983 pTabList = p->pSrc;
1984 pWhere = p->pWhere;
1985 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00001986 pGroupBy = p->pGroupBy;
1987 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00001988 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00001989
drh6a3ea0e2003-05-02 14:32:12 +00001990 /* Allocate VDBE cursors for each table in the FROM clause
drh10e5e3c2000-06-08 00:19:02 +00001991 */
drh6a3ea0e2003-05-02 14:32:12 +00001992 sqliteSrcListAssignCursors(pParse, pTabList);
drh10e5e3c2000-06-08 00:19:02 +00001993
drh9bb61fe2000-06-05 16:01:39 +00001994 /*
1995 ** Do not even attempt to generate any code if we have already seen
1996 ** errors before this routine starts.
1997 */
drh1d83f052002-02-17 00:30:36 +00001998 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001999
drhe78e8282003-01-19 03:59:45 +00002000 /* Expand any "*" terms in the result set. (For example the "*" in
2001 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
2002 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00002003 */
drhd8bc7082000-06-07 23:51:50 +00002004 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00002005 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002006 }
drhad2d8302002-05-24 20:31:36 +00002007 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00002008 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00002009 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002010
drh22827922000-06-06 17:27:05 +00002011 /* If writing to memory or generating a set
2012 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002013 */
drhfef52082000-06-06 01:50:43 +00002014 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
drhda93d232003-03-31 02:12:46 +00002015 sqliteErrorMsg(pParse, "only a single result allowed for "
2016 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002017 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002018 }
2019
drhc926afb2002-06-20 03:38:26 +00002020 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002021 */
drhc926afb2002-06-20 03:38:26 +00002022 switch( eDest ){
2023 case SRT_Union:
2024 case SRT_Except:
2025 case SRT_Discard:
2026 pOrderBy = 0;
2027 break;
2028 default:
2029 break;
drh22827922000-06-06 17:27:05 +00002030 }
2031
drh10e5e3c2000-06-08 00:19:02 +00002032 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002033 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002034 **
drh967e8b72000-06-21 13:59:10 +00002035 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002036 */
drh4794b982000-06-06 13:54:14 +00002037 for(i=0; i<pEList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00002038 if( sqliteExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002039 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002040 }
drh22827922000-06-06 17:27:05 +00002041 if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002042 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002043 }
2044 }
drhcce7d172000-05-31 15:34:51 +00002045 if( pWhere ){
drh6a3ea0e2003-05-02 14:32:12 +00002046 if( sqliteExprResolveIds(pParse, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00002047 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002048 }
2049 if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00002050 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002051 }
drh6a3ea0e2003-05-02 14:32:12 +00002052 sqliteOracle8JoinFixup(pTabList, pWhere);
drhcce7d172000-05-31 15:34:51 +00002053 }
drhc66c5a22002-12-03 02:34:49 +00002054 if( pHaving ){
2055 if( pGroupBy==0 ){
drhda93d232003-03-31 02:12:46 +00002056 sqliteErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
drhc66c5a22002-12-03 02:34:49 +00002057 goto select_end;
2058 }
drh6a3ea0e2003-05-02 14:32:12 +00002059 if( sqliteExprResolveIds(pParse, pTabList, pEList, pHaving) ){
drhc66c5a22002-12-03 02:34:49 +00002060 goto select_end;
2061 }
2062 if( sqliteExprCheck(pParse, pHaving, 1, &isAgg) ){
2063 goto select_end;
2064 }
2065 }
drhcce7d172000-05-31 15:34:51 +00002066 if( pOrderBy ){
2067 for(i=0; i<pOrderBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002068 int iCol;
drh22827922000-06-06 17:27:05 +00002069 Expr *pE = pOrderBy->a[i].pExpr;
drh88eee382003-01-31 17:16:36 +00002070 if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2071 sqliteExprDelete(pE);
2072 pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
2073 }
drh6a3ea0e2003-05-02 14:32:12 +00002074 if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
drh88eee382003-01-31 17:16:36 +00002075 goto select_end;
2076 }
2077 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
2078 goto select_end;
2079 }
drh92086432002-01-22 14:11:29 +00002080 if( sqliteExprIsConstant(pE) ){
drhe4de1fe2002-06-02 16:09:01 +00002081 if( sqliteExprIsInteger(pE, &iCol)==0 ){
drhda93d232003-03-31 02:12:46 +00002082 sqliteErrorMsg(pParse,
2083 "ORDER BY terms must not be non-integer constants");
drhe4de1fe2002-06-02 16:09:01 +00002084 goto select_end;
2085 }else if( iCol<=0 || iCol>pEList->nExpr ){
drhda93d232003-03-31 02:12:46 +00002086 sqliteErrorMsg(pParse,
2087 "ORDER BY column number %d out of range - should be "
drhe4de1fe2002-06-02 16:09:01 +00002088 "between 1 and %d", iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00002089 goto select_end;
2090 }
drhcce7d172000-05-31 15:34:51 +00002091 }
2092 }
2093 }
drh22827922000-06-06 17:27:05 +00002094 if( pGroupBy ){
2095 for(i=0; i<pGroupBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002096 int iCol;
drh22827922000-06-06 17:27:05 +00002097 Expr *pE = pGroupBy->a[i].pExpr;
drh88eee382003-01-31 17:16:36 +00002098 if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2099 sqliteExprDelete(pE);
2100 pE = pGroupBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00002101 }
drh6a3ea0e2003-05-02 14:32:12 +00002102 if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00002103 goto select_end;
drh22827922000-06-06 17:27:05 +00002104 }
2105 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00002106 goto select_end;
drh22827922000-06-06 17:27:05 +00002107 }
drh88eee382003-01-31 17:16:36 +00002108 if( sqliteExprIsConstant(pE) ){
2109 if( sqliteExprIsInteger(pE, &iCol)==0 ){
drhda93d232003-03-31 02:12:46 +00002110 sqliteErrorMsg(pParse,
2111 "GROUP BY terms must not be non-integer constants");
drh88eee382003-01-31 17:16:36 +00002112 goto select_end;
2113 }else if( iCol<=0 || iCol>pEList->nExpr ){
drhda93d232003-03-31 02:12:46 +00002114 sqliteErrorMsg(pParse,
2115 "GROUP BY column number %d out of range - should be "
drh88eee382003-01-31 17:16:36 +00002116 "between 1 and %d", iCol, pEList->nExpr);
drh88eee382003-01-31 17:16:36 +00002117 goto select_end;
2118 }
2119 }
drh22827922000-06-06 17:27:05 +00002120 }
2121 }
drhcce7d172000-05-31 15:34:51 +00002122
drh9562b552002-02-19 15:00:07 +00002123 /* Check for the special case of a min() or max() function by itself
2124 ** in the result set.
2125 */
2126 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
drh5cf8e8c2002-02-19 22:42:05 +00002127 rc = 0;
drh9562b552002-02-19 15:00:07 +00002128 goto select_end;
2129 }
2130
drhd820cb12002-02-18 03:21:45 +00002131 /* Begin generating code.
2132 */
2133 v = sqliteGetVdbe(pParse);
2134 if( v==0 ) goto select_end;
2135
drhe78e8282003-01-19 03:59:45 +00002136 /* Identify column names if we will be using them in a callback. This
2137 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002138 */
2139 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002140 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002141 }
2142
drhef0cae52003-07-16 02:19:37 +00002143 /* Set the limiter.
2144 **
2145 ** The phrase "LIMIT 0" means all rows are shown, not zero rows.
2146 ** If the comparison is p->nLimit<=0 then "LIMIT 0" shows
2147 ** all rows. It is the same as no limit. If the comparision is
2148 ** p->nLimit<0 then "LIMIT 0" show no rows at all.
2149 ** "LIMIT -1" always shows all rows. There is some
2150 ** contraversy about what the correct behavior should be.
drh0bb28102002-05-08 11:54:14 +00002151 */
2152 if( p->nLimit<=0 ){
drhd11d3822002-06-21 23:01:49 +00002153 p->nLimit = -1;
drh0bb28102002-05-08 11:54:14 +00002154 }else{
drhd11d3822002-06-21 23:01:49 +00002155 int iMem = pParse->nMem++;
2156 sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
drhbf5cd972002-06-24 12:20:23 +00002157 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
drhd11d3822002-06-21 23:01:49 +00002158 p->nLimit = iMem;
drhef0cae52003-07-16 02:19:37 +00002159 }
2160 if( p->nOffset<=0 ){
2161 p->nOffset = 0;
2162 }else{
2163 int iMem = pParse->nMem++;
2164 if( iMem==0 ) iMem = pParse->nMem++;
2165 sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
2166 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
2167 p->nOffset = iMem;
drh0bb28102002-05-08 11:54:14 +00002168 }
2169
drhd820cb12002-02-18 03:21:45 +00002170 /* Generate code for all sub-queries in the FROM clause
2171 */
drhad3cab52002-05-24 02:04:32 +00002172 for(i=0; i<pTabList->nSrc; i++){
drh5cf590c2003-04-24 01:45:04 +00002173 const char *zSavedAuthContext;
drhc31c2eb2003-05-02 16:04:17 +00002174 int needRestoreContext;
2175
drha76b5df2002-02-23 02:32:10 +00002176 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002177 if( pTabList->a[i].zName!=0 ){
2178 zSavedAuthContext = pParse->zAuthContext;
2179 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002180 needRestoreContext = 1;
2181 }else{
2182 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002183 }
drh6a3ea0e2003-05-02 14:32:12 +00002184 sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable,
2185 pTabList->a[i].iCursor, p, i, &isAgg);
drhc31c2eb2003-05-02 16:04:17 +00002186 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002187 pParse->zAuthContext = zSavedAuthContext;
2188 }
drh1b2e0322002-03-03 02:49:51 +00002189 pTabList = p->pSrc;
2190 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002191 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002192 pOrderBy = p->pOrderBy;
2193 }
drh1b2e0322002-03-03 02:49:51 +00002194 pGroupBy = p->pGroupBy;
2195 pHaving = p->pHaving;
2196 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002197 }
2198
drh832508b2002-03-02 17:04:07 +00002199 /* Check to see if this is a subquery that can be "flattened" into its parent.
2200 ** If flattening is a possiblity, do so and return immediately.
2201 */
drh1b2e0322002-03-03 02:49:51 +00002202 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002203 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002204 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002205 return rc;
2206 }
drh832508b2002-03-02 17:04:07 +00002207
drhe78e8282003-01-19 03:59:45 +00002208 /* Identify column types if we will be using a callback. This
2209 ** step is skipped if the output is going to a destination other
2210 ** than a callback.
drhfcb78a42003-01-18 20:11:05 +00002211 */
2212 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002213 generateColumnTypes(pParse, pTabList, pEList);
drhfcb78a42003-01-18 20:11:05 +00002214 }
2215
drh2d0794e2002-03-03 03:03:52 +00002216 /* If the output is destined for a temporary table, open that table.
2217 */
2218 if( eDest==SRT_TempTable ){
2219 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
2220 }
2221
drh22827922000-06-06 17:27:05 +00002222 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002223 */
drhd820cb12002-02-18 03:21:45 +00002224 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002225 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002226 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002227 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002228 for(i=0; i<pEList->nExpr; i++){
2229 if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002230 goto select_end;
drh22827922000-06-06 17:27:05 +00002231 }
2232 }
2233 if( pGroupBy ){
2234 for(i=0; i<pGroupBy->nExpr; i++){
2235 if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002236 goto select_end;
drh22827922000-06-06 17:27:05 +00002237 }
2238 }
2239 }
2240 if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002241 goto select_end;
drh22827922000-06-06 17:27:05 +00002242 }
drh191b6902000-06-08 11:13:01 +00002243 if( pOrderBy ){
2244 for(i=0; i<pOrderBy->nExpr; i++){
2245 if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002246 goto select_end;
drh191b6902000-06-08 11:13:01 +00002247 }
2248 }
2249 }
drhefb72512000-05-31 20:00:52 +00002250 }
2251
drh22827922000-06-06 17:27:05 +00002252 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002253 */
2254 if( isAgg ){
drh99fcd712001-10-13 01:06:47 +00002255 sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002256 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002257 FuncDef *pFunc;
2258 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drh1350b032002-02-27 19:00:20 +00002259 sqliteVdbeAddOp(v, OP_AggInit, 0, i);
drh0bce8352002-02-28 00:41:10 +00002260 sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
drhe5095352002-02-24 03:25:14 +00002261 }
2262 }
drh1bee3d72001-10-15 00:44:35 +00002263 if( pGroupBy==0 ){
2264 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002265 sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002266 }
drhcce7d172000-05-31 15:34:51 +00002267 }
2268
drh19a775c2000-06-05 18:54:46 +00002269 /* Initialize the memory cell to NULL
2270 */
drhfef52082000-06-06 01:50:43 +00002271 if( eDest==SRT_Mem ){
drh99fcd712001-10-13 01:06:47 +00002272 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh8721ce42001-11-07 14:22:00 +00002273 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002274 }
2275
drh832508b2002-03-02 17:04:07 +00002276 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002277 */
drh19a775c2000-06-05 18:54:46 +00002278 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002279 distinct = pParse->nTab++;
drhc6b52df2002-01-04 03:09:29 +00002280 sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
drh832508b2002-03-02 17:04:07 +00002281 }else{
2282 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002283 }
drh832508b2002-03-02 17:04:07 +00002284
2285 /* Begin the database scan
2286 */
drh6a3ea0e2003-05-02 14:32:12 +00002287 pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 0,
drh68d2e592002-08-04 00:52:38 +00002288 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002289 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002290
drh22827922000-06-06 17:27:05 +00002291 /* Use the standard inner loop if we are not dealing with
2292 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002293 */
drhda9d6c42000-05-31 18:20:14 +00002294 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002295 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2296 iParm, pWInfo->iContinue, pWInfo->iBreak) ){
drh1d83f052002-02-17 00:30:36 +00002297 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002298 }
drhcce7d172000-05-31 15:34:51 +00002299 }
drhefb72512000-05-31 20:00:52 +00002300
drhe3184742002-06-19 14:27:05 +00002301 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002302 ** processing.
drhefb72512000-05-31 20:00:52 +00002303 */
drh22827922000-06-06 17:27:05 +00002304 else{
drh22827922000-06-06 17:27:05 +00002305 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002306 int lbl1;
drh22827922000-06-06 17:27:05 +00002307 for(i=0; i<pGroupBy->nExpr; i++){
2308 sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
2309 }
drh99fcd712001-10-13 01:06:47 +00002310 sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
drh491791a2002-07-18 00:34:09 +00002311 if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pGroupBy);
drh1bee3d72001-10-15 00:44:35 +00002312 lbl1 = sqliteVdbeMakeLabel(v);
drh99fcd712001-10-13 01:06:47 +00002313 sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh22827922000-06-06 17:27:05 +00002314 for(i=0; i<pParse->nAgg; i++){
2315 if( pParse->aAgg[i].isAgg ) continue;
2316 sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
drh99fcd712001-10-13 01:06:47 +00002317 sqliteVdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002318 }
drh22827922000-06-06 17:27:05 +00002319 sqliteVdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002320 }
drh22827922000-06-06 17:27:05 +00002321 for(i=0; i<pParse->nAgg; i++){
2322 Expr *pE;
drh0bce8352002-02-28 00:41:10 +00002323 int j;
drh22827922000-06-06 17:27:05 +00002324 if( !pParse->aAgg[i].isAgg ) continue;
2325 pE = pParse->aAgg[i].pExpr;
drh22827922000-06-06 17:27:05 +00002326 assert( pE->op==TK_AGG_FUNCTION );
drh0bce8352002-02-28 00:41:10 +00002327 if( pE->pList ){
2328 for(j=0; j<pE->pList->nExpr; j++){
2329 sqliteExprCode(pParse, pE->pList->a[j].pExpr);
2330 }
drhe5095352002-02-24 03:25:14 +00002331 }
drh0bce8352002-02-28 00:41:10 +00002332 sqliteVdbeAddOp(v, OP_Integer, i, 0);
drhf55f25f2002-02-28 01:46:11 +00002333 sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
drh0bce8352002-02-28 00:41:10 +00002334 assert( pParse->aAgg[i].pFunc!=0 );
2335 assert( pParse->aAgg[i].pFunc->xStep!=0 );
2336 sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002337 }
drhcce7d172000-05-31 15:34:51 +00002338 }
2339
2340 /* End the database scan loop.
2341 */
2342 sqliteWhereEnd(pWInfo);
2343
drh22827922000-06-06 17:27:05 +00002344 /* If we are processing aggregates, we need to set up a second loop
2345 ** over all of the aggregate values and process them.
2346 */
2347 if( isAgg ){
2348 int endagg = sqliteVdbeMakeLabel(v);
2349 int startagg;
drh99fcd712001-10-13 01:06:47 +00002350 startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002351 pParse->useAgg = 1;
2352 if( pHaving ){
drhf5905aa2002-05-26 20:54:33 +00002353 sqliteExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002354 }
drhdf199a22002-06-14 22:38:41 +00002355 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
2356 iParm, startagg, endagg) ){
drh1d83f052002-02-17 00:30:36 +00002357 goto select_end;
drh22827922000-06-06 17:27:05 +00002358 }
drh99fcd712001-10-13 01:06:47 +00002359 sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
2360 sqliteVdbeResolveLabel(v, endagg);
2361 sqliteVdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002362 pParse->useAgg = 0;
2363 }
2364
drhcce7d172000-05-31 15:34:51 +00002365 /* If there is an ORDER BY clause, then we need to sort the results
2366 ** and send them to the callback one by one.
2367 */
2368 if( pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00002369 generateSortTail(p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002370 }
drh6a535342001-10-19 16:44:56 +00002371
2372
2373 /* Issue a null callback if that is what the user wants.
2374 */
drh326dce72003-01-29 14:06:07 +00002375 if( eDest==SRT_Callback &&
2376 (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
2377 ){
drh6a535342001-10-19 16:44:56 +00002378 sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
2379 }
2380
drh1d83f052002-02-17 00:30:36 +00002381 /* The SELECT was successfully coded. Set the return code to 0
2382 ** to indicate no errors.
2383 */
2384 rc = 0;
2385
2386 /* Control jumps to here if an error is encountered above, or upon
2387 ** successful coding of the SELECT.
2388 */
2389select_end:
2390 sqliteAggregateInfoReset(pParse);
2391 return rc;
drhcce7d172000-05-31 15:34:51 +00002392}