blob: 5531c34b740a7529ed4f89ddccd12534065e7cb6 [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**
drh736c22b2004-05-21 02:14:24 +000015** $Id: select.c,v 1.173 2004/05/21 02:14:25 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;
drhc926afb2002-06-20 03:38:26 +0000322 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000323 sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
drhc926afb2002-06-20 03:38:26 +0000324 }
drhffbc3082004-05-21 01:29:06 +0000325 sqlite3VdbeAddOp(v, OP_MakeKey, pOrderBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +0000326 sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000327}
328
329/*
drh22827922000-06-06 17:27:05 +0000330** This routine generates the code for the inside of the inner loop
331** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000332**
drh38640e12002-07-05 21:42:36 +0000333** If srcTab and nColumn are both zero, then the pEList expressions
334** are evaluated in order to get the data for this row. If nColumn>0
335** then data is pulled from srcTab and pEList is used only to get the
336** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000337*/
338static int selectInnerLoop(
339 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000340 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000341 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000342 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000343 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000344 ExprList *pOrderBy, /* If not NULL, sort results using this key */
345 int distinct, /* If >=0, make sure results are distinct */
346 int eDest, /* How to dispose of the results */
347 int iParm, /* An argument to the disposal method */
348 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000349 int iBreak, /* Jump here to break out of the inner loop */
350 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000351){
352 Vdbe *v = pParse->pVdbe;
353 int i;
drh38640e12002-07-05 21:42:36 +0000354
drhdaffd0e2001-04-11 14:28:42 +0000355 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000356 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000357
drhdf199a22002-06-14 22:38:41 +0000358 /* If there was a LIMIT clause on the SELECT statement, then do the check
359 ** to see if this row should be output.
360 */
361 if( pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +0000362 if( p->iOffset>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000363 int addr = sqlite3VdbeCurrentAddr(v);
364 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2);
365 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhdf199a22002-06-14 22:38:41 +0000366 }
drh7b58dae2003-07-20 01:16:46 +0000367 if( p->iLimit>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000368 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhdf199a22002-06-14 22:38:41 +0000369 }
370 }
371
drh967e8b72000-06-21 13:59:10 +0000372 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000373 */
drh38640e12002-07-05 21:42:36 +0000374 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000375 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000376 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000377 }
drh38640e12002-07-05 21:42:36 +0000378 }else{
379 nColumn = pEList->nExpr;
380 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000381 sqlite3ExprCode(pParse, pEList->a[i].pExpr);
drh38640e12002-07-05 21:42:36 +0000382 }
drh22827922000-06-06 17:27:05 +0000383 }
384
drhdaffd0e2001-04-11 14:28:42 +0000385 /* If the DISTINCT keyword was present on the SELECT statement
386 ** and this row has been seen before, then do not make this row
387 ** part of the result.
drh22827922000-06-06 17:27:05 +0000388 */
drhf5905aa2002-05-26 20:54:33 +0000389 if( distinct>=0 && pEList && pEList->nExpr>0 ){
drh0bd1f4e2002-06-06 18:54:39 +0000390#if NULL_ALWAYS_DISTINCT
danielk19774adee202004-05-08 08:23:19 +0000391 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
drh0bd1f4e2002-06-06 18:54:39 +0000392#endif
drhd3d39e92004-05-20 22:16:29 +0000393 /* Deliberately leave the affinity string off of the following OP_MakeKey */
danielk19774adee202004-05-08 08:23:19 +0000394 sqlite3VdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
danielk19774adee202004-05-08 08:23:19 +0000395 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
396 sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
397 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
398 sqlite3VdbeAddOp(v, OP_String, 0, 0);
399 sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
drh22827922000-06-06 17:27:05 +0000400 }
drh82c3d632000-06-06 21:56:07 +0000401
drhc926afb2002-06-20 03:38:26 +0000402 switch( eDest ){
403 /* In this mode, write each query result to the key of the temporary
404 ** table iParm.
405 */
406 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000407 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000408 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000409 sqlite3VdbeAddOp(v, OP_String, 0, 0);
410 sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000411 break;
drh22827922000-06-06 17:27:05 +0000412 }
drh22827922000-06-06 17:27:05 +0000413
drhc926afb2002-06-20 03:38:26 +0000414 /* Store the result as data using a unique key.
415 */
416 case SRT_Table:
417 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000418 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000419 if( pOrderBy ){
420 pushOntoSorter(pParse, v, pOrderBy);
421 }else{
danielk19774adee202004-05-08 08:23:19 +0000422 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
423 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
424 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000425 }
426 break;
427 }
drh82c3d632000-06-06 21:56:07 +0000428
drhc926afb2002-06-20 03:38:26 +0000429 /* Construct a record from the query result, but instead of
430 ** saving that record, use it as a key to delete elements from
431 ** the temporary table iParm.
432 */
433 case SRT_Except: {
434 int addr;
danielk19774adee202004-05-08 08:23:19 +0000435 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000436 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000437 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
438 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000439 break;
440 }
drh5974a302000-06-07 14:42:26 +0000441
drhc926afb2002-06-20 03:38:26 +0000442 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
443 ** then there should be a single item on the stack. Write this
444 ** item into the set table with bogus data.
445 */
446 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000447 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000448 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000449
drhc926afb2002-06-20 03:38:26 +0000450 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000451 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
452 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
453 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000454 if( pOrderBy ){
455 pushOntoSorter(pParse, v, pOrderBy);
456 }else{
danielk1977e014a832004-05-17 10:48:57 +0000457 char const *affStr;
458 char aff = (iParm>>16)&0xFF;
459 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
460 affStr = sqlite3AffinityString(aff);
danielk197784ac9d02004-05-18 09:58:06 +0000461 sqlite3VdbeOp3(v, OP_MakeKey, 1, 0, affStr, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000462 sqlite3VdbeAddOp(v, OP_String, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000463 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000464 }
danielk19774adee202004-05-08 08:23:19 +0000465 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000466 break;
467 }
drh22827922000-06-06 17:27:05 +0000468
drhc926afb2002-06-20 03:38:26 +0000469 /* If this is a scalar select that is part of an expression, then
470 ** store the results in the appropriate memory cell and break out
471 ** of the scan loop.
472 */
473 case SRT_Mem: {
474 assert( nColumn==1 );
475 if( pOrderBy ){
476 pushOntoSorter(pParse, v, pOrderBy);
477 }else{
danielk19774adee202004-05-08 08:23:19 +0000478 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
479 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000480 }
481 break;
482 }
drh22827922000-06-06 17:27:05 +0000483
drhf46f9052002-06-22 02:33:38 +0000484 /* Send the data to the callback function.
485 */
486 case SRT_Callback:
487 case SRT_Sorter: {
488 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000489 sqlite3VdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000490 pushOntoSorter(pParse, v, pOrderBy);
491 }else{
492 assert( eDest==SRT_Callback );
danielk19774adee202004-05-08 08:23:19 +0000493 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000494 }
495 break;
496 }
497
drh142e30d2002-08-28 03:00:58 +0000498 /* Invoke a subroutine to handle the results. The subroutine itself
499 ** is responsible for popping the results off of the stack.
500 */
501 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000502 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000503 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000504 pushOntoSorter(pParse, v, pOrderBy);
505 }else{
danielk19774adee202004-05-08 08:23:19 +0000506 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhac82fcf2002-09-08 17:23:41 +0000507 }
drh142e30d2002-08-28 03:00:58 +0000508 break;
509 }
510
drhc926afb2002-06-20 03:38:26 +0000511 /* Discard the results. This is used for SELECT statements inside
512 ** the body of a TRIGGER. The purpose of such selects is to call
513 ** user-defined functions that have side effects. We do not care
514 ** about the actual results of the select.
515 */
drhc926afb2002-06-20 03:38:26 +0000516 default: {
drhf46f9052002-06-22 02:33:38 +0000517 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000518 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000519 break;
520 }
drh82c3d632000-06-06 21:56:07 +0000521 }
522 return 0;
523}
524
525/*
drhd8bc7082000-06-07 23:51:50 +0000526** If the inner loop was generated using a non-null pOrderBy argument,
527** then the results were placed in a sorter. After the loop is terminated
528** we need to run the sorter and output the results. The following
529** routine generates the code needed to do that.
530*/
drhc926afb2002-06-20 03:38:26 +0000531static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000532 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000533 Select *p, /* The SELECT statement */
534 Vdbe *v, /* Generate code into this VDBE */
535 int nColumn, /* Number of columns of data */
536 int eDest, /* Write the sorted results here */
537 int iParm /* Optional parameter associated with eDest */
538){
danielk19774adee202004-05-08 08:23:19 +0000539 int end1 = sqlite3VdbeMakeLabel(v);
540 int end2 = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000541 int addr;
drhffbc3082004-05-21 01:29:06 +0000542 KeyInfo *pInfo;
543 ExprList *pOrderBy;
544 int nCol, i;
545 sqlite *db = pParse->db;
546
drhf46f9052002-06-22 02:33:38 +0000547 if( eDest==SRT_Sorter ) return;
drhffbc3082004-05-21 01:29:06 +0000548 pOrderBy = p->pOrderBy;
549 nCol = pOrderBy->nExpr;
550 pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
551 if( pInfo==0 ) return;
552 pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
553 pInfo->nField = nCol;
554 for(i=0; i<nCol; i++){
555 pInfo->aColl[i] = db->pDfltColl;
556 pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
557 }
558 sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
danielk19774adee202004-05-08 08:23:19 +0000559 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
drh7b58dae2003-07-20 01:16:46 +0000560 if( p->iOffset>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000561 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4);
562 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
563 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
drhdf199a22002-06-14 22:38:41 +0000564 }
drh7b58dae2003-07-20 01:16:46 +0000565 if( p->iLimit>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000566 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, end2);
drhdf199a22002-06-14 22:38:41 +0000567 }
drhc926afb2002-06-20 03:38:26 +0000568 switch( eDest ){
569 case SRT_Callback: {
danielk19774adee202004-05-08 08:23:19 +0000570 sqlite3VdbeAddOp(v, OP_SortCallback, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000571 break;
572 }
573 case SRT_Table:
574 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000575 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
576 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
577 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000578 break;
579 }
580 case SRT_Set: {
581 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000582 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
583 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
584 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
drhd6861792004-05-20 03:02:47 +0000585 sqlite3VdbeOp3(v, OP_MakeKey, 1, 0, "n", P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000586 sqlite3VdbeAddOp(v, OP_String, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000587 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000588 break;
589 }
590 case SRT_Mem: {
591 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000592 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
593 sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
drhc926afb2002-06-20 03:38:26 +0000594 break;
595 }
drhac82fcf2002-09-08 17:23:41 +0000596 case SRT_Subroutine: {
597 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000598 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
599 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000600 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000601 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000602 }
danielk19774adee202004-05-08 08:23:19 +0000603 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
danielk197784ac9d02004-05-18 09:58:06 +0000604 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000605 break;
606 }
drhc926afb2002-06-20 03:38:26 +0000607 default: {
drhf46f9052002-06-22 02:33:38 +0000608 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000609 break;
610 }
611 }
danielk19774adee202004-05-08 08:23:19 +0000612 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
613 sqlite3VdbeResolveLabel(v, end2);
614 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
615 sqlite3VdbeResolveLabel(v, end1);
616 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000617}
618
619/*
drhfcb78a42003-01-18 20:11:05 +0000620** Generate code that will tell the VDBE the datatypes of
621** columns in the result set.
drhe78e8282003-01-19 03:59:45 +0000622**
623** This routine only generates code if the "PRAGMA show_datatypes=on"
624** has been executed. The datatypes are reported out in the azCol
625** parameter to the callback function. The first N azCol[] entries
626** are the names of the columns, and the second N entries are the
627** datatypes for the columns.
628**
629** The "datatype" for a result that is a column of a type is the
630** datatype definition extracted from the CREATE TABLE statement.
631** The datatype for an expression is either TEXT or NUMERIC. The
632** datatype for a ROWID field is INTEGER.
drhfcb78a42003-01-18 20:11:05 +0000633*/
634static void generateColumnTypes(
635 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000636 SrcList *pTabList, /* List of tables */
637 ExprList *pEList /* Expressions defining the result set */
638){
639 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000640 int i, j;
drhfcb78a42003-01-18 20:11:05 +0000641 for(i=0; i<pEList->nExpr; i++){
642 Expr *p = pEList->a[i].pExpr;
643 char *zType = 0;
644 if( p==0 ) continue;
645 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000646 Table *pTab;
drhfcb78a42003-01-18 20:11:05 +0000647 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000648 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
649 assert( j<pTabList->nSrc );
650 pTab = pTabList->a[j].pTab;
drhfcb78a42003-01-18 20:11:05 +0000651 if( iCol<0 ) iCol = pTab->iPKey;
652 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
653 if( iCol<0 ){
654 zType = "INTEGER";
655 }else{
656 zType = pTab->aCol[iCol].zType;
657 }
658 }else{
drh736c22b2004-05-21 02:14:24 +0000659 switch( sqlite3ExprType(p) ){
660 case SQLITE_AFF_TEXT: zType = "TEXT"; break;
661 case SQLITE_AFF_NUMERIC: zType = "NUMERIC"; break;
662 default: zType = "ANY"; break;
663 }
drhfcb78a42003-01-18 20:11:05 +0000664 }
danielk19774adee202004-05-08 08:23:19 +0000665 sqlite3VdbeOp3(v, OP_ColumnName, i + pEList->nExpr, 0, zType, 0);
drhfcb78a42003-01-18 20:11:05 +0000666 }
667}
668
669/*
670** Generate code that will tell the VDBE the names of columns
671** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000672** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000673*/
drh832508b2002-03-02 17:04:07 +0000674static void generateColumnNames(
675 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000676 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000677 ExprList *pEList /* Expressions defining the result set */
678){
drhd8bc7082000-06-07 23:51:50 +0000679 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000680 int i, j;
drhfcabd462004-02-20 14:50:58 +0000681 sqlite *db = pParse->db;
682 int fullNames, shortNames;
683
drhd6502752004-02-16 03:44:01 +0000684 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000685 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000686 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000687 fullNames = (db->flags & SQLITE_FullColNames)!=0;
688 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
drh82c3d632000-06-06 21:56:07 +0000689 for(i=0; i<pEList->nExpr; i++){
690 Expr *p;
drhd6502752004-02-16 03:44:01 +0000691 int p2 = i==pEList->nExpr-1;
drh5a387052003-01-11 14:19:51 +0000692 p = pEList->a[i].pExpr;
693 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000694 if( pEList->a[i].zName ){
695 char *zName = pEList->a[i].zName;
danielk19774adee202004-05-08 08:23:19 +0000696 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000697 continue;
698 }
drhfa173a72002-07-10 21:26:00 +0000699 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000700 Table *pTab;
drh97665872002-02-13 23:22:53 +0000701 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000702 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000703 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
704 assert( j<pTabList->nSrc );
705 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000706 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000707 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000708 if( iCol<0 ){
709 zCol = "_ROWID_";
drhb1363202002-06-26 02:45:03 +0000710 }else{
711 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000712 }
drhfcabd462004-02-20 14:50:58 +0000713 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000714 int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
715 sqlite3VdbeCompressSpace(v, addr);
drhfcabd462004-02-20 14:50:58 +0000716 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000717 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000718 char *zTab;
719
drh6a3ea0e2003-05-02 14:32:12 +0000720 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000721 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000722 sqlite3SetString(&zName, zTab, ".", zCol, 0);
723 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000724 }else{
danielk19774adee202004-05-08 08:23:19 +0000725 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000726 }
drh6977fea2002-10-22 23:38:04 +0000727 }else if( p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000728 int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
729 sqlite3VdbeCompressSpace(v, addr);
drh1bee3d72001-10-15 00:44:35 +0000730 }else{
731 char zName[30];
732 assert( p->op!=TK_COLUMN || pTabList==0 );
733 sprintf(zName, "column%d", i+1);
danielk19774adee202004-05-08 08:23:19 +0000734 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000735 }
736 }
737}
738
739/*
drhd8bc7082000-06-07 23:51:50 +0000740** Name of the connection operator, used for error messages.
741*/
742static const char *selectOpName(int id){
743 char *z;
744 switch( id ){
745 case TK_ALL: z = "UNION ALL"; break;
746 case TK_INTERSECT: z = "INTERSECT"; break;
747 case TK_EXCEPT: z = "EXCEPT"; break;
748 default: z = "UNION"; break;
749 }
750 return z;
751}
752
753/*
drh315555c2002-10-20 15:53:03 +0000754** Forward declaration
755*/
756static int fillInColumnList(Parse*, Select*);
757
758/*
drh22f70c32002-02-18 01:17:00 +0000759** Given a SELECT statement, generate a Table structure that describes
760** the result set of that SELECT.
761*/
danielk19774adee202004-05-08 08:23:19 +0000762Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000763 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000764 int i, j;
drh22f70c32002-02-18 01:17:00 +0000765 ExprList *pEList;
drhb733d032004-01-24 20:18:12 +0000766 Column *aCol;
drh22f70c32002-02-18 01:17:00 +0000767
768 if( fillInColumnList(pParse, pSelect) ){
769 return 0;
770 }
771 pTab = sqliteMalloc( sizeof(Table) );
772 if( pTab==0 ){
773 return 0;
774 }
775 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
776 pEList = pSelect->pEList;
777 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000778 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000779 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh22f70c32002-02-18 01:17:00 +0000780 for(i=0; i<pTab->nCol; i++){
drhb733d032004-01-24 20:18:12 +0000781 Expr *p, *pR;
drh22f70c32002-02-18 01:17:00 +0000782 if( pEList->a[i].zName ){
drhb733d032004-01-24 20:18:12 +0000783 aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
784 }else if( (p=pEList->a[i].pExpr)->op==TK_DOT
785 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
786 int cnt;
danielk19774adee202004-05-08 08:23:19 +0000787 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
drhb733d032004-01-24 20:18:12 +0000788 for(j=cnt=0; j<i; j++){
danielk19774adee202004-05-08 08:23:19 +0000789 if( sqlite3StrICmp(aCol[j].zName, aCol[i].zName)==0 ){
drhb733d032004-01-24 20:18:12 +0000790 int n;
791 char zBuf[30];
792 sprintf(zBuf,"_%d",++cnt);
793 n = strlen(zBuf);
danielk1977e014a832004-05-17 10:48:57 +0000794 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf,n,0);
drhb733d032004-01-24 20:18:12 +0000795 j = -1;
796 }
797 }
798 }else if( p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000799 sqlite3SetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drh22f70c32002-02-18 01:17:00 +0000800 }else{
801 char zBuf[30];
802 sprintf(zBuf, "column%d", i+1);
803 pTab->aCol[i].zName = sqliteStrDup(zBuf);
804 }
danielk1977e014a832004-05-17 10:48:57 +0000805
806 /* Affinity is always NONE, as there is no type name. */
807 pTab->aCol[i].affinity = SQLITE_AFF_NONE;
drh22f70c32002-02-18 01:17:00 +0000808 }
809 pTab->iPKey = -1;
810 return pTab;
811}
812
813/*
drhad2d8302002-05-24 20:31:36 +0000814** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000815**
drhad3cab52002-05-24 02:04:32 +0000816** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh63eb5f22003-04-29 16:20:44 +0000817** defines the set of tables that should be scanned. For views,
818** fill pTabList->a[].pSelect with a copy of the SELECT statement
819** that implements the view. A copy is made of the view's SELECT
820** statement so that we can freely modify or delete that statement
821** without worrying about messing up the presistent representation
822** of the view.
drhd8bc7082000-06-07 23:51:50 +0000823**
drhad2d8302002-05-24 20:31:36 +0000824** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
825** on joins and the ON and USING clause of joins.
826**
827** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000828** for instances of the "*" operator or the TABLE.* operator.
829** If found, expand each "*" to be every column in every table
830** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000831**
832** Return 0 on success. If there are problems, leave an error message
833** in pParse and return non-zero.
834*/
835static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000836 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000837 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000838 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000839 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000840
841 if( p==0 || p->pSrc==0 ) return 1;
842 pTabList = p->pSrc;
843 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000844
845 /* Look up every table in the table list.
846 */
drhad3cab52002-05-24 02:04:32 +0000847 for(i=0; i<pTabList->nSrc; i++){
drhd8bc7082000-06-07 23:51:50 +0000848 if( pTabList->a[i].pTab ){
849 /* This routine has run before! No need to continue */
850 return 0;
851 }
drhdaffd0e2001-04-11 14:28:42 +0000852 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000853 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000854 assert( pTabList->a[i].pSelect!=0 );
drhad2d8302002-05-24 20:31:36 +0000855 if( pTabList->a[i].zAlias==0 ){
856 char zFakeName[60];
857 sprintf(zFakeName, "sqlite_subquery_%p_",
858 (void*)pTabList->a[i].pSelect);
danielk19774adee202004-05-08 08:23:19 +0000859 sqlite3SetString(&pTabList->a[i].zAlias, zFakeName, 0);
drhad2d8302002-05-24 20:31:36 +0000860 }
drh22f70c32002-02-18 01:17:00 +0000861 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000862 sqlite3ResultSetOfSelect(pParse, pTabList->a[i].zAlias,
drh22f70c32002-02-18 01:17:00 +0000863 pTabList->a[i].pSelect);
864 if( pTab==0 ){
865 return 1;
866 }
drh5cf590c2003-04-24 01:45:04 +0000867 /* The isTransient flag indicates that the Table structure has been
868 ** dynamically allocated and may be freed at any time. In other words,
869 ** pTab is not pointing to a persistent table structure that defines
870 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000871 pTab->isTransient = 1;
872 }else{
drha76b5df2002-02-23 02:32:10 +0000873 /* An ordinary table or view name in the FROM clause */
874 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000875 sqlite3LocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
drha76b5df2002-02-23 02:32:10 +0000876 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000877 return 1;
878 }
drha76b5df2002-02-23 02:32:10 +0000879 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +0000880 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +0000881 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +0000882 return 1;
883 }
drh63eb5f22003-04-29 16:20:44 +0000884 /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
885 ** view within a view. The SELECT structure has already been
886 ** copied by the outer view so we can skip the copy step here
887 ** in the inner view.
888 */
889 if( pTabList->a[i].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +0000890 pTabList->a[i].pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +0000891 }
drha76b5df2002-02-23 02:32:10 +0000892 }
drhd8bc7082000-06-07 23:51:50 +0000893 }
894 }
895
drhad2d8302002-05-24 20:31:36 +0000896 /* Process NATURAL keywords, and ON and USING clauses of joins.
897 */
898 if( sqliteProcessJoin(pParse, p) ) return 1;
899
drh7c917d12001-12-16 20:05:05 +0000900 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000901 ** all columns in all tables. And for every TABLE.* insert the names
902 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000903 ** with the TK_ALL operator for each "*" that it found in the column list.
904 ** The following code just has to locate the TK_ALL expressions and expand
905 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000906 **
907 ** The first loop just checks to see if there are any "*" operators
908 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000909 */
drh7c917d12001-12-16 20:05:05 +0000910 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000911 Expr *pE = pEList->a[k].pExpr;
912 if( pE->op==TK_ALL ) break;
913 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
914 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000915 }
drh54473222002-04-04 02:10:55 +0000916 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000917 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000918 /*
919 ** If we get here it means the result set contains one or more "*"
920 ** operators that need to be expanded. Loop through each expression
921 ** in the result set and expand them one by one.
922 */
drh7c917d12001-12-16 20:05:05 +0000923 struct ExprList_item *a = pEList->a;
924 ExprList *pNew = 0;
925 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000926 Expr *pE = a[k].pExpr;
927 if( pE->op!=TK_ALL &&
928 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
929 /* This particular expression does not need to be expanded.
930 */
danielk19774adee202004-05-08 08:23:19 +0000931 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +0000932 pNew->a[pNew->nExpr-1].zName = a[k].zName;
933 a[k].pExpr = 0;
934 a[k].zName = 0;
935 }else{
drh54473222002-04-04 02:10:55 +0000936 /* This expression is a "*" or a "TABLE.*" and needs to be
937 ** expanded. */
938 int tableSeen = 0; /* Set to 1 when TABLE matches */
939 Token *pName; /* text of name of TABLE */
940 if( pE->op==TK_DOT && pE->pLeft ){
941 pName = &pE->pLeft->token;
942 }else{
943 pName = 0;
944 }
drhad3cab52002-05-24 02:04:32 +0000945 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000946 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000947 char *zTabName = pTabList->a[i].zAlias;
948 if( zTabName==0 || zTabName[0]==0 ){
949 zTabName = pTab->zName;
950 }
drhc754fa52002-05-27 03:25:51 +0000951 if( pName && (zTabName==0 || zTabName[0]==0 ||
danielk19774adee202004-05-08 08:23:19 +0000952 sqlite3StrNICmp(pName->z, zTabName, pName->n)!=0 ||
drhc754fa52002-05-27 03:25:51 +0000953 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +0000954 continue;
955 }
956 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +0000957 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000958 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +0000959 char *zName = pTab->aCol[j].zName;
960
961 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
962 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
963 /* In a NATURAL join, omit the join columns from the
964 ** table on the right */
965 continue;
966 }
danielk19774adee202004-05-08 08:23:19 +0000967 if( i>0 && sqlite3IdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
drhad2d8302002-05-24 20:31:36 +0000968 /* In a join with a USING clause, omit columns in the
969 ** using clause from the table on the right. */
970 continue;
971 }
danielk19774adee202004-05-08 08:23:19 +0000972 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +0000973 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +0000974 pRight->token.z = zName;
975 pRight->token.n = strlen(zName);
drh4b59ab52002-08-24 18:24:51 +0000976 pRight->token.dyn = 0;
drh4b59ab52002-08-24 18:24:51 +0000977 if( zTabName && pTabList->nSrc>1 ){
danielk19774adee202004-05-08 08:23:19 +0000978 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
979 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +0000980 if( pExpr==0 ) break;
drh4b59ab52002-08-24 18:24:51 +0000981 pLeft->token.z = zTabName;
982 pLeft->token.n = strlen(zTabName);
983 pLeft->token.dyn = 0;
danielk19774adee202004-05-08 08:23:19 +0000984 sqlite3SetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
drh6977fea2002-10-22 23:38:04 +0000985 pExpr->span.n = strlen(pExpr->span.z);
986 pExpr->span.dyn = 1;
987 pExpr->token.z = 0;
988 pExpr->token.n = 0;
989 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +0000990 }else{
drh22f70c32002-02-18 01:17:00 +0000991 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +0000992 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +0000993 }
danielk19774adee202004-05-08 08:23:19 +0000994 pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
drh7c917d12001-12-16 20:05:05 +0000995 }
drh17e24df2001-11-06 14:10:41 +0000996 }
drh54473222002-04-04 02:10:55 +0000997 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +0000998 if( pName ){
danielk19774adee202004-05-08 08:23:19 +0000999 sqlite3ErrorMsg(pParse, "no such table: %T", pName);
drhf5db2d32002-06-06 23:42:27 +00001000 }else{
danielk19774adee202004-05-08 08:23:19 +00001001 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001002 }
drh54473222002-04-04 02:10:55 +00001003 rc = 1;
1004 }
drhd8bc7082000-06-07 23:51:50 +00001005 }
1006 }
danielk19774adee202004-05-08 08:23:19 +00001007 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001008 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001009 }
drh54473222002-04-04 02:10:55 +00001010 return rc;
drhd8bc7082000-06-07 23:51:50 +00001011}
1012
1013/*
drhff78bd22002-02-27 01:47:11 +00001014** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1015** in a select structure. It just sets the pointers to NULL. This
1016** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1017** pointer is not NULL, this routine is called recursively on that pointer.
1018**
1019** This routine is called on the Select structure that defines a
1020** VIEW in order to undo any bindings to tables. This is necessary
1021** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001022** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1023** will be left pointing to a deallocated Table structure after the
1024** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001025*/
danielk19774adee202004-05-08 08:23:19 +00001026void sqlite3SelectUnbind(Select *p){
drhff78bd22002-02-27 01:47:11 +00001027 int i;
drhad3cab52002-05-24 02:04:32 +00001028 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +00001029 Table *pTab;
1030 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +00001031 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +00001032 if( (pTab = pSrc->a[i].pTab)!=0 ){
1033 if( pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001034 sqlite3DeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001035 }
1036 pSrc->a[i].pTab = 0;
1037 if( pSrc->a[i].pSelect ){
danielk19774adee202004-05-08 08:23:19 +00001038 sqlite3SelectUnbind(pSrc->a[i].pSelect);
drhff78bd22002-02-27 01:47:11 +00001039 }
1040 }
1041 }
1042}
1043
1044/*
drhd8bc7082000-06-07 23:51:50 +00001045** This routine associates entries in an ORDER BY expression list with
1046** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001047** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001048** the top-level node is filled in with column number and the iTable
1049** value of the top-level node is filled with iTable parameter.
1050**
1051** If there are prior SELECT clauses, they are processed first. A match
1052** in an earlier SELECT takes precedence over a later SELECT.
1053**
1054** Any entry that does not match is flagged as an error. The number
1055** of errors is returned.
1056*/
1057static int matchOrderbyToColumn(
1058 Parse *pParse, /* A place to leave error messages */
1059 Select *pSelect, /* Match to result columns of this SELECT */
1060 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001061 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001062 int mustComplete /* If TRUE all ORDER BYs must match */
1063){
1064 int nErr = 0;
1065 int i, j;
1066 ExprList *pEList;
1067
drhdaffd0e2001-04-11 14:28:42 +00001068 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001069 if( mustComplete ){
1070 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1071 }
1072 if( fillInColumnList(pParse, pSelect) ){
1073 return 1;
1074 }
1075 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001076 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1077 return 1;
1078 }
drhd8bc7082000-06-07 23:51:50 +00001079 }
1080 pEList = pSelect->pEList;
1081 for(i=0; i<pOrderBy->nExpr; i++){
1082 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001083 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001084 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001085 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001086 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001087 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001088 "ORDER BY position %d should be between 1 and %d",
1089 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001090 nErr++;
1091 break;
1092 }
drhfcb78a42003-01-18 20:11:05 +00001093 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001094 iCol--;
1095 }
1096 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001097 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001098 char *zName, *zLabel;
1099 zName = pEList->a[j].zName;
1100 assert( pE->token.z );
1101 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
danielk19774adee202004-05-08 08:23:19 +00001102 sqlite3Dequote(zLabel);
1103 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001104 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001105 }
drh6e142f52000-06-08 13:36:40 +00001106 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001107 }
danielk19774adee202004-05-08 08:23:19 +00001108 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001109 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001110 }
1111 }
drhe4de1fe2002-06-02 16:09:01 +00001112 if( iCol>=0 ){
1113 pE->op = TK_COLUMN;
1114 pE->iColumn = iCol;
1115 pE->iTable = iTable;
1116 pOrderBy->a[i].done = 1;
1117 }
1118 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001119 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001120 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001121 nErr++;
1122 break;
1123 }
1124 }
1125 return nErr;
1126}
1127
1128/*
1129** Get a VDBE for the given parser context. Create a new one if necessary.
1130** If an error occurs, return NULL and leave a message in pParse.
1131*/
danielk19774adee202004-05-08 08:23:19 +00001132Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001133 Vdbe *v = pParse->pVdbe;
1134 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001135 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001136 }
drhd8bc7082000-06-07 23:51:50 +00001137 return v;
1138}
drhfcb78a42003-01-18 20:11:05 +00001139
drhd3d39e92004-05-20 22:16:29 +00001140#if 0 /***** This routine needs deleting *****/
danielk197784ac9d02004-05-18 09:58:06 +00001141static void multiSelectAffinity(Select *p, char *zAff){
1142 int i;
1143
1144 if( !p ) return;
1145 multiSelectAffinity(p->pPrior, zAff);
1146
1147 for(i=0; i<p->pEList->nExpr; i++){
1148 if( zAff[i]=='\0' ){
1149 zAff[i] = sqlite3ExprAffinity(p->pEList->a[i].pExpr);
1150 }
1151 }
1152}
drhd3d39e92004-05-20 22:16:29 +00001153#endif
danielk197784ac9d02004-05-18 09:58:06 +00001154
drhd8bc7082000-06-07 23:51:50 +00001155/*
drh7b58dae2003-07-20 01:16:46 +00001156** Compute the iLimit and iOffset fields of the SELECT based on the
1157** nLimit and nOffset fields. nLimit and nOffset hold the integers
1158** that appear in the original SQL statement after the LIMIT and OFFSET
1159** keywords. Or that hold -1 and 0 if those keywords are omitted.
1160** iLimit and iOffset are the integer memory register numbers for
1161** counters used to compute the limit and offset. If there is no
1162** limit and/or offset, then iLimit and iOffset are negative.
1163**
1164** This routine changes the values if iLimit and iOffset only if
1165** a limit or offset is defined by nLimit and nOffset. iLimit and
1166** iOffset should have been preset to appropriate default values
1167** (usually but not always -1) prior to calling this routine.
1168** Only if nLimit>=0 or nOffset>0 do the limit registers get
1169** redefined. The UNION ALL operator uses this property to force
1170** the reuse of the same limit and offset registers across multiple
1171** SELECT statements.
1172*/
1173static void computeLimitRegisters(Parse *pParse, Select *p){
1174 /*
1175 ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
1176 ** all rows. It is the same as no limit. If the comparision is
1177 ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
1178 ** "LIMIT -1" always shows all rows. There is some
1179 ** contraversy about what the correct behavior should be.
1180 ** The current implementation interprets "LIMIT 0" to mean
1181 ** no rows.
1182 */
1183 if( p->nLimit>=0 ){
1184 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001185 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001186 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001187 sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1188 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001189 p->iLimit = iMem;
1190 }
1191 if( p->nOffset>0 ){
1192 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001193 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001194 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001195 sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1196 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001197 p->iOffset = iMem;
1198 }
1199}
1200
1201/*
drhd3d39e92004-05-20 22:16:29 +00001202** Generate VDBE instructions that will open a transient table that
1203** will be used for an index or to store keyed results for a compound
1204** select. In other words, open a transient table that needs a
1205** KeyInfo structure. The number of columns in the KeyInfo is determined
1206** by the result set of the SELECT statement in the second argument.
1207**
1208** Make the new table a KeyAsData table if keyAsData is true.
1209*/
1210static void openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
1211 KeyInfo *pKeyInfo;
drh736c22b2004-05-21 02:14:24 +00001212 int nColumn;
drhd3d39e92004-05-20 22:16:29 +00001213 sqlite *db = pParse->db;
1214 int i;
1215 Vdbe *v = pParse->pVdbe;
1216
drh736c22b2004-05-21 02:14:24 +00001217 if( fillInColumnList(pParse, p) ){
1218 return;
1219 }
1220 nColumn = p->pEList->nExpr;
drhd3d39e92004-05-20 22:16:29 +00001221 pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
1222 if( pKeyInfo==0 ) return;
1223 pKeyInfo->nField = nColumn;
1224 for(i=0; i<nColumn; i++){
1225 pKeyInfo->aColl[i] = db->pDfltColl;
1226 }
drhffbc3082004-05-21 01:29:06 +00001227 sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drhd3d39e92004-05-20 22:16:29 +00001228 if( keyAsData ){
1229 sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1230 }
1231}
1232
1233/*
drh82c3d632000-06-06 21:56:07 +00001234** This routine is called to process a query that is really the union
1235** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001236**
drhe78e8282003-01-19 03:59:45 +00001237** "p" points to the right-most of the two queries. the query on the
1238** left is p->pPrior. The left query could also be a compound query
1239** in which case this routine will be called recursively.
1240**
1241** The results of the total query are to be written into a destination
1242** of type eDest with parameter iParm.
1243**
1244** Example 1: Consider a three-way compound SQL statement.
1245**
1246** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1247**
1248** This statement is parsed up as follows:
1249**
1250** SELECT c FROM t3
1251** |
1252** `-----> SELECT b FROM t2
1253** |
jplyon4b11c6d2004-01-19 04:57:53 +00001254** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001255**
1256** The arrows in the diagram above represent the Select.pPrior pointer.
1257** So if this routine is called with p equal to the t3 query, then
1258** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1259**
1260** Notice that because of the way SQLite parses compound SELECTs, the
1261** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001262*/
danielk197784ac9d02004-05-18 09:58:06 +00001263static int multiSelect(
1264 Parse *pParse,
1265 Select *p,
1266 int eDest,
1267 int iParm,
1268 char *aff /* If eDest is SRT_Union, the affinity string */
1269){
1270 int rc = SQLITE_OK; /* Success code from a subroutine */
drh10e5e3c2000-06-08 00:19:02 +00001271 Select *pPrior; /* Another SELECT immediately to our left */
1272 Vdbe *v; /* Generate code to this VDBE */
danielk197784ac9d02004-05-18 09:58:06 +00001273 char *affStr = 0;
1274
drhd3d39e92004-05-20 22:16:29 +00001275#if 0 /* NOT USED */
danielk197784ac9d02004-05-18 09:58:06 +00001276 if( !aff ){
1277 int len;
1278 rc = fillInColumnList(pParse, p);
1279 if( rc!=SQLITE_OK ){
1280 goto multi_select_end;
1281 }
1282 len = p->pEList->nExpr+1;
1283 affStr = (char *)sqliteMalloc(p->pEList->nExpr+1);
1284 if( !affStr ){
1285 rc = SQLITE_NOMEM;
1286 goto multi_select_end;
1287 }
1288 memset(affStr, (int)SQLITE_AFF_NUMERIC, len-1);
1289 aff = affStr;
1290 }
drhd3d39e92004-05-20 22:16:29 +00001291#endif
drh82c3d632000-06-06 21:56:07 +00001292
drh7b58dae2003-07-20 01:16:46 +00001293 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
1294 ** the last SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001295 */
danielk197784ac9d02004-05-18 09:58:06 +00001296 if( p==0 || p->pPrior==0 ){
1297 rc = 1;
1298 goto multi_select_end;
1299 }
drhd8bc7082000-06-07 23:51:50 +00001300 pPrior = p->pPrior;
1301 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001302 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001303 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001304 rc = 1;
1305 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001306 }
drh7b58dae2003-07-20 01:16:46 +00001307 if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
danielk19774adee202004-05-08 08:23:19 +00001308 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001309 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001310 rc = 1;
1311 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001312 }
drh82c3d632000-06-06 21:56:07 +00001313
drhd8bc7082000-06-07 23:51:50 +00001314 /* Make sure we have a valid query engine. If not, create a new one.
1315 */
danielk19774adee202004-05-08 08:23:19 +00001316 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001317 if( v==0 ){
1318 rc = 1;
1319 goto multi_select_end;
1320 }
drhd8bc7082000-06-07 23:51:50 +00001321
drh1cc3d752002-03-23 00:31:29 +00001322 /* Create the destination temporary table if necessary
1323 */
1324 if( eDest==SRT_TempTable ){
danielk1977b4964b72004-05-18 01:23:38 +00001325 assert( p->pEList );
danielk19774adee202004-05-08 08:23:19 +00001326 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00001327 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, p->pEList->nExpr);
drh1cc3d752002-03-23 00:31:29 +00001328 eDest = SRT_Table;
1329 }
1330
drhf46f9052002-06-22 02:33:38 +00001331 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001332 */
drh82c3d632000-06-06 21:56:07 +00001333 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001334 case TK_ALL: {
1335 if( p->pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +00001336 pPrior->nLimit = p->nLimit;
1337 pPrior->nOffset = p->nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001338 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1339 if( rc ){
1340 goto multi_select_end;
1341 }
drhf46f9052002-06-22 02:33:38 +00001342 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001343 p->iLimit = pPrior->iLimit;
1344 p->iOffset = pPrior->iOffset;
1345 p->nLimit = -1;
1346 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001347 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001348 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001349 if( rc ){
1350 goto multi_select_end;
1351 }
drhf46f9052002-06-22 02:33:38 +00001352 break;
1353 }
1354 /* For UNION ALL ... ORDER BY fall through to the next case */
1355 }
drh82c3d632000-06-06 21:56:07 +00001356 case TK_EXCEPT:
1357 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001358 int unionTab; /* Cursor number of the temporary table holding result */
1359 int op; /* One of the SRT_ operations to apply to self */
1360 int priorOp; /* The SRT_ operation to apply to prior selects */
drh7b58dae2003-07-20 01:16:46 +00001361 int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
drhc926afb2002-06-20 03:38:26 +00001362 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
drh82c3d632000-06-06 21:56:07 +00001363
drhd8bc7082000-06-07 23:51:50 +00001364 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh7b58dae2003-07-20 01:16:46 +00001365 if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
drhd8bc7082000-06-07 23:51:50 +00001366 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001367 ** right.
drhd8bc7082000-06-07 23:51:50 +00001368 */
drh82c3d632000-06-06 21:56:07 +00001369 unionTab = iParm;
1370 }else{
drhd8bc7082000-06-07 23:51:50 +00001371 /* We will need to create our own temporary table to hold the
1372 ** intermediate results.
1373 */
1374 unionTab = pParse->nTab++;
1375 if( p->pOrderBy
1376 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001377 rc = 1;
1378 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001379 }
drhd8bc7082000-06-07 23:51:50 +00001380 if( p->op!=TK_ALL ){
drhd3d39e92004-05-20 22:16:29 +00001381 openTempIndex(pParse, p, unionTab, 1);
drh345fda32001-01-15 22:51:08 +00001382 }else{
danielk19774adee202004-05-08 08:23:19 +00001383 sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001384 }
danielk197784ac9d02004-05-18 09:58:06 +00001385 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001386 }
drhd8bc7082000-06-07 23:51:50 +00001387
1388 /* Code the SELECT statements to our left
1389 */
danielk197784ac9d02004-05-18 09:58:06 +00001390 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
1391 if( rc ){
1392 goto multi_select_end;
1393 }
1394 if( p->op==TK_ALL ){
1395 sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, pPrior->pEList->nExpr);
1396 }
drhd8bc7082000-06-07 23:51:50 +00001397
1398 /* Code the current SELECT statement
1399 */
1400 switch( p->op ){
1401 case TK_EXCEPT: op = SRT_Except; break;
1402 case TK_UNION: op = SRT_Union; break;
1403 case TK_ALL: op = SRT_Table; break;
1404 }
drh82c3d632000-06-06 21:56:07 +00001405 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001406 pOrderBy = p->pOrderBy;
1407 p->pOrderBy = 0;
drh7b58dae2003-07-20 01:16:46 +00001408 nLimit = p->nLimit;
1409 p->nLimit = -1;
1410 nOffset = p->nOffset;
1411 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001412 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001413 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001414 p->pOrderBy = pOrderBy;
drh7b58dae2003-07-20 01:16:46 +00001415 p->nLimit = nLimit;
1416 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001417 if( rc ){
1418 goto multi_select_end;
1419 }
1420
drhd8bc7082000-06-07 23:51:50 +00001421
1422 /* Convert the data in the temporary table into whatever form
1423 ** it is that we currently need.
1424 */
drhc926afb2002-06-20 03:38:26 +00001425 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001426 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001427 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001428 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001429 generateColumnNames(pParse, 0, p->pEList);
1430 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001431 }
danielk19774adee202004-05-08 08:23:19 +00001432 iBreak = sqlite3VdbeMakeLabel(v);
1433 iCont = sqlite3VdbeMakeLabel(v);
1434 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001435 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001436 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001437 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001438 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001439 iCont, iBreak, 0);
1440 if( rc ){
1441 rc = 1;
1442 goto multi_select_end;
1443 }
danielk19774adee202004-05-08 08:23:19 +00001444 sqlite3VdbeResolveLabel(v, iCont);
1445 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1446 sqlite3VdbeResolveLabel(v, iBreak);
1447 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001448 if( p->pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00001449 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001450 }
drh82c3d632000-06-06 21:56:07 +00001451 }
1452 break;
1453 }
1454 case TK_INTERSECT: {
1455 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001456 int iCont, iBreak, iStart;
drh7b58dae2003-07-20 01:16:46 +00001457 int nLimit, nOffset;
drh82c3d632000-06-06 21:56:07 +00001458
drhd8bc7082000-06-07 23:51:50 +00001459 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001460 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001461 ** by allocating the tables we will need.
1462 */
drh82c3d632000-06-06 21:56:07 +00001463 tab1 = pParse->nTab++;
1464 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001465 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001466 rc = 1;
1467 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001468 }
drhd3d39e92004-05-20 22:16:29 +00001469 openTempIndex(pParse, p, tab1, 1);
danielk197784ac9d02004-05-18 09:58:06 +00001470 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001471
1472 /* Code the SELECTs to our left into temporary table "tab1".
1473 */
danielk197784ac9d02004-05-18 09:58:06 +00001474 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
1475 if( rc ){
1476 goto multi_select_end;
1477 }
drhd8bc7082000-06-07 23:51:50 +00001478
1479 /* Code the current SELECT into temporary table "tab2"
1480 */
drhd3d39e92004-05-20 22:16:29 +00001481 openTempIndex(pParse, p, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001482 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001483 nLimit = p->nLimit;
1484 p->nLimit = -1;
1485 nOffset = p->nOffset;
1486 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001487 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001488 p->pPrior = pPrior;
drh7b58dae2003-07-20 01:16:46 +00001489 p->nLimit = nLimit;
1490 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001491 if( rc ){
1492 goto multi_select_end;
1493 }
drhd8bc7082000-06-07 23:51:50 +00001494
1495 /* Generate code to take the intersection of the two temporary
1496 ** tables.
1497 */
drh82c3d632000-06-06 21:56:07 +00001498 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001499 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001500 generateColumnNames(pParse, 0, p->pEList);
1501 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001502 }
danielk19774adee202004-05-08 08:23:19 +00001503 iBreak = sqlite3VdbeMakeLabel(v);
1504 iCont = sqlite3VdbeMakeLabel(v);
1505 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001506 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001507 iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
1508 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001509 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001510 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001511 iCont, iBreak, 0);
1512 if( rc ){
1513 rc = 1;
1514 goto multi_select_end;
1515 }
danielk19774adee202004-05-08 08:23:19 +00001516 sqlite3VdbeResolveLabel(v, iCont);
1517 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1518 sqlite3VdbeResolveLabel(v, iBreak);
1519 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1520 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drhd8bc7082000-06-07 23:51:50 +00001521 if( p->pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00001522 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001523 }
drh82c3d632000-06-06 21:56:07 +00001524 break;
1525 }
1526 }
1527 assert( p->pEList && pPrior->pEList );
1528 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001529 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001530 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001531 rc = 1;
1532 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001533 }
danielk197784ac9d02004-05-18 09:58:06 +00001534
1535multi_select_end:
drhd3d39e92004-05-20 22:16:29 +00001536#if 0 /*** NOT USED ****/
danielk197784ac9d02004-05-18 09:58:06 +00001537 if( affStr ){
1538 if( rc!=SQLITE_OK ){
1539 sqliteFree(affStr);
1540 }else{
1541 multiSelectAffinity(p, affStr);
1542 sqlite3VdbeOp3(v, OP_Noop, 0, 0, affStr, P3_DYNAMIC);
1543 }
1544 }
drhd3d39e92004-05-20 22:16:29 +00001545#endif
danielk197784ac9d02004-05-18 09:58:06 +00001546 return rc;
drh22827922000-06-06 17:27:05 +00001547}
1548
1549/*
drh832508b2002-03-02 17:04:07 +00001550** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001551** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001552** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001553** unchanged.)
drh832508b2002-03-02 17:04:07 +00001554**
1555** This routine is part of the flattening procedure. A subquery
1556** whose result set is defined by pEList appears as entry in the
1557** FROM clause of a SELECT such that the VDBE cursor assigned to that
1558** FORM clause entry is iTable. This routine make the necessary
1559** changes to pExpr so that it refers directly to the source table
1560** of the subquery rather the result set of the subquery.
1561*/
drh6a3ea0e2003-05-02 14:32:12 +00001562static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1563static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001564 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001565 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1566 if( pExpr->iColumn<0 ){
1567 pExpr->op = TK_NULL;
1568 }else{
1569 Expr *pNew;
1570 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1571 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1572 pNew = pEList->a[pExpr->iColumn].pExpr;
1573 assert( pNew!=0 );
1574 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001575 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001576 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001577 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001578 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001579 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001580 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001581 pExpr->iTable = pNew->iTable;
1582 pExpr->iColumn = pNew->iColumn;
1583 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001584 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1585 sqlite3TokenCopy(&pExpr->span, &pNew->span);
drh50350a12004-02-13 16:22:22 +00001586 }
drh832508b2002-03-02 17:04:07 +00001587 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001588 substExpr(pExpr->pLeft, iTable, pEList);
1589 substExpr(pExpr->pRight, iTable, pEList);
1590 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001591 }
1592}
1593static void
drh6a3ea0e2003-05-02 14:32:12 +00001594substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001595 int i;
1596 if( pList==0 ) return;
1597 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001598 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001599 }
1600}
1601
1602/*
drh1350b032002-02-27 19:00:20 +00001603** This routine attempts to flatten subqueries in order to speed
1604** execution. It returns 1 if it makes changes and 0 if no flattening
1605** occurs.
1606**
1607** To understand the concept of flattening, consider the following
1608** query:
1609**
1610** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1611**
1612** The default way of implementing this query is to execute the
1613** subquery first and store the results in a temporary table, then
1614** run the outer query on that temporary table. This requires two
1615** passes over the data. Furthermore, because the temporary table
1616** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001617** optimized.
drh1350b032002-02-27 19:00:20 +00001618**
drh832508b2002-03-02 17:04:07 +00001619** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001620** a single flat select, like this:
1621**
1622** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1623**
1624** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001625** but only has to scan the data once. And because indices might
1626** exist on the table t1, a complete scan of the data might be
1627** avoided.
drh1350b032002-02-27 19:00:20 +00001628**
drh832508b2002-03-02 17:04:07 +00001629** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001630**
drh832508b2002-03-02 17:04:07 +00001631** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001632**
drh832508b2002-03-02 17:04:07 +00001633** (2) The subquery is not an aggregate or the outer query is not a join.
1634**
drh8af4d3a2003-05-06 20:35:16 +00001635** (3) The subquery is not the right operand of a left outer join, or
1636** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001637**
1638** (4) The subquery is not DISTINCT or the outer query is not a join.
1639**
1640** (5) The subquery is not DISTINCT or the outer query does not use
1641** aggregates.
1642**
1643** (6) The subquery does not use aggregates or the outer query is not
1644** DISTINCT.
1645**
drh08192d52002-04-30 19:20:28 +00001646** (7) The subquery has a FROM clause.
1647**
drhdf199a22002-06-14 22:38:41 +00001648** (8) The subquery does not use LIMIT or the outer query is not a join.
1649**
1650** (9) The subquery does not use LIMIT or the outer query does not use
1651** aggregates.
1652**
1653** (10) The subquery does not use aggregates or the outer query does not
1654** use LIMIT.
1655**
drh174b6192002-12-03 02:22:52 +00001656** (11) The subquery and the outer query do not both have ORDER BY clauses.
1657**
drh3fc673e2003-06-16 00:40:34 +00001658** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1659** subquery has no WHERE clause. (added by ticket #350)
1660**
drh832508b2002-03-02 17:04:07 +00001661** In this routine, the "p" parameter is a pointer to the outer query.
1662** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1663** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1664**
drh665de472003-03-31 13:36:09 +00001665** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001666** If flattening is attempted this routine returns 1.
1667**
1668** All of the expression analysis must occur on both the outer query and
1669** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001670*/
drh8c74a8c2002-08-25 19:20:40 +00001671static int flattenSubquery(
1672 Parse *pParse, /* The parsing context */
1673 Select *p, /* The parent or outer SELECT statement */
1674 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1675 int isAgg, /* True if outer SELECT uses aggregate functions */
1676 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1677){
drh0bb28102002-05-08 11:54:14 +00001678 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001679 SrcList *pSrc; /* The FROM clause of the outer query */
1680 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001681 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001682 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh832508b2002-03-02 17:04:07 +00001683 int i;
drh832508b2002-03-02 17:04:07 +00001684 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001685
drh832508b2002-03-02 17:04:07 +00001686 /* Check to see if flattening is permitted. Return 0 if not.
1687 */
1688 if( p==0 ) return 0;
1689 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001690 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001691 pSub = pSrc->a[iFrom].pSelect;
1692 assert( pSub!=0 );
1693 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001694 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001695 pSubSrc = pSub->pSrc;
1696 assert( pSubSrc );
drhc31c2eb2003-05-02 16:04:17 +00001697 if( pSubSrc->nSrc==0 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001698 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1699 return 0;
1700 }
drhd11d3822002-06-21 23:01:49 +00001701 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001702 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001703
drh8af4d3a2003-05-06 20:35:16 +00001704 /* Restriction 3: If the subquery is a join, make sure the subquery is
1705 ** not used as the right operand of an outer join. Examples of why this
1706 ** is not allowed:
1707 **
1708 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1709 **
1710 ** If we flatten the above, we would get
1711 **
1712 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1713 **
1714 ** which is not at all the same thing.
1715 */
1716 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1717 return 0;
1718 }
1719
drh3fc673e2003-06-16 00:40:34 +00001720 /* Restriction 12: If the subquery is the right operand of a left outer
1721 ** join, make sure the subquery has no WHERE clause.
1722 ** An examples of why this is not allowed:
1723 **
1724 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1725 **
1726 ** If we flatten the above, we would get
1727 **
1728 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1729 **
1730 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1731 ** effectively converts the OUTER JOIN into an INNER JOIN.
1732 */
1733 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1734 && pSub->pWhere!=0 ){
1735 return 0;
1736 }
1737
drh0bb28102002-05-08 11:54:14 +00001738 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001739 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001740 */
drhc31c2eb2003-05-02 16:04:17 +00001741
1742 /* Move all of the FROM elements of the subquery into the
1743 ** the FROM clause of the outer query. Before doing this, remember
1744 ** the cursor number for the original outer query FROM element in
1745 ** iParent. The iParent cursor will never be used. Subsequent code
1746 ** will scan expressions looking for iParent references and replace
1747 ** those references with expressions that resolve to the subquery FROM
1748 ** elements we are now copying in.
1749 */
drh6a3ea0e2003-05-02 14:32:12 +00001750 iParent = pSrc->a[iFrom].iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001751 {
1752 int nSubSrc = pSubSrc->nSrc;
drh8af4d3a2003-05-06 20:35:16 +00001753 int jointype = pSrc->a[iFrom].jointype;
drhc31c2eb2003-05-02 16:04:17 +00001754
1755 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001756 sqlite3DeleteTable(0, pSrc->a[iFrom].pTab);
drhc31c2eb2003-05-02 16:04:17 +00001757 }
drhf26e09c2003-05-31 16:21:12 +00001758 sqliteFree(pSrc->a[iFrom].zDatabase);
drhc31c2eb2003-05-02 16:04:17 +00001759 sqliteFree(pSrc->a[iFrom].zName);
1760 sqliteFree(pSrc->a[iFrom].zAlias);
1761 if( nSubSrc>1 ){
1762 int extra = nSubSrc - 1;
1763 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00001764 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00001765 }
1766 p->pSrc = pSrc;
1767 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1768 pSrc->a[i] = pSrc->a[i-extra];
1769 }
1770 }
1771 for(i=0; i<nSubSrc; i++){
1772 pSrc->a[i+iFrom] = pSubSrc->a[i];
1773 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1774 }
drh8af4d3a2003-05-06 20:35:16 +00001775 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00001776 }
1777
1778 /* Now begin substituting subquery result set expressions for
1779 ** references to the iParent in the outer query.
1780 **
1781 ** Example:
1782 **
1783 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1784 ** \ \_____________ subquery __________/ /
1785 ** \_____________________ outer query ______________________________/
1786 **
1787 ** We look at every expression in the outer query and every place we see
1788 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1789 */
drh6a3ea0e2003-05-02 14:32:12 +00001790 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001791 pList = p->pEList;
1792 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001793 Expr *pExpr;
1794 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1795 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001796 }
1797 }
drh1b2e0322002-03-03 02:49:51 +00001798 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00001799 substExprList(p->pGroupBy, iParent, pSub->pEList);
1800 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001801 }
drh174b6192002-12-03 02:22:52 +00001802 if( pSub->pOrderBy ){
1803 assert( p->pOrderBy==0 );
1804 p->pOrderBy = pSub->pOrderBy;
1805 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00001806 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00001807 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00001808 }
drh832508b2002-03-02 17:04:07 +00001809 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001810 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00001811 }else{
1812 pWhere = 0;
1813 }
1814 if( subqueryIsAgg ){
1815 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001816 p->pHaving = p->pWhere;
1817 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00001818 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001819 if( pSub->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001820 Expr *pHaving = sqlite3ExprDup(pSub->pHaving);
drh1b2e0322002-03-03 02:49:51 +00001821 if( p->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001822 p->pHaving = sqlite3Expr(TK_AND, p->pHaving, pHaving, 0);
drh1b2e0322002-03-03 02:49:51 +00001823 }else{
1824 p->pHaving = pHaving;
1825 }
1826 }
1827 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00001828 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00001829 }else if( p->pWhere==0 ){
1830 p->pWhere = pWhere;
1831 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001832 substExpr(p->pWhere, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001833 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001834 p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pWhere, 0);
drh832508b2002-03-02 17:04:07 +00001835 }
1836 }
drhc31c2eb2003-05-02 16:04:17 +00001837
1838 /* The flattened query is distinct if either the inner or the
1839 ** outer query is distinct.
1840 */
drh832508b2002-03-02 17:04:07 +00001841 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00001842
drhc31c2eb2003-05-02 16:04:17 +00001843 /* Transfer the limit expression from the subquery to the outer
1844 ** query.
1845 */
drhdf199a22002-06-14 22:38:41 +00001846 if( pSub->nLimit>=0 ){
1847 if( p->nLimit<0 ){
1848 p->nLimit = pSub->nLimit;
1849 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1850 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1851 }
1852 }
1853 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00001854
drhc31c2eb2003-05-02 16:04:17 +00001855 /* Finially, delete what is left of the subquery and return
1856 ** success.
1857 */
danielk19774adee202004-05-08 08:23:19 +00001858 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00001859 return 1;
1860}
drh1350b032002-02-27 19:00:20 +00001861
1862/*
drh9562b552002-02-19 15:00:07 +00001863** Analyze the SELECT statement passed in as an argument to see if it
1864** is a simple min() or max() query. If it is and this query can be
1865** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00001866** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00001867** simple min() or max() query, then return 0;
1868**
1869** A simply min() or max() query looks like this:
1870**
1871** SELECT min(a) FROM table;
1872** SELECT max(a) FROM table;
1873**
1874** The query may have only a single table in its FROM argument. There
1875** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1876** be the min() or max() of a single column of the table. The column
1877** in the min() or max() function must be indexed.
1878**
danielk19774adee202004-05-08 08:23:19 +00001879** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00001880** See the header comment on that routine for additional information.
1881*/
1882static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1883 Expr *pExpr;
1884 int iCol;
1885 Table *pTab;
1886 Index *pIdx;
1887 int base;
1888 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00001889 int seekOp;
1890 int cont;
drh6e175292004-03-13 14:00:36 +00001891 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00001892 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00001893 SrcList *pSrc;
1894
drh9562b552002-02-19 15:00:07 +00001895
1896 /* Check to see if this query is a simple min() or max() query. Return
1897 ** zero if it is not.
1898 */
1899 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00001900 pSrc = p->pSrc;
1901 if( pSrc->nSrc!=1 ) return 0;
1902 pEList = p->pEList;
1903 if( pEList->nExpr!=1 ) return 0;
1904 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00001905 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00001906 pList = pExpr->pList;
1907 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00001908 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00001909 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00001910 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00001911 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00001912 seekOp = OP_Last;
1913 }else{
1914 return 0;
1915 }
drh6e175292004-03-13 14:00:36 +00001916 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00001917 if( pExpr->op!=TK_COLUMN ) return 0;
1918 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00001919 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00001920
1921 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00001922 ** Check to make sure we have an index and make pIdx point to the
1923 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
1924 ** key column, no index is necessary so set pIdx to NULL. If no
1925 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00001926 */
1927 if( iCol<0 ){
1928 pIdx = 0;
1929 }else{
1930 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1931 assert( pIdx->nColumn>=1 );
1932 if( pIdx->aiColumn[0]==iCol ) break;
1933 }
1934 if( pIdx==0 ) return 0;
1935 }
1936
drhe5f50722003-07-19 00:44:14 +00001937 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00001938 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00001939 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00001940 */
danielk19774adee202004-05-08 08:23:19 +00001941 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00001942 if( v==0 ) return 0;
1943 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001944 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh9562b552002-02-19 15:00:07 +00001945 }
1946
drh0c37e632004-01-30 02:01:03 +00001947 /* If the output is destined for a temporary table, open that table.
1948 */
1949 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00001950 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00001951 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00001952 }
1953
drh17f71932002-02-21 12:01:27 +00001954 /* Generating code to find the min or the max. Basically all we have
1955 ** to do is find the first or the last entry in the chosen index. If
1956 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
1957 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00001958 */
danielk19774adee202004-05-08 08:23:19 +00001959 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00001960 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00001961 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00001962 if( pSrc->a[0].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +00001963 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00001964 sqlite3VdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
danielk1977b4964b72004-05-18 01:23:38 +00001965 sqlite3VdbeAddOp(v, OP_SetNumColumns, base, pTab->nCol);
drh6e175292004-03-13 14:00:36 +00001966 }
danielk19774adee202004-05-08 08:23:19 +00001967 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00001968 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00001969 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00001970 }else{
danielk19774adee202004-05-08 08:23:19 +00001971 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00001972 sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum,
1973 (char*)&pIdx->keyInfo, P3_KEYINFO);
danielk19774adee202004-05-08 08:23:19 +00001974 sqlite3VdbeAddOp(v, seekOp, base+1, 0);
1975 sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
1976 sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
drh7cf6e4d2004-05-19 14:56:55 +00001977 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00001978 }
drh5cf8e8c2002-02-19 22:42:05 +00001979 eList.nExpr = 1;
1980 memset(&eListItem, 0, sizeof(eListItem));
1981 eList.a = &eListItem;
1982 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00001983 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00001984 sqlite3VdbeResolveLabel(v, cont);
1985 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00001986
drh9562b552002-02-19 15:00:07 +00001987 return 1;
1988}
1989
1990/*
drh9bb61fe2000-06-05 16:01:39 +00001991** Generate code for the given SELECT statement.
1992**
drhfef52082000-06-06 01:50:43 +00001993** The results are distributed in various ways depending on the
1994** value of eDest and iParm.
1995**
1996** eDest Value Result
1997** ------------ -------------------------------------------
1998** SRT_Callback Invoke the callback for each row of the result.
1999**
2000** SRT_Mem Store first result in memory cell iParm
2001**
danielk1977e014a832004-05-17 10:48:57 +00002002** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002003**
drh82c3d632000-06-06 21:56:07 +00002004** SRT_Union Store results as a key in a temporary table iParm
2005**
jplyon4b11c6d2004-01-19 04:57:53 +00002006** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002007**
2008** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002009**
drhe78e8282003-01-19 03:59:45 +00002010** The table above is incomplete. Additional eDist value have be added
2011** since this comment was written. See the selectInnerLoop() function for
2012** a complete listing of the allowed values of eDest and their meanings.
2013**
drh9bb61fe2000-06-05 16:01:39 +00002014** This routine returns the number of errors. If any errors are
2015** encountered, then an appropriate error message is left in
2016** pParse->zErrMsg.
2017**
2018** This routine does NOT free the Select structure passed in. The
2019** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002020**
2021** The pParent, parentTab, and *pParentAgg fields are filled in if this
2022** SELECT is a subquery. This routine may try to combine this SELECT
2023** with its parent to form a single flat query. In so doing, it might
2024** change the parent query from a non-aggregate to an aggregate query.
2025** For that reason, the pParentAgg flag is passed as a pointer, so it
2026** can be changed.
drhe78e8282003-01-19 03:59:45 +00002027**
2028** Example 1: The meaning of the pParent parameter.
2029**
2030** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2031** \ \_______ subquery _______/ /
2032** \ /
2033** \____________________ outer query ___________________/
2034**
2035** This routine is called for the outer query first. For that call,
2036** pParent will be NULL. During the processing of the outer query, this
2037** routine is called recursively to handle the subquery. For the recursive
2038** call, pParent will point to the outer query. Because the subquery is
2039** the second element in a three-way join, the parentTab parameter will
2040** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002041*/
danielk19774adee202004-05-08 08:23:19 +00002042int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002043 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002044 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002045 int eDest, /* How to dispose of the results */
2046 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002047 Select *pParent, /* Another SELECT for which this is a sub-query */
2048 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002049 int *pParentAgg, /* True if pParent uses aggregate functions */
2050 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002051){
drhd8bc7082000-06-07 23:51:50 +00002052 int i;
drhcce7d172000-05-31 15:34:51 +00002053 WhereInfo *pWInfo;
2054 Vdbe *v;
2055 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002056 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002057 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002058 Expr *pWhere; /* The WHERE clause. May be NULL */
2059 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002060 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2061 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002062 int isDistinct; /* True if the DISTINCT keyword is present */
2063 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002064 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00002065
danielk19776f8a5032004-05-10 10:34:51 +00002066 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002067 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002068
drh82c3d632000-06-06 21:56:07 +00002069 /* If there is are a sequence of queries, do the earlier ones first.
2070 */
2071 if( p->pPrior ){
danielk197784ac9d02004-05-18 09:58:06 +00002072 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002073 }
2074
2075 /* Make local copies of the parameters for this query.
2076 */
drh9bb61fe2000-06-05 16:01:39 +00002077 pTabList = p->pSrc;
2078 pWhere = p->pWhere;
2079 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00002080 pGroupBy = p->pGroupBy;
2081 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00002082 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00002083
drh6a3ea0e2003-05-02 14:32:12 +00002084 /* Allocate VDBE cursors for each table in the FROM clause
drh10e5e3c2000-06-08 00:19:02 +00002085 */
danielk19774adee202004-05-08 08:23:19 +00002086 sqlite3SrcListAssignCursors(pParse, pTabList);
drh10e5e3c2000-06-08 00:19:02 +00002087
drh9bb61fe2000-06-05 16:01:39 +00002088 /*
2089 ** Do not even attempt to generate any code if we have already seen
2090 ** errors before this routine starts.
2091 */
drh1d83f052002-02-17 00:30:36 +00002092 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002093
drhe78e8282003-01-19 03:59:45 +00002094 /* Expand any "*" terms in the result set. (For example the "*" in
2095 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
2096 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00002097 */
drhd8bc7082000-06-07 23:51:50 +00002098 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00002099 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002100 }
drhad2d8302002-05-24 20:31:36 +00002101 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00002102 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00002103 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002104
drh22827922000-06-06 17:27:05 +00002105 /* If writing to memory or generating a set
2106 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002107 */
drhfef52082000-06-06 01:50:43 +00002108 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002109 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002110 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002111 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002112 }
2113
drhc926afb2002-06-20 03:38:26 +00002114 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002115 */
drhc926afb2002-06-20 03:38:26 +00002116 switch( eDest ){
2117 case SRT_Union:
2118 case SRT_Except:
2119 case SRT_Discard:
2120 pOrderBy = 0;
2121 break;
2122 default:
2123 break;
drh22827922000-06-06 17:27:05 +00002124 }
2125
drh10e5e3c2000-06-08 00:19:02 +00002126 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002127 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002128 **
drh967e8b72000-06-21 13:59:10 +00002129 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002130 */
drh4794b982000-06-06 13:54:14 +00002131 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002132 if( sqlite3ExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002133 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002134 }
danielk19774adee202004-05-08 08:23:19 +00002135 if( sqlite3ExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002136 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002137 }
2138 }
drhcce7d172000-05-31 15:34:51 +00002139 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002140 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00002141 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002142 }
danielk19774adee202004-05-08 08:23:19 +00002143 if( sqlite3ExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00002144 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002145 }
2146 }
drhc66c5a22002-12-03 02:34:49 +00002147 if( pHaving ){
2148 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002149 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
drhc66c5a22002-12-03 02:34:49 +00002150 goto select_end;
2151 }
danielk19774adee202004-05-08 08:23:19 +00002152 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pHaving) ){
drhc66c5a22002-12-03 02:34:49 +00002153 goto select_end;
2154 }
danielk19774adee202004-05-08 08:23:19 +00002155 if( sqlite3ExprCheck(pParse, pHaving, 1, &isAgg) ){
drhc66c5a22002-12-03 02:34:49 +00002156 goto select_end;
2157 }
2158 }
drhcce7d172000-05-31 15:34:51 +00002159 if( pOrderBy ){
2160 for(i=0; i<pOrderBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002161 int iCol;
drh22827922000-06-06 17:27:05 +00002162 Expr *pE = pOrderBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002163 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2164 sqlite3ExprDelete(pE);
2165 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh88eee382003-01-31 17:16:36 +00002166 }
danielk19774adee202004-05-08 08:23:19 +00002167 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh88eee382003-01-31 17:16:36 +00002168 goto select_end;
2169 }
danielk19774adee202004-05-08 08:23:19 +00002170 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh88eee382003-01-31 17:16:36 +00002171 goto select_end;
2172 }
danielk19774adee202004-05-08 08:23:19 +00002173 if( sqlite3ExprIsConstant(pE) ){
2174 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2175 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002176 "ORDER BY terms must not be non-integer constants");
drhe4de1fe2002-06-02 16:09:01 +00002177 goto select_end;
2178 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002179 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002180 "ORDER BY column number %d out of range - should be "
drhe4de1fe2002-06-02 16:09:01 +00002181 "between 1 and %d", iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00002182 goto select_end;
2183 }
drhcce7d172000-05-31 15:34:51 +00002184 }
2185 }
2186 }
drh22827922000-06-06 17:27:05 +00002187 if( pGroupBy ){
2188 for(i=0; i<pGroupBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002189 int iCol;
drh22827922000-06-06 17:27:05 +00002190 Expr *pE = pGroupBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002191 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2192 sqlite3ExprDelete(pE);
2193 pE = pGroupBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00002194 }
danielk19774adee202004-05-08 08:23:19 +00002195 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00002196 goto select_end;
drh22827922000-06-06 17:27:05 +00002197 }
danielk19774adee202004-05-08 08:23:19 +00002198 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00002199 goto select_end;
drh22827922000-06-06 17:27:05 +00002200 }
danielk19774adee202004-05-08 08:23:19 +00002201 if( sqlite3ExprIsConstant(pE) ){
2202 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2203 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002204 "GROUP BY terms must not be non-integer constants");
drh88eee382003-01-31 17:16:36 +00002205 goto select_end;
2206 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002207 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002208 "GROUP BY column number %d out of range - should be "
drh88eee382003-01-31 17:16:36 +00002209 "between 1 and %d", iCol, pEList->nExpr);
drh88eee382003-01-31 17:16:36 +00002210 goto select_end;
2211 }
2212 }
drh22827922000-06-06 17:27:05 +00002213 }
2214 }
drhcce7d172000-05-31 15:34:51 +00002215
drhd820cb12002-02-18 03:21:45 +00002216 /* Begin generating code.
2217 */
danielk19774adee202004-05-08 08:23:19 +00002218 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002219 if( v==0 ) goto select_end;
2220
drhe78e8282003-01-19 03:59:45 +00002221 /* Identify column names if we will be using them in a callback. This
2222 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002223 */
2224 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002225 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002226 }
2227
drhd3d39e92004-05-20 22:16:29 +00002228#if 1 /* I do not think we need the following code any more.... */
danielk197784ac9d02004-05-18 09:58:06 +00002229 /* If the destination is SRT_Union, then set the number of columns in
2230 ** the records that will be inserted into the temporary table. The caller
2231 ** couldn't do this, in case the select statement is of the form
2232 ** "SELECT * FROM ....".
2233 **
2234 ** We need to do this before we start inserting records into the
2235 ** temporary table (which has had OP_KeyAsData executed on it), because
2236 ** it is required by the key comparison function. So do it now, even
2237 ** though this means that OP_SetNumColumns may be executed on the same
2238 ** cursor more than once.
2239 */
2240 if( eDest==SRT_Union ){
2241 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
2242 }
drhd3d39e92004-05-20 22:16:29 +00002243#endif
danielk197784ac9d02004-05-18 09:58:06 +00002244
drhd820cb12002-02-18 03:21:45 +00002245 /* Generate code for all sub-queries in the FROM clause
2246 */
drhad3cab52002-05-24 02:04:32 +00002247 for(i=0; i<pTabList->nSrc; i++){
drh5cf590c2003-04-24 01:45:04 +00002248 const char *zSavedAuthContext;
drhc31c2eb2003-05-02 16:04:17 +00002249 int needRestoreContext;
2250
drha76b5df2002-02-23 02:32:10 +00002251 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002252 if( pTabList->a[i].zName!=0 ){
2253 zSavedAuthContext = pParse->zAuthContext;
2254 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002255 needRestoreContext = 1;
2256 }else{
2257 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002258 }
danielk19774adee202004-05-08 08:23:19 +00002259 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
danielk197784ac9d02004-05-18 09:58:06 +00002260 pTabList->a[i].iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002261 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002262 pParse->zAuthContext = zSavedAuthContext;
2263 }
drh1b2e0322002-03-03 02:49:51 +00002264 pTabList = p->pSrc;
2265 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002266 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002267 pOrderBy = p->pOrderBy;
2268 }
drh1b2e0322002-03-03 02:49:51 +00002269 pGroupBy = p->pGroupBy;
2270 pHaving = p->pHaving;
2271 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002272 }
2273
drh6e175292004-03-13 14:00:36 +00002274 /* Check for the special case of a min() or max() function by itself
2275 ** in the result set.
2276 */
2277 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2278 rc = 0;
2279 goto select_end;
2280 }
2281
drh832508b2002-03-02 17:04:07 +00002282 /* Check to see if this is a subquery that can be "flattened" into its parent.
2283 ** If flattening is a possiblity, do so and return immediately.
2284 */
drh1b2e0322002-03-03 02:49:51 +00002285 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002286 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002287 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002288 return rc;
2289 }
drh832508b2002-03-02 17:04:07 +00002290
drh7b58dae2003-07-20 01:16:46 +00002291 /* Set the limiter.
2292 */
2293 computeLimitRegisters(pParse, p);
2294
drhe78e8282003-01-19 03:59:45 +00002295 /* Identify column types if we will be using a callback. This
2296 ** step is skipped if the output is going to a destination other
2297 ** than a callback.
drhe5f50722003-07-19 00:44:14 +00002298 **
2299 ** We have to do this separately from the creation of column names
2300 ** above because if the pTabList contains views then they will not
2301 ** have been resolved and we will not know the column types until
2302 ** now.
drhfcb78a42003-01-18 20:11:05 +00002303 */
2304 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002305 generateColumnTypes(pParse, pTabList, pEList);
drhfcb78a42003-01-18 20:11:05 +00002306 }
2307
drh2d0794e2002-03-03 03:03:52 +00002308 /* If the output is destined for a temporary table, open that table.
2309 */
2310 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002311 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002312 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002313 }
2314
drh22827922000-06-06 17:27:05 +00002315 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002316 */
drhd820cb12002-02-18 03:21:45 +00002317 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002318 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002319 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002320 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002321 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002322 if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002323 goto select_end;
drh22827922000-06-06 17:27:05 +00002324 }
2325 }
2326 if( pGroupBy ){
2327 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002328 if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002329 goto select_end;
drh22827922000-06-06 17:27:05 +00002330 }
2331 }
2332 }
danielk19774adee202004-05-08 08:23:19 +00002333 if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002334 goto select_end;
drh22827922000-06-06 17:27:05 +00002335 }
drh191b6902000-06-08 11:13:01 +00002336 if( pOrderBy ){
2337 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002338 if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002339 goto select_end;
drh191b6902000-06-08 11:13:01 +00002340 }
2341 }
2342 }
drhefb72512000-05-31 20:00:52 +00002343 }
2344
drh22827922000-06-06 17:27:05 +00002345 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002346 */
2347 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002348 sqlite3VdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002349 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002350 FuncDef *pFunc;
2351 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002352 sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_POINTER);
drhe5095352002-02-24 03:25:14 +00002353 }
2354 }
drh1bee3d72001-10-15 00:44:35 +00002355 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002356 sqlite3VdbeAddOp(v, OP_String, 0, 0);
2357 sqlite3VdbeAddOp(v, OP_AggFocus, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002358 }
drhcce7d172000-05-31 15:34:51 +00002359 }
2360
drh19a775c2000-06-05 18:54:46 +00002361 /* Initialize the memory cell to NULL
2362 */
drhfef52082000-06-06 01:50:43 +00002363 if( eDest==SRT_Mem ){
danielk19774adee202004-05-08 08:23:19 +00002364 sqlite3VdbeAddOp(v, OP_String, 0, 0);
2365 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002366 }
2367
drh832508b2002-03-02 17:04:07 +00002368 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002369 */
drh19a775c2000-06-05 18:54:46 +00002370 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002371 distinct = pParse->nTab++;
drhd3d39e92004-05-20 22:16:29 +00002372 openTempIndex(pParse, p, distinct, 0);
drh832508b2002-03-02 17:04:07 +00002373 }else{
2374 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002375 }
drh832508b2002-03-02 17:04:07 +00002376
2377 /* Begin the database scan
2378 */
danielk19774adee202004-05-08 08:23:19 +00002379 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
drh68d2e592002-08-04 00:52:38 +00002380 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002381 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002382
drh22827922000-06-06 17:27:05 +00002383 /* Use the standard inner loop if we are not dealing with
2384 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002385 */
drhda9d6c42000-05-31 18:20:14 +00002386 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002387 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002388 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002389 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002390 }
drhcce7d172000-05-31 15:34:51 +00002391 }
drhefb72512000-05-31 20:00:52 +00002392
drhe3184742002-06-19 14:27:05 +00002393 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002394 ** processing.
drhefb72512000-05-31 20:00:52 +00002395 */
drh22827922000-06-06 17:27:05 +00002396 else{
drh268380c2004-02-25 13:47:31 +00002397 AggExpr *pAgg;
drh22827922000-06-06 17:27:05 +00002398 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002399 int lbl1;
drh22827922000-06-06 17:27:05 +00002400 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002401 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
drh22827922000-06-06 17:27:05 +00002402 }
drhd3d39e92004-05-20 22:16:29 +00002403 /* No affinity string is attached to the following OP_MakeKey
2404 ** because we do not need to do any coercion of datatypes. */
danielk19774adee202004-05-08 08:23:19 +00002405 sqlite3VdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +00002406 lbl1 = sqlite3VdbeMakeLabel(v);
2407 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh268380c2004-02-25 13:47:31 +00002408 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2409 if( pAgg->isAgg ) continue;
danielk19774adee202004-05-08 08:23:19 +00002410 sqlite3ExprCode(pParse, pAgg->pExpr);
2411 sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002412 }
danielk19774adee202004-05-08 08:23:19 +00002413 sqlite3VdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002414 }
drh268380c2004-02-25 13:47:31 +00002415 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002416 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002417 int nExpr;
2418 FuncDef *pDef;
2419 if( !pAgg->isAgg ) continue;
2420 assert( pAgg->pFunc!=0 );
2421 assert( pAgg->pFunc->xStep!=0 );
2422 pDef = pAgg->pFunc;
2423 pE = pAgg->pExpr;
2424 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002425 assert( pE->op==TK_AGG_FUNCTION );
danielk19774adee202004-05-08 08:23:19 +00002426 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList, pDef->includeTypes);
2427 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
2428 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002429 }
drhcce7d172000-05-31 15:34:51 +00002430 }
2431
2432 /* End the database scan loop.
2433 */
danielk19774adee202004-05-08 08:23:19 +00002434 sqlite3WhereEnd(pWInfo);
drhcce7d172000-05-31 15:34:51 +00002435
drh22827922000-06-06 17:27:05 +00002436 /* If we are processing aggregates, we need to set up a second loop
2437 ** over all of the aggregate values and process them.
2438 */
2439 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002440 int endagg = sqlite3VdbeMakeLabel(v);
drh22827922000-06-06 17:27:05 +00002441 int startagg;
danielk19774adee202004-05-08 08:23:19 +00002442 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002443 pParse->useAgg = 1;
2444 if( pHaving ){
danielk19774adee202004-05-08 08:23:19 +00002445 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002446 }
drhdf199a22002-06-14 22:38:41 +00002447 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002448 iParm, startagg, endagg, aff) ){
drh1d83f052002-02-17 00:30:36 +00002449 goto select_end;
drh22827922000-06-06 17:27:05 +00002450 }
danielk19774adee202004-05-08 08:23:19 +00002451 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2452 sqlite3VdbeResolveLabel(v, endagg);
2453 sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002454 pParse->useAgg = 0;
2455 }
2456
drhcce7d172000-05-31 15:34:51 +00002457 /* If there is an ORDER BY clause, then we need to sort the results
2458 ** and send them to the callback one by one.
2459 */
2460 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00002461 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002462 }
drh6a535342001-10-19 16:44:56 +00002463
drhf620b4e2004-02-09 14:37:50 +00002464 /* If this was a subquery, we have now converted the subquery into a
2465 ** temporary table. So delete the subquery structure from the parent
2466 ** to prevent this subquery from being evaluated again and to force the
2467 ** the use of the temporary table.
2468 */
2469 if( pParent ){
2470 assert( pParent->pSrc->nSrc>parentTab );
2471 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00002472 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00002473 pParent->pSrc->a[parentTab].pSelect = 0;
2474 }
2475
drh1d83f052002-02-17 00:30:36 +00002476 /* The SELECT was successfully coded. Set the return code to 0
2477 ** to indicate no errors.
2478 */
2479 rc = 0;
2480
2481 /* Control jumps to here if an error is encountered above, or upon
2482 ** successful coding of the SELECT.
2483 */
2484select_end:
2485 sqliteAggregateInfoReset(pParse);
2486 return rc;
drhcce7d172000-05-31 15:34:51 +00002487}