blob: 243c8186dc3c0b130fe5b14092be5304d3df78a5 [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**
drh2c61c072004-07-20 00:20:23 +000015** $Id: select.c,v 1.200 2004/07/20 00:20:23 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
drh315555c2002-10-20 15:53:03 +000019
drhcce7d172000-05-31 15:34:51 +000020/*
drh9bb61fe2000-06-05 16:01:39 +000021** Allocate a new Select structure and return a pointer to that
22** structure.
drhcce7d172000-05-31 15:34:51 +000023*/
danielk19774adee202004-05-08 08:23:19 +000024Select *sqlite3SelectNew(
drhdaffd0e2001-04-11 14:28:42 +000025 ExprList *pEList, /* which columns to include in the result */
drhad3cab52002-05-24 02:04:32 +000026 SrcList *pSrc, /* the FROM clause -- which tables to scan */
drhdaffd0e2001-04-11 14:28:42 +000027 Expr *pWhere, /* the WHERE clause */
28 ExprList *pGroupBy, /* the GROUP BY clause */
29 Expr *pHaving, /* the HAVING clause */
30 ExprList *pOrderBy, /* the ORDER BY clause */
drh9bbca4c2001-11-06 04:00:18 +000031 int isDistinct, /* true if the DISTINCT keyword is present */
32 int nLimit, /* LIMIT value. -1 means not used */
drhef0cae52003-07-16 02:19:37 +000033 int nOffset /* OFFSET value. 0 means no offset */
drh9bb61fe2000-06-05 16:01:39 +000034){
35 Select *pNew;
36 pNew = sqliteMalloc( sizeof(*pNew) );
drhdaffd0e2001-04-11 14:28:42 +000037 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +000038 sqlite3ExprListDelete(pEList);
39 sqlite3SrcListDelete(pSrc);
40 sqlite3ExprDelete(pWhere);
41 sqlite3ExprListDelete(pGroupBy);
42 sqlite3ExprDelete(pHaving);
43 sqlite3ExprListDelete(pOrderBy);
drhdaffd0e2001-04-11 14:28:42 +000044 }else{
drhb733d032004-01-24 20:18:12 +000045 if( pEList==0 ){
danielk19774adee202004-05-08 08:23:19 +000046 pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
drhb733d032004-01-24 20:18:12 +000047 }
drhdaffd0e2001-04-11 14:28:42 +000048 pNew->pEList = pEList;
49 pNew->pSrc = pSrc;
50 pNew->pWhere = pWhere;
51 pNew->pGroupBy = pGroupBy;
52 pNew->pHaving = pHaving;
53 pNew->pOrderBy = pOrderBy;
54 pNew->isDistinct = isDistinct;
55 pNew->op = TK_SELECT;
drh9bbca4c2001-11-06 04:00:18 +000056 pNew->nLimit = nLimit;
57 pNew->nOffset = nOffset;
drh7b58dae2003-07-20 01:16:46 +000058 pNew->iLimit = -1;
59 pNew->iOffset = -1;
drhdaffd0e2001-04-11 14:28:42 +000060 }
drh9bb61fe2000-06-05 16:01:39 +000061 return pNew;
62}
63
64/*
drh01f3f252002-05-24 16:14:15 +000065** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
66** type of join. Return an integer constant that expresses that type
67** in terms of the following bit values:
68**
69** JT_INNER
70** JT_OUTER
71** JT_NATURAL
72** JT_LEFT
73** JT_RIGHT
74**
75** A full outer join is the combination of JT_LEFT and JT_RIGHT.
76**
77** If an illegal or unsupported join type is seen, then still return
78** a join type, but put an error in the pParse structure.
79*/
danielk19774adee202004-05-08 08:23:19 +000080int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
drh01f3f252002-05-24 16:14:15 +000081 int jointype = 0;
82 Token *apAll[3];
83 Token *p;
84 static struct {
85 const char *zKeyword;
86 int nChar;
87 int code;
88 } keywords[] = {
89 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000090 { "left", 4, JT_LEFT|JT_OUTER },
91 { "right", 5, JT_RIGHT|JT_OUTER },
92 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +000093 { "outer", 5, JT_OUTER },
94 { "inner", 5, JT_INNER },
95 { "cross", 5, JT_INNER },
96 };
97 int i, j;
98 apAll[0] = pA;
99 apAll[1] = pB;
100 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +0000101 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +0000102 p = apAll[i];
103 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
104 if( p->n==keywords[j].nChar
danielk19774adee202004-05-08 08:23:19 +0000105 && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
drh01f3f252002-05-24 16:14:15 +0000106 jointype |= keywords[j].code;
107 break;
108 }
109 }
110 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
111 jointype |= JT_ERROR;
112 break;
113 }
114 }
drhad2d8302002-05-24 20:31:36 +0000115 if(
116 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000117 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000118 ){
drh01f3f252002-05-24 16:14:15 +0000119 static Token dummy = { 0, 0 };
120 char *zSp1 = " ", *zSp2 = " ";
121 if( pB==0 ){ pB = &dummy; zSp1 = 0; }
122 if( pC==0 ){ pC = &dummy; zSp2 = 0; }
danielk19774adee202004-05-08 08:23:19 +0000123 sqlite3SetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
drh01f3f252002-05-24 16:14:15 +0000124 pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
125 pParse->nErr++;
126 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000127 }else if( jointype & JT_RIGHT ){
danielk19774adee202004-05-08 08:23:19 +0000128 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000129 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000130 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000131 }
132 return jointype;
133}
134
135/*
drhad2d8302002-05-24 20:31:36 +0000136** Return the index of a column in a table. Return -1 if the column
137** is not contained in the table.
138*/
139static int columnIndex(Table *pTab, const char *zCol){
140 int i;
141 for(i=0; i<pTab->nCol; i++){
danielk19774adee202004-05-08 08:23:19 +0000142 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
drhad2d8302002-05-24 20:31:36 +0000143 }
144 return -1;
145}
146
147/*
148** Add a term to the WHERE expression in *ppExpr that requires the
149** zCol column to be equal in the two tables pTab1 and pTab2.
150*/
151static void addWhereTerm(
152 const char *zCol, /* Name of the column */
153 const Table *pTab1, /* First table */
154 const Table *pTab2, /* Second table */
155 Expr **ppExpr /* Add the equality term to this expression */
156){
157 Token dummy;
158 Expr *pE1a, *pE1b, *pE1c;
159 Expr *pE2a, *pE2b, *pE2c;
160 Expr *pE;
161
162 dummy.z = zCol;
163 dummy.n = strlen(zCol);
drh4b59ab52002-08-24 18:24:51 +0000164 dummy.dyn = 0;
danielk19774adee202004-05-08 08:23:19 +0000165 pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy);
166 pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy);
drhad2d8302002-05-24 20:31:36 +0000167 dummy.z = pTab1->zName;
168 dummy.n = strlen(dummy.z);
danielk19774adee202004-05-08 08:23:19 +0000169 pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy);
drhad2d8302002-05-24 20:31:36 +0000170 dummy.z = pTab2->zName;
171 dummy.n = strlen(dummy.z);
danielk19774adee202004-05-08 08:23:19 +0000172 pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy);
173 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
174 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
175 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000176 ExprSetProperty(pE, EP_FromJoin);
drhad2d8302002-05-24 20:31:36 +0000177 if( *ppExpr ){
danielk19774adee202004-05-08 08:23:19 +0000178 *ppExpr = sqlite3Expr(TK_AND, *ppExpr, pE, 0);
drhad2d8302002-05-24 20:31:36 +0000179 }else{
180 *ppExpr = pE;
181 }
182}
183
184/*
drh1f162302002-10-27 19:35:33 +0000185** Set the EP_FromJoin property on all terms of the given expression.
drh1cc093c2002-06-24 22:01:57 +0000186**
drhe78e8282003-01-19 03:59:45 +0000187** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000188** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000189** join restriction specified in the ON or USING clause and not a part
190** of the more general WHERE clause. These terms are moved over to the
191** WHERE clause during join processing but we need to remember that they
192** originated in the ON or USING clause.
drh1cc093c2002-06-24 22:01:57 +0000193*/
194static void setJoinExpr(Expr *p){
195 while( p ){
drh1f162302002-10-27 19:35:33 +0000196 ExprSetProperty(p, EP_FromJoin);
drh1cc093c2002-06-24 22:01:57 +0000197 setJoinExpr(p->pLeft);
198 p = p->pRight;
199 }
200}
201
202/*
drhad2d8302002-05-24 20:31:36 +0000203** This routine processes the join information for a SELECT statement.
204** ON and USING clauses are converted into extra terms of the WHERE clause.
205** NATURAL joins also create extra WHERE clause terms.
206**
207** This routine returns the number of errors encountered.
208*/
209static int sqliteProcessJoin(Parse *pParse, Select *p){
210 SrcList *pSrc;
211 int i, j;
212 pSrc = p->pSrc;
213 for(i=0; i<pSrc->nSrc-1; i++){
214 struct SrcList_item *pTerm = &pSrc->a[i];
215 struct SrcList_item *pOther = &pSrc->a[i+1];
216
217 if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
218
219 /* When the NATURAL keyword is present, add WHERE clause terms for
220 ** every column that the two tables have in common.
221 */
222 if( pTerm->jointype & JT_NATURAL ){
223 Table *pTab;
224 if( pTerm->pOn || pTerm->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000225 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000226 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000227 return 1;
228 }
229 pTab = pTerm->pTab;
230 for(j=0; j<pTab->nCol; j++){
231 if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
232 addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
233 }
234 }
235 }
236
237 /* Disallow both ON and USING clauses in the same join
238 */
239 if( pTerm->pOn && pTerm->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000240 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
drhda93d232003-03-31 02:12:46 +0000241 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000242 return 1;
243 }
244
245 /* Add the ON clause to the end of the WHERE clause, connected by
246 ** and AND operator.
247 */
248 if( pTerm->pOn ){
drh1cc093c2002-06-24 22:01:57 +0000249 setJoinExpr(pTerm->pOn);
drhad2d8302002-05-24 20:31:36 +0000250 if( p->pWhere==0 ){
251 p->pWhere = pTerm->pOn;
252 }else{
danielk19774adee202004-05-08 08:23:19 +0000253 p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pTerm->pOn, 0);
drhad2d8302002-05-24 20:31:36 +0000254 }
255 pTerm->pOn = 0;
256 }
257
258 /* Create extra terms on the WHERE clause for each column named
259 ** in the USING clause. Example: If the two tables to be joined are
260 ** A and B and the USING clause names X, Y, and Z, then add this
261 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
262 ** Report an error if any column mentioned in the USING clause is
263 ** not contained in both tables to be joined.
264 */
265 if( pTerm->pUsing ){
266 IdList *pList;
267 int j;
268 assert( i<pSrc->nSrc-1 );
269 pList = pTerm->pUsing;
270 for(j=0; j<pList->nId; j++){
drhbf5cd972002-06-24 12:20:23 +0000271 if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
272 columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
danielk19774adee202004-05-08 08:23:19 +0000273 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
drhda93d232003-03-31 02:12:46 +0000274 "not present in both tables", pList->a[j].zName);
drhad2d8302002-05-24 20:31:36 +0000275 return 1;
276 }
drhbf5cd972002-06-24 12:20:23 +0000277 addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000278 }
279 }
280 }
281 return 0;
282}
283
284/*
drh9bb61fe2000-06-05 16:01:39 +0000285** Delete the given Select structure and all of its substructures.
286*/
danielk19774adee202004-05-08 08:23:19 +0000287void sqlite3SelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000288 if( p==0 ) return;
danielk19774adee202004-05-08 08:23:19 +0000289 sqlite3ExprListDelete(p->pEList);
290 sqlite3SrcListDelete(p->pSrc);
291 sqlite3ExprDelete(p->pWhere);
292 sqlite3ExprListDelete(p->pGroupBy);
293 sqlite3ExprDelete(p->pHaving);
294 sqlite3ExprListDelete(p->pOrderBy);
295 sqlite3SelectDelete(p->pPrior);
drha76b5df2002-02-23 02:32:10 +0000296 sqliteFree(p->zSelect);
drh9bb61fe2000-06-05 16:01:39 +0000297 sqliteFree(p);
298}
299
300/*
drh22827922000-06-06 17:27:05 +0000301** Delete the aggregate information from the parse structure.
302*/
drh1d83f052002-02-17 00:30:36 +0000303static void sqliteAggregateInfoReset(Parse *pParse){
drh22827922000-06-06 17:27:05 +0000304 sqliteFree(pParse->aAgg);
305 pParse->aAgg = 0;
306 pParse->nAgg = 0;
drh22827922000-06-06 17:27:05 +0000307 pParse->useAgg = 0;
308}
309
310/*
drhc926afb2002-06-20 03:38:26 +0000311** Insert code into "v" that will push the record on the top of the
312** stack into the sorter.
313*/
314static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
drhc926afb2002-06-20 03:38:26 +0000315 int i;
drhc926afb2002-06-20 03:38:26 +0000316 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000317 sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
drhc926afb2002-06-20 03:38:26 +0000318 }
danielk1977ededfd52004-06-17 07:53:01 +0000319 sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +0000320 sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000321}
322
323/*
drhea48eb22004-07-19 23:16:38 +0000324** Add code to implement the OFFSET and LIMIT
325*/
326static void codeLimiter(
drhbab39e12004-07-19 23:38:11 +0000327 Vdbe *v, /* Generate code into this VM */
drhea48eb22004-07-19 23:16:38 +0000328 Select *p, /* The SELECT statement being coded */
329 int iContinue, /* Jump here to skip the current record */
330 int iBreak, /* Jump here to end the loop */
331 int nPop /* Number of times to pop stack when jumping */
332){
drhea48eb22004-07-19 23:16:38 +0000333 if( p->iOffset>=0 ){
334 int addr = sqlite3VdbeCurrentAddr(v) + 2;
335 if( nPop>0 ) addr++;
336 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr);
337 if( nPop>0 ){
338 sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
339 }
340 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
341 }
342 if( p->iLimit>=0 ){
343 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
344 }
345}
346
347/*
drh22827922000-06-06 17:27:05 +0000348** This routine generates the code for the inside of the inner loop
349** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000350**
drh38640e12002-07-05 21:42:36 +0000351** If srcTab and nColumn are both zero, then the pEList expressions
352** are evaluated in order to get the data for this row. If nColumn>0
353** then data is pulled from srcTab and pEList is used only to get the
354** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000355*/
356static int selectInnerLoop(
357 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000358 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000359 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000360 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000361 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000362 ExprList *pOrderBy, /* If not NULL, sort results using this key */
363 int distinct, /* If >=0, make sure results are distinct */
364 int eDest, /* How to dispose of the results */
365 int iParm, /* An argument to the disposal method */
366 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000367 int iBreak, /* Jump here to break out of the inner loop */
368 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000369){
370 Vdbe *v = pParse->pVdbe;
371 int i;
drhea48eb22004-07-19 23:16:38 +0000372 int hasDistinct; /* True if the DISTINCT keyword is present */
drh38640e12002-07-05 21:42:36 +0000373
drhdaffd0e2001-04-11 14:28:42 +0000374 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000375 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000376
drhdf199a22002-06-14 22:38:41 +0000377 /* If there was a LIMIT clause on the SELECT statement, then do the check
378 ** to see if this row should be output.
379 */
drhea48eb22004-07-19 23:16:38 +0000380 hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
381 if( pOrderBy==0 && !hasDistinct ){
drhbab39e12004-07-19 23:38:11 +0000382 codeLimiter(v, p, iContinue, iBreak, 0);
drhdf199a22002-06-14 22:38:41 +0000383 }
384
drh967e8b72000-06-21 13:59:10 +0000385 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000386 */
drh38640e12002-07-05 21:42:36 +0000387 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000388 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000389 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000390 }
drh38640e12002-07-05 21:42:36 +0000391 }else{
392 nColumn = pEList->nExpr;
393 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000394 sqlite3ExprCode(pParse, pEList->a[i].pExpr);
drh38640e12002-07-05 21:42:36 +0000395 }
drh22827922000-06-06 17:27:05 +0000396 }
397
drhdaffd0e2001-04-11 14:28:42 +0000398 /* If the DISTINCT keyword was present on the SELECT statement
399 ** and this row has been seen before, then do not make this row
400 ** part of the result.
drh22827922000-06-06 17:27:05 +0000401 */
drhea48eb22004-07-19 23:16:38 +0000402 if( hasDistinct ){
drh0bd1f4e2002-06-06 18:54:39 +0000403#if NULL_ALWAYS_DISTINCT
danielk19774adee202004-05-08 08:23:19 +0000404 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
drh0bd1f4e2002-06-06 18:54:39 +0000405#endif
danielk1977ededfd52004-06-17 07:53:01 +0000406 /* Deliberately leave the affinity string off of the following
407 ** OP_MakeRecord */
408 sqlite3VdbeAddOp(v, OP_MakeRecord, pEList->nExpr * -1, 0);
danielk19774adee202004-05-08 08:23:19 +0000409 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
410 sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
411 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
danielk19770f69c1e2004-05-29 11:24:50 +0000412 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000413 sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
drhea48eb22004-07-19 23:16:38 +0000414 if( pOrderBy==0 ){
drhbab39e12004-07-19 23:38:11 +0000415 codeLimiter(v, p, iContinue, iBreak, nColumn);
drhea48eb22004-07-19 23:16:38 +0000416 }
drh22827922000-06-06 17:27:05 +0000417 }
drh82c3d632000-06-06 21:56:07 +0000418
drhc926afb2002-06-20 03:38:26 +0000419 switch( eDest ){
420 /* In this mode, write each query result to the key of the temporary
421 ** table iParm.
422 */
423 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000424 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000425 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000426 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000427 sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000428 break;
drh22827922000-06-06 17:27:05 +0000429 }
drh22827922000-06-06 17:27:05 +0000430
drhc926afb2002-06-20 03:38:26 +0000431 /* Store the result as data using a unique key.
432 */
433 case SRT_Table:
434 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000435 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000436 if( pOrderBy ){
437 pushOntoSorter(pParse, v, pOrderBy);
438 }else{
danielk19774adee202004-05-08 08:23:19 +0000439 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
440 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
441 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000442 }
443 break;
444 }
drh82c3d632000-06-06 21:56:07 +0000445
drhc926afb2002-06-20 03:38:26 +0000446 /* Construct a record from the query result, but instead of
447 ** saving that record, use it as a key to delete elements from
448 ** the temporary table iParm.
449 */
450 case SRT_Except: {
451 int addr;
danielk19774adee202004-05-08 08:23:19 +0000452 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000453 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000454 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
455 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000456 break;
457 }
drh5974a302000-06-07 14:42:26 +0000458
drhc926afb2002-06-20 03:38:26 +0000459 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
460 ** then there should be a single item on the stack. Write this
461 ** item into the set table with bogus data.
462 */
463 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000464 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000465 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000466
drhc926afb2002-06-20 03:38:26 +0000467 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000468 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
469 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
470 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000471 if( pOrderBy ){
472 pushOntoSorter(pParse, v, pOrderBy);
473 }else{
danielk1977e014a832004-05-17 10:48:57 +0000474 char const *affStr;
475 char aff = (iParm>>16)&0xFF;
476 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
477 affStr = sqlite3AffinityString(aff);
danielk1977ededfd52004-06-17 07:53:01 +0000478 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, affStr, P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000479 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000480 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000481 }
danielk19774adee202004-05-08 08:23:19 +0000482 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000483 break;
484 }
drh22827922000-06-06 17:27:05 +0000485
drhc926afb2002-06-20 03:38:26 +0000486 /* If this is a scalar select that is part of an expression, then
487 ** store the results in the appropriate memory cell and break out
488 ** of the scan loop.
489 */
490 case SRT_Mem: {
491 assert( nColumn==1 );
492 if( pOrderBy ){
493 pushOntoSorter(pParse, v, pOrderBy);
494 }else{
danielk19774adee202004-05-08 08:23:19 +0000495 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
496 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000497 }
498 break;
499 }
drh22827922000-06-06 17:27:05 +0000500
drhf46f9052002-06-22 02:33:38 +0000501 /* Send the data to the callback function.
502 */
503 case SRT_Callback:
504 case SRT_Sorter: {
505 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000506 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000507 pushOntoSorter(pParse, v, pOrderBy);
508 }else{
509 assert( eDest==SRT_Callback );
danielk19774adee202004-05-08 08:23:19 +0000510 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000511 }
512 break;
513 }
514
drh142e30d2002-08-28 03:00:58 +0000515 /* Invoke a subroutine to handle the results. The subroutine itself
516 ** is responsible for popping the results off of the stack.
517 */
518 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000519 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000520 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000521 pushOntoSorter(pParse, v, pOrderBy);
522 }else{
danielk19774adee202004-05-08 08:23:19 +0000523 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhac82fcf2002-09-08 17:23:41 +0000524 }
drh142e30d2002-08-28 03:00:58 +0000525 break;
526 }
527
drhc926afb2002-06-20 03:38:26 +0000528 /* Discard the results. This is used for SELECT statements inside
529 ** the body of a TRIGGER. The purpose of such selects is to call
530 ** user-defined functions that have side effects. We do not care
531 ** about the actual results of the select.
532 */
drhc926afb2002-06-20 03:38:26 +0000533 default: {
drhf46f9052002-06-22 02:33:38 +0000534 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000535 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000536 break;
537 }
drh82c3d632000-06-06 21:56:07 +0000538 }
539 return 0;
540}
541
542/*
drhd8bc7082000-06-07 23:51:50 +0000543** If the inner loop was generated using a non-null pOrderBy argument,
544** then the results were placed in a sorter. After the loop is terminated
545** we need to run the sorter and output the results. The following
546** routine generates the code needed to do that.
547*/
drhc926afb2002-06-20 03:38:26 +0000548static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000549 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000550 Select *p, /* The SELECT statement */
551 Vdbe *v, /* Generate code into this VDBE */
552 int nColumn, /* Number of columns of data */
553 int eDest, /* Write the sorted results here */
554 int iParm /* Optional parameter associated with eDest */
555){
danielk19774adee202004-05-08 08:23:19 +0000556 int end1 = sqlite3VdbeMakeLabel(v);
557 int end2 = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000558 int addr;
drhffbc3082004-05-21 01:29:06 +0000559 KeyInfo *pInfo;
560 ExprList *pOrderBy;
561 int nCol, i;
562 sqlite *db = pParse->db;
563
drhf46f9052002-06-22 02:33:38 +0000564 if( eDest==SRT_Sorter ) return;
drhffbc3082004-05-21 01:29:06 +0000565 pOrderBy = p->pOrderBy;
566 nCol = pOrderBy->nExpr;
567 pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
568 if( pInfo==0 ) return;
569 pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
570 pInfo->nField = nCol;
571 for(i=0; i<nCol; i++){
danielk19770202b292004-06-09 09:55:16 +0000572 /* If a collation sequence was specified explicity, then it
573 ** is stored in pOrderBy->a[i].zName. Otherwise, use the default
574 ** collation type for the expression.
575 */
danielk19777cedc8d2004-06-10 10:50:08 +0000576 pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr);
danielk19770202b292004-06-09 09:55:16 +0000577 if( !pInfo->aColl[i] ){
578 pInfo->aColl[i] = db->pDfltColl;
579 }
drhffbc3082004-05-21 01:29:06 +0000580 pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
581 }
582 sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
danielk19774adee202004-05-08 08:23:19 +0000583 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
drhbab39e12004-07-19 23:38:11 +0000584 codeLimiter(v, p, addr, end2, 1);
drhc926afb2002-06-20 03:38:26 +0000585 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000586 case SRT_Table:
587 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000588 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
589 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
590 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000591 break;
592 }
593 case SRT_Set: {
594 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000595 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
596 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
597 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
danielk1977ededfd52004-06-17 07:53:01 +0000598 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000599 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000600 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000601 break;
602 }
603 case SRT_Mem: {
604 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000605 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
606 sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
drhc926afb2002-06-20 03:38:26 +0000607 break;
608 }
drhce665cf2004-05-21 03:01:58 +0000609 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000610 case SRT_Subroutine: {
611 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000612 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
613 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000614 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000615 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000616 }
drhce665cf2004-05-21 03:01:58 +0000617 if( eDest==SRT_Callback ){
618 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
619 }else{
620 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
621 }
danielk197784ac9d02004-05-18 09:58:06 +0000622 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000623 break;
624 }
drhc926afb2002-06-20 03:38:26 +0000625 default: {
drhf46f9052002-06-22 02:33:38 +0000626 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000627 break;
628 }
629 }
danielk19774adee202004-05-08 08:23:19 +0000630 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
631 sqlite3VdbeResolveLabel(v, end2);
632 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
633 sqlite3VdbeResolveLabel(v, end1);
634 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000635}
636
637/*
danielk1977517eb642004-06-07 10:00:31 +0000638** Return a pointer to a string containing the 'declaration type' of the
639** expression pExpr. The string may be treated as static by the caller.
drhe78e8282003-01-19 03:59:45 +0000640**
danielk1977517eb642004-06-07 10:00:31 +0000641** If the declaration type is the exact datatype definition extracted from
642** the original CREATE TABLE statement if the expression is a column.
643**
644** The declaration type for an expression is either TEXT, NUMERIC or ANY.
645** The declaration type for a ROWID field is INTEGER.
646*/
647static const char *columnType(Parse *pParse, SrcList *pTabList, Expr *pExpr){
danielk197700e279d2004-06-21 07:36:32 +0000648 char const *zType;
danielk1977517eb642004-06-07 10:00:31 +0000649 int j;
danielk197700e279d2004-06-21 07:36:32 +0000650 if( pExpr==0 || pTabList==0 ) return 0;
651
652 switch( pExpr->op ){
653 case TK_COLUMN: {
654 Table *pTab;
655 int iCol = pExpr->iColumn;
656 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable; j++){}
657 assert( j<pTabList->nSrc );
658 pTab = pTabList->a[j].pTab;
659 if( iCol<0 ) iCol = pTab->iPKey;
660 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
661 if( iCol<0 ){
662 zType = "INTEGER";
663 }else{
664 zType = pTab->aCol[iCol].zType;
665 }
666 break;
danielk1977517eb642004-06-07 10:00:31 +0000667 }
danielk197700e279d2004-06-21 07:36:32 +0000668 case TK_AS:
669 zType = columnType(pParse, pTabList, pExpr->pLeft);
670 break;
671 case TK_SELECT: {
672 Select *pS = pExpr->pSelect;
673 zType = columnType(pParse, pS->pSrc, pS->pEList->a[0].pExpr);
674 break;
danielk1977517eb642004-06-07 10:00:31 +0000675 }
danielk197700e279d2004-06-21 07:36:32 +0000676 default:
677 zType = 0;
danielk1977517eb642004-06-07 10:00:31 +0000678 }
danielk197700e279d2004-06-21 07:36:32 +0000679
danielk1977517eb642004-06-07 10:00:31 +0000680 return zType;
681}
682
683/*
684** Generate code that will tell the VDBE the declaration types of columns
685** in the result set.
drhfcb78a42003-01-18 20:11:05 +0000686*/
687static void generateColumnTypes(
688 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000689 SrcList *pTabList, /* List of tables */
690 ExprList *pEList /* Expressions defining the result set */
691){
692 Vdbe *v = pParse->pVdbe;
danielk1977517eb642004-06-07 10:00:31 +0000693 int i;
drhfcb78a42003-01-18 20:11:05 +0000694 for(i=0; i<pEList->nExpr; i++){
695 Expr *p = pEList->a[i].pExpr;
danielk1977517eb642004-06-07 10:00:31 +0000696 const char *zType = columnType(pParse, pTabList, p);
danielk197700e279d2004-06-21 07:36:32 +0000697 if( zType==0 ) continue;
danielk1977fbcd5852004-06-15 02:44:18 +0000698 /* The vdbe must make it's own copy of the column-type, in case the
699 ** schema is reset before this virtual machine is deleted.
700 */
701 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
drhfcb78a42003-01-18 20:11:05 +0000702 }
703}
704
705/*
706** Generate code that will tell the VDBE the names of columns
707** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000708** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000709*/
drh832508b2002-03-02 17:04:07 +0000710static void generateColumnNames(
711 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000712 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000713 ExprList *pEList /* Expressions defining the result set */
714){
drhd8bc7082000-06-07 23:51:50 +0000715 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000716 int i, j;
drhfcabd462004-02-20 14:50:58 +0000717 sqlite *db = pParse->db;
718 int fullNames, shortNames;
719
danielk19773cf86062004-05-26 10:11:05 +0000720 /* If this is an EXPLAIN, skip this step */
721 if( pParse->explain ){
danielk197761de0d12004-05-27 23:56:16 +0000722 return;
danielk19773cf86062004-05-26 10:11:05 +0000723 }
724
drhd6502752004-02-16 03:44:01 +0000725 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000726 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000727 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000728 fullNames = (db->flags & SQLITE_FullColNames)!=0;
729 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
danielk197722322fd2004-05-25 23:35:17 +0000730 sqlite3VdbeSetNumCols(v, pEList->nExpr);
drh82c3d632000-06-06 21:56:07 +0000731 for(i=0; i<pEList->nExpr; i++){
732 Expr *p;
drh5a387052003-01-11 14:19:51 +0000733 p = pEList->a[i].pExpr;
734 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000735 if( pEList->a[i].zName ){
736 char *zName = pEList->a[i].zName;
danielk1977d8123362004-06-12 09:25:12 +0000737 sqlite3VdbeSetColName(v, i, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000738 continue;
739 }
drhfa173a72002-07-10 21:26:00 +0000740 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000741 Table *pTab;
drh97665872002-02-13 23:22:53 +0000742 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000743 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000744 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
745 assert( j<pTabList->nSrc );
746 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000747 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000748 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000749 if( iCol<0 ){
750 zCol = "_ROWID_";
drhb1363202002-06-26 02:45:03 +0000751 }else{
752 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000753 }
drhfcabd462004-02-20 14:50:58 +0000754 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000755 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
drhfcabd462004-02-20 14:50:58 +0000756 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000757 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000758 char *zTab;
759
drh6a3ea0e2003-05-02 14:32:12 +0000760 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000761 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000762 sqlite3SetString(&zName, zTab, ".", zCol, 0);
danielk19773cf86062004-05-26 10:11:05 +0000763 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000764 }else{
danielk19773cf86062004-05-26 10:11:05 +0000765 sqlite3VdbeSetColName(v, i, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000766 }
drh6977fea2002-10-22 23:38:04 +0000767 }else if( p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000768 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
769 /* sqlite3VdbeCompressSpace(v, addr); */
drh1bee3d72001-10-15 00:44:35 +0000770 }else{
771 char zName[30];
772 assert( p->op!=TK_COLUMN || pTabList==0 );
773 sprintf(zName, "column%d", i+1);
danielk19773cf86062004-05-26 10:11:05 +0000774 sqlite3VdbeSetColName(v, i, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000775 }
776 }
danielk197776d505b2004-05-28 13:13:02 +0000777 generateColumnTypes(pParse, pTabList, pEList);
drh82c3d632000-06-06 21:56:07 +0000778}
779
780/*
drhd8bc7082000-06-07 23:51:50 +0000781** Name of the connection operator, used for error messages.
782*/
783static const char *selectOpName(int id){
784 char *z;
785 switch( id ){
786 case TK_ALL: z = "UNION ALL"; break;
787 case TK_INTERSECT: z = "INTERSECT"; break;
788 case TK_EXCEPT: z = "EXCEPT"; break;
789 default: z = "UNION"; break;
790 }
791 return z;
792}
793
794/*
drh315555c2002-10-20 15:53:03 +0000795** Forward declaration
796*/
797static int fillInColumnList(Parse*, Select*);
798
799/*
drh22f70c32002-02-18 01:17:00 +0000800** Given a SELECT statement, generate a Table structure that describes
801** the result set of that SELECT.
802*/
danielk19774adee202004-05-08 08:23:19 +0000803Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000804 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000805 int i, j;
drh22f70c32002-02-18 01:17:00 +0000806 ExprList *pEList;
drhb733d032004-01-24 20:18:12 +0000807 Column *aCol;
drh22f70c32002-02-18 01:17:00 +0000808
809 if( fillInColumnList(pParse, pSelect) ){
810 return 0;
811 }
812 pTab = sqliteMalloc( sizeof(Table) );
813 if( pTab==0 ){
814 return 0;
815 }
816 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
817 pEList = pSelect->pEList;
818 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000819 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000820 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh22f70c32002-02-18 01:17:00 +0000821 for(i=0; i<pTab->nCol; i++){
danielk1977517eb642004-06-07 10:00:31 +0000822 Expr *pR;
823 char *zType;
824 Expr *p = pEList->a[i].pExpr;
drh22f70c32002-02-18 01:17:00 +0000825 if( pEList->a[i].zName ){
drhb733d032004-01-24 20:18:12 +0000826 aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
danielk1977517eb642004-06-07 10:00:31 +0000827 }else if( p->op==TK_DOT
drhb733d032004-01-24 20:18:12 +0000828 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
829 int cnt;
danielk19774adee202004-05-08 08:23:19 +0000830 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
drhb733d032004-01-24 20:18:12 +0000831 for(j=cnt=0; j<i; j++){
danielk19774adee202004-05-08 08:23:19 +0000832 if( sqlite3StrICmp(aCol[j].zName, aCol[i].zName)==0 ){
drhb733d032004-01-24 20:18:12 +0000833 int n;
834 char zBuf[30];
835 sprintf(zBuf,"_%d",++cnt);
836 n = strlen(zBuf);
danielk1977e014a832004-05-17 10:48:57 +0000837 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf,n,0);
drhb733d032004-01-24 20:18:12 +0000838 j = -1;
839 }
840 }
841 }else if( p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000842 sqlite3SetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drh22f70c32002-02-18 01:17:00 +0000843 }else{
844 char zBuf[30];
845 sprintf(zBuf, "column%d", i+1);
846 pTab->aCol[i].zName = sqliteStrDup(zBuf);
847 }
drh2c61c072004-07-20 00:20:23 +0000848 sqlite3Dequote(aCol[i].zName);
danielk1977517eb642004-06-07 10:00:31 +0000849
850 zType = sqliteStrDup(columnType(pParse, pSelect->pSrc ,p));
851 pTab->aCol[i].zType = zType;
852 pTab->aCol[i].affinity = SQLITE_AFF_NUMERIC;
853 if( zType ){
854 pTab->aCol[i].affinity = sqlite3AffinityType(zType, strlen(zType));
855 }
danielk19777cedc8d2004-06-10 10:50:08 +0000856 pTab->aCol[i].pColl = sqlite3ExprCollSeq(pParse, p);
danielk19770202b292004-06-09 09:55:16 +0000857 if( !pTab->aCol[i].pColl ){
858 pTab->aCol[i].pColl = pParse->db->pDfltColl;
859 }
drh22f70c32002-02-18 01:17:00 +0000860 }
861 pTab->iPKey = -1;
862 return pTab;
863}
864
865/*
drhad2d8302002-05-24 20:31:36 +0000866** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000867**
drhad3cab52002-05-24 02:04:32 +0000868** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh63eb5f22003-04-29 16:20:44 +0000869** defines the set of tables that should be scanned. For views,
870** fill pTabList->a[].pSelect with a copy of the SELECT statement
871** that implements the view. A copy is made of the view's SELECT
872** statement so that we can freely modify or delete that statement
873** without worrying about messing up the presistent representation
874** of the view.
drhd8bc7082000-06-07 23:51:50 +0000875**
drhad2d8302002-05-24 20:31:36 +0000876** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
877** on joins and the ON and USING clause of joins.
878**
879** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000880** for instances of the "*" operator or the TABLE.* operator.
881** If found, expand each "*" to be every column in every table
882** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000883**
884** Return 0 on success. If there are problems, leave an error message
885** in pParse and return non-zero.
886*/
887static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000888 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000889 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000890 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000891 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000892
893 if( p==0 || p->pSrc==0 ) return 1;
894 pTabList = p->pSrc;
895 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000896
897 /* Look up every table in the table list.
898 */
drhad3cab52002-05-24 02:04:32 +0000899 for(i=0; i<pTabList->nSrc; i++){
drhd8bc7082000-06-07 23:51:50 +0000900 if( pTabList->a[i].pTab ){
901 /* This routine has run before! No need to continue */
902 return 0;
903 }
drhdaffd0e2001-04-11 14:28:42 +0000904 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000905 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000906 assert( pTabList->a[i].pSelect!=0 );
drhad2d8302002-05-24 20:31:36 +0000907 if( pTabList->a[i].zAlias==0 ){
908 char zFakeName[60];
909 sprintf(zFakeName, "sqlite_subquery_%p_",
910 (void*)pTabList->a[i].pSelect);
danielk19774adee202004-05-08 08:23:19 +0000911 sqlite3SetString(&pTabList->a[i].zAlias, zFakeName, 0);
drhad2d8302002-05-24 20:31:36 +0000912 }
drh22f70c32002-02-18 01:17:00 +0000913 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000914 sqlite3ResultSetOfSelect(pParse, pTabList->a[i].zAlias,
drh22f70c32002-02-18 01:17:00 +0000915 pTabList->a[i].pSelect);
916 if( pTab==0 ){
917 return 1;
918 }
drh5cf590c2003-04-24 01:45:04 +0000919 /* The isTransient flag indicates that the Table structure has been
920 ** dynamically allocated and may be freed at any time. In other words,
921 ** pTab is not pointing to a persistent table structure that defines
922 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000923 pTab->isTransient = 1;
924 }else{
drha76b5df2002-02-23 02:32:10 +0000925 /* An ordinary table or view name in the FROM clause */
926 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000927 sqlite3LocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
drha76b5df2002-02-23 02:32:10 +0000928 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000929 return 1;
930 }
drha76b5df2002-02-23 02:32:10 +0000931 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +0000932 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +0000933 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +0000934 return 1;
935 }
drh63eb5f22003-04-29 16:20:44 +0000936 /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
937 ** view within a view. The SELECT structure has already been
938 ** copied by the outer view so we can skip the copy step here
939 ** in the inner view.
940 */
941 if( pTabList->a[i].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +0000942 pTabList->a[i].pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +0000943 }
drha76b5df2002-02-23 02:32:10 +0000944 }
drhd8bc7082000-06-07 23:51:50 +0000945 }
946 }
947
drhad2d8302002-05-24 20:31:36 +0000948 /* Process NATURAL keywords, and ON and USING clauses of joins.
949 */
950 if( sqliteProcessJoin(pParse, p) ) return 1;
951
drh7c917d12001-12-16 20:05:05 +0000952 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000953 ** all columns in all tables. And for every TABLE.* insert the names
954 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000955 ** with the TK_ALL operator for each "*" that it found in the column list.
956 ** The following code just has to locate the TK_ALL expressions and expand
957 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000958 **
959 ** The first loop just checks to see if there are any "*" operators
960 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000961 */
drh7c917d12001-12-16 20:05:05 +0000962 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000963 Expr *pE = pEList->a[k].pExpr;
964 if( pE->op==TK_ALL ) break;
965 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
966 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000967 }
drh54473222002-04-04 02:10:55 +0000968 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000969 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000970 /*
971 ** If we get here it means the result set contains one or more "*"
972 ** operators that need to be expanded. Loop through each expression
973 ** in the result set and expand them one by one.
974 */
drh7c917d12001-12-16 20:05:05 +0000975 struct ExprList_item *a = pEList->a;
976 ExprList *pNew = 0;
977 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000978 Expr *pE = a[k].pExpr;
979 if( pE->op!=TK_ALL &&
980 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
981 /* This particular expression does not need to be expanded.
982 */
danielk19774adee202004-05-08 08:23:19 +0000983 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +0000984 pNew->a[pNew->nExpr-1].zName = a[k].zName;
985 a[k].pExpr = 0;
986 a[k].zName = 0;
987 }else{
drh54473222002-04-04 02:10:55 +0000988 /* This expression is a "*" or a "TABLE.*" and needs to be
989 ** expanded. */
990 int tableSeen = 0; /* Set to 1 when TABLE matches */
991 Token *pName; /* text of name of TABLE */
992 if( pE->op==TK_DOT && pE->pLeft ){
993 pName = &pE->pLeft->token;
994 }else{
995 pName = 0;
996 }
drhad3cab52002-05-24 02:04:32 +0000997 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000998 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000999 char *zTabName = pTabList->a[i].zAlias;
1000 if( zTabName==0 || zTabName[0]==0 ){
1001 zTabName = pTab->zName;
1002 }
drhc754fa52002-05-27 03:25:51 +00001003 if( pName && (zTabName==0 || zTabName[0]==0 ||
danielk19774adee202004-05-08 08:23:19 +00001004 sqlite3StrNICmp(pName->z, zTabName, pName->n)!=0 ||
drhc754fa52002-05-27 03:25:51 +00001005 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +00001006 continue;
1007 }
1008 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001009 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001010 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001011 char *zName = pTab->aCol[j].zName;
1012
1013 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
1014 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
1015 /* In a NATURAL join, omit the join columns from the
1016 ** table on the right */
1017 continue;
1018 }
danielk19774adee202004-05-08 08:23:19 +00001019 if( i>0 && sqlite3IdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
drhad2d8302002-05-24 20:31:36 +00001020 /* In a join with a USING clause, omit columns in the
1021 ** using clause from the table on the right. */
1022 continue;
1023 }
danielk19774adee202004-05-08 08:23:19 +00001024 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001025 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +00001026 pRight->token.z = zName;
1027 pRight->token.n = strlen(zName);
drh4b59ab52002-08-24 18:24:51 +00001028 pRight->token.dyn = 0;
drh4b59ab52002-08-24 18:24:51 +00001029 if( zTabName && pTabList->nSrc>1 ){
danielk19774adee202004-05-08 08:23:19 +00001030 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1031 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001032 if( pExpr==0 ) break;
drh4b59ab52002-08-24 18:24:51 +00001033 pLeft->token.z = zTabName;
1034 pLeft->token.n = strlen(zTabName);
1035 pLeft->token.dyn = 0;
danielk19774adee202004-05-08 08:23:19 +00001036 sqlite3SetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
drh6977fea2002-10-22 23:38:04 +00001037 pExpr->span.n = strlen(pExpr->span.z);
1038 pExpr->span.dyn = 1;
1039 pExpr->token.z = 0;
1040 pExpr->token.n = 0;
1041 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001042 }else{
drh22f70c32002-02-18 01:17:00 +00001043 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001044 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001045 }
danielk19774adee202004-05-08 08:23:19 +00001046 pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001047 }
drh17e24df2001-11-06 14:10:41 +00001048 }
drh54473222002-04-04 02:10:55 +00001049 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +00001050 if( pName ){
danielk19774adee202004-05-08 08:23:19 +00001051 sqlite3ErrorMsg(pParse, "no such table: %T", pName);
drhf5db2d32002-06-06 23:42:27 +00001052 }else{
danielk19774adee202004-05-08 08:23:19 +00001053 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001054 }
drh54473222002-04-04 02:10:55 +00001055 rc = 1;
1056 }
drhd8bc7082000-06-07 23:51:50 +00001057 }
1058 }
danielk19774adee202004-05-08 08:23:19 +00001059 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001060 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001061 }
drh54473222002-04-04 02:10:55 +00001062 return rc;
drhd8bc7082000-06-07 23:51:50 +00001063}
1064
1065/*
drhff78bd22002-02-27 01:47:11 +00001066** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1067** in a select structure. It just sets the pointers to NULL. This
1068** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1069** pointer is not NULL, this routine is called recursively on that pointer.
1070**
1071** This routine is called on the Select structure that defines a
1072** VIEW in order to undo any bindings to tables. This is necessary
1073** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001074** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1075** will be left pointing to a deallocated Table structure after the
1076** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001077*/
danielk19774adee202004-05-08 08:23:19 +00001078void sqlite3SelectUnbind(Select *p){
drhff78bd22002-02-27 01:47:11 +00001079 int i;
drhad3cab52002-05-24 02:04:32 +00001080 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +00001081 Table *pTab;
1082 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +00001083 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +00001084 if( (pTab = pSrc->a[i].pTab)!=0 ){
1085 if( pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001086 sqlite3DeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001087 }
1088 pSrc->a[i].pTab = 0;
1089 if( pSrc->a[i].pSelect ){
danielk19774adee202004-05-08 08:23:19 +00001090 sqlite3SelectUnbind(pSrc->a[i].pSelect);
drhff78bd22002-02-27 01:47:11 +00001091 }
1092 }
1093 }
1094}
1095
1096/*
drhd8bc7082000-06-07 23:51:50 +00001097** This routine associates entries in an ORDER BY expression list with
1098** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001099** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001100** the top-level node is filled in with column number and the iTable
1101** value of the top-level node is filled with iTable parameter.
1102**
1103** If there are prior SELECT clauses, they are processed first. A match
1104** in an earlier SELECT takes precedence over a later SELECT.
1105**
1106** Any entry that does not match is flagged as an error. The number
1107** of errors is returned.
1108*/
1109static int matchOrderbyToColumn(
1110 Parse *pParse, /* A place to leave error messages */
1111 Select *pSelect, /* Match to result columns of this SELECT */
1112 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001113 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001114 int mustComplete /* If TRUE all ORDER BYs must match */
1115){
1116 int nErr = 0;
1117 int i, j;
1118 ExprList *pEList;
1119
drhdaffd0e2001-04-11 14:28:42 +00001120 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001121 if( mustComplete ){
1122 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1123 }
1124 if( fillInColumnList(pParse, pSelect) ){
1125 return 1;
1126 }
1127 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001128 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1129 return 1;
1130 }
drhd8bc7082000-06-07 23:51:50 +00001131 }
1132 pEList = pSelect->pEList;
1133 for(i=0; i<pOrderBy->nExpr; i++){
1134 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001135 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001136 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001137 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001138 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001139 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001140 "ORDER BY position %d should be between 1 and %d",
1141 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001142 nErr++;
1143 break;
1144 }
drhfcb78a42003-01-18 20:11:05 +00001145 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001146 iCol--;
1147 }
1148 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001149 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001150 char *zName, *zLabel;
1151 zName = pEList->a[j].zName;
drha99db3b2004-06-19 14:49:12 +00001152 zLabel = sqlite3NameFromToken(&pE->token);
1153 assert( zLabel!=0 );
danielk19774adee202004-05-08 08:23:19 +00001154 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001155 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001156 }
drh6e142f52000-06-08 13:36:40 +00001157 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001158 }
danielk19774adee202004-05-08 08:23:19 +00001159 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001160 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001161 }
1162 }
drhe4de1fe2002-06-02 16:09:01 +00001163 if( iCol>=0 ){
1164 pE->op = TK_COLUMN;
1165 pE->iColumn = iCol;
1166 pE->iTable = iTable;
1167 pOrderBy->a[i].done = 1;
1168 }
1169 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001170 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001171 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001172 nErr++;
1173 break;
1174 }
1175 }
1176 return nErr;
1177}
1178
1179/*
1180** Get a VDBE for the given parser context. Create a new one if necessary.
1181** If an error occurs, return NULL and leave a message in pParse.
1182*/
danielk19774adee202004-05-08 08:23:19 +00001183Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001184 Vdbe *v = pParse->pVdbe;
1185 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001186 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001187 }
drhd8bc7082000-06-07 23:51:50 +00001188 return v;
1189}
drhfcb78a42003-01-18 20:11:05 +00001190
drhd3d39e92004-05-20 22:16:29 +00001191#if 0 /***** This routine needs deleting *****/
danielk197784ac9d02004-05-18 09:58:06 +00001192static void multiSelectAffinity(Select *p, char *zAff){
1193 int i;
1194
1195 if( !p ) return;
1196 multiSelectAffinity(p->pPrior, zAff);
1197
1198 for(i=0; i<p->pEList->nExpr; i++){
1199 if( zAff[i]=='\0' ){
1200 zAff[i] = sqlite3ExprAffinity(p->pEList->a[i].pExpr);
1201 }
1202 }
1203}
drhd3d39e92004-05-20 22:16:29 +00001204#endif
danielk197784ac9d02004-05-18 09:58:06 +00001205
drhd8bc7082000-06-07 23:51:50 +00001206/*
drh7b58dae2003-07-20 01:16:46 +00001207** Compute the iLimit and iOffset fields of the SELECT based on the
1208** nLimit and nOffset fields. nLimit and nOffset hold the integers
1209** that appear in the original SQL statement after the LIMIT and OFFSET
1210** keywords. Or that hold -1 and 0 if those keywords are omitted.
1211** iLimit and iOffset are the integer memory register numbers for
1212** counters used to compute the limit and offset. If there is no
1213** limit and/or offset, then iLimit and iOffset are negative.
1214**
1215** This routine changes the values if iLimit and iOffset only if
1216** a limit or offset is defined by nLimit and nOffset. iLimit and
1217** iOffset should have been preset to appropriate default values
1218** (usually but not always -1) prior to calling this routine.
1219** Only if nLimit>=0 or nOffset>0 do the limit registers get
1220** redefined. The UNION ALL operator uses this property to force
1221** the reuse of the same limit and offset registers across multiple
1222** SELECT statements.
1223*/
1224static void computeLimitRegisters(Parse *pParse, Select *p){
1225 /*
1226 ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
1227 ** all rows. It is the same as no limit. If the comparision is
1228 ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
1229 ** "LIMIT -1" always shows all rows. There is some
1230 ** contraversy about what the correct behavior should be.
1231 ** The current implementation interprets "LIMIT 0" to mean
1232 ** no rows.
1233 */
1234 if( p->nLimit>=0 ){
1235 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001236 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001237 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001238 sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1239 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001240 p->iLimit = iMem;
1241 }
1242 if( p->nOffset>0 ){
1243 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001244 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001245 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001246 sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1247 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001248 p->iOffset = iMem;
1249 }
1250}
1251
1252/*
drhd3d39e92004-05-20 22:16:29 +00001253** Generate VDBE instructions that will open a transient table that
1254** will be used for an index or to store keyed results for a compound
1255** select. In other words, open a transient table that needs a
1256** KeyInfo structure. The number of columns in the KeyInfo is determined
1257** by the result set of the SELECT statement in the second argument.
1258**
danielk1977dc1bdc42004-06-11 10:51:27 +00001259** Specifically, this routine is called to open an index table for
1260** DISTINCT, UNION, INTERSECT and EXCEPT select statements (but not
1261** UNION ALL).
1262**
drhd3d39e92004-05-20 22:16:29 +00001263** Make the new table a KeyAsData table if keyAsData is true.
danielk1977dc1bdc42004-06-11 10:51:27 +00001264**
1265** The value returned is the address of the OP_OpenTemp instruction.
drhd3d39e92004-05-20 22:16:29 +00001266*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001267static int openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
drhd3d39e92004-05-20 22:16:29 +00001268 KeyInfo *pKeyInfo;
drh736c22b2004-05-21 02:14:24 +00001269 int nColumn;
drhd3d39e92004-05-20 22:16:29 +00001270 sqlite *db = pParse->db;
1271 int i;
1272 Vdbe *v = pParse->pVdbe;
danielk1977dc1bdc42004-06-11 10:51:27 +00001273 int addr;
drhd3d39e92004-05-20 22:16:29 +00001274
drh736c22b2004-05-21 02:14:24 +00001275 if( fillInColumnList(pParse, p) ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001276 return 0;
drh736c22b2004-05-21 02:14:24 +00001277 }
1278 nColumn = p->pEList->nExpr;
drhd3d39e92004-05-20 22:16:29 +00001279 pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
danielk1977dc1bdc42004-06-11 10:51:27 +00001280 if( pKeyInfo==0 ) return 0;
1281 pKeyInfo->enc = pParse->db->enc;
drhd3d39e92004-05-20 22:16:29 +00001282 pKeyInfo->nField = nColumn;
1283 for(i=0; i<nColumn; i++){
danielk1977dc1bdc42004-06-11 10:51:27 +00001284 pKeyInfo->aColl[i] = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
1285 if( !pKeyInfo->aColl[i] ){
1286 pKeyInfo->aColl[i] = db->pDfltColl;
1287 }
drhd3d39e92004-05-20 22:16:29 +00001288 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001289 addr = sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0,
1290 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drhd3d39e92004-05-20 22:16:29 +00001291 if( keyAsData ){
1292 sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1293 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001294 return addr;
1295}
1296
1297static int multiSelectOpenTempAddr(Select *p, int addr, IdList **ppOpenTemp){
1298 if( !p->ppOpenTemp ){
1299 *ppOpenTemp = sqlite3IdListAppend(0, 0);
1300 p->ppOpenTemp = ppOpenTemp;
1301 }else{
1302 *p->ppOpenTemp = sqlite3IdListAppend(*p->ppOpenTemp, 0);
1303 }
1304 if( !(*p->ppOpenTemp) ){
1305 return SQLITE_NOMEM;
1306 }
1307 (*p->ppOpenTemp)->a[(*p->ppOpenTemp)->nId-1].idx = addr;
1308 return SQLITE_OK;
1309}
1310
1311static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1312 CollSeq *pRet = 0;
1313 if( p->pPrior ){
1314 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1315 }
1316 if( !pRet ){
1317 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1318 }
1319 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001320}
1321
1322/*
drh82c3d632000-06-06 21:56:07 +00001323** This routine is called to process a query that is really the union
1324** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001325**
drhe78e8282003-01-19 03:59:45 +00001326** "p" points to the right-most of the two queries. the query on the
1327** left is p->pPrior. The left query could also be a compound query
1328** in which case this routine will be called recursively.
1329**
1330** The results of the total query are to be written into a destination
1331** of type eDest with parameter iParm.
1332**
1333** Example 1: Consider a three-way compound SQL statement.
1334**
1335** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1336**
1337** This statement is parsed up as follows:
1338**
1339** SELECT c FROM t3
1340** |
1341** `-----> SELECT b FROM t2
1342** |
jplyon4b11c6d2004-01-19 04:57:53 +00001343** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001344**
1345** The arrows in the diagram above represent the Select.pPrior pointer.
1346** So if this routine is called with p equal to the t3 query, then
1347** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1348**
1349** Notice that because of the way SQLite parses compound SELECTs, the
1350** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001351*/
danielk197784ac9d02004-05-18 09:58:06 +00001352static int multiSelect(
1353 Parse *pParse,
1354 Select *p,
1355 int eDest,
1356 int iParm,
1357 char *aff /* If eDest is SRT_Union, the affinity string */
1358){
1359 int rc = SQLITE_OK; /* Success code from a subroutine */
drh10e5e3c2000-06-08 00:19:02 +00001360 Select *pPrior; /* Another SELECT immediately to our left */
1361 Vdbe *v; /* Generate code to this VDBE */
danielk1977dc1bdc42004-06-11 10:51:27 +00001362 IdList *pOpenTemp = 0;
drh82c3d632000-06-06 21:56:07 +00001363
drh7b58dae2003-07-20 01:16:46 +00001364 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
1365 ** the last SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001366 */
danielk197784ac9d02004-05-18 09:58:06 +00001367 if( p==0 || p->pPrior==0 ){
1368 rc = 1;
1369 goto multi_select_end;
1370 }
drhd8bc7082000-06-07 23:51:50 +00001371 pPrior = p->pPrior;
1372 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001373 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001374 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001375 rc = 1;
1376 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001377 }
drh7b58dae2003-07-20 01:16:46 +00001378 if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
danielk19774adee202004-05-08 08:23:19 +00001379 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001380 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001381 rc = 1;
1382 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001383 }
drh82c3d632000-06-06 21:56:07 +00001384
drhd8bc7082000-06-07 23:51:50 +00001385 /* Make sure we have a valid query engine. If not, create a new one.
1386 */
danielk19774adee202004-05-08 08:23:19 +00001387 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001388 if( v==0 ){
1389 rc = 1;
1390 goto multi_select_end;
1391 }
drhd8bc7082000-06-07 23:51:50 +00001392
drh1cc3d752002-03-23 00:31:29 +00001393 /* Create the destination temporary table if necessary
1394 */
1395 if( eDest==SRT_TempTable ){
danielk1977b4964b72004-05-18 01:23:38 +00001396 assert( p->pEList );
danielk19774adee202004-05-08 08:23:19 +00001397 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00001398 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, p->pEList->nExpr);
drh1cc3d752002-03-23 00:31:29 +00001399 eDest = SRT_Table;
1400 }
1401
drhf46f9052002-06-22 02:33:38 +00001402 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001403 */
drh82c3d632000-06-06 21:56:07 +00001404 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001405 case TK_ALL: {
1406 if( p->pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +00001407 pPrior->nLimit = p->nLimit;
1408 pPrior->nOffset = p->nOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001409 pPrior->ppOpenTemp = p->ppOpenTemp;
danielk197784ac9d02004-05-18 09:58:06 +00001410 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1411 if( rc ){
1412 goto multi_select_end;
1413 }
drhf46f9052002-06-22 02:33:38 +00001414 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001415 p->iLimit = pPrior->iLimit;
1416 p->iOffset = pPrior->iOffset;
1417 p->nLimit = -1;
1418 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001419 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001420 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001421 if( rc ){
1422 goto multi_select_end;
1423 }
drhf46f9052002-06-22 02:33:38 +00001424 break;
1425 }
1426 /* For UNION ALL ... ORDER BY fall through to the next case */
1427 }
drh82c3d632000-06-06 21:56:07 +00001428 case TK_EXCEPT:
1429 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001430 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001431 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001432 int priorOp; /* The SRT_ operation to apply to prior selects */
drh7b58dae2003-07-20 01:16:46 +00001433 int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
drhc926afb2002-06-20 03:38:26 +00001434 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
danielk1977dc1bdc42004-06-11 10:51:27 +00001435 int addr;
drh82c3d632000-06-06 21:56:07 +00001436
drhd8bc7082000-06-07 23:51:50 +00001437 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh7b58dae2003-07-20 01:16:46 +00001438 if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
drhd8bc7082000-06-07 23:51:50 +00001439 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001440 ** right.
drhd8bc7082000-06-07 23:51:50 +00001441 */
drh82c3d632000-06-06 21:56:07 +00001442 unionTab = iParm;
1443 }else{
drhd8bc7082000-06-07 23:51:50 +00001444 /* We will need to create our own temporary table to hold the
1445 ** intermediate results.
1446 */
1447 unionTab = pParse->nTab++;
1448 if( p->pOrderBy
1449 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001450 rc = 1;
1451 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001452 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001453 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001454 if( p->op!=TK_ALL ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001455 rc = multiSelectOpenTempAddr(p, addr, &pOpenTemp);
1456 if( rc!=SQLITE_OK ){
1457 goto multi_select_end;
1458 }
1459 sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drhd8bc7082000-06-07 23:51:50 +00001460 }
danielk197784ac9d02004-05-18 09:58:06 +00001461 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001462 }
drhd8bc7082000-06-07 23:51:50 +00001463
1464 /* Code the SELECT statements to our left
1465 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001466 pPrior->ppOpenTemp = p->ppOpenTemp;
danielk197784ac9d02004-05-18 09:58:06 +00001467 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
1468 if( rc ){
1469 goto multi_select_end;
1470 }
1471 if( p->op==TK_ALL ){
1472 sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, pPrior->pEList->nExpr);
1473 }
drhd8bc7082000-06-07 23:51:50 +00001474
1475 /* Code the current SELECT statement
1476 */
1477 switch( p->op ){
1478 case TK_EXCEPT: op = SRT_Except; break;
1479 case TK_UNION: op = SRT_Union; break;
1480 case TK_ALL: op = SRT_Table; break;
1481 }
drh82c3d632000-06-06 21:56:07 +00001482 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001483 pOrderBy = p->pOrderBy;
1484 p->pOrderBy = 0;
drh7b58dae2003-07-20 01:16:46 +00001485 nLimit = p->nLimit;
1486 p->nLimit = -1;
1487 nOffset = p->nOffset;
1488 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001489 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001490 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001491 p->pOrderBy = pOrderBy;
drh7b58dae2003-07-20 01:16:46 +00001492 p->nLimit = nLimit;
1493 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001494 if( rc ){
1495 goto multi_select_end;
1496 }
1497
drhd8bc7082000-06-07 23:51:50 +00001498
1499 /* Convert the data in the temporary table into whatever form
1500 ** it is that we currently need.
1501 */
drhc926afb2002-06-20 03:38:26 +00001502 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001503 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001504 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001505 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001506 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001507 }
danielk19774adee202004-05-08 08:23:19 +00001508 iBreak = sqlite3VdbeMakeLabel(v);
1509 iCont = sqlite3VdbeMakeLabel(v);
1510 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001511 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001512 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001513 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001514 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001515 iCont, iBreak, 0);
1516 if( rc ){
1517 rc = 1;
1518 goto multi_select_end;
1519 }
danielk19774adee202004-05-08 08:23:19 +00001520 sqlite3VdbeResolveLabel(v, iCont);
1521 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1522 sqlite3VdbeResolveLabel(v, iBreak);
1523 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001524 }
1525 break;
1526 }
1527 case TK_INTERSECT: {
1528 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001529 int iCont, iBreak, iStart;
drh7b58dae2003-07-20 01:16:46 +00001530 int nLimit, nOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001531 int addr;
drh82c3d632000-06-06 21:56:07 +00001532
drhd8bc7082000-06-07 23:51:50 +00001533 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001534 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001535 ** by allocating the tables we will need.
1536 */
drh82c3d632000-06-06 21:56:07 +00001537 tab1 = pParse->nTab++;
1538 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001539 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001540 rc = 1;
1541 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001542 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001543
1544 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 0);
1545 rc = multiSelectOpenTempAddr(p, addr, &pOpenTemp);
1546 if( rc!=SQLITE_OK ){
1547 goto multi_select_end;
1548 }
1549 sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
danielk197784ac9d02004-05-18 09:58:06 +00001550 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001551
1552 /* Code the SELECTs to our left into temporary table "tab1".
1553 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001554 pPrior->ppOpenTemp = p->ppOpenTemp;
danielk197784ac9d02004-05-18 09:58:06 +00001555 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
1556 if( rc ){
1557 goto multi_select_end;
1558 }
drhd8bc7082000-06-07 23:51:50 +00001559
1560 /* Code the current SELECT into temporary table "tab2"
1561 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001562 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0);
1563 rc = multiSelectOpenTempAddr(p, addr, &pOpenTemp);
1564 if( rc!=SQLITE_OK ){
1565 goto multi_select_end;
1566 }
1567 sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001568 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001569 nLimit = p->nLimit;
1570 p->nLimit = -1;
1571 nOffset = p->nOffset;
1572 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001573 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001574 p->pPrior = pPrior;
drh7b58dae2003-07-20 01:16:46 +00001575 p->nLimit = nLimit;
1576 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001577 if( rc ){
1578 goto multi_select_end;
1579 }
drhd8bc7082000-06-07 23:51:50 +00001580
1581 /* Generate code to take the intersection of the two temporary
1582 ** tables.
1583 */
drh82c3d632000-06-06 21:56:07 +00001584 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001585 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001586 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001587 }
danielk19774adee202004-05-08 08:23:19 +00001588 iBreak = sqlite3VdbeMakeLabel(v);
1589 iCont = sqlite3VdbeMakeLabel(v);
1590 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001591 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001592 iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
1593 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001594 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001595 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001596 iCont, iBreak, 0);
1597 if( rc ){
1598 rc = 1;
1599 goto multi_select_end;
1600 }
danielk19774adee202004-05-08 08:23:19 +00001601 sqlite3VdbeResolveLabel(v, iCont);
1602 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1603 sqlite3VdbeResolveLabel(v, iBreak);
1604 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1605 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001606 break;
1607 }
1608 }
1609 assert( p->pEList && pPrior->pEList );
1610 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001611 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001612 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001613 rc = 1;
1614 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001615 }
danielk197784ac9d02004-05-18 09:58:06 +00001616
danielk1977dc1bdc42004-06-11 10:51:27 +00001617 if( p->pOrderBy || (pOpenTemp && pOpenTemp->nId>0) ){
1618 int nCol = p->pEList->nExpr;
1619 int i;
1620 KeyInfo *pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*sizeof(CollSeq*));
1621 if( !pKeyInfo ){
1622 rc = SQLITE_NOMEM;
1623 goto multi_select_end;
1624 }
1625
1626 pKeyInfo->enc = pParse->db->enc;
1627 pKeyInfo->nField = nCol;
1628
1629 for(i=0; i<nCol; i++){
1630 pKeyInfo->aColl[i] = multiSelectCollSeq(pParse, p, i);
1631 if( !pKeyInfo->aColl[i] ){
1632 pKeyInfo->aColl[i] = pParse->db->pDfltColl;
1633 }
1634 }
1635
1636 for(i=0; pOpenTemp && i<pOpenTemp->nId; i++){
1637 int p3type = (i==0?P3_KEYINFO_HANDOFF:P3_KEYINFO);
1638 int addr = pOpenTemp->a[i].idx;
1639 sqlite3VdbeChangeP3(v, addr, (char *)pKeyInfo, p3type);
1640 }
1641
1642 if( p->pOrderBy ){
1643 for(i=0; i<p->pOrderBy->nExpr; i++){
1644 Expr *pExpr = p->pOrderBy->a[i].pExpr;
1645 char *zName = p->pOrderBy->a[i].zName;
1646 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
1647 assert( !pExpr->pColl );
1648 if( zName ){
1649 pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1);
1650 }else{
1651 pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn];
1652 }
1653 }
1654 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1655 }
1656
1657 if( !pOpenTemp ){
1658 /* This happens for UNION ALL ... ORDER BY */
1659 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001660 }
1661 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001662
1663multi_select_end:
1664 if( pOpenTemp ){
1665 sqlite3IdListDelete(pOpenTemp);
1666 }
1667 p->ppOpenTemp = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001668 return rc;
drh22827922000-06-06 17:27:05 +00001669}
1670
1671/*
drh832508b2002-03-02 17:04:07 +00001672** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001673** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001674** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001675** unchanged.)
drh832508b2002-03-02 17:04:07 +00001676**
1677** This routine is part of the flattening procedure. A subquery
1678** whose result set is defined by pEList appears as entry in the
1679** FROM clause of a SELECT such that the VDBE cursor assigned to that
1680** FORM clause entry is iTable. This routine make the necessary
1681** changes to pExpr so that it refers directly to the source table
1682** of the subquery rather the result set of the subquery.
1683*/
drh6a3ea0e2003-05-02 14:32:12 +00001684static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1685static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001686 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001687 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1688 if( pExpr->iColumn<0 ){
1689 pExpr->op = TK_NULL;
1690 }else{
1691 Expr *pNew;
1692 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1693 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1694 pNew = pEList->a[pExpr->iColumn].pExpr;
1695 assert( pNew!=0 );
1696 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001697 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001698 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001699 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001700 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001701 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001702 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001703 pExpr->iTable = pNew->iTable;
1704 pExpr->iColumn = pNew->iColumn;
1705 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001706 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1707 sqlite3TokenCopy(&pExpr->span, &pNew->span);
drh50350a12004-02-13 16:22:22 +00001708 }
drh832508b2002-03-02 17:04:07 +00001709 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001710 substExpr(pExpr->pLeft, iTable, pEList);
1711 substExpr(pExpr->pRight, iTable, pEList);
1712 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001713 }
1714}
1715static void
drh6a3ea0e2003-05-02 14:32:12 +00001716substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001717 int i;
1718 if( pList==0 ) return;
1719 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001720 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001721 }
1722}
1723
1724/*
drh1350b032002-02-27 19:00:20 +00001725** This routine attempts to flatten subqueries in order to speed
1726** execution. It returns 1 if it makes changes and 0 if no flattening
1727** occurs.
1728**
1729** To understand the concept of flattening, consider the following
1730** query:
1731**
1732** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1733**
1734** The default way of implementing this query is to execute the
1735** subquery first and store the results in a temporary table, then
1736** run the outer query on that temporary table. This requires two
1737** passes over the data. Furthermore, because the temporary table
1738** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001739** optimized.
drh1350b032002-02-27 19:00:20 +00001740**
drh832508b2002-03-02 17:04:07 +00001741** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001742** a single flat select, like this:
1743**
1744** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1745**
1746** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001747** but only has to scan the data once. And because indices might
1748** exist on the table t1, a complete scan of the data might be
1749** avoided.
drh1350b032002-02-27 19:00:20 +00001750**
drh832508b2002-03-02 17:04:07 +00001751** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001752**
drh832508b2002-03-02 17:04:07 +00001753** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001754**
drh832508b2002-03-02 17:04:07 +00001755** (2) The subquery is not an aggregate or the outer query is not a join.
1756**
drh8af4d3a2003-05-06 20:35:16 +00001757** (3) The subquery is not the right operand of a left outer join, or
1758** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001759**
1760** (4) The subquery is not DISTINCT or the outer query is not a join.
1761**
1762** (5) The subquery is not DISTINCT or the outer query does not use
1763** aggregates.
1764**
1765** (6) The subquery does not use aggregates or the outer query is not
1766** DISTINCT.
1767**
drh08192d52002-04-30 19:20:28 +00001768** (7) The subquery has a FROM clause.
1769**
drhdf199a22002-06-14 22:38:41 +00001770** (8) The subquery does not use LIMIT or the outer query is not a join.
1771**
1772** (9) The subquery does not use LIMIT or the outer query does not use
1773** aggregates.
1774**
1775** (10) The subquery does not use aggregates or the outer query does not
1776** use LIMIT.
1777**
drh174b6192002-12-03 02:22:52 +00001778** (11) The subquery and the outer query do not both have ORDER BY clauses.
1779**
drh3fc673e2003-06-16 00:40:34 +00001780** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1781** subquery has no WHERE clause. (added by ticket #350)
1782**
drh832508b2002-03-02 17:04:07 +00001783** In this routine, the "p" parameter is a pointer to the outer query.
1784** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1785** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1786**
drh665de472003-03-31 13:36:09 +00001787** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001788** If flattening is attempted this routine returns 1.
1789**
1790** All of the expression analysis must occur on both the outer query and
1791** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001792*/
drh8c74a8c2002-08-25 19:20:40 +00001793static int flattenSubquery(
1794 Parse *pParse, /* The parsing context */
1795 Select *p, /* The parent or outer SELECT statement */
1796 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1797 int isAgg, /* True if outer SELECT uses aggregate functions */
1798 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1799){
drh0bb28102002-05-08 11:54:14 +00001800 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001801 SrcList *pSrc; /* The FROM clause of the outer query */
1802 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001803 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001804 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh832508b2002-03-02 17:04:07 +00001805 int i;
drh832508b2002-03-02 17:04:07 +00001806 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001807
drh832508b2002-03-02 17:04:07 +00001808 /* Check to see if flattening is permitted. Return 0 if not.
1809 */
1810 if( p==0 ) return 0;
1811 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001812 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001813 pSub = pSrc->a[iFrom].pSelect;
1814 assert( pSub!=0 );
1815 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001816 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001817 pSubSrc = pSub->pSrc;
1818 assert( pSubSrc );
drhc31c2eb2003-05-02 16:04:17 +00001819 if( pSubSrc->nSrc==0 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001820 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1821 return 0;
1822 }
drhd11d3822002-06-21 23:01:49 +00001823 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001824 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001825
drh8af4d3a2003-05-06 20:35:16 +00001826 /* Restriction 3: If the subquery is a join, make sure the subquery is
1827 ** not used as the right operand of an outer join. Examples of why this
1828 ** is not allowed:
1829 **
1830 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1831 **
1832 ** If we flatten the above, we would get
1833 **
1834 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1835 **
1836 ** which is not at all the same thing.
1837 */
1838 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1839 return 0;
1840 }
1841
drh3fc673e2003-06-16 00:40:34 +00001842 /* Restriction 12: If the subquery is the right operand of a left outer
1843 ** join, make sure the subquery has no WHERE clause.
1844 ** An examples of why this is not allowed:
1845 **
1846 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1847 **
1848 ** If we flatten the above, we would get
1849 **
1850 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1851 **
1852 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1853 ** effectively converts the OUTER JOIN into an INNER JOIN.
1854 */
1855 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1856 && pSub->pWhere!=0 ){
1857 return 0;
1858 }
1859
drh0bb28102002-05-08 11:54:14 +00001860 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001861 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001862 */
drhc31c2eb2003-05-02 16:04:17 +00001863
1864 /* Move all of the FROM elements of the subquery into the
1865 ** the FROM clause of the outer query. Before doing this, remember
1866 ** the cursor number for the original outer query FROM element in
1867 ** iParent. The iParent cursor will never be used. Subsequent code
1868 ** will scan expressions looking for iParent references and replace
1869 ** those references with expressions that resolve to the subquery FROM
1870 ** elements we are now copying in.
1871 */
drh6a3ea0e2003-05-02 14:32:12 +00001872 iParent = pSrc->a[iFrom].iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001873 {
1874 int nSubSrc = pSubSrc->nSrc;
drh8af4d3a2003-05-06 20:35:16 +00001875 int jointype = pSrc->a[iFrom].jointype;
drhc31c2eb2003-05-02 16:04:17 +00001876
1877 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001878 sqlite3DeleteTable(0, pSrc->a[iFrom].pTab);
drhc31c2eb2003-05-02 16:04:17 +00001879 }
drhf26e09c2003-05-31 16:21:12 +00001880 sqliteFree(pSrc->a[iFrom].zDatabase);
drhc31c2eb2003-05-02 16:04:17 +00001881 sqliteFree(pSrc->a[iFrom].zName);
1882 sqliteFree(pSrc->a[iFrom].zAlias);
1883 if( nSubSrc>1 ){
1884 int extra = nSubSrc - 1;
1885 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00001886 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00001887 }
1888 p->pSrc = pSrc;
1889 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1890 pSrc->a[i] = pSrc->a[i-extra];
1891 }
1892 }
1893 for(i=0; i<nSubSrc; i++){
1894 pSrc->a[i+iFrom] = pSubSrc->a[i];
1895 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1896 }
drh8af4d3a2003-05-06 20:35:16 +00001897 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00001898 }
1899
1900 /* Now begin substituting subquery result set expressions for
1901 ** references to the iParent in the outer query.
1902 **
1903 ** Example:
1904 **
1905 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1906 ** \ \_____________ subquery __________/ /
1907 ** \_____________________ outer query ______________________________/
1908 **
1909 ** We look at every expression in the outer query and every place we see
1910 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1911 */
drh6a3ea0e2003-05-02 14:32:12 +00001912 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001913 pList = p->pEList;
1914 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001915 Expr *pExpr;
1916 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1917 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001918 }
1919 }
drh1b2e0322002-03-03 02:49:51 +00001920 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00001921 substExprList(p->pGroupBy, iParent, pSub->pEList);
1922 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001923 }
drh174b6192002-12-03 02:22:52 +00001924 if( pSub->pOrderBy ){
1925 assert( p->pOrderBy==0 );
1926 p->pOrderBy = pSub->pOrderBy;
1927 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00001928 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00001929 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00001930 }
drh832508b2002-03-02 17:04:07 +00001931 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001932 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00001933 }else{
1934 pWhere = 0;
1935 }
1936 if( subqueryIsAgg ){
1937 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001938 p->pHaving = p->pWhere;
1939 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00001940 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001941 if( pSub->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001942 Expr *pHaving = sqlite3ExprDup(pSub->pHaving);
drh1b2e0322002-03-03 02:49:51 +00001943 if( p->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001944 p->pHaving = sqlite3Expr(TK_AND, p->pHaving, pHaving, 0);
drh1b2e0322002-03-03 02:49:51 +00001945 }else{
1946 p->pHaving = pHaving;
1947 }
1948 }
1949 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00001950 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00001951 }else if( p->pWhere==0 ){
1952 p->pWhere = pWhere;
1953 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001954 substExpr(p->pWhere, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001955 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001956 p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pWhere, 0);
drh832508b2002-03-02 17:04:07 +00001957 }
1958 }
drhc31c2eb2003-05-02 16:04:17 +00001959
1960 /* The flattened query is distinct if either the inner or the
1961 ** outer query is distinct.
1962 */
drh832508b2002-03-02 17:04:07 +00001963 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00001964
drhc31c2eb2003-05-02 16:04:17 +00001965 /* Transfer the limit expression from the subquery to the outer
1966 ** query.
1967 */
drhdf199a22002-06-14 22:38:41 +00001968 if( pSub->nLimit>=0 ){
1969 if( p->nLimit<0 ){
1970 p->nLimit = pSub->nLimit;
1971 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1972 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1973 }
1974 }
1975 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00001976
drhc31c2eb2003-05-02 16:04:17 +00001977 /* Finially, delete what is left of the subquery and return
1978 ** success.
1979 */
danielk19774adee202004-05-08 08:23:19 +00001980 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00001981 return 1;
1982}
drh1350b032002-02-27 19:00:20 +00001983
1984/*
drh9562b552002-02-19 15:00:07 +00001985** Analyze the SELECT statement passed in as an argument to see if it
1986** is a simple min() or max() query. If it is and this query can be
1987** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00001988** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00001989** simple min() or max() query, then return 0;
1990**
1991** A simply min() or max() query looks like this:
1992**
1993** SELECT min(a) FROM table;
1994** SELECT max(a) FROM table;
1995**
1996** The query may have only a single table in its FROM argument. There
1997** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1998** be the min() or max() of a single column of the table. The column
1999** in the min() or max() function must be indexed.
2000**
danielk19774adee202004-05-08 08:23:19 +00002001** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00002002** See the header comment on that routine for additional information.
2003*/
2004static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2005 Expr *pExpr;
2006 int iCol;
2007 Table *pTab;
2008 Index *pIdx;
2009 int base;
2010 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00002011 int seekOp;
2012 int cont;
drh6e175292004-03-13 14:00:36 +00002013 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00002014 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00002015 SrcList *pSrc;
2016
drh9562b552002-02-19 15:00:07 +00002017
2018 /* Check to see if this query is a simple min() or max() query. Return
2019 ** zero if it is not.
2020 */
2021 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00002022 pSrc = p->pSrc;
2023 if( pSrc->nSrc!=1 ) return 0;
2024 pEList = p->pEList;
2025 if( pEList->nExpr!=1 ) return 0;
2026 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002027 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002028 pList = pExpr->pList;
2029 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002030 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00002031 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002032 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00002033 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002034 seekOp = OP_Last;
2035 }else{
2036 return 0;
2037 }
drh6e175292004-03-13 14:00:36 +00002038 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002039 if( pExpr->op!=TK_COLUMN ) return 0;
2040 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002041 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002042
2043 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002044 ** Check to make sure we have an index and make pIdx point to the
2045 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2046 ** key column, no index is necessary so set pIdx to NULL. If no
2047 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002048 */
2049 if( iCol<0 ){
2050 pIdx = 0;
2051 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002052 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002053 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2054 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002055 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002056 }
2057 if( pIdx==0 ) return 0;
2058 }
2059
drhe5f50722003-07-19 00:44:14 +00002060 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002061 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002062 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002063 */
danielk19774adee202004-05-08 08:23:19 +00002064 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002065 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002066
drh0c37e632004-01-30 02:01:03 +00002067 /* If the output is destined for a temporary table, open that table.
2068 */
2069 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002070 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002071 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002072 }
2073
drh17f71932002-02-21 12:01:27 +00002074 /* Generating code to find the min or the max. Basically all we have
2075 ** to do is find the first or the last entry in the chosen index. If
2076 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2077 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002078 */
danielk19774adee202004-05-08 08:23:19 +00002079 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00002080 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00002081 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00002082 if( pSrc->a[0].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +00002083 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00002084 sqlite3VdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
danielk1977b4964b72004-05-18 01:23:38 +00002085 sqlite3VdbeAddOp(v, OP_SetNumColumns, base, pTab->nCol);
drh6e175292004-03-13 14:00:36 +00002086 }
danielk19774adee202004-05-08 08:23:19 +00002087 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00002088 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002089 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002090 }else{
danielk19774adee202004-05-08 08:23:19 +00002091 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00002092 sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum,
2093 (char*)&pIdx->keyInfo, P3_KEYINFO);
drh9eb516c2004-07-18 20:52:32 +00002094 if( seekOp==OP_Rewind ){
drh1af3fdb2004-07-18 21:33:01 +00002095 sqlite3VdbeAddOp(v, OP_String, 0, 0);
2096 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2097 seekOp = OP_MoveGt;
drh9eb516c2004-07-18 20:52:32 +00002098 }
drh1af3fdb2004-07-18 21:33:01 +00002099 sqlite3VdbeAddOp(v, seekOp, base+1, 0);
danielk19774adee202004-05-08 08:23:19 +00002100 sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
2101 sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002102 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002103 }
drh5cf8e8c2002-02-19 22:42:05 +00002104 eList.nExpr = 1;
2105 memset(&eListItem, 0, sizeof(eListItem));
2106 eList.a = &eListItem;
2107 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00002108 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00002109 sqlite3VdbeResolveLabel(v, cont);
2110 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002111
drh9562b552002-02-19 15:00:07 +00002112 return 1;
2113}
2114
2115/*
drh9bb61fe2000-06-05 16:01:39 +00002116** Generate code for the given SELECT statement.
2117**
drhfef52082000-06-06 01:50:43 +00002118** The results are distributed in various ways depending on the
2119** value of eDest and iParm.
2120**
2121** eDest Value Result
2122** ------------ -------------------------------------------
2123** SRT_Callback Invoke the callback for each row of the result.
2124**
2125** SRT_Mem Store first result in memory cell iParm
2126**
danielk1977e014a832004-05-17 10:48:57 +00002127** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002128**
drh82c3d632000-06-06 21:56:07 +00002129** SRT_Union Store results as a key in a temporary table iParm
2130**
jplyon4b11c6d2004-01-19 04:57:53 +00002131** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002132**
2133** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002134**
drhe78e8282003-01-19 03:59:45 +00002135** The table above is incomplete. Additional eDist value have be added
2136** since this comment was written. See the selectInnerLoop() function for
2137** a complete listing of the allowed values of eDest and their meanings.
2138**
drh9bb61fe2000-06-05 16:01:39 +00002139** This routine returns the number of errors. If any errors are
2140** encountered, then an appropriate error message is left in
2141** pParse->zErrMsg.
2142**
2143** This routine does NOT free the Select structure passed in. The
2144** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002145**
2146** The pParent, parentTab, and *pParentAgg fields are filled in if this
2147** SELECT is a subquery. This routine may try to combine this SELECT
2148** with its parent to form a single flat query. In so doing, it might
2149** change the parent query from a non-aggregate to an aggregate query.
2150** For that reason, the pParentAgg flag is passed as a pointer, so it
2151** can be changed.
drhe78e8282003-01-19 03:59:45 +00002152**
2153** Example 1: The meaning of the pParent parameter.
2154**
2155** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2156** \ \_______ subquery _______/ /
2157** \ /
2158** \____________________ outer query ___________________/
2159**
2160** This routine is called for the outer query first. For that call,
2161** pParent will be NULL. During the processing of the outer query, this
2162** routine is called recursively to handle the subquery. For the recursive
2163** call, pParent will point to the outer query. Because the subquery is
2164** the second element in a three-way join, the parentTab parameter will
2165** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002166*/
danielk19774adee202004-05-08 08:23:19 +00002167int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002168 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002169 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002170 int eDest, /* How to dispose of the results */
2171 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002172 Select *pParent, /* Another SELECT for which this is a sub-query */
2173 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002174 int *pParentAgg, /* True if pParent uses aggregate functions */
2175 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002176){
drhd8bc7082000-06-07 23:51:50 +00002177 int i;
drhcce7d172000-05-31 15:34:51 +00002178 WhereInfo *pWInfo;
2179 Vdbe *v;
2180 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002181 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002182 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002183 Expr *pWhere; /* The WHERE clause. May be NULL */
2184 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002185 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2186 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002187 int isDistinct; /* True if the DISTINCT keyword is present */
2188 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002189 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00002190
danielk19776f8a5032004-05-10 10:34:51 +00002191 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002192 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002193
drh82c3d632000-06-06 21:56:07 +00002194 /* If there is are a sequence of queries, do the earlier ones first.
2195 */
2196 if( p->pPrior ){
danielk197784ac9d02004-05-18 09:58:06 +00002197 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002198 }
2199
2200 /* Make local copies of the parameters for this query.
2201 */
drh9bb61fe2000-06-05 16:01:39 +00002202 pTabList = p->pSrc;
2203 pWhere = p->pWhere;
2204 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00002205 pGroupBy = p->pGroupBy;
2206 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00002207 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00002208
drh6a3ea0e2003-05-02 14:32:12 +00002209 /* Allocate VDBE cursors for each table in the FROM clause
drh10e5e3c2000-06-08 00:19:02 +00002210 */
danielk19774adee202004-05-08 08:23:19 +00002211 sqlite3SrcListAssignCursors(pParse, pTabList);
drh10e5e3c2000-06-08 00:19:02 +00002212
drh9bb61fe2000-06-05 16:01:39 +00002213 /*
2214 ** Do not even attempt to generate any code if we have already seen
2215 ** errors before this routine starts.
2216 */
drh1d83f052002-02-17 00:30:36 +00002217 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002218
drhe78e8282003-01-19 03:59:45 +00002219 /* Expand any "*" terms in the result set. (For example the "*" in
2220 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
2221 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00002222 */
drhd8bc7082000-06-07 23:51:50 +00002223 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00002224 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002225 }
drhad2d8302002-05-24 20:31:36 +00002226 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00002227 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00002228 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002229
drh22827922000-06-06 17:27:05 +00002230 /* If writing to memory or generating a set
2231 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002232 */
drhfef52082000-06-06 01:50:43 +00002233 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002234 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002235 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002236 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002237 }
2238
drhc926afb2002-06-20 03:38:26 +00002239 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002240 */
drhc926afb2002-06-20 03:38:26 +00002241 switch( eDest ){
2242 case SRT_Union:
2243 case SRT_Except:
2244 case SRT_Discard:
danielk1977f93bbbe2004-05-27 10:30:52 +00002245 case SRT_Set:
drhc926afb2002-06-20 03:38:26 +00002246 pOrderBy = 0;
2247 break;
2248 default:
2249 break;
drh22827922000-06-06 17:27:05 +00002250 }
2251
drh10e5e3c2000-06-08 00:19:02 +00002252 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002253 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002254 **
drh967e8b72000-06-21 13:59:10 +00002255 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002256 */
drh4794b982000-06-06 13:54:14 +00002257 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002258 if( sqlite3ExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002259 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002260 }
danielk19774adee202004-05-08 08:23:19 +00002261 if( sqlite3ExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002262 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002263 }
2264 }
drhcce7d172000-05-31 15:34:51 +00002265 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002266 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00002267 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002268 }
danielk19774adee202004-05-08 08:23:19 +00002269 if( sqlite3ExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00002270 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002271 }
2272 }
drhc66c5a22002-12-03 02:34:49 +00002273 if( pHaving ){
2274 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002275 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
drhc66c5a22002-12-03 02:34:49 +00002276 goto select_end;
2277 }
danielk19774adee202004-05-08 08:23:19 +00002278 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pHaving) ){
drhc66c5a22002-12-03 02:34:49 +00002279 goto select_end;
2280 }
danielk19774adee202004-05-08 08:23:19 +00002281 if( sqlite3ExprCheck(pParse, pHaving, 1, &isAgg) ){
drhc66c5a22002-12-03 02:34:49 +00002282 goto select_end;
2283 }
2284 }
drhcce7d172000-05-31 15:34:51 +00002285 if( pOrderBy ){
2286 for(i=0; i<pOrderBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002287 int iCol;
drh22827922000-06-06 17:27:05 +00002288 Expr *pE = pOrderBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002289 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2290 sqlite3ExprDelete(pE);
2291 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh88eee382003-01-31 17:16:36 +00002292 }
danielk19774adee202004-05-08 08:23:19 +00002293 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh88eee382003-01-31 17:16:36 +00002294 goto select_end;
2295 }
danielk19774adee202004-05-08 08:23:19 +00002296 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh88eee382003-01-31 17:16:36 +00002297 goto select_end;
2298 }
danielk19774adee202004-05-08 08:23:19 +00002299 if( sqlite3ExprIsConstant(pE) ){
2300 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2301 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002302 "ORDER BY terms must not be non-integer constants");
drhe4de1fe2002-06-02 16:09:01 +00002303 goto select_end;
2304 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002305 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002306 "ORDER BY column number %d out of range - should be "
drhe4de1fe2002-06-02 16:09:01 +00002307 "between 1 and %d", iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00002308 goto select_end;
2309 }
drhcce7d172000-05-31 15:34:51 +00002310 }
2311 }
2312 }
drh22827922000-06-06 17:27:05 +00002313 if( pGroupBy ){
2314 for(i=0; i<pGroupBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002315 int iCol;
drh22827922000-06-06 17:27:05 +00002316 Expr *pE = pGroupBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002317 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2318 sqlite3ExprDelete(pE);
2319 pE = pGroupBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00002320 }
danielk19774adee202004-05-08 08:23:19 +00002321 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00002322 goto select_end;
drh22827922000-06-06 17:27:05 +00002323 }
danielk19774adee202004-05-08 08:23:19 +00002324 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00002325 goto select_end;
drh22827922000-06-06 17:27:05 +00002326 }
danielk19774adee202004-05-08 08:23:19 +00002327 if( sqlite3ExprIsConstant(pE) ){
2328 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2329 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002330 "GROUP BY terms must not be non-integer constants");
drh88eee382003-01-31 17:16:36 +00002331 goto select_end;
2332 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002333 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002334 "GROUP BY column number %d out of range - should be "
drh88eee382003-01-31 17:16:36 +00002335 "between 1 and %d", iCol, pEList->nExpr);
drh88eee382003-01-31 17:16:36 +00002336 goto select_end;
2337 }
2338 }
drh22827922000-06-06 17:27:05 +00002339 }
2340 }
drhcce7d172000-05-31 15:34:51 +00002341
drhd820cb12002-02-18 03:21:45 +00002342 /* Begin generating code.
2343 */
danielk19774adee202004-05-08 08:23:19 +00002344 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002345 if( v==0 ) goto select_end;
2346
drhe78e8282003-01-19 03:59:45 +00002347 /* Identify column names if we will be using them in a callback. This
2348 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002349 */
2350 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002351 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002352 }
2353
drhd3d39e92004-05-20 22:16:29 +00002354#if 1 /* I do not think we need the following code any more.... */
danielk197784ac9d02004-05-18 09:58:06 +00002355 /* If the destination is SRT_Union, then set the number of columns in
2356 ** the records that will be inserted into the temporary table. The caller
2357 ** couldn't do this, in case the select statement is of the form
2358 ** "SELECT * FROM ....".
2359 **
2360 ** We need to do this before we start inserting records into the
2361 ** temporary table (which has had OP_KeyAsData executed on it), because
2362 ** it is required by the key comparison function. So do it now, even
2363 ** though this means that OP_SetNumColumns may be executed on the same
2364 ** cursor more than once.
2365 */
2366 if( eDest==SRT_Union ){
2367 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
2368 }
drhd3d39e92004-05-20 22:16:29 +00002369#endif
danielk197784ac9d02004-05-18 09:58:06 +00002370
drhd820cb12002-02-18 03:21:45 +00002371 /* Generate code for all sub-queries in the FROM clause
2372 */
drhad3cab52002-05-24 02:04:32 +00002373 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002374 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002375 int needRestoreContext;
2376
drha76b5df2002-02-23 02:32:10 +00002377 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002378 if( pTabList->a[i].zName!=0 ){
2379 zSavedAuthContext = pParse->zAuthContext;
2380 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002381 needRestoreContext = 1;
2382 }else{
2383 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002384 }
danielk19774adee202004-05-08 08:23:19 +00002385 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
danielk197784ac9d02004-05-18 09:58:06 +00002386 pTabList->a[i].iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002387 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002388 pParse->zAuthContext = zSavedAuthContext;
2389 }
drh1b2e0322002-03-03 02:49:51 +00002390 pTabList = p->pSrc;
2391 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002392 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002393 pOrderBy = p->pOrderBy;
2394 }
drh1b2e0322002-03-03 02:49:51 +00002395 pGroupBy = p->pGroupBy;
2396 pHaving = p->pHaving;
2397 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002398 }
2399
drh6e175292004-03-13 14:00:36 +00002400 /* Check for the special case of a min() or max() function by itself
2401 ** in the result set.
2402 */
2403 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2404 rc = 0;
2405 goto select_end;
2406 }
2407
drh832508b2002-03-02 17:04:07 +00002408 /* Check to see if this is a subquery that can be "flattened" into its parent.
2409 ** If flattening is a possiblity, do so and return immediately.
2410 */
drh1b2e0322002-03-03 02:49:51 +00002411 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002412 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002413 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002414 return rc;
2415 }
drh832508b2002-03-02 17:04:07 +00002416
danielk19777cedc8d2004-06-10 10:50:08 +00002417 /* If there is an ORDER BY clause, resolve any collation sequences
2418 ** names that have been explicitly specified.
2419 */
2420 if( pOrderBy ){
2421 for(i=0; i<pOrderBy->nExpr; i++){
2422 if( pOrderBy->a[i].zName ){
2423 pOrderBy->a[i].pExpr->pColl =
2424 sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1);
2425 }
2426 }
2427 if( pParse->nErr ){
2428 goto select_end;
2429 }
2430 }
2431
drh7b58dae2003-07-20 01:16:46 +00002432 /* Set the limiter.
2433 */
2434 computeLimitRegisters(pParse, p);
2435
drh2d0794e2002-03-03 03:03:52 +00002436 /* If the output is destined for a temporary table, open that table.
2437 */
2438 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002439 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002440 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002441 }
2442
drh22827922000-06-06 17:27:05 +00002443 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002444 */
drhd820cb12002-02-18 03:21:45 +00002445 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002446 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002447 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002448 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002449 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002450 if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002451 goto select_end;
drh22827922000-06-06 17:27:05 +00002452 }
2453 }
2454 if( pGroupBy ){
2455 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002456 if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002457 goto select_end;
drh22827922000-06-06 17:27:05 +00002458 }
2459 }
2460 }
danielk19774adee202004-05-08 08:23:19 +00002461 if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002462 goto select_end;
drh22827922000-06-06 17:27:05 +00002463 }
drh191b6902000-06-08 11:13:01 +00002464 if( pOrderBy ){
2465 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002466 if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002467 goto select_end;
drh191b6902000-06-08 11:13:01 +00002468 }
2469 }
2470 }
drhefb72512000-05-31 20:00:52 +00002471 }
2472
drh22827922000-06-06 17:27:05 +00002473 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002474 */
2475 if( isAgg ){
danielk1977e159fdf2004-06-21 10:45:06 +00002476 int addr = sqlite3VdbeAddOp(v, OP_AggReset, (pGroupBy?0:1), pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002477 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002478 FuncDef *pFunc;
2479 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drhf9b596e2004-05-26 16:54:42 +00002480 sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_FUNCDEF);
drhe5095352002-02-24 03:25:14 +00002481 }
2482 }
danielk1977e159fdf2004-06-21 10:45:06 +00002483 if( pGroupBy ){
danielk1977ce2663c2004-06-11 13:19:21 +00002484 int sz = sizeof(KeyInfo) + pGroupBy->nExpr*sizeof(CollSeq*);
2485 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(sz);
2486 if( 0==pKey ){
2487 goto select_end;
2488 }
2489 pKey->enc = pParse->db->enc;
2490 pKey->nField = pGroupBy->nExpr;
2491 for(i=0; i<pGroupBy->nExpr; i++){
2492 pKey->aColl[i] = sqlite3ExprCollSeq(pParse, pGroupBy->a[i].pExpr);
2493 if( !pKey->aColl[i] ){
2494 pKey->aColl[i] = pParse->db->pDfltColl;
2495 }
2496 }
2497 sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF);
drh1bee3d72001-10-15 00:44:35 +00002498 }
drhcce7d172000-05-31 15:34:51 +00002499 }
2500
drh19a775c2000-06-05 18:54:46 +00002501 /* Initialize the memory cell to NULL
2502 */
drhfef52082000-06-06 01:50:43 +00002503 if( eDest==SRT_Mem ){
danielk19770f69c1e2004-05-29 11:24:50 +00002504 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00002505 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002506 }
2507
drh832508b2002-03-02 17:04:07 +00002508 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002509 */
drh19a775c2000-06-05 18:54:46 +00002510 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002511 distinct = pParse->nTab++;
drhd3d39e92004-05-20 22:16:29 +00002512 openTempIndex(pParse, p, distinct, 0);
drh832508b2002-03-02 17:04:07 +00002513 }else{
2514 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002515 }
drh832508b2002-03-02 17:04:07 +00002516
2517 /* Begin the database scan
2518 */
danielk19774adee202004-05-08 08:23:19 +00002519 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
drh68d2e592002-08-04 00:52:38 +00002520 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002521 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002522
drh22827922000-06-06 17:27:05 +00002523 /* Use the standard inner loop if we are not dealing with
2524 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002525 */
drhda9d6c42000-05-31 18:20:14 +00002526 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002527 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002528 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002529 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002530 }
drhcce7d172000-05-31 15:34:51 +00002531 }
drhefb72512000-05-31 20:00:52 +00002532
drhe3184742002-06-19 14:27:05 +00002533 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002534 ** processing.
drhefb72512000-05-31 20:00:52 +00002535 */
drh22827922000-06-06 17:27:05 +00002536 else{
drh268380c2004-02-25 13:47:31 +00002537 AggExpr *pAgg;
drh22827922000-06-06 17:27:05 +00002538 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002539 int lbl1;
drh22827922000-06-06 17:27:05 +00002540 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002541 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
drh22827922000-06-06 17:27:05 +00002542 }
danielk1977ededfd52004-06-17 07:53:01 +00002543 /* No affinity string is attached to the following OP_MakeRecord
drhd3d39e92004-05-20 22:16:29 +00002544 ** because we do not need to do any coercion of datatypes. */
danielk1977ededfd52004-06-17 07:53:01 +00002545 sqlite3VdbeAddOp(v, OP_MakeRecord, pGroupBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +00002546 lbl1 = sqlite3VdbeMakeLabel(v);
2547 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh268380c2004-02-25 13:47:31 +00002548 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2549 if( pAgg->isAgg ) continue;
danielk19774adee202004-05-08 08:23:19 +00002550 sqlite3ExprCode(pParse, pAgg->pExpr);
2551 sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002552 }
danielk19774adee202004-05-08 08:23:19 +00002553 sqlite3VdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002554 }
drh268380c2004-02-25 13:47:31 +00002555 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002556 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002557 int nExpr;
2558 FuncDef *pDef;
2559 if( !pAgg->isAgg ) continue;
2560 assert( pAgg->pFunc!=0 );
2561 assert( pAgg->pFunc->xStep!=0 );
2562 pDef = pAgg->pFunc;
2563 pE = pAgg->pExpr;
2564 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002565 assert( pE->op==TK_AGG_FUNCTION );
drhf9b596e2004-05-26 16:54:42 +00002566 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
danielk19774adee202004-05-08 08:23:19 +00002567 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
danielk1977dc1bdc42004-06-11 10:51:27 +00002568 if( pDef->needCollSeq ){
2569 CollSeq *pColl = 0;
2570 int j;
2571 for(j=0; !pColl && j<nExpr; j++){
2572 pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr);
2573 }
2574 if( !pColl ) pColl = pParse->db->pDfltColl;
2575 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2576 }
danielk19774adee202004-05-08 08:23:19 +00002577 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002578 }
drhcce7d172000-05-31 15:34:51 +00002579 }
2580
2581 /* End the database scan loop.
2582 */
danielk19774adee202004-05-08 08:23:19 +00002583 sqlite3WhereEnd(pWInfo);
drhcce7d172000-05-31 15:34:51 +00002584
drh22827922000-06-06 17:27:05 +00002585 /* If we are processing aggregates, we need to set up a second loop
2586 ** over all of the aggregate values and process them.
2587 */
2588 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002589 int endagg = sqlite3VdbeMakeLabel(v);
drh22827922000-06-06 17:27:05 +00002590 int startagg;
danielk19774adee202004-05-08 08:23:19 +00002591 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002592 pParse->useAgg = 1;
2593 if( pHaving ){
danielk19774adee202004-05-08 08:23:19 +00002594 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002595 }
drhdf199a22002-06-14 22:38:41 +00002596 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002597 iParm, startagg, endagg, aff) ){
drh1d83f052002-02-17 00:30:36 +00002598 goto select_end;
drh22827922000-06-06 17:27:05 +00002599 }
danielk19774adee202004-05-08 08:23:19 +00002600 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2601 sqlite3VdbeResolveLabel(v, endagg);
2602 sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002603 pParse->useAgg = 0;
2604 }
2605
drhcce7d172000-05-31 15:34:51 +00002606 /* If there is an ORDER BY clause, then we need to sort the results
2607 ** and send them to the callback one by one.
2608 */
2609 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00002610 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002611 }
drh6a535342001-10-19 16:44:56 +00002612
drhf620b4e2004-02-09 14:37:50 +00002613 /* If this was a subquery, we have now converted the subquery into a
2614 ** temporary table. So delete the subquery structure from the parent
2615 ** to prevent this subquery from being evaluated again and to force the
2616 ** the use of the temporary table.
2617 */
2618 if( pParent ){
2619 assert( pParent->pSrc->nSrc>parentTab );
2620 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00002621 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00002622 pParent->pSrc->a[parentTab].pSelect = 0;
2623 }
2624
drh1d83f052002-02-17 00:30:36 +00002625 /* The SELECT was successfully coded. Set the return code to 0
2626 ** to indicate no errors.
2627 */
2628 rc = 0;
2629
2630 /* Control jumps to here if an error is encountered above, or upon
2631 ** successful coding of the SELECT.
2632 */
2633select_end:
2634 sqliteAggregateInfoReset(pParse);
2635 return rc;
drhcce7d172000-05-31 15:34:51 +00002636}