blob: 9c601423c3b8284c636688c42d7c95ed8c3e769e [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**
danielk1977742f9472004-06-16 12:02:43 +000015** $Id: select.c,v 1.191 2004/06/16 12:02:47 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 }
drhffbc3082004-05-21 01:29:06 +0000319 sqlite3VdbeAddOp(v, OP_MakeKey, 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
drhd3d39e92004-05-20 22:16:29 +0000387 /* Deliberately leave the affinity string off of the following OP_MakeKey */
danielk19774adee202004-05-08 08:23:19 +0000388 sqlite3VdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
danielk19774adee202004-05-08 08:23:19 +0000389 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
390 sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
391 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
danielk19770f69c1e2004-05-29 11:24:50 +0000392 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000393 sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
drh22827922000-06-06 17:27:05 +0000394 }
drh82c3d632000-06-06 21:56:07 +0000395
drhc926afb2002-06-20 03:38:26 +0000396 switch( eDest ){
397 /* In this mode, write each query result to the key of the temporary
398 ** table iParm.
399 */
400 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000401 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000402 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000403 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000404 sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000405 break;
drh22827922000-06-06 17:27:05 +0000406 }
drh22827922000-06-06 17:27:05 +0000407
drhc926afb2002-06-20 03:38:26 +0000408 /* Store the result as data using a unique key.
409 */
410 case SRT_Table:
411 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000412 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000413 if( pOrderBy ){
414 pushOntoSorter(pParse, v, pOrderBy);
415 }else{
danielk19774adee202004-05-08 08:23:19 +0000416 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
417 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
418 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000419 }
420 break;
421 }
drh82c3d632000-06-06 21:56:07 +0000422
drhc926afb2002-06-20 03:38:26 +0000423 /* Construct a record from the query result, but instead of
424 ** saving that record, use it as a key to delete elements from
425 ** the temporary table iParm.
426 */
427 case SRT_Except: {
428 int addr;
danielk19774adee202004-05-08 08:23:19 +0000429 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000430 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000431 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
432 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000433 break;
434 }
drh5974a302000-06-07 14:42:26 +0000435
drhc926afb2002-06-20 03:38:26 +0000436 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
437 ** then there should be a single item on the stack. Write this
438 ** item into the set table with bogus data.
439 */
440 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000441 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000442 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000443
drhc926afb2002-06-20 03:38:26 +0000444 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000445 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
446 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
447 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000448 if( pOrderBy ){
449 pushOntoSorter(pParse, v, pOrderBy);
450 }else{
danielk1977e014a832004-05-17 10:48:57 +0000451 char const *affStr;
452 char aff = (iParm>>16)&0xFF;
453 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
454 affStr = sqlite3AffinityString(aff);
danielk197784ac9d02004-05-18 09:58:06 +0000455 sqlite3VdbeOp3(v, OP_MakeKey, 1, 0, affStr, P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000456 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000457 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000458 }
danielk19774adee202004-05-08 08:23:19 +0000459 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000460 break;
461 }
drh22827922000-06-06 17:27:05 +0000462
drhc926afb2002-06-20 03:38:26 +0000463 /* If this is a scalar select that is part of an expression, then
464 ** store the results in the appropriate memory cell and break out
465 ** of the scan loop.
466 */
467 case SRT_Mem: {
468 assert( nColumn==1 );
469 if( pOrderBy ){
470 pushOntoSorter(pParse, v, pOrderBy);
471 }else{
danielk19774adee202004-05-08 08:23:19 +0000472 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
473 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000474 }
475 break;
476 }
drh22827922000-06-06 17:27:05 +0000477
drhf46f9052002-06-22 02:33:38 +0000478 /* Send the data to the callback function.
479 */
480 case SRT_Callback:
481 case SRT_Sorter: {
482 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000483 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000484 pushOntoSorter(pParse, v, pOrderBy);
485 }else{
486 assert( eDest==SRT_Callback );
danielk19774adee202004-05-08 08:23:19 +0000487 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000488 }
489 break;
490 }
491
drh142e30d2002-08-28 03:00:58 +0000492 /* Invoke a subroutine to handle the results. The subroutine itself
493 ** is responsible for popping the results off of the stack.
494 */
495 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000496 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000497 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000498 pushOntoSorter(pParse, v, pOrderBy);
499 }else{
danielk19774adee202004-05-08 08:23:19 +0000500 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhac82fcf2002-09-08 17:23:41 +0000501 }
drh142e30d2002-08-28 03:00:58 +0000502 break;
503 }
504
drhc926afb2002-06-20 03:38:26 +0000505 /* Discard the results. This is used for SELECT statements inside
506 ** the body of a TRIGGER. The purpose of such selects is to call
507 ** user-defined functions that have side effects. We do not care
508 ** about the actual results of the select.
509 */
drhc926afb2002-06-20 03:38:26 +0000510 default: {
drhf46f9052002-06-22 02:33:38 +0000511 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000512 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000513 break;
514 }
drh82c3d632000-06-06 21:56:07 +0000515 }
516 return 0;
517}
518
519/*
drhd8bc7082000-06-07 23:51:50 +0000520** If the inner loop was generated using a non-null pOrderBy argument,
521** then the results were placed in a sorter. After the loop is terminated
522** we need to run the sorter and output the results. The following
523** routine generates the code needed to do that.
524*/
drhc926afb2002-06-20 03:38:26 +0000525static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000526 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000527 Select *p, /* The SELECT statement */
528 Vdbe *v, /* Generate code into this VDBE */
529 int nColumn, /* Number of columns of data */
530 int eDest, /* Write the sorted results here */
531 int iParm /* Optional parameter associated with eDest */
532){
danielk19774adee202004-05-08 08:23:19 +0000533 int end1 = sqlite3VdbeMakeLabel(v);
534 int end2 = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000535 int addr;
drhffbc3082004-05-21 01:29:06 +0000536 KeyInfo *pInfo;
537 ExprList *pOrderBy;
538 int nCol, i;
539 sqlite *db = pParse->db;
540
drhf46f9052002-06-22 02:33:38 +0000541 if( eDest==SRT_Sorter ) return;
drhffbc3082004-05-21 01:29:06 +0000542 pOrderBy = p->pOrderBy;
543 nCol = pOrderBy->nExpr;
544 pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
545 if( pInfo==0 ) return;
546 pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
547 pInfo->nField = nCol;
548 for(i=0; i<nCol; i++){
danielk19770202b292004-06-09 09:55:16 +0000549 /* If a collation sequence was specified explicity, then it
550 ** is stored in pOrderBy->a[i].zName. Otherwise, use the default
551 ** collation type for the expression.
552 */
danielk19777cedc8d2004-06-10 10:50:08 +0000553 pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr);
danielk19770202b292004-06-09 09:55:16 +0000554 if( !pInfo->aColl[i] ){
555 pInfo->aColl[i] = db->pDfltColl;
556 }
drhffbc3082004-05-21 01:29:06 +0000557 pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
558 }
559 sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
danielk19774adee202004-05-08 08:23:19 +0000560 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
drh7b58dae2003-07-20 01:16:46 +0000561 if( p->iOffset>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000562 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4);
563 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
564 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
drhdf199a22002-06-14 22:38:41 +0000565 }
drh7b58dae2003-07-20 01:16:46 +0000566 if( p->iLimit>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000567 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, end2);
drhdf199a22002-06-14 22:38:41 +0000568 }
drhc926afb2002-06-20 03:38:26 +0000569 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000570 case SRT_Table:
571 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000572 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
573 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
574 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000575 break;
576 }
577 case SRT_Set: {
578 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000579 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
580 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
581 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
drhd6861792004-05-20 03:02:47 +0000582 sqlite3VdbeOp3(v, OP_MakeKey, 1, 0, "n", P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000583 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000584 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000585 break;
586 }
587 case SRT_Mem: {
588 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000589 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
590 sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
drhc926afb2002-06-20 03:38:26 +0000591 break;
592 }
drhce665cf2004-05-21 03:01:58 +0000593 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000594 case SRT_Subroutine: {
595 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000596 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
597 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000598 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000599 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000600 }
drhce665cf2004-05-21 03:01:58 +0000601 if( eDest==SRT_Callback ){
602 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
603 }else{
604 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
605 }
danielk197784ac9d02004-05-18 09:58:06 +0000606 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000607 break;
608 }
drhc926afb2002-06-20 03:38:26 +0000609 default: {
drhf46f9052002-06-22 02:33:38 +0000610 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000611 break;
612 }
613 }
danielk19774adee202004-05-08 08:23:19 +0000614 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
615 sqlite3VdbeResolveLabel(v, end2);
616 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
617 sqlite3VdbeResolveLabel(v, end1);
618 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000619}
620
621/*
danielk1977517eb642004-06-07 10:00:31 +0000622** Return a pointer to a string containing the 'declaration type' of the
623** expression pExpr. The string may be treated as static by the caller.
drhe78e8282003-01-19 03:59:45 +0000624**
danielk1977517eb642004-06-07 10:00:31 +0000625** If the declaration type is the exact datatype definition extracted from
626** the original CREATE TABLE statement if the expression is a column.
627**
628** The declaration type for an expression is either TEXT, NUMERIC or ANY.
629** The declaration type for a ROWID field is INTEGER.
630*/
631static const char *columnType(Parse *pParse, SrcList *pTabList, Expr *pExpr){
632 char const *zType = 0;
633 int j;
634 if( pExpr==0 ) return 0;
635 if( pExpr->op==TK_COLUMN && pTabList ){
636 Table *pTab;
637 int iCol = pExpr->iColumn;
638 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable; j++){}
639 assert( j<pTabList->nSrc );
640 pTab = pTabList->a[j].pTab;
641 if( iCol<0 ) iCol = pTab->iPKey;
642 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
643 if( iCol<0 ){
644 zType = "INTEGER";
645 }else{
646 zType = pTab->aCol[iCol].zType;
danielk1977fbcd5852004-06-15 02:44:18 +0000647 if( !zType ) zType = "";
danielk1977517eb642004-06-07 10:00:31 +0000648 }
649 }else{
650 switch( sqlite3ExprType(pExpr) ){
651 case SQLITE_AFF_TEXT: zType = "TEXT"; break;
652 case SQLITE_AFF_NUMERIC: zType = "NUMERIC"; break;
653 default: zType = "ANY"; break;
654 }
655 }
656 return zType;
657}
658
659/*
660** Generate code that will tell the VDBE the declaration types of columns
661** in the result set.
drhfcb78a42003-01-18 20:11:05 +0000662*/
663static void generateColumnTypes(
664 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000665 SrcList *pTabList, /* List of tables */
666 ExprList *pEList /* Expressions defining the result set */
667){
668 Vdbe *v = pParse->pVdbe;
danielk1977517eb642004-06-07 10:00:31 +0000669 int i;
drhfcb78a42003-01-18 20:11:05 +0000670 for(i=0; i<pEList->nExpr; i++){
671 Expr *p = pEList->a[i].pExpr;
danielk1977517eb642004-06-07 10:00:31 +0000672 const char *zType = columnType(pParse, pTabList, p);
drhfcb78a42003-01-18 20:11:05 +0000673 if( p==0 ) continue;
danielk1977fbcd5852004-06-15 02:44:18 +0000674 /* The vdbe must make it's own copy of the column-type, in case the
675 ** schema is reset before this virtual machine is deleted.
676 */
677 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
drhfcb78a42003-01-18 20:11:05 +0000678 }
679}
680
681/*
682** Generate code that will tell the VDBE the names of columns
683** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000684** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000685*/
drh832508b2002-03-02 17:04:07 +0000686static void generateColumnNames(
687 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000688 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000689 ExprList *pEList /* Expressions defining the result set */
690){
drhd8bc7082000-06-07 23:51:50 +0000691 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000692 int i, j;
drhfcabd462004-02-20 14:50:58 +0000693 sqlite *db = pParse->db;
694 int fullNames, shortNames;
695
danielk19773cf86062004-05-26 10:11:05 +0000696 /* If this is an EXPLAIN, skip this step */
697 if( pParse->explain ){
danielk197761de0d12004-05-27 23:56:16 +0000698 return;
danielk19773cf86062004-05-26 10:11:05 +0000699 }
700
drhd6502752004-02-16 03:44:01 +0000701 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000702 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000703 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000704 fullNames = (db->flags & SQLITE_FullColNames)!=0;
705 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
danielk197722322fd2004-05-25 23:35:17 +0000706 sqlite3VdbeSetNumCols(v, pEList->nExpr);
drh82c3d632000-06-06 21:56:07 +0000707 for(i=0; i<pEList->nExpr; i++){
708 Expr *p;
drh5a387052003-01-11 14:19:51 +0000709 p = pEList->a[i].pExpr;
710 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000711 if( pEList->a[i].zName ){
712 char *zName = pEList->a[i].zName;
danielk1977d8123362004-06-12 09:25:12 +0000713 sqlite3VdbeSetColName(v, i, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000714 continue;
715 }
drhfa173a72002-07-10 21:26:00 +0000716 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000717 Table *pTab;
drh97665872002-02-13 23:22:53 +0000718 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000719 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000720 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
721 assert( j<pTabList->nSrc );
722 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000723 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000724 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000725 if( iCol<0 ){
726 zCol = "_ROWID_";
drhb1363202002-06-26 02:45:03 +0000727 }else{
728 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000729 }
drhfcabd462004-02-20 14:50:58 +0000730 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000731 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
drhfcabd462004-02-20 14:50:58 +0000732 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000733 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000734 char *zTab;
735
drh6a3ea0e2003-05-02 14:32:12 +0000736 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000737 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000738 sqlite3SetString(&zName, zTab, ".", zCol, 0);
danielk19773cf86062004-05-26 10:11:05 +0000739 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000740 }else{
danielk19773cf86062004-05-26 10:11:05 +0000741 sqlite3VdbeSetColName(v, i, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000742 }
drh6977fea2002-10-22 23:38:04 +0000743 }else if( p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000744 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
745 /* sqlite3VdbeCompressSpace(v, addr); */
drh1bee3d72001-10-15 00:44:35 +0000746 }else{
747 char zName[30];
748 assert( p->op!=TK_COLUMN || pTabList==0 );
749 sprintf(zName, "column%d", i+1);
danielk19773cf86062004-05-26 10:11:05 +0000750 sqlite3VdbeSetColName(v, i, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000751 }
752 }
danielk197776d505b2004-05-28 13:13:02 +0000753 generateColumnTypes(pParse, pTabList, pEList);
drh82c3d632000-06-06 21:56:07 +0000754}
755
756/*
drhd8bc7082000-06-07 23:51:50 +0000757** Name of the connection operator, used for error messages.
758*/
759static const char *selectOpName(int id){
760 char *z;
761 switch( id ){
762 case TK_ALL: z = "UNION ALL"; break;
763 case TK_INTERSECT: z = "INTERSECT"; break;
764 case TK_EXCEPT: z = "EXCEPT"; break;
765 default: z = "UNION"; break;
766 }
767 return z;
768}
769
770/*
drh315555c2002-10-20 15:53:03 +0000771** Forward declaration
772*/
773static int fillInColumnList(Parse*, Select*);
774
775/*
drh22f70c32002-02-18 01:17:00 +0000776** Given a SELECT statement, generate a Table structure that describes
777** the result set of that SELECT.
778*/
danielk19774adee202004-05-08 08:23:19 +0000779Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000780 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000781 int i, j;
drh22f70c32002-02-18 01:17:00 +0000782 ExprList *pEList;
drhb733d032004-01-24 20:18:12 +0000783 Column *aCol;
drh22f70c32002-02-18 01:17:00 +0000784
785 if( fillInColumnList(pParse, pSelect) ){
786 return 0;
787 }
788 pTab = sqliteMalloc( sizeof(Table) );
789 if( pTab==0 ){
790 return 0;
791 }
792 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
793 pEList = pSelect->pEList;
794 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000795 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000796 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh22f70c32002-02-18 01:17:00 +0000797 for(i=0; i<pTab->nCol; i++){
danielk1977517eb642004-06-07 10:00:31 +0000798 Expr *pR;
799 char *zType;
800 Expr *p = pEList->a[i].pExpr;
drh22f70c32002-02-18 01:17:00 +0000801 if( pEList->a[i].zName ){
drhb733d032004-01-24 20:18:12 +0000802 aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
danielk1977517eb642004-06-07 10:00:31 +0000803 }else if( p->op==TK_DOT
drhb733d032004-01-24 20:18:12 +0000804 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
805 int cnt;
danielk19774adee202004-05-08 08:23:19 +0000806 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
drhb733d032004-01-24 20:18:12 +0000807 for(j=cnt=0; j<i; j++){
danielk19774adee202004-05-08 08:23:19 +0000808 if( sqlite3StrICmp(aCol[j].zName, aCol[i].zName)==0 ){
drhb733d032004-01-24 20:18:12 +0000809 int n;
810 char zBuf[30];
811 sprintf(zBuf,"_%d",++cnt);
812 n = strlen(zBuf);
danielk1977e014a832004-05-17 10:48:57 +0000813 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf,n,0);
drhb733d032004-01-24 20:18:12 +0000814 j = -1;
815 }
816 }
817 }else if( p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000818 sqlite3SetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drh22f70c32002-02-18 01:17:00 +0000819 }else{
820 char zBuf[30];
821 sprintf(zBuf, "column%d", i+1);
822 pTab->aCol[i].zName = sqliteStrDup(zBuf);
823 }
danielk1977517eb642004-06-07 10:00:31 +0000824
825 zType = sqliteStrDup(columnType(pParse, pSelect->pSrc ,p));
826 pTab->aCol[i].zType = zType;
827 pTab->aCol[i].affinity = SQLITE_AFF_NUMERIC;
828 if( zType ){
829 pTab->aCol[i].affinity = sqlite3AffinityType(zType, strlen(zType));
830 }
danielk19777cedc8d2004-06-10 10:50:08 +0000831 pTab->aCol[i].pColl = sqlite3ExprCollSeq(pParse, p);
danielk19770202b292004-06-09 09:55:16 +0000832 if( !pTab->aCol[i].pColl ){
833 pTab->aCol[i].pColl = pParse->db->pDfltColl;
834 }
drh22f70c32002-02-18 01:17:00 +0000835 }
836 pTab->iPKey = -1;
837 return pTab;
838}
839
840/*
drhad2d8302002-05-24 20:31:36 +0000841** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000842**
drhad3cab52002-05-24 02:04:32 +0000843** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh63eb5f22003-04-29 16:20:44 +0000844** defines the set of tables that should be scanned. For views,
845** fill pTabList->a[].pSelect with a copy of the SELECT statement
846** that implements the view. A copy is made of the view's SELECT
847** statement so that we can freely modify or delete that statement
848** without worrying about messing up the presistent representation
849** of the view.
drhd8bc7082000-06-07 23:51:50 +0000850**
drhad2d8302002-05-24 20:31:36 +0000851** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
852** on joins and the ON and USING clause of joins.
853**
854** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000855** for instances of the "*" operator or the TABLE.* operator.
856** If found, expand each "*" to be every column in every table
857** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000858**
859** Return 0 on success. If there are problems, leave an error message
860** in pParse and return non-zero.
861*/
862static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000863 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000864 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000865 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000866 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000867
868 if( p==0 || p->pSrc==0 ) return 1;
869 pTabList = p->pSrc;
870 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000871
872 /* Look up every table in the table list.
873 */
drhad3cab52002-05-24 02:04:32 +0000874 for(i=0; i<pTabList->nSrc; i++){
drhd8bc7082000-06-07 23:51:50 +0000875 if( pTabList->a[i].pTab ){
876 /* This routine has run before! No need to continue */
877 return 0;
878 }
drhdaffd0e2001-04-11 14:28:42 +0000879 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000880 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000881 assert( pTabList->a[i].pSelect!=0 );
drhad2d8302002-05-24 20:31:36 +0000882 if( pTabList->a[i].zAlias==0 ){
883 char zFakeName[60];
884 sprintf(zFakeName, "sqlite_subquery_%p_",
885 (void*)pTabList->a[i].pSelect);
danielk19774adee202004-05-08 08:23:19 +0000886 sqlite3SetString(&pTabList->a[i].zAlias, zFakeName, 0);
drhad2d8302002-05-24 20:31:36 +0000887 }
drh22f70c32002-02-18 01:17:00 +0000888 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000889 sqlite3ResultSetOfSelect(pParse, pTabList->a[i].zAlias,
drh22f70c32002-02-18 01:17:00 +0000890 pTabList->a[i].pSelect);
891 if( pTab==0 ){
892 return 1;
893 }
drh5cf590c2003-04-24 01:45:04 +0000894 /* The isTransient flag indicates that the Table structure has been
895 ** dynamically allocated and may be freed at any time. In other words,
896 ** pTab is not pointing to a persistent table structure that defines
897 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000898 pTab->isTransient = 1;
899 }else{
drha76b5df2002-02-23 02:32:10 +0000900 /* An ordinary table or view name in the FROM clause */
901 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000902 sqlite3LocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
drha76b5df2002-02-23 02:32:10 +0000903 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000904 return 1;
905 }
drha76b5df2002-02-23 02:32:10 +0000906 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +0000907 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +0000908 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +0000909 return 1;
910 }
drh63eb5f22003-04-29 16:20:44 +0000911 /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
912 ** view within a view. The SELECT structure has already been
913 ** copied by the outer view so we can skip the copy step here
914 ** in the inner view.
915 */
916 if( pTabList->a[i].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +0000917 pTabList->a[i].pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +0000918 }
drha76b5df2002-02-23 02:32:10 +0000919 }
drhd8bc7082000-06-07 23:51:50 +0000920 }
921 }
922
drhad2d8302002-05-24 20:31:36 +0000923 /* Process NATURAL keywords, and ON and USING clauses of joins.
924 */
925 if( sqliteProcessJoin(pParse, p) ) return 1;
926
drh7c917d12001-12-16 20:05:05 +0000927 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000928 ** all columns in all tables. And for every TABLE.* insert the names
929 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000930 ** with the TK_ALL operator for each "*" that it found in the column list.
931 ** The following code just has to locate the TK_ALL expressions and expand
932 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000933 **
934 ** The first loop just checks to see if there are any "*" operators
935 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000936 */
drh7c917d12001-12-16 20:05:05 +0000937 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000938 Expr *pE = pEList->a[k].pExpr;
939 if( pE->op==TK_ALL ) break;
940 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
941 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000942 }
drh54473222002-04-04 02:10:55 +0000943 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000944 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000945 /*
946 ** If we get here it means the result set contains one or more "*"
947 ** operators that need to be expanded. Loop through each expression
948 ** in the result set and expand them one by one.
949 */
drh7c917d12001-12-16 20:05:05 +0000950 struct ExprList_item *a = pEList->a;
951 ExprList *pNew = 0;
952 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000953 Expr *pE = a[k].pExpr;
954 if( pE->op!=TK_ALL &&
955 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
956 /* This particular expression does not need to be expanded.
957 */
danielk19774adee202004-05-08 08:23:19 +0000958 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +0000959 pNew->a[pNew->nExpr-1].zName = a[k].zName;
960 a[k].pExpr = 0;
961 a[k].zName = 0;
962 }else{
drh54473222002-04-04 02:10:55 +0000963 /* This expression is a "*" or a "TABLE.*" and needs to be
964 ** expanded. */
965 int tableSeen = 0; /* Set to 1 when TABLE matches */
966 Token *pName; /* text of name of TABLE */
967 if( pE->op==TK_DOT && pE->pLeft ){
968 pName = &pE->pLeft->token;
969 }else{
970 pName = 0;
971 }
drhad3cab52002-05-24 02:04:32 +0000972 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000973 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000974 char *zTabName = pTabList->a[i].zAlias;
975 if( zTabName==0 || zTabName[0]==0 ){
976 zTabName = pTab->zName;
977 }
drhc754fa52002-05-27 03:25:51 +0000978 if( pName && (zTabName==0 || zTabName[0]==0 ||
danielk19774adee202004-05-08 08:23:19 +0000979 sqlite3StrNICmp(pName->z, zTabName, pName->n)!=0 ||
drhc754fa52002-05-27 03:25:51 +0000980 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +0000981 continue;
982 }
983 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +0000984 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000985 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +0000986 char *zName = pTab->aCol[j].zName;
987
988 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
989 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
990 /* In a NATURAL join, omit the join columns from the
991 ** table on the right */
992 continue;
993 }
danielk19774adee202004-05-08 08:23:19 +0000994 if( i>0 && sqlite3IdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
drhad2d8302002-05-24 20:31:36 +0000995 /* In a join with a USING clause, omit columns in the
996 ** using clause from the table on the right. */
997 continue;
998 }
danielk19774adee202004-05-08 08:23:19 +0000999 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001000 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +00001001 pRight->token.z = zName;
1002 pRight->token.n = strlen(zName);
drh4b59ab52002-08-24 18:24:51 +00001003 pRight->token.dyn = 0;
drh4b59ab52002-08-24 18:24:51 +00001004 if( zTabName && pTabList->nSrc>1 ){
danielk19774adee202004-05-08 08:23:19 +00001005 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1006 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001007 if( pExpr==0 ) break;
drh4b59ab52002-08-24 18:24:51 +00001008 pLeft->token.z = zTabName;
1009 pLeft->token.n = strlen(zTabName);
1010 pLeft->token.dyn = 0;
danielk19774adee202004-05-08 08:23:19 +00001011 sqlite3SetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
drh6977fea2002-10-22 23:38:04 +00001012 pExpr->span.n = strlen(pExpr->span.z);
1013 pExpr->span.dyn = 1;
1014 pExpr->token.z = 0;
1015 pExpr->token.n = 0;
1016 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001017 }else{
drh22f70c32002-02-18 01:17:00 +00001018 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001019 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001020 }
danielk19774adee202004-05-08 08:23:19 +00001021 pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001022 }
drh17e24df2001-11-06 14:10:41 +00001023 }
drh54473222002-04-04 02:10:55 +00001024 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +00001025 if( pName ){
danielk19774adee202004-05-08 08:23:19 +00001026 sqlite3ErrorMsg(pParse, "no such table: %T", pName);
drhf5db2d32002-06-06 23:42:27 +00001027 }else{
danielk19774adee202004-05-08 08:23:19 +00001028 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001029 }
drh54473222002-04-04 02:10:55 +00001030 rc = 1;
1031 }
drhd8bc7082000-06-07 23:51:50 +00001032 }
1033 }
danielk19774adee202004-05-08 08:23:19 +00001034 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001035 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001036 }
drh54473222002-04-04 02:10:55 +00001037 return rc;
drhd8bc7082000-06-07 23:51:50 +00001038}
1039
1040/*
drhff78bd22002-02-27 01:47:11 +00001041** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1042** in a select structure. It just sets the pointers to NULL. This
1043** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1044** pointer is not NULL, this routine is called recursively on that pointer.
1045**
1046** This routine is called on the Select structure that defines a
1047** VIEW in order to undo any bindings to tables. This is necessary
1048** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001049** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1050** will be left pointing to a deallocated Table structure after the
1051** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001052*/
danielk19774adee202004-05-08 08:23:19 +00001053void sqlite3SelectUnbind(Select *p){
drhff78bd22002-02-27 01:47:11 +00001054 int i;
drhad3cab52002-05-24 02:04:32 +00001055 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +00001056 Table *pTab;
1057 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +00001058 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +00001059 if( (pTab = pSrc->a[i].pTab)!=0 ){
1060 if( pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001061 sqlite3DeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001062 }
1063 pSrc->a[i].pTab = 0;
1064 if( pSrc->a[i].pSelect ){
danielk19774adee202004-05-08 08:23:19 +00001065 sqlite3SelectUnbind(pSrc->a[i].pSelect);
drhff78bd22002-02-27 01:47:11 +00001066 }
1067 }
1068 }
1069}
1070
1071/*
drhd8bc7082000-06-07 23:51:50 +00001072** This routine associates entries in an ORDER BY expression list with
1073** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001074** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001075** the top-level node is filled in with column number and the iTable
1076** value of the top-level node is filled with iTable parameter.
1077**
1078** If there are prior SELECT clauses, they are processed first. A match
1079** in an earlier SELECT takes precedence over a later SELECT.
1080**
1081** Any entry that does not match is flagged as an error. The number
1082** of errors is returned.
1083*/
1084static int matchOrderbyToColumn(
1085 Parse *pParse, /* A place to leave error messages */
1086 Select *pSelect, /* Match to result columns of this SELECT */
1087 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001088 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001089 int mustComplete /* If TRUE all ORDER BYs must match */
1090){
1091 int nErr = 0;
1092 int i, j;
1093 ExprList *pEList;
1094
drhdaffd0e2001-04-11 14:28:42 +00001095 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001096 if( mustComplete ){
1097 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1098 }
1099 if( fillInColumnList(pParse, pSelect) ){
1100 return 1;
1101 }
1102 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001103 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1104 return 1;
1105 }
drhd8bc7082000-06-07 23:51:50 +00001106 }
1107 pEList = pSelect->pEList;
1108 for(i=0; i<pOrderBy->nExpr; i++){
1109 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001110 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001111 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001112 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001113 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001114 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001115 "ORDER BY position %d should be between 1 and %d",
1116 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001117 nErr++;
1118 break;
1119 }
drhfcb78a42003-01-18 20:11:05 +00001120 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001121 iCol--;
1122 }
1123 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001124 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001125 char *zName, *zLabel;
1126 zName = pEList->a[j].zName;
1127 assert( pE->token.z );
1128 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
danielk19774adee202004-05-08 08:23:19 +00001129 sqlite3Dequote(zLabel);
1130 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001131 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001132 }
drh6e142f52000-06-08 13:36:40 +00001133 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001134 }
danielk19774adee202004-05-08 08:23:19 +00001135 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001136 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001137 }
1138 }
drhe4de1fe2002-06-02 16:09:01 +00001139 if( iCol>=0 ){
1140 pE->op = TK_COLUMN;
1141 pE->iColumn = iCol;
1142 pE->iTable = iTable;
1143 pOrderBy->a[i].done = 1;
1144 }
1145 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001146 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001147 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001148 nErr++;
1149 break;
1150 }
1151 }
1152 return nErr;
1153}
1154
1155/*
1156** Get a VDBE for the given parser context. Create a new one if necessary.
1157** If an error occurs, return NULL and leave a message in pParse.
1158*/
danielk19774adee202004-05-08 08:23:19 +00001159Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001160 Vdbe *v = pParse->pVdbe;
1161 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001162 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001163 }
drhd8bc7082000-06-07 23:51:50 +00001164 return v;
1165}
drhfcb78a42003-01-18 20:11:05 +00001166
drhd3d39e92004-05-20 22:16:29 +00001167#if 0 /***** This routine needs deleting *****/
danielk197784ac9d02004-05-18 09:58:06 +00001168static void multiSelectAffinity(Select *p, char *zAff){
1169 int i;
1170
1171 if( !p ) return;
1172 multiSelectAffinity(p->pPrior, zAff);
1173
1174 for(i=0; i<p->pEList->nExpr; i++){
1175 if( zAff[i]=='\0' ){
1176 zAff[i] = sqlite3ExprAffinity(p->pEList->a[i].pExpr);
1177 }
1178 }
1179}
drhd3d39e92004-05-20 22:16:29 +00001180#endif
danielk197784ac9d02004-05-18 09:58:06 +00001181
drhd8bc7082000-06-07 23:51:50 +00001182/*
drh7b58dae2003-07-20 01:16:46 +00001183** Compute the iLimit and iOffset fields of the SELECT based on the
1184** nLimit and nOffset fields. nLimit and nOffset hold the integers
1185** that appear in the original SQL statement after the LIMIT and OFFSET
1186** keywords. Or that hold -1 and 0 if those keywords are omitted.
1187** iLimit and iOffset are the integer memory register numbers for
1188** counters used to compute the limit and offset. If there is no
1189** limit and/or offset, then iLimit and iOffset are negative.
1190**
1191** This routine changes the values if iLimit and iOffset only if
1192** a limit or offset is defined by nLimit and nOffset. iLimit and
1193** iOffset should have been preset to appropriate default values
1194** (usually but not always -1) prior to calling this routine.
1195** Only if nLimit>=0 or nOffset>0 do the limit registers get
1196** redefined. The UNION ALL operator uses this property to force
1197** the reuse of the same limit and offset registers across multiple
1198** SELECT statements.
1199*/
1200static void computeLimitRegisters(Parse *pParse, Select *p){
1201 /*
1202 ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
1203 ** all rows. It is the same as no limit. If the comparision is
1204 ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
1205 ** "LIMIT -1" always shows all rows. There is some
1206 ** contraversy about what the correct behavior should be.
1207 ** The current implementation interprets "LIMIT 0" to mean
1208 ** no rows.
1209 */
1210 if( p->nLimit>=0 ){
1211 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001212 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001213 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001214 sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1215 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001216 p->iLimit = iMem;
1217 }
1218 if( p->nOffset>0 ){
1219 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001220 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001221 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001222 sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1223 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001224 p->iOffset = iMem;
1225 }
1226}
1227
1228/*
drhd3d39e92004-05-20 22:16:29 +00001229** Generate VDBE instructions that will open a transient table that
1230** will be used for an index or to store keyed results for a compound
1231** select. In other words, open a transient table that needs a
1232** KeyInfo structure. The number of columns in the KeyInfo is determined
1233** by the result set of the SELECT statement in the second argument.
1234**
danielk1977dc1bdc42004-06-11 10:51:27 +00001235** Specifically, this routine is called to open an index table for
1236** DISTINCT, UNION, INTERSECT and EXCEPT select statements (but not
1237** UNION ALL).
1238**
drhd3d39e92004-05-20 22:16:29 +00001239** Make the new table a KeyAsData table if keyAsData is true.
danielk1977dc1bdc42004-06-11 10:51:27 +00001240**
1241** The value returned is the address of the OP_OpenTemp instruction.
drhd3d39e92004-05-20 22:16:29 +00001242*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001243static int openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
drhd3d39e92004-05-20 22:16:29 +00001244 KeyInfo *pKeyInfo;
drh736c22b2004-05-21 02:14:24 +00001245 int nColumn;
drhd3d39e92004-05-20 22:16:29 +00001246 sqlite *db = pParse->db;
1247 int i;
1248 Vdbe *v = pParse->pVdbe;
danielk1977dc1bdc42004-06-11 10:51:27 +00001249 int addr;
drhd3d39e92004-05-20 22:16:29 +00001250
drh736c22b2004-05-21 02:14:24 +00001251 if( fillInColumnList(pParse, p) ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001252 return 0;
drh736c22b2004-05-21 02:14:24 +00001253 }
1254 nColumn = p->pEList->nExpr;
drhd3d39e92004-05-20 22:16:29 +00001255 pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
danielk1977dc1bdc42004-06-11 10:51:27 +00001256 if( pKeyInfo==0 ) return 0;
1257 pKeyInfo->enc = pParse->db->enc;
drhd3d39e92004-05-20 22:16:29 +00001258 pKeyInfo->nField = nColumn;
1259 for(i=0; i<nColumn; i++){
danielk1977dc1bdc42004-06-11 10:51:27 +00001260 pKeyInfo->aColl[i] = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
1261 if( !pKeyInfo->aColl[i] ){
1262 pKeyInfo->aColl[i] = db->pDfltColl;
1263 }
drhd3d39e92004-05-20 22:16:29 +00001264 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001265 addr = sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0,
1266 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drhd3d39e92004-05-20 22:16:29 +00001267 if( keyAsData ){
1268 sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1269 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001270 return addr;
1271}
1272
1273static int multiSelectOpenTempAddr(Select *p, int addr, IdList **ppOpenTemp){
1274 if( !p->ppOpenTemp ){
1275 *ppOpenTemp = sqlite3IdListAppend(0, 0);
1276 p->ppOpenTemp = ppOpenTemp;
1277 }else{
1278 *p->ppOpenTemp = sqlite3IdListAppend(*p->ppOpenTemp, 0);
1279 }
1280 if( !(*p->ppOpenTemp) ){
1281 return SQLITE_NOMEM;
1282 }
1283 (*p->ppOpenTemp)->a[(*p->ppOpenTemp)->nId-1].idx = addr;
1284 return SQLITE_OK;
1285}
1286
1287static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1288 CollSeq *pRet = 0;
1289 if( p->pPrior ){
1290 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1291 }
1292 if( !pRet ){
1293 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1294 }
1295 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001296}
1297
1298/*
drh82c3d632000-06-06 21:56:07 +00001299** This routine is called to process a query that is really the union
1300** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001301**
drhe78e8282003-01-19 03:59:45 +00001302** "p" points to the right-most of the two queries. the query on the
1303** left is p->pPrior. The left query could also be a compound query
1304** in which case this routine will be called recursively.
1305**
1306** The results of the total query are to be written into a destination
1307** of type eDest with parameter iParm.
1308**
1309** Example 1: Consider a three-way compound SQL statement.
1310**
1311** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1312**
1313** This statement is parsed up as follows:
1314**
1315** SELECT c FROM t3
1316** |
1317** `-----> SELECT b FROM t2
1318** |
jplyon4b11c6d2004-01-19 04:57:53 +00001319** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001320**
1321** The arrows in the diagram above represent the Select.pPrior pointer.
1322** So if this routine is called with p equal to the t3 query, then
1323** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1324**
1325** Notice that because of the way SQLite parses compound SELECTs, the
1326** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001327*/
danielk197784ac9d02004-05-18 09:58:06 +00001328static int multiSelect(
1329 Parse *pParse,
1330 Select *p,
1331 int eDest,
1332 int iParm,
1333 char *aff /* If eDest is SRT_Union, the affinity string */
1334){
1335 int rc = SQLITE_OK; /* Success code from a subroutine */
drh10e5e3c2000-06-08 00:19:02 +00001336 Select *pPrior; /* Another SELECT immediately to our left */
1337 Vdbe *v; /* Generate code to this VDBE */
danielk1977dc1bdc42004-06-11 10:51:27 +00001338 IdList *pOpenTemp = 0;
drh82c3d632000-06-06 21:56:07 +00001339
drh7b58dae2003-07-20 01:16:46 +00001340 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
1341 ** the last SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001342 */
danielk197784ac9d02004-05-18 09:58:06 +00001343 if( p==0 || p->pPrior==0 ){
1344 rc = 1;
1345 goto multi_select_end;
1346 }
drhd8bc7082000-06-07 23:51:50 +00001347 pPrior = p->pPrior;
1348 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001349 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001350 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001351 rc = 1;
1352 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001353 }
drh7b58dae2003-07-20 01:16:46 +00001354 if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
danielk19774adee202004-05-08 08:23:19 +00001355 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001356 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001357 rc = 1;
1358 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001359 }
drh82c3d632000-06-06 21:56:07 +00001360
drhd8bc7082000-06-07 23:51:50 +00001361 /* Make sure we have a valid query engine. If not, create a new one.
1362 */
danielk19774adee202004-05-08 08:23:19 +00001363 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001364 if( v==0 ){
1365 rc = 1;
1366 goto multi_select_end;
1367 }
drhd8bc7082000-06-07 23:51:50 +00001368
drh1cc3d752002-03-23 00:31:29 +00001369 /* Create the destination temporary table if necessary
1370 */
1371 if( eDest==SRT_TempTable ){
danielk1977b4964b72004-05-18 01:23:38 +00001372 assert( p->pEList );
danielk19774adee202004-05-08 08:23:19 +00001373 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00001374 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, p->pEList->nExpr);
drh1cc3d752002-03-23 00:31:29 +00001375 eDest = SRT_Table;
1376 }
1377
drhf46f9052002-06-22 02:33:38 +00001378 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001379 */
drh82c3d632000-06-06 21:56:07 +00001380 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001381 case TK_ALL: {
1382 if( p->pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +00001383 pPrior->nLimit = p->nLimit;
1384 pPrior->nOffset = p->nOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001385 pPrior->ppOpenTemp = p->ppOpenTemp;
danielk197784ac9d02004-05-18 09:58:06 +00001386 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1387 if( rc ){
1388 goto multi_select_end;
1389 }
drhf46f9052002-06-22 02:33:38 +00001390 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001391 p->iLimit = pPrior->iLimit;
1392 p->iOffset = pPrior->iOffset;
1393 p->nLimit = -1;
1394 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001395 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001396 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001397 if( rc ){
1398 goto multi_select_end;
1399 }
drhf46f9052002-06-22 02:33:38 +00001400 break;
1401 }
1402 /* For UNION ALL ... ORDER BY fall through to the next case */
1403 }
drh82c3d632000-06-06 21:56:07 +00001404 case TK_EXCEPT:
1405 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001406 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001407 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001408 int priorOp; /* The SRT_ operation to apply to prior selects */
drh7b58dae2003-07-20 01:16:46 +00001409 int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
drhc926afb2002-06-20 03:38:26 +00001410 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
danielk1977dc1bdc42004-06-11 10:51:27 +00001411 int addr;
drh82c3d632000-06-06 21:56:07 +00001412
drhd8bc7082000-06-07 23:51:50 +00001413 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh7b58dae2003-07-20 01:16:46 +00001414 if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
drhd8bc7082000-06-07 23:51:50 +00001415 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001416 ** right.
drhd8bc7082000-06-07 23:51:50 +00001417 */
drh82c3d632000-06-06 21:56:07 +00001418 unionTab = iParm;
1419 }else{
drhd8bc7082000-06-07 23:51:50 +00001420 /* We will need to create our own temporary table to hold the
1421 ** intermediate results.
1422 */
1423 unionTab = pParse->nTab++;
1424 if( p->pOrderBy
1425 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001426 rc = 1;
1427 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001428 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001429 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001430 if( p->op!=TK_ALL ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001431 rc = multiSelectOpenTempAddr(p, addr, &pOpenTemp);
1432 if( rc!=SQLITE_OK ){
1433 goto multi_select_end;
1434 }
1435 sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drhd8bc7082000-06-07 23:51:50 +00001436 }
danielk197784ac9d02004-05-18 09:58:06 +00001437 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001438 }
drhd8bc7082000-06-07 23:51:50 +00001439
1440 /* Code the SELECT statements to our left
1441 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001442 pPrior->ppOpenTemp = p->ppOpenTemp;
danielk197784ac9d02004-05-18 09:58:06 +00001443 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
1444 if( rc ){
1445 goto multi_select_end;
1446 }
1447 if( p->op==TK_ALL ){
1448 sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, pPrior->pEList->nExpr);
1449 }
drhd8bc7082000-06-07 23:51:50 +00001450
1451 /* Code the current SELECT statement
1452 */
1453 switch( p->op ){
1454 case TK_EXCEPT: op = SRT_Except; break;
1455 case TK_UNION: op = SRT_Union; break;
1456 case TK_ALL: op = SRT_Table; break;
1457 }
drh82c3d632000-06-06 21:56:07 +00001458 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001459 pOrderBy = p->pOrderBy;
1460 p->pOrderBy = 0;
drh7b58dae2003-07-20 01:16:46 +00001461 nLimit = p->nLimit;
1462 p->nLimit = -1;
1463 nOffset = p->nOffset;
1464 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001465 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001466 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001467 p->pOrderBy = pOrderBy;
drh7b58dae2003-07-20 01:16:46 +00001468 p->nLimit = nLimit;
1469 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001470 if( rc ){
1471 goto multi_select_end;
1472 }
1473
drhd8bc7082000-06-07 23:51:50 +00001474
1475 /* Convert the data in the temporary table into whatever form
1476 ** it is that we currently need.
1477 */
drhc926afb2002-06-20 03:38:26 +00001478 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001479 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001480 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001481 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001482 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001483 }
danielk19774adee202004-05-08 08:23:19 +00001484 iBreak = sqlite3VdbeMakeLabel(v);
1485 iCont = sqlite3VdbeMakeLabel(v);
1486 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001487 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001488 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001489 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001490 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001491 iCont, iBreak, 0);
1492 if( rc ){
1493 rc = 1;
1494 goto multi_select_end;
1495 }
danielk19774adee202004-05-08 08:23:19 +00001496 sqlite3VdbeResolveLabel(v, iCont);
1497 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1498 sqlite3VdbeResolveLabel(v, iBreak);
1499 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001500 }
1501 break;
1502 }
1503 case TK_INTERSECT: {
1504 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001505 int iCont, iBreak, iStart;
drh7b58dae2003-07-20 01:16:46 +00001506 int nLimit, nOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001507 int addr;
drh82c3d632000-06-06 21:56:07 +00001508
drhd8bc7082000-06-07 23:51:50 +00001509 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001510 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001511 ** by allocating the tables we will need.
1512 */
drh82c3d632000-06-06 21:56:07 +00001513 tab1 = pParse->nTab++;
1514 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001515 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001516 rc = 1;
1517 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001518 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001519
1520 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 0);
1521 rc = multiSelectOpenTempAddr(p, addr, &pOpenTemp);
1522 if( rc!=SQLITE_OK ){
1523 goto multi_select_end;
1524 }
1525 sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
danielk197784ac9d02004-05-18 09:58:06 +00001526 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001527
1528 /* Code the SELECTs to our left into temporary table "tab1".
1529 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001530 pPrior->ppOpenTemp = p->ppOpenTemp;
danielk197784ac9d02004-05-18 09:58:06 +00001531 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
1532 if( rc ){
1533 goto multi_select_end;
1534 }
drhd8bc7082000-06-07 23:51:50 +00001535
1536 /* Code the current SELECT into temporary table "tab2"
1537 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001538 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0);
1539 rc = multiSelectOpenTempAddr(p, addr, &pOpenTemp);
1540 if( rc!=SQLITE_OK ){
1541 goto multi_select_end;
1542 }
1543 sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001544 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001545 nLimit = p->nLimit;
1546 p->nLimit = -1;
1547 nOffset = p->nOffset;
1548 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001549 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001550 p->pPrior = pPrior;
drh7b58dae2003-07-20 01:16:46 +00001551 p->nLimit = nLimit;
1552 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001553 if( rc ){
1554 goto multi_select_end;
1555 }
drhd8bc7082000-06-07 23:51:50 +00001556
1557 /* Generate code to take the intersection of the two temporary
1558 ** tables.
1559 */
drh82c3d632000-06-06 21:56:07 +00001560 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001561 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001562 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001563 }
danielk19774adee202004-05-08 08:23:19 +00001564 iBreak = sqlite3VdbeMakeLabel(v);
1565 iCont = sqlite3VdbeMakeLabel(v);
1566 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001567 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001568 iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
1569 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001570 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001571 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001572 iCont, iBreak, 0);
1573 if( rc ){
1574 rc = 1;
1575 goto multi_select_end;
1576 }
danielk19774adee202004-05-08 08:23:19 +00001577 sqlite3VdbeResolveLabel(v, iCont);
1578 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1579 sqlite3VdbeResolveLabel(v, iBreak);
1580 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1581 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001582 break;
1583 }
1584 }
1585 assert( p->pEList && pPrior->pEList );
1586 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001587 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001588 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001589 rc = 1;
1590 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001591 }
danielk197784ac9d02004-05-18 09:58:06 +00001592
danielk1977dc1bdc42004-06-11 10:51:27 +00001593 if( p->pOrderBy || (pOpenTemp && pOpenTemp->nId>0) ){
1594 int nCol = p->pEList->nExpr;
1595 int i;
1596 KeyInfo *pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*sizeof(CollSeq*));
1597 if( !pKeyInfo ){
1598 rc = SQLITE_NOMEM;
1599 goto multi_select_end;
1600 }
1601
1602 pKeyInfo->enc = pParse->db->enc;
1603 pKeyInfo->nField = nCol;
1604
1605 for(i=0; i<nCol; i++){
1606 pKeyInfo->aColl[i] = multiSelectCollSeq(pParse, p, i);
1607 if( !pKeyInfo->aColl[i] ){
1608 pKeyInfo->aColl[i] = pParse->db->pDfltColl;
1609 }
1610 }
1611
1612 for(i=0; pOpenTemp && i<pOpenTemp->nId; i++){
1613 int p3type = (i==0?P3_KEYINFO_HANDOFF:P3_KEYINFO);
1614 int addr = pOpenTemp->a[i].idx;
1615 sqlite3VdbeChangeP3(v, addr, (char *)pKeyInfo, p3type);
1616 }
1617
1618 if( p->pOrderBy ){
1619 for(i=0; i<p->pOrderBy->nExpr; i++){
1620 Expr *pExpr = p->pOrderBy->a[i].pExpr;
1621 char *zName = p->pOrderBy->a[i].zName;
1622 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
1623 assert( !pExpr->pColl );
1624 if( zName ){
1625 pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1);
1626 }else{
1627 pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn];
1628 }
1629 }
1630 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1631 }
1632
1633 if( !pOpenTemp ){
1634 /* This happens for UNION ALL ... ORDER BY */
1635 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001636 }
1637 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001638
1639multi_select_end:
1640 if( pOpenTemp ){
1641 sqlite3IdListDelete(pOpenTemp);
1642 }
1643 p->ppOpenTemp = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001644 return rc;
drh22827922000-06-06 17:27:05 +00001645}
1646
1647/*
drh832508b2002-03-02 17:04:07 +00001648** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001649** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001650** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001651** unchanged.)
drh832508b2002-03-02 17:04:07 +00001652**
1653** This routine is part of the flattening procedure. A subquery
1654** whose result set is defined by pEList appears as entry in the
1655** FROM clause of a SELECT such that the VDBE cursor assigned to that
1656** FORM clause entry is iTable. This routine make the necessary
1657** changes to pExpr so that it refers directly to the source table
1658** of the subquery rather the result set of the subquery.
1659*/
drh6a3ea0e2003-05-02 14:32:12 +00001660static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1661static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001662 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001663 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1664 if( pExpr->iColumn<0 ){
1665 pExpr->op = TK_NULL;
1666 }else{
1667 Expr *pNew;
1668 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1669 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1670 pNew = pEList->a[pExpr->iColumn].pExpr;
1671 assert( pNew!=0 );
1672 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001673 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001674 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001675 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001676 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001677 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001678 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001679 pExpr->iTable = pNew->iTable;
1680 pExpr->iColumn = pNew->iColumn;
1681 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001682 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1683 sqlite3TokenCopy(&pExpr->span, &pNew->span);
drh50350a12004-02-13 16:22:22 +00001684 }
drh832508b2002-03-02 17:04:07 +00001685 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001686 substExpr(pExpr->pLeft, iTable, pEList);
1687 substExpr(pExpr->pRight, iTable, pEList);
1688 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001689 }
1690}
1691static void
drh6a3ea0e2003-05-02 14:32:12 +00001692substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001693 int i;
1694 if( pList==0 ) return;
1695 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001696 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001697 }
1698}
1699
1700/*
drh1350b032002-02-27 19:00:20 +00001701** This routine attempts to flatten subqueries in order to speed
1702** execution. It returns 1 if it makes changes and 0 if no flattening
1703** occurs.
1704**
1705** To understand the concept of flattening, consider the following
1706** query:
1707**
1708** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1709**
1710** The default way of implementing this query is to execute the
1711** subquery first and store the results in a temporary table, then
1712** run the outer query on that temporary table. This requires two
1713** passes over the data. Furthermore, because the temporary table
1714** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001715** optimized.
drh1350b032002-02-27 19:00:20 +00001716**
drh832508b2002-03-02 17:04:07 +00001717** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001718** a single flat select, like this:
1719**
1720** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1721**
1722** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001723** but only has to scan the data once. And because indices might
1724** exist on the table t1, a complete scan of the data might be
1725** avoided.
drh1350b032002-02-27 19:00:20 +00001726**
drh832508b2002-03-02 17:04:07 +00001727** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001728**
drh832508b2002-03-02 17:04:07 +00001729** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001730**
drh832508b2002-03-02 17:04:07 +00001731** (2) The subquery is not an aggregate or the outer query is not a join.
1732**
drh8af4d3a2003-05-06 20:35:16 +00001733** (3) The subquery is not the right operand of a left outer join, or
1734** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001735**
1736** (4) The subquery is not DISTINCT or the outer query is not a join.
1737**
1738** (5) The subquery is not DISTINCT or the outer query does not use
1739** aggregates.
1740**
1741** (6) The subquery does not use aggregates or the outer query is not
1742** DISTINCT.
1743**
drh08192d52002-04-30 19:20:28 +00001744** (7) The subquery has a FROM clause.
1745**
drhdf199a22002-06-14 22:38:41 +00001746** (8) The subquery does not use LIMIT or the outer query is not a join.
1747**
1748** (9) The subquery does not use LIMIT or the outer query does not use
1749** aggregates.
1750**
1751** (10) The subquery does not use aggregates or the outer query does not
1752** use LIMIT.
1753**
drh174b6192002-12-03 02:22:52 +00001754** (11) The subquery and the outer query do not both have ORDER BY clauses.
1755**
drh3fc673e2003-06-16 00:40:34 +00001756** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1757** subquery has no WHERE clause. (added by ticket #350)
1758**
drh832508b2002-03-02 17:04:07 +00001759** In this routine, the "p" parameter is a pointer to the outer query.
1760** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1761** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1762**
drh665de472003-03-31 13:36:09 +00001763** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001764** If flattening is attempted this routine returns 1.
1765**
1766** All of the expression analysis must occur on both the outer query and
1767** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001768*/
drh8c74a8c2002-08-25 19:20:40 +00001769static int flattenSubquery(
1770 Parse *pParse, /* The parsing context */
1771 Select *p, /* The parent or outer SELECT statement */
1772 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1773 int isAgg, /* True if outer SELECT uses aggregate functions */
1774 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1775){
drh0bb28102002-05-08 11:54:14 +00001776 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001777 SrcList *pSrc; /* The FROM clause of the outer query */
1778 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001779 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001780 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh832508b2002-03-02 17:04:07 +00001781 int i;
drh832508b2002-03-02 17:04:07 +00001782 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001783
drh832508b2002-03-02 17:04:07 +00001784 /* Check to see if flattening is permitted. Return 0 if not.
1785 */
1786 if( p==0 ) return 0;
1787 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001788 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001789 pSub = pSrc->a[iFrom].pSelect;
1790 assert( pSub!=0 );
1791 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001792 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001793 pSubSrc = pSub->pSrc;
1794 assert( pSubSrc );
drhc31c2eb2003-05-02 16:04:17 +00001795 if( pSubSrc->nSrc==0 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001796 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1797 return 0;
1798 }
drhd11d3822002-06-21 23:01:49 +00001799 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001800 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001801
drh8af4d3a2003-05-06 20:35:16 +00001802 /* Restriction 3: If the subquery is a join, make sure the subquery is
1803 ** not used as the right operand of an outer join. Examples of why this
1804 ** is not allowed:
1805 **
1806 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1807 **
1808 ** If we flatten the above, we would get
1809 **
1810 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1811 **
1812 ** which is not at all the same thing.
1813 */
1814 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1815 return 0;
1816 }
1817
drh3fc673e2003-06-16 00:40:34 +00001818 /* Restriction 12: If the subquery is the right operand of a left outer
1819 ** join, make sure the subquery has no WHERE clause.
1820 ** An examples of why this is not allowed:
1821 **
1822 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1823 **
1824 ** If we flatten the above, we would get
1825 **
1826 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1827 **
1828 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1829 ** effectively converts the OUTER JOIN into an INNER JOIN.
1830 */
1831 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1832 && pSub->pWhere!=0 ){
1833 return 0;
1834 }
1835
drh0bb28102002-05-08 11:54:14 +00001836 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001837 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001838 */
drhc31c2eb2003-05-02 16:04:17 +00001839
1840 /* Move all of the FROM elements of the subquery into the
1841 ** the FROM clause of the outer query. Before doing this, remember
1842 ** the cursor number for the original outer query FROM element in
1843 ** iParent. The iParent cursor will never be used. Subsequent code
1844 ** will scan expressions looking for iParent references and replace
1845 ** those references with expressions that resolve to the subquery FROM
1846 ** elements we are now copying in.
1847 */
drh6a3ea0e2003-05-02 14:32:12 +00001848 iParent = pSrc->a[iFrom].iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001849 {
1850 int nSubSrc = pSubSrc->nSrc;
drh8af4d3a2003-05-06 20:35:16 +00001851 int jointype = pSrc->a[iFrom].jointype;
drhc31c2eb2003-05-02 16:04:17 +00001852
1853 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001854 sqlite3DeleteTable(0, pSrc->a[iFrom].pTab);
drhc31c2eb2003-05-02 16:04:17 +00001855 }
drhf26e09c2003-05-31 16:21:12 +00001856 sqliteFree(pSrc->a[iFrom].zDatabase);
drhc31c2eb2003-05-02 16:04:17 +00001857 sqliteFree(pSrc->a[iFrom].zName);
1858 sqliteFree(pSrc->a[iFrom].zAlias);
1859 if( nSubSrc>1 ){
1860 int extra = nSubSrc - 1;
1861 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00001862 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00001863 }
1864 p->pSrc = pSrc;
1865 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1866 pSrc->a[i] = pSrc->a[i-extra];
1867 }
1868 }
1869 for(i=0; i<nSubSrc; i++){
1870 pSrc->a[i+iFrom] = pSubSrc->a[i];
1871 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1872 }
drh8af4d3a2003-05-06 20:35:16 +00001873 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00001874 }
1875
1876 /* Now begin substituting subquery result set expressions for
1877 ** references to the iParent in the outer query.
1878 **
1879 ** Example:
1880 **
1881 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1882 ** \ \_____________ subquery __________/ /
1883 ** \_____________________ outer query ______________________________/
1884 **
1885 ** We look at every expression in the outer query and every place we see
1886 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1887 */
drh6a3ea0e2003-05-02 14:32:12 +00001888 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001889 pList = p->pEList;
1890 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001891 Expr *pExpr;
1892 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1893 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001894 }
1895 }
drh1b2e0322002-03-03 02:49:51 +00001896 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00001897 substExprList(p->pGroupBy, iParent, pSub->pEList);
1898 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001899 }
drh174b6192002-12-03 02:22:52 +00001900 if( pSub->pOrderBy ){
1901 assert( p->pOrderBy==0 );
1902 p->pOrderBy = pSub->pOrderBy;
1903 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00001904 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00001905 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00001906 }
drh832508b2002-03-02 17:04:07 +00001907 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001908 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00001909 }else{
1910 pWhere = 0;
1911 }
1912 if( subqueryIsAgg ){
1913 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001914 p->pHaving = p->pWhere;
1915 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00001916 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001917 if( pSub->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001918 Expr *pHaving = sqlite3ExprDup(pSub->pHaving);
drh1b2e0322002-03-03 02:49:51 +00001919 if( p->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001920 p->pHaving = sqlite3Expr(TK_AND, p->pHaving, pHaving, 0);
drh1b2e0322002-03-03 02:49:51 +00001921 }else{
1922 p->pHaving = pHaving;
1923 }
1924 }
1925 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00001926 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00001927 }else if( p->pWhere==0 ){
1928 p->pWhere = pWhere;
1929 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001930 substExpr(p->pWhere, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001931 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001932 p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pWhere, 0);
drh832508b2002-03-02 17:04:07 +00001933 }
1934 }
drhc31c2eb2003-05-02 16:04:17 +00001935
1936 /* The flattened query is distinct if either the inner or the
1937 ** outer query is distinct.
1938 */
drh832508b2002-03-02 17:04:07 +00001939 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00001940
drhc31c2eb2003-05-02 16:04:17 +00001941 /* Transfer the limit expression from the subquery to the outer
1942 ** query.
1943 */
drhdf199a22002-06-14 22:38:41 +00001944 if( pSub->nLimit>=0 ){
1945 if( p->nLimit<0 ){
1946 p->nLimit = pSub->nLimit;
1947 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1948 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1949 }
1950 }
1951 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00001952
drhc31c2eb2003-05-02 16:04:17 +00001953 /* Finially, delete what is left of the subquery and return
1954 ** success.
1955 */
danielk19774adee202004-05-08 08:23:19 +00001956 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00001957 return 1;
1958}
drh1350b032002-02-27 19:00:20 +00001959
1960/*
drh9562b552002-02-19 15:00:07 +00001961** Analyze the SELECT statement passed in as an argument to see if it
1962** is a simple min() or max() query. If it is and this query can be
1963** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00001964** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00001965** simple min() or max() query, then return 0;
1966**
1967** A simply min() or max() query looks like this:
1968**
1969** SELECT min(a) FROM table;
1970** SELECT max(a) FROM table;
1971**
1972** The query may have only a single table in its FROM argument. There
1973** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1974** be the min() or max() of a single column of the table. The column
1975** in the min() or max() function must be indexed.
1976**
danielk19774adee202004-05-08 08:23:19 +00001977** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00001978** See the header comment on that routine for additional information.
1979*/
1980static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1981 Expr *pExpr;
1982 int iCol;
1983 Table *pTab;
1984 Index *pIdx;
1985 int base;
1986 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00001987 int seekOp;
1988 int cont;
drh6e175292004-03-13 14:00:36 +00001989 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00001990 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00001991 SrcList *pSrc;
1992
drh9562b552002-02-19 15:00:07 +00001993
1994 /* Check to see if this query is a simple min() or max() query. Return
1995 ** zero if it is not.
1996 */
1997 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00001998 pSrc = p->pSrc;
1999 if( pSrc->nSrc!=1 ) return 0;
2000 pEList = p->pEList;
2001 if( pEList->nExpr!=1 ) return 0;
2002 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002003 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002004 pList = pExpr->pList;
2005 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002006 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00002007 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002008 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00002009 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002010 seekOp = OP_Last;
2011 }else{
2012 return 0;
2013 }
drh6e175292004-03-13 14:00:36 +00002014 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002015 if( pExpr->op!=TK_COLUMN ) return 0;
2016 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002017 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002018
2019 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002020 ** Check to make sure we have an index and make pIdx point to the
2021 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2022 ** key column, no index is necessary so set pIdx to NULL. If no
2023 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002024 */
2025 if( iCol<0 ){
2026 pIdx = 0;
2027 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002028 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002029 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2030 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002031 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002032 }
2033 if( pIdx==0 ) return 0;
2034 }
2035
drhe5f50722003-07-19 00:44:14 +00002036 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002037 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002038 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002039 */
danielk19774adee202004-05-08 08:23:19 +00002040 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002041 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002042
drh0c37e632004-01-30 02:01:03 +00002043 /* If the output is destined for a temporary table, open that table.
2044 */
2045 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002046 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002047 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002048 }
2049
drh17f71932002-02-21 12:01:27 +00002050 /* Generating code to find the min or the max. Basically all we have
2051 ** to do is find the first or the last entry in the chosen index. If
2052 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2053 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002054 */
danielk19774adee202004-05-08 08:23:19 +00002055 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00002056 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00002057 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00002058 if( pSrc->a[0].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +00002059 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00002060 sqlite3VdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
danielk1977b4964b72004-05-18 01:23:38 +00002061 sqlite3VdbeAddOp(v, OP_SetNumColumns, base, pTab->nCol);
drh6e175292004-03-13 14:00:36 +00002062 }
danielk19774adee202004-05-08 08:23:19 +00002063 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00002064 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002065 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002066 }else{
danielk19774adee202004-05-08 08:23:19 +00002067 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00002068 sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum,
2069 (char*)&pIdx->keyInfo, P3_KEYINFO);
danielk19774adee202004-05-08 08:23:19 +00002070 sqlite3VdbeAddOp(v, seekOp, base+1, 0);
2071 sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
2072 sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002073 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002074 }
drh5cf8e8c2002-02-19 22:42:05 +00002075 eList.nExpr = 1;
2076 memset(&eListItem, 0, sizeof(eListItem));
2077 eList.a = &eListItem;
2078 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00002079 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00002080 sqlite3VdbeResolveLabel(v, cont);
2081 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002082
drh9562b552002-02-19 15:00:07 +00002083 return 1;
2084}
2085
2086/*
drh9bb61fe2000-06-05 16:01:39 +00002087** Generate code for the given SELECT statement.
2088**
drhfef52082000-06-06 01:50:43 +00002089** The results are distributed in various ways depending on the
2090** value of eDest and iParm.
2091**
2092** eDest Value Result
2093** ------------ -------------------------------------------
2094** SRT_Callback Invoke the callback for each row of the result.
2095**
2096** SRT_Mem Store first result in memory cell iParm
2097**
danielk1977e014a832004-05-17 10:48:57 +00002098** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002099**
drh82c3d632000-06-06 21:56:07 +00002100** SRT_Union Store results as a key in a temporary table iParm
2101**
jplyon4b11c6d2004-01-19 04:57:53 +00002102** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002103**
2104** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002105**
drhe78e8282003-01-19 03:59:45 +00002106** The table above is incomplete. Additional eDist value have be added
2107** since this comment was written. See the selectInnerLoop() function for
2108** a complete listing of the allowed values of eDest and their meanings.
2109**
drh9bb61fe2000-06-05 16:01:39 +00002110** This routine returns the number of errors. If any errors are
2111** encountered, then an appropriate error message is left in
2112** pParse->zErrMsg.
2113**
2114** This routine does NOT free the Select structure passed in. The
2115** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002116**
2117** The pParent, parentTab, and *pParentAgg fields are filled in if this
2118** SELECT is a subquery. This routine may try to combine this SELECT
2119** with its parent to form a single flat query. In so doing, it might
2120** change the parent query from a non-aggregate to an aggregate query.
2121** For that reason, the pParentAgg flag is passed as a pointer, so it
2122** can be changed.
drhe78e8282003-01-19 03:59:45 +00002123**
2124** Example 1: The meaning of the pParent parameter.
2125**
2126** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2127** \ \_______ subquery _______/ /
2128** \ /
2129** \____________________ outer query ___________________/
2130**
2131** This routine is called for the outer query first. For that call,
2132** pParent will be NULL. During the processing of the outer query, this
2133** routine is called recursively to handle the subquery. For the recursive
2134** call, pParent will point to the outer query. Because the subquery is
2135** the second element in a three-way join, the parentTab parameter will
2136** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002137*/
danielk19774adee202004-05-08 08:23:19 +00002138int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002139 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002140 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002141 int eDest, /* How to dispose of the results */
2142 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002143 Select *pParent, /* Another SELECT for which this is a sub-query */
2144 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002145 int *pParentAgg, /* True if pParent uses aggregate functions */
2146 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002147){
drhd8bc7082000-06-07 23:51:50 +00002148 int i;
drhcce7d172000-05-31 15:34:51 +00002149 WhereInfo *pWInfo;
2150 Vdbe *v;
2151 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002152 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002153 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002154 Expr *pWhere; /* The WHERE clause. May be NULL */
2155 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002156 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2157 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002158 int isDistinct; /* True if the DISTINCT keyword is present */
2159 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002160 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00002161
danielk19776f8a5032004-05-10 10:34:51 +00002162 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002163 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002164
drh82c3d632000-06-06 21:56:07 +00002165 /* If there is are a sequence of queries, do the earlier ones first.
2166 */
2167 if( p->pPrior ){
danielk197784ac9d02004-05-18 09:58:06 +00002168 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002169 }
2170
2171 /* Make local copies of the parameters for this query.
2172 */
drh9bb61fe2000-06-05 16:01:39 +00002173 pTabList = p->pSrc;
2174 pWhere = p->pWhere;
2175 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00002176 pGroupBy = p->pGroupBy;
2177 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00002178 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00002179
drh6a3ea0e2003-05-02 14:32:12 +00002180 /* Allocate VDBE cursors for each table in the FROM clause
drh10e5e3c2000-06-08 00:19:02 +00002181 */
danielk19774adee202004-05-08 08:23:19 +00002182 sqlite3SrcListAssignCursors(pParse, pTabList);
drh10e5e3c2000-06-08 00:19:02 +00002183
drh9bb61fe2000-06-05 16:01:39 +00002184 /*
2185 ** Do not even attempt to generate any code if we have already seen
2186 ** errors before this routine starts.
2187 */
drh1d83f052002-02-17 00:30:36 +00002188 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002189
drhe78e8282003-01-19 03:59:45 +00002190 /* Expand any "*" terms in the result set. (For example the "*" in
2191 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
2192 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00002193 */
drhd8bc7082000-06-07 23:51:50 +00002194 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00002195 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002196 }
drhad2d8302002-05-24 20:31:36 +00002197 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00002198 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00002199 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002200
drh22827922000-06-06 17:27:05 +00002201 /* If writing to memory or generating a set
2202 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002203 */
drhfef52082000-06-06 01:50:43 +00002204 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002205 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002206 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002207 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002208 }
2209
drhc926afb2002-06-20 03:38:26 +00002210 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002211 */
drhc926afb2002-06-20 03:38:26 +00002212 switch( eDest ){
2213 case SRT_Union:
2214 case SRT_Except:
2215 case SRT_Discard:
danielk1977f93bbbe2004-05-27 10:30:52 +00002216 case SRT_Set:
drhc926afb2002-06-20 03:38:26 +00002217 pOrderBy = 0;
2218 break;
2219 default:
2220 break;
drh22827922000-06-06 17:27:05 +00002221 }
2222
drh10e5e3c2000-06-08 00:19:02 +00002223 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002224 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002225 **
drh967e8b72000-06-21 13:59:10 +00002226 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002227 */
drh4794b982000-06-06 13:54:14 +00002228 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002229 if( sqlite3ExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002230 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002231 }
danielk19774adee202004-05-08 08:23:19 +00002232 if( sqlite3ExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002233 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002234 }
2235 }
drhcce7d172000-05-31 15:34:51 +00002236 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002237 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00002238 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002239 }
danielk19774adee202004-05-08 08:23:19 +00002240 if( sqlite3ExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00002241 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002242 }
2243 }
drhc66c5a22002-12-03 02:34:49 +00002244 if( pHaving ){
2245 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002246 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
drhc66c5a22002-12-03 02:34:49 +00002247 goto select_end;
2248 }
danielk19774adee202004-05-08 08:23:19 +00002249 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pHaving) ){
drhc66c5a22002-12-03 02:34:49 +00002250 goto select_end;
2251 }
danielk19774adee202004-05-08 08:23:19 +00002252 if( sqlite3ExprCheck(pParse, pHaving, 1, &isAgg) ){
drhc66c5a22002-12-03 02:34:49 +00002253 goto select_end;
2254 }
2255 }
drhcce7d172000-05-31 15:34:51 +00002256 if( pOrderBy ){
2257 for(i=0; i<pOrderBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002258 int iCol;
drh22827922000-06-06 17:27:05 +00002259 Expr *pE = pOrderBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002260 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2261 sqlite3ExprDelete(pE);
2262 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh88eee382003-01-31 17:16:36 +00002263 }
danielk19774adee202004-05-08 08:23:19 +00002264 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh88eee382003-01-31 17:16:36 +00002265 goto select_end;
2266 }
danielk19774adee202004-05-08 08:23:19 +00002267 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh88eee382003-01-31 17:16:36 +00002268 goto select_end;
2269 }
danielk19774adee202004-05-08 08:23:19 +00002270 if( sqlite3ExprIsConstant(pE) ){
2271 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2272 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002273 "ORDER BY terms must not be non-integer constants");
drhe4de1fe2002-06-02 16:09:01 +00002274 goto select_end;
2275 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002276 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002277 "ORDER BY column number %d out of range - should be "
drhe4de1fe2002-06-02 16:09:01 +00002278 "between 1 and %d", iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00002279 goto select_end;
2280 }
drhcce7d172000-05-31 15:34:51 +00002281 }
2282 }
2283 }
drh22827922000-06-06 17:27:05 +00002284 if( pGroupBy ){
2285 for(i=0; i<pGroupBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002286 int iCol;
drh22827922000-06-06 17:27:05 +00002287 Expr *pE = pGroupBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002288 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2289 sqlite3ExprDelete(pE);
2290 pE = pGroupBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00002291 }
danielk19774adee202004-05-08 08:23:19 +00002292 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00002293 goto select_end;
drh22827922000-06-06 17:27:05 +00002294 }
danielk19774adee202004-05-08 08:23:19 +00002295 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00002296 goto select_end;
drh22827922000-06-06 17:27:05 +00002297 }
danielk19774adee202004-05-08 08:23:19 +00002298 if( sqlite3ExprIsConstant(pE) ){
2299 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2300 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002301 "GROUP BY terms must not be non-integer constants");
drh88eee382003-01-31 17:16:36 +00002302 goto select_end;
2303 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002304 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002305 "GROUP BY column number %d out of range - should be "
drh88eee382003-01-31 17:16:36 +00002306 "between 1 and %d", iCol, pEList->nExpr);
drh88eee382003-01-31 17:16:36 +00002307 goto select_end;
2308 }
2309 }
drh22827922000-06-06 17:27:05 +00002310 }
2311 }
drhcce7d172000-05-31 15:34:51 +00002312
drhd820cb12002-02-18 03:21:45 +00002313 /* Begin generating code.
2314 */
danielk19774adee202004-05-08 08:23:19 +00002315 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002316 if( v==0 ) goto select_end;
2317
drhe78e8282003-01-19 03:59:45 +00002318 /* Identify column names if we will be using them in a callback. This
2319 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002320 */
2321 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002322 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002323 }
2324
drhd3d39e92004-05-20 22:16:29 +00002325#if 1 /* I do not think we need the following code any more.... */
danielk197784ac9d02004-05-18 09:58:06 +00002326 /* If the destination is SRT_Union, then set the number of columns in
2327 ** the records that will be inserted into the temporary table. The caller
2328 ** couldn't do this, in case the select statement is of the form
2329 ** "SELECT * FROM ....".
2330 **
2331 ** We need to do this before we start inserting records into the
2332 ** temporary table (which has had OP_KeyAsData executed on it), because
2333 ** it is required by the key comparison function. So do it now, even
2334 ** though this means that OP_SetNumColumns may be executed on the same
2335 ** cursor more than once.
2336 */
2337 if( eDest==SRT_Union ){
2338 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
2339 }
drhd3d39e92004-05-20 22:16:29 +00002340#endif
danielk197784ac9d02004-05-18 09:58:06 +00002341
drhd820cb12002-02-18 03:21:45 +00002342 /* Generate code for all sub-queries in the FROM clause
2343 */
drhad3cab52002-05-24 02:04:32 +00002344 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002345 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002346 int needRestoreContext;
2347
drha76b5df2002-02-23 02:32:10 +00002348 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002349 if( pTabList->a[i].zName!=0 ){
2350 zSavedAuthContext = pParse->zAuthContext;
2351 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002352 needRestoreContext = 1;
2353 }else{
2354 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002355 }
danielk19774adee202004-05-08 08:23:19 +00002356 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
danielk197784ac9d02004-05-18 09:58:06 +00002357 pTabList->a[i].iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002358 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002359 pParse->zAuthContext = zSavedAuthContext;
2360 }
drh1b2e0322002-03-03 02:49:51 +00002361 pTabList = p->pSrc;
2362 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002363 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002364 pOrderBy = p->pOrderBy;
2365 }
drh1b2e0322002-03-03 02:49:51 +00002366 pGroupBy = p->pGroupBy;
2367 pHaving = p->pHaving;
2368 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002369 }
2370
drh6e175292004-03-13 14:00:36 +00002371 /* Check for the special case of a min() or max() function by itself
2372 ** in the result set.
2373 */
2374 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2375 rc = 0;
2376 goto select_end;
2377 }
2378
drh832508b2002-03-02 17:04:07 +00002379 /* Check to see if this is a subquery that can be "flattened" into its parent.
2380 ** If flattening is a possiblity, do so and return immediately.
2381 */
drh1b2e0322002-03-03 02:49:51 +00002382 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002383 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002384 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002385 return rc;
2386 }
drh832508b2002-03-02 17:04:07 +00002387
danielk19777cedc8d2004-06-10 10:50:08 +00002388 /* If there is an ORDER BY clause, resolve any collation sequences
2389 ** names that have been explicitly specified.
2390 */
2391 if( pOrderBy ){
2392 for(i=0; i<pOrderBy->nExpr; i++){
2393 if( pOrderBy->a[i].zName ){
2394 pOrderBy->a[i].pExpr->pColl =
2395 sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1);
2396 }
2397 }
2398 if( pParse->nErr ){
2399 goto select_end;
2400 }
2401 }
2402
drh7b58dae2003-07-20 01:16:46 +00002403 /* Set the limiter.
2404 */
2405 computeLimitRegisters(pParse, p);
2406
drh2d0794e2002-03-03 03:03:52 +00002407 /* If the output is destined for a temporary table, open that table.
2408 */
2409 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002410 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002411 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002412 }
2413
drh22827922000-06-06 17:27:05 +00002414 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002415 */
drhd820cb12002-02-18 03:21:45 +00002416 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002417 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002418 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002419 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002420 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002421 if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002422 goto select_end;
drh22827922000-06-06 17:27:05 +00002423 }
2424 }
2425 if( pGroupBy ){
2426 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002427 if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002428 goto select_end;
drh22827922000-06-06 17:27:05 +00002429 }
2430 }
2431 }
danielk19774adee202004-05-08 08:23:19 +00002432 if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002433 goto select_end;
drh22827922000-06-06 17:27:05 +00002434 }
drh191b6902000-06-08 11:13:01 +00002435 if( pOrderBy ){
2436 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002437 if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002438 goto select_end;
drh191b6902000-06-08 11:13:01 +00002439 }
2440 }
2441 }
drhefb72512000-05-31 20:00:52 +00002442 }
2443
drh22827922000-06-06 17:27:05 +00002444 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002445 */
2446 if( isAgg ){
danielk1977ce2663c2004-06-11 13:19:21 +00002447 int addr = sqlite3VdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002448 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002449 FuncDef *pFunc;
2450 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drhf9b596e2004-05-26 16:54:42 +00002451 sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_FUNCDEF);
drhe5095352002-02-24 03:25:14 +00002452 }
2453 }
drh1bee3d72001-10-15 00:44:35 +00002454 if( pGroupBy==0 ){
danielk19770f69c1e2004-05-29 11:24:50 +00002455 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00002456 sqlite3VdbeAddOp(v, OP_AggFocus, 0, 0);
danielk1977ce2663c2004-06-11 13:19:21 +00002457 }else{
2458 int sz = sizeof(KeyInfo) + pGroupBy->nExpr*sizeof(CollSeq*);
2459 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(sz);
2460 if( 0==pKey ){
2461 goto select_end;
2462 }
2463 pKey->enc = pParse->db->enc;
2464 pKey->nField = pGroupBy->nExpr;
2465 for(i=0; i<pGroupBy->nExpr; i++){
2466 pKey->aColl[i] = sqlite3ExprCollSeq(pParse, pGroupBy->a[i].pExpr);
2467 if( !pKey->aColl[i] ){
2468 pKey->aColl[i] = pParse->db->pDfltColl;
2469 }
2470 }
2471 sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF);
drh1bee3d72001-10-15 00:44:35 +00002472 }
drhcce7d172000-05-31 15:34:51 +00002473 }
2474
drh19a775c2000-06-05 18:54:46 +00002475 /* Initialize the memory cell to NULL
2476 */
drhfef52082000-06-06 01:50:43 +00002477 if( eDest==SRT_Mem ){
danielk19770f69c1e2004-05-29 11:24:50 +00002478 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00002479 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002480 }
2481
drh832508b2002-03-02 17:04:07 +00002482 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002483 */
drh19a775c2000-06-05 18:54:46 +00002484 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002485 distinct = pParse->nTab++;
drhd3d39e92004-05-20 22:16:29 +00002486 openTempIndex(pParse, p, distinct, 0);
drh832508b2002-03-02 17:04:07 +00002487 }else{
2488 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002489 }
drh832508b2002-03-02 17:04:07 +00002490
2491 /* Begin the database scan
2492 */
danielk19774adee202004-05-08 08:23:19 +00002493 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
drh68d2e592002-08-04 00:52:38 +00002494 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002495 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002496
drh22827922000-06-06 17:27:05 +00002497 /* Use the standard inner loop if we are not dealing with
2498 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002499 */
drhda9d6c42000-05-31 18:20:14 +00002500 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002501 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002502 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002503 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002504 }
drhcce7d172000-05-31 15:34:51 +00002505 }
drhefb72512000-05-31 20:00:52 +00002506
drhe3184742002-06-19 14:27:05 +00002507 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002508 ** processing.
drhefb72512000-05-31 20:00:52 +00002509 */
drh22827922000-06-06 17:27:05 +00002510 else{
drh268380c2004-02-25 13:47:31 +00002511 AggExpr *pAgg;
drh22827922000-06-06 17:27:05 +00002512 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002513 int lbl1;
drh22827922000-06-06 17:27:05 +00002514 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002515 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
drh22827922000-06-06 17:27:05 +00002516 }
drhd3d39e92004-05-20 22:16:29 +00002517 /* No affinity string is attached to the following OP_MakeKey
2518 ** because we do not need to do any coercion of datatypes. */
danielk19774adee202004-05-08 08:23:19 +00002519 sqlite3VdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +00002520 lbl1 = sqlite3VdbeMakeLabel(v);
2521 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh268380c2004-02-25 13:47:31 +00002522 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2523 if( pAgg->isAgg ) continue;
danielk19774adee202004-05-08 08:23:19 +00002524 sqlite3ExprCode(pParse, pAgg->pExpr);
2525 sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002526 }
danielk19774adee202004-05-08 08:23:19 +00002527 sqlite3VdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002528 }
drh268380c2004-02-25 13:47:31 +00002529 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002530 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002531 int nExpr;
2532 FuncDef *pDef;
2533 if( !pAgg->isAgg ) continue;
2534 assert( pAgg->pFunc!=0 );
2535 assert( pAgg->pFunc->xStep!=0 );
2536 pDef = pAgg->pFunc;
2537 pE = pAgg->pExpr;
2538 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002539 assert( pE->op==TK_AGG_FUNCTION );
drhf9b596e2004-05-26 16:54:42 +00002540 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
danielk19774adee202004-05-08 08:23:19 +00002541 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
danielk1977dc1bdc42004-06-11 10:51:27 +00002542 if( pDef->needCollSeq ){
2543 CollSeq *pColl = 0;
2544 int j;
2545 for(j=0; !pColl && j<nExpr; j++){
2546 pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr);
2547 }
2548 if( !pColl ) pColl = pParse->db->pDfltColl;
2549 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2550 }
danielk19774adee202004-05-08 08:23:19 +00002551 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002552 }
drhcce7d172000-05-31 15:34:51 +00002553 }
2554
2555 /* End the database scan loop.
2556 */
danielk19774adee202004-05-08 08:23:19 +00002557 sqlite3WhereEnd(pWInfo);
drhcce7d172000-05-31 15:34:51 +00002558
drh22827922000-06-06 17:27:05 +00002559 /* If we are processing aggregates, we need to set up a second loop
2560 ** over all of the aggregate values and process them.
2561 */
2562 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002563 int endagg = sqlite3VdbeMakeLabel(v);
drh22827922000-06-06 17:27:05 +00002564 int startagg;
danielk19774adee202004-05-08 08:23:19 +00002565 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002566 pParse->useAgg = 1;
2567 if( pHaving ){
danielk19774adee202004-05-08 08:23:19 +00002568 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002569 }
drhdf199a22002-06-14 22:38:41 +00002570 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002571 iParm, startagg, endagg, aff) ){
drh1d83f052002-02-17 00:30:36 +00002572 goto select_end;
drh22827922000-06-06 17:27:05 +00002573 }
danielk19774adee202004-05-08 08:23:19 +00002574 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2575 sqlite3VdbeResolveLabel(v, endagg);
2576 sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002577 pParse->useAgg = 0;
2578 }
2579
drhcce7d172000-05-31 15:34:51 +00002580 /* If there is an ORDER BY clause, then we need to sort the results
2581 ** and send them to the callback one by one.
2582 */
2583 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00002584 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002585 }
drh6a535342001-10-19 16:44:56 +00002586
drhf620b4e2004-02-09 14:37:50 +00002587 /* If this was a subquery, we have now converted the subquery into a
2588 ** temporary table. So delete the subquery structure from the parent
2589 ** to prevent this subquery from being evaluated again and to force the
2590 ** the use of the temporary table.
2591 */
2592 if( pParent ){
2593 assert( pParent->pSrc->nSrc>parentTab );
2594 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00002595 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00002596 pParent->pSrc->a[parentTab].pSelect = 0;
2597 }
2598
drh1d83f052002-02-17 00:30:36 +00002599 /* The SELECT was successfully coded. Set the return code to 0
2600 ** to indicate no errors.
2601 */
2602 rc = 0;
2603
2604 /* Control jumps to here if an error is encountered above, or upon
2605 ** successful coding of the SELECT.
2606 */
2607select_end:
2608 sqliteAggregateInfoReset(pParse);
2609 return rc;
drhcce7d172000-05-31 15:34:51 +00002610}