blob: d3504c55f60a92c149167e9f92c6fb38c0cd5ed5 [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**
drhffbc3082004-05-21 01:29:06 +000015** $Id: select.c,v 1.172 2004/05/21 01:29:06 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.
drh428702d2004-05-18 22:38:31 +0000313**
314** FIX ME: Change this so that it uses the OP_MakeKey opcode
315** instead of OP_SortMakeKey. Delete the OP_SortMakeKey opcode.
316** All columns should have affinity NONE. Handle ASC versus
317** DESC sort order by defining a list of comparison functions to
318** be used by the OP_Sort opcode.
drhc926afb2002-06-20 03:38:26 +0000319*/
320static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
drhc926afb2002-06-20 03:38:26 +0000321 int i;
drhffbc3082004-05-21 01:29:06 +0000322#if 0
323 char *zSortOrder;
drhc926afb2002-06-20 03:38:26 +0000324 zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
325 if( zSortOrder==0 ) return;
drhffbc3082004-05-21 01:29:06 +0000326#endif
drhc926afb2002-06-20 03:38:26 +0000327 for(i=0; i<pOrderBy->nExpr; i++){
drhffbc3082004-05-21 01:29:06 +0000328#if 0
drh38640e12002-07-05 21:42:36 +0000329 int order = pOrderBy->a[i].sortOrder;
drh38640e12002-07-05 21:42:36 +0000330 int c;
drhd3d39e92004-05-20 22:16:29 +0000331 if( order==SQLITE_SO_ASC ){
332 c = 'A';
drh38640e12002-07-05 21:42:36 +0000333 }else{
drhd3d39e92004-05-20 22:16:29 +0000334 c = 'D';
drh38640e12002-07-05 21:42:36 +0000335 }
336 zSortOrder[i] = c;
drhffbc3082004-05-21 01:29:06 +0000337#endif
danielk19774adee202004-05-08 08:23:19 +0000338 sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
drhc926afb2002-06-20 03:38:26 +0000339 }
drhffbc3082004-05-21 01:29:06 +0000340#if 0
drhc926afb2002-06-20 03:38:26 +0000341 zSortOrder[pOrderBy->nExpr] = 0;
danielk19774adee202004-05-08 08:23:19 +0000342 sqlite3VdbeOp3(v, OP_SortMakeKey, pOrderBy->nExpr, 0, zSortOrder, P3_DYNAMIC);
drhffbc3082004-05-21 01:29:06 +0000343#endif
344 sqlite3VdbeAddOp(v, OP_MakeKey, pOrderBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +0000345 sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000346}
347
348/*
drh22827922000-06-06 17:27:05 +0000349** This routine generates the code for the inside of the inner loop
350** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000351**
drh38640e12002-07-05 21:42:36 +0000352** If srcTab and nColumn are both zero, then the pEList expressions
353** are evaluated in order to get the data for this row. If nColumn>0
354** then data is pulled from srcTab and pEList is used only to get the
355** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000356*/
357static int selectInnerLoop(
358 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000359 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000360 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000361 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000362 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000363 ExprList *pOrderBy, /* If not NULL, sort results using this key */
364 int distinct, /* If >=0, make sure results are distinct */
365 int eDest, /* How to dispose of the results */
366 int iParm, /* An argument to the disposal method */
367 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000368 int iBreak, /* Jump here to break out of the inner loop */
369 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000370){
371 Vdbe *v = pParse->pVdbe;
372 int i;
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 */
380 if( pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +0000381 if( p->iOffset>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000382 int addr = sqlite3VdbeCurrentAddr(v);
383 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2);
384 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhdf199a22002-06-14 22:38:41 +0000385 }
drh7b58dae2003-07-20 01:16:46 +0000386 if( p->iLimit>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000387 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhdf199a22002-06-14 22:38:41 +0000388 }
389 }
390
drh967e8b72000-06-21 13:59:10 +0000391 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000392 */
drh38640e12002-07-05 21:42:36 +0000393 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000394 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000395 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000396 }
drh38640e12002-07-05 21:42:36 +0000397 }else{
398 nColumn = pEList->nExpr;
399 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000400 sqlite3ExprCode(pParse, pEList->a[i].pExpr);
drh38640e12002-07-05 21:42:36 +0000401 }
drh22827922000-06-06 17:27:05 +0000402 }
403
drhdaffd0e2001-04-11 14:28:42 +0000404 /* If the DISTINCT keyword was present on the SELECT statement
405 ** and this row has been seen before, then do not make this row
406 ** part of the result.
drh22827922000-06-06 17:27:05 +0000407 */
drhf5905aa2002-05-26 20:54:33 +0000408 if( distinct>=0 && pEList && pEList->nExpr>0 ){
drh0bd1f4e2002-06-06 18:54:39 +0000409#if NULL_ALWAYS_DISTINCT
danielk19774adee202004-05-08 08:23:19 +0000410 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
drh0bd1f4e2002-06-06 18:54:39 +0000411#endif
drhd3d39e92004-05-20 22:16:29 +0000412 /* Deliberately leave the affinity string off of the following OP_MakeKey */
danielk19774adee202004-05-08 08:23:19 +0000413 sqlite3VdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
danielk19774adee202004-05-08 08:23:19 +0000414 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
415 sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
416 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
417 sqlite3VdbeAddOp(v, OP_String, 0, 0);
418 sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
drh22827922000-06-06 17:27:05 +0000419 }
drh82c3d632000-06-06 21:56:07 +0000420
drhc926afb2002-06-20 03:38:26 +0000421 switch( eDest ){
422 /* In this mode, write each query result to the key of the temporary
423 ** table iParm.
424 */
425 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000426 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000427 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000428 sqlite3VdbeAddOp(v, OP_String, 0, 0);
429 sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000430 break;
drh22827922000-06-06 17:27:05 +0000431 }
drh22827922000-06-06 17:27:05 +0000432
drhc926afb2002-06-20 03:38:26 +0000433 /* Store the result as data using a unique key.
434 */
435 case SRT_Table:
436 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000437 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000438 if( pOrderBy ){
439 pushOntoSorter(pParse, v, pOrderBy);
440 }else{
danielk19774adee202004-05-08 08:23:19 +0000441 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
442 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
443 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000444 }
445 break;
446 }
drh82c3d632000-06-06 21:56:07 +0000447
drhc926afb2002-06-20 03:38:26 +0000448 /* Construct a record from the query result, but instead of
449 ** saving that record, use it as a key to delete elements from
450 ** the temporary table iParm.
451 */
452 case SRT_Except: {
453 int addr;
danielk19774adee202004-05-08 08:23:19 +0000454 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000455 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000456 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
457 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000458 break;
459 }
drh5974a302000-06-07 14:42:26 +0000460
drhc926afb2002-06-20 03:38:26 +0000461 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
462 ** then there should be a single item on the stack. Write this
463 ** item into the set table with bogus data.
464 */
465 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000466 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000467 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000468
drhc926afb2002-06-20 03:38:26 +0000469 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000470 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
471 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
472 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000473 if( pOrderBy ){
474 pushOntoSorter(pParse, v, pOrderBy);
475 }else{
danielk1977e014a832004-05-17 10:48:57 +0000476 char const *affStr;
477 char aff = (iParm>>16)&0xFF;
478 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
479 affStr = sqlite3AffinityString(aff);
danielk197784ac9d02004-05-18 09:58:06 +0000480 sqlite3VdbeOp3(v, OP_MakeKey, 1, 0, affStr, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000481 sqlite3VdbeAddOp(v, OP_String, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000482 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000483 }
danielk19774adee202004-05-08 08:23:19 +0000484 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000485 break;
486 }
drh22827922000-06-06 17:27:05 +0000487
drhc926afb2002-06-20 03:38:26 +0000488 /* If this is a scalar select that is part of an expression, then
489 ** store the results in the appropriate memory cell and break out
490 ** of the scan loop.
491 */
492 case SRT_Mem: {
493 assert( nColumn==1 );
494 if( pOrderBy ){
495 pushOntoSorter(pParse, v, pOrderBy);
496 }else{
danielk19774adee202004-05-08 08:23:19 +0000497 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
498 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000499 }
500 break;
501 }
drh22827922000-06-06 17:27:05 +0000502
drhf46f9052002-06-22 02:33:38 +0000503 /* Send the data to the callback function.
504 */
505 case SRT_Callback:
506 case SRT_Sorter: {
507 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000508 sqlite3VdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000509 pushOntoSorter(pParse, v, pOrderBy);
510 }else{
511 assert( eDest==SRT_Callback );
danielk19774adee202004-05-08 08:23:19 +0000512 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000513 }
514 break;
515 }
516
drh142e30d2002-08-28 03:00:58 +0000517 /* Invoke a subroutine to handle the results. The subroutine itself
518 ** is responsible for popping the results off of the stack.
519 */
520 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000521 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000522 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000523 pushOntoSorter(pParse, v, pOrderBy);
524 }else{
danielk19774adee202004-05-08 08:23:19 +0000525 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhac82fcf2002-09-08 17:23:41 +0000526 }
drh142e30d2002-08-28 03:00:58 +0000527 break;
528 }
529
drhc926afb2002-06-20 03:38:26 +0000530 /* Discard the results. This is used for SELECT statements inside
531 ** the body of a TRIGGER. The purpose of such selects is to call
532 ** user-defined functions that have side effects. We do not care
533 ** about the actual results of the select.
534 */
drhc926afb2002-06-20 03:38:26 +0000535 default: {
drhf46f9052002-06-22 02:33:38 +0000536 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000537 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000538 break;
539 }
drh82c3d632000-06-06 21:56:07 +0000540 }
541 return 0;
542}
543
544/*
drhd8bc7082000-06-07 23:51:50 +0000545** If the inner loop was generated using a non-null pOrderBy argument,
546** then the results were placed in a sorter. After the loop is terminated
547** we need to run the sorter and output the results. The following
548** routine generates the code needed to do that.
549*/
drhc926afb2002-06-20 03:38:26 +0000550static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000551 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000552 Select *p, /* The SELECT statement */
553 Vdbe *v, /* Generate code into this VDBE */
554 int nColumn, /* Number of columns of data */
555 int eDest, /* Write the sorted results here */
556 int iParm /* Optional parameter associated with eDest */
557){
danielk19774adee202004-05-08 08:23:19 +0000558 int end1 = sqlite3VdbeMakeLabel(v);
559 int end2 = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000560 int addr;
drhffbc3082004-05-21 01:29:06 +0000561 KeyInfo *pInfo;
562 ExprList *pOrderBy;
563 int nCol, i;
564 sqlite *db = pParse->db;
565
drhf46f9052002-06-22 02:33:38 +0000566 if( eDest==SRT_Sorter ) return;
drhffbc3082004-05-21 01:29:06 +0000567 pOrderBy = p->pOrderBy;
568 nCol = pOrderBy->nExpr;
569 pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
570 if( pInfo==0 ) return;
571 pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
572 pInfo->nField = nCol;
573 for(i=0; i<nCol; i++){
574 pInfo->aColl[i] = db->pDfltColl;
575 pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
576 }
577 sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
danielk19774adee202004-05-08 08:23:19 +0000578 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
drh7b58dae2003-07-20 01:16:46 +0000579 if( p->iOffset>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000580 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4);
581 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
582 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
drhdf199a22002-06-14 22:38:41 +0000583 }
drh7b58dae2003-07-20 01:16:46 +0000584 if( p->iLimit>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000585 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, end2);
drhdf199a22002-06-14 22:38:41 +0000586 }
drhc926afb2002-06-20 03:38:26 +0000587 switch( eDest ){
588 case SRT_Callback: {
danielk19774adee202004-05-08 08:23:19 +0000589 sqlite3VdbeAddOp(v, OP_SortCallback, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000590 break;
591 }
592 case SRT_Table:
593 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000594 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
595 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
596 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000597 break;
598 }
599 case SRT_Set: {
600 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000601 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
602 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
603 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
drhd6861792004-05-20 03:02:47 +0000604 sqlite3VdbeOp3(v, OP_MakeKey, 1, 0, "n", P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000605 sqlite3VdbeAddOp(v, OP_String, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000606 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000607 break;
608 }
609 case SRT_Mem: {
610 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000611 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
612 sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
drhc926afb2002-06-20 03:38:26 +0000613 break;
614 }
drhac82fcf2002-09-08 17:23:41 +0000615 case SRT_Subroutine: {
616 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000617 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
618 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000619 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000620 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000621 }
danielk19774adee202004-05-08 08:23:19 +0000622 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
danielk197784ac9d02004-05-18 09:58:06 +0000623 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000624 break;
625 }
drhc926afb2002-06-20 03:38:26 +0000626 default: {
drhf46f9052002-06-22 02:33:38 +0000627 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000628 break;
629 }
630 }
danielk19774adee202004-05-08 08:23:19 +0000631 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
632 sqlite3VdbeResolveLabel(v, end2);
633 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
634 sqlite3VdbeResolveLabel(v, end1);
635 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000636}
637
638/*
drhfcb78a42003-01-18 20:11:05 +0000639** Generate code that will tell the VDBE the datatypes of
640** columns in the result set.
drhe78e8282003-01-19 03:59:45 +0000641**
642** This routine only generates code if the "PRAGMA show_datatypes=on"
643** has been executed. The datatypes are reported out in the azCol
644** parameter to the callback function. The first N azCol[] entries
645** are the names of the columns, and the second N entries are the
646** datatypes for the columns.
647**
648** The "datatype" for a result that is a column of a type is the
649** datatype definition extracted from the CREATE TABLE statement.
650** The datatype for an expression is either TEXT or NUMERIC. The
651** datatype for a ROWID field is INTEGER.
drhfcb78a42003-01-18 20:11:05 +0000652*/
653static void generateColumnTypes(
654 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000655 SrcList *pTabList, /* List of tables */
656 ExprList *pEList /* Expressions defining the result set */
657){
658 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000659 int i, j;
drhfcb78a42003-01-18 20:11:05 +0000660 for(i=0; i<pEList->nExpr; i++){
661 Expr *p = pEList->a[i].pExpr;
662 char *zType = 0;
663 if( p==0 ) continue;
664 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000665 Table *pTab;
drhfcb78a42003-01-18 20:11:05 +0000666 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000667 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
668 assert( j<pTabList->nSrc );
669 pTab = pTabList->a[j].pTab;
drhfcb78a42003-01-18 20:11:05 +0000670 if( iCol<0 ) iCol = pTab->iPKey;
671 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
672 if( iCol<0 ){
673 zType = "INTEGER";
674 }else{
675 zType = pTab->aCol[iCol].zType;
676 }
677 }else{
drhd3d39e92004-05-20 22:16:29 +0000678 zType = "ANY";
679 /** TODO: Perhaps something related to the affinity of the
680 ** exprsssion? */
drhfcb78a42003-01-18 20:11:05 +0000681 }
danielk19774adee202004-05-08 08:23:19 +0000682 sqlite3VdbeOp3(v, OP_ColumnName, i + pEList->nExpr, 0, zType, 0);
drhfcb78a42003-01-18 20:11:05 +0000683 }
684}
685
686/*
687** Generate code that will tell the VDBE the names of columns
688** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000689** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000690*/
drh832508b2002-03-02 17:04:07 +0000691static void generateColumnNames(
692 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000693 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000694 ExprList *pEList /* Expressions defining the result set */
695){
drhd8bc7082000-06-07 23:51:50 +0000696 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000697 int i, j;
drhfcabd462004-02-20 14:50:58 +0000698 sqlite *db = pParse->db;
699 int fullNames, shortNames;
700
drhd6502752004-02-16 03:44:01 +0000701 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000702 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000703 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000704 fullNames = (db->flags & SQLITE_FullColNames)!=0;
705 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
drh82c3d632000-06-06 21:56:07 +0000706 for(i=0; i<pEList->nExpr; i++){
707 Expr *p;
drhd6502752004-02-16 03:44:01 +0000708 int p2 = i==pEList->nExpr-1;
drh5a387052003-01-11 14:19:51 +0000709 p = pEList->a[i].pExpr;
710 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000711 if( pEList->a[i].zName ){
712 char *zName = pEList->a[i].zName;
danielk19774adee202004-05-08 08:23:19 +0000713 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000714 continue;
715 }
drhfa173a72002-07-10 21:26:00 +0000716 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000717 Table *pTab;
drh97665872002-02-13 23:22:53 +0000718 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000719 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000720 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
721 assert( j<pTabList->nSrc );
722 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000723 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000724 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000725 if( iCol<0 ){
726 zCol = "_ROWID_";
drhb1363202002-06-26 02:45:03 +0000727 }else{
728 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000729 }
drhfcabd462004-02-20 14:50:58 +0000730 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000731 int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
732 sqlite3VdbeCompressSpace(v, addr);
drhfcabd462004-02-20 14:50:58 +0000733 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000734 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000735 char *zTab;
736
drh6a3ea0e2003-05-02 14:32:12 +0000737 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000738 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000739 sqlite3SetString(&zName, zTab, ".", zCol, 0);
740 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000741 }else{
danielk19774adee202004-05-08 08:23:19 +0000742 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000743 }
drh6977fea2002-10-22 23:38:04 +0000744 }else if( p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000745 int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
746 sqlite3VdbeCompressSpace(v, addr);
drh1bee3d72001-10-15 00:44:35 +0000747 }else{
748 char zName[30];
749 assert( p->op!=TK_COLUMN || pTabList==0 );
750 sprintf(zName, "column%d", i+1);
danielk19774adee202004-05-08 08:23:19 +0000751 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000752 }
753 }
754}
755
756/*
drhd8bc7082000-06-07 23:51:50 +0000757** Name of the connection operator, used for error messages.
758*/
759static const char *selectOpName(int id){
760 char *z;
761 switch( id ){
762 case TK_ALL: z = "UNION ALL"; break;
763 case TK_INTERSECT: z = "INTERSECT"; break;
764 case TK_EXCEPT: z = "EXCEPT"; break;
765 default: z = "UNION"; break;
766 }
767 return z;
768}
769
770/*
drh315555c2002-10-20 15:53:03 +0000771** Forward declaration
772*/
773static int fillInColumnList(Parse*, Select*);
774
775/*
drh22f70c32002-02-18 01:17:00 +0000776** Given a SELECT statement, generate a Table structure that describes
777** the result set of that SELECT.
778*/
danielk19774adee202004-05-08 08:23:19 +0000779Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000780 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000781 int i, j;
drh22f70c32002-02-18 01:17:00 +0000782 ExprList *pEList;
drhb733d032004-01-24 20:18:12 +0000783 Column *aCol;
drh22f70c32002-02-18 01:17:00 +0000784
785 if( fillInColumnList(pParse, pSelect) ){
786 return 0;
787 }
788 pTab = sqliteMalloc( sizeof(Table) );
789 if( pTab==0 ){
790 return 0;
791 }
792 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
793 pEList = pSelect->pEList;
794 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000795 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000796 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh22f70c32002-02-18 01:17:00 +0000797 for(i=0; i<pTab->nCol; i++){
drhb733d032004-01-24 20:18:12 +0000798 Expr *p, *pR;
drh22f70c32002-02-18 01:17:00 +0000799 if( pEList->a[i].zName ){
drhb733d032004-01-24 20:18:12 +0000800 aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
801 }else if( (p=pEList->a[i].pExpr)->op==TK_DOT
802 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
803 int cnt;
danielk19774adee202004-05-08 08:23:19 +0000804 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
drhb733d032004-01-24 20:18:12 +0000805 for(j=cnt=0; j<i; j++){
danielk19774adee202004-05-08 08:23:19 +0000806 if( sqlite3StrICmp(aCol[j].zName, aCol[i].zName)==0 ){
drhb733d032004-01-24 20:18:12 +0000807 int n;
808 char zBuf[30];
809 sprintf(zBuf,"_%d",++cnt);
810 n = strlen(zBuf);
danielk1977e014a832004-05-17 10:48:57 +0000811 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf,n,0);
drhb733d032004-01-24 20:18:12 +0000812 j = -1;
813 }
814 }
815 }else if( p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000816 sqlite3SetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drh22f70c32002-02-18 01:17:00 +0000817 }else{
818 char zBuf[30];
819 sprintf(zBuf, "column%d", i+1);
820 pTab->aCol[i].zName = sqliteStrDup(zBuf);
821 }
danielk1977e014a832004-05-17 10:48:57 +0000822
823 /* Affinity is always NONE, as there is no type name. */
824 pTab->aCol[i].affinity = SQLITE_AFF_NONE;
drh22f70c32002-02-18 01:17:00 +0000825 }
826 pTab->iPKey = -1;
827 return pTab;
828}
829
830/*
drhad2d8302002-05-24 20:31:36 +0000831** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000832**
drhad3cab52002-05-24 02:04:32 +0000833** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh63eb5f22003-04-29 16:20:44 +0000834** defines the set of tables that should be scanned. For views,
835** fill pTabList->a[].pSelect with a copy of the SELECT statement
836** that implements the view. A copy is made of the view's SELECT
837** statement so that we can freely modify or delete that statement
838** without worrying about messing up the presistent representation
839** of the view.
drhd8bc7082000-06-07 23:51:50 +0000840**
drhad2d8302002-05-24 20:31:36 +0000841** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
842** on joins and the ON and USING clause of joins.
843**
844** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000845** for instances of the "*" operator or the TABLE.* operator.
846** If found, expand each "*" to be every column in every table
847** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000848**
849** Return 0 on success. If there are problems, leave an error message
850** in pParse and return non-zero.
851*/
852static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000853 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000854 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000855 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000856 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000857
858 if( p==0 || p->pSrc==0 ) return 1;
859 pTabList = p->pSrc;
860 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000861
862 /* Look up every table in the table list.
863 */
drhad3cab52002-05-24 02:04:32 +0000864 for(i=0; i<pTabList->nSrc; i++){
drhd8bc7082000-06-07 23:51:50 +0000865 if( pTabList->a[i].pTab ){
866 /* This routine has run before! No need to continue */
867 return 0;
868 }
drhdaffd0e2001-04-11 14:28:42 +0000869 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000870 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000871 assert( pTabList->a[i].pSelect!=0 );
drhad2d8302002-05-24 20:31:36 +0000872 if( pTabList->a[i].zAlias==0 ){
873 char zFakeName[60];
874 sprintf(zFakeName, "sqlite_subquery_%p_",
875 (void*)pTabList->a[i].pSelect);
danielk19774adee202004-05-08 08:23:19 +0000876 sqlite3SetString(&pTabList->a[i].zAlias, zFakeName, 0);
drhad2d8302002-05-24 20:31:36 +0000877 }
drh22f70c32002-02-18 01:17:00 +0000878 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000879 sqlite3ResultSetOfSelect(pParse, pTabList->a[i].zAlias,
drh22f70c32002-02-18 01:17:00 +0000880 pTabList->a[i].pSelect);
881 if( pTab==0 ){
882 return 1;
883 }
drh5cf590c2003-04-24 01:45:04 +0000884 /* The isTransient flag indicates that the Table structure has been
885 ** dynamically allocated and may be freed at any time. In other words,
886 ** pTab is not pointing to a persistent table structure that defines
887 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000888 pTab->isTransient = 1;
889 }else{
drha76b5df2002-02-23 02:32:10 +0000890 /* An ordinary table or view name in the FROM clause */
891 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000892 sqlite3LocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
drha76b5df2002-02-23 02:32:10 +0000893 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000894 return 1;
895 }
drha76b5df2002-02-23 02:32:10 +0000896 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +0000897 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +0000898 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +0000899 return 1;
900 }
drh63eb5f22003-04-29 16:20:44 +0000901 /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
902 ** view within a view. The SELECT structure has already been
903 ** copied by the outer view so we can skip the copy step here
904 ** in the inner view.
905 */
906 if( pTabList->a[i].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +0000907 pTabList->a[i].pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +0000908 }
drha76b5df2002-02-23 02:32:10 +0000909 }
drhd8bc7082000-06-07 23:51:50 +0000910 }
911 }
912
drhad2d8302002-05-24 20:31:36 +0000913 /* Process NATURAL keywords, and ON and USING clauses of joins.
914 */
915 if( sqliteProcessJoin(pParse, p) ) return 1;
916
drh7c917d12001-12-16 20:05:05 +0000917 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000918 ** all columns in all tables. And for every TABLE.* insert the names
919 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000920 ** with the TK_ALL operator for each "*" that it found in the column list.
921 ** The following code just has to locate the TK_ALL expressions and expand
922 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000923 **
924 ** The first loop just checks to see if there are any "*" operators
925 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000926 */
drh7c917d12001-12-16 20:05:05 +0000927 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000928 Expr *pE = pEList->a[k].pExpr;
929 if( pE->op==TK_ALL ) break;
930 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
931 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000932 }
drh54473222002-04-04 02:10:55 +0000933 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000934 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000935 /*
936 ** If we get here it means the result set contains one or more "*"
937 ** operators that need to be expanded. Loop through each expression
938 ** in the result set and expand them one by one.
939 */
drh7c917d12001-12-16 20:05:05 +0000940 struct ExprList_item *a = pEList->a;
941 ExprList *pNew = 0;
942 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000943 Expr *pE = a[k].pExpr;
944 if( pE->op!=TK_ALL &&
945 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
946 /* This particular expression does not need to be expanded.
947 */
danielk19774adee202004-05-08 08:23:19 +0000948 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +0000949 pNew->a[pNew->nExpr-1].zName = a[k].zName;
950 a[k].pExpr = 0;
951 a[k].zName = 0;
952 }else{
drh54473222002-04-04 02:10:55 +0000953 /* This expression is a "*" or a "TABLE.*" and needs to be
954 ** expanded. */
955 int tableSeen = 0; /* Set to 1 when TABLE matches */
956 Token *pName; /* text of name of TABLE */
957 if( pE->op==TK_DOT && pE->pLeft ){
958 pName = &pE->pLeft->token;
959 }else{
960 pName = 0;
961 }
drhad3cab52002-05-24 02:04:32 +0000962 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000963 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000964 char *zTabName = pTabList->a[i].zAlias;
965 if( zTabName==0 || zTabName[0]==0 ){
966 zTabName = pTab->zName;
967 }
drhc754fa52002-05-27 03:25:51 +0000968 if( pName && (zTabName==0 || zTabName[0]==0 ||
danielk19774adee202004-05-08 08:23:19 +0000969 sqlite3StrNICmp(pName->z, zTabName, pName->n)!=0 ||
drhc754fa52002-05-27 03:25:51 +0000970 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +0000971 continue;
972 }
973 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +0000974 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000975 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +0000976 char *zName = pTab->aCol[j].zName;
977
978 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
979 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
980 /* In a NATURAL join, omit the join columns from the
981 ** table on the right */
982 continue;
983 }
danielk19774adee202004-05-08 08:23:19 +0000984 if( i>0 && sqlite3IdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
drhad2d8302002-05-24 20:31:36 +0000985 /* In a join with a USING clause, omit columns in the
986 ** using clause from the table on the right. */
987 continue;
988 }
danielk19774adee202004-05-08 08:23:19 +0000989 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +0000990 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +0000991 pRight->token.z = zName;
992 pRight->token.n = strlen(zName);
drh4b59ab52002-08-24 18:24:51 +0000993 pRight->token.dyn = 0;
drh4b59ab52002-08-24 18:24:51 +0000994 if( zTabName && pTabList->nSrc>1 ){
danielk19774adee202004-05-08 08:23:19 +0000995 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
996 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +0000997 if( pExpr==0 ) break;
drh4b59ab52002-08-24 18:24:51 +0000998 pLeft->token.z = zTabName;
999 pLeft->token.n = strlen(zTabName);
1000 pLeft->token.dyn = 0;
danielk19774adee202004-05-08 08:23:19 +00001001 sqlite3SetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
drh6977fea2002-10-22 23:38:04 +00001002 pExpr->span.n = strlen(pExpr->span.z);
1003 pExpr->span.dyn = 1;
1004 pExpr->token.z = 0;
1005 pExpr->token.n = 0;
1006 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001007 }else{
drh22f70c32002-02-18 01:17:00 +00001008 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001009 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001010 }
danielk19774adee202004-05-08 08:23:19 +00001011 pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001012 }
drh17e24df2001-11-06 14:10:41 +00001013 }
drh54473222002-04-04 02:10:55 +00001014 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +00001015 if( pName ){
danielk19774adee202004-05-08 08:23:19 +00001016 sqlite3ErrorMsg(pParse, "no such table: %T", pName);
drhf5db2d32002-06-06 23:42:27 +00001017 }else{
danielk19774adee202004-05-08 08:23:19 +00001018 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001019 }
drh54473222002-04-04 02:10:55 +00001020 rc = 1;
1021 }
drhd8bc7082000-06-07 23:51:50 +00001022 }
1023 }
danielk19774adee202004-05-08 08:23:19 +00001024 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001025 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001026 }
drh54473222002-04-04 02:10:55 +00001027 return rc;
drhd8bc7082000-06-07 23:51:50 +00001028}
1029
1030/*
drhff78bd22002-02-27 01:47:11 +00001031** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1032** in a select structure. It just sets the pointers to NULL. This
1033** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1034** pointer is not NULL, this routine is called recursively on that pointer.
1035**
1036** This routine is called on the Select structure that defines a
1037** VIEW in order to undo any bindings to tables. This is necessary
1038** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001039** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1040** will be left pointing to a deallocated Table structure after the
1041** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001042*/
danielk19774adee202004-05-08 08:23:19 +00001043void sqlite3SelectUnbind(Select *p){
drhff78bd22002-02-27 01:47:11 +00001044 int i;
drhad3cab52002-05-24 02:04:32 +00001045 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +00001046 Table *pTab;
1047 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +00001048 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +00001049 if( (pTab = pSrc->a[i].pTab)!=0 ){
1050 if( pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001051 sqlite3DeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001052 }
1053 pSrc->a[i].pTab = 0;
1054 if( pSrc->a[i].pSelect ){
danielk19774adee202004-05-08 08:23:19 +00001055 sqlite3SelectUnbind(pSrc->a[i].pSelect);
drhff78bd22002-02-27 01:47:11 +00001056 }
1057 }
1058 }
1059}
1060
1061/*
drhd8bc7082000-06-07 23:51:50 +00001062** This routine associates entries in an ORDER BY expression list with
1063** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001064** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001065** the top-level node is filled in with column number and the iTable
1066** value of the top-level node is filled with iTable parameter.
1067**
1068** If there are prior SELECT clauses, they are processed first. A match
1069** in an earlier SELECT takes precedence over a later SELECT.
1070**
1071** Any entry that does not match is flagged as an error. The number
1072** of errors is returned.
1073*/
1074static int matchOrderbyToColumn(
1075 Parse *pParse, /* A place to leave error messages */
1076 Select *pSelect, /* Match to result columns of this SELECT */
1077 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001078 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001079 int mustComplete /* If TRUE all ORDER BYs must match */
1080){
1081 int nErr = 0;
1082 int i, j;
1083 ExprList *pEList;
1084
drhdaffd0e2001-04-11 14:28:42 +00001085 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001086 if( mustComplete ){
1087 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1088 }
1089 if( fillInColumnList(pParse, pSelect) ){
1090 return 1;
1091 }
1092 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001093 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1094 return 1;
1095 }
drhd8bc7082000-06-07 23:51:50 +00001096 }
1097 pEList = pSelect->pEList;
1098 for(i=0; i<pOrderBy->nExpr; i++){
1099 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001100 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001101 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001102 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001103 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001104 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001105 "ORDER BY position %d should be between 1 and %d",
1106 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001107 nErr++;
1108 break;
1109 }
drhfcb78a42003-01-18 20:11:05 +00001110 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001111 iCol--;
1112 }
1113 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001114 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001115 char *zName, *zLabel;
1116 zName = pEList->a[j].zName;
1117 assert( pE->token.z );
1118 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
danielk19774adee202004-05-08 08:23:19 +00001119 sqlite3Dequote(zLabel);
1120 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001121 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001122 }
drh6e142f52000-06-08 13:36:40 +00001123 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001124 }
danielk19774adee202004-05-08 08:23:19 +00001125 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001126 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001127 }
1128 }
drhe4de1fe2002-06-02 16:09:01 +00001129 if( iCol>=0 ){
1130 pE->op = TK_COLUMN;
1131 pE->iColumn = iCol;
1132 pE->iTable = iTable;
1133 pOrderBy->a[i].done = 1;
1134 }
1135 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001136 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001137 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001138 nErr++;
1139 break;
1140 }
1141 }
1142 return nErr;
1143}
1144
1145/*
1146** Get a VDBE for the given parser context. Create a new one if necessary.
1147** If an error occurs, return NULL and leave a message in pParse.
1148*/
danielk19774adee202004-05-08 08:23:19 +00001149Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001150 Vdbe *v = pParse->pVdbe;
1151 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001152 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001153 }
drhd8bc7082000-06-07 23:51:50 +00001154 return v;
1155}
drhfcb78a42003-01-18 20:11:05 +00001156
drhd3d39e92004-05-20 22:16:29 +00001157#if 0 /***** This routine needs deleting *****/
danielk197784ac9d02004-05-18 09:58:06 +00001158static void multiSelectAffinity(Select *p, char *zAff){
1159 int i;
1160
1161 if( !p ) return;
1162 multiSelectAffinity(p->pPrior, zAff);
1163
1164 for(i=0; i<p->pEList->nExpr; i++){
1165 if( zAff[i]=='\0' ){
1166 zAff[i] = sqlite3ExprAffinity(p->pEList->a[i].pExpr);
1167 }
1168 }
1169}
drhd3d39e92004-05-20 22:16:29 +00001170#endif
danielk197784ac9d02004-05-18 09:58:06 +00001171
drhd8bc7082000-06-07 23:51:50 +00001172/*
drh7b58dae2003-07-20 01:16:46 +00001173** Compute the iLimit and iOffset fields of the SELECT based on the
1174** nLimit and nOffset fields. nLimit and nOffset hold the integers
1175** that appear in the original SQL statement after the LIMIT and OFFSET
1176** keywords. Or that hold -1 and 0 if those keywords are omitted.
1177** iLimit and iOffset are the integer memory register numbers for
1178** counters used to compute the limit and offset. If there is no
1179** limit and/or offset, then iLimit and iOffset are negative.
1180**
1181** This routine changes the values if iLimit and iOffset only if
1182** a limit or offset is defined by nLimit and nOffset. iLimit and
1183** iOffset should have been preset to appropriate default values
1184** (usually but not always -1) prior to calling this routine.
1185** Only if nLimit>=0 or nOffset>0 do the limit registers get
1186** redefined. The UNION ALL operator uses this property to force
1187** the reuse of the same limit and offset registers across multiple
1188** SELECT statements.
1189*/
1190static void computeLimitRegisters(Parse *pParse, Select *p){
1191 /*
1192 ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
1193 ** all rows. It is the same as no limit. If the comparision is
1194 ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
1195 ** "LIMIT -1" always shows all rows. There is some
1196 ** contraversy about what the correct behavior should be.
1197 ** The current implementation interprets "LIMIT 0" to mean
1198 ** no rows.
1199 */
1200 if( p->nLimit>=0 ){
1201 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001202 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001203 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001204 sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1205 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001206 p->iLimit = iMem;
1207 }
1208 if( p->nOffset>0 ){
1209 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001210 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001211 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001212 sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1213 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001214 p->iOffset = iMem;
1215 }
1216}
1217
1218/*
drhd3d39e92004-05-20 22:16:29 +00001219** Generate VDBE instructions that will open a transient table that
1220** will be used for an index or to store keyed results for a compound
1221** select. In other words, open a transient table that needs a
1222** KeyInfo structure. The number of columns in the KeyInfo is determined
1223** by the result set of the SELECT statement in the second argument.
1224**
1225** Make the new table a KeyAsData table if keyAsData is true.
1226*/
1227static void openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
1228 KeyInfo *pKeyInfo;
1229 int nColumn = p->pEList->nExpr;
1230 sqlite *db = pParse->db;
1231 int i;
1232 Vdbe *v = pParse->pVdbe;
1233
1234 pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
1235 if( pKeyInfo==0 ) return;
1236 pKeyInfo->nField = nColumn;
1237 for(i=0; i<nColumn; i++){
1238 pKeyInfo->aColl[i] = db->pDfltColl;
1239 }
drhffbc3082004-05-21 01:29:06 +00001240 sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drhd3d39e92004-05-20 22:16:29 +00001241 if( keyAsData ){
1242 sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1243 }
1244}
1245
1246/*
drh82c3d632000-06-06 21:56:07 +00001247** This routine is called to process a query that is really the union
1248** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001249**
drhe78e8282003-01-19 03:59:45 +00001250** "p" points to the right-most of the two queries. the query on the
1251** left is p->pPrior. The left query could also be a compound query
1252** in which case this routine will be called recursively.
1253**
1254** The results of the total query are to be written into a destination
1255** of type eDest with parameter iParm.
1256**
1257** Example 1: Consider a three-way compound SQL statement.
1258**
1259** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1260**
1261** This statement is parsed up as follows:
1262**
1263** SELECT c FROM t3
1264** |
1265** `-----> SELECT b FROM t2
1266** |
jplyon4b11c6d2004-01-19 04:57:53 +00001267** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001268**
1269** The arrows in the diagram above represent the Select.pPrior pointer.
1270** So if this routine is called with p equal to the t3 query, then
1271** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1272**
1273** Notice that because of the way SQLite parses compound SELECTs, the
1274** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001275*/
danielk197784ac9d02004-05-18 09:58:06 +00001276static int multiSelect(
1277 Parse *pParse,
1278 Select *p,
1279 int eDest,
1280 int iParm,
1281 char *aff /* If eDest is SRT_Union, the affinity string */
1282){
1283 int rc = SQLITE_OK; /* Success code from a subroutine */
drh10e5e3c2000-06-08 00:19:02 +00001284 Select *pPrior; /* Another SELECT immediately to our left */
1285 Vdbe *v; /* Generate code to this VDBE */
danielk197784ac9d02004-05-18 09:58:06 +00001286 char *affStr = 0;
1287
drhd3d39e92004-05-20 22:16:29 +00001288#if 0 /* NOT USED */
danielk197784ac9d02004-05-18 09:58:06 +00001289 if( !aff ){
1290 int len;
1291 rc = fillInColumnList(pParse, p);
1292 if( rc!=SQLITE_OK ){
1293 goto multi_select_end;
1294 }
1295 len = p->pEList->nExpr+1;
1296 affStr = (char *)sqliteMalloc(p->pEList->nExpr+1);
1297 if( !affStr ){
1298 rc = SQLITE_NOMEM;
1299 goto multi_select_end;
1300 }
1301 memset(affStr, (int)SQLITE_AFF_NUMERIC, len-1);
1302 aff = affStr;
1303 }
drhd3d39e92004-05-20 22:16:29 +00001304#endif
drh82c3d632000-06-06 21:56:07 +00001305
drh7b58dae2003-07-20 01:16:46 +00001306 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
1307 ** the last SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001308 */
danielk197784ac9d02004-05-18 09:58:06 +00001309 if( p==0 || p->pPrior==0 ){
1310 rc = 1;
1311 goto multi_select_end;
1312 }
drhd8bc7082000-06-07 23:51:50 +00001313 pPrior = p->pPrior;
1314 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001315 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001316 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001317 rc = 1;
1318 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001319 }
drh7b58dae2003-07-20 01:16:46 +00001320 if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
danielk19774adee202004-05-08 08:23:19 +00001321 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001322 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001323 rc = 1;
1324 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001325 }
drh82c3d632000-06-06 21:56:07 +00001326
drhd8bc7082000-06-07 23:51:50 +00001327 /* Make sure we have a valid query engine. If not, create a new one.
1328 */
danielk19774adee202004-05-08 08:23:19 +00001329 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001330 if( v==0 ){
1331 rc = 1;
1332 goto multi_select_end;
1333 }
drhd8bc7082000-06-07 23:51:50 +00001334
drh1cc3d752002-03-23 00:31:29 +00001335 /* Create the destination temporary table if necessary
1336 */
1337 if( eDest==SRT_TempTable ){
danielk1977b4964b72004-05-18 01:23:38 +00001338 assert( p->pEList );
danielk19774adee202004-05-08 08:23:19 +00001339 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00001340 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, p->pEList->nExpr);
drh1cc3d752002-03-23 00:31:29 +00001341 eDest = SRT_Table;
1342 }
1343
drhf46f9052002-06-22 02:33:38 +00001344 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001345 */
drh82c3d632000-06-06 21:56:07 +00001346 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001347 case TK_ALL: {
1348 if( p->pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +00001349 pPrior->nLimit = p->nLimit;
1350 pPrior->nOffset = p->nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001351 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1352 if( rc ){
1353 goto multi_select_end;
1354 }
drhf46f9052002-06-22 02:33:38 +00001355 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001356 p->iLimit = pPrior->iLimit;
1357 p->iOffset = pPrior->iOffset;
1358 p->nLimit = -1;
1359 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001360 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001361 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001362 if( rc ){
1363 goto multi_select_end;
1364 }
drhf46f9052002-06-22 02:33:38 +00001365 break;
1366 }
1367 /* For UNION ALL ... ORDER BY fall through to the next case */
1368 }
drh82c3d632000-06-06 21:56:07 +00001369 case TK_EXCEPT:
1370 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001371 int unionTab; /* Cursor number of the temporary table holding result */
1372 int op; /* One of the SRT_ operations to apply to self */
1373 int priorOp; /* The SRT_ operation to apply to prior selects */
drh7b58dae2003-07-20 01:16:46 +00001374 int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
drhc926afb2002-06-20 03:38:26 +00001375 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
drh82c3d632000-06-06 21:56:07 +00001376
drhd8bc7082000-06-07 23:51:50 +00001377 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh7b58dae2003-07-20 01:16:46 +00001378 if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
drhd8bc7082000-06-07 23:51:50 +00001379 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001380 ** right.
drhd8bc7082000-06-07 23:51:50 +00001381 */
drh82c3d632000-06-06 21:56:07 +00001382 unionTab = iParm;
1383 }else{
drhd8bc7082000-06-07 23:51:50 +00001384 /* We will need to create our own temporary table to hold the
1385 ** intermediate results.
1386 */
1387 unionTab = pParse->nTab++;
1388 if( p->pOrderBy
1389 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001390 rc = 1;
1391 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001392 }
drhd8bc7082000-06-07 23:51:50 +00001393 if( p->op!=TK_ALL ){
drhd3d39e92004-05-20 22:16:29 +00001394 openTempIndex(pParse, p, unionTab, 1);
drh345fda32001-01-15 22:51:08 +00001395 }else{
danielk19774adee202004-05-08 08:23:19 +00001396 sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001397 }
danielk197784ac9d02004-05-18 09:58:06 +00001398 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001399 }
drhd8bc7082000-06-07 23:51:50 +00001400
1401 /* Code the SELECT statements to our left
1402 */
danielk197784ac9d02004-05-18 09:58:06 +00001403 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
1404 if( rc ){
1405 goto multi_select_end;
1406 }
1407 if( p->op==TK_ALL ){
1408 sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, pPrior->pEList->nExpr);
1409 }
drhd8bc7082000-06-07 23:51:50 +00001410
1411 /* Code the current SELECT statement
1412 */
1413 switch( p->op ){
1414 case TK_EXCEPT: op = SRT_Except; break;
1415 case TK_UNION: op = SRT_Union; break;
1416 case TK_ALL: op = SRT_Table; break;
1417 }
drh82c3d632000-06-06 21:56:07 +00001418 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001419 pOrderBy = p->pOrderBy;
1420 p->pOrderBy = 0;
drh7b58dae2003-07-20 01:16:46 +00001421 nLimit = p->nLimit;
1422 p->nLimit = -1;
1423 nOffset = p->nOffset;
1424 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001425 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001426 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001427 p->pOrderBy = pOrderBy;
drh7b58dae2003-07-20 01:16:46 +00001428 p->nLimit = nLimit;
1429 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001430 if( rc ){
1431 goto multi_select_end;
1432 }
1433
drhd8bc7082000-06-07 23:51:50 +00001434
1435 /* Convert the data in the temporary table into whatever form
1436 ** it is that we currently need.
1437 */
drhc926afb2002-06-20 03:38:26 +00001438 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001439 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001440 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001441 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001442 generateColumnNames(pParse, 0, p->pEList);
1443 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001444 }
danielk19774adee202004-05-08 08:23:19 +00001445 iBreak = sqlite3VdbeMakeLabel(v);
1446 iCont = sqlite3VdbeMakeLabel(v);
1447 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001448 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001449 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001450 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001451 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001452 iCont, iBreak, 0);
1453 if( rc ){
1454 rc = 1;
1455 goto multi_select_end;
1456 }
danielk19774adee202004-05-08 08:23:19 +00001457 sqlite3VdbeResolveLabel(v, iCont);
1458 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1459 sqlite3VdbeResolveLabel(v, iBreak);
1460 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001461 if( p->pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00001462 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001463 }
drh82c3d632000-06-06 21:56:07 +00001464 }
1465 break;
1466 }
1467 case TK_INTERSECT: {
1468 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001469 int iCont, iBreak, iStart;
drh7b58dae2003-07-20 01:16:46 +00001470 int nLimit, nOffset;
drh82c3d632000-06-06 21:56:07 +00001471
drhd8bc7082000-06-07 23:51:50 +00001472 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001473 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001474 ** by allocating the tables we will need.
1475 */
drh82c3d632000-06-06 21:56:07 +00001476 tab1 = pParse->nTab++;
1477 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001478 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001479 rc = 1;
1480 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001481 }
drhd3d39e92004-05-20 22:16:29 +00001482 openTempIndex(pParse, p, tab1, 1);
danielk197784ac9d02004-05-18 09:58:06 +00001483 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001484
1485 /* Code the SELECTs to our left into temporary table "tab1".
1486 */
danielk197784ac9d02004-05-18 09:58:06 +00001487 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
1488 if( rc ){
1489 goto multi_select_end;
1490 }
drhd8bc7082000-06-07 23:51:50 +00001491
1492 /* Code the current SELECT into temporary table "tab2"
1493 */
drhd3d39e92004-05-20 22:16:29 +00001494 openTempIndex(pParse, p, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001495 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001496 nLimit = p->nLimit;
1497 p->nLimit = -1;
1498 nOffset = p->nOffset;
1499 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001500 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001501 p->pPrior = pPrior;
drh7b58dae2003-07-20 01:16:46 +00001502 p->nLimit = nLimit;
1503 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001504 if( rc ){
1505 goto multi_select_end;
1506 }
drhd8bc7082000-06-07 23:51:50 +00001507
1508 /* Generate code to take the intersection of the two temporary
1509 ** tables.
1510 */
drh82c3d632000-06-06 21:56:07 +00001511 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001512 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001513 generateColumnNames(pParse, 0, p->pEList);
1514 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001515 }
danielk19774adee202004-05-08 08:23:19 +00001516 iBreak = sqlite3VdbeMakeLabel(v);
1517 iCont = sqlite3VdbeMakeLabel(v);
1518 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001519 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001520 iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
1521 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001522 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001523 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001524 iCont, iBreak, 0);
1525 if( rc ){
1526 rc = 1;
1527 goto multi_select_end;
1528 }
danielk19774adee202004-05-08 08:23:19 +00001529 sqlite3VdbeResolveLabel(v, iCont);
1530 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1531 sqlite3VdbeResolveLabel(v, iBreak);
1532 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1533 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drhd8bc7082000-06-07 23:51:50 +00001534 if( p->pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00001535 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001536 }
drh82c3d632000-06-06 21:56:07 +00001537 break;
1538 }
1539 }
1540 assert( p->pEList && pPrior->pEList );
1541 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001542 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001543 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001544 rc = 1;
1545 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001546 }
danielk197784ac9d02004-05-18 09:58:06 +00001547
1548multi_select_end:
drhd3d39e92004-05-20 22:16:29 +00001549#if 0 /*** NOT USED ****/
danielk197784ac9d02004-05-18 09:58:06 +00001550 if( affStr ){
1551 if( rc!=SQLITE_OK ){
1552 sqliteFree(affStr);
1553 }else{
1554 multiSelectAffinity(p, affStr);
1555 sqlite3VdbeOp3(v, OP_Noop, 0, 0, affStr, P3_DYNAMIC);
1556 }
1557 }
drhd3d39e92004-05-20 22:16:29 +00001558#endif
danielk197784ac9d02004-05-18 09:58:06 +00001559 return rc;
drh22827922000-06-06 17:27:05 +00001560}
1561
1562/*
drh832508b2002-03-02 17:04:07 +00001563** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001564** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001565** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001566** unchanged.)
drh832508b2002-03-02 17:04:07 +00001567**
1568** This routine is part of the flattening procedure. A subquery
1569** whose result set is defined by pEList appears as entry in the
1570** FROM clause of a SELECT such that the VDBE cursor assigned to that
1571** FORM clause entry is iTable. This routine make the necessary
1572** changes to pExpr so that it refers directly to the source table
1573** of the subquery rather the result set of the subquery.
1574*/
drh6a3ea0e2003-05-02 14:32:12 +00001575static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1576static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001577 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001578 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1579 if( pExpr->iColumn<0 ){
1580 pExpr->op = TK_NULL;
1581 }else{
1582 Expr *pNew;
1583 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1584 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1585 pNew = pEList->a[pExpr->iColumn].pExpr;
1586 assert( pNew!=0 );
1587 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001588 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001589 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001590 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001591 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001592 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001593 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001594 pExpr->iTable = pNew->iTable;
1595 pExpr->iColumn = pNew->iColumn;
1596 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001597 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1598 sqlite3TokenCopy(&pExpr->span, &pNew->span);
drh50350a12004-02-13 16:22:22 +00001599 }
drh832508b2002-03-02 17:04:07 +00001600 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001601 substExpr(pExpr->pLeft, iTable, pEList);
1602 substExpr(pExpr->pRight, iTable, pEList);
1603 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001604 }
1605}
1606static void
drh6a3ea0e2003-05-02 14:32:12 +00001607substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001608 int i;
1609 if( pList==0 ) return;
1610 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001611 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001612 }
1613}
1614
1615/*
drh1350b032002-02-27 19:00:20 +00001616** This routine attempts to flatten subqueries in order to speed
1617** execution. It returns 1 if it makes changes and 0 if no flattening
1618** occurs.
1619**
1620** To understand the concept of flattening, consider the following
1621** query:
1622**
1623** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1624**
1625** The default way of implementing this query is to execute the
1626** subquery first and store the results in a temporary table, then
1627** run the outer query on that temporary table. This requires two
1628** passes over the data. Furthermore, because the temporary table
1629** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001630** optimized.
drh1350b032002-02-27 19:00:20 +00001631**
drh832508b2002-03-02 17:04:07 +00001632** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001633** a single flat select, like this:
1634**
1635** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1636**
1637** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001638** but only has to scan the data once. And because indices might
1639** exist on the table t1, a complete scan of the data might be
1640** avoided.
drh1350b032002-02-27 19:00:20 +00001641**
drh832508b2002-03-02 17:04:07 +00001642** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001643**
drh832508b2002-03-02 17:04:07 +00001644** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001645**
drh832508b2002-03-02 17:04:07 +00001646** (2) The subquery is not an aggregate or the outer query is not a join.
1647**
drh8af4d3a2003-05-06 20:35:16 +00001648** (3) The subquery is not the right operand of a left outer join, or
1649** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001650**
1651** (4) The subquery is not DISTINCT or the outer query is not a join.
1652**
1653** (5) The subquery is not DISTINCT or the outer query does not use
1654** aggregates.
1655**
1656** (6) The subquery does not use aggregates or the outer query is not
1657** DISTINCT.
1658**
drh08192d52002-04-30 19:20:28 +00001659** (7) The subquery has a FROM clause.
1660**
drhdf199a22002-06-14 22:38:41 +00001661** (8) The subquery does not use LIMIT or the outer query is not a join.
1662**
1663** (9) The subquery does not use LIMIT or the outer query does not use
1664** aggregates.
1665**
1666** (10) The subquery does not use aggregates or the outer query does not
1667** use LIMIT.
1668**
drh174b6192002-12-03 02:22:52 +00001669** (11) The subquery and the outer query do not both have ORDER BY clauses.
1670**
drh3fc673e2003-06-16 00:40:34 +00001671** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1672** subquery has no WHERE clause. (added by ticket #350)
1673**
drh832508b2002-03-02 17:04:07 +00001674** In this routine, the "p" parameter is a pointer to the outer query.
1675** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1676** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1677**
drh665de472003-03-31 13:36:09 +00001678** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001679** If flattening is attempted this routine returns 1.
1680**
1681** All of the expression analysis must occur on both the outer query and
1682** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001683*/
drh8c74a8c2002-08-25 19:20:40 +00001684static int flattenSubquery(
1685 Parse *pParse, /* The parsing context */
1686 Select *p, /* The parent or outer SELECT statement */
1687 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1688 int isAgg, /* True if outer SELECT uses aggregate functions */
1689 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1690){
drh0bb28102002-05-08 11:54:14 +00001691 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001692 SrcList *pSrc; /* The FROM clause of the outer query */
1693 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001694 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001695 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh832508b2002-03-02 17:04:07 +00001696 int i;
drh832508b2002-03-02 17:04:07 +00001697 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001698
drh832508b2002-03-02 17:04:07 +00001699 /* Check to see if flattening is permitted. Return 0 if not.
1700 */
1701 if( p==0 ) return 0;
1702 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001703 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001704 pSub = pSrc->a[iFrom].pSelect;
1705 assert( pSub!=0 );
1706 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001707 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001708 pSubSrc = pSub->pSrc;
1709 assert( pSubSrc );
drhc31c2eb2003-05-02 16:04:17 +00001710 if( pSubSrc->nSrc==0 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001711 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1712 return 0;
1713 }
drhd11d3822002-06-21 23:01:49 +00001714 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001715 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001716
drh8af4d3a2003-05-06 20:35:16 +00001717 /* Restriction 3: If the subquery is a join, make sure the subquery is
1718 ** not used as the right operand of an outer join. Examples of why this
1719 ** is not allowed:
1720 **
1721 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1722 **
1723 ** If we flatten the above, we would get
1724 **
1725 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1726 **
1727 ** which is not at all the same thing.
1728 */
1729 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1730 return 0;
1731 }
1732
drh3fc673e2003-06-16 00:40:34 +00001733 /* Restriction 12: If the subquery is the right operand of a left outer
1734 ** join, make sure the subquery has no WHERE clause.
1735 ** An examples of why this is not allowed:
1736 **
1737 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1738 **
1739 ** If we flatten the above, we would get
1740 **
1741 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1742 **
1743 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1744 ** effectively converts the OUTER JOIN into an INNER JOIN.
1745 */
1746 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1747 && pSub->pWhere!=0 ){
1748 return 0;
1749 }
1750
drh0bb28102002-05-08 11:54:14 +00001751 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001752 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001753 */
drhc31c2eb2003-05-02 16:04:17 +00001754
1755 /* Move all of the FROM elements of the subquery into the
1756 ** the FROM clause of the outer query. Before doing this, remember
1757 ** the cursor number for the original outer query FROM element in
1758 ** iParent. The iParent cursor will never be used. Subsequent code
1759 ** will scan expressions looking for iParent references and replace
1760 ** those references with expressions that resolve to the subquery FROM
1761 ** elements we are now copying in.
1762 */
drh6a3ea0e2003-05-02 14:32:12 +00001763 iParent = pSrc->a[iFrom].iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001764 {
1765 int nSubSrc = pSubSrc->nSrc;
drh8af4d3a2003-05-06 20:35:16 +00001766 int jointype = pSrc->a[iFrom].jointype;
drhc31c2eb2003-05-02 16:04:17 +00001767
1768 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001769 sqlite3DeleteTable(0, pSrc->a[iFrom].pTab);
drhc31c2eb2003-05-02 16:04:17 +00001770 }
drhf26e09c2003-05-31 16:21:12 +00001771 sqliteFree(pSrc->a[iFrom].zDatabase);
drhc31c2eb2003-05-02 16:04:17 +00001772 sqliteFree(pSrc->a[iFrom].zName);
1773 sqliteFree(pSrc->a[iFrom].zAlias);
1774 if( nSubSrc>1 ){
1775 int extra = nSubSrc - 1;
1776 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00001777 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00001778 }
1779 p->pSrc = pSrc;
1780 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1781 pSrc->a[i] = pSrc->a[i-extra];
1782 }
1783 }
1784 for(i=0; i<nSubSrc; i++){
1785 pSrc->a[i+iFrom] = pSubSrc->a[i];
1786 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1787 }
drh8af4d3a2003-05-06 20:35:16 +00001788 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00001789 }
1790
1791 /* Now begin substituting subquery result set expressions for
1792 ** references to the iParent in the outer query.
1793 **
1794 ** Example:
1795 **
1796 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1797 ** \ \_____________ subquery __________/ /
1798 ** \_____________________ outer query ______________________________/
1799 **
1800 ** We look at every expression in the outer query and every place we see
1801 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1802 */
drh6a3ea0e2003-05-02 14:32:12 +00001803 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001804 pList = p->pEList;
1805 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001806 Expr *pExpr;
1807 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1808 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001809 }
1810 }
drh1b2e0322002-03-03 02:49:51 +00001811 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00001812 substExprList(p->pGroupBy, iParent, pSub->pEList);
1813 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001814 }
drh174b6192002-12-03 02:22:52 +00001815 if( pSub->pOrderBy ){
1816 assert( p->pOrderBy==0 );
1817 p->pOrderBy = pSub->pOrderBy;
1818 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00001819 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00001820 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00001821 }
drh832508b2002-03-02 17:04:07 +00001822 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001823 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00001824 }else{
1825 pWhere = 0;
1826 }
1827 if( subqueryIsAgg ){
1828 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001829 p->pHaving = p->pWhere;
1830 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00001831 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001832 if( pSub->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001833 Expr *pHaving = sqlite3ExprDup(pSub->pHaving);
drh1b2e0322002-03-03 02:49:51 +00001834 if( p->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001835 p->pHaving = sqlite3Expr(TK_AND, p->pHaving, pHaving, 0);
drh1b2e0322002-03-03 02:49:51 +00001836 }else{
1837 p->pHaving = pHaving;
1838 }
1839 }
1840 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00001841 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00001842 }else if( p->pWhere==0 ){
1843 p->pWhere = pWhere;
1844 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001845 substExpr(p->pWhere, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001846 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001847 p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pWhere, 0);
drh832508b2002-03-02 17:04:07 +00001848 }
1849 }
drhc31c2eb2003-05-02 16:04:17 +00001850
1851 /* The flattened query is distinct if either the inner or the
1852 ** outer query is distinct.
1853 */
drh832508b2002-03-02 17:04:07 +00001854 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00001855
drhc31c2eb2003-05-02 16:04:17 +00001856 /* Transfer the limit expression from the subquery to the outer
1857 ** query.
1858 */
drhdf199a22002-06-14 22:38:41 +00001859 if( pSub->nLimit>=0 ){
1860 if( p->nLimit<0 ){
1861 p->nLimit = pSub->nLimit;
1862 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1863 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1864 }
1865 }
1866 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00001867
drhc31c2eb2003-05-02 16:04:17 +00001868 /* Finially, delete what is left of the subquery and return
1869 ** success.
1870 */
danielk19774adee202004-05-08 08:23:19 +00001871 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00001872 return 1;
1873}
drh1350b032002-02-27 19:00:20 +00001874
1875/*
drh9562b552002-02-19 15:00:07 +00001876** Analyze the SELECT statement passed in as an argument to see if it
1877** is a simple min() or max() query. If it is and this query can be
1878** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00001879** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00001880** simple min() or max() query, then return 0;
1881**
1882** A simply min() or max() query looks like this:
1883**
1884** SELECT min(a) FROM table;
1885** SELECT max(a) FROM table;
1886**
1887** The query may have only a single table in its FROM argument. There
1888** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1889** be the min() or max() of a single column of the table. The column
1890** in the min() or max() function must be indexed.
1891**
danielk19774adee202004-05-08 08:23:19 +00001892** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00001893** See the header comment on that routine for additional information.
1894*/
1895static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1896 Expr *pExpr;
1897 int iCol;
1898 Table *pTab;
1899 Index *pIdx;
1900 int base;
1901 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00001902 int seekOp;
1903 int cont;
drh6e175292004-03-13 14:00:36 +00001904 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00001905 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00001906 SrcList *pSrc;
1907
drh9562b552002-02-19 15:00:07 +00001908
1909 /* Check to see if this query is a simple min() or max() query. Return
1910 ** zero if it is not.
1911 */
1912 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00001913 pSrc = p->pSrc;
1914 if( pSrc->nSrc!=1 ) return 0;
1915 pEList = p->pEList;
1916 if( pEList->nExpr!=1 ) return 0;
1917 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00001918 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00001919 pList = pExpr->pList;
1920 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00001921 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00001922 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00001923 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00001924 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00001925 seekOp = OP_Last;
1926 }else{
1927 return 0;
1928 }
drh6e175292004-03-13 14:00:36 +00001929 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00001930 if( pExpr->op!=TK_COLUMN ) return 0;
1931 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00001932 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00001933
1934 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00001935 ** Check to make sure we have an index and make pIdx point to the
1936 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
1937 ** key column, no index is necessary so set pIdx to NULL. If no
1938 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00001939 */
1940 if( iCol<0 ){
1941 pIdx = 0;
1942 }else{
1943 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1944 assert( pIdx->nColumn>=1 );
1945 if( pIdx->aiColumn[0]==iCol ) break;
1946 }
1947 if( pIdx==0 ) return 0;
1948 }
1949
drhe5f50722003-07-19 00:44:14 +00001950 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00001951 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00001952 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00001953 */
danielk19774adee202004-05-08 08:23:19 +00001954 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00001955 if( v==0 ) return 0;
1956 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001957 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh9562b552002-02-19 15:00:07 +00001958 }
1959
drh0c37e632004-01-30 02:01:03 +00001960 /* If the output is destined for a temporary table, open that table.
1961 */
1962 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00001963 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00001964 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00001965 }
1966
drh17f71932002-02-21 12:01:27 +00001967 /* Generating code to find the min or the max. Basically all we have
1968 ** to do is find the first or the last entry in the chosen index. If
1969 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
1970 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00001971 */
danielk19774adee202004-05-08 08:23:19 +00001972 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00001973 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00001974 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00001975 if( pSrc->a[0].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +00001976 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00001977 sqlite3VdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
danielk1977b4964b72004-05-18 01:23:38 +00001978 sqlite3VdbeAddOp(v, OP_SetNumColumns, base, pTab->nCol);
drh6e175292004-03-13 14:00:36 +00001979 }
danielk19774adee202004-05-08 08:23:19 +00001980 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00001981 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00001982 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00001983 }else{
danielk19774adee202004-05-08 08:23:19 +00001984 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00001985 sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum,
1986 (char*)&pIdx->keyInfo, P3_KEYINFO);
danielk19774adee202004-05-08 08:23:19 +00001987 sqlite3VdbeAddOp(v, seekOp, base+1, 0);
1988 sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
1989 sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
drh7cf6e4d2004-05-19 14:56:55 +00001990 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00001991 }
drh5cf8e8c2002-02-19 22:42:05 +00001992 eList.nExpr = 1;
1993 memset(&eListItem, 0, sizeof(eListItem));
1994 eList.a = &eListItem;
1995 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00001996 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00001997 sqlite3VdbeResolveLabel(v, cont);
1998 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00001999
drh9562b552002-02-19 15:00:07 +00002000 return 1;
2001}
2002
2003/*
drh9bb61fe2000-06-05 16:01:39 +00002004** Generate code for the given SELECT statement.
2005**
drhfef52082000-06-06 01:50:43 +00002006** The results are distributed in various ways depending on the
2007** value of eDest and iParm.
2008**
2009** eDest Value Result
2010** ------------ -------------------------------------------
2011** SRT_Callback Invoke the callback for each row of the result.
2012**
2013** SRT_Mem Store first result in memory cell iParm
2014**
danielk1977e014a832004-05-17 10:48:57 +00002015** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002016**
drh82c3d632000-06-06 21:56:07 +00002017** SRT_Union Store results as a key in a temporary table iParm
2018**
jplyon4b11c6d2004-01-19 04:57:53 +00002019** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002020**
2021** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002022**
drhe78e8282003-01-19 03:59:45 +00002023** The table above is incomplete. Additional eDist value have be added
2024** since this comment was written. See the selectInnerLoop() function for
2025** a complete listing of the allowed values of eDest and their meanings.
2026**
drh9bb61fe2000-06-05 16:01:39 +00002027** This routine returns the number of errors. If any errors are
2028** encountered, then an appropriate error message is left in
2029** pParse->zErrMsg.
2030**
2031** This routine does NOT free the Select structure passed in. The
2032** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002033**
2034** The pParent, parentTab, and *pParentAgg fields are filled in if this
2035** SELECT is a subquery. This routine may try to combine this SELECT
2036** with its parent to form a single flat query. In so doing, it might
2037** change the parent query from a non-aggregate to an aggregate query.
2038** For that reason, the pParentAgg flag is passed as a pointer, so it
2039** can be changed.
drhe78e8282003-01-19 03:59:45 +00002040**
2041** Example 1: The meaning of the pParent parameter.
2042**
2043** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2044** \ \_______ subquery _______/ /
2045** \ /
2046** \____________________ outer query ___________________/
2047**
2048** This routine is called for the outer query first. For that call,
2049** pParent will be NULL. During the processing of the outer query, this
2050** routine is called recursively to handle the subquery. For the recursive
2051** call, pParent will point to the outer query. Because the subquery is
2052** the second element in a three-way join, the parentTab parameter will
2053** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002054*/
danielk19774adee202004-05-08 08:23:19 +00002055int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002056 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002057 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002058 int eDest, /* How to dispose of the results */
2059 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002060 Select *pParent, /* Another SELECT for which this is a sub-query */
2061 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002062 int *pParentAgg, /* True if pParent uses aggregate functions */
2063 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002064){
drhd8bc7082000-06-07 23:51:50 +00002065 int i;
drhcce7d172000-05-31 15:34:51 +00002066 WhereInfo *pWInfo;
2067 Vdbe *v;
2068 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002069 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002070 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002071 Expr *pWhere; /* The WHERE clause. May be NULL */
2072 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002073 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2074 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002075 int isDistinct; /* True if the DISTINCT keyword is present */
2076 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002077 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00002078
danielk19776f8a5032004-05-10 10:34:51 +00002079 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002080 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002081
drh82c3d632000-06-06 21:56:07 +00002082 /* If there is are a sequence of queries, do the earlier ones first.
2083 */
2084 if( p->pPrior ){
danielk197784ac9d02004-05-18 09:58:06 +00002085 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002086 }
2087
2088 /* Make local copies of the parameters for this query.
2089 */
drh9bb61fe2000-06-05 16:01:39 +00002090 pTabList = p->pSrc;
2091 pWhere = p->pWhere;
2092 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00002093 pGroupBy = p->pGroupBy;
2094 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00002095 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00002096
drh6a3ea0e2003-05-02 14:32:12 +00002097 /* Allocate VDBE cursors for each table in the FROM clause
drh10e5e3c2000-06-08 00:19:02 +00002098 */
danielk19774adee202004-05-08 08:23:19 +00002099 sqlite3SrcListAssignCursors(pParse, pTabList);
drh10e5e3c2000-06-08 00:19:02 +00002100
drh9bb61fe2000-06-05 16:01:39 +00002101 /*
2102 ** Do not even attempt to generate any code if we have already seen
2103 ** errors before this routine starts.
2104 */
drh1d83f052002-02-17 00:30:36 +00002105 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002106
drhe78e8282003-01-19 03:59:45 +00002107 /* Expand any "*" terms in the result set. (For example the "*" in
2108 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
2109 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00002110 */
drhd8bc7082000-06-07 23:51:50 +00002111 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00002112 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002113 }
drhad2d8302002-05-24 20:31:36 +00002114 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00002115 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00002116 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002117
drh22827922000-06-06 17:27:05 +00002118 /* If writing to memory or generating a set
2119 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002120 */
drhfef52082000-06-06 01:50:43 +00002121 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002122 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002123 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002124 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002125 }
2126
drhc926afb2002-06-20 03:38:26 +00002127 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002128 */
drhc926afb2002-06-20 03:38:26 +00002129 switch( eDest ){
2130 case SRT_Union:
2131 case SRT_Except:
2132 case SRT_Discard:
2133 pOrderBy = 0;
2134 break;
2135 default:
2136 break;
drh22827922000-06-06 17:27:05 +00002137 }
2138
drh10e5e3c2000-06-08 00:19:02 +00002139 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002140 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002141 **
drh967e8b72000-06-21 13:59:10 +00002142 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002143 */
drh4794b982000-06-06 13:54:14 +00002144 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002145 if( sqlite3ExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002146 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002147 }
danielk19774adee202004-05-08 08:23:19 +00002148 if( sqlite3ExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002149 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002150 }
2151 }
drhcce7d172000-05-31 15:34:51 +00002152 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002153 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00002154 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002155 }
danielk19774adee202004-05-08 08:23:19 +00002156 if( sqlite3ExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00002157 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002158 }
2159 }
drhc66c5a22002-12-03 02:34:49 +00002160 if( pHaving ){
2161 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002162 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
drhc66c5a22002-12-03 02:34:49 +00002163 goto select_end;
2164 }
danielk19774adee202004-05-08 08:23:19 +00002165 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pHaving) ){
drhc66c5a22002-12-03 02:34:49 +00002166 goto select_end;
2167 }
danielk19774adee202004-05-08 08:23:19 +00002168 if( sqlite3ExprCheck(pParse, pHaving, 1, &isAgg) ){
drhc66c5a22002-12-03 02:34:49 +00002169 goto select_end;
2170 }
2171 }
drhcce7d172000-05-31 15:34:51 +00002172 if( pOrderBy ){
2173 for(i=0; i<pOrderBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002174 int iCol;
drh22827922000-06-06 17:27:05 +00002175 Expr *pE = pOrderBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002176 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2177 sqlite3ExprDelete(pE);
2178 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh88eee382003-01-31 17:16:36 +00002179 }
danielk19774adee202004-05-08 08:23:19 +00002180 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh88eee382003-01-31 17:16:36 +00002181 goto select_end;
2182 }
danielk19774adee202004-05-08 08:23:19 +00002183 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh88eee382003-01-31 17:16:36 +00002184 goto select_end;
2185 }
danielk19774adee202004-05-08 08:23:19 +00002186 if( sqlite3ExprIsConstant(pE) ){
2187 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2188 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002189 "ORDER BY terms must not be non-integer constants");
drhe4de1fe2002-06-02 16:09:01 +00002190 goto select_end;
2191 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002192 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002193 "ORDER BY column number %d out of range - should be "
drhe4de1fe2002-06-02 16:09:01 +00002194 "between 1 and %d", iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00002195 goto select_end;
2196 }
drhcce7d172000-05-31 15:34:51 +00002197 }
2198 }
2199 }
drh22827922000-06-06 17:27:05 +00002200 if( pGroupBy ){
2201 for(i=0; i<pGroupBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002202 int iCol;
drh22827922000-06-06 17:27:05 +00002203 Expr *pE = pGroupBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002204 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2205 sqlite3ExprDelete(pE);
2206 pE = pGroupBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00002207 }
danielk19774adee202004-05-08 08:23:19 +00002208 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00002209 goto select_end;
drh22827922000-06-06 17:27:05 +00002210 }
danielk19774adee202004-05-08 08:23:19 +00002211 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00002212 goto select_end;
drh22827922000-06-06 17:27:05 +00002213 }
danielk19774adee202004-05-08 08:23:19 +00002214 if( sqlite3ExprIsConstant(pE) ){
2215 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2216 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002217 "GROUP BY terms must not be non-integer constants");
drh88eee382003-01-31 17:16:36 +00002218 goto select_end;
2219 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002220 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002221 "GROUP BY column number %d out of range - should be "
drh88eee382003-01-31 17:16:36 +00002222 "between 1 and %d", iCol, pEList->nExpr);
drh88eee382003-01-31 17:16:36 +00002223 goto select_end;
2224 }
2225 }
drh22827922000-06-06 17:27:05 +00002226 }
2227 }
drhcce7d172000-05-31 15:34:51 +00002228
drhd820cb12002-02-18 03:21:45 +00002229 /* Begin generating code.
2230 */
danielk19774adee202004-05-08 08:23:19 +00002231 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002232 if( v==0 ) goto select_end;
2233
drhe78e8282003-01-19 03:59:45 +00002234 /* Identify column names if we will be using them in a callback. This
2235 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002236 */
2237 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002238 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002239 }
2240
drhd3d39e92004-05-20 22:16:29 +00002241#if 1 /* I do not think we need the following code any more.... */
danielk197784ac9d02004-05-18 09:58:06 +00002242 /* If the destination is SRT_Union, then set the number of columns in
2243 ** the records that will be inserted into the temporary table. The caller
2244 ** couldn't do this, in case the select statement is of the form
2245 ** "SELECT * FROM ....".
2246 **
2247 ** We need to do this before we start inserting records into the
2248 ** temporary table (which has had OP_KeyAsData executed on it), because
2249 ** it is required by the key comparison function. So do it now, even
2250 ** though this means that OP_SetNumColumns may be executed on the same
2251 ** cursor more than once.
2252 */
2253 if( eDest==SRT_Union ){
2254 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
2255 }
drhd3d39e92004-05-20 22:16:29 +00002256#endif
danielk197784ac9d02004-05-18 09:58:06 +00002257
drhd820cb12002-02-18 03:21:45 +00002258 /* Generate code for all sub-queries in the FROM clause
2259 */
drhad3cab52002-05-24 02:04:32 +00002260 for(i=0; i<pTabList->nSrc; i++){
drh5cf590c2003-04-24 01:45:04 +00002261 const char *zSavedAuthContext;
drhc31c2eb2003-05-02 16:04:17 +00002262 int needRestoreContext;
2263
drha76b5df2002-02-23 02:32:10 +00002264 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002265 if( pTabList->a[i].zName!=0 ){
2266 zSavedAuthContext = pParse->zAuthContext;
2267 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002268 needRestoreContext = 1;
2269 }else{
2270 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002271 }
danielk19774adee202004-05-08 08:23:19 +00002272 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
danielk197784ac9d02004-05-18 09:58:06 +00002273 pTabList->a[i].iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002274 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002275 pParse->zAuthContext = zSavedAuthContext;
2276 }
drh1b2e0322002-03-03 02:49:51 +00002277 pTabList = p->pSrc;
2278 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002279 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002280 pOrderBy = p->pOrderBy;
2281 }
drh1b2e0322002-03-03 02:49:51 +00002282 pGroupBy = p->pGroupBy;
2283 pHaving = p->pHaving;
2284 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002285 }
2286
drh6e175292004-03-13 14:00:36 +00002287 /* Check for the special case of a min() or max() function by itself
2288 ** in the result set.
2289 */
2290 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2291 rc = 0;
2292 goto select_end;
2293 }
2294
drh832508b2002-03-02 17:04:07 +00002295 /* Check to see if this is a subquery that can be "flattened" into its parent.
2296 ** If flattening is a possiblity, do so and return immediately.
2297 */
drh1b2e0322002-03-03 02:49:51 +00002298 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002299 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002300 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002301 return rc;
2302 }
drh832508b2002-03-02 17:04:07 +00002303
drh7b58dae2003-07-20 01:16:46 +00002304 /* Set the limiter.
2305 */
2306 computeLimitRegisters(pParse, p);
2307
drhe78e8282003-01-19 03:59:45 +00002308 /* Identify column types if we will be using a callback. This
2309 ** step is skipped if the output is going to a destination other
2310 ** than a callback.
drhe5f50722003-07-19 00:44:14 +00002311 **
2312 ** We have to do this separately from the creation of column names
2313 ** above because if the pTabList contains views then they will not
2314 ** have been resolved and we will not know the column types until
2315 ** now.
drhfcb78a42003-01-18 20:11:05 +00002316 */
2317 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002318 generateColumnTypes(pParse, pTabList, pEList);
drhfcb78a42003-01-18 20:11:05 +00002319 }
2320
drh2d0794e2002-03-03 03:03:52 +00002321 /* If the output is destined for a temporary table, open that table.
2322 */
2323 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002324 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002325 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002326 }
2327
drh22827922000-06-06 17:27:05 +00002328 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002329 */
drhd820cb12002-02-18 03:21:45 +00002330 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002331 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002332 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002333 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002334 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002335 if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002336 goto select_end;
drh22827922000-06-06 17:27:05 +00002337 }
2338 }
2339 if( pGroupBy ){
2340 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002341 if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002342 goto select_end;
drh22827922000-06-06 17:27:05 +00002343 }
2344 }
2345 }
danielk19774adee202004-05-08 08:23:19 +00002346 if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002347 goto select_end;
drh22827922000-06-06 17:27:05 +00002348 }
drh191b6902000-06-08 11:13:01 +00002349 if( pOrderBy ){
2350 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002351 if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002352 goto select_end;
drh191b6902000-06-08 11:13:01 +00002353 }
2354 }
2355 }
drhefb72512000-05-31 20:00:52 +00002356 }
2357
drh22827922000-06-06 17:27:05 +00002358 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002359 */
2360 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002361 sqlite3VdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002362 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002363 FuncDef *pFunc;
2364 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002365 sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_POINTER);
drhe5095352002-02-24 03:25:14 +00002366 }
2367 }
drh1bee3d72001-10-15 00:44:35 +00002368 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002369 sqlite3VdbeAddOp(v, OP_String, 0, 0);
2370 sqlite3VdbeAddOp(v, OP_AggFocus, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002371 }
drhcce7d172000-05-31 15:34:51 +00002372 }
2373
drh19a775c2000-06-05 18:54:46 +00002374 /* Initialize the memory cell to NULL
2375 */
drhfef52082000-06-06 01:50:43 +00002376 if( eDest==SRT_Mem ){
danielk19774adee202004-05-08 08:23:19 +00002377 sqlite3VdbeAddOp(v, OP_String, 0, 0);
2378 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002379 }
2380
drh832508b2002-03-02 17:04:07 +00002381 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002382 */
drh19a775c2000-06-05 18:54:46 +00002383 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002384 distinct = pParse->nTab++;
drhd3d39e92004-05-20 22:16:29 +00002385 openTempIndex(pParse, p, distinct, 0);
drh832508b2002-03-02 17:04:07 +00002386 }else{
2387 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002388 }
drh832508b2002-03-02 17:04:07 +00002389
2390 /* Begin the database scan
2391 */
danielk19774adee202004-05-08 08:23:19 +00002392 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
drh68d2e592002-08-04 00:52:38 +00002393 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002394 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002395
drh22827922000-06-06 17:27:05 +00002396 /* Use the standard inner loop if we are not dealing with
2397 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002398 */
drhda9d6c42000-05-31 18:20:14 +00002399 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002400 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002401 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002402 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002403 }
drhcce7d172000-05-31 15:34:51 +00002404 }
drhefb72512000-05-31 20:00:52 +00002405
drhe3184742002-06-19 14:27:05 +00002406 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002407 ** processing.
drhefb72512000-05-31 20:00:52 +00002408 */
drh22827922000-06-06 17:27:05 +00002409 else{
drh268380c2004-02-25 13:47:31 +00002410 AggExpr *pAgg;
drh22827922000-06-06 17:27:05 +00002411 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002412 int lbl1;
drh22827922000-06-06 17:27:05 +00002413 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002414 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
drh22827922000-06-06 17:27:05 +00002415 }
drhd3d39e92004-05-20 22:16:29 +00002416 /* No affinity string is attached to the following OP_MakeKey
2417 ** because we do not need to do any coercion of datatypes. */
danielk19774adee202004-05-08 08:23:19 +00002418 sqlite3VdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +00002419 lbl1 = sqlite3VdbeMakeLabel(v);
2420 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh268380c2004-02-25 13:47:31 +00002421 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2422 if( pAgg->isAgg ) continue;
danielk19774adee202004-05-08 08:23:19 +00002423 sqlite3ExprCode(pParse, pAgg->pExpr);
2424 sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002425 }
danielk19774adee202004-05-08 08:23:19 +00002426 sqlite3VdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002427 }
drh268380c2004-02-25 13:47:31 +00002428 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002429 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002430 int nExpr;
2431 FuncDef *pDef;
2432 if( !pAgg->isAgg ) continue;
2433 assert( pAgg->pFunc!=0 );
2434 assert( pAgg->pFunc->xStep!=0 );
2435 pDef = pAgg->pFunc;
2436 pE = pAgg->pExpr;
2437 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002438 assert( pE->op==TK_AGG_FUNCTION );
danielk19774adee202004-05-08 08:23:19 +00002439 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList, pDef->includeTypes);
2440 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
2441 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002442 }
drhcce7d172000-05-31 15:34:51 +00002443 }
2444
2445 /* End the database scan loop.
2446 */
danielk19774adee202004-05-08 08:23:19 +00002447 sqlite3WhereEnd(pWInfo);
drhcce7d172000-05-31 15:34:51 +00002448
drh22827922000-06-06 17:27:05 +00002449 /* If we are processing aggregates, we need to set up a second loop
2450 ** over all of the aggregate values and process them.
2451 */
2452 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002453 int endagg = sqlite3VdbeMakeLabel(v);
drh22827922000-06-06 17:27:05 +00002454 int startagg;
danielk19774adee202004-05-08 08:23:19 +00002455 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002456 pParse->useAgg = 1;
2457 if( pHaving ){
danielk19774adee202004-05-08 08:23:19 +00002458 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002459 }
drhdf199a22002-06-14 22:38:41 +00002460 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002461 iParm, startagg, endagg, aff) ){
drh1d83f052002-02-17 00:30:36 +00002462 goto select_end;
drh22827922000-06-06 17:27:05 +00002463 }
danielk19774adee202004-05-08 08:23:19 +00002464 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2465 sqlite3VdbeResolveLabel(v, endagg);
2466 sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002467 pParse->useAgg = 0;
2468 }
2469
drhcce7d172000-05-31 15:34:51 +00002470 /* If there is an ORDER BY clause, then we need to sort the results
2471 ** and send them to the callback one by one.
2472 */
2473 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00002474 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002475 }
drh6a535342001-10-19 16:44:56 +00002476
drhf620b4e2004-02-09 14:37:50 +00002477 /* If this was a subquery, we have now converted the subquery into a
2478 ** temporary table. So delete the subquery structure from the parent
2479 ** to prevent this subquery from being evaluated again and to force the
2480 ** the use of the temporary table.
2481 */
2482 if( pParent ){
2483 assert( pParent->pSrc->nSrc>parentTab );
2484 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00002485 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00002486 pParent->pSrc->a[parentTab].pSelect = 0;
2487 }
2488
drh1d83f052002-02-17 00:30:36 +00002489 /* The SELECT was successfully coded. Set the return code to 0
2490 ** to indicate no errors.
2491 */
2492 rc = 0;
2493
2494 /* Control jumps to here if an error is encountered above, or upon
2495 ** successful coding of the SELECT.
2496 */
2497select_end:
2498 sqliteAggregateInfoReset(pParse);
2499 return rc;
drhcce7d172000-05-31 15:34:51 +00002500}