blob: d228097f1b9e3fe40d93d6aeaf24057b1a8ebc16 [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**
drh9b3187e2005-01-18 14:45:47 +000015** $Id: select.c,v 1.225 2005/01/18 14:45:48 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;
drh57196282004-10-06 15:41:16 +000084 static const struct {
drh01f3f252002-05-24 16:14:15 +000085 const char *zKeyword;
drh290c1942004-08-21 17:54:45 +000086 u8 nChar;
87 u8 code;
drh01f3f252002-05-24 16:14:15 +000088 } 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 ){
drhae29ffb2004-09-25 14:39:18 +0000119 const char *zSp1 = " ";
120 const char *zSp2 = " ";
121 if( pB==0 ){ zSp1++; }
122 if( pC==0 ){ zSp2++; }
123 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
124 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
drh01f3f252002-05-24 16:14:15 +0000125 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000126 }else if( jointype & JT_RIGHT ){
danielk19774adee202004-05-08 08:23:19 +0000127 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000128 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000129 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000130 }
131 return jointype;
132}
133
134/*
drhad2d8302002-05-24 20:31:36 +0000135** Return the index of a column in a table. Return -1 if the column
136** is not contained in the table.
137*/
138static int columnIndex(Table *pTab, const char *zCol){
139 int i;
140 for(i=0; i<pTab->nCol; i++){
danielk19774adee202004-05-08 08:23:19 +0000141 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
drhad2d8302002-05-24 20:31:36 +0000142 }
143 return -1;
144}
145
146/*
drh91bb0ee2004-09-01 03:06:34 +0000147** Set the value of a token to a '\000'-terminated string.
148*/
149static void setToken(Token *p, const char *z){
150 p->z = z;
151 p->n = strlen(z);
152 p->dyn = 0;
153}
154
155
156/*
drhad2d8302002-05-24 20:31:36 +0000157** Add a term to the WHERE expression in *ppExpr that requires the
158** zCol column to be equal in the two tables pTab1 and pTab2.
159*/
160static void addWhereTerm(
161 const char *zCol, /* Name of the column */
162 const Table *pTab1, /* First table */
163 const Table *pTab2, /* Second table */
164 Expr **ppExpr /* Add the equality term to this expression */
165){
166 Token dummy;
167 Expr *pE1a, *pE1b, *pE1c;
168 Expr *pE2a, *pE2b, *pE2c;
169 Expr *pE;
170
drh91bb0ee2004-09-01 03:06:34 +0000171 setToken(&dummy, zCol);
danielk19774adee202004-05-08 08:23:19 +0000172 pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy);
173 pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy);
drh91bb0ee2004-09-01 03:06:34 +0000174 setToken(&dummy, pTab1->zName);
danielk19774adee202004-05-08 08:23:19 +0000175 pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy);
drh91bb0ee2004-09-01 03:06:34 +0000176 setToken(&dummy, pTab2->zName);
danielk19774adee202004-05-08 08:23:19 +0000177 pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy);
178 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
179 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
180 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000181 ExprSetProperty(pE, EP_FromJoin);
drh91bb0ee2004-09-01 03:06:34 +0000182 *ppExpr = sqlite3ExprAnd(*ppExpr, pE);
drhad2d8302002-05-24 20:31:36 +0000183}
184
185/*
drh1f162302002-10-27 19:35:33 +0000186** Set the EP_FromJoin property on all terms of the given expression.
drh1cc093c2002-06-24 22:01:57 +0000187**
drhe78e8282003-01-19 03:59:45 +0000188** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000189** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000190** join restriction specified in the ON or USING clause and not a part
191** of the more general WHERE clause. These terms are moved over to the
192** WHERE clause during join processing but we need to remember that they
193** originated in the ON or USING clause.
drh1cc093c2002-06-24 22:01:57 +0000194*/
195static void setJoinExpr(Expr *p){
196 while( p ){
drh1f162302002-10-27 19:35:33 +0000197 ExprSetProperty(p, EP_FromJoin);
drh1cc093c2002-06-24 22:01:57 +0000198 setJoinExpr(p->pLeft);
199 p = p->pRight;
200 }
201}
202
203/*
drhad2d8302002-05-24 20:31:36 +0000204** This routine processes the join information for a SELECT statement.
205** ON and USING clauses are converted into extra terms of the WHERE clause.
206** NATURAL joins also create extra WHERE clause terms.
207**
drh91bb0ee2004-09-01 03:06:34 +0000208** The terms of a FROM clause are contained in the Select.pSrc structure.
209** The left most table is the first entry in Select.pSrc. The right-most
210** table is the last entry. The join operator is held in the entry to
211** the left. Thus entry 0 contains the join operator for the join between
212** entries 0 and 1. Any ON or USING clauses associated with the join are
213** also attached to the left entry.
214**
drhad2d8302002-05-24 20:31:36 +0000215** This routine returns the number of errors encountered.
216*/
217static int sqliteProcessJoin(Parse *pParse, Select *p){
drh91bb0ee2004-09-01 03:06:34 +0000218 SrcList *pSrc; /* All tables in the FROM clause */
219 int i, j; /* Loop counters */
220 struct SrcList_item *pLeft; /* Left table being joined */
221 struct SrcList_item *pRight; /* Right table being joined */
drhad2d8302002-05-24 20:31:36 +0000222
drh91bb0ee2004-09-01 03:06:34 +0000223 pSrc = p->pSrc;
224 pLeft = &pSrc->a[0];
225 pRight = &pLeft[1];
226 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
227 Table *pLeftTab = pLeft->pTab;
228 Table *pRightTab = pRight->pTab;
229
230 if( pLeftTab==0 || pRightTab==0 ) continue;
drhad2d8302002-05-24 20:31:36 +0000231
232 /* When the NATURAL keyword is present, add WHERE clause terms for
233 ** every column that the two tables have in common.
234 */
drh91bb0ee2004-09-01 03:06:34 +0000235 if( pLeft->jointype & JT_NATURAL ){
236 if( pLeft->pOn || pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000237 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000238 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000239 return 1;
240 }
drh91bb0ee2004-09-01 03:06:34 +0000241 for(j=0; j<pLeftTab->nCol; j++){
242 char *zName = pLeftTab->aCol[j].zName;
243 if( columnIndex(pRightTab, zName)>=0 ){
244 addWhereTerm(zName, pLeftTab, pRightTab, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000245 }
246 }
247 }
248
249 /* Disallow both ON and USING clauses in the same join
250 */
drh91bb0ee2004-09-01 03:06:34 +0000251 if( pLeft->pOn && pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000252 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
drhda93d232003-03-31 02:12:46 +0000253 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000254 return 1;
255 }
256
257 /* Add the ON clause to the end of the WHERE clause, connected by
drh91bb0ee2004-09-01 03:06:34 +0000258 ** an AND operator.
drhad2d8302002-05-24 20:31:36 +0000259 */
drh91bb0ee2004-09-01 03:06:34 +0000260 if( pLeft->pOn ){
261 setJoinExpr(pLeft->pOn);
262 p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn);
263 pLeft->pOn = 0;
drhad2d8302002-05-24 20:31:36 +0000264 }
265
266 /* Create extra terms on the WHERE clause for each column named
267 ** in the USING clause. Example: If the two tables to be joined are
268 ** A and B and the USING clause names X, Y, and Z, then add this
269 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
270 ** Report an error if any column mentioned in the USING clause is
271 ** not contained in both tables to be joined.
272 */
drh91bb0ee2004-09-01 03:06:34 +0000273 if( pLeft->pUsing ){
274 IdList *pList = pLeft->pUsing;
drhad2d8302002-05-24 20:31:36 +0000275 for(j=0; j<pList->nId; j++){
drh91bb0ee2004-09-01 03:06:34 +0000276 char *zName = pList->a[j].zName;
277 if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
danielk19774adee202004-05-08 08:23:19 +0000278 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
drh91bb0ee2004-09-01 03:06:34 +0000279 "not present in both tables", zName);
drhad2d8302002-05-24 20:31:36 +0000280 return 1;
281 }
drh91bb0ee2004-09-01 03:06:34 +0000282 addWhereTerm(zName, pLeftTab, pRightTab, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000283 }
284 }
285 }
286 return 0;
287}
288
289/*
drh9bb61fe2000-06-05 16:01:39 +0000290** Delete the given Select structure and all of its substructures.
291*/
danielk19774adee202004-05-08 08:23:19 +0000292void sqlite3SelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000293 if( p==0 ) return;
danielk19774adee202004-05-08 08:23:19 +0000294 sqlite3ExprListDelete(p->pEList);
295 sqlite3SrcListDelete(p->pSrc);
296 sqlite3ExprDelete(p->pWhere);
297 sqlite3ExprListDelete(p->pGroupBy);
298 sqlite3ExprDelete(p->pHaving);
299 sqlite3ExprListDelete(p->pOrderBy);
300 sqlite3SelectDelete(p->pPrior);
drh9bb61fe2000-06-05 16:01:39 +0000301 sqliteFree(p);
302}
303
304/*
drh22827922000-06-06 17:27:05 +0000305** Delete the aggregate information from the parse structure.
306*/
drh1d83f052002-02-17 00:30:36 +0000307static void sqliteAggregateInfoReset(Parse *pParse){
drh22827922000-06-06 17:27:05 +0000308 sqliteFree(pParse->aAgg);
309 pParse->aAgg = 0;
310 pParse->nAgg = 0;
drh22827922000-06-06 17:27:05 +0000311 pParse->useAgg = 0;
312}
313
314/*
drhc926afb2002-06-20 03:38:26 +0000315** Insert code into "v" that will push the record on the top of the
316** stack into the sorter.
317*/
318static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
drhc926afb2002-06-20 03:38:26 +0000319 int i;
drhc926afb2002-06-20 03:38:26 +0000320 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000321 sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
drhc926afb2002-06-20 03:38:26 +0000322 }
danielk1977ededfd52004-06-17 07:53:01 +0000323 sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +0000324 sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000325}
326
327/*
drhea48eb22004-07-19 23:16:38 +0000328** Add code to implement the OFFSET and LIMIT
329*/
330static void codeLimiter(
drhbab39e12004-07-19 23:38:11 +0000331 Vdbe *v, /* Generate code into this VM */
drhea48eb22004-07-19 23:16:38 +0000332 Select *p, /* The SELECT statement being coded */
333 int iContinue, /* Jump here to skip the current record */
334 int iBreak, /* Jump here to end the loop */
335 int nPop /* Number of times to pop stack when jumping */
336){
drhea48eb22004-07-19 23:16:38 +0000337 if( p->iOffset>=0 ){
338 int addr = sqlite3VdbeCurrentAddr(v) + 2;
339 if( nPop>0 ) addr++;
340 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr);
341 if( nPop>0 ){
342 sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
343 }
344 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000345 VdbeComment((v, "# skip OFFSET records"));
drhea48eb22004-07-19 23:16:38 +0000346 }
347 if( p->iLimit>=0 ){
348 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhad6d9462004-09-19 02:15:24 +0000349 VdbeComment((v, "# exit when LIMIT reached"));
drhea48eb22004-07-19 23:16:38 +0000350 }
351}
352
353/*
drh22827922000-06-06 17:27:05 +0000354** This routine generates the code for the inside of the inner loop
355** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000356**
drh38640e12002-07-05 21:42:36 +0000357** If srcTab and nColumn are both zero, then the pEList expressions
358** are evaluated in order to get the data for this row. If nColumn>0
359** then data is pulled from srcTab and pEList is used only to get the
360** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000361*/
362static int selectInnerLoop(
363 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000364 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000365 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000366 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000367 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000368 ExprList *pOrderBy, /* If not NULL, sort results using this key */
369 int distinct, /* If >=0, make sure results are distinct */
370 int eDest, /* How to dispose of the results */
371 int iParm, /* An argument to the disposal method */
372 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000373 int iBreak, /* Jump here to break out of the inner loop */
374 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000375){
376 Vdbe *v = pParse->pVdbe;
377 int i;
drhea48eb22004-07-19 23:16:38 +0000378 int hasDistinct; /* True if the DISTINCT keyword is present */
drh38640e12002-07-05 21:42:36 +0000379
drhdaffd0e2001-04-11 14:28:42 +0000380 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000381 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000382
drhdf199a22002-06-14 22:38:41 +0000383 /* If there was a LIMIT clause on the SELECT statement, then do the check
384 ** to see if this row should be output.
385 */
drhea48eb22004-07-19 23:16:38 +0000386 hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
387 if( pOrderBy==0 && !hasDistinct ){
drhbab39e12004-07-19 23:38:11 +0000388 codeLimiter(v, p, iContinue, iBreak, 0);
drhdf199a22002-06-14 22:38:41 +0000389 }
390
drh967e8b72000-06-21 13:59:10 +0000391 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000392 */
drh38640e12002-07-05 21:42:36 +0000393 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000394 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000395 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000396 }
drh38640e12002-07-05 21:42:36 +0000397 }else{
398 nColumn = pEList->nExpr;
399 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000400 sqlite3ExprCode(pParse, pEList->a[i].pExpr);
drh38640e12002-07-05 21:42:36 +0000401 }
drh22827922000-06-06 17:27:05 +0000402 }
403
drhdaffd0e2001-04-11 14:28:42 +0000404 /* If the DISTINCT keyword was present on the SELECT statement
405 ** and this row has been seen before, then do not make this row
406 ** part of the result.
drh22827922000-06-06 17:27:05 +0000407 */
drhea48eb22004-07-19 23:16:38 +0000408 if( hasDistinct ){
drh0bd1f4e2002-06-06 18:54:39 +0000409#if NULL_ALWAYS_DISTINCT
danielk19774adee202004-05-08 08:23:19 +0000410 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
drh0bd1f4e2002-06-06 18:54:39 +0000411#endif
danielk1977ededfd52004-06-17 07:53:01 +0000412 /* Deliberately leave the affinity string off of the following
413 ** OP_MakeRecord */
414 sqlite3VdbeAddOp(v, OP_MakeRecord, pEList->nExpr * -1, 0);
danielk19774adee202004-05-08 08:23:19 +0000415 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
416 sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
417 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000418 VdbeComment((v, "# skip indistinct records"));
danielk19770f69c1e2004-05-29 11:24:50 +0000419 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000420 sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
drhea48eb22004-07-19 23:16:38 +0000421 if( pOrderBy==0 ){
drhbab39e12004-07-19 23:38:11 +0000422 codeLimiter(v, p, iContinue, iBreak, nColumn);
drhea48eb22004-07-19 23:16:38 +0000423 }
drh22827922000-06-06 17:27:05 +0000424 }
drh82c3d632000-06-06 21:56:07 +0000425
drhc926afb2002-06-20 03:38:26 +0000426 switch( eDest ){
427 /* In this mode, write each query result to the key of the temporary
428 ** table iParm.
429 */
430 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000431 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000432 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000433 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000434 sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000435 break;
drh22827922000-06-06 17:27:05 +0000436 }
drh22827922000-06-06 17:27:05 +0000437
drhc926afb2002-06-20 03:38:26 +0000438 /* Store the result as data using a unique key.
439 */
440 case SRT_Table:
441 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000442 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000443 if( pOrderBy ){
444 pushOntoSorter(pParse, v, pOrderBy);
445 }else{
danielk19774adee202004-05-08 08:23:19 +0000446 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
447 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
448 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000449 }
450 break;
451 }
drh82c3d632000-06-06 21:56:07 +0000452
drhc926afb2002-06-20 03:38:26 +0000453 /* Construct a record from the query result, but instead of
454 ** saving that record, use it as a key to delete elements from
455 ** the temporary table iParm.
456 */
457 case SRT_Except: {
458 int addr;
danielk19774adee202004-05-08 08:23:19 +0000459 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000460 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000461 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
462 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000463 break;
464 }
drh5974a302000-06-07 14:42:26 +0000465
drhc926afb2002-06-20 03:38:26 +0000466 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
467 ** then there should be a single item on the stack. Write this
468 ** item into the set table with bogus data.
469 */
470 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000471 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000472 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000473
drhc926afb2002-06-20 03:38:26 +0000474 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000475 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
476 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
477 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000478 if( pOrderBy ){
479 pushOntoSorter(pParse, v, pOrderBy);
480 }else{
danielk1977e014a832004-05-17 10:48:57 +0000481 char aff = (iParm>>16)&0xFF;
482 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
drh94a11212004-09-25 13:12:14 +0000483 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1);
danielk19770f69c1e2004-05-29 11:24:50 +0000484 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000485 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000486 }
danielk19774adee202004-05-08 08:23:19 +0000487 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000488 break;
489 }
drh22827922000-06-06 17:27:05 +0000490
drhc926afb2002-06-20 03:38:26 +0000491 /* If this is a scalar select that is part of an expression, then
492 ** store the results in the appropriate memory cell and break out
493 ** of the scan loop.
494 */
495 case SRT_Mem: {
496 assert( nColumn==1 );
497 if( pOrderBy ){
498 pushOntoSorter(pParse, v, pOrderBy);
499 }else{
danielk19774adee202004-05-08 08:23:19 +0000500 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
501 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000502 }
503 break;
504 }
drh22827922000-06-06 17:27:05 +0000505
drhf46f9052002-06-22 02:33:38 +0000506 /* Send the data to the callback function.
507 */
508 case SRT_Callback:
509 case SRT_Sorter: {
510 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000511 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000512 pushOntoSorter(pParse, v, pOrderBy);
513 }else{
514 assert( eDest==SRT_Callback );
danielk19774adee202004-05-08 08:23:19 +0000515 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000516 }
517 break;
518 }
519
drh142e30d2002-08-28 03:00:58 +0000520 /* Invoke a subroutine to handle the results. The subroutine itself
521 ** is responsible for popping the results off of the stack.
522 */
523 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000524 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000525 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000526 pushOntoSorter(pParse, v, pOrderBy);
527 }else{
danielk19774adee202004-05-08 08:23:19 +0000528 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhac82fcf2002-09-08 17:23:41 +0000529 }
drh142e30d2002-08-28 03:00:58 +0000530 break;
531 }
532
drhc926afb2002-06-20 03:38:26 +0000533 /* Discard the results. This is used for SELECT statements inside
534 ** the body of a TRIGGER. The purpose of such selects is to call
535 ** user-defined functions that have side effects. We do not care
536 ** about the actual results of the select.
537 */
drhc926afb2002-06-20 03:38:26 +0000538 default: {
drhf46f9052002-06-22 02:33:38 +0000539 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000540 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000541 break;
542 }
drh82c3d632000-06-06 21:56:07 +0000543 }
544 return 0;
545}
546
547/*
drhd8bc7082000-06-07 23:51:50 +0000548** If the inner loop was generated using a non-null pOrderBy argument,
549** then the results were placed in a sorter. After the loop is terminated
550** we need to run the sorter and output the results. The following
551** routine generates the code needed to do that.
552*/
drhc926afb2002-06-20 03:38:26 +0000553static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000554 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000555 Select *p, /* The SELECT statement */
556 Vdbe *v, /* Generate code into this VDBE */
557 int nColumn, /* Number of columns of data */
558 int eDest, /* Write the sorted results here */
559 int iParm /* Optional parameter associated with eDest */
560){
danielk19774adee202004-05-08 08:23:19 +0000561 int end1 = sqlite3VdbeMakeLabel(v);
562 int end2 = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000563 int addr;
drhffbc3082004-05-21 01:29:06 +0000564 KeyInfo *pInfo;
565 ExprList *pOrderBy;
566 int nCol, i;
drh9bb575f2004-09-06 17:24:11 +0000567 sqlite3 *db = pParse->db;
drhffbc3082004-05-21 01:29:06 +0000568
drhf46f9052002-06-22 02:33:38 +0000569 if( eDest==SRT_Sorter ) return;
drhffbc3082004-05-21 01:29:06 +0000570 pOrderBy = p->pOrderBy;
571 nCol = pOrderBy->nExpr;
572 pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
573 if( pInfo==0 ) return;
574 pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
575 pInfo->nField = nCol;
576 for(i=0; i<nCol; i++){
danielk19770202b292004-06-09 09:55:16 +0000577 /* If a collation sequence was specified explicity, then it
578 ** is stored in pOrderBy->a[i].zName. Otherwise, use the default
579 ** collation type for the expression.
580 */
danielk19777cedc8d2004-06-10 10:50:08 +0000581 pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr);
danielk19770202b292004-06-09 09:55:16 +0000582 if( !pInfo->aColl[i] ){
583 pInfo->aColl[i] = db->pDfltColl;
584 }
drhffbc3082004-05-21 01:29:06 +0000585 pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
586 }
587 sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
danielk19774adee202004-05-08 08:23:19 +0000588 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
drhbab39e12004-07-19 23:38:11 +0000589 codeLimiter(v, p, addr, end2, 1);
drhc926afb2002-06-20 03:38:26 +0000590 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000591 case SRT_Table:
592 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000593 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
594 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
595 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000596 break;
597 }
598 case SRT_Set: {
599 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000600 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
601 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
602 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
danielk1977ededfd52004-06-17 07:53:01 +0000603 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000604 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000605 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000606 break;
607 }
608 case SRT_Mem: {
609 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000610 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
611 sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
drhc926afb2002-06-20 03:38:26 +0000612 break;
613 }
drhce665cf2004-05-21 03:01:58 +0000614 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000615 case SRT_Subroutine: {
616 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000617 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
618 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000619 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000620 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000621 }
drhce665cf2004-05-21 03:01:58 +0000622 if( eDest==SRT_Callback ){
623 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
624 }else{
625 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
626 }
danielk197784ac9d02004-05-18 09:58:06 +0000627 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000628 break;
629 }
drhc926afb2002-06-20 03:38:26 +0000630 default: {
drhf46f9052002-06-22 02:33:38 +0000631 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000632 break;
633 }
634 }
danielk19774adee202004-05-08 08:23:19 +0000635 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
636 sqlite3VdbeResolveLabel(v, end2);
637 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
638 sqlite3VdbeResolveLabel(v, end1);
639 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000640}
641
642/*
danielk1977517eb642004-06-07 10:00:31 +0000643** Return a pointer to a string containing the 'declaration type' of the
644** expression pExpr. The string may be treated as static by the caller.
drhe78e8282003-01-19 03:59:45 +0000645**
danielk1977517eb642004-06-07 10:00:31 +0000646** If the declaration type is the exact datatype definition extracted from
647** the original CREATE TABLE statement if the expression is a column.
648**
649** The declaration type for an expression is either TEXT, NUMERIC or ANY.
650** The declaration type for a ROWID field is INTEGER.
651*/
652static const char *columnType(Parse *pParse, SrcList *pTabList, Expr *pExpr){
danielk197700e279d2004-06-21 07:36:32 +0000653 char const *zType;
danielk1977517eb642004-06-07 10:00:31 +0000654 int j;
danielk197700e279d2004-06-21 07:36:32 +0000655 if( pExpr==0 || pTabList==0 ) return 0;
656
drh9b3187e2005-01-18 14:45:47 +0000657 sqlite3ExprResolveNames(pParse, pTabList, 0, pExpr, 1, 0);
danielk197700e279d2004-06-21 07:36:32 +0000658 switch( pExpr->op ){
659 case TK_COLUMN: {
660 Table *pTab;
661 int iCol = pExpr->iColumn;
662 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable; j++){}
663 assert( j<pTabList->nSrc );
664 pTab = pTabList->a[j].pTab;
665 if( iCol<0 ) iCol = pTab->iPKey;
666 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
667 if( iCol<0 ){
668 zType = "INTEGER";
669 }else{
670 zType = pTab->aCol[iCol].zType;
671 }
672 break;
danielk1977517eb642004-06-07 10:00:31 +0000673 }
danielk197700e279d2004-06-21 07:36:32 +0000674 case TK_SELECT: {
675 Select *pS = pExpr->pSelect;
676 zType = columnType(pParse, pS->pSrc, pS->pEList->a[0].pExpr);
677 break;
danielk1977517eb642004-06-07 10:00:31 +0000678 }
drh018d1a42005-01-15 01:52:31 +0000679 case TK_AS:
680 /* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING,
681 ** and LIMIT clauses. But pExpr originates in the result set of a
682 ** SELECT. So pExpr can never contain an AS operator.
683 */
684 assert( 0 );
685 /* Fall thru */
danielk197700e279d2004-06-21 07:36:32 +0000686 default:
687 zType = 0;
danielk1977517eb642004-06-07 10:00:31 +0000688 }
danielk197700e279d2004-06-21 07:36:32 +0000689
danielk1977517eb642004-06-07 10:00:31 +0000690 return zType;
691}
692
693/*
694** Generate code that will tell the VDBE the declaration types of columns
695** in the result set.
drhfcb78a42003-01-18 20:11:05 +0000696*/
697static void generateColumnTypes(
698 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000699 SrcList *pTabList, /* List of tables */
700 ExprList *pEList /* Expressions defining the result set */
701){
702 Vdbe *v = pParse->pVdbe;
danielk1977517eb642004-06-07 10:00:31 +0000703 int i;
drhfcb78a42003-01-18 20:11:05 +0000704 for(i=0; i<pEList->nExpr; i++){
705 Expr *p = pEList->a[i].pExpr;
danielk1977517eb642004-06-07 10:00:31 +0000706 const char *zType = columnType(pParse, pTabList, p);
danielk197700e279d2004-06-21 07:36:32 +0000707 if( zType==0 ) continue;
danielk1977fbcd5852004-06-15 02:44:18 +0000708 /* The vdbe must make it's own copy of the column-type, in case the
709 ** schema is reset before this virtual machine is deleted.
710 */
711 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
drhfcb78a42003-01-18 20:11:05 +0000712 }
713}
714
715/*
716** Generate code that will tell the VDBE the names of columns
717** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000718** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000719*/
drh832508b2002-03-02 17:04:07 +0000720static void generateColumnNames(
721 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000722 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000723 ExprList *pEList /* Expressions defining the result set */
724){
drhd8bc7082000-06-07 23:51:50 +0000725 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000726 int i, j;
drh9bb575f2004-09-06 17:24:11 +0000727 sqlite3 *db = pParse->db;
drhfcabd462004-02-20 14:50:58 +0000728 int fullNames, shortNames;
729
danielk19773cf86062004-05-26 10:11:05 +0000730 /* If this is an EXPLAIN, skip this step */
731 if( pParse->explain ){
danielk197761de0d12004-05-27 23:56:16 +0000732 return;
danielk19773cf86062004-05-26 10:11:05 +0000733 }
734
drhd6502752004-02-16 03:44:01 +0000735 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000736 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000737 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000738 fullNames = (db->flags & SQLITE_FullColNames)!=0;
739 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
danielk197722322fd2004-05-25 23:35:17 +0000740 sqlite3VdbeSetNumCols(v, pEList->nExpr);
drh82c3d632000-06-06 21:56:07 +0000741 for(i=0; i<pEList->nExpr; i++){
742 Expr *p;
drh5a387052003-01-11 14:19:51 +0000743 p = pEList->a[i].pExpr;
744 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000745 if( pEList->a[i].zName ){
746 char *zName = pEList->a[i].zName;
danielk1977d8123362004-06-12 09:25:12 +0000747 sqlite3VdbeSetColName(v, i, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000748 continue;
749 }
drhfa173a72002-07-10 21:26:00 +0000750 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000751 Table *pTab;
drh97665872002-02-13 23:22:53 +0000752 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000753 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000754 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
755 assert( j<pTabList->nSrc );
756 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000757 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000758 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000759 if( iCol<0 ){
760 zCol = "_ROWID_";
drhb1363202002-06-26 02:45:03 +0000761 }else{
762 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000763 }
drhfcabd462004-02-20 14:50:58 +0000764 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000765 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
drhfcabd462004-02-20 14:50:58 +0000766 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000767 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000768 char *zTab;
769
drh6a3ea0e2003-05-02 14:32:12 +0000770 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000771 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000772 sqlite3SetString(&zName, zTab, ".", zCol, 0);
danielk19773cf86062004-05-26 10:11:05 +0000773 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000774 }else{
danielk19773cf86062004-05-26 10:11:05 +0000775 sqlite3VdbeSetColName(v, i, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000776 }
drh6977fea2002-10-22 23:38:04 +0000777 }else if( p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000778 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
779 /* sqlite3VdbeCompressSpace(v, addr); */
drh1bee3d72001-10-15 00:44:35 +0000780 }else{
781 char zName[30];
782 assert( p->op!=TK_COLUMN || pTabList==0 );
783 sprintf(zName, "column%d", i+1);
danielk19773cf86062004-05-26 10:11:05 +0000784 sqlite3VdbeSetColName(v, i, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000785 }
786 }
danielk197776d505b2004-05-28 13:13:02 +0000787 generateColumnTypes(pParse, pTabList, pEList);
drh82c3d632000-06-06 21:56:07 +0000788}
789
790/*
drhd8bc7082000-06-07 23:51:50 +0000791** Name of the connection operator, used for error messages.
792*/
793static const char *selectOpName(int id){
794 char *z;
795 switch( id ){
796 case TK_ALL: z = "UNION ALL"; break;
797 case TK_INTERSECT: z = "INTERSECT"; break;
798 case TK_EXCEPT: z = "EXCEPT"; break;
799 default: z = "UNION"; break;
800 }
801 return z;
802}
803
804/*
drh315555c2002-10-20 15:53:03 +0000805** Forward declaration
806*/
drh9b3187e2005-01-18 14:45:47 +0000807static int prepSelectStmt(Parse*, Select*);
drh315555c2002-10-20 15:53:03 +0000808
809/*
drh22f70c32002-02-18 01:17:00 +0000810** Given a SELECT statement, generate a Table structure that describes
811** the result set of that SELECT.
812*/
danielk19774adee202004-05-08 08:23:19 +0000813Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000814 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000815 int i, j;
drh22f70c32002-02-18 01:17:00 +0000816 ExprList *pEList;
drh290c1942004-08-21 17:54:45 +0000817 Column *aCol, *pCol;
drh22f70c32002-02-18 01:17:00 +0000818
drh9b3187e2005-01-18 14:45:47 +0000819 if( prepSelectStmt(pParse, pSelect) ){
drh22f70c32002-02-18 01:17:00 +0000820 return 0;
821 }
822 pTab = sqliteMalloc( sizeof(Table) );
823 if( pTab==0 ){
824 return 0;
825 }
826 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
827 pEList = pSelect->pEList;
828 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000829 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000830 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh290c1942004-08-21 17:54:45 +0000831 for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
danielk1977517eb642004-06-07 10:00:31 +0000832 Expr *pR;
833 char *zType;
drh91bb0ee2004-09-01 03:06:34 +0000834 char *zName;
danielk1977517eb642004-06-07 10:00:31 +0000835 Expr *p = pEList->a[i].pExpr;
drh290c1942004-08-21 17:54:45 +0000836 assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
drh91bb0ee2004-09-01 03:06:34 +0000837 if( (zName = pEList->a[i].zName)!=0 ){
838 zName = sqliteStrDup(zName);
danielk1977517eb642004-06-07 10:00:31 +0000839 }else if( p->op==TK_DOT
drhb733d032004-01-24 20:18:12 +0000840 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
841 int cnt;
drh91bb0ee2004-09-01 03:06:34 +0000842 zName = sqlite3MPrintf("%T", &pR->token);
drhb733d032004-01-24 20:18:12 +0000843 for(j=cnt=0; j<i; j++){
drh91bb0ee2004-09-01 03:06:34 +0000844 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
845 sqliteFree(zName);
846 zName = sqlite3MPrintf("%T_%d", &pR->token, ++cnt);
drhb733d032004-01-24 20:18:12 +0000847 j = -1;
848 }
849 }
850 }else if( p->span.z && p->span.z[0] ){
drh91bb0ee2004-09-01 03:06:34 +0000851 zName = sqlite3MPrintf("%T", &p->span);
drh22f70c32002-02-18 01:17:00 +0000852 }else{
drh91bb0ee2004-09-01 03:06:34 +0000853 zName = sqlite3MPrintf("column%d", i+1);
drh22f70c32002-02-18 01:17:00 +0000854 }
drh91bb0ee2004-09-01 03:06:34 +0000855 sqlite3Dequote(zName);
856 pCol->zName = zName;
danielk1977517eb642004-06-07 10:00:31 +0000857
858 zType = sqliteStrDup(columnType(pParse, pSelect->pSrc ,p));
drh290c1942004-08-21 17:54:45 +0000859 pCol->zType = zType;
860 pCol->affinity = SQLITE_AFF_NUMERIC;
danielk1977517eb642004-06-07 10:00:31 +0000861 if( zType ){
drh290c1942004-08-21 17:54:45 +0000862 pCol->affinity = sqlite3AffinityType(zType, strlen(zType));
danielk1977517eb642004-06-07 10:00:31 +0000863 }
drh290c1942004-08-21 17:54:45 +0000864 pCol->pColl = sqlite3ExprCollSeq(pParse, p);
865 if( !pCol->pColl ){
866 pCol->pColl = pParse->db->pDfltColl;
danielk19770202b292004-06-09 09:55:16 +0000867 }
drh22f70c32002-02-18 01:17:00 +0000868 }
869 pTab->iPKey = -1;
870 return pTab;
871}
872
873/*
drh9b3187e2005-01-18 14:45:47 +0000874** Prepare a SELECT statement for processing by doing the following
875** things:
drhd8bc7082000-06-07 23:51:50 +0000876**
drh9b3187e2005-01-18 14:45:47 +0000877** (1) Make sure VDBE cursor numbers have been assigned to every
878** element of the FROM clause.
879**
880** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
881** defines FROM clause. When views appear in the FROM clause,
drh63eb5f22003-04-29 16:20:44 +0000882** fill pTabList->a[].pSelect with a copy of the SELECT statement
883** that implements the view. A copy is made of the view's SELECT
884** statement so that we can freely modify or delete that statement
885** without worrying about messing up the presistent representation
886** of the view.
drhd8bc7082000-06-07 23:51:50 +0000887**
drh9b3187e2005-01-18 14:45:47 +0000888** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
drhad2d8302002-05-24 20:31:36 +0000889** on joins and the ON and USING clause of joins.
890**
drh9b3187e2005-01-18 14:45:47 +0000891** (4) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000892** for instances of the "*" operator or the TABLE.* operator.
893** If found, expand each "*" to be every column in every table
894** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000895**
896** Return 0 on success. If there are problems, leave an error message
897** in pParse and return non-zero.
898*/
drh9b3187e2005-01-18 14:45:47 +0000899static int prepSelectStmt(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000900 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000901 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000902 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000903 Table *pTab;
drh290c1942004-08-21 17:54:45 +0000904 struct SrcList_item *pFrom;
drhdaffd0e2001-04-11 14:28:42 +0000905
906 if( p==0 || p->pSrc==0 ) return 1;
907 pTabList = p->pSrc;
908 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000909
drh9b3187e2005-01-18 14:45:47 +0000910 /* Make sure cursor numbers have been assigned to all entries in
911 ** the FROM clause of the SELECT statement.
912 */
913 sqlite3SrcListAssignCursors(pParse, p->pSrc);
914
915 /* Look up every table named in the FROM clause of the select. If
916 ** an entry of the FROM clause is a subquery instead of a table or view,
917 ** then create a transient table structure to describe the subquery.
drhd8bc7082000-06-07 23:51:50 +0000918 */
drh290c1942004-08-21 17:54:45 +0000919 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
drh9b3187e2005-01-18 14:45:47 +0000920 if( pFrom->pTab!=0 ){
921 /* This statement has already been prepared. There is no need
922 ** to go further. */
923 assert( i==0 );
drhd8bc7082000-06-07 23:51:50 +0000924 return 0;
925 }
drh290c1942004-08-21 17:54:45 +0000926 if( pFrom->zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000927 /* A sub-query in the FROM clause of a SELECT */
drh290c1942004-08-21 17:54:45 +0000928 assert( pFrom->pSelect!=0 );
929 if( pFrom->zAlias==0 ){
drh91bb0ee2004-09-01 03:06:34 +0000930 pFrom->zAlias =
931 sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
drhad2d8302002-05-24 20:31:36 +0000932 }
drh290c1942004-08-21 17:54:45 +0000933 pFrom->pTab = pTab =
934 sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
drh22f70c32002-02-18 01:17:00 +0000935 if( pTab==0 ){
936 return 1;
937 }
drh5cf590c2003-04-24 01:45:04 +0000938 /* The isTransient flag indicates that the Table structure has been
939 ** dynamically allocated and may be freed at any time. In other words,
940 ** pTab is not pointing to a persistent table structure that defines
941 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000942 pTab->isTransient = 1;
943 }else{
drha76b5df2002-02-23 02:32:10 +0000944 /* An ordinary table or view name in the FROM clause */
drh290c1942004-08-21 17:54:45 +0000945 pFrom->pTab = pTab =
946 sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
drha76b5df2002-02-23 02:32:10 +0000947 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000948 return 1;
949 }
drha76b5df2002-02-23 02:32:10 +0000950 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +0000951 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +0000952 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +0000953 return 1;
954 }
drh290c1942004-08-21 17:54:45 +0000955 /* If pFrom->pSelect!=0 it means we are dealing with a
drh63eb5f22003-04-29 16:20:44 +0000956 ** view within a view. The SELECT structure has already been
957 ** copied by the outer view so we can skip the copy step here
958 ** in the inner view.
959 */
drh290c1942004-08-21 17:54:45 +0000960 if( pFrom->pSelect==0 ){
961 pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +0000962 }
drha76b5df2002-02-23 02:32:10 +0000963 }
drhd8bc7082000-06-07 23:51:50 +0000964 }
965 }
966
drhad2d8302002-05-24 20:31:36 +0000967 /* Process NATURAL keywords, and ON and USING clauses of joins.
968 */
969 if( sqliteProcessJoin(pParse, p) ) return 1;
970
drh7c917d12001-12-16 20:05:05 +0000971 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000972 ** all columns in all tables. And for every TABLE.* insert the names
973 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000974 ** with the TK_ALL operator for each "*" that it found in the column list.
975 ** The following code just has to locate the TK_ALL expressions and expand
976 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000977 **
978 ** The first loop just checks to see if there are any "*" operators
979 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000980 */
drh7c917d12001-12-16 20:05:05 +0000981 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000982 Expr *pE = pEList->a[k].pExpr;
983 if( pE->op==TK_ALL ) break;
984 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
985 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000986 }
drh54473222002-04-04 02:10:55 +0000987 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000988 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000989 /*
990 ** If we get here it means the result set contains one or more "*"
991 ** operators that need to be expanded. Loop through each expression
992 ** in the result set and expand them one by one.
993 */
drh7c917d12001-12-16 20:05:05 +0000994 struct ExprList_item *a = pEList->a;
995 ExprList *pNew = 0;
996 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000997 Expr *pE = a[k].pExpr;
998 if( pE->op!=TK_ALL &&
999 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
1000 /* This particular expression does not need to be expanded.
1001 */
danielk19774adee202004-05-08 08:23:19 +00001002 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001003 pNew->a[pNew->nExpr-1].zName = a[k].zName;
1004 a[k].pExpr = 0;
1005 a[k].zName = 0;
1006 }else{
drh54473222002-04-04 02:10:55 +00001007 /* This expression is a "*" or a "TABLE.*" and needs to be
1008 ** expanded. */
1009 int tableSeen = 0; /* Set to 1 when TABLE matches */
drhcf55b7a2004-07-20 01:45:19 +00001010 char *zTName; /* text of name of TABLE */
drh54473222002-04-04 02:10:55 +00001011 if( pE->op==TK_DOT && pE->pLeft ){
drhcf55b7a2004-07-20 01:45:19 +00001012 zTName = sqlite3NameFromToken(&pE->pLeft->token);
drh54473222002-04-04 02:10:55 +00001013 }else{
drhcf55b7a2004-07-20 01:45:19 +00001014 zTName = 0;
drh54473222002-04-04 02:10:55 +00001015 }
drh290c1942004-08-21 17:54:45 +00001016 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1017 Table *pTab = pFrom->pTab;
1018 char *zTabName = pFrom->zAlias;
drh54473222002-04-04 02:10:55 +00001019 if( zTabName==0 || zTabName[0]==0 ){
1020 zTabName = pTab->zName;
1021 }
drhcf55b7a2004-07-20 01:45:19 +00001022 if( zTName && (zTabName==0 || zTabName[0]==0 ||
1023 sqlite3StrICmp(zTName, zTabName)!=0) ){
drh54473222002-04-04 02:10:55 +00001024 continue;
1025 }
1026 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001027 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001028 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001029 char *zName = pTab->aCol[j].zName;
1030
drh91bb0ee2004-09-01 03:06:34 +00001031 if( i>0 ){
1032 struct SrcList_item *pLeft = &pTabList->a[i-1];
1033 if( (pLeft->jointype & JT_NATURAL)!=0 &&
1034 columnIndex(pLeft->pTab, zName)>=0 ){
1035 /* In a NATURAL join, omit the join columns from the
1036 ** table on the right */
1037 continue;
1038 }
1039 if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1040 /* In a join with a USING clause, omit columns in the
1041 ** using clause from the table on the right. */
1042 continue;
1043 }
drhad2d8302002-05-24 20:31:36 +00001044 }
danielk19774adee202004-05-08 08:23:19 +00001045 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001046 if( pRight==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001047 setToken(&pRight->token, zName);
drh4b59ab52002-08-24 18:24:51 +00001048 if( zTabName && pTabList->nSrc>1 ){
danielk19774adee202004-05-08 08:23:19 +00001049 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1050 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001051 if( pExpr==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001052 setToken(&pLeft->token, zTabName);
1053 setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
drh6977fea2002-10-22 23:38:04 +00001054 pExpr->span.dyn = 1;
1055 pExpr->token.z = 0;
1056 pExpr->token.n = 0;
1057 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001058 }else{
drh22f70c32002-02-18 01:17:00 +00001059 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001060 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001061 }
danielk19774adee202004-05-08 08:23:19 +00001062 pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001063 }
drh17e24df2001-11-06 14:10:41 +00001064 }
drh54473222002-04-04 02:10:55 +00001065 if( !tableSeen ){
drhcf55b7a2004-07-20 01:45:19 +00001066 if( zTName ){
1067 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
drhf5db2d32002-06-06 23:42:27 +00001068 }else{
danielk19774adee202004-05-08 08:23:19 +00001069 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001070 }
drh54473222002-04-04 02:10:55 +00001071 rc = 1;
1072 }
drhcf55b7a2004-07-20 01:45:19 +00001073 sqliteFree(zTName);
drhd8bc7082000-06-07 23:51:50 +00001074 }
1075 }
danielk19774adee202004-05-08 08:23:19 +00001076 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001077 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001078 }
drh54473222002-04-04 02:10:55 +00001079 return rc;
drhd8bc7082000-06-07 23:51:50 +00001080}
1081
1082/*
drhff78bd22002-02-27 01:47:11 +00001083** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1084** in a select structure. It just sets the pointers to NULL. This
1085** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1086** pointer is not NULL, this routine is called recursively on that pointer.
1087**
1088** This routine is called on the Select structure that defines a
1089** VIEW in order to undo any bindings to tables. This is necessary
1090** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001091** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1092** will be left pointing to a deallocated Table structure after the
1093** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001094*/
danielk19774adee202004-05-08 08:23:19 +00001095void sqlite3SelectUnbind(Select *p){
drhff78bd22002-02-27 01:47:11 +00001096 int i;
drhad3cab52002-05-24 02:04:32 +00001097 SrcList *pSrc = p->pSrc;
drh91bb0ee2004-09-01 03:06:34 +00001098 struct SrcList_item *pItem;
drhff78bd22002-02-27 01:47:11 +00001099 Table *pTab;
1100 if( p==0 ) return;
drh91bb0ee2004-09-01 03:06:34 +00001101 for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
1102 if( (pTab = pItem->pTab)!=0 ){
drhff78bd22002-02-27 01:47:11 +00001103 if( pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001104 sqlite3DeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001105 }
drh91bb0ee2004-09-01 03:06:34 +00001106 pItem->pTab = 0;
1107 if( pItem->pSelect ){
1108 sqlite3SelectUnbind(pItem->pSelect);
drhff78bd22002-02-27 01:47:11 +00001109 }
1110 }
1111 }
1112}
1113
1114/*
drhd8bc7082000-06-07 23:51:50 +00001115** This routine associates entries in an ORDER BY expression list with
1116** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001117** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001118** the top-level node is filled in with column number and the iTable
1119** value of the top-level node is filled with iTable parameter.
1120**
1121** If there are prior SELECT clauses, they are processed first. A match
1122** in an earlier SELECT takes precedence over a later SELECT.
1123**
1124** Any entry that does not match is flagged as an error. The number
1125** of errors is returned.
1126*/
1127static int matchOrderbyToColumn(
1128 Parse *pParse, /* A place to leave error messages */
1129 Select *pSelect, /* Match to result columns of this SELECT */
1130 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001131 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001132 int mustComplete /* If TRUE all ORDER BYs must match */
1133){
1134 int nErr = 0;
1135 int i, j;
1136 ExprList *pEList;
1137
drhdaffd0e2001-04-11 14:28:42 +00001138 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001139 if( mustComplete ){
1140 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1141 }
drh9b3187e2005-01-18 14:45:47 +00001142 if( prepSelectStmt(pParse, pSelect) ){
drhd8bc7082000-06-07 23:51:50 +00001143 return 1;
1144 }
1145 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001146 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1147 return 1;
1148 }
drhd8bc7082000-06-07 23:51:50 +00001149 }
1150 pEList = pSelect->pEList;
1151 for(i=0; i<pOrderBy->nExpr; i++){
1152 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001153 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001154 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001155 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001156 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001157 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001158 "ORDER BY position %d should be between 1 and %d",
1159 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001160 nErr++;
1161 break;
1162 }
drhfcb78a42003-01-18 20:11:05 +00001163 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001164 iCol--;
1165 }
1166 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001167 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001168 char *zName, *zLabel;
1169 zName = pEList->a[j].zName;
drha99db3b2004-06-19 14:49:12 +00001170 zLabel = sqlite3NameFromToken(&pE->token);
1171 assert( zLabel!=0 );
danielk19774adee202004-05-08 08:23:19 +00001172 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001173 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001174 }
drh6e142f52000-06-08 13:36:40 +00001175 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001176 }
danielk19774adee202004-05-08 08:23:19 +00001177 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001178 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001179 }
1180 }
drhe4de1fe2002-06-02 16:09:01 +00001181 if( iCol>=0 ){
1182 pE->op = TK_COLUMN;
1183 pE->iColumn = iCol;
1184 pE->iTable = iTable;
1185 pOrderBy->a[i].done = 1;
1186 }
1187 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001188 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001189 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001190 nErr++;
1191 break;
1192 }
1193 }
1194 return nErr;
1195}
1196
1197/*
1198** Get a VDBE for the given parser context. Create a new one if necessary.
1199** If an error occurs, return NULL and leave a message in pParse.
1200*/
danielk19774adee202004-05-08 08:23:19 +00001201Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001202 Vdbe *v = pParse->pVdbe;
1203 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001204 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001205 }
drhd8bc7082000-06-07 23:51:50 +00001206 return v;
1207}
drhfcb78a42003-01-18 20:11:05 +00001208
drhd8bc7082000-06-07 23:51:50 +00001209/*
drh7b58dae2003-07-20 01:16:46 +00001210** Compute the iLimit and iOffset fields of the SELECT based on the
1211** nLimit and nOffset fields. nLimit and nOffset hold the integers
1212** that appear in the original SQL statement after the LIMIT and OFFSET
1213** keywords. Or that hold -1 and 0 if those keywords are omitted.
1214** iLimit and iOffset are the integer memory register numbers for
1215** counters used to compute the limit and offset. If there is no
1216** limit and/or offset, then iLimit and iOffset are negative.
1217**
1218** This routine changes the values if iLimit and iOffset only if
1219** a limit or offset is defined by nLimit and nOffset. iLimit and
1220** iOffset should have been preset to appropriate default values
1221** (usually but not always -1) prior to calling this routine.
1222** Only if nLimit>=0 or nOffset>0 do the limit registers get
1223** redefined. The UNION ALL operator uses this property to force
1224** the reuse of the same limit and offset registers across multiple
1225** SELECT statements.
1226*/
1227static void computeLimitRegisters(Parse *pParse, Select *p){
1228 /*
1229 ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
1230 ** all rows. It is the same as no limit. If the comparision is
1231 ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
1232 ** "LIMIT -1" always shows all rows. There is some
1233 ** contraversy about what the correct behavior should be.
1234 ** The current implementation interprets "LIMIT 0" to mean
1235 ** no rows.
1236 */
1237 if( p->nLimit>=0 ){
1238 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001239 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001240 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001241 sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1242 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001243 VdbeComment((v, "# LIMIT counter"));
drh7b58dae2003-07-20 01:16:46 +00001244 p->iLimit = iMem;
1245 }
1246 if( p->nOffset>0 ){
1247 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001248 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001249 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001250 sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1251 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001252 VdbeComment((v, "# OFFSET counter"));
drh7b58dae2003-07-20 01:16:46 +00001253 p->iOffset = iMem;
1254 }
1255}
1256
1257/*
drhd3d39e92004-05-20 22:16:29 +00001258** Generate VDBE instructions that will open a transient table that
1259** will be used for an index or to store keyed results for a compound
1260** select. In other words, open a transient table that needs a
1261** KeyInfo structure. The number of columns in the KeyInfo is determined
1262** by the result set of the SELECT statement in the second argument.
1263**
danielk1977dc1bdc42004-06-11 10:51:27 +00001264** Specifically, this routine is called to open an index table for
1265** DISTINCT, UNION, INTERSECT and EXCEPT select statements (but not
1266** UNION ALL).
1267**
drhd3d39e92004-05-20 22:16:29 +00001268** Make the new table a KeyAsData table if keyAsData is true.
danielk1977dc1bdc42004-06-11 10:51:27 +00001269**
1270** The value returned is the address of the OP_OpenTemp instruction.
drhd3d39e92004-05-20 22:16:29 +00001271*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001272static int openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
drhd3d39e92004-05-20 22:16:29 +00001273 KeyInfo *pKeyInfo;
drh736c22b2004-05-21 02:14:24 +00001274 int nColumn;
drh9bb575f2004-09-06 17:24:11 +00001275 sqlite3 *db = pParse->db;
drhd3d39e92004-05-20 22:16:29 +00001276 int i;
1277 Vdbe *v = pParse->pVdbe;
danielk1977dc1bdc42004-06-11 10:51:27 +00001278 int addr;
drhd3d39e92004-05-20 22:16:29 +00001279
drh9b3187e2005-01-18 14:45:47 +00001280 if( prepSelectStmt(pParse, p) ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001281 return 0;
drh736c22b2004-05-21 02:14:24 +00001282 }
1283 nColumn = p->pEList->nExpr;
drhd3d39e92004-05-20 22:16:29 +00001284 pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
danielk1977dc1bdc42004-06-11 10:51:27 +00001285 if( pKeyInfo==0 ) return 0;
drh91bb0ee2004-09-01 03:06:34 +00001286 pKeyInfo->enc = db->enc;
drhd3d39e92004-05-20 22:16:29 +00001287 pKeyInfo->nField = nColumn;
1288 for(i=0; i<nColumn; i++){
danielk1977dc1bdc42004-06-11 10:51:27 +00001289 pKeyInfo->aColl[i] = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
1290 if( !pKeyInfo->aColl[i] ){
1291 pKeyInfo->aColl[i] = db->pDfltColl;
1292 }
drhd3d39e92004-05-20 22:16:29 +00001293 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001294 addr = sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0,
1295 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drhd3d39e92004-05-20 22:16:29 +00001296 if( keyAsData ){
1297 sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1298 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001299 return addr;
1300}
1301
drhb7f91642004-10-31 02:22:47 +00001302#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001303/*
drh8cdbf832004-08-29 16:25:03 +00001304** Add the address "addr" to the set of all OpenTemp opcode addresses
1305** that are being accumulated in p->ppOpenTemp.
drhfbc4ee72004-08-29 01:31:05 +00001306*/
drh8cdbf832004-08-29 16:25:03 +00001307static int multiSelectOpenTempAddr(Select *p, int addr){
1308 IdList *pList = *p->ppOpenTemp = sqlite3IdListAppend(*p->ppOpenTemp, 0);
drhfbc4ee72004-08-29 01:31:05 +00001309 if( pList==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001310 return SQLITE_NOMEM;
1311 }
drhfbc4ee72004-08-29 01:31:05 +00001312 pList->a[pList->nId-1].idx = addr;
danielk1977dc1bdc42004-06-11 10:51:27 +00001313 return SQLITE_OK;
1314}
drhb7f91642004-10-31 02:22:47 +00001315#endif /* SQLITE_OMIT_COMPOUND_SELECT */
danielk1977dc1bdc42004-06-11 10:51:27 +00001316
drhb7f91642004-10-31 02:22:47 +00001317#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001318/*
1319** Return the appropriate collating sequence for the iCol-th column of
1320** the result set for the compound-select statement "p". Return NULL if
1321** the column has no default collating sequence.
1322**
1323** The collating sequence for the compound select is taken from the
1324** left-most term of the select that has a collating sequence.
1325*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001326static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
drhfbc4ee72004-08-29 01:31:05 +00001327 CollSeq *pRet;
danielk1977dc1bdc42004-06-11 10:51:27 +00001328 if( p->pPrior ){
1329 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
drhfbc4ee72004-08-29 01:31:05 +00001330 }else{
1331 pRet = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001332 }
drhfbc4ee72004-08-29 01:31:05 +00001333 if( pRet==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001334 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1335 }
1336 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001337}
drhb7f91642004-10-31 02:22:47 +00001338#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd3d39e92004-05-20 22:16:29 +00001339
drhb7f91642004-10-31 02:22:47 +00001340#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhd3d39e92004-05-20 22:16:29 +00001341/*
drh82c3d632000-06-06 21:56:07 +00001342** This routine is called to process a query that is really the union
1343** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001344**
drhe78e8282003-01-19 03:59:45 +00001345** "p" points to the right-most of the two queries. the query on the
1346** left is p->pPrior. The left query could also be a compound query
1347** in which case this routine will be called recursively.
1348**
1349** The results of the total query are to be written into a destination
1350** of type eDest with parameter iParm.
1351**
1352** Example 1: Consider a three-way compound SQL statement.
1353**
1354** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1355**
1356** This statement is parsed up as follows:
1357**
1358** SELECT c FROM t3
1359** |
1360** `-----> SELECT b FROM t2
1361** |
jplyon4b11c6d2004-01-19 04:57:53 +00001362** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001363**
1364** The arrows in the diagram above represent the Select.pPrior pointer.
1365** So if this routine is called with p equal to the t3 query, then
1366** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1367**
1368** Notice that because of the way SQLite parses compound SELECTs, the
1369** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001370*/
danielk197784ac9d02004-05-18 09:58:06 +00001371static int multiSelect(
drhfbc4ee72004-08-29 01:31:05 +00001372 Parse *pParse, /* Parsing context */
1373 Select *p, /* The right-most of SELECTs to be coded */
1374 int eDest, /* \___ Store query results as specified */
1375 int iParm, /* / by these two parameters. */
1376 char *aff /* If eDest is SRT_Union, the affinity string */
danielk197784ac9d02004-05-18 09:58:06 +00001377){
drhfbc4ee72004-08-29 01:31:05 +00001378 int rc = SQLITE_OK; /* Success code from a subroutine */
1379 Select *pPrior; /* Another SELECT immediately to our left */
1380 Vdbe *v; /* Generate code to this VDBE */
1381 IdList *pOpenTemp = 0;/* OP_OpenTemp opcodes that need a KeyInfo */
drh8cdbf832004-08-29 16:25:03 +00001382 int aAddr[5]; /* Addresses of SetNumColumns operators */
1383 int nAddr = 0; /* Number used */
1384 int nCol; /* Number of columns in the result set */
drh82c3d632000-06-06 21:56:07 +00001385
drh7b58dae2003-07-20 01:16:46 +00001386 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
drhfbc4ee72004-08-29 01:31:05 +00001387 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001388 */
danielk197784ac9d02004-05-18 09:58:06 +00001389 if( p==0 || p->pPrior==0 ){
1390 rc = 1;
1391 goto multi_select_end;
1392 }
drhd8bc7082000-06-07 23:51:50 +00001393 pPrior = p->pPrior;
1394 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001395 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001396 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001397 rc = 1;
1398 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001399 }
drh7b58dae2003-07-20 01:16:46 +00001400 if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
danielk19774adee202004-05-08 08:23:19 +00001401 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001402 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001403 rc = 1;
1404 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001405 }
drh82c3d632000-06-06 21:56:07 +00001406
drhd8bc7082000-06-07 23:51:50 +00001407 /* Make sure we have a valid query engine. If not, create a new one.
1408 */
danielk19774adee202004-05-08 08:23:19 +00001409 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001410 if( v==0 ){
1411 rc = 1;
1412 goto multi_select_end;
1413 }
drhd8bc7082000-06-07 23:51:50 +00001414
drh8cdbf832004-08-29 16:25:03 +00001415 /* If *p this is the right-most select statement, then initialize
1416 ** p->ppOpenTemp to point to pOpenTemp. If *p is not the right most
1417 ** statement then p->ppOpenTemp will have already been initialized
1418 ** by a prior call to this same procedure. Pass along the pOpenTemp
1419 ** pointer to pPrior, the next statement to our left.
drhfbc4ee72004-08-29 01:31:05 +00001420 */
1421 if( p->ppOpenTemp==0 ){
1422 p->ppOpenTemp = &pOpenTemp;
1423 }
1424 pPrior->ppOpenTemp = p->ppOpenTemp;
1425
drh1cc3d752002-03-23 00:31:29 +00001426 /* Create the destination temporary table if necessary
1427 */
1428 if( eDest==SRT_TempTable ){
danielk1977b4964b72004-05-18 01:23:38 +00001429 assert( p->pEList );
danielk19774adee202004-05-08 08:23:19 +00001430 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
drh8cdbf832004-08-29 16:25:03 +00001431 assert( nAddr==0 );
1432 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 0);
drh1cc3d752002-03-23 00:31:29 +00001433 eDest = SRT_Table;
1434 }
1435
drhf46f9052002-06-22 02:33:38 +00001436 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001437 */
drh82c3d632000-06-06 21:56:07 +00001438 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001439 case TK_ALL: {
1440 if( p->pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +00001441 pPrior->nLimit = p->nLimit;
1442 pPrior->nOffset = p->nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001443 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1444 if( rc ){
1445 goto multi_select_end;
1446 }
drhf46f9052002-06-22 02:33:38 +00001447 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001448 p->iLimit = pPrior->iLimit;
1449 p->iOffset = pPrior->iOffset;
1450 p->nLimit = -1;
1451 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001452 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001453 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001454 if( rc ){
1455 goto multi_select_end;
1456 }
drhf46f9052002-06-22 02:33:38 +00001457 break;
1458 }
1459 /* For UNION ALL ... ORDER BY fall through to the next case */
1460 }
drh82c3d632000-06-06 21:56:07 +00001461 case TK_EXCEPT:
1462 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001463 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001464 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001465 int priorOp; /* The SRT_ operation to apply to prior selects */
drh7b58dae2003-07-20 01:16:46 +00001466 int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
drhc926afb2002-06-20 03:38:26 +00001467 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
danielk1977dc1bdc42004-06-11 10:51:27 +00001468 int addr;
drh82c3d632000-06-06 21:56:07 +00001469
drhd8bc7082000-06-07 23:51:50 +00001470 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh7b58dae2003-07-20 01:16:46 +00001471 if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
drhd8bc7082000-06-07 23:51:50 +00001472 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001473 ** right.
drhd8bc7082000-06-07 23:51:50 +00001474 */
drh82c3d632000-06-06 21:56:07 +00001475 unionTab = iParm;
1476 }else{
drhd8bc7082000-06-07 23:51:50 +00001477 /* We will need to create our own temporary table to hold the
1478 ** intermediate results.
1479 */
1480 unionTab = pParse->nTab++;
1481 if( p->pOrderBy
1482 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001483 rc = 1;
1484 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001485 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001486 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001487 if( p->op!=TK_ALL ){
drh8cdbf832004-08-29 16:25:03 +00001488 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001489 if( rc!=SQLITE_OK ){
1490 goto multi_select_end;
1491 }
1492 sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drhd8bc7082000-06-07 23:51:50 +00001493 }
drh8cdbf832004-08-29 16:25:03 +00001494 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1495 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, 0);
danielk197784ac9d02004-05-18 09:58:06 +00001496 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001497 }
drhd8bc7082000-06-07 23:51:50 +00001498
1499 /* Code the SELECT statements to our left
1500 */
danielk197784ac9d02004-05-18 09:58:06 +00001501 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
1502 if( rc ){
1503 goto multi_select_end;
1504 }
drhd8bc7082000-06-07 23:51:50 +00001505
1506 /* Code the current SELECT statement
1507 */
1508 switch( p->op ){
1509 case TK_EXCEPT: op = SRT_Except; break;
1510 case TK_UNION: op = SRT_Union; break;
1511 case TK_ALL: op = SRT_Table; break;
1512 }
drh82c3d632000-06-06 21:56:07 +00001513 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001514 pOrderBy = p->pOrderBy;
1515 p->pOrderBy = 0;
drh7b58dae2003-07-20 01:16:46 +00001516 nLimit = p->nLimit;
1517 p->nLimit = -1;
1518 nOffset = p->nOffset;
1519 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001520 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001521 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001522 p->pOrderBy = pOrderBy;
drh7b58dae2003-07-20 01:16:46 +00001523 p->nLimit = nLimit;
1524 p->nOffset = nOffset;
drhbe5fd492004-12-16 21:09:16 +00001525 p->iLimit = -1;
1526 p->iOffset = -1;
danielk197784ac9d02004-05-18 09:58:06 +00001527 if( rc ){
1528 goto multi_select_end;
1529 }
1530
drhd8bc7082000-06-07 23:51:50 +00001531
1532 /* Convert the data in the temporary table into whatever form
1533 ** it is that we currently need.
1534 */
drhc926afb2002-06-20 03:38:26 +00001535 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001536 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001537 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001538 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001539 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001540 }
danielk19774adee202004-05-08 08:23:19 +00001541 iBreak = sqlite3VdbeMakeLabel(v);
1542 iCont = sqlite3VdbeMakeLabel(v);
1543 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001544 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001545 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001546 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001547 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001548 iCont, iBreak, 0);
1549 if( rc ){
1550 rc = 1;
1551 goto multi_select_end;
1552 }
danielk19774adee202004-05-08 08:23:19 +00001553 sqlite3VdbeResolveLabel(v, iCont);
1554 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1555 sqlite3VdbeResolveLabel(v, iBreak);
1556 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001557 }
1558 break;
1559 }
1560 case TK_INTERSECT: {
1561 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001562 int iCont, iBreak, iStart;
drh7b58dae2003-07-20 01:16:46 +00001563 int nLimit, nOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001564 int addr;
drh82c3d632000-06-06 21:56:07 +00001565
drhd8bc7082000-06-07 23:51:50 +00001566 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001567 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001568 ** by allocating the tables we will need.
1569 */
drh82c3d632000-06-06 21:56:07 +00001570 tab1 = pParse->nTab++;
1571 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001572 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001573 rc = 1;
1574 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001575 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001576
1577 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 0);
drh8cdbf832004-08-29 16:25:03 +00001578 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001579 if( rc!=SQLITE_OK ){
1580 goto multi_select_end;
1581 }
1582 sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
drh8cdbf832004-08-29 16:25:03 +00001583 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1584 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab1, 0);
danielk197784ac9d02004-05-18 09:58:06 +00001585 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001586
1587 /* Code the SELECTs to our left into temporary table "tab1".
1588 */
danielk197784ac9d02004-05-18 09:58:06 +00001589 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
1590 if( rc ){
1591 goto multi_select_end;
1592 }
drhd8bc7082000-06-07 23:51:50 +00001593
1594 /* Code the current SELECT into temporary table "tab2"
1595 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001596 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0);
drh8cdbf832004-08-29 16:25:03 +00001597 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001598 if( rc!=SQLITE_OK ){
1599 goto multi_select_end;
1600 }
1601 sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh8cdbf832004-08-29 16:25:03 +00001602 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1603 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab2, 0);
drh82c3d632000-06-06 21:56:07 +00001604 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001605 nLimit = p->nLimit;
1606 p->nLimit = -1;
1607 nOffset = p->nOffset;
1608 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001609 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001610 p->pPrior = pPrior;
drh7b58dae2003-07-20 01:16:46 +00001611 p->nLimit = nLimit;
1612 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001613 if( rc ){
1614 goto multi_select_end;
1615 }
drhd8bc7082000-06-07 23:51:50 +00001616
1617 /* Generate code to take the intersection of the two temporary
1618 ** tables.
1619 */
drh82c3d632000-06-06 21:56:07 +00001620 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001621 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001622 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001623 }
danielk19774adee202004-05-08 08:23:19 +00001624 iBreak = sqlite3VdbeMakeLabel(v);
1625 iCont = sqlite3VdbeMakeLabel(v);
1626 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001627 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001628 iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
1629 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001630 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001631 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001632 iCont, iBreak, 0);
1633 if( rc ){
1634 rc = 1;
1635 goto multi_select_end;
1636 }
danielk19774adee202004-05-08 08:23:19 +00001637 sqlite3VdbeResolveLabel(v, iCont);
1638 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1639 sqlite3VdbeResolveLabel(v, iBreak);
1640 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1641 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001642 break;
1643 }
1644 }
drh8cdbf832004-08-29 16:25:03 +00001645
1646 /* Make sure all SELECTs in the statement have the same number of elements
1647 ** in their result sets.
1648 */
drh82c3d632000-06-06 21:56:07 +00001649 assert( p->pEList && pPrior->pEList );
1650 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001651 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001652 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001653 rc = 1;
1654 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001655 }
danielk197784ac9d02004-05-18 09:58:06 +00001656
drh8cdbf832004-08-29 16:25:03 +00001657 /* Set the number of columns in temporary tables
1658 */
1659 nCol = p->pEList->nExpr;
1660 while( nAddr>0 ){
1661 nAddr--;
1662 sqlite3VdbeChangeP2(v, aAddr[nAddr], nCol);
1663 }
1664
drhfbc4ee72004-08-29 01:31:05 +00001665 /* Compute collating sequences used by either the ORDER BY clause or
1666 ** by any temporary tables needed to implement the compound select.
1667 ** Attach the KeyInfo structure to all temporary tables. Invoke the
1668 ** ORDER BY processing if there is an ORDER BY clause.
drh8cdbf832004-08-29 16:25:03 +00001669 **
1670 ** This section is run by the right-most SELECT statement only.
1671 ** SELECT statements to the left always skip this part. The right-most
1672 ** SELECT might also skip this part if it has no ORDER BY clause and
1673 ** no temp tables are required.
drhfbc4ee72004-08-29 01:31:05 +00001674 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001675 if( p->pOrderBy || (pOpenTemp && pOpenTemp->nId>0) ){
drhfbc4ee72004-08-29 01:31:05 +00001676 int i; /* Loop counter */
1677 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
1678
drh8cdbf832004-08-29 16:25:03 +00001679 assert( p->ppOpenTemp == &pOpenTemp );
drhfbc4ee72004-08-29 01:31:05 +00001680 pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*sizeof(CollSeq*));
danielk1977dc1bdc42004-06-11 10:51:27 +00001681 if( !pKeyInfo ){
1682 rc = SQLITE_NOMEM;
1683 goto multi_select_end;
1684 }
1685
1686 pKeyInfo->enc = pParse->db->enc;
1687 pKeyInfo->nField = nCol;
1688
1689 for(i=0; i<nCol; i++){
1690 pKeyInfo->aColl[i] = multiSelectCollSeq(pParse, p, i);
1691 if( !pKeyInfo->aColl[i] ){
1692 pKeyInfo->aColl[i] = pParse->db->pDfltColl;
1693 }
1694 }
1695
1696 for(i=0; pOpenTemp && i<pOpenTemp->nId; i++){
1697 int p3type = (i==0?P3_KEYINFO_HANDOFF:P3_KEYINFO);
1698 int addr = pOpenTemp->a[i].idx;
1699 sqlite3VdbeChangeP3(v, addr, (char *)pKeyInfo, p3type);
1700 }
1701
1702 if( p->pOrderBy ){
drhfbc4ee72004-08-29 01:31:05 +00001703 struct ExprList_item *pOrderByTerm = p->pOrderBy->a;
1704 for(i=0; i<p->pOrderBy->nExpr; i++, pOrderByTerm++){
1705 Expr *pExpr = pOrderByTerm->pExpr;
1706 char *zName = pOrderByTerm->zName;
danielk1977dc1bdc42004-06-11 10:51:27 +00001707 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
1708 assert( !pExpr->pColl );
1709 if( zName ){
1710 pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1);
1711 }else{
1712 pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn];
1713 }
1714 }
1715 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1716 }
1717
1718 if( !pOpenTemp ){
1719 /* This happens for UNION ALL ... ORDER BY */
1720 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001721 }
1722 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001723
1724multi_select_end:
1725 if( pOpenTemp ){
1726 sqlite3IdListDelete(pOpenTemp);
1727 }
1728 p->ppOpenTemp = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001729 return rc;
drh22827922000-06-06 17:27:05 +00001730}
drhb7f91642004-10-31 02:22:47 +00001731#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drh22827922000-06-06 17:27:05 +00001732
drhb7f91642004-10-31 02:22:47 +00001733#ifndef SQLITE_OMIT_VIEW
drh22827922000-06-06 17:27:05 +00001734/*
drh832508b2002-03-02 17:04:07 +00001735** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001736** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001737** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001738** unchanged.)
drh832508b2002-03-02 17:04:07 +00001739**
1740** This routine is part of the flattening procedure. A subquery
1741** whose result set is defined by pEList appears as entry in the
1742** FROM clause of a SELECT such that the VDBE cursor assigned to that
1743** FORM clause entry is iTable. This routine make the necessary
1744** changes to pExpr so that it refers directly to the source table
1745** of the subquery rather the result set of the subquery.
1746*/
drh6a3ea0e2003-05-02 14:32:12 +00001747static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1748static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001749 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001750 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1751 if( pExpr->iColumn<0 ){
1752 pExpr->op = TK_NULL;
1753 }else{
1754 Expr *pNew;
1755 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1756 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1757 pNew = pEList->a[pExpr->iColumn].pExpr;
1758 assert( pNew!=0 );
1759 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001760 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001761 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001762 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001763 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001764 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001765 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001766 pExpr->iTable = pNew->iTable;
1767 pExpr->iColumn = pNew->iColumn;
1768 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001769 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1770 sqlite3TokenCopy(&pExpr->span, &pNew->span);
drh50350a12004-02-13 16:22:22 +00001771 }
drh832508b2002-03-02 17:04:07 +00001772 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001773 substExpr(pExpr->pLeft, iTable, pEList);
1774 substExpr(pExpr->pRight, iTable, pEList);
1775 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001776 }
1777}
1778static void
drh6a3ea0e2003-05-02 14:32:12 +00001779substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001780 int i;
1781 if( pList==0 ) return;
1782 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001783 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001784 }
1785}
drhb7f91642004-10-31 02:22:47 +00001786#endif /* !defined(SQLITE_OMIT_VIEW) */
drh832508b2002-03-02 17:04:07 +00001787
drhb7f91642004-10-31 02:22:47 +00001788#ifndef SQLITE_OMIT_VIEW
drh832508b2002-03-02 17:04:07 +00001789/*
drh1350b032002-02-27 19:00:20 +00001790** This routine attempts to flatten subqueries in order to speed
1791** execution. It returns 1 if it makes changes and 0 if no flattening
1792** occurs.
1793**
1794** To understand the concept of flattening, consider the following
1795** query:
1796**
1797** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1798**
1799** The default way of implementing this query is to execute the
1800** subquery first and store the results in a temporary table, then
1801** run the outer query on that temporary table. This requires two
1802** passes over the data. Furthermore, because the temporary table
1803** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001804** optimized.
drh1350b032002-02-27 19:00:20 +00001805**
drh832508b2002-03-02 17:04:07 +00001806** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001807** a single flat select, like this:
1808**
1809** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1810**
1811** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001812** but only has to scan the data once. And because indices might
1813** exist on the table t1, a complete scan of the data might be
1814** avoided.
drh1350b032002-02-27 19:00:20 +00001815**
drh832508b2002-03-02 17:04:07 +00001816** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001817**
drh832508b2002-03-02 17:04:07 +00001818** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001819**
drh832508b2002-03-02 17:04:07 +00001820** (2) The subquery is not an aggregate or the outer query is not a join.
1821**
drh8af4d3a2003-05-06 20:35:16 +00001822** (3) The subquery is not the right operand of a left outer join, or
1823** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001824**
1825** (4) The subquery is not DISTINCT or the outer query is not a join.
1826**
1827** (5) The subquery is not DISTINCT or the outer query does not use
1828** aggregates.
1829**
1830** (6) The subquery does not use aggregates or the outer query is not
1831** DISTINCT.
1832**
drh08192d52002-04-30 19:20:28 +00001833** (7) The subquery has a FROM clause.
1834**
drhdf199a22002-06-14 22:38:41 +00001835** (8) The subquery does not use LIMIT or the outer query is not a join.
1836**
1837** (9) The subquery does not use LIMIT or the outer query does not use
1838** aggregates.
1839**
1840** (10) The subquery does not use aggregates or the outer query does not
1841** use LIMIT.
1842**
drh174b6192002-12-03 02:22:52 +00001843** (11) The subquery and the outer query do not both have ORDER BY clauses.
1844**
drh3fc673e2003-06-16 00:40:34 +00001845** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1846** subquery has no WHERE clause. (added by ticket #350)
1847**
drh832508b2002-03-02 17:04:07 +00001848** In this routine, the "p" parameter is a pointer to the outer query.
1849** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1850** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1851**
drh665de472003-03-31 13:36:09 +00001852** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001853** If flattening is attempted this routine returns 1.
1854**
1855** All of the expression analysis must occur on both the outer query and
1856** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001857*/
drh8c74a8c2002-08-25 19:20:40 +00001858static int flattenSubquery(
1859 Parse *pParse, /* The parsing context */
1860 Select *p, /* The parent or outer SELECT statement */
1861 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1862 int isAgg, /* True if outer SELECT uses aggregate functions */
1863 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1864){
drh0bb28102002-05-08 11:54:14 +00001865 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001866 SrcList *pSrc; /* The FROM clause of the outer query */
1867 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001868 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001869 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh91bb0ee2004-09-01 03:06:34 +00001870 int i; /* Loop counter */
1871 Expr *pWhere; /* The WHERE clause */
1872 struct SrcList_item *pSubitem; /* The subquery */
drh1350b032002-02-27 19:00:20 +00001873
drh832508b2002-03-02 17:04:07 +00001874 /* Check to see if flattening is permitted. Return 0 if not.
1875 */
1876 if( p==0 ) return 0;
1877 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001878 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh91bb0ee2004-09-01 03:06:34 +00001879 pSubitem = &pSrc->a[iFrom];
1880 pSub = pSubitem->pSelect;
drh832508b2002-03-02 17:04:07 +00001881 assert( pSub!=0 );
1882 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001883 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001884 pSubSrc = pSub->pSrc;
1885 assert( pSubSrc );
drhc31c2eb2003-05-02 16:04:17 +00001886 if( pSubSrc->nSrc==0 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001887 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1888 return 0;
1889 }
drhd11d3822002-06-21 23:01:49 +00001890 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001891 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001892
drh8af4d3a2003-05-06 20:35:16 +00001893 /* Restriction 3: If the subquery is a join, make sure the subquery is
1894 ** not used as the right operand of an outer join. Examples of why this
1895 ** is not allowed:
1896 **
1897 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1898 **
1899 ** If we flatten the above, we would get
1900 **
1901 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1902 **
1903 ** which is not at all the same thing.
1904 */
1905 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1906 return 0;
1907 }
1908
drh3fc673e2003-06-16 00:40:34 +00001909 /* Restriction 12: If the subquery is the right operand of a left outer
1910 ** join, make sure the subquery has no WHERE clause.
1911 ** An examples of why this is not allowed:
1912 **
1913 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1914 **
1915 ** If we flatten the above, we would get
1916 **
1917 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1918 **
1919 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1920 ** effectively converts the OUTER JOIN into an INNER JOIN.
1921 */
1922 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1923 && pSub->pWhere!=0 ){
1924 return 0;
1925 }
1926
drh0bb28102002-05-08 11:54:14 +00001927 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001928 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001929 */
drhc31c2eb2003-05-02 16:04:17 +00001930
1931 /* Move all of the FROM elements of the subquery into the
1932 ** the FROM clause of the outer query. Before doing this, remember
1933 ** the cursor number for the original outer query FROM element in
1934 ** iParent. The iParent cursor will never be used. Subsequent code
1935 ** will scan expressions looking for iParent references and replace
1936 ** those references with expressions that resolve to the subquery FROM
1937 ** elements we are now copying in.
1938 */
drh91bb0ee2004-09-01 03:06:34 +00001939 iParent = pSubitem->iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001940 {
1941 int nSubSrc = pSubSrc->nSrc;
drh91bb0ee2004-09-01 03:06:34 +00001942 int jointype = pSubitem->jointype;
1943 Table *pTab = pSubitem->pTab;
drhc31c2eb2003-05-02 16:04:17 +00001944
drh91bb0ee2004-09-01 03:06:34 +00001945 if( pTab && pTab->isTransient ){
1946 sqlite3DeleteTable(0, pSubitem->pTab);
drhc31c2eb2003-05-02 16:04:17 +00001947 }
drh91bb0ee2004-09-01 03:06:34 +00001948 sqliteFree(pSubitem->zDatabase);
1949 sqliteFree(pSubitem->zName);
1950 sqliteFree(pSubitem->zAlias);
drhc31c2eb2003-05-02 16:04:17 +00001951 if( nSubSrc>1 ){
1952 int extra = nSubSrc - 1;
1953 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00001954 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00001955 }
1956 p->pSrc = pSrc;
1957 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1958 pSrc->a[i] = pSrc->a[i-extra];
1959 }
1960 }
1961 for(i=0; i<nSubSrc; i++){
1962 pSrc->a[i+iFrom] = pSubSrc->a[i];
1963 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1964 }
drh8af4d3a2003-05-06 20:35:16 +00001965 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00001966 }
1967
1968 /* Now begin substituting subquery result set expressions for
1969 ** references to the iParent in the outer query.
1970 **
1971 ** Example:
1972 **
1973 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1974 ** \ \_____________ subquery __________/ /
1975 ** \_____________________ outer query ______________________________/
1976 **
1977 ** We look at every expression in the outer query and every place we see
1978 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1979 */
drh6a3ea0e2003-05-02 14:32:12 +00001980 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001981 pList = p->pEList;
1982 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001983 Expr *pExpr;
1984 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1985 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001986 }
1987 }
drh1b2e0322002-03-03 02:49:51 +00001988 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00001989 substExprList(p->pGroupBy, iParent, pSub->pEList);
1990 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001991 }
drh174b6192002-12-03 02:22:52 +00001992 if( pSub->pOrderBy ){
1993 assert( p->pOrderBy==0 );
1994 p->pOrderBy = pSub->pOrderBy;
1995 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00001996 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00001997 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00001998 }
drh832508b2002-03-02 17:04:07 +00001999 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002000 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00002001 }else{
2002 pWhere = 0;
2003 }
2004 if( subqueryIsAgg ){
2005 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00002006 p->pHaving = p->pWhere;
2007 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00002008 substExpr(p->pHaving, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002009 p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
drh1b2e0322002-03-03 02:49:51 +00002010 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00002011 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00002012 }else{
drh6a3ea0e2003-05-02 14:32:12 +00002013 substExpr(p->pWhere, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002014 p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
drh832508b2002-03-02 17:04:07 +00002015 }
drhc31c2eb2003-05-02 16:04:17 +00002016
2017 /* The flattened query is distinct if either the inner or the
2018 ** outer query is distinct.
2019 */
drh832508b2002-03-02 17:04:07 +00002020 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00002021
drhc31c2eb2003-05-02 16:04:17 +00002022 /* Transfer the limit expression from the subquery to the outer
2023 ** query.
2024 */
drhdf199a22002-06-14 22:38:41 +00002025 if( pSub->nLimit>=0 ){
2026 if( p->nLimit<0 ){
2027 p->nLimit = pSub->nLimit;
2028 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
2029 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
2030 }
2031 }
2032 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00002033
drhc31c2eb2003-05-02 16:04:17 +00002034 /* Finially, delete what is left of the subquery and return
2035 ** success.
2036 */
danielk19774adee202004-05-08 08:23:19 +00002037 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00002038 return 1;
2039}
drhb7f91642004-10-31 02:22:47 +00002040#endif /* SQLITE_OMIT_VIEW */
drh1350b032002-02-27 19:00:20 +00002041
2042/*
drh9562b552002-02-19 15:00:07 +00002043** Analyze the SELECT statement passed in as an argument to see if it
2044** is a simple min() or max() query. If it is and this query can be
2045** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00002046** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00002047** simple min() or max() query, then return 0;
2048**
2049** A simply min() or max() query looks like this:
2050**
2051** SELECT min(a) FROM table;
2052** SELECT max(a) FROM table;
2053**
2054** The query may have only a single table in its FROM argument. There
2055** can be no GROUP BY or HAVING or WHERE clauses. The result set must
2056** be the min() or max() of a single column of the table. The column
2057** in the min() or max() function must be indexed.
2058**
danielk19774adee202004-05-08 08:23:19 +00002059** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00002060** See the header comment on that routine for additional information.
2061*/
2062static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2063 Expr *pExpr;
2064 int iCol;
2065 Table *pTab;
2066 Index *pIdx;
2067 int base;
2068 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00002069 int seekOp;
2070 int cont;
drh6e175292004-03-13 14:00:36 +00002071 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00002072 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00002073 SrcList *pSrc;
drh9562b552002-02-19 15:00:07 +00002074
2075 /* Check to see if this query is a simple min() or max() query. Return
2076 ** zero if it is not.
2077 */
2078 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00002079 pSrc = p->pSrc;
2080 if( pSrc->nSrc!=1 ) return 0;
2081 pEList = p->pEList;
2082 if( pEList->nExpr!=1 ) return 0;
2083 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002084 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002085 pList = pExpr->pList;
2086 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002087 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00002088 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002089 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00002090 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002091 seekOp = OP_Last;
2092 }else{
2093 return 0;
2094 }
drh6e175292004-03-13 14:00:36 +00002095 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002096 if( pExpr->op!=TK_COLUMN ) return 0;
2097 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002098 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002099
2100 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002101 ** Check to make sure we have an index and make pIdx point to the
2102 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2103 ** key column, no index is necessary so set pIdx to NULL. If no
2104 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002105 */
2106 if( iCol<0 ){
2107 pIdx = 0;
2108 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002109 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002110 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2111 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002112 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002113 }
2114 if( pIdx==0 ) return 0;
2115 }
2116
drhe5f50722003-07-19 00:44:14 +00002117 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002118 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002119 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002120 */
danielk19774adee202004-05-08 08:23:19 +00002121 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002122 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002123
drh0c37e632004-01-30 02:01:03 +00002124 /* If the output is destined for a temporary table, open that table.
2125 */
2126 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002127 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002128 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002129 }
2130
drh17f71932002-02-21 12:01:27 +00002131 /* Generating code to find the min or the max. Basically all we have
2132 ** to do is find the first or the last entry in the chosen index. If
2133 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2134 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002135 */
danielk19774adee202004-05-08 08:23:19 +00002136 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00002137 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00002138 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00002139 if( pSrc->a[0].pSelect==0 ){
drhad6d9462004-09-19 02:15:24 +00002140 sqlite3OpenTableForReading(v, base, pTab);
drh6e175292004-03-13 14:00:36 +00002141 }
danielk19774adee202004-05-08 08:23:19 +00002142 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00002143 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002144 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002145 }else{
danielk19773719d7f2005-01-17 08:57:09 +00002146 /* Even though the cursor used to open the index here is closed
2147 ** as soon as a single value has been read from it, allocate it
2148 ** using (pParse->nTab++) to prevent the cursor id from being
2149 ** reused. This is important for statements of the form
2150 ** "INSERT INTO x SELECT max() FROM x".
2151 */
2152 int iIdx;
2153 iIdx = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +00002154 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002155 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
drhd3d39e92004-05-20 22:16:29 +00002156 (char*)&pIdx->keyInfo, P3_KEYINFO);
drh9eb516c2004-07-18 20:52:32 +00002157 if( seekOp==OP_Rewind ){
drh1af3fdb2004-07-18 21:33:01 +00002158 sqlite3VdbeAddOp(v, OP_String, 0, 0);
2159 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2160 seekOp = OP_MoveGt;
drh9eb516c2004-07-18 20:52:32 +00002161 }
danielk19773719d7f2005-01-17 08:57:09 +00002162 sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
2163 sqlite3VdbeAddOp(v, OP_IdxRecno, iIdx, 0);
2164 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002165 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002166 }
drh5cf8e8c2002-02-19 22:42:05 +00002167 eList.nExpr = 1;
2168 memset(&eListItem, 0, sizeof(eListItem));
2169 eList.a = &eListItem;
2170 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00002171 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00002172 sqlite3VdbeResolveLabel(v, cont);
2173 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002174
drh9562b552002-02-19 15:00:07 +00002175 return 1;
2176}
2177
2178/*
drh290c1942004-08-21 17:54:45 +00002179** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
2180** the number of errors seen.
2181**
2182** An ORDER BY or GROUP BY is a list of expressions. If any expression
2183** is an integer constant, then that expression is replaced by the
2184** corresponding entry in the result set.
2185*/
2186static int processOrderGroupBy(
2187 Parse *pParse, /* Parsing context */
2188 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
2189 SrcList *pTabList, /* The FROM clause */
2190 ExprList *pEList, /* The result set */
2191 int isAgg, /* True if aggregate functions are involved */
2192 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
2193){
2194 int i;
2195 if( pOrderBy==0 ) return 0;
2196 for(i=0; i<pOrderBy->nExpr; i++){
2197 int iCol;
2198 Expr *pE = pOrderBy->a[i].pExpr;
2199 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2200 sqlite3ExprDelete(pE);
2201 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2202 }
drh73b211a2005-01-18 04:00:42 +00002203 if( sqlite3ExprResolveNames(pParse, pTabList, pEList, pE, isAgg, 1) ){
drh290c1942004-08-21 17:54:45 +00002204 return 1;
2205 }
2206 if( sqlite3ExprIsConstant(pE) ){
2207 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2208 sqlite3ErrorMsg(pParse,
2209 "%s BY terms must not be non-integer constants", zType);
2210 return 1;
2211 }else if( iCol<=0 || iCol>pEList->nExpr ){
2212 sqlite3ErrorMsg(pParse,
2213 "%s BY column number %d out of range - should be "
2214 "between 1 and %d", zType, iCol, pEList->nExpr);
2215 return 1;
2216 }
2217 }
2218 }
2219 return 0;
2220}
2221
2222/*
drh9bb61fe2000-06-05 16:01:39 +00002223** Generate code for the given SELECT statement.
2224**
drhfef52082000-06-06 01:50:43 +00002225** The results are distributed in various ways depending on the
2226** value of eDest and iParm.
2227**
2228** eDest Value Result
2229** ------------ -------------------------------------------
2230** SRT_Callback Invoke the callback for each row of the result.
2231**
2232** SRT_Mem Store first result in memory cell iParm
2233**
danielk1977e014a832004-05-17 10:48:57 +00002234** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002235**
drh82c3d632000-06-06 21:56:07 +00002236** SRT_Union Store results as a key in a temporary table iParm
2237**
jplyon4b11c6d2004-01-19 04:57:53 +00002238** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002239**
2240** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002241**
drhe78e8282003-01-19 03:59:45 +00002242** The table above is incomplete. Additional eDist value have be added
2243** since this comment was written. See the selectInnerLoop() function for
2244** a complete listing of the allowed values of eDest and their meanings.
2245**
drh9bb61fe2000-06-05 16:01:39 +00002246** This routine returns the number of errors. If any errors are
2247** encountered, then an appropriate error message is left in
2248** pParse->zErrMsg.
2249**
2250** This routine does NOT free the Select structure passed in. The
2251** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002252**
2253** The pParent, parentTab, and *pParentAgg fields are filled in if this
2254** SELECT is a subquery. This routine may try to combine this SELECT
2255** with its parent to form a single flat query. In so doing, it might
2256** change the parent query from a non-aggregate to an aggregate query.
2257** For that reason, the pParentAgg flag is passed as a pointer, so it
2258** can be changed.
drhe78e8282003-01-19 03:59:45 +00002259**
2260** Example 1: The meaning of the pParent parameter.
2261**
2262** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2263** \ \_______ subquery _______/ /
2264** \ /
2265** \____________________ outer query ___________________/
2266**
2267** This routine is called for the outer query first. For that call,
2268** pParent will be NULL. During the processing of the outer query, this
2269** routine is called recursively to handle the subquery. For the recursive
2270** call, pParent will point to the outer query. Because the subquery is
2271** the second element in a three-way join, the parentTab parameter will
2272** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002273*/
danielk19774adee202004-05-08 08:23:19 +00002274int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002275 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002276 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002277 int eDest, /* How to dispose of the results */
2278 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002279 Select *pParent, /* Another SELECT for which this is a sub-query */
2280 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002281 int *pParentAgg, /* True if pParent uses aggregate functions */
2282 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002283){
drhd8bc7082000-06-07 23:51:50 +00002284 int i;
drhcce7d172000-05-31 15:34:51 +00002285 WhereInfo *pWInfo;
2286 Vdbe *v;
2287 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002288 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002289 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002290 Expr *pWhere; /* The WHERE clause. May be NULL */
2291 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002292 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2293 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002294 int isDistinct; /* True if the DISTINCT keyword is present */
2295 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002296 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00002297
danielk19776f8a5032004-05-10 10:34:51 +00002298 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002299 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002300
drhb7f91642004-10-31 02:22:47 +00002301#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +00002302 /* If there is are a sequence of queries, do the earlier ones first.
2303 */
2304 if( p->pPrior ){
drhb6c29892004-11-22 19:12:19 +00002305#ifndef SQLITE_OMIT_CURSOR
2306 if( p->pFetch ){
2307 sqlite3ErrorMsg(pParse, "cursors cannot be used on compound queries");
2308 goto select_end;
2309 }
2310#endif
danielk197784ac9d02004-05-18 09:58:06 +00002311 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002312 }
drhb7f91642004-10-31 02:22:47 +00002313#endif
drh82c3d632000-06-06 21:56:07 +00002314
2315 /* Make local copies of the parameters for this query.
2316 */
drh9bb61fe2000-06-05 16:01:39 +00002317 pTabList = p->pSrc;
2318 pWhere = p->pWhere;
2319 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00002320 pGroupBy = p->pGroupBy;
2321 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00002322 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00002323
2324 /*
2325 ** Do not even attempt to generate any code if we have already seen
2326 ** errors before this routine starts.
2327 */
drh1d83f052002-02-17 00:30:36 +00002328 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002329
drh9b3187e2005-01-18 14:45:47 +00002330 if( prepSelectStmt(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00002331 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002332 }
drhad2d8302002-05-24 20:31:36 +00002333 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00002334 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00002335 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002336
drh22827922000-06-06 17:27:05 +00002337 /* If writing to memory or generating a set
2338 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002339 */
drhfef52082000-06-06 01:50:43 +00002340 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002341 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002342 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002343 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002344 }
2345
drhc926afb2002-06-20 03:38:26 +00002346 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002347 */
drhc926afb2002-06-20 03:38:26 +00002348 switch( eDest ){
2349 case SRT_Union:
2350 case SRT_Except:
2351 case SRT_Discard:
2352 pOrderBy = 0;
2353 break;
2354 default:
2355 break;
drh22827922000-06-06 17:27:05 +00002356 }
2357
drh10e5e3c2000-06-08 00:19:02 +00002358 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002359 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002360 **
drh967e8b72000-06-21 13:59:10 +00002361 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002362 */
drh4794b982000-06-06 13:54:14 +00002363 for(i=0; i<pEList->nExpr; i++){
drh73b211a2005-01-18 04:00:42 +00002364 Expr *pX = pEList->a[i].pExpr;
2365 if( sqlite3ExprResolveNames(pParse, pTabList, 0, pX, 1, 1) ){
drh1d83f052002-02-17 00:30:36 +00002366 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002367 }
drh73b211a2005-01-18 04:00:42 +00002368 if( ExprHasProperty(pX, EP_Agg) ) isAgg = 1;
drhcce7d172000-05-31 15:34:51 +00002369 }
drh73b211a2005-01-18 04:00:42 +00002370 if( sqlite3ExprResolveNames(pParse, pTabList, pEList, pWhere, 0, 1) ){
drh290c1942004-08-21 17:54:45 +00002371 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002372 }
drhc66c5a22002-12-03 02:34:49 +00002373 if( pHaving ){
2374 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002375 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
drhc66c5a22002-12-03 02:34:49 +00002376 goto select_end;
2377 }
drh73b211a2005-01-18 04:00:42 +00002378 if( sqlite3ExprResolveNames(pParse, pTabList, pEList, pHaving, 1, 1) ){
drhc66c5a22002-12-03 02:34:49 +00002379 goto select_end;
2380 }
drh73b211a2005-01-18 04:00:42 +00002381 if( ExprHasProperty(pHaving, EP_Agg) ) isAgg = 1;
drhc66c5a22002-12-03 02:34:49 +00002382 }
drh49d642d2005-01-03 02:26:54 +00002383 if( pGroupBy && !isAgg ){
2384 sqlite3ErrorMsg(pParse, "GROUP BY may only be used on aggregate queries");
2385 goto select_end;
2386 }
drh290c1942004-08-21 17:54:45 +00002387 if( processOrderGroupBy(pParse, pOrderBy, pTabList, pEList, isAgg, "ORDER")
2388 || processOrderGroupBy(pParse, pGroupBy, pTabList, pEList, isAgg, "GROUP")
2389 ){
2390 goto select_end;
drh22827922000-06-06 17:27:05 +00002391 }
drhcce7d172000-05-31 15:34:51 +00002392
drhb6c29892004-11-22 19:12:19 +00002393 /* We cannot use a SQL cursor on a join or on a DISTINCT query
2394 */
2395#ifndef SQLITE_OMIT_CURSOR
2396 if( p->pFetch ){
2397 if( p->isDistinct ){
2398 sqlite3ErrorMsg(pParse, "cursors cannot be used on DISTINCT queries");
2399 goto select_end;
2400 }
2401 if( pTabList->nSrc>0 ){
2402 sqlite3ErrorMsg(pParse, "cursors cannot be used on joins");
2403 goto select_end;
2404 }
2405 if( pTabList->a[0].pSelect ){
2406 sqlite3ErrorMsg(pParse, "cursor cannot be used with nested queries "
2407 "or views");
2408 goto select_end;
2409 }
2410 }
2411#endif
2412
drhd820cb12002-02-18 03:21:45 +00002413 /* Begin generating code.
2414 */
danielk19774adee202004-05-08 08:23:19 +00002415 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002416 if( v==0 ) goto select_end;
2417
drhe78e8282003-01-19 03:59:45 +00002418 /* Identify column names if we will be using them in a callback. This
2419 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002420 */
2421 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002422 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002423 }
2424
drhd820cb12002-02-18 03:21:45 +00002425 /* Generate code for all sub-queries in the FROM clause
2426 */
drhad3cab52002-05-24 02:04:32 +00002427 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002428 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002429 int needRestoreContext;
2430
drha76b5df2002-02-23 02:32:10 +00002431 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002432 if( pTabList->a[i].zName!=0 ){
2433 zSavedAuthContext = pParse->zAuthContext;
2434 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002435 needRestoreContext = 1;
2436 }else{
2437 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002438 }
danielk19774adee202004-05-08 08:23:19 +00002439 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
danielk197784ac9d02004-05-18 09:58:06 +00002440 pTabList->a[i].iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002441 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002442 pParse->zAuthContext = zSavedAuthContext;
2443 }
drh1b2e0322002-03-03 02:49:51 +00002444 pTabList = p->pSrc;
2445 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002446 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002447 pOrderBy = p->pOrderBy;
2448 }
drh1b2e0322002-03-03 02:49:51 +00002449 pGroupBy = p->pGroupBy;
2450 pHaving = p->pHaving;
2451 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002452 }
2453
drh6e175292004-03-13 14:00:36 +00002454 /* Check for the special case of a min() or max() function by itself
2455 ** in the result set.
2456 */
2457 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2458 rc = 0;
2459 goto select_end;
2460 }
2461
drh832508b2002-03-02 17:04:07 +00002462 /* Check to see if this is a subquery that can be "flattened" into its parent.
2463 ** If flattening is a possiblity, do so and return immediately.
2464 */
drhb7f91642004-10-31 02:22:47 +00002465#ifndef SQLITE_OMIT_VIEW
drh1b2e0322002-03-03 02:49:51 +00002466 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002467 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002468 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002469 return rc;
2470 }
drhb7f91642004-10-31 02:22:47 +00002471#endif
drh832508b2002-03-02 17:04:07 +00002472
danielk19777cedc8d2004-06-10 10:50:08 +00002473 /* If there is an ORDER BY clause, resolve any collation sequences
2474 ** names that have been explicitly specified.
2475 */
2476 if( pOrderBy ){
2477 for(i=0; i<pOrderBy->nExpr; i++){
2478 if( pOrderBy->a[i].zName ){
2479 pOrderBy->a[i].pExpr->pColl =
2480 sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1);
2481 }
2482 }
2483 if( pParse->nErr ){
2484 goto select_end;
2485 }
2486 }
2487
drh7b58dae2003-07-20 01:16:46 +00002488 /* Set the limiter.
2489 */
2490 computeLimitRegisters(pParse, p);
2491
drh2d0794e2002-03-03 03:03:52 +00002492 /* If the output is destined for a temporary table, open that table.
2493 */
2494 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002495 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002496 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002497 }
2498
drh22827922000-06-06 17:27:05 +00002499 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002500 */
drhd820cb12002-02-18 03:21:45 +00002501 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002502 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002503 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002504 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002505 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002506 if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002507 goto select_end;
drh22827922000-06-06 17:27:05 +00002508 }
2509 }
2510 if( pGroupBy ){
2511 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002512 if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002513 goto select_end;
drh22827922000-06-06 17:27:05 +00002514 }
2515 }
2516 }
danielk19774adee202004-05-08 08:23:19 +00002517 if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002518 goto select_end;
drh22827922000-06-06 17:27:05 +00002519 }
drh191b6902000-06-08 11:13:01 +00002520 if( pOrderBy ){
2521 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002522 if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002523 goto select_end;
drh191b6902000-06-08 11:13:01 +00002524 }
2525 }
2526 }
drhefb72512000-05-31 20:00:52 +00002527 }
2528
drh22827922000-06-06 17:27:05 +00002529 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002530 */
2531 if( isAgg ){
danielk1977e159fdf2004-06-21 10:45:06 +00002532 int addr = sqlite3VdbeAddOp(v, OP_AggReset, (pGroupBy?0:1), pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002533 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002534 FuncDef *pFunc;
2535 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drhf9b596e2004-05-26 16:54:42 +00002536 sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_FUNCDEF);
drhe5095352002-02-24 03:25:14 +00002537 }
2538 }
danielk1977e159fdf2004-06-21 10:45:06 +00002539 if( pGroupBy ){
danielk1977ce2663c2004-06-11 13:19:21 +00002540 int sz = sizeof(KeyInfo) + pGroupBy->nExpr*sizeof(CollSeq*);
2541 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(sz);
2542 if( 0==pKey ){
2543 goto select_end;
2544 }
2545 pKey->enc = pParse->db->enc;
2546 pKey->nField = pGroupBy->nExpr;
2547 for(i=0; i<pGroupBy->nExpr; i++){
2548 pKey->aColl[i] = sqlite3ExprCollSeq(pParse, pGroupBy->a[i].pExpr);
2549 if( !pKey->aColl[i] ){
2550 pKey->aColl[i] = pParse->db->pDfltColl;
2551 }
2552 }
2553 sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF);
drh1bee3d72001-10-15 00:44:35 +00002554 }
drhcce7d172000-05-31 15:34:51 +00002555 }
2556
drh19a775c2000-06-05 18:54:46 +00002557 /* Initialize the memory cell to NULL
2558 */
drhfef52082000-06-06 01:50:43 +00002559 if( eDest==SRT_Mem ){
danielk19770f69c1e2004-05-29 11:24:50 +00002560 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00002561 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002562 }
2563
drh832508b2002-03-02 17:04:07 +00002564 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002565 */
drh19a775c2000-06-05 18:54:46 +00002566 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002567 distinct = pParse->nTab++;
drhd3d39e92004-05-20 22:16:29 +00002568 openTempIndex(pParse, p, distinct, 0);
drh832508b2002-03-02 17:04:07 +00002569 }else{
2570 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002571 }
drh832508b2002-03-02 17:04:07 +00002572
2573 /* Begin the database scan
2574 */
drhe6f85e72004-12-25 01:03:13 +00002575 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,
drhe4e72072004-11-23 01:47:30 +00002576 pGroupBy ? 0 : &pOrderBy, p->pFetch);
drh1d83f052002-02-17 00:30:36 +00002577 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002578
drh22827922000-06-06 17:27:05 +00002579 /* Use the standard inner loop if we are not dealing with
2580 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002581 */
drhda9d6c42000-05-31 18:20:14 +00002582 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002583 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002584 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002585 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002586 }
drhcce7d172000-05-31 15:34:51 +00002587 }
drhefb72512000-05-31 20:00:52 +00002588
drhe3184742002-06-19 14:27:05 +00002589 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002590 ** processing.
drhefb72512000-05-31 20:00:52 +00002591 */
drh22827922000-06-06 17:27:05 +00002592 else{
drh268380c2004-02-25 13:47:31 +00002593 AggExpr *pAgg;
drh22827922000-06-06 17:27:05 +00002594 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002595 int lbl1;
drh22827922000-06-06 17:27:05 +00002596 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002597 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
drh22827922000-06-06 17:27:05 +00002598 }
danielk1977ededfd52004-06-17 07:53:01 +00002599 /* No affinity string is attached to the following OP_MakeRecord
drhd3d39e92004-05-20 22:16:29 +00002600 ** because we do not need to do any coercion of datatypes. */
danielk1977ededfd52004-06-17 07:53:01 +00002601 sqlite3VdbeAddOp(v, OP_MakeRecord, pGroupBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +00002602 lbl1 = sqlite3VdbeMakeLabel(v);
2603 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh268380c2004-02-25 13:47:31 +00002604 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2605 if( pAgg->isAgg ) continue;
danielk19774adee202004-05-08 08:23:19 +00002606 sqlite3ExprCode(pParse, pAgg->pExpr);
2607 sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002608 }
danielk19774adee202004-05-08 08:23:19 +00002609 sqlite3VdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002610 }
drh268380c2004-02-25 13:47:31 +00002611 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002612 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002613 int nExpr;
2614 FuncDef *pDef;
2615 if( !pAgg->isAgg ) continue;
2616 assert( pAgg->pFunc!=0 );
2617 assert( pAgg->pFunc->xStep!=0 );
2618 pDef = pAgg->pFunc;
2619 pE = pAgg->pExpr;
2620 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002621 assert( pE->op==TK_AGG_FUNCTION );
drhf9b596e2004-05-26 16:54:42 +00002622 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
danielk19774adee202004-05-08 08:23:19 +00002623 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
danielk1977dc1bdc42004-06-11 10:51:27 +00002624 if( pDef->needCollSeq ){
2625 CollSeq *pColl = 0;
2626 int j;
2627 for(j=0; !pColl && j<nExpr; j++){
2628 pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr);
2629 }
2630 if( !pColl ) pColl = pParse->db->pDfltColl;
2631 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2632 }
danielk19774adee202004-05-08 08:23:19 +00002633 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002634 }
drhcce7d172000-05-31 15:34:51 +00002635 }
2636
2637 /* End the database scan loop.
2638 */
danielk19774adee202004-05-08 08:23:19 +00002639 sqlite3WhereEnd(pWInfo);
drhcce7d172000-05-31 15:34:51 +00002640
drh22827922000-06-06 17:27:05 +00002641 /* If we are processing aggregates, we need to set up a second loop
2642 ** over all of the aggregate values and process them.
2643 */
2644 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002645 int endagg = sqlite3VdbeMakeLabel(v);
drh22827922000-06-06 17:27:05 +00002646 int startagg;
danielk19774adee202004-05-08 08:23:19 +00002647 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002648 pParse->useAgg = 1;
2649 if( pHaving ){
danielk19774adee202004-05-08 08:23:19 +00002650 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002651 }
drhdf199a22002-06-14 22:38:41 +00002652 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002653 iParm, startagg, endagg, aff) ){
drh1d83f052002-02-17 00:30:36 +00002654 goto select_end;
drh22827922000-06-06 17:27:05 +00002655 }
danielk19774adee202004-05-08 08:23:19 +00002656 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2657 sqlite3VdbeResolveLabel(v, endagg);
2658 sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002659 pParse->useAgg = 0;
2660 }
2661
drhcce7d172000-05-31 15:34:51 +00002662 /* If there is an ORDER BY clause, then we need to sort the results
2663 ** and send them to the callback one by one.
2664 */
2665 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00002666 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002667 }
drh6a535342001-10-19 16:44:56 +00002668
drhf620b4e2004-02-09 14:37:50 +00002669 /* If this was a subquery, we have now converted the subquery into a
2670 ** temporary table. So delete the subquery structure from the parent
2671 ** to prevent this subquery from being evaluated again and to force the
2672 ** the use of the temporary table.
2673 */
2674 if( pParent ){
2675 assert( pParent->pSrc->nSrc>parentTab );
2676 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00002677 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00002678 pParent->pSrc->a[parentTab].pSelect = 0;
2679 }
2680
drh1d83f052002-02-17 00:30:36 +00002681 /* The SELECT was successfully coded. Set the return code to 0
2682 ** to indicate no errors.
2683 */
2684 rc = 0;
2685
2686 /* Control jumps to here if an error is encountered above, or upon
2687 ** successful coding of the SELECT.
2688 */
2689select_end:
2690 sqliteAggregateInfoReset(pParse);
2691 return rc;
drhcce7d172000-05-31 15:34:51 +00002692}