blob: 27e7f119343924570787b774cc01f7a1d1c205a1 [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**
danielk1977ededfd52004-06-17 07:53:01 +000015** $Id: select.c,v 1.192 2004/06/17 07:53:03 danielk1977 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*/
danielk19774adee202004-05-08 08:23:19 +000024Select *sqlite3SelectNew(
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 ){
danielk19774adee202004-05-08 08:23:19 +000038 sqlite3ExprListDelete(pEList);
39 sqlite3SrcListDelete(pSrc);
40 sqlite3ExprDelete(pWhere);
41 sqlite3ExprListDelete(pGroupBy);
42 sqlite3ExprDelete(pHaving);
43 sqlite3ExprListDelete(pOrderBy);
drhdaffd0e2001-04-11 14:28:42 +000044 }else{
drhb733d032004-01-24 20:18:12 +000045 if( pEList==0 ){
danielk19774adee202004-05-08 08:23:19 +000046 pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
drhb733d032004-01-24 20:18:12 +000047 }
drhdaffd0e2001-04-11 14:28:42 +000048 pNew->pEList = pEList;
49 pNew->pSrc = pSrc;
50 pNew->pWhere = pWhere;
51 pNew->pGroupBy = pGroupBy;
52 pNew->pHaving = pHaving;
53 pNew->pOrderBy = pOrderBy;
54 pNew->isDistinct = isDistinct;
55 pNew->op = TK_SELECT;
drh9bbca4c2001-11-06 04:00:18 +000056 pNew->nLimit = nLimit;
57 pNew->nOffset = nOffset;
drh7b58dae2003-07-20 01:16:46 +000058 pNew->iLimit = -1;
59 pNew->iOffset = -1;
drhdaffd0e2001-04-11 14:28:42 +000060 }
drh9bb61fe2000-06-05 16:01:39 +000061 return pNew;
62}
63
64/*
drh01f3f252002-05-24 16:14:15 +000065** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
66** type of join. Return an integer constant that expresses that type
67** in terms of the following bit values:
68**
69** JT_INNER
70** JT_OUTER
71** JT_NATURAL
72** JT_LEFT
73** JT_RIGHT
74**
75** A full outer join is the combination of JT_LEFT and JT_RIGHT.
76**
77** If an illegal or unsupported join type is seen, then still return
78** a join type, but put an error in the pParse structure.
79*/
danielk19774adee202004-05-08 08:23:19 +000080int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
drh01f3f252002-05-24 16:14:15 +000081 int jointype = 0;
82 Token *apAll[3];
83 Token *p;
84 static struct {
85 const char *zKeyword;
86 int nChar;
87 int code;
88 } keywords[] = {
89 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000090 { "left", 4, JT_LEFT|JT_OUTER },
91 { "right", 5, JT_RIGHT|JT_OUTER },
92 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +000093 { "outer", 5, JT_OUTER },
94 { "inner", 5, JT_INNER },
95 { "cross", 5, JT_INNER },
96 };
97 int i, j;
98 apAll[0] = pA;
99 apAll[1] = pB;
100 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +0000101 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +0000102 p = apAll[i];
103 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
104 if( p->n==keywords[j].nChar
danielk19774adee202004-05-08 08:23:19 +0000105 && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
drh01f3f252002-05-24 16:14:15 +0000106 jointype |= keywords[j].code;
107 break;
108 }
109 }
110 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
111 jointype |= JT_ERROR;
112 break;
113 }
114 }
drhad2d8302002-05-24 20:31:36 +0000115 if(
116 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000117 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000118 ){
drh01f3f252002-05-24 16:14:15 +0000119 static Token dummy = { 0, 0 };
120 char *zSp1 = " ", *zSp2 = " ";
121 if( pB==0 ){ pB = &dummy; zSp1 = 0; }
122 if( pC==0 ){ pC = &dummy; zSp2 = 0; }
danielk19774adee202004-05-08 08:23:19 +0000123 sqlite3SetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
drh01f3f252002-05-24 16:14:15 +0000124 pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
125 pParse->nErr++;
126 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000127 }else if( jointype & JT_RIGHT ){
danielk19774adee202004-05-08 08:23:19 +0000128 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000129 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000130 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000131 }
132 return jointype;
133}
134
135/*
drhad2d8302002-05-24 20:31:36 +0000136** Return the index of a column in a table. Return -1 if the column
137** is not contained in the table.
138*/
139static int columnIndex(Table *pTab, const char *zCol){
140 int i;
141 for(i=0; i<pTab->nCol; i++){
danielk19774adee202004-05-08 08:23:19 +0000142 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
drhad2d8302002-05-24 20:31:36 +0000143 }
144 return -1;
145}
146
147/*
148** Add a term to the WHERE expression in *ppExpr that requires the
149** zCol column to be equal in the two tables pTab1 and pTab2.
150*/
151static void addWhereTerm(
152 const char *zCol, /* Name of the column */
153 const Table *pTab1, /* First table */
154 const Table *pTab2, /* Second table */
155 Expr **ppExpr /* Add the equality term to this expression */
156){
157 Token dummy;
158 Expr *pE1a, *pE1b, *pE1c;
159 Expr *pE2a, *pE2b, *pE2c;
160 Expr *pE;
161
162 dummy.z = zCol;
163 dummy.n = strlen(zCol);
drh4b59ab52002-08-24 18:24:51 +0000164 dummy.dyn = 0;
danielk19774adee202004-05-08 08:23:19 +0000165 pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy);
166 pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy);
drhad2d8302002-05-24 20:31:36 +0000167 dummy.z = pTab1->zName;
168 dummy.n = strlen(dummy.z);
danielk19774adee202004-05-08 08:23:19 +0000169 pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy);
drhad2d8302002-05-24 20:31:36 +0000170 dummy.z = pTab2->zName;
171 dummy.n = strlen(dummy.z);
danielk19774adee202004-05-08 08:23:19 +0000172 pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy);
173 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
174 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
175 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000176 ExprSetProperty(pE, EP_FromJoin);
drhad2d8302002-05-24 20:31:36 +0000177 if( *ppExpr ){
danielk19774adee202004-05-08 08:23:19 +0000178 *ppExpr = sqlite3Expr(TK_AND, *ppExpr, pE, 0);
drhad2d8302002-05-24 20:31:36 +0000179 }else{
180 *ppExpr = pE;
181 }
182}
183
184/*
drh1f162302002-10-27 19:35:33 +0000185** Set the EP_FromJoin property on all terms of the given expression.
drh1cc093c2002-06-24 22:01:57 +0000186**
drhe78e8282003-01-19 03:59:45 +0000187** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000188** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000189** join restriction specified in the ON or USING clause and not a part
190** of the more general WHERE clause. These terms are moved over to the
191** WHERE clause during join processing but we need to remember that they
192** originated in the ON or USING clause.
drh1cc093c2002-06-24 22:01:57 +0000193*/
194static void setJoinExpr(Expr *p){
195 while( p ){
drh1f162302002-10-27 19:35:33 +0000196 ExprSetProperty(p, EP_FromJoin);
drh1cc093c2002-06-24 22:01:57 +0000197 setJoinExpr(p->pLeft);
198 p = p->pRight;
199 }
200}
201
202/*
drhad2d8302002-05-24 20:31:36 +0000203** This routine processes the join information for a SELECT statement.
204** ON and USING clauses are converted into extra terms of the WHERE clause.
205** NATURAL joins also create extra WHERE clause terms.
206**
207** This routine returns the number of errors encountered.
208*/
209static int sqliteProcessJoin(Parse *pParse, Select *p){
210 SrcList *pSrc;
211 int i, j;
212 pSrc = p->pSrc;
213 for(i=0; i<pSrc->nSrc-1; i++){
214 struct SrcList_item *pTerm = &pSrc->a[i];
215 struct SrcList_item *pOther = &pSrc->a[i+1];
216
217 if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
218
219 /* When the NATURAL keyword is present, add WHERE clause terms for
220 ** every column that the two tables have in common.
221 */
222 if( pTerm->jointype & JT_NATURAL ){
223 Table *pTab;
224 if( pTerm->pOn || pTerm->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000225 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000226 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000227 return 1;
228 }
229 pTab = pTerm->pTab;
230 for(j=0; j<pTab->nCol; j++){
231 if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
232 addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
233 }
234 }
235 }
236
237 /* Disallow both ON and USING clauses in the same join
238 */
239 if( pTerm->pOn && pTerm->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000240 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
drhda93d232003-03-31 02:12:46 +0000241 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000242 return 1;
243 }
244
245 /* Add the ON clause to the end of the WHERE clause, connected by
246 ** and AND operator.
247 */
248 if( pTerm->pOn ){
drh1cc093c2002-06-24 22:01:57 +0000249 setJoinExpr(pTerm->pOn);
drhad2d8302002-05-24 20:31:36 +0000250 if( p->pWhere==0 ){
251 p->pWhere = pTerm->pOn;
252 }else{
danielk19774adee202004-05-08 08:23:19 +0000253 p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pTerm->pOn, 0);
drhad2d8302002-05-24 20:31:36 +0000254 }
255 pTerm->pOn = 0;
256 }
257
258 /* Create extra terms on the WHERE clause for each column named
259 ** in the USING clause. Example: If the two tables to be joined are
260 ** A and B and the USING clause names X, Y, and Z, then add this
261 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
262 ** Report an error if any column mentioned in the USING clause is
263 ** not contained in both tables to be joined.
264 */
265 if( pTerm->pUsing ){
266 IdList *pList;
267 int j;
268 assert( i<pSrc->nSrc-1 );
269 pList = pTerm->pUsing;
270 for(j=0; j<pList->nId; j++){
drhbf5cd972002-06-24 12:20:23 +0000271 if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
272 columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
danielk19774adee202004-05-08 08:23:19 +0000273 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
drhda93d232003-03-31 02:12:46 +0000274 "not present in both tables", pList->a[j].zName);
drhad2d8302002-05-24 20:31:36 +0000275 return 1;
276 }
drhbf5cd972002-06-24 12:20:23 +0000277 addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000278 }
279 }
280 }
281 return 0;
282}
283
284/*
drh9bb61fe2000-06-05 16:01:39 +0000285** Delete the given Select structure and all of its substructures.
286*/
danielk19774adee202004-05-08 08:23:19 +0000287void sqlite3SelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000288 if( p==0 ) return;
danielk19774adee202004-05-08 08:23:19 +0000289 sqlite3ExprListDelete(p->pEList);
290 sqlite3SrcListDelete(p->pSrc);
291 sqlite3ExprDelete(p->pWhere);
292 sqlite3ExprListDelete(p->pGroupBy);
293 sqlite3ExprDelete(p->pHaving);
294 sqlite3ExprListDelete(p->pOrderBy);
295 sqlite3SelectDelete(p->pPrior);
drha76b5df2002-02-23 02:32:10 +0000296 sqliteFree(p->zSelect);
drh9bb61fe2000-06-05 16:01:39 +0000297 sqliteFree(p);
298}
299
300/*
drh22827922000-06-06 17:27:05 +0000301** Delete the aggregate information from the parse structure.
302*/
drh1d83f052002-02-17 00:30:36 +0000303static void sqliteAggregateInfoReset(Parse *pParse){
drh22827922000-06-06 17:27:05 +0000304 sqliteFree(pParse->aAgg);
305 pParse->aAgg = 0;
306 pParse->nAgg = 0;
drh22827922000-06-06 17:27:05 +0000307 pParse->useAgg = 0;
308}
309
310/*
drhc926afb2002-06-20 03:38:26 +0000311** Insert code into "v" that will push the record on the top of the
312** stack into the sorter.
313*/
314static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
drhc926afb2002-06-20 03:38:26 +0000315 int i;
drhc926afb2002-06-20 03:38:26 +0000316 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000317 sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
drhc926afb2002-06-20 03:38:26 +0000318 }
danielk1977ededfd52004-06-17 07:53:01 +0000319 sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +0000320 sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000321}
322
323/*
drh22827922000-06-06 17:27:05 +0000324** This routine generates the code for the inside of the inner loop
325** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000326**
drh38640e12002-07-05 21:42:36 +0000327** If srcTab and nColumn are both zero, then the pEList expressions
328** are evaluated in order to get the data for this row. If nColumn>0
329** then data is pulled from srcTab and pEList is used only to get the
330** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000331*/
332static int selectInnerLoop(
333 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000334 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000335 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000336 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000337 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000338 ExprList *pOrderBy, /* If not NULL, sort results using this key */
339 int distinct, /* If >=0, make sure results are distinct */
340 int eDest, /* How to dispose of the results */
341 int iParm, /* An argument to the disposal method */
342 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000343 int iBreak, /* Jump here to break out of the inner loop */
344 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000345){
346 Vdbe *v = pParse->pVdbe;
347 int i;
drh38640e12002-07-05 21:42:36 +0000348
drhdaffd0e2001-04-11 14:28:42 +0000349 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000350 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000351
drhdf199a22002-06-14 22:38:41 +0000352 /* If there was a LIMIT clause on the SELECT statement, then do the check
353 ** to see if this row should be output.
354 */
355 if( pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +0000356 if( p->iOffset>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000357 int addr = sqlite3VdbeCurrentAddr(v);
358 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2);
359 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhdf199a22002-06-14 22:38:41 +0000360 }
drh7b58dae2003-07-20 01:16:46 +0000361 if( p->iLimit>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000362 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhdf199a22002-06-14 22:38:41 +0000363 }
364 }
365
drh967e8b72000-06-21 13:59:10 +0000366 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000367 */
drh38640e12002-07-05 21:42:36 +0000368 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000369 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000370 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000371 }
drh38640e12002-07-05 21:42:36 +0000372 }else{
373 nColumn = pEList->nExpr;
374 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000375 sqlite3ExprCode(pParse, pEList->a[i].pExpr);
drh38640e12002-07-05 21:42:36 +0000376 }
drh22827922000-06-06 17:27:05 +0000377 }
378
drhdaffd0e2001-04-11 14:28:42 +0000379 /* If the DISTINCT keyword was present on the SELECT statement
380 ** and this row has been seen before, then do not make this row
381 ** part of the result.
drh22827922000-06-06 17:27:05 +0000382 */
drhf5905aa2002-05-26 20:54:33 +0000383 if( distinct>=0 && pEList && pEList->nExpr>0 ){
drh0bd1f4e2002-06-06 18:54:39 +0000384#if NULL_ALWAYS_DISTINCT
danielk19774adee202004-05-08 08:23:19 +0000385 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
drh0bd1f4e2002-06-06 18:54:39 +0000386#endif
danielk1977ededfd52004-06-17 07:53:01 +0000387 /* Deliberately leave the affinity string off of the following
388 ** OP_MakeRecord */
389 sqlite3VdbeAddOp(v, OP_MakeRecord, pEList->nExpr * -1, 0);
danielk19774adee202004-05-08 08:23:19 +0000390 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
391 sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
392 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
danielk19770f69c1e2004-05-29 11:24:50 +0000393 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000394 sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
drh22827922000-06-06 17:27:05 +0000395 }
drh82c3d632000-06-06 21:56:07 +0000396
drhc926afb2002-06-20 03:38:26 +0000397 switch( eDest ){
398 /* In this mode, write each query result to the key of the temporary
399 ** table iParm.
400 */
401 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000402 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000403 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000404 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000405 sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000406 break;
drh22827922000-06-06 17:27:05 +0000407 }
drh22827922000-06-06 17:27:05 +0000408
drhc926afb2002-06-20 03:38:26 +0000409 /* Store the result as data using a unique key.
410 */
411 case SRT_Table:
412 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000413 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000414 if( pOrderBy ){
415 pushOntoSorter(pParse, v, pOrderBy);
416 }else{
danielk19774adee202004-05-08 08:23:19 +0000417 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
418 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
419 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000420 }
421 break;
422 }
drh82c3d632000-06-06 21:56:07 +0000423
drhc926afb2002-06-20 03:38:26 +0000424 /* Construct a record from the query result, but instead of
425 ** saving that record, use it as a key to delete elements from
426 ** the temporary table iParm.
427 */
428 case SRT_Except: {
429 int addr;
danielk19774adee202004-05-08 08:23:19 +0000430 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000431 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000432 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
433 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000434 break;
435 }
drh5974a302000-06-07 14:42:26 +0000436
drhc926afb2002-06-20 03:38:26 +0000437 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
438 ** then there should be a single item on the stack. Write this
439 ** item into the set table with bogus data.
440 */
441 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000442 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000443 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000444
drhc926afb2002-06-20 03:38:26 +0000445 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000446 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
447 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
448 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000449 if( pOrderBy ){
450 pushOntoSorter(pParse, v, pOrderBy);
451 }else{
danielk1977e014a832004-05-17 10:48:57 +0000452 char const *affStr;
453 char aff = (iParm>>16)&0xFF;
454 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
455 affStr = sqlite3AffinityString(aff);
danielk1977ededfd52004-06-17 07:53:01 +0000456 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, affStr, P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000457 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000458 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000459 }
danielk19774adee202004-05-08 08:23:19 +0000460 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000461 break;
462 }
drh22827922000-06-06 17:27:05 +0000463
drhc926afb2002-06-20 03:38:26 +0000464 /* If this is a scalar select that is part of an expression, then
465 ** store the results in the appropriate memory cell and break out
466 ** of the scan loop.
467 */
468 case SRT_Mem: {
469 assert( nColumn==1 );
470 if( pOrderBy ){
471 pushOntoSorter(pParse, v, pOrderBy);
472 }else{
danielk19774adee202004-05-08 08:23:19 +0000473 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
474 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000475 }
476 break;
477 }
drh22827922000-06-06 17:27:05 +0000478
drhf46f9052002-06-22 02:33:38 +0000479 /* Send the data to the callback function.
480 */
481 case SRT_Callback:
482 case SRT_Sorter: {
483 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000484 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000485 pushOntoSorter(pParse, v, pOrderBy);
486 }else{
487 assert( eDest==SRT_Callback );
danielk19774adee202004-05-08 08:23:19 +0000488 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000489 }
490 break;
491 }
492
drh142e30d2002-08-28 03:00:58 +0000493 /* Invoke a subroutine to handle the results. The subroutine itself
494 ** is responsible for popping the results off of the stack.
495 */
496 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000497 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000498 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000499 pushOntoSorter(pParse, v, pOrderBy);
500 }else{
danielk19774adee202004-05-08 08:23:19 +0000501 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhac82fcf2002-09-08 17:23:41 +0000502 }
drh142e30d2002-08-28 03:00:58 +0000503 break;
504 }
505
drhc926afb2002-06-20 03:38:26 +0000506 /* Discard the results. This is used for SELECT statements inside
507 ** the body of a TRIGGER. The purpose of such selects is to call
508 ** user-defined functions that have side effects. We do not care
509 ** about the actual results of the select.
510 */
drhc926afb2002-06-20 03:38:26 +0000511 default: {
drhf46f9052002-06-22 02:33:38 +0000512 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000513 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000514 break;
515 }
drh82c3d632000-06-06 21:56:07 +0000516 }
517 return 0;
518}
519
520/*
drhd8bc7082000-06-07 23:51:50 +0000521** If the inner loop was generated using a non-null pOrderBy argument,
522** then the results were placed in a sorter. After the loop is terminated
523** we need to run the sorter and output the results. The following
524** routine generates the code needed to do that.
525*/
drhc926afb2002-06-20 03:38:26 +0000526static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000527 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000528 Select *p, /* The SELECT statement */
529 Vdbe *v, /* Generate code into this VDBE */
530 int nColumn, /* Number of columns of data */
531 int eDest, /* Write the sorted results here */
532 int iParm /* Optional parameter associated with eDest */
533){
danielk19774adee202004-05-08 08:23:19 +0000534 int end1 = sqlite3VdbeMakeLabel(v);
535 int end2 = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000536 int addr;
drhffbc3082004-05-21 01:29:06 +0000537 KeyInfo *pInfo;
538 ExprList *pOrderBy;
539 int nCol, i;
540 sqlite *db = pParse->db;
541
drhf46f9052002-06-22 02:33:38 +0000542 if( eDest==SRT_Sorter ) return;
drhffbc3082004-05-21 01:29:06 +0000543 pOrderBy = p->pOrderBy;
544 nCol = pOrderBy->nExpr;
545 pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
546 if( pInfo==0 ) return;
547 pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
548 pInfo->nField = nCol;
549 for(i=0; i<nCol; i++){
danielk19770202b292004-06-09 09:55:16 +0000550 /* If a collation sequence was specified explicity, then it
551 ** is stored in pOrderBy->a[i].zName. Otherwise, use the default
552 ** collation type for the expression.
553 */
danielk19777cedc8d2004-06-10 10:50:08 +0000554 pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr);
danielk19770202b292004-06-09 09:55:16 +0000555 if( !pInfo->aColl[i] ){
556 pInfo->aColl[i] = db->pDfltColl;
557 }
drhffbc3082004-05-21 01:29:06 +0000558 pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
559 }
560 sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
danielk19774adee202004-05-08 08:23:19 +0000561 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
drh7b58dae2003-07-20 01:16:46 +0000562 if( p->iOffset>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000563 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4);
564 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
565 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
drhdf199a22002-06-14 22:38:41 +0000566 }
drh7b58dae2003-07-20 01:16:46 +0000567 if( p->iLimit>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000568 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, end2);
drhdf199a22002-06-14 22:38:41 +0000569 }
drhc926afb2002-06-20 03:38:26 +0000570 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000571 case SRT_Table:
572 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000573 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
574 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
575 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000576 break;
577 }
578 case SRT_Set: {
579 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000580 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
581 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
582 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
danielk1977ededfd52004-06-17 07:53:01 +0000583 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000584 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000585 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000586 break;
587 }
588 case SRT_Mem: {
589 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000590 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
591 sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
drhc926afb2002-06-20 03:38:26 +0000592 break;
593 }
drhce665cf2004-05-21 03:01:58 +0000594 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000595 case SRT_Subroutine: {
596 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000597 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
598 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000599 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000600 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000601 }
drhce665cf2004-05-21 03:01:58 +0000602 if( eDest==SRT_Callback ){
603 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
604 }else{
605 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
606 }
danielk197784ac9d02004-05-18 09:58:06 +0000607 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000608 break;
609 }
drhc926afb2002-06-20 03:38:26 +0000610 default: {
drhf46f9052002-06-22 02:33:38 +0000611 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000612 break;
613 }
614 }
danielk19774adee202004-05-08 08:23:19 +0000615 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
616 sqlite3VdbeResolveLabel(v, end2);
617 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
618 sqlite3VdbeResolveLabel(v, end1);
619 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000620}
621
622/*
danielk1977517eb642004-06-07 10:00:31 +0000623** Return a pointer to a string containing the 'declaration type' of the
624** expression pExpr. The string may be treated as static by the caller.
drhe78e8282003-01-19 03:59:45 +0000625**
danielk1977517eb642004-06-07 10:00:31 +0000626** If the declaration type is the exact datatype definition extracted from
627** the original CREATE TABLE statement if the expression is a column.
628**
629** The declaration type for an expression is either TEXT, NUMERIC or ANY.
630** The declaration type for a ROWID field is INTEGER.
631*/
632static const char *columnType(Parse *pParse, SrcList *pTabList, Expr *pExpr){
633 char const *zType = 0;
634 int j;
635 if( pExpr==0 ) return 0;
636 if( pExpr->op==TK_COLUMN && pTabList ){
637 Table *pTab;
638 int iCol = pExpr->iColumn;
639 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable; j++){}
640 assert( j<pTabList->nSrc );
641 pTab = pTabList->a[j].pTab;
642 if( iCol<0 ) iCol = pTab->iPKey;
643 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
644 if( iCol<0 ){
645 zType = "INTEGER";
646 }else{
647 zType = pTab->aCol[iCol].zType;
danielk1977fbcd5852004-06-15 02:44:18 +0000648 if( !zType ) zType = "";
danielk1977517eb642004-06-07 10:00:31 +0000649 }
650 }else{
651 switch( sqlite3ExprType(pExpr) ){
652 case SQLITE_AFF_TEXT: zType = "TEXT"; break;
653 case SQLITE_AFF_NUMERIC: zType = "NUMERIC"; break;
654 default: zType = "ANY"; break;
655 }
656 }
657 return zType;
658}
659
660/*
661** Generate code that will tell the VDBE the declaration types of columns
662** in the result set.
drhfcb78a42003-01-18 20:11:05 +0000663*/
664static void generateColumnTypes(
665 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000666 SrcList *pTabList, /* List of tables */
667 ExprList *pEList /* Expressions defining the result set */
668){
669 Vdbe *v = pParse->pVdbe;
danielk1977517eb642004-06-07 10:00:31 +0000670 int i;
drhfcb78a42003-01-18 20:11:05 +0000671 for(i=0; i<pEList->nExpr; i++){
672 Expr *p = pEList->a[i].pExpr;
danielk1977517eb642004-06-07 10:00:31 +0000673 const char *zType = columnType(pParse, pTabList, p);
drhfcb78a42003-01-18 20:11:05 +0000674 if( p==0 ) continue;
danielk1977fbcd5852004-06-15 02:44:18 +0000675 /* The vdbe must make it's own copy of the column-type, in case the
676 ** schema is reset before this virtual machine is deleted.
677 */
678 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
drhfcb78a42003-01-18 20:11:05 +0000679 }
680}
681
682/*
683** Generate code that will tell the VDBE the names of columns
684** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000685** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000686*/
drh832508b2002-03-02 17:04:07 +0000687static void generateColumnNames(
688 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000689 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000690 ExprList *pEList /* Expressions defining the result set */
691){
drhd8bc7082000-06-07 23:51:50 +0000692 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000693 int i, j;
drhfcabd462004-02-20 14:50:58 +0000694 sqlite *db = pParse->db;
695 int fullNames, shortNames;
696
danielk19773cf86062004-05-26 10:11:05 +0000697 /* If this is an EXPLAIN, skip this step */
698 if( pParse->explain ){
danielk197761de0d12004-05-27 23:56:16 +0000699 return;
danielk19773cf86062004-05-26 10:11:05 +0000700 }
701
drhd6502752004-02-16 03:44:01 +0000702 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000703 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000704 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000705 fullNames = (db->flags & SQLITE_FullColNames)!=0;
706 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
danielk197722322fd2004-05-25 23:35:17 +0000707 sqlite3VdbeSetNumCols(v, pEList->nExpr);
drh82c3d632000-06-06 21:56:07 +0000708 for(i=0; i<pEList->nExpr; i++){
709 Expr *p;
drh5a387052003-01-11 14:19:51 +0000710 p = pEList->a[i].pExpr;
711 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000712 if( pEList->a[i].zName ){
713 char *zName = pEList->a[i].zName;
danielk1977d8123362004-06-12 09:25:12 +0000714 sqlite3VdbeSetColName(v, i, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000715 continue;
716 }
drhfa173a72002-07-10 21:26:00 +0000717 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000718 Table *pTab;
drh97665872002-02-13 23:22:53 +0000719 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000720 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000721 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
722 assert( j<pTabList->nSrc );
723 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000724 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000725 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000726 if( iCol<0 ){
727 zCol = "_ROWID_";
drhb1363202002-06-26 02:45:03 +0000728 }else{
729 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000730 }
drhfcabd462004-02-20 14:50:58 +0000731 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000732 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
drhfcabd462004-02-20 14:50:58 +0000733 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000734 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000735 char *zTab;
736
drh6a3ea0e2003-05-02 14:32:12 +0000737 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000738 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000739 sqlite3SetString(&zName, zTab, ".", zCol, 0);
danielk19773cf86062004-05-26 10:11:05 +0000740 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000741 }else{
danielk19773cf86062004-05-26 10:11:05 +0000742 sqlite3VdbeSetColName(v, i, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000743 }
drh6977fea2002-10-22 23:38:04 +0000744 }else if( p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000745 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
746 /* sqlite3VdbeCompressSpace(v, addr); */
drh1bee3d72001-10-15 00:44:35 +0000747 }else{
748 char zName[30];
749 assert( p->op!=TK_COLUMN || pTabList==0 );
750 sprintf(zName, "column%d", i+1);
danielk19773cf86062004-05-26 10:11:05 +0000751 sqlite3VdbeSetColName(v, i, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000752 }
753 }
danielk197776d505b2004-05-28 13:13:02 +0000754 generateColumnTypes(pParse, pTabList, pEList);
drh82c3d632000-06-06 21:56:07 +0000755}
756
757/*
drhd8bc7082000-06-07 23:51:50 +0000758** Name of the connection operator, used for error messages.
759*/
760static const char *selectOpName(int id){
761 char *z;
762 switch( id ){
763 case TK_ALL: z = "UNION ALL"; break;
764 case TK_INTERSECT: z = "INTERSECT"; break;
765 case TK_EXCEPT: z = "EXCEPT"; break;
766 default: z = "UNION"; break;
767 }
768 return z;
769}
770
771/*
drh315555c2002-10-20 15:53:03 +0000772** Forward declaration
773*/
774static int fillInColumnList(Parse*, Select*);
775
776/*
drh22f70c32002-02-18 01:17:00 +0000777** Given a SELECT statement, generate a Table structure that describes
778** the result set of that SELECT.
779*/
danielk19774adee202004-05-08 08:23:19 +0000780Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000781 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000782 int i, j;
drh22f70c32002-02-18 01:17:00 +0000783 ExprList *pEList;
drhb733d032004-01-24 20:18:12 +0000784 Column *aCol;
drh22f70c32002-02-18 01:17:00 +0000785
786 if( fillInColumnList(pParse, pSelect) ){
787 return 0;
788 }
789 pTab = sqliteMalloc( sizeof(Table) );
790 if( pTab==0 ){
791 return 0;
792 }
793 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
794 pEList = pSelect->pEList;
795 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000796 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000797 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh22f70c32002-02-18 01:17:00 +0000798 for(i=0; i<pTab->nCol; i++){
danielk1977517eb642004-06-07 10:00:31 +0000799 Expr *pR;
800 char *zType;
801 Expr *p = pEList->a[i].pExpr;
drh22f70c32002-02-18 01:17:00 +0000802 if( pEList->a[i].zName ){
drhb733d032004-01-24 20:18:12 +0000803 aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
danielk1977517eb642004-06-07 10:00:31 +0000804 }else if( p->op==TK_DOT
drhb733d032004-01-24 20:18:12 +0000805 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
806 int cnt;
danielk19774adee202004-05-08 08:23:19 +0000807 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
drhb733d032004-01-24 20:18:12 +0000808 for(j=cnt=0; j<i; j++){
danielk19774adee202004-05-08 08:23:19 +0000809 if( sqlite3StrICmp(aCol[j].zName, aCol[i].zName)==0 ){
drhb733d032004-01-24 20:18:12 +0000810 int n;
811 char zBuf[30];
812 sprintf(zBuf,"_%d",++cnt);
813 n = strlen(zBuf);
danielk1977e014a832004-05-17 10:48:57 +0000814 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf,n,0);
drhb733d032004-01-24 20:18:12 +0000815 j = -1;
816 }
817 }
818 }else if( p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000819 sqlite3SetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drh22f70c32002-02-18 01:17:00 +0000820 }else{
821 char zBuf[30];
822 sprintf(zBuf, "column%d", i+1);
823 pTab->aCol[i].zName = sqliteStrDup(zBuf);
824 }
danielk1977517eb642004-06-07 10:00:31 +0000825
826 zType = sqliteStrDup(columnType(pParse, pSelect->pSrc ,p));
827 pTab->aCol[i].zType = zType;
828 pTab->aCol[i].affinity = SQLITE_AFF_NUMERIC;
829 if( zType ){
830 pTab->aCol[i].affinity = sqlite3AffinityType(zType, strlen(zType));
831 }
danielk19777cedc8d2004-06-10 10:50:08 +0000832 pTab->aCol[i].pColl = sqlite3ExprCollSeq(pParse, p);
danielk19770202b292004-06-09 09:55:16 +0000833 if( !pTab->aCol[i].pColl ){
834 pTab->aCol[i].pColl = pParse->db->pDfltColl;
835 }
drh22f70c32002-02-18 01:17:00 +0000836 }
837 pTab->iPKey = -1;
838 return pTab;
839}
840
841/*
drhad2d8302002-05-24 20:31:36 +0000842** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000843**
drhad3cab52002-05-24 02:04:32 +0000844** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh63eb5f22003-04-29 16:20:44 +0000845** defines the set of tables that should be scanned. For views,
846** fill pTabList->a[].pSelect with a copy of the SELECT statement
847** that implements the view. A copy is made of the view's SELECT
848** statement so that we can freely modify or delete that statement
849** without worrying about messing up the presistent representation
850** of the view.
drhd8bc7082000-06-07 23:51:50 +0000851**
drhad2d8302002-05-24 20:31:36 +0000852** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
853** on joins and the ON and USING clause of joins.
854**
855** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000856** for instances of the "*" operator or the TABLE.* operator.
857** If found, expand each "*" to be every column in every table
858** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000859**
860** Return 0 on success. If there are problems, leave an error message
861** in pParse and return non-zero.
862*/
863static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000864 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000865 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000866 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000867 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000868
869 if( p==0 || p->pSrc==0 ) return 1;
870 pTabList = p->pSrc;
871 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000872
873 /* Look up every table in the table list.
874 */
drhad3cab52002-05-24 02:04:32 +0000875 for(i=0; i<pTabList->nSrc; i++){
drhd8bc7082000-06-07 23:51:50 +0000876 if( pTabList->a[i].pTab ){
877 /* This routine has run before! No need to continue */
878 return 0;
879 }
drhdaffd0e2001-04-11 14:28:42 +0000880 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000881 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000882 assert( pTabList->a[i].pSelect!=0 );
drhad2d8302002-05-24 20:31:36 +0000883 if( pTabList->a[i].zAlias==0 ){
884 char zFakeName[60];
885 sprintf(zFakeName, "sqlite_subquery_%p_",
886 (void*)pTabList->a[i].pSelect);
danielk19774adee202004-05-08 08:23:19 +0000887 sqlite3SetString(&pTabList->a[i].zAlias, zFakeName, 0);
drhad2d8302002-05-24 20:31:36 +0000888 }
drh22f70c32002-02-18 01:17:00 +0000889 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000890 sqlite3ResultSetOfSelect(pParse, pTabList->a[i].zAlias,
drh22f70c32002-02-18 01:17:00 +0000891 pTabList->a[i].pSelect);
892 if( pTab==0 ){
893 return 1;
894 }
drh5cf590c2003-04-24 01:45:04 +0000895 /* The isTransient flag indicates that the Table structure has been
896 ** dynamically allocated and may be freed at any time. In other words,
897 ** pTab is not pointing to a persistent table structure that defines
898 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000899 pTab->isTransient = 1;
900 }else{
drha76b5df2002-02-23 02:32:10 +0000901 /* An ordinary table or view name in the FROM clause */
902 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000903 sqlite3LocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
drha76b5df2002-02-23 02:32:10 +0000904 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000905 return 1;
906 }
drha76b5df2002-02-23 02:32:10 +0000907 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +0000908 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +0000909 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +0000910 return 1;
911 }
drh63eb5f22003-04-29 16:20:44 +0000912 /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
913 ** view within a view. The SELECT structure has already been
914 ** copied by the outer view so we can skip the copy step here
915 ** in the inner view.
916 */
917 if( pTabList->a[i].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +0000918 pTabList->a[i].pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +0000919 }
drha76b5df2002-02-23 02:32:10 +0000920 }
drhd8bc7082000-06-07 23:51:50 +0000921 }
922 }
923
drhad2d8302002-05-24 20:31:36 +0000924 /* Process NATURAL keywords, and ON and USING clauses of joins.
925 */
926 if( sqliteProcessJoin(pParse, p) ) return 1;
927
drh7c917d12001-12-16 20:05:05 +0000928 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000929 ** all columns in all tables. And for every TABLE.* insert the names
930 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000931 ** with the TK_ALL operator for each "*" that it found in the column list.
932 ** The following code just has to locate the TK_ALL expressions and expand
933 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000934 **
935 ** The first loop just checks to see if there are any "*" operators
936 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000937 */
drh7c917d12001-12-16 20:05:05 +0000938 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000939 Expr *pE = pEList->a[k].pExpr;
940 if( pE->op==TK_ALL ) break;
941 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
942 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000943 }
drh54473222002-04-04 02:10:55 +0000944 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000945 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000946 /*
947 ** If we get here it means the result set contains one or more "*"
948 ** operators that need to be expanded. Loop through each expression
949 ** in the result set and expand them one by one.
950 */
drh7c917d12001-12-16 20:05:05 +0000951 struct ExprList_item *a = pEList->a;
952 ExprList *pNew = 0;
953 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000954 Expr *pE = a[k].pExpr;
955 if( pE->op!=TK_ALL &&
956 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
957 /* This particular expression does not need to be expanded.
958 */
danielk19774adee202004-05-08 08:23:19 +0000959 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +0000960 pNew->a[pNew->nExpr-1].zName = a[k].zName;
961 a[k].pExpr = 0;
962 a[k].zName = 0;
963 }else{
drh54473222002-04-04 02:10:55 +0000964 /* This expression is a "*" or a "TABLE.*" and needs to be
965 ** expanded. */
966 int tableSeen = 0; /* Set to 1 when TABLE matches */
967 Token *pName; /* text of name of TABLE */
968 if( pE->op==TK_DOT && pE->pLeft ){
969 pName = &pE->pLeft->token;
970 }else{
971 pName = 0;
972 }
drhad3cab52002-05-24 02:04:32 +0000973 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000974 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000975 char *zTabName = pTabList->a[i].zAlias;
976 if( zTabName==0 || zTabName[0]==0 ){
977 zTabName = pTab->zName;
978 }
drhc754fa52002-05-27 03:25:51 +0000979 if( pName && (zTabName==0 || zTabName[0]==0 ||
danielk19774adee202004-05-08 08:23:19 +0000980 sqlite3StrNICmp(pName->z, zTabName, pName->n)!=0 ||
drhc754fa52002-05-27 03:25:51 +0000981 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +0000982 continue;
983 }
984 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +0000985 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000986 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +0000987 char *zName = pTab->aCol[j].zName;
988
989 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
990 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
991 /* In a NATURAL join, omit the join columns from the
992 ** table on the right */
993 continue;
994 }
danielk19774adee202004-05-08 08:23:19 +0000995 if( i>0 && sqlite3IdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
drhad2d8302002-05-24 20:31:36 +0000996 /* In a join with a USING clause, omit columns in the
997 ** using clause from the table on the right. */
998 continue;
999 }
danielk19774adee202004-05-08 08:23:19 +00001000 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001001 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +00001002 pRight->token.z = zName;
1003 pRight->token.n = strlen(zName);
drh4b59ab52002-08-24 18:24:51 +00001004 pRight->token.dyn = 0;
drh4b59ab52002-08-24 18:24:51 +00001005 if( zTabName && pTabList->nSrc>1 ){
danielk19774adee202004-05-08 08:23:19 +00001006 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1007 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001008 if( pExpr==0 ) break;
drh4b59ab52002-08-24 18:24:51 +00001009 pLeft->token.z = zTabName;
1010 pLeft->token.n = strlen(zTabName);
1011 pLeft->token.dyn = 0;
danielk19774adee202004-05-08 08:23:19 +00001012 sqlite3SetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
drh6977fea2002-10-22 23:38:04 +00001013 pExpr->span.n = strlen(pExpr->span.z);
1014 pExpr->span.dyn = 1;
1015 pExpr->token.z = 0;
1016 pExpr->token.n = 0;
1017 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001018 }else{
drh22f70c32002-02-18 01:17:00 +00001019 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001020 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001021 }
danielk19774adee202004-05-08 08:23:19 +00001022 pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001023 }
drh17e24df2001-11-06 14:10:41 +00001024 }
drh54473222002-04-04 02:10:55 +00001025 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +00001026 if( pName ){
danielk19774adee202004-05-08 08:23:19 +00001027 sqlite3ErrorMsg(pParse, "no such table: %T", pName);
drhf5db2d32002-06-06 23:42:27 +00001028 }else{
danielk19774adee202004-05-08 08:23:19 +00001029 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001030 }
drh54473222002-04-04 02:10:55 +00001031 rc = 1;
1032 }
drhd8bc7082000-06-07 23:51:50 +00001033 }
1034 }
danielk19774adee202004-05-08 08:23:19 +00001035 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001036 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001037 }
drh54473222002-04-04 02:10:55 +00001038 return rc;
drhd8bc7082000-06-07 23:51:50 +00001039}
1040
1041/*
drhff78bd22002-02-27 01:47:11 +00001042** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1043** in a select structure. It just sets the pointers to NULL. This
1044** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1045** pointer is not NULL, this routine is called recursively on that pointer.
1046**
1047** This routine is called on the Select structure that defines a
1048** VIEW in order to undo any bindings to tables. This is necessary
1049** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001050** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1051** will be left pointing to a deallocated Table structure after the
1052** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001053*/
danielk19774adee202004-05-08 08:23:19 +00001054void sqlite3SelectUnbind(Select *p){
drhff78bd22002-02-27 01:47:11 +00001055 int i;
drhad3cab52002-05-24 02:04:32 +00001056 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +00001057 Table *pTab;
1058 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +00001059 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +00001060 if( (pTab = pSrc->a[i].pTab)!=0 ){
1061 if( pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001062 sqlite3DeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001063 }
1064 pSrc->a[i].pTab = 0;
1065 if( pSrc->a[i].pSelect ){
danielk19774adee202004-05-08 08:23:19 +00001066 sqlite3SelectUnbind(pSrc->a[i].pSelect);
drhff78bd22002-02-27 01:47:11 +00001067 }
1068 }
1069 }
1070}
1071
1072/*
drhd8bc7082000-06-07 23:51:50 +00001073** This routine associates entries in an ORDER BY expression list with
1074** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001075** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001076** the top-level node is filled in with column number and the iTable
1077** value of the top-level node is filled with iTable parameter.
1078**
1079** If there are prior SELECT clauses, they are processed first. A match
1080** in an earlier SELECT takes precedence over a later SELECT.
1081**
1082** Any entry that does not match is flagged as an error. The number
1083** of errors is returned.
1084*/
1085static int matchOrderbyToColumn(
1086 Parse *pParse, /* A place to leave error messages */
1087 Select *pSelect, /* Match to result columns of this SELECT */
1088 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001089 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001090 int mustComplete /* If TRUE all ORDER BYs must match */
1091){
1092 int nErr = 0;
1093 int i, j;
1094 ExprList *pEList;
1095
drhdaffd0e2001-04-11 14:28:42 +00001096 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001097 if( mustComplete ){
1098 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1099 }
1100 if( fillInColumnList(pParse, pSelect) ){
1101 return 1;
1102 }
1103 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001104 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1105 return 1;
1106 }
drhd8bc7082000-06-07 23:51:50 +00001107 }
1108 pEList = pSelect->pEList;
1109 for(i=0; i<pOrderBy->nExpr; i++){
1110 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001111 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001112 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001113 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001114 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001115 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001116 "ORDER BY position %d should be between 1 and %d",
1117 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001118 nErr++;
1119 break;
1120 }
drhfcb78a42003-01-18 20:11:05 +00001121 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001122 iCol--;
1123 }
1124 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001125 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001126 char *zName, *zLabel;
1127 zName = pEList->a[j].zName;
1128 assert( pE->token.z );
1129 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
danielk19774adee202004-05-08 08:23:19 +00001130 sqlite3Dequote(zLabel);
1131 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001132 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001133 }
drh6e142f52000-06-08 13:36:40 +00001134 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001135 }
danielk19774adee202004-05-08 08:23:19 +00001136 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001137 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001138 }
1139 }
drhe4de1fe2002-06-02 16:09:01 +00001140 if( iCol>=0 ){
1141 pE->op = TK_COLUMN;
1142 pE->iColumn = iCol;
1143 pE->iTable = iTable;
1144 pOrderBy->a[i].done = 1;
1145 }
1146 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001147 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001148 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001149 nErr++;
1150 break;
1151 }
1152 }
1153 return nErr;
1154}
1155
1156/*
1157** Get a VDBE for the given parser context. Create a new one if necessary.
1158** If an error occurs, return NULL and leave a message in pParse.
1159*/
danielk19774adee202004-05-08 08:23:19 +00001160Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001161 Vdbe *v = pParse->pVdbe;
1162 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001163 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001164 }
drhd8bc7082000-06-07 23:51:50 +00001165 return v;
1166}
drhfcb78a42003-01-18 20:11:05 +00001167
drhd3d39e92004-05-20 22:16:29 +00001168#if 0 /***** This routine needs deleting *****/
danielk197784ac9d02004-05-18 09:58:06 +00001169static void multiSelectAffinity(Select *p, char *zAff){
1170 int i;
1171
1172 if( !p ) return;
1173 multiSelectAffinity(p->pPrior, zAff);
1174
1175 for(i=0; i<p->pEList->nExpr; i++){
1176 if( zAff[i]=='\0' ){
1177 zAff[i] = sqlite3ExprAffinity(p->pEList->a[i].pExpr);
1178 }
1179 }
1180}
drhd3d39e92004-05-20 22:16:29 +00001181#endif
danielk197784ac9d02004-05-18 09:58:06 +00001182
drhd8bc7082000-06-07 23:51:50 +00001183/*
drh7b58dae2003-07-20 01:16:46 +00001184** Compute the iLimit and iOffset fields of the SELECT based on the
1185** nLimit and nOffset fields. nLimit and nOffset hold the integers
1186** that appear in the original SQL statement after the LIMIT and OFFSET
1187** keywords. Or that hold -1 and 0 if those keywords are omitted.
1188** iLimit and iOffset are the integer memory register numbers for
1189** counters used to compute the limit and offset. If there is no
1190** limit and/or offset, then iLimit and iOffset are negative.
1191**
1192** This routine changes the values if iLimit and iOffset only if
1193** a limit or offset is defined by nLimit and nOffset. iLimit and
1194** iOffset should have been preset to appropriate default values
1195** (usually but not always -1) prior to calling this routine.
1196** Only if nLimit>=0 or nOffset>0 do the limit registers get
1197** redefined. The UNION ALL operator uses this property to force
1198** the reuse of the same limit and offset registers across multiple
1199** SELECT statements.
1200*/
1201static void computeLimitRegisters(Parse *pParse, Select *p){
1202 /*
1203 ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
1204 ** all rows. It is the same as no limit. If the comparision is
1205 ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
1206 ** "LIMIT -1" always shows all rows. There is some
1207 ** contraversy about what the correct behavior should be.
1208 ** The current implementation interprets "LIMIT 0" to mean
1209 ** no rows.
1210 */
1211 if( p->nLimit>=0 ){
1212 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001213 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001214 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001215 sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1216 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001217 p->iLimit = iMem;
1218 }
1219 if( p->nOffset>0 ){
1220 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001221 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001222 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001223 sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1224 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001225 p->iOffset = iMem;
1226 }
1227}
1228
1229/*
drhd3d39e92004-05-20 22:16:29 +00001230** Generate VDBE instructions that will open a transient table that
1231** will be used for an index or to store keyed results for a compound
1232** select. In other words, open a transient table that needs a
1233** KeyInfo structure. The number of columns in the KeyInfo is determined
1234** by the result set of the SELECT statement in the second argument.
1235**
danielk1977dc1bdc42004-06-11 10:51:27 +00001236** Specifically, this routine is called to open an index table for
1237** DISTINCT, UNION, INTERSECT and EXCEPT select statements (but not
1238** UNION ALL).
1239**
drhd3d39e92004-05-20 22:16:29 +00001240** Make the new table a KeyAsData table if keyAsData is true.
danielk1977dc1bdc42004-06-11 10:51:27 +00001241**
1242** The value returned is the address of the OP_OpenTemp instruction.
drhd3d39e92004-05-20 22:16:29 +00001243*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001244static int openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
drhd3d39e92004-05-20 22:16:29 +00001245 KeyInfo *pKeyInfo;
drh736c22b2004-05-21 02:14:24 +00001246 int nColumn;
drhd3d39e92004-05-20 22:16:29 +00001247 sqlite *db = pParse->db;
1248 int i;
1249 Vdbe *v = pParse->pVdbe;
danielk1977dc1bdc42004-06-11 10:51:27 +00001250 int addr;
drhd3d39e92004-05-20 22:16:29 +00001251
drh736c22b2004-05-21 02:14:24 +00001252 if( fillInColumnList(pParse, p) ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001253 return 0;
drh736c22b2004-05-21 02:14:24 +00001254 }
1255 nColumn = p->pEList->nExpr;
drhd3d39e92004-05-20 22:16:29 +00001256 pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
danielk1977dc1bdc42004-06-11 10:51:27 +00001257 if( pKeyInfo==0 ) return 0;
1258 pKeyInfo->enc = pParse->db->enc;
drhd3d39e92004-05-20 22:16:29 +00001259 pKeyInfo->nField = nColumn;
1260 for(i=0; i<nColumn; i++){
danielk1977dc1bdc42004-06-11 10:51:27 +00001261 pKeyInfo->aColl[i] = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
1262 if( !pKeyInfo->aColl[i] ){
1263 pKeyInfo->aColl[i] = db->pDfltColl;
1264 }
drhd3d39e92004-05-20 22:16:29 +00001265 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001266 addr = sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0,
1267 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drhd3d39e92004-05-20 22:16:29 +00001268 if( keyAsData ){
1269 sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1270 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001271 return addr;
1272}
1273
1274static int multiSelectOpenTempAddr(Select *p, int addr, IdList **ppOpenTemp){
1275 if( !p->ppOpenTemp ){
1276 *ppOpenTemp = sqlite3IdListAppend(0, 0);
1277 p->ppOpenTemp = ppOpenTemp;
1278 }else{
1279 *p->ppOpenTemp = sqlite3IdListAppend(*p->ppOpenTemp, 0);
1280 }
1281 if( !(*p->ppOpenTemp) ){
1282 return SQLITE_NOMEM;
1283 }
1284 (*p->ppOpenTemp)->a[(*p->ppOpenTemp)->nId-1].idx = addr;
1285 return SQLITE_OK;
1286}
1287
1288static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1289 CollSeq *pRet = 0;
1290 if( p->pPrior ){
1291 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1292 }
1293 if( !pRet ){
1294 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1295 }
1296 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001297}
1298
1299/*
drh82c3d632000-06-06 21:56:07 +00001300** This routine is called to process a query that is really the union
1301** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001302**
drhe78e8282003-01-19 03:59:45 +00001303** "p" points to the right-most of the two queries. the query on the
1304** left is p->pPrior. The left query could also be a compound query
1305** in which case this routine will be called recursively.
1306**
1307** The results of the total query are to be written into a destination
1308** of type eDest with parameter iParm.
1309**
1310** Example 1: Consider a three-way compound SQL statement.
1311**
1312** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1313**
1314** This statement is parsed up as follows:
1315**
1316** SELECT c FROM t3
1317** |
1318** `-----> SELECT b FROM t2
1319** |
jplyon4b11c6d2004-01-19 04:57:53 +00001320** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001321**
1322** The arrows in the diagram above represent the Select.pPrior pointer.
1323** So if this routine is called with p equal to the t3 query, then
1324** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1325**
1326** Notice that because of the way SQLite parses compound SELECTs, the
1327** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001328*/
danielk197784ac9d02004-05-18 09:58:06 +00001329static int multiSelect(
1330 Parse *pParse,
1331 Select *p,
1332 int eDest,
1333 int iParm,
1334 char *aff /* If eDest is SRT_Union, the affinity string */
1335){
1336 int rc = SQLITE_OK; /* Success code from a subroutine */
drh10e5e3c2000-06-08 00:19:02 +00001337 Select *pPrior; /* Another SELECT immediately to our left */
1338 Vdbe *v; /* Generate code to this VDBE */
danielk1977dc1bdc42004-06-11 10:51:27 +00001339 IdList *pOpenTemp = 0;
drh82c3d632000-06-06 21:56:07 +00001340
drh7b58dae2003-07-20 01:16:46 +00001341 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
1342 ** the last SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001343 */
danielk197784ac9d02004-05-18 09:58:06 +00001344 if( p==0 || p->pPrior==0 ){
1345 rc = 1;
1346 goto multi_select_end;
1347 }
drhd8bc7082000-06-07 23:51:50 +00001348 pPrior = p->pPrior;
1349 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001350 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001351 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001352 rc = 1;
1353 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001354 }
drh7b58dae2003-07-20 01:16:46 +00001355 if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
danielk19774adee202004-05-08 08:23:19 +00001356 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001357 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001358 rc = 1;
1359 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001360 }
drh82c3d632000-06-06 21:56:07 +00001361
drhd8bc7082000-06-07 23:51:50 +00001362 /* Make sure we have a valid query engine. If not, create a new one.
1363 */
danielk19774adee202004-05-08 08:23:19 +00001364 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001365 if( v==0 ){
1366 rc = 1;
1367 goto multi_select_end;
1368 }
drhd8bc7082000-06-07 23:51:50 +00001369
drh1cc3d752002-03-23 00:31:29 +00001370 /* Create the destination temporary table if necessary
1371 */
1372 if( eDest==SRT_TempTable ){
danielk1977b4964b72004-05-18 01:23:38 +00001373 assert( p->pEList );
danielk19774adee202004-05-08 08:23:19 +00001374 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00001375 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, p->pEList->nExpr);
drh1cc3d752002-03-23 00:31:29 +00001376 eDest = SRT_Table;
1377 }
1378
drhf46f9052002-06-22 02:33:38 +00001379 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001380 */
drh82c3d632000-06-06 21:56:07 +00001381 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001382 case TK_ALL: {
1383 if( p->pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +00001384 pPrior->nLimit = p->nLimit;
1385 pPrior->nOffset = p->nOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001386 pPrior->ppOpenTemp = p->ppOpenTemp;
danielk197784ac9d02004-05-18 09:58:06 +00001387 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1388 if( rc ){
1389 goto multi_select_end;
1390 }
drhf46f9052002-06-22 02:33:38 +00001391 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001392 p->iLimit = pPrior->iLimit;
1393 p->iOffset = pPrior->iOffset;
1394 p->nLimit = -1;
1395 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001396 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001397 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001398 if( rc ){
1399 goto multi_select_end;
1400 }
drhf46f9052002-06-22 02:33:38 +00001401 break;
1402 }
1403 /* For UNION ALL ... ORDER BY fall through to the next case */
1404 }
drh82c3d632000-06-06 21:56:07 +00001405 case TK_EXCEPT:
1406 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001407 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001408 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001409 int priorOp; /* The SRT_ operation to apply to prior selects */
drh7b58dae2003-07-20 01:16:46 +00001410 int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
drhc926afb2002-06-20 03:38:26 +00001411 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
danielk1977dc1bdc42004-06-11 10:51:27 +00001412 int addr;
drh82c3d632000-06-06 21:56:07 +00001413
drhd8bc7082000-06-07 23:51:50 +00001414 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh7b58dae2003-07-20 01:16:46 +00001415 if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
drhd8bc7082000-06-07 23:51:50 +00001416 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001417 ** right.
drhd8bc7082000-06-07 23:51:50 +00001418 */
drh82c3d632000-06-06 21:56:07 +00001419 unionTab = iParm;
1420 }else{
drhd8bc7082000-06-07 23:51:50 +00001421 /* We will need to create our own temporary table to hold the
1422 ** intermediate results.
1423 */
1424 unionTab = pParse->nTab++;
1425 if( p->pOrderBy
1426 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001427 rc = 1;
1428 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001429 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001430 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001431 if( p->op!=TK_ALL ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001432 rc = multiSelectOpenTempAddr(p, addr, &pOpenTemp);
1433 if( rc!=SQLITE_OK ){
1434 goto multi_select_end;
1435 }
1436 sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drhd8bc7082000-06-07 23:51:50 +00001437 }
danielk197784ac9d02004-05-18 09:58:06 +00001438 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001439 }
drhd8bc7082000-06-07 23:51:50 +00001440
1441 /* Code the SELECT statements to our left
1442 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001443 pPrior->ppOpenTemp = p->ppOpenTemp;
danielk197784ac9d02004-05-18 09:58:06 +00001444 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
1445 if( rc ){
1446 goto multi_select_end;
1447 }
1448 if( p->op==TK_ALL ){
1449 sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, pPrior->pEList->nExpr);
1450 }
drhd8bc7082000-06-07 23:51:50 +00001451
1452 /* Code the current SELECT statement
1453 */
1454 switch( p->op ){
1455 case TK_EXCEPT: op = SRT_Except; break;
1456 case TK_UNION: op = SRT_Union; break;
1457 case TK_ALL: op = SRT_Table; break;
1458 }
drh82c3d632000-06-06 21:56:07 +00001459 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001460 pOrderBy = p->pOrderBy;
1461 p->pOrderBy = 0;
drh7b58dae2003-07-20 01:16:46 +00001462 nLimit = p->nLimit;
1463 p->nLimit = -1;
1464 nOffset = p->nOffset;
1465 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001466 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001467 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001468 p->pOrderBy = pOrderBy;
drh7b58dae2003-07-20 01:16:46 +00001469 p->nLimit = nLimit;
1470 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001471 if( rc ){
1472 goto multi_select_end;
1473 }
1474
drhd8bc7082000-06-07 23:51:50 +00001475
1476 /* Convert the data in the temporary table into whatever form
1477 ** it is that we currently need.
1478 */
drhc926afb2002-06-20 03:38:26 +00001479 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001480 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001481 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001482 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001483 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001484 }
danielk19774adee202004-05-08 08:23:19 +00001485 iBreak = sqlite3VdbeMakeLabel(v);
1486 iCont = sqlite3VdbeMakeLabel(v);
1487 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001488 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001489 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001490 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001491 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001492 iCont, iBreak, 0);
1493 if( rc ){
1494 rc = 1;
1495 goto multi_select_end;
1496 }
danielk19774adee202004-05-08 08:23:19 +00001497 sqlite3VdbeResolveLabel(v, iCont);
1498 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1499 sqlite3VdbeResolveLabel(v, iBreak);
1500 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001501 }
1502 break;
1503 }
1504 case TK_INTERSECT: {
1505 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001506 int iCont, iBreak, iStart;
drh7b58dae2003-07-20 01:16:46 +00001507 int nLimit, nOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001508 int addr;
drh82c3d632000-06-06 21:56:07 +00001509
drhd8bc7082000-06-07 23:51:50 +00001510 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001511 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001512 ** by allocating the tables we will need.
1513 */
drh82c3d632000-06-06 21:56:07 +00001514 tab1 = pParse->nTab++;
1515 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001516 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001517 rc = 1;
1518 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001519 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001520
1521 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 0);
1522 rc = multiSelectOpenTempAddr(p, addr, &pOpenTemp);
1523 if( rc!=SQLITE_OK ){
1524 goto multi_select_end;
1525 }
1526 sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
danielk197784ac9d02004-05-18 09:58:06 +00001527 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001528
1529 /* Code the SELECTs to our left into temporary table "tab1".
1530 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001531 pPrior->ppOpenTemp = p->ppOpenTemp;
danielk197784ac9d02004-05-18 09:58:06 +00001532 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
1533 if( rc ){
1534 goto multi_select_end;
1535 }
drhd8bc7082000-06-07 23:51:50 +00001536
1537 /* Code the current SELECT into temporary table "tab2"
1538 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001539 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0);
1540 rc = multiSelectOpenTempAddr(p, addr, &pOpenTemp);
1541 if( rc!=SQLITE_OK ){
1542 goto multi_select_end;
1543 }
1544 sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001545 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001546 nLimit = p->nLimit;
1547 p->nLimit = -1;
1548 nOffset = p->nOffset;
1549 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001550 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001551 p->pPrior = pPrior;
drh7b58dae2003-07-20 01:16:46 +00001552 p->nLimit = nLimit;
1553 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001554 if( rc ){
1555 goto multi_select_end;
1556 }
drhd8bc7082000-06-07 23:51:50 +00001557
1558 /* Generate code to take the intersection of the two temporary
1559 ** tables.
1560 */
drh82c3d632000-06-06 21:56:07 +00001561 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001562 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001563 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001564 }
danielk19774adee202004-05-08 08:23:19 +00001565 iBreak = sqlite3VdbeMakeLabel(v);
1566 iCont = sqlite3VdbeMakeLabel(v);
1567 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001568 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001569 iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
1570 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001571 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001572 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001573 iCont, iBreak, 0);
1574 if( rc ){
1575 rc = 1;
1576 goto multi_select_end;
1577 }
danielk19774adee202004-05-08 08:23:19 +00001578 sqlite3VdbeResolveLabel(v, iCont);
1579 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1580 sqlite3VdbeResolveLabel(v, iBreak);
1581 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1582 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001583 break;
1584 }
1585 }
1586 assert( p->pEList && pPrior->pEList );
1587 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001588 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001589 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001590 rc = 1;
1591 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001592 }
danielk197784ac9d02004-05-18 09:58:06 +00001593
danielk1977dc1bdc42004-06-11 10:51:27 +00001594 if( p->pOrderBy || (pOpenTemp && pOpenTemp->nId>0) ){
1595 int nCol = p->pEList->nExpr;
1596 int i;
1597 KeyInfo *pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*sizeof(CollSeq*));
1598 if( !pKeyInfo ){
1599 rc = SQLITE_NOMEM;
1600 goto multi_select_end;
1601 }
1602
1603 pKeyInfo->enc = pParse->db->enc;
1604 pKeyInfo->nField = nCol;
1605
1606 for(i=0; i<nCol; i++){
1607 pKeyInfo->aColl[i] = multiSelectCollSeq(pParse, p, i);
1608 if( !pKeyInfo->aColl[i] ){
1609 pKeyInfo->aColl[i] = pParse->db->pDfltColl;
1610 }
1611 }
1612
1613 for(i=0; pOpenTemp && i<pOpenTemp->nId; i++){
1614 int p3type = (i==0?P3_KEYINFO_HANDOFF:P3_KEYINFO);
1615 int addr = pOpenTemp->a[i].idx;
1616 sqlite3VdbeChangeP3(v, addr, (char *)pKeyInfo, p3type);
1617 }
1618
1619 if( p->pOrderBy ){
1620 for(i=0; i<p->pOrderBy->nExpr; i++){
1621 Expr *pExpr = p->pOrderBy->a[i].pExpr;
1622 char *zName = p->pOrderBy->a[i].zName;
1623 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
1624 assert( !pExpr->pColl );
1625 if( zName ){
1626 pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1);
1627 }else{
1628 pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn];
1629 }
1630 }
1631 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1632 }
1633
1634 if( !pOpenTemp ){
1635 /* This happens for UNION ALL ... ORDER BY */
1636 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001637 }
1638 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001639
1640multi_select_end:
1641 if( pOpenTemp ){
1642 sqlite3IdListDelete(pOpenTemp);
1643 }
1644 p->ppOpenTemp = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001645 return rc;
drh22827922000-06-06 17:27:05 +00001646}
1647
1648/*
drh832508b2002-03-02 17:04:07 +00001649** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001650** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001651** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001652** unchanged.)
drh832508b2002-03-02 17:04:07 +00001653**
1654** This routine is part of the flattening procedure. A subquery
1655** whose result set is defined by pEList appears as entry in the
1656** FROM clause of a SELECT such that the VDBE cursor assigned to that
1657** FORM clause entry is iTable. This routine make the necessary
1658** changes to pExpr so that it refers directly to the source table
1659** of the subquery rather the result set of the subquery.
1660*/
drh6a3ea0e2003-05-02 14:32:12 +00001661static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1662static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001663 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001664 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1665 if( pExpr->iColumn<0 ){
1666 pExpr->op = TK_NULL;
1667 }else{
1668 Expr *pNew;
1669 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1670 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1671 pNew = pEList->a[pExpr->iColumn].pExpr;
1672 assert( pNew!=0 );
1673 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001674 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001675 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001676 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001677 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001678 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001679 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001680 pExpr->iTable = pNew->iTable;
1681 pExpr->iColumn = pNew->iColumn;
1682 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001683 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1684 sqlite3TokenCopy(&pExpr->span, &pNew->span);
drh50350a12004-02-13 16:22:22 +00001685 }
drh832508b2002-03-02 17:04:07 +00001686 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001687 substExpr(pExpr->pLeft, iTable, pEList);
1688 substExpr(pExpr->pRight, iTable, pEList);
1689 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001690 }
1691}
1692static void
drh6a3ea0e2003-05-02 14:32:12 +00001693substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001694 int i;
1695 if( pList==0 ) return;
1696 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001697 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001698 }
1699}
1700
1701/*
drh1350b032002-02-27 19:00:20 +00001702** This routine attempts to flatten subqueries in order to speed
1703** execution. It returns 1 if it makes changes and 0 if no flattening
1704** occurs.
1705**
1706** To understand the concept of flattening, consider the following
1707** query:
1708**
1709** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1710**
1711** The default way of implementing this query is to execute the
1712** subquery first and store the results in a temporary table, then
1713** run the outer query on that temporary table. This requires two
1714** passes over the data. Furthermore, because the temporary table
1715** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001716** optimized.
drh1350b032002-02-27 19:00:20 +00001717**
drh832508b2002-03-02 17:04:07 +00001718** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001719** a single flat select, like this:
1720**
1721** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1722**
1723** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001724** but only has to scan the data once. And because indices might
1725** exist on the table t1, a complete scan of the data might be
1726** avoided.
drh1350b032002-02-27 19:00:20 +00001727**
drh832508b2002-03-02 17:04:07 +00001728** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001729**
drh832508b2002-03-02 17:04:07 +00001730** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001731**
drh832508b2002-03-02 17:04:07 +00001732** (2) The subquery is not an aggregate or the outer query is not a join.
1733**
drh8af4d3a2003-05-06 20:35:16 +00001734** (3) The subquery is not the right operand of a left outer join, or
1735** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001736**
1737** (4) The subquery is not DISTINCT or the outer query is not a join.
1738**
1739** (5) The subquery is not DISTINCT or the outer query does not use
1740** aggregates.
1741**
1742** (6) The subquery does not use aggregates or the outer query is not
1743** DISTINCT.
1744**
drh08192d52002-04-30 19:20:28 +00001745** (7) The subquery has a FROM clause.
1746**
drhdf199a22002-06-14 22:38:41 +00001747** (8) The subquery does not use LIMIT or the outer query is not a join.
1748**
1749** (9) The subquery does not use LIMIT or the outer query does not use
1750** aggregates.
1751**
1752** (10) The subquery does not use aggregates or the outer query does not
1753** use LIMIT.
1754**
drh174b6192002-12-03 02:22:52 +00001755** (11) The subquery and the outer query do not both have ORDER BY clauses.
1756**
drh3fc673e2003-06-16 00:40:34 +00001757** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1758** subquery has no WHERE clause. (added by ticket #350)
1759**
drh832508b2002-03-02 17:04:07 +00001760** In this routine, the "p" parameter is a pointer to the outer query.
1761** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1762** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1763**
drh665de472003-03-31 13:36:09 +00001764** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001765** If flattening is attempted this routine returns 1.
1766**
1767** All of the expression analysis must occur on both the outer query and
1768** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001769*/
drh8c74a8c2002-08-25 19:20:40 +00001770static int flattenSubquery(
1771 Parse *pParse, /* The parsing context */
1772 Select *p, /* The parent or outer SELECT statement */
1773 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1774 int isAgg, /* True if outer SELECT uses aggregate functions */
1775 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1776){
drh0bb28102002-05-08 11:54:14 +00001777 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001778 SrcList *pSrc; /* The FROM clause of the outer query */
1779 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001780 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001781 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh832508b2002-03-02 17:04:07 +00001782 int i;
drh832508b2002-03-02 17:04:07 +00001783 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001784
drh832508b2002-03-02 17:04:07 +00001785 /* Check to see if flattening is permitted. Return 0 if not.
1786 */
1787 if( p==0 ) return 0;
1788 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001789 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001790 pSub = pSrc->a[iFrom].pSelect;
1791 assert( pSub!=0 );
1792 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001793 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001794 pSubSrc = pSub->pSrc;
1795 assert( pSubSrc );
drhc31c2eb2003-05-02 16:04:17 +00001796 if( pSubSrc->nSrc==0 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001797 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1798 return 0;
1799 }
drhd11d3822002-06-21 23:01:49 +00001800 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001801 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001802
drh8af4d3a2003-05-06 20:35:16 +00001803 /* Restriction 3: If the subquery is a join, make sure the subquery is
1804 ** not used as the right operand of an outer join. Examples of why this
1805 ** is not allowed:
1806 **
1807 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1808 **
1809 ** If we flatten the above, we would get
1810 **
1811 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1812 **
1813 ** which is not at all the same thing.
1814 */
1815 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1816 return 0;
1817 }
1818
drh3fc673e2003-06-16 00:40:34 +00001819 /* Restriction 12: If the subquery is the right operand of a left outer
1820 ** join, make sure the subquery has no WHERE clause.
1821 ** An examples of why this is not allowed:
1822 **
1823 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1824 **
1825 ** If we flatten the above, we would get
1826 **
1827 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1828 **
1829 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1830 ** effectively converts the OUTER JOIN into an INNER JOIN.
1831 */
1832 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1833 && pSub->pWhere!=0 ){
1834 return 0;
1835 }
1836
drh0bb28102002-05-08 11:54:14 +00001837 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001838 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001839 */
drhc31c2eb2003-05-02 16:04:17 +00001840
1841 /* Move all of the FROM elements of the subquery into the
1842 ** the FROM clause of the outer query. Before doing this, remember
1843 ** the cursor number for the original outer query FROM element in
1844 ** iParent. The iParent cursor will never be used. Subsequent code
1845 ** will scan expressions looking for iParent references and replace
1846 ** those references with expressions that resolve to the subquery FROM
1847 ** elements we are now copying in.
1848 */
drh6a3ea0e2003-05-02 14:32:12 +00001849 iParent = pSrc->a[iFrom].iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001850 {
1851 int nSubSrc = pSubSrc->nSrc;
drh8af4d3a2003-05-06 20:35:16 +00001852 int jointype = pSrc->a[iFrom].jointype;
drhc31c2eb2003-05-02 16:04:17 +00001853
1854 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001855 sqlite3DeleteTable(0, pSrc->a[iFrom].pTab);
drhc31c2eb2003-05-02 16:04:17 +00001856 }
drhf26e09c2003-05-31 16:21:12 +00001857 sqliteFree(pSrc->a[iFrom].zDatabase);
drhc31c2eb2003-05-02 16:04:17 +00001858 sqliteFree(pSrc->a[iFrom].zName);
1859 sqliteFree(pSrc->a[iFrom].zAlias);
1860 if( nSubSrc>1 ){
1861 int extra = nSubSrc - 1;
1862 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00001863 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00001864 }
1865 p->pSrc = pSrc;
1866 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1867 pSrc->a[i] = pSrc->a[i-extra];
1868 }
1869 }
1870 for(i=0; i<nSubSrc; i++){
1871 pSrc->a[i+iFrom] = pSubSrc->a[i];
1872 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1873 }
drh8af4d3a2003-05-06 20:35:16 +00001874 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00001875 }
1876
1877 /* Now begin substituting subquery result set expressions for
1878 ** references to the iParent in the outer query.
1879 **
1880 ** Example:
1881 **
1882 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1883 ** \ \_____________ subquery __________/ /
1884 ** \_____________________ outer query ______________________________/
1885 **
1886 ** We look at every expression in the outer query and every place we see
1887 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1888 */
drh6a3ea0e2003-05-02 14:32:12 +00001889 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001890 pList = p->pEList;
1891 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001892 Expr *pExpr;
1893 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1894 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001895 }
1896 }
drh1b2e0322002-03-03 02:49:51 +00001897 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00001898 substExprList(p->pGroupBy, iParent, pSub->pEList);
1899 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001900 }
drh174b6192002-12-03 02:22:52 +00001901 if( pSub->pOrderBy ){
1902 assert( p->pOrderBy==0 );
1903 p->pOrderBy = pSub->pOrderBy;
1904 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00001905 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00001906 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00001907 }
drh832508b2002-03-02 17:04:07 +00001908 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001909 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00001910 }else{
1911 pWhere = 0;
1912 }
1913 if( subqueryIsAgg ){
1914 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001915 p->pHaving = p->pWhere;
1916 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00001917 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001918 if( pSub->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001919 Expr *pHaving = sqlite3ExprDup(pSub->pHaving);
drh1b2e0322002-03-03 02:49:51 +00001920 if( p->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001921 p->pHaving = sqlite3Expr(TK_AND, p->pHaving, pHaving, 0);
drh1b2e0322002-03-03 02:49:51 +00001922 }else{
1923 p->pHaving = pHaving;
1924 }
1925 }
1926 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00001927 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00001928 }else if( p->pWhere==0 ){
1929 p->pWhere = pWhere;
1930 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001931 substExpr(p->pWhere, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001932 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001933 p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pWhere, 0);
drh832508b2002-03-02 17:04:07 +00001934 }
1935 }
drhc31c2eb2003-05-02 16:04:17 +00001936
1937 /* The flattened query is distinct if either the inner or the
1938 ** outer query is distinct.
1939 */
drh832508b2002-03-02 17:04:07 +00001940 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00001941
drhc31c2eb2003-05-02 16:04:17 +00001942 /* Transfer the limit expression from the subquery to the outer
1943 ** query.
1944 */
drhdf199a22002-06-14 22:38:41 +00001945 if( pSub->nLimit>=0 ){
1946 if( p->nLimit<0 ){
1947 p->nLimit = pSub->nLimit;
1948 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1949 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1950 }
1951 }
1952 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00001953
drhc31c2eb2003-05-02 16:04:17 +00001954 /* Finially, delete what is left of the subquery and return
1955 ** success.
1956 */
danielk19774adee202004-05-08 08:23:19 +00001957 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00001958 return 1;
1959}
drh1350b032002-02-27 19:00:20 +00001960
1961/*
drh9562b552002-02-19 15:00:07 +00001962** Analyze the SELECT statement passed in as an argument to see if it
1963** is a simple min() or max() query. If it is and this query can be
1964** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00001965** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00001966** simple min() or max() query, then return 0;
1967**
1968** A simply min() or max() query looks like this:
1969**
1970** SELECT min(a) FROM table;
1971** SELECT max(a) FROM table;
1972**
1973** The query may have only a single table in its FROM argument. There
1974** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1975** be the min() or max() of a single column of the table. The column
1976** in the min() or max() function must be indexed.
1977**
danielk19774adee202004-05-08 08:23:19 +00001978** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00001979** See the header comment on that routine for additional information.
1980*/
1981static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1982 Expr *pExpr;
1983 int iCol;
1984 Table *pTab;
1985 Index *pIdx;
1986 int base;
1987 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00001988 int seekOp;
1989 int cont;
drh6e175292004-03-13 14:00:36 +00001990 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00001991 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00001992 SrcList *pSrc;
1993
drh9562b552002-02-19 15:00:07 +00001994
1995 /* Check to see if this query is a simple min() or max() query. Return
1996 ** zero if it is not.
1997 */
1998 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00001999 pSrc = p->pSrc;
2000 if( pSrc->nSrc!=1 ) return 0;
2001 pEList = p->pEList;
2002 if( pEList->nExpr!=1 ) return 0;
2003 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002004 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002005 pList = pExpr->pList;
2006 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002007 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00002008 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002009 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00002010 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002011 seekOp = OP_Last;
2012 }else{
2013 return 0;
2014 }
drh6e175292004-03-13 14:00:36 +00002015 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002016 if( pExpr->op!=TK_COLUMN ) return 0;
2017 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002018 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002019
2020 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002021 ** Check to make sure we have an index and make pIdx point to the
2022 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2023 ** key column, no index is necessary so set pIdx to NULL. If no
2024 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002025 */
2026 if( iCol<0 ){
2027 pIdx = 0;
2028 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002029 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002030 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2031 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002032 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002033 }
2034 if( pIdx==0 ) return 0;
2035 }
2036
drhe5f50722003-07-19 00:44:14 +00002037 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002038 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002039 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002040 */
danielk19774adee202004-05-08 08:23:19 +00002041 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002042 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002043
drh0c37e632004-01-30 02:01:03 +00002044 /* If the output is destined for a temporary table, open that table.
2045 */
2046 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002047 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002048 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002049 }
2050
drh17f71932002-02-21 12:01:27 +00002051 /* Generating code to find the min or the max. Basically all we have
2052 ** to do is find the first or the last entry in the chosen index. If
2053 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2054 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002055 */
danielk19774adee202004-05-08 08:23:19 +00002056 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00002057 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00002058 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00002059 if( pSrc->a[0].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +00002060 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00002061 sqlite3VdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
danielk1977b4964b72004-05-18 01:23:38 +00002062 sqlite3VdbeAddOp(v, OP_SetNumColumns, base, pTab->nCol);
drh6e175292004-03-13 14:00:36 +00002063 }
danielk19774adee202004-05-08 08:23:19 +00002064 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00002065 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002066 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002067 }else{
danielk19774adee202004-05-08 08:23:19 +00002068 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00002069 sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum,
2070 (char*)&pIdx->keyInfo, P3_KEYINFO);
danielk19774adee202004-05-08 08:23:19 +00002071 sqlite3VdbeAddOp(v, seekOp, base+1, 0);
2072 sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
2073 sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002074 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002075 }
drh5cf8e8c2002-02-19 22:42:05 +00002076 eList.nExpr = 1;
2077 memset(&eListItem, 0, sizeof(eListItem));
2078 eList.a = &eListItem;
2079 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00002080 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00002081 sqlite3VdbeResolveLabel(v, cont);
2082 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002083
drh9562b552002-02-19 15:00:07 +00002084 return 1;
2085}
2086
2087/*
drh9bb61fe2000-06-05 16:01:39 +00002088** Generate code for the given SELECT statement.
2089**
drhfef52082000-06-06 01:50:43 +00002090** The results are distributed in various ways depending on the
2091** value of eDest and iParm.
2092**
2093** eDest Value Result
2094** ------------ -------------------------------------------
2095** SRT_Callback Invoke the callback for each row of the result.
2096**
2097** SRT_Mem Store first result in memory cell iParm
2098**
danielk1977e014a832004-05-17 10:48:57 +00002099** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002100**
drh82c3d632000-06-06 21:56:07 +00002101** SRT_Union Store results as a key in a temporary table iParm
2102**
jplyon4b11c6d2004-01-19 04:57:53 +00002103** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002104**
2105** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002106**
drhe78e8282003-01-19 03:59:45 +00002107** The table above is incomplete. Additional eDist value have be added
2108** since this comment was written. See the selectInnerLoop() function for
2109** a complete listing of the allowed values of eDest and their meanings.
2110**
drh9bb61fe2000-06-05 16:01:39 +00002111** This routine returns the number of errors. If any errors are
2112** encountered, then an appropriate error message is left in
2113** pParse->zErrMsg.
2114**
2115** This routine does NOT free the Select structure passed in. The
2116** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002117**
2118** The pParent, parentTab, and *pParentAgg fields are filled in if this
2119** SELECT is a subquery. This routine may try to combine this SELECT
2120** with its parent to form a single flat query. In so doing, it might
2121** change the parent query from a non-aggregate to an aggregate query.
2122** For that reason, the pParentAgg flag is passed as a pointer, so it
2123** can be changed.
drhe78e8282003-01-19 03:59:45 +00002124**
2125** Example 1: The meaning of the pParent parameter.
2126**
2127** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2128** \ \_______ subquery _______/ /
2129** \ /
2130** \____________________ outer query ___________________/
2131**
2132** This routine is called for the outer query first. For that call,
2133** pParent will be NULL. During the processing of the outer query, this
2134** routine is called recursively to handle the subquery. For the recursive
2135** call, pParent will point to the outer query. Because the subquery is
2136** the second element in a three-way join, the parentTab parameter will
2137** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002138*/
danielk19774adee202004-05-08 08:23:19 +00002139int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002140 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002141 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002142 int eDest, /* How to dispose of the results */
2143 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002144 Select *pParent, /* Another SELECT for which this is a sub-query */
2145 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002146 int *pParentAgg, /* True if pParent uses aggregate functions */
2147 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002148){
drhd8bc7082000-06-07 23:51:50 +00002149 int i;
drhcce7d172000-05-31 15:34:51 +00002150 WhereInfo *pWInfo;
2151 Vdbe *v;
2152 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002153 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002154 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002155 Expr *pWhere; /* The WHERE clause. May be NULL */
2156 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002157 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2158 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002159 int isDistinct; /* True if the DISTINCT keyword is present */
2160 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002161 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00002162
danielk19776f8a5032004-05-10 10:34:51 +00002163 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002164 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002165
drh82c3d632000-06-06 21:56:07 +00002166 /* If there is are a sequence of queries, do the earlier ones first.
2167 */
2168 if( p->pPrior ){
danielk197784ac9d02004-05-18 09:58:06 +00002169 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002170 }
2171
2172 /* Make local copies of the parameters for this query.
2173 */
drh9bb61fe2000-06-05 16:01:39 +00002174 pTabList = p->pSrc;
2175 pWhere = p->pWhere;
2176 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00002177 pGroupBy = p->pGroupBy;
2178 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00002179 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00002180
drh6a3ea0e2003-05-02 14:32:12 +00002181 /* Allocate VDBE cursors for each table in the FROM clause
drh10e5e3c2000-06-08 00:19:02 +00002182 */
danielk19774adee202004-05-08 08:23:19 +00002183 sqlite3SrcListAssignCursors(pParse, pTabList);
drh10e5e3c2000-06-08 00:19:02 +00002184
drh9bb61fe2000-06-05 16:01:39 +00002185 /*
2186 ** Do not even attempt to generate any code if we have already seen
2187 ** errors before this routine starts.
2188 */
drh1d83f052002-02-17 00:30:36 +00002189 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002190
drhe78e8282003-01-19 03:59:45 +00002191 /* Expand any "*" terms in the result set. (For example the "*" in
2192 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
2193 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00002194 */
drhd8bc7082000-06-07 23:51:50 +00002195 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00002196 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002197 }
drhad2d8302002-05-24 20:31:36 +00002198 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00002199 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00002200 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002201
drh22827922000-06-06 17:27:05 +00002202 /* If writing to memory or generating a set
2203 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002204 */
drhfef52082000-06-06 01:50:43 +00002205 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002206 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002207 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002208 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002209 }
2210
drhc926afb2002-06-20 03:38:26 +00002211 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002212 */
drhc926afb2002-06-20 03:38:26 +00002213 switch( eDest ){
2214 case SRT_Union:
2215 case SRT_Except:
2216 case SRT_Discard:
danielk1977f93bbbe2004-05-27 10:30:52 +00002217 case SRT_Set:
drhc926afb2002-06-20 03:38:26 +00002218 pOrderBy = 0;
2219 break;
2220 default:
2221 break;
drh22827922000-06-06 17:27:05 +00002222 }
2223
drh10e5e3c2000-06-08 00:19:02 +00002224 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002225 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002226 **
drh967e8b72000-06-21 13:59:10 +00002227 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002228 */
drh4794b982000-06-06 13:54:14 +00002229 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002230 if( sqlite3ExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002231 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002232 }
danielk19774adee202004-05-08 08:23:19 +00002233 if( sqlite3ExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002234 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002235 }
2236 }
drhcce7d172000-05-31 15:34:51 +00002237 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002238 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00002239 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002240 }
danielk19774adee202004-05-08 08:23:19 +00002241 if( sqlite3ExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00002242 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002243 }
2244 }
drhc66c5a22002-12-03 02:34:49 +00002245 if( pHaving ){
2246 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002247 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
drhc66c5a22002-12-03 02:34:49 +00002248 goto select_end;
2249 }
danielk19774adee202004-05-08 08:23:19 +00002250 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pHaving) ){
drhc66c5a22002-12-03 02:34:49 +00002251 goto select_end;
2252 }
danielk19774adee202004-05-08 08:23:19 +00002253 if( sqlite3ExprCheck(pParse, pHaving, 1, &isAgg) ){
drhc66c5a22002-12-03 02:34:49 +00002254 goto select_end;
2255 }
2256 }
drhcce7d172000-05-31 15:34:51 +00002257 if( pOrderBy ){
2258 for(i=0; i<pOrderBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002259 int iCol;
drh22827922000-06-06 17:27:05 +00002260 Expr *pE = pOrderBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002261 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2262 sqlite3ExprDelete(pE);
2263 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh88eee382003-01-31 17:16:36 +00002264 }
danielk19774adee202004-05-08 08:23:19 +00002265 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh88eee382003-01-31 17:16:36 +00002266 goto select_end;
2267 }
danielk19774adee202004-05-08 08:23:19 +00002268 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh88eee382003-01-31 17:16:36 +00002269 goto select_end;
2270 }
danielk19774adee202004-05-08 08:23:19 +00002271 if( sqlite3ExprIsConstant(pE) ){
2272 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2273 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002274 "ORDER BY terms must not be non-integer constants");
drhe4de1fe2002-06-02 16:09:01 +00002275 goto select_end;
2276 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002277 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002278 "ORDER BY column number %d out of range - should be "
drhe4de1fe2002-06-02 16:09:01 +00002279 "between 1 and %d", iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00002280 goto select_end;
2281 }
drhcce7d172000-05-31 15:34:51 +00002282 }
2283 }
2284 }
drh22827922000-06-06 17:27:05 +00002285 if( pGroupBy ){
2286 for(i=0; i<pGroupBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002287 int iCol;
drh22827922000-06-06 17:27:05 +00002288 Expr *pE = pGroupBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002289 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2290 sqlite3ExprDelete(pE);
2291 pE = pGroupBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00002292 }
danielk19774adee202004-05-08 08:23:19 +00002293 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00002294 goto select_end;
drh22827922000-06-06 17:27:05 +00002295 }
danielk19774adee202004-05-08 08:23:19 +00002296 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00002297 goto select_end;
drh22827922000-06-06 17:27:05 +00002298 }
danielk19774adee202004-05-08 08:23:19 +00002299 if( sqlite3ExprIsConstant(pE) ){
2300 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2301 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002302 "GROUP BY terms must not be non-integer constants");
drh88eee382003-01-31 17:16:36 +00002303 goto select_end;
2304 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002305 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002306 "GROUP BY column number %d out of range - should be "
drh88eee382003-01-31 17:16:36 +00002307 "between 1 and %d", iCol, pEList->nExpr);
drh88eee382003-01-31 17:16:36 +00002308 goto select_end;
2309 }
2310 }
drh22827922000-06-06 17:27:05 +00002311 }
2312 }
drhcce7d172000-05-31 15:34:51 +00002313
drhd820cb12002-02-18 03:21:45 +00002314 /* Begin generating code.
2315 */
danielk19774adee202004-05-08 08:23:19 +00002316 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002317 if( v==0 ) goto select_end;
2318
drhe78e8282003-01-19 03:59:45 +00002319 /* Identify column names if we will be using them in a callback. This
2320 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002321 */
2322 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002323 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002324 }
2325
drhd3d39e92004-05-20 22:16:29 +00002326#if 1 /* I do not think we need the following code any more.... */
danielk197784ac9d02004-05-18 09:58:06 +00002327 /* If the destination is SRT_Union, then set the number of columns in
2328 ** the records that will be inserted into the temporary table. The caller
2329 ** couldn't do this, in case the select statement is of the form
2330 ** "SELECT * FROM ....".
2331 **
2332 ** We need to do this before we start inserting records into the
2333 ** temporary table (which has had OP_KeyAsData executed on it), because
2334 ** it is required by the key comparison function. So do it now, even
2335 ** though this means that OP_SetNumColumns may be executed on the same
2336 ** cursor more than once.
2337 */
2338 if( eDest==SRT_Union ){
2339 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
2340 }
drhd3d39e92004-05-20 22:16:29 +00002341#endif
danielk197784ac9d02004-05-18 09:58:06 +00002342
drhd820cb12002-02-18 03:21:45 +00002343 /* Generate code for all sub-queries in the FROM clause
2344 */
drhad3cab52002-05-24 02:04:32 +00002345 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002346 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002347 int needRestoreContext;
2348
drha76b5df2002-02-23 02:32:10 +00002349 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002350 if( pTabList->a[i].zName!=0 ){
2351 zSavedAuthContext = pParse->zAuthContext;
2352 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002353 needRestoreContext = 1;
2354 }else{
2355 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002356 }
danielk19774adee202004-05-08 08:23:19 +00002357 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
danielk197784ac9d02004-05-18 09:58:06 +00002358 pTabList->a[i].iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002359 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002360 pParse->zAuthContext = zSavedAuthContext;
2361 }
drh1b2e0322002-03-03 02:49:51 +00002362 pTabList = p->pSrc;
2363 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002364 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002365 pOrderBy = p->pOrderBy;
2366 }
drh1b2e0322002-03-03 02:49:51 +00002367 pGroupBy = p->pGroupBy;
2368 pHaving = p->pHaving;
2369 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002370 }
2371
drh6e175292004-03-13 14:00:36 +00002372 /* Check for the special case of a min() or max() function by itself
2373 ** in the result set.
2374 */
2375 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2376 rc = 0;
2377 goto select_end;
2378 }
2379
drh832508b2002-03-02 17:04:07 +00002380 /* Check to see if this is a subquery that can be "flattened" into its parent.
2381 ** If flattening is a possiblity, do so and return immediately.
2382 */
drh1b2e0322002-03-03 02:49:51 +00002383 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002384 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002385 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002386 return rc;
2387 }
drh832508b2002-03-02 17:04:07 +00002388
danielk19777cedc8d2004-06-10 10:50:08 +00002389 /* If there is an ORDER BY clause, resolve any collation sequences
2390 ** names that have been explicitly specified.
2391 */
2392 if( pOrderBy ){
2393 for(i=0; i<pOrderBy->nExpr; i++){
2394 if( pOrderBy->a[i].zName ){
2395 pOrderBy->a[i].pExpr->pColl =
2396 sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1);
2397 }
2398 }
2399 if( pParse->nErr ){
2400 goto select_end;
2401 }
2402 }
2403
drh7b58dae2003-07-20 01:16:46 +00002404 /* Set the limiter.
2405 */
2406 computeLimitRegisters(pParse, p);
2407
drh2d0794e2002-03-03 03:03:52 +00002408 /* If the output is destined for a temporary table, open that table.
2409 */
2410 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002411 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002412 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002413 }
2414
drh22827922000-06-06 17:27:05 +00002415 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002416 */
drhd820cb12002-02-18 03:21:45 +00002417 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002418 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002419 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002420 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002421 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002422 if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002423 goto select_end;
drh22827922000-06-06 17:27:05 +00002424 }
2425 }
2426 if( pGroupBy ){
2427 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002428 if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002429 goto select_end;
drh22827922000-06-06 17:27:05 +00002430 }
2431 }
2432 }
danielk19774adee202004-05-08 08:23:19 +00002433 if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002434 goto select_end;
drh22827922000-06-06 17:27:05 +00002435 }
drh191b6902000-06-08 11:13:01 +00002436 if( pOrderBy ){
2437 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002438 if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002439 goto select_end;
drh191b6902000-06-08 11:13:01 +00002440 }
2441 }
2442 }
drhefb72512000-05-31 20:00:52 +00002443 }
2444
drh22827922000-06-06 17:27:05 +00002445 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002446 */
2447 if( isAgg ){
danielk1977ce2663c2004-06-11 13:19:21 +00002448 int addr = sqlite3VdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002449 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002450 FuncDef *pFunc;
2451 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drhf9b596e2004-05-26 16:54:42 +00002452 sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_FUNCDEF);
drhe5095352002-02-24 03:25:14 +00002453 }
2454 }
drh1bee3d72001-10-15 00:44:35 +00002455 if( pGroupBy==0 ){
danielk19770f69c1e2004-05-29 11:24:50 +00002456 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00002457 sqlite3VdbeAddOp(v, OP_AggFocus, 0, 0);
danielk1977ce2663c2004-06-11 13:19:21 +00002458 }else{
2459 int sz = sizeof(KeyInfo) + pGroupBy->nExpr*sizeof(CollSeq*);
2460 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(sz);
2461 if( 0==pKey ){
2462 goto select_end;
2463 }
2464 pKey->enc = pParse->db->enc;
2465 pKey->nField = pGroupBy->nExpr;
2466 for(i=0; i<pGroupBy->nExpr; i++){
2467 pKey->aColl[i] = sqlite3ExprCollSeq(pParse, pGroupBy->a[i].pExpr);
2468 if( !pKey->aColl[i] ){
2469 pKey->aColl[i] = pParse->db->pDfltColl;
2470 }
2471 }
2472 sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF);
drh1bee3d72001-10-15 00:44:35 +00002473 }
drhcce7d172000-05-31 15:34:51 +00002474 }
2475
drh19a775c2000-06-05 18:54:46 +00002476 /* Initialize the memory cell to NULL
2477 */
drhfef52082000-06-06 01:50:43 +00002478 if( eDest==SRT_Mem ){
danielk19770f69c1e2004-05-29 11:24:50 +00002479 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00002480 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002481 }
2482
drh832508b2002-03-02 17:04:07 +00002483 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002484 */
drh19a775c2000-06-05 18:54:46 +00002485 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002486 distinct = pParse->nTab++;
drhd3d39e92004-05-20 22:16:29 +00002487 openTempIndex(pParse, p, distinct, 0);
drh832508b2002-03-02 17:04:07 +00002488 }else{
2489 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002490 }
drh832508b2002-03-02 17:04:07 +00002491
2492 /* Begin the database scan
2493 */
danielk19774adee202004-05-08 08:23:19 +00002494 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
drh68d2e592002-08-04 00:52:38 +00002495 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002496 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002497
drh22827922000-06-06 17:27:05 +00002498 /* Use the standard inner loop if we are not dealing with
2499 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002500 */
drhda9d6c42000-05-31 18:20:14 +00002501 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002502 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002503 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002504 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002505 }
drhcce7d172000-05-31 15:34:51 +00002506 }
drhefb72512000-05-31 20:00:52 +00002507
drhe3184742002-06-19 14:27:05 +00002508 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002509 ** processing.
drhefb72512000-05-31 20:00:52 +00002510 */
drh22827922000-06-06 17:27:05 +00002511 else{
drh268380c2004-02-25 13:47:31 +00002512 AggExpr *pAgg;
drh22827922000-06-06 17:27:05 +00002513 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002514 int lbl1;
drh22827922000-06-06 17:27:05 +00002515 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002516 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
drh22827922000-06-06 17:27:05 +00002517 }
danielk1977ededfd52004-06-17 07:53:01 +00002518 /* No affinity string is attached to the following OP_MakeRecord
drhd3d39e92004-05-20 22:16:29 +00002519 ** because we do not need to do any coercion of datatypes. */
danielk1977ededfd52004-06-17 07:53:01 +00002520 sqlite3VdbeAddOp(v, OP_MakeRecord, pGroupBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +00002521 lbl1 = sqlite3VdbeMakeLabel(v);
2522 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh268380c2004-02-25 13:47:31 +00002523 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2524 if( pAgg->isAgg ) continue;
danielk19774adee202004-05-08 08:23:19 +00002525 sqlite3ExprCode(pParse, pAgg->pExpr);
2526 sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002527 }
danielk19774adee202004-05-08 08:23:19 +00002528 sqlite3VdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002529 }
drh268380c2004-02-25 13:47:31 +00002530 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002531 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002532 int nExpr;
2533 FuncDef *pDef;
2534 if( !pAgg->isAgg ) continue;
2535 assert( pAgg->pFunc!=0 );
2536 assert( pAgg->pFunc->xStep!=0 );
2537 pDef = pAgg->pFunc;
2538 pE = pAgg->pExpr;
2539 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002540 assert( pE->op==TK_AGG_FUNCTION );
drhf9b596e2004-05-26 16:54:42 +00002541 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
danielk19774adee202004-05-08 08:23:19 +00002542 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
danielk1977dc1bdc42004-06-11 10:51:27 +00002543 if( pDef->needCollSeq ){
2544 CollSeq *pColl = 0;
2545 int j;
2546 for(j=0; !pColl && j<nExpr; j++){
2547 pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr);
2548 }
2549 if( !pColl ) pColl = pParse->db->pDfltColl;
2550 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2551 }
danielk19774adee202004-05-08 08:23:19 +00002552 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002553 }
drhcce7d172000-05-31 15:34:51 +00002554 }
2555
2556 /* End the database scan loop.
2557 */
danielk19774adee202004-05-08 08:23:19 +00002558 sqlite3WhereEnd(pWInfo);
drhcce7d172000-05-31 15:34:51 +00002559
drh22827922000-06-06 17:27:05 +00002560 /* If we are processing aggregates, we need to set up a second loop
2561 ** over all of the aggregate values and process them.
2562 */
2563 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002564 int endagg = sqlite3VdbeMakeLabel(v);
drh22827922000-06-06 17:27:05 +00002565 int startagg;
danielk19774adee202004-05-08 08:23:19 +00002566 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002567 pParse->useAgg = 1;
2568 if( pHaving ){
danielk19774adee202004-05-08 08:23:19 +00002569 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002570 }
drhdf199a22002-06-14 22:38:41 +00002571 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002572 iParm, startagg, endagg, aff) ){
drh1d83f052002-02-17 00:30:36 +00002573 goto select_end;
drh22827922000-06-06 17:27:05 +00002574 }
danielk19774adee202004-05-08 08:23:19 +00002575 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2576 sqlite3VdbeResolveLabel(v, endagg);
2577 sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002578 pParse->useAgg = 0;
2579 }
2580
drhcce7d172000-05-31 15:34:51 +00002581 /* If there is an ORDER BY clause, then we need to sort the results
2582 ** and send them to the callback one by one.
2583 */
2584 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00002585 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002586 }
drh6a535342001-10-19 16:44:56 +00002587
drhf620b4e2004-02-09 14:37:50 +00002588 /* If this was a subquery, we have now converted the subquery into a
2589 ** temporary table. So delete the subquery structure from the parent
2590 ** to prevent this subquery from being evaluated again and to force the
2591 ** the use of the temporary table.
2592 */
2593 if( pParent ){
2594 assert( pParent->pSrc->nSrc>parentTab );
2595 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00002596 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00002597 pParent->pSrc->a[parentTab].pSelect = 0;
2598 }
2599
drh1d83f052002-02-17 00:30:36 +00002600 /* The SELECT was successfully coded. Set the return code to 0
2601 ** to indicate no errors.
2602 */
2603 rc = 0;
2604
2605 /* Control jumps to here if an error is encountered above, or upon
2606 ** successful coding of the SELECT.
2607 */
2608select_end:
2609 sqliteAggregateInfoReset(pParse);
2610 return rc;
drhcce7d172000-05-31 15:34:51 +00002611}