blob: 3da05e1087a4e6661a4a5f0535849e3fe8f23236 [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**
drh0342b1f2005-09-01 03:07:44 +000015** $Id: select.c,v 1.258 2005/09/01 03:07:44 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 */
danielk1977a2dc3b12005-02-05 12:48:48 +000032 Expr *pLimit, /* LIMIT value. NULL means not used */
33 Expr *pOffset /* OFFSET value. NULL means no offset */
drh9bb61fe2000-06-05 16:01:39 +000034){
35 Select *pNew;
36 pNew = sqliteMalloc( sizeof(*pNew) );
danielk1977a2dc3b12005-02-05 12:48:48 +000037 assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */
drhdaffd0e2001-04-11 14:28:42 +000038 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +000039 sqlite3ExprListDelete(pEList);
40 sqlite3SrcListDelete(pSrc);
41 sqlite3ExprDelete(pWhere);
42 sqlite3ExprListDelete(pGroupBy);
43 sqlite3ExprDelete(pHaving);
44 sqlite3ExprListDelete(pOrderBy);
danielk1977a2dc3b12005-02-05 12:48:48 +000045 sqlite3ExprDelete(pLimit);
46 sqlite3ExprDelete(pOffset);
drhdaffd0e2001-04-11 14:28:42 +000047 }else{
drhb733d032004-01-24 20:18:12 +000048 if( pEList==0 ){
danielk19774adee202004-05-08 08:23:19 +000049 pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
drhb733d032004-01-24 20:18:12 +000050 }
drhdaffd0e2001-04-11 14:28:42 +000051 pNew->pEList = pEList;
52 pNew->pSrc = pSrc;
53 pNew->pWhere = pWhere;
54 pNew->pGroupBy = pGroupBy;
55 pNew->pHaving = pHaving;
56 pNew->pOrderBy = pOrderBy;
57 pNew->isDistinct = isDistinct;
58 pNew->op = TK_SELECT;
danielk1977a2dc3b12005-02-05 12:48:48 +000059 pNew->pLimit = pLimit;
60 pNew->pOffset = pOffset;
drh7b58dae2003-07-20 01:16:46 +000061 pNew->iLimit = -1;
62 pNew->iOffset = -1;
drh0342b1f2005-09-01 03:07:44 +000063 pNew->addrOpenVirt[0] = -1;
64 pNew->addrOpenVirt[1] = -1;
65 pNew->addrOpenVirt[2] = -1;
drhdaffd0e2001-04-11 14:28:42 +000066 }
drh9bb61fe2000-06-05 16:01:39 +000067 return pNew;
68}
69
70/*
drh01f3f252002-05-24 16:14:15 +000071** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
72** type of join. Return an integer constant that expresses that type
73** in terms of the following bit values:
74**
75** JT_INNER
76** JT_OUTER
77** JT_NATURAL
78** JT_LEFT
79** JT_RIGHT
80**
81** A full outer join is the combination of JT_LEFT and JT_RIGHT.
82**
83** If an illegal or unsupported join type is seen, then still return
84** a join type, but put an error in the pParse structure.
85*/
danielk19774adee202004-05-08 08:23:19 +000086int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
drh01f3f252002-05-24 16:14:15 +000087 int jointype = 0;
88 Token *apAll[3];
89 Token *p;
drh57196282004-10-06 15:41:16 +000090 static const struct {
drhc182d162005-08-14 20:47:16 +000091 const char zKeyword[8];
drh290c1942004-08-21 17:54:45 +000092 u8 nChar;
93 u8 code;
drh01f3f252002-05-24 16:14:15 +000094 } keywords[] = {
95 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000096 { "left", 4, JT_LEFT|JT_OUTER },
97 { "right", 5, JT_RIGHT|JT_OUTER },
98 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +000099 { "outer", 5, JT_OUTER },
100 { "inner", 5, JT_INNER },
101 { "cross", 5, JT_INNER },
102 };
103 int i, j;
104 apAll[0] = pA;
105 apAll[1] = pB;
106 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +0000107 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +0000108 p = apAll[i];
109 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
110 if( p->n==keywords[j].nChar
danielk19774adee202004-05-08 08:23:19 +0000111 && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
drh01f3f252002-05-24 16:14:15 +0000112 jointype |= keywords[j].code;
113 break;
114 }
115 }
116 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
117 jointype |= JT_ERROR;
118 break;
119 }
120 }
drhad2d8302002-05-24 20:31:36 +0000121 if(
122 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000123 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000124 ){
drhae29ffb2004-09-25 14:39:18 +0000125 const char *zSp1 = " ";
126 const char *zSp2 = " ";
127 if( pB==0 ){ zSp1++; }
128 if( pC==0 ){ zSp2++; }
129 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
130 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
drh01f3f252002-05-24 16:14:15 +0000131 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000132 }else if( jointype & JT_RIGHT ){
danielk19774adee202004-05-08 08:23:19 +0000133 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000134 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000135 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000136 }
137 return jointype;
138}
139
140/*
drhad2d8302002-05-24 20:31:36 +0000141** Return the index of a column in a table. Return -1 if the column
142** is not contained in the table.
143*/
144static int columnIndex(Table *pTab, const char *zCol){
145 int i;
146 for(i=0; i<pTab->nCol; i++){
danielk19774adee202004-05-08 08:23:19 +0000147 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
drhad2d8302002-05-24 20:31:36 +0000148 }
149 return -1;
150}
151
152/*
drh91bb0ee2004-09-01 03:06:34 +0000153** Set the value of a token to a '\000'-terminated string.
154*/
155static void setToken(Token *p, const char *z){
156 p->z = z;
157 p->n = strlen(z);
158 p->dyn = 0;
159}
160
drhc182d162005-08-14 20:47:16 +0000161/*
162** Create an expression node for an identifier with the name of zName
163*/
164static Expr *createIdExpr(const char *zName){
165 Token dummy;
166 setToken(&dummy, zName);
167 return sqlite3Expr(TK_ID, 0, 0, &dummy);
168}
169
drh91bb0ee2004-09-01 03:06:34 +0000170
171/*
drhad2d8302002-05-24 20:31:36 +0000172** Add a term to the WHERE expression in *ppExpr that requires the
173** zCol column to be equal in the two tables pTab1 and pTab2.
174*/
175static void addWhereTerm(
176 const char *zCol, /* Name of the column */
177 const Table *pTab1, /* First table */
drh030530d2005-01-18 17:40:04 +0000178 const char *zAlias1, /* Alias for first table. May be NULL */
drhad2d8302002-05-24 20:31:36 +0000179 const Table *pTab2, /* Second table */
drh030530d2005-01-18 17:40:04 +0000180 const char *zAlias2, /* Alias for second table. May be NULL */
drhad2d8302002-05-24 20:31:36 +0000181 Expr **ppExpr /* Add the equality term to this expression */
182){
drhad2d8302002-05-24 20:31:36 +0000183 Expr *pE1a, *pE1b, *pE1c;
184 Expr *pE2a, *pE2b, *pE2c;
185 Expr *pE;
186
drhc182d162005-08-14 20:47:16 +0000187 pE1a = createIdExpr(zCol);
188 pE2a = createIdExpr(zCol);
drh030530d2005-01-18 17:40:04 +0000189 if( zAlias1==0 ){
190 zAlias1 = pTab1->zName;
191 }
drhc182d162005-08-14 20:47:16 +0000192 pE1b = createIdExpr(zAlias1);
drh030530d2005-01-18 17:40:04 +0000193 if( zAlias2==0 ){
194 zAlias2 = pTab2->zName;
195 }
drhc182d162005-08-14 20:47:16 +0000196 pE2b = createIdExpr(zAlias2);
danielk19774adee202004-05-08 08:23:19 +0000197 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
198 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
199 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000200 ExprSetProperty(pE, EP_FromJoin);
drh91bb0ee2004-09-01 03:06:34 +0000201 *ppExpr = sqlite3ExprAnd(*ppExpr, pE);
drhad2d8302002-05-24 20:31:36 +0000202}
203
204/*
drh1f162302002-10-27 19:35:33 +0000205** Set the EP_FromJoin property on all terms of the given expression.
drh1cc093c2002-06-24 22:01:57 +0000206**
drhe78e8282003-01-19 03:59:45 +0000207** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000208** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000209** join restriction specified in the ON or USING clause and not a part
210** of the more general WHERE clause. These terms are moved over to the
211** WHERE clause during join processing but we need to remember that they
212** originated in the ON or USING clause.
drh1cc093c2002-06-24 22:01:57 +0000213*/
214static void setJoinExpr(Expr *p){
215 while( p ){
drh1f162302002-10-27 19:35:33 +0000216 ExprSetProperty(p, EP_FromJoin);
drh1cc093c2002-06-24 22:01:57 +0000217 setJoinExpr(p->pLeft);
218 p = p->pRight;
219 }
220}
221
222/*
drhad2d8302002-05-24 20:31:36 +0000223** This routine processes the join information for a SELECT statement.
224** ON and USING clauses are converted into extra terms of the WHERE clause.
225** NATURAL joins also create extra WHERE clause terms.
226**
drh91bb0ee2004-09-01 03:06:34 +0000227** The terms of a FROM clause are contained in the Select.pSrc structure.
228** The left most table is the first entry in Select.pSrc. The right-most
229** table is the last entry. The join operator is held in the entry to
230** the left. Thus entry 0 contains the join operator for the join between
231** entries 0 and 1. Any ON or USING clauses associated with the join are
232** also attached to the left entry.
233**
drhad2d8302002-05-24 20:31:36 +0000234** This routine returns the number of errors encountered.
235*/
236static int sqliteProcessJoin(Parse *pParse, Select *p){
drh91bb0ee2004-09-01 03:06:34 +0000237 SrcList *pSrc; /* All tables in the FROM clause */
238 int i, j; /* Loop counters */
239 struct SrcList_item *pLeft; /* Left table being joined */
240 struct SrcList_item *pRight; /* Right table being joined */
drhad2d8302002-05-24 20:31:36 +0000241
drh91bb0ee2004-09-01 03:06:34 +0000242 pSrc = p->pSrc;
243 pLeft = &pSrc->a[0];
244 pRight = &pLeft[1];
245 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
246 Table *pLeftTab = pLeft->pTab;
247 Table *pRightTab = pRight->pTab;
248
249 if( pLeftTab==0 || pRightTab==0 ) continue;
drhad2d8302002-05-24 20:31:36 +0000250
251 /* When the NATURAL keyword is present, add WHERE clause terms for
252 ** every column that the two tables have in common.
253 */
drh91bb0ee2004-09-01 03:06:34 +0000254 if( pLeft->jointype & JT_NATURAL ){
255 if( pLeft->pOn || pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000256 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000257 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000258 return 1;
259 }
drh91bb0ee2004-09-01 03:06:34 +0000260 for(j=0; j<pLeftTab->nCol; j++){
261 char *zName = pLeftTab->aCol[j].zName;
262 if( columnIndex(pRightTab, zName)>=0 ){
drh030530d2005-01-18 17:40:04 +0000263 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
264 pRightTab, pRight->zAlias, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000265 }
266 }
267 }
268
269 /* Disallow both ON and USING clauses in the same join
270 */
drh91bb0ee2004-09-01 03:06:34 +0000271 if( pLeft->pOn && pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000272 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
drhda93d232003-03-31 02:12:46 +0000273 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000274 return 1;
275 }
276
277 /* Add the ON clause to the end of the WHERE clause, connected by
drh91bb0ee2004-09-01 03:06:34 +0000278 ** an AND operator.
drhad2d8302002-05-24 20:31:36 +0000279 */
drh91bb0ee2004-09-01 03:06:34 +0000280 if( pLeft->pOn ){
281 setJoinExpr(pLeft->pOn);
282 p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn);
283 pLeft->pOn = 0;
drhad2d8302002-05-24 20:31:36 +0000284 }
285
286 /* Create extra terms on the WHERE clause for each column named
287 ** in the USING clause. Example: If the two tables to be joined are
288 ** A and B and the USING clause names X, Y, and Z, then add this
289 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
290 ** Report an error if any column mentioned in the USING clause is
291 ** not contained in both tables to be joined.
292 */
drh91bb0ee2004-09-01 03:06:34 +0000293 if( pLeft->pUsing ){
294 IdList *pList = pLeft->pUsing;
drhad2d8302002-05-24 20:31:36 +0000295 for(j=0; j<pList->nId; j++){
drh91bb0ee2004-09-01 03:06:34 +0000296 char *zName = pList->a[j].zName;
297 if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
danielk19774adee202004-05-08 08:23:19 +0000298 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
drh91bb0ee2004-09-01 03:06:34 +0000299 "not present in both tables", zName);
drhad2d8302002-05-24 20:31:36 +0000300 return 1;
301 }
drh030530d2005-01-18 17:40:04 +0000302 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
303 pRightTab, pRight->zAlias, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000304 }
305 }
306 }
307 return 0;
308}
309
310/*
drh9bb61fe2000-06-05 16:01:39 +0000311** Delete the given Select structure and all of its substructures.
312*/
danielk19774adee202004-05-08 08:23:19 +0000313void sqlite3SelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000314 if( p==0 ) return;
danielk19774adee202004-05-08 08:23:19 +0000315 sqlite3ExprListDelete(p->pEList);
316 sqlite3SrcListDelete(p->pSrc);
317 sqlite3ExprDelete(p->pWhere);
318 sqlite3ExprListDelete(p->pGroupBy);
319 sqlite3ExprDelete(p->pHaving);
320 sqlite3ExprListDelete(p->pOrderBy);
321 sqlite3SelectDelete(p->pPrior);
danielk1977a2dc3b12005-02-05 12:48:48 +0000322 sqlite3ExprDelete(p->pLimit);
323 sqlite3ExprDelete(p->pOffset);
drh9bb61fe2000-06-05 16:01:39 +0000324 sqliteFree(p);
325}
326
327/*
drhc926afb2002-06-20 03:38:26 +0000328** Insert code into "v" that will push the record on the top of the
329** stack into the sorter.
330*/
331static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
drhc182d162005-08-14 20:47:16 +0000332 sqlite3ExprCodeExprList(pParse, pOrderBy);
drh0342b1f2005-09-01 03:07:44 +0000333 sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr, 0);
334 sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 1, 0);
335 sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iTab, 0);
drhc926afb2002-06-20 03:38:26 +0000336}
337
338/*
drhea48eb22004-07-19 23:16:38 +0000339** Add code to implement the OFFSET and LIMIT
340*/
341static void codeLimiter(
drhbab39e12004-07-19 23:38:11 +0000342 Vdbe *v, /* Generate code into this VM */
drhea48eb22004-07-19 23:16:38 +0000343 Select *p, /* The SELECT statement being coded */
344 int iContinue, /* Jump here to skip the current record */
345 int iBreak, /* Jump here to end the loop */
346 int nPop /* Number of times to pop stack when jumping */
347){
drhea48eb22004-07-19 23:16:38 +0000348 if( p->iOffset>=0 ){
danielk1977a2dc3b12005-02-05 12:48:48 +0000349 int addr = sqlite3VdbeCurrentAddr(v) + 3;
drhea48eb22004-07-19 23:16:38 +0000350 if( nPop>0 ) addr++;
danielk1977a2dc3b12005-02-05 12:48:48 +0000351 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, 0);
352 sqlite3VdbeAddOp(v, OP_IfMemPos, p->iOffset, addr);
drhea48eb22004-07-19 23:16:38 +0000353 if( nPop>0 ){
354 sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
355 }
356 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000357 VdbeComment((v, "# skip OFFSET records"));
drhea48eb22004-07-19 23:16:38 +0000358 }
359 if( p->iLimit>=0 ){
360 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhad6d9462004-09-19 02:15:24 +0000361 VdbeComment((v, "# exit when LIMIT reached"));
drhea48eb22004-07-19 23:16:38 +0000362 }
363}
364
365/*
drh22827922000-06-06 17:27:05 +0000366** This routine generates the code for the inside of the inner loop
367** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000368**
drh38640e12002-07-05 21:42:36 +0000369** If srcTab and nColumn are both zero, then the pEList expressions
370** are evaluated in order to get the data for this row. If nColumn>0
371** then data is pulled from srcTab and pEList is used only to get the
372** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000373*/
374static int selectInnerLoop(
375 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000376 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000377 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000378 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000379 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000380 ExprList *pOrderBy, /* If not NULL, sort results using this key */
381 int distinct, /* If >=0, make sure results are distinct */
382 int eDest, /* How to dispose of the results */
383 int iParm, /* An argument to the disposal method */
384 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000385 int iBreak, /* Jump here to break out of the inner loop */
386 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000387){
388 Vdbe *v = pParse->pVdbe;
389 int i;
drhea48eb22004-07-19 23:16:38 +0000390 int hasDistinct; /* True if the DISTINCT keyword is present */
drh38640e12002-07-05 21:42:36 +0000391
drhdaffd0e2001-04-11 14:28:42 +0000392 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000393 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000394
drhdf199a22002-06-14 22:38:41 +0000395 /* If there was a LIMIT clause on the SELECT statement, then do the check
396 ** to see if this row should be output.
397 */
drhea48eb22004-07-19 23:16:38 +0000398 hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
399 if( pOrderBy==0 && !hasDistinct ){
drhbab39e12004-07-19 23:38:11 +0000400 codeLimiter(v, p, iContinue, iBreak, 0);
drhdf199a22002-06-14 22:38:41 +0000401 }
402
drh967e8b72000-06-21 13:59:10 +0000403 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000404 */
drh38640e12002-07-05 21:42:36 +0000405 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000406 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000407 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000408 }
drh38640e12002-07-05 21:42:36 +0000409 }else{
410 nColumn = pEList->nExpr;
drhc182d162005-08-14 20:47:16 +0000411 sqlite3ExprCodeExprList(pParse, pEList);
drh22827922000-06-06 17:27:05 +0000412 }
413
drhdaffd0e2001-04-11 14:28:42 +0000414 /* If the DISTINCT keyword was present on the SELECT statement
415 ** and this row has been seen before, then do not make this row
416 ** part of the result.
drh22827922000-06-06 17:27:05 +0000417 */
drhea48eb22004-07-19 23:16:38 +0000418 if( hasDistinct ){
drhc182d162005-08-14 20:47:16 +0000419 int n = pEList->nExpr;
drh0bd1f4e2002-06-06 18:54:39 +0000420#if NULL_ALWAYS_DISTINCT
danielk19774adee202004-05-08 08:23:19 +0000421 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
drh0bd1f4e2002-06-06 18:54:39 +0000422#endif
danielk1977ededfd52004-06-17 07:53:01 +0000423 /* Deliberately leave the affinity string off of the following
424 ** OP_MakeRecord */
drhc182d162005-08-14 20:47:16 +0000425 sqlite3VdbeAddOp(v, OP_MakeRecord, -n, 0);
danielk19774adee202004-05-08 08:23:19 +0000426 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
drhc182d162005-08-14 20:47:16 +0000427 sqlite3VdbeAddOp(v, OP_Pop, n+1, 0);
danielk19774adee202004-05-08 08:23:19 +0000428 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000429 VdbeComment((v, "# skip indistinct records"));
drhf0863fe2005-06-12 21:35:51 +0000430 sqlite3VdbeAddOp(v, OP_IdxInsert, distinct, 0);
drhea48eb22004-07-19 23:16:38 +0000431 if( pOrderBy==0 ){
drhbab39e12004-07-19 23:38:11 +0000432 codeLimiter(v, p, iContinue, iBreak, nColumn);
drhea48eb22004-07-19 23:16:38 +0000433 }
drh22827922000-06-06 17:27:05 +0000434 }
drh82c3d632000-06-06 21:56:07 +0000435
drhc926afb2002-06-20 03:38:26 +0000436 switch( eDest ){
danielk19775338a5f2005-01-20 13:03:10 +0000437#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhc926afb2002-06-20 03:38:26 +0000438 /* In this mode, write each query result to the key of the temporary
439 ** table iParm.
440 */
441 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000442 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000443 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
drhf0863fe2005-06-12 21:35:51 +0000444 sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000445 break;
drh22827922000-06-06 17:27:05 +0000446 }
drh22827922000-06-06 17:27:05 +0000447
drhc926afb2002-06-20 03:38:26 +0000448 /* Construct a record from the query result, but instead of
449 ** saving that record, use it as a key to delete elements from
450 ** the temporary table iParm.
451 */
452 case SRT_Except: {
453 int addr;
danielk19774adee202004-05-08 08:23:19 +0000454 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000455 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000456 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
457 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000458 break;
459 }
danielk19775338a5f2005-01-20 13:03:10 +0000460#endif
461
462 /* Store the result as data using a unique key.
463 */
464 case SRT_Table:
465 case SRT_TempTable: {
466 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
467 if( pOrderBy ){
468 pushOntoSorter(pParse, v, pOrderBy);
469 }else{
drhf0863fe2005-06-12 21:35:51 +0000470 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
danielk19775338a5f2005-01-20 13:03:10 +0000471 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhf0863fe2005-06-12 21:35:51 +0000472 sqlite3VdbeAddOp(v, OP_Insert, iParm, 0);
danielk19775338a5f2005-01-20 13:03:10 +0000473 }
474 break;
475 }
drh5974a302000-06-07 14:42:26 +0000476
danielk197793758c82005-01-21 08:13:14 +0000477#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000478 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
479 ** then there should be a single item on the stack. Write this
480 ** item into the set table with bogus data.
481 */
482 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000483 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000484 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000485
drhc926afb2002-06-20 03:38:26 +0000486 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000487 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
488 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
489 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000490 if( pOrderBy ){
drhde941c62005-08-28 01:34:21 +0000491 /* At first glance you would think we could optimize out the
492 ** ORDER BY in this case since the order of entries in the set
493 ** does not matter. But there might be a LIMIT clause, in which
494 ** case the order does matter */
drhc926afb2002-06-20 03:38:26 +0000495 pushOntoSorter(pParse, v, pOrderBy);
496 }else{
danielk1977e014a832004-05-17 10:48:57 +0000497 char aff = (iParm>>16)&0xFF;
498 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
drh94a11212004-09-25 13:12:14 +0000499 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1);
drhf0863fe2005-06-12 21:35:51 +0000500 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000501 }
danielk19774adee202004-05-08 08:23:19 +0000502 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000503 break;
504 }
drh22827922000-06-06 17:27:05 +0000505
drhc926afb2002-06-20 03:38:26 +0000506 /* If this is a scalar select that is part of an expression, then
507 ** store the results in the appropriate memory cell and break out
508 ** of the scan loop.
509 */
drh51522cd2005-01-20 13:36:19 +0000510 case SRT_Exists:
drhc926afb2002-06-20 03:38:26 +0000511 case SRT_Mem: {
512 assert( nColumn==1 );
513 if( pOrderBy ){
514 pushOntoSorter(pParse, v, pOrderBy);
515 }else{
danielk19774adee202004-05-08 08:23:19 +0000516 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
517 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000518 }
519 break;
520 }
danielk197793758c82005-01-21 08:13:14 +0000521#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
drh22827922000-06-06 17:27:05 +0000522
drhc182d162005-08-14 20:47:16 +0000523 /* Send the data to the callback function or to a subroutine. In the
524 ** case of a subroutine, the subroutine itself is responsible for
525 ** popping the data from the stack.
drhf46f9052002-06-22 02:33:38 +0000526 */
drhc182d162005-08-14 20:47:16 +0000527 case SRT_Subroutine:
drhf46f9052002-06-22 02:33:38 +0000528 case SRT_Callback:
529 case SRT_Sorter: {
530 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000531 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000532 pushOntoSorter(pParse, v, pOrderBy);
drhc182d162005-08-14 20:47:16 +0000533 }else if( eDest==SRT_Subroutine ){
danielk19774adee202004-05-08 08:23:19 +0000534 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhc182d162005-08-14 20:47:16 +0000535 }else{
536 assert( eDest!=SRT_Sorter );
537 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000538 }
drh142e30d2002-08-28 03:00:58 +0000539 break;
540 }
541
danielk19776a67fe82005-02-04 04:07:16 +0000542#if !defined(SQLITE_OMIT_TRIGGER)
drhc926afb2002-06-20 03:38:26 +0000543 /* Discard the results. This is used for SELECT statements inside
544 ** the body of a TRIGGER. The purpose of such selects is to call
545 ** user-defined functions that have side effects. We do not care
546 ** about the actual results of the select.
547 */
drhc926afb2002-06-20 03:38:26 +0000548 default: {
drhf46f9052002-06-22 02:33:38 +0000549 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000550 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000551 break;
552 }
danielk197793758c82005-01-21 08:13:14 +0000553#endif
drh82c3d632000-06-06 21:56:07 +0000554 }
555 return 0;
556}
557
558/*
drhdece1a82005-08-31 18:20:00 +0000559** Given an expression list, generate a KeyInfo structure that records
560** the collating sequence for each expression in that expression list.
561**
drh0342b1f2005-09-01 03:07:44 +0000562** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
563** KeyInfo structure is appropriate for initializing a virtual index to
564** implement that clause. If the ExprList is the result set of a SELECT
565** then the KeyInfo structure is appropriate for initializing a virtual
566** index to implement a DISTINCT test.
567**
drhdece1a82005-08-31 18:20:00 +0000568** Space to hold the KeyInfo structure is obtain from malloc. The calling
569** function is responsible for seeing that this structure is eventually
570** freed. Add the KeyInfo structure to the P3 field of an opcode using
571** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
572*/
573static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
574 sqlite3 *db = pParse->db;
575 int nExpr;
576 KeyInfo *pInfo;
577 struct ExprList_item *pItem;
578 int i;
579
580 nExpr = pList->nExpr;
581 pInfo = sqliteMalloc( sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
582 if( pInfo ){
583 pInfo->aSortOrder = (char*)&pInfo->aColl[nExpr];
584 pInfo->nField = nExpr;
585 pInfo->enc = db->enc;
586 for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
587 CollSeq *pColl;
588 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
589 if( !pColl ){
590 pColl = db->pDfltColl;
591 }
592 pInfo->aColl[i] = pColl;
593 pInfo->aSortOrder[i] = pItem->sortOrder;
594 }
595 }
596 return pInfo;
597}
598
599
600/*
drhd8bc7082000-06-07 23:51:50 +0000601** If the inner loop was generated using a non-null pOrderBy argument,
602** then the results were placed in a sorter. After the loop is terminated
603** we need to run the sorter and output the results. The following
604** routine generates the code needed to do that.
605*/
drhc926afb2002-06-20 03:38:26 +0000606static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000607 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000608 Select *p, /* The SELECT statement */
609 Vdbe *v, /* Generate code into this VDBE */
610 int nColumn, /* Number of columns of data */
611 int eDest, /* Write the sorted results here */
612 int iParm /* Optional parameter associated with eDest */
613){
drh0342b1f2005-09-01 03:07:44 +0000614 int brk = sqlite3VdbeMakeLabel(v);
615 int cont = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000616 int addr;
drh0342b1f2005-09-01 03:07:44 +0000617 int iTab;
618 ExprList *pOrderBy = p->pOrderBy;
drhffbc3082004-05-21 01:29:06 +0000619
drhf46f9052002-06-22 02:33:38 +0000620 if( eDest==SRT_Sorter ) return;
drh0342b1f2005-09-01 03:07:44 +0000621 iTab = pOrderBy->iTab;
622 addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
623 codeLimiter(v, p, cont, brk, 0);
624 sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr);
drhc926afb2002-06-20 03:38:26 +0000625 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000626 case SRT_Table:
627 case SRT_TempTable: {
drhf0863fe2005-06-12 21:35:51 +0000628 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
danielk19774adee202004-05-08 08:23:19 +0000629 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhf0863fe2005-06-12 21:35:51 +0000630 sqlite3VdbeAddOp(v, OP_Insert, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000631 break;
632 }
danielk197793758c82005-01-21 08:13:14 +0000633#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000634 case SRT_Set: {
635 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000636 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
637 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
638 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
danielk1977ededfd52004-06-17 07:53:01 +0000639 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
drhf0863fe2005-06-12 21:35:51 +0000640 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000641 break;
642 }
drh51522cd2005-01-20 13:36:19 +0000643 case SRT_Exists:
drhc926afb2002-06-20 03:38:26 +0000644 case SRT_Mem: {
645 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000646 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh0342b1f2005-09-01 03:07:44 +0000647 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
drhc926afb2002-06-20 03:38:26 +0000648 break;
649 }
danielk197793758c82005-01-21 08:13:14 +0000650#endif
drhce665cf2004-05-21 03:01:58 +0000651 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000652 case SRT_Subroutine: {
653 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000654 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
655 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000656 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000657 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000658 }
drhce665cf2004-05-21 03:01:58 +0000659 if( eDest==SRT_Callback ){
660 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
661 }else{
662 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
663 }
danielk197784ac9d02004-05-18 09:58:06 +0000664 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000665 break;
666 }
drhc926afb2002-06-20 03:38:26 +0000667 default: {
drhf46f9052002-06-22 02:33:38 +0000668 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000669 break;
670 }
671 }
drh0342b1f2005-09-01 03:07:44 +0000672 sqlite3VdbeResolveLabel(v, cont);
673 sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
674 sqlite3VdbeResolveLabel(v, brk);
drhd8bc7082000-06-07 23:51:50 +0000675}
676
677/*
danielk1977517eb642004-06-07 10:00:31 +0000678** Return a pointer to a string containing the 'declaration type' of the
679** expression pExpr. The string may be treated as static by the caller.
drhe78e8282003-01-19 03:59:45 +0000680**
danielk1977517eb642004-06-07 10:00:31 +0000681** If the declaration type is the exact datatype definition extracted from
682** the original CREATE TABLE statement if the expression is a column.
683**
684** The declaration type for an expression is either TEXT, NUMERIC or ANY.
685** The declaration type for a ROWID field is INTEGER.
686*/
danielk1977b3bce662005-01-29 08:32:43 +0000687static const char *columnType(NameContext *pNC, Expr *pExpr){
danielk197700e279d2004-06-21 07:36:32 +0000688 char const *zType;
danielk1977517eb642004-06-07 10:00:31 +0000689 int j;
danielk1977b3bce662005-01-29 08:32:43 +0000690 if( pExpr==0 || pNC->pSrcList==0 ) return 0;
danielk19775338a5f2005-01-20 13:03:10 +0000691
692 /* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING,
693 ** and LIMIT clauses. But pExpr originates in the result set of a
694 ** SELECT. So pExpr can never contain an AS operator.
695 */
696 assert( pExpr->op!=TK_AS );
697
danielk197700e279d2004-06-21 07:36:32 +0000698 switch( pExpr->op ){
699 case TK_COLUMN: {
danielk1977b3bce662005-01-29 08:32:43 +0000700 Table *pTab = 0;
danielk197700e279d2004-06-21 07:36:32 +0000701 int iCol = pExpr->iColumn;
danielk1977b3bce662005-01-29 08:32:43 +0000702 while( pNC && !pTab ){
703 SrcList *pTabList = pNC->pSrcList;
704 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
705 if( j<pTabList->nSrc ){
706 pTab = pTabList->a[j].pTab;
707 }else{
708 pNC = pNC->pNext;
709 }
710 }
drh7e627792005-04-29 02:10:00 +0000711 if( pTab==0 ){
712 /* FIX ME:
713 ** This can occurs if you have something like "SELECT new.x;" inside
714 ** a trigger. In other words, if you reference the special "new"
715 ** table in the result set of a select. We do not have a good way
716 ** to find the actual table type, so call it "TEXT". This is really
717 ** something of a bug, but I do not know how to fix it.
718 **
719 ** This code does not produce the correct answer - it just prevents
720 ** a segfault. See ticket #1229.
721 */
722 zType = "TEXT";
723 break;
724 }
danielk1977b3bce662005-01-29 08:32:43 +0000725 assert( pTab );
danielk197700e279d2004-06-21 07:36:32 +0000726 if( iCol<0 ) iCol = pTab->iPKey;
727 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
728 if( iCol<0 ){
729 zType = "INTEGER";
730 }else{
731 zType = pTab->aCol[iCol].zType;
732 }
733 break;
danielk1977517eb642004-06-07 10:00:31 +0000734 }
danielk197793758c82005-01-21 08:13:14 +0000735#ifndef SQLITE_OMIT_SUBQUERY
danielk197700e279d2004-06-21 07:36:32 +0000736 case TK_SELECT: {
danielk1977b3bce662005-01-29 08:32:43 +0000737 NameContext sNC;
danielk197700e279d2004-06-21 07:36:32 +0000738 Select *pS = pExpr->pSelect;
danielk1977b3bce662005-01-29 08:32:43 +0000739 sNC.pSrcList = pExpr->pSelect->pSrc;
740 sNC.pNext = pNC;
741 zType = columnType(&sNC, pS->pEList->a[0].pExpr);
danielk197700e279d2004-06-21 07:36:32 +0000742 break;
danielk1977517eb642004-06-07 10:00:31 +0000743 }
danielk197793758c82005-01-21 08:13:14 +0000744#endif
danielk197700e279d2004-06-21 07:36:32 +0000745 default:
746 zType = 0;
danielk1977517eb642004-06-07 10:00:31 +0000747 }
danielk197700e279d2004-06-21 07:36:32 +0000748
danielk1977517eb642004-06-07 10:00:31 +0000749 return zType;
750}
751
752/*
753** Generate code that will tell the VDBE the declaration types of columns
754** in the result set.
drhfcb78a42003-01-18 20:11:05 +0000755*/
756static void generateColumnTypes(
757 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000758 SrcList *pTabList, /* List of tables */
759 ExprList *pEList /* Expressions defining the result set */
760){
761 Vdbe *v = pParse->pVdbe;
danielk1977517eb642004-06-07 10:00:31 +0000762 int i;
danielk1977b3bce662005-01-29 08:32:43 +0000763 NameContext sNC;
764 sNC.pSrcList = pTabList;
drhfcb78a42003-01-18 20:11:05 +0000765 for(i=0; i<pEList->nExpr; i++){
766 Expr *p = pEList->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +0000767 const char *zType = columnType(&sNC, p);
danielk197700e279d2004-06-21 07:36:32 +0000768 if( zType==0 ) continue;
danielk1977fbcd5852004-06-15 02:44:18 +0000769 /* The vdbe must make it's own copy of the column-type, in case the
770 ** schema is reset before this virtual machine is deleted.
771 */
772 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
drhfcb78a42003-01-18 20:11:05 +0000773 }
774}
775
776/*
777** Generate code that will tell the VDBE the names of columns
778** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000779** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000780*/
drh832508b2002-03-02 17:04:07 +0000781static void generateColumnNames(
782 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000783 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000784 ExprList *pEList /* Expressions defining the result set */
785){
drhd8bc7082000-06-07 23:51:50 +0000786 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000787 int i, j;
drh9bb575f2004-09-06 17:24:11 +0000788 sqlite3 *db = pParse->db;
drhfcabd462004-02-20 14:50:58 +0000789 int fullNames, shortNames;
790
drhfe2093d2005-01-20 22:48:47 +0000791#ifndef SQLITE_OMIT_EXPLAIN
danielk19773cf86062004-05-26 10:11:05 +0000792 /* If this is an EXPLAIN, skip this step */
793 if( pParse->explain ){
danielk197761de0d12004-05-27 23:56:16 +0000794 return;
danielk19773cf86062004-05-26 10:11:05 +0000795 }
danielk19775338a5f2005-01-20 13:03:10 +0000796#endif
danielk19773cf86062004-05-26 10:11:05 +0000797
drhd6502752004-02-16 03:44:01 +0000798 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000799 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000800 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000801 fullNames = (db->flags & SQLITE_FullColNames)!=0;
802 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
danielk197722322fd2004-05-25 23:35:17 +0000803 sqlite3VdbeSetNumCols(v, pEList->nExpr);
drh82c3d632000-06-06 21:56:07 +0000804 for(i=0; i<pEList->nExpr; i++){
805 Expr *p;
drh5a387052003-01-11 14:19:51 +0000806 p = pEList->a[i].pExpr;
807 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000808 if( pEList->a[i].zName ){
809 char *zName = pEList->a[i].zName;
danielk1977d8123362004-06-12 09:25:12 +0000810 sqlite3VdbeSetColName(v, i, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000811 continue;
812 }
drhfa173a72002-07-10 21:26:00 +0000813 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000814 Table *pTab;
drh97665872002-02-13 23:22:53 +0000815 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000816 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000817 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
818 assert( j<pTabList->nSrc );
819 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000820 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000821 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000822 if( iCol<0 ){
drh47a6db22005-01-18 16:02:40 +0000823 zCol = "rowid";
drhb1363202002-06-26 02:45:03 +0000824 }else{
825 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000826 }
drhfcabd462004-02-20 14:50:58 +0000827 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000828 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
drhfcabd462004-02-20 14:50:58 +0000829 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000830 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000831 char *zTab;
832
drh6a3ea0e2003-05-02 14:32:12 +0000833 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000834 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000835 sqlite3SetString(&zName, zTab, ".", zCol, 0);
danielk19773cf86062004-05-26 10:11:05 +0000836 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000837 }else{
drh47a6db22005-01-18 16:02:40 +0000838 sqlite3VdbeSetColName(v, i, zCol, strlen(zCol));
drh82c3d632000-06-06 21:56:07 +0000839 }
drh6977fea2002-10-22 23:38:04 +0000840 }else if( p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000841 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
842 /* sqlite3VdbeCompressSpace(v, addr); */
drh1bee3d72001-10-15 00:44:35 +0000843 }else{
844 char zName[30];
845 assert( p->op!=TK_COLUMN || pTabList==0 );
846 sprintf(zName, "column%d", i+1);
danielk19773cf86062004-05-26 10:11:05 +0000847 sqlite3VdbeSetColName(v, i, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000848 }
849 }
danielk197776d505b2004-05-28 13:13:02 +0000850 generateColumnTypes(pParse, pTabList, pEList);
drh82c3d632000-06-06 21:56:07 +0000851}
852
danielk197793758c82005-01-21 08:13:14 +0000853#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +0000854/*
drhd8bc7082000-06-07 23:51:50 +0000855** Name of the connection operator, used for error messages.
856*/
857static const char *selectOpName(int id){
858 char *z;
859 switch( id ){
860 case TK_ALL: z = "UNION ALL"; break;
861 case TK_INTERSECT: z = "INTERSECT"; break;
862 case TK_EXCEPT: z = "EXCEPT"; break;
863 default: z = "UNION"; break;
864 }
865 return z;
866}
danielk197793758c82005-01-21 08:13:14 +0000867#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +0000868
869/*
drh315555c2002-10-20 15:53:03 +0000870** Forward declaration
871*/
drh9b3187e2005-01-18 14:45:47 +0000872static int prepSelectStmt(Parse*, Select*);
drh315555c2002-10-20 15:53:03 +0000873
874/*
drh22f70c32002-02-18 01:17:00 +0000875** Given a SELECT statement, generate a Table structure that describes
876** the result set of that SELECT.
877*/
danielk19774adee202004-05-08 08:23:19 +0000878Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000879 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000880 int i, j;
drh22f70c32002-02-18 01:17:00 +0000881 ExprList *pEList;
drh290c1942004-08-21 17:54:45 +0000882 Column *aCol, *pCol;
drh22f70c32002-02-18 01:17:00 +0000883
drh9b3187e2005-01-18 14:45:47 +0000884 if( prepSelectStmt(pParse, pSelect) ){
drh22f70c32002-02-18 01:17:00 +0000885 return 0;
886 }
danielk1977142bdf42005-01-30 11:11:44 +0000887 if( sqlite3SelectResolve(pParse, pSelect, 0) ){
888 return 0;
889 }
drh22f70c32002-02-18 01:17:00 +0000890 pTab = sqliteMalloc( sizeof(Table) );
891 if( pTab==0 ){
892 return 0;
893 }
drhed8a3bb2005-06-06 21:19:56 +0000894 pTab->nRef = 1;
drh22f70c32002-02-18 01:17:00 +0000895 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
896 pEList = pSelect->pEList;
897 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000898 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000899 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh290c1942004-08-21 17:54:45 +0000900 for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
drh79d5f632005-01-18 17:20:10 +0000901 Expr *p, *pR;
danielk1977517eb642004-06-07 10:00:31 +0000902 char *zType;
drh91bb0ee2004-09-01 03:06:34 +0000903 char *zName;
drh79d5f632005-01-18 17:20:10 +0000904 char *zBasename;
905 int cnt;
danielk1977b3bce662005-01-29 08:32:43 +0000906 NameContext sNC;
drh79d5f632005-01-18 17:20:10 +0000907
908 /* Get an appropriate name for the column
909 */
910 p = pEList->a[i].pExpr;
drh290c1942004-08-21 17:54:45 +0000911 assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
drh91bb0ee2004-09-01 03:06:34 +0000912 if( (zName = pEList->a[i].zName)!=0 ){
drh79d5f632005-01-18 17:20:10 +0000913 /* If the column contains an "AS <name>" phrase, use <name> as the name */
drh91bb0ee2004-09-01 03:06:34 +0000914 zName = sqliteStrDup(zName);
danielk1977517eb642004-06-07 10:00:31 +0000915 }else if( p->op==TK_DOT
drh79d5f632005-01-18 17:20:10 +0000916 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
917 /* For columns of the from A.B use B as the name */
drh91bb0ee2004-09-01 03:06:34 +0000918 zName = sqlite3MPrintf("%T", &pR->token);
drhb733d032004-01-24 20:18:12 +0000919 }else if( p->span.z && p->span.z[0] ){
drh79d5f632005-01-18 17:20:10 +0000920 /* Use the original text of the column expression as its name */
drh91bb0ee2004-09-01 03:06:34 +0000921 zName = sqlite3MPrintf("%T", &p->span);
drh22f70c32002-02-18 01:17:00 +0000922 }else{
drh79d5f632005-01-18 17:20:10 +0000923 /* If all else fails, make up a name */
drh91bb0ee2004-09-01 03:06:34 +0000924 zName = sqlite3MPrintf("column%d", i+1);
drh22f70c32002-02-18 01:17:00 +0000925 }
drh91bb0ee2004-09-01 03:06:34 +0000926 sqlite3Dequote(zName);
drhdd5b2fa2005-03-28 03:39:55 +0000927 if( sqlite3_malloc_failed ){
928 sqliteFree(zName);
929 sqlite3DeleteTable(0, pTab);
930 return 0;
931 }
drh79d5f632005-01-18 17:20:10 +0000932
933 /* Make sure the column name is unique. If the name is not unique,
934 ** append a integer to the name so that it becomes unique.
935 */
936 zBasename = zName;
937 for(j=cnt=0; j<i; j++){
938 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
939 zName = sqlite3MPrintf("%s:%d", zBasename, ++cnt);
940 j = -1;
drhdd5b2fa2005-03-28 03:39:55 +0000941 if( zName==0 ) break;
drh79d5f632005-01-18 17:20:10 +0000942 }
943 }
944 if( zBasename!=zName ){
945 sqliteFree(zBasename);
946 }
drh91bb0ee2004-09-01 03:06:34 +0000947 pCol->zName = zName;
danielk1977517eb642004-06-07 10:00:31 +0000948
drh79d5f632005-01-18 17:20:10 +0000949 /* Get the typename, type affinity, and collating sequence for the
950 ** column.
951 */
drhc43e8be2005-05-16 22:37:54 +0000952 memset(&sNC, 0, sizeof(sNC));
danielk1977b3bce662005-01-29 08:32:43 +0000953 sNC.pSrcList = pSelect->pSrc;
954 zType = sqliteStrDup(columnType(&sNC, p));
drh290c1942004-08-21 17:54:45 +0000955 pCol->zType = zType;
danielk1977c60e9b82005-01-31 12:42:29 +0000956 pCol->affinity = sqlite3ExprAffinity(p);
drh290c1942004-08-21 17:54:45 +0000957 pCol->pColl = sqlite3ExprCollSeq(pParse, p);
958 if( !pCol->pColl ){
959 pCol->pColl = pParse->db->pDfltColl;
danielk19770202b292004-06-09 09:55:16 +0000960 }
drh22f70c32002-02-18 01:17:00 +0000961 }
962 pTab->iPKey = -1;
963 return pTab;
964}
965
966/*
drh9b3187e2005-01-18 14:45:47 +0000967** Prepare a SELECT statement for processing by doing the following
968** things:
drhd8bc7082000-06-07 23:51:50 +0000969**
drh9b3187e2005-01-18 14:45:47 +0000970** (1) Make sure VDBE cursor numbers have been assigned to every
971** element of the FROM clause.
972**
973** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
974** defines FROM clause. When views appear in the FROM clause,
drh63eb5f22003-04-29 16:20:44 +0000975** fill pTabList->a[].pSelect with a copy of the SELECT statement
976** that implements the view. A copy is made of the view's SELECT
977** statement so that we can freely modify or delete that statement
978** without worrying about messing up the presistent representation
979** of the view.
drhd8bc7082000-06-07 23:51:50 +0000980**
drh9b3187e2005-01-18 14:45:47 +0000981** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
drhad2d8302002-05-24 20:31:36 +0000982** on joins and the ON and USING clause of joins.
983**
drh9b3187e2005-01-18 14:45:47 +0000984** (4) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000985** for instances of the "*" operator or the TABLE.* operator.
986** If found, expand each "*" to be every column in every table
987** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000988**
989** Return 0 on success. If there are problems, leave an error message
990** in pParse and return non-zero.
991*/
drh9b3187e2005-01-18 14:45:47 +0000992static int prepSelectStmt(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000993 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000994 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000995 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000996 Table *pTab;
drh290c1942004-08-21 17:54:45 +0000997 struct SrcList_item *pFrom;
drhdaffd0e2001-04-11 14:28:42 +0000998
danielk1977e94ddc92005-03-21 03:53:38 +0000999 if( p==0 || p->pSrc==0 || sqlite3_malloc_failed ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00001000 pTabList = p->pSrc;
1001 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +00001002
drh9b3187e2005-01-18 14:45:47 +00001003 /* Make sure cursor numbers have been assigned to all entries in
1004 ** the FROM clause of the SELECT statement.
1005 */
1006 sqlite3SrcListAssignCursors(pParse, p->pSrc);
1007
1008 /* Look up every table named in the FROM clause of the select. If
1009 ** an entry of the FROM clause is a subquery instead of a table or view,
1010 ** then create a transient table structure to describe the subquery.
drhd8bc7082000-06-07 23:51:50 +00001011 */
drh290c1942004-08-21 17:54:45 +00001012 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
drh9b3187e2005-01-18 14:45:47 +00001013 if( pFrom->pTab!=0 ){
1014 /* This statement has already been prepared. There is no need
1015 ** to go further. */
1016 assert( i==0 );
drhd8bc7082000-06-07 23:51:50 +00001017 return 0;
1018 }
drh290c1942004-08-21 17:54:45 +00001019 if( pFrom->zName==0 ){
danielk197793758c82005-01-21 08:13:14 +00001020#ifndef SQLITE_OMIT_SUBQUERY
drh22f70c32002-02-18 01:17:00 +00001021 /* A sub-query in the FROM clause of a SELECT */
drh290c1942004-08-21 17:54:45 +00001022 assert( pFrom->pSelect!=0 );
1023 if( pFrom->zAlias==0 ){
drh91bb0ee2004-09-01 03:06:34 +00001024 pFrom->zAlias =
1025 sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
drhad2d8302002-05-24 20:31:36 +00001026 }
drhed8a3bb2005-06-06 21:19:56 +00001027 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001028 pFrom->pTab = pTab =
1029 sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
drh22f70c32002-02-18 01:17:00 +00001030 if( pTab==0 ){
1031 return 1;
1032 }
drh5cf590c2003-04-24 01:45:04 +00001033 /* The isTransient flag indicates that the Table structure has been
1034 ** dynamically allocated and may be freed at any time. In other words,
1035 ** pTab is not pointing to a persistent table structure that defines
1036 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +00001037 pTab->isTransient = 1;
danielk197793758c82005-01-21 08:13:14 +00001038#endif
drh22f70c32002-02-18 01:17:00 +00001039 }else{
drha76b5df2002-02-23 02:32:10 +00001040 /* An ordinary table or view name in the FROM clause */
drhed8a3bb2005-06-06 21:19:56 +00001041 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001042 pFrom->pTab = pTab =
1043 sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
drha76b5df2002-02-23 02:32:10 +00001044 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +00001045 return 1;
1046 }
drhed8a3bb2005-06-06 21:19:56 +00001047 pTab->nRef++;
danielk197793758c82005-01-21 08:13:14 +00001048#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00001049 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +00001050 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +00001051 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +00001052 return 1;
1053 }
drh290c1942004-08-21 17:54:45 +00001054 /* If pFrom->pSelect!=0 it means we are dealing with a
drh63eb5f22003-04-29 16:20:44 +00001055 ** view within a view. The SELECT structure has already been
1056 ** copied by the outer view so we can skip the copy step here
1057 ** in the inner view.
1058 */
drh290c1942004-08-21 17:54:45 +00001059 if( pFrom->pSelect==0 ){
1060 pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +00001061 }
drha76b5df2002-02-23 02:32:10 +00001062 }
danielk197793758c82005-01-21 08:13:14 +00001063#endif
drhd8bc7082000-06-07 23:51:50 +00001064 }
1065 }
1066
drhad2d8302002-05-24 20:31:36 +00001067 /* Process NATURAL keywords, and ON and USING clauses of joins.
1068 */
1069 if( sqliteProcessJoin(pParse, p) ) return 1;
1070
drh7c917d12001-12-16 20:05:05 +00001071 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +00001072 ** all columns in all tables. And for every TABLE.* insert the names
1073 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +00001074 ** with the TK_ALL operator for each "*" that it found in the column list.
1075 ** The following code just has to locate the TK_ALL expressions and expand
1076 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +00001077 **
1078 ** The first loop just checks to see if there are any "*" operators
1079 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +00001080 */
drh7c917d12001-12-16 20:05:05 +00001081 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001082 Expr *pE = pEList->a[k].pExpr;
1083 if( pE->op==TK_ALL ) break;
1084 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
1085 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +00001086 }
drh54473222002-04-04 02:10:55 +00001087 rc = 0;
drh7c917d12001-12-16 20:05:05 +00001088 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +00001089 /*
1090 ** If we get here it means the result set contains one or more "*"
1091 ** operators that need to be expanded. Loop through each expression
1092 ** in the result set and expand them one by one.
1093 */
drh7c917d12001-12-16 20:05:05 +00001094 struct ExprList_item *a = pEList->a;
1095 ExprList *pNew = 0;
drhd70dc522005-06-06 16:34:33 +00001096 int flags = pParse->db->flags;
1097 int longNames = (flags & SQLITE_FullColNames)!=0 &&
1098 (flags & SQLITE_ShortColNames)==0;
1099
drh7c917d12001-12-16 20:05:05 +00001100 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001101 Expr *pE = a[k].pExpr;
1102 if( pE->op!=TK_ALL &&
1103 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
1104 /* This particular expression does not need to be expanded.
1105 */
danielk19774adee202004-05-08 08:23:19 +00001106 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001107 pNew->a[pNew->nExpr-1].zName = a[k].zName;
1108 a[k].pExpr = 0;
1109 a[k].zName = 0;
1110 }else{
drh54473222002-04-04 02:10:55 +00001111 /* This expression is a "*" or a "TABLE.*" and needs to be
1112 ** expanded. */
1113 int tableSeen = 0; /* Set to 1 when TABLE matches */
drhcf55b7a2004-07-20 01:45:19 +00001114 char *zTName; /* text of name of TABLE */
drh54473222002-04-04 02:10:55 +00001115 if( pE->op==TK_DOT && pE->pLeft ){
drhcf55b7a2004-07-20 01:45:19 +00001116 zTName = sqlite3NameFromToken(&pE->pLeft->token);
drh54473222002-04-04 02:10:55 +00001117 }else{
drhcf55b7a2004-07-20 01:45:19 +00001118 zTName = 0;
drh54473222002-04-04 02:10:55 +00001119 }
drh290c1942004-08-21 17:54:45 +00001120 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1121 Table *pTab = pFrom->pTab;
1122 char *zTabName = pFrom->zAlias;
drh54473222002-04-04 02:10:55 +00001123 if( zTabName==0 || zTabName[0]==0 ){
1124 zTabName = pTab->zName;
1125 }
drhcf55b7a2004-07-20 01:45:19 +00001126 if( zTName && (zTabName==0 || zTabName[0]==0 ||
1127 sqlite3StrICmp(zTName, zTabName)!=0) ){
drh54473222002-04-04 02:10:55 +00001128 continue;
1129 }
1130 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001131 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001132 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001133 char *zName = pTab->aCol[j].zName;
1134
drh91bb0ee2004-09-01 03:06:34 +00001135 if( i>0 ){
1136 struct SrcList_item *pLeft = &pTabList->a[i-1];
1137 if( (pLeft->jointype & JT_NATURAL)!=0 &&
1138 columnIndex(pLeft->pTab, zName)>=0 ){
1139 /* In a NATURAL join, omit the join columns from the
1140 ** table on the right */
1141 continue;
1142 }
1143 if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1144 /* In a join with a USING clause, omit columns in the
1145 ** using clause from the table on the right. */
1146 continue;
1147 }
drhad2d8302002-05-24 20:31:36 +00001148 }
danielk19774adee202004-05-08 08:23:19 +00001149 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001150 if( pRight==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001151 setToken(&pRight->token, zName);
drhd70dc522005-06-06 16:34:33 +00001152 if( zTabName && (longNames || pTabList->nSrc>1) ){
danielk19774adee202004-05-08 08:23:19 +00001153 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1154 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001155 if( pExpr==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001156 setToken(&pLeft->token, zTabName);
1157 setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
drh6977fea2002-10-22 23:38:04 +00001158 pExpr->span.dyn = 1;
1159 pExpr->token.z = 0;
1160 pExpr->token.n = 0;
1161 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001162 }else{
drh22f70c32002-02-18 01:17:00 +00001163 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001164 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001165 }
drhd70dc522005-06-06 16:34:33 +00001166 if( longNames ){
1167 pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span);
1168 }else{
1169 pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
1170 }
drh7c917d12001-12-16 20:05:05 +00001171 }
drh17e24df2001-11-06 14:10:41 +00001172 }
drh54473222002-04-04 02:10:55 +00001173 if( !tableSeen ){
drhcf55b7a2004-07-20 01:45:19 +00001174 if( zTName ){
1175 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
drhf5db2d32002-06-06 23:42:27 +00001176 }else{
danielk19774adee202004-05-08 08:23:19 +00001177 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001178 }
drh54473222002-04-04 02:10:55 +00001179 rc = 1;
1180 }
drhcf55b7a2004-07-20 01:45:19 +00001181 sqliteFree(zTName);
drhd8bc7082000-06-07 23:51:50 +00001182 }
1183 }
danielk19774adee202004-05-08 08:23:19 +00001184 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001185 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001186 }
drh54473222002-04-04 02:10:55 +00001187 return rc;
drhd8bc7082000-06-07 23:51:50 +00001188}
1189
danielk197793758c82005-01-21 08:13:14 +00001190#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhff78bd22002-02-27 01:47:11 +00001191/*
drhd8bc7082000-06-07 23:51:50 +00001192** This routine associates entries in an ORDER BY expression list with
1193** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001194** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001195** the top-level node is filled in with column number and the iTable
1196** value of the top-level node is filled with iTable parameter.
1197**
1198** If there are prior SELECT clauses, they are processed first. A match
1199** in an earlier SELECT takes precedence over a later SELECT.
1200**
1201** Any entry that does not match is flagged as an error. The number
1202** of errors is returned.
1203*/
1204static int matchOrderbyToColumn(
1205 Parse *pParse, /* A place to leave error messages */
1206 Select *pSelect, /* Match to result columns of this SELECT */
1207 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001208 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001209 int mustComplete /* If TRUE all ORDER BYs must match */
1210){
1211 int nErr = 0;
1212 int i, j;
1213 ExprList *pEList;
1214
drhdaffd0e2001-04-11 14:28:42 +00001215 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001216 if( mustComplete ){
1217 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1218 }
drh9b3187e2005-01-18 14:45:47 +00001219 if( prepSelectStmt(pParse, pSelect) ){
drhd8bc7082000-06-07 23:51:50 +00001220 return 1;
1221 }
1222 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001223 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1224 return 1;
1225 }
drhd8bc7082000-06-07 23:51:50 +00001226 }
1227 pEList = pSelect->pEList;
1228 for(i=0; i<pOrderBy->nExpr; i++){
1229 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001230 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001231 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001232 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001233 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001234 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001235 "ORDER BY position %d should be between 1 and %d",
1236 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001237 nErr++;
1238 break;
1239 }
drhfcb78a42003-01-18 20:11:05 +00001240 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001241 iCol--;
1242 }
1243 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001244 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001245 char *zName, *zLabel;
1246 zName = pEList->a[j].zName;
drha99db3b2004-06-19 14:49:12 +00001247 zLabel = sqlite3NameFromToken(&pE->token);
1248 assert( zLabel!=0 );
danielk19774adee202004-05-08 08:23:19 +00001249 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001250 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001251 }
drh6e142f52000-06-08 13:36:40 +00001252 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001253 }
danielk19774adee202004-05-08 08:23:19 +00001254 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001255 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001256 }
1257 }
drhe4de1fe2002-06-02 16:09:01 +00001258 if( iCol>=0 ){
1259 pE->op = TK_COLUMN;
1260 pE->iColumn = iCol;
1261 pE->iTable = iTable;
danielk1977a58fdfb2005-02-08 07:50:40 +00001262 pE->iAgg = -1;
drhe4de1fe2002-06-02 16:09:01 +00001263 pOrderBy->a[i].done = 1;
1264 }
1265 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001266 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001267 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001268 nErr++;
1269 break;
1270 }
1271 }
1272 return nErr;
1273}
danielk197793758c82005-01-21 08:13:14 +00001274#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +00001275
1276/*
1277** Get a VDBE for the given parser context. Create a new one if necessary.
1278** If an error occurs, return NULL and leave a message in pParse.
1279*/
danielk19774adee202004-05-08 08:23:19 +00001280Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001281 Vdbe *v = pParse->pVdbe;
1282 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001283 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001284 }
drhd8bc7082000-06-07 23:51:50 +00001285 return v;
1286}
drhfcb78a42003-01-18 20:11:05 +00001287
drhd8bc7082000-06-07 23:51:50 +00001288/*
drh7b58dae2003-07-20 01:16:46 +00001289** Compute the iLimit and iOffset fields of the SELECT based on the
danielk1977a2dc3b12005-02-05 12:48:48 +00001290** pLimit and pOffset expressions. nLimit and nOffset hold the expressions
drh7b58dae2003-07-20 01:16:46 +00001291** that appear in the original SQL statement after the LIMIT and OFFSET
danielk1977a2dc3b12005-02-05 12:48:48 +00001292** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
1293** are the integer memory register numbers for counters used to compute
1294** the limit and offset. If there is no limit and/or offset, then
1295** iLimit and iOffset are negative.
drh7b58dae2003-07-20 01:16:46 +00001296**
1297** This routine changes the values if iLimit and iOffset only if
1298** a limit or offset is defined by nLimit and nOffset. iLimit and
1299** iOffset should have been preset to appropriate default values
1300** (usually but not always -1) prior to calling this routine.
1301** Only if nLimit>=0 or nOffset>0 do the limit registers get
1302** redefined. The UNION ALL operator uses this property to force
1303** the reuse of the same limit and offset registers across multiple
1304** SELECT statements.
1305*/
1306static void computeLimitRegisters(Parse *pParse, Select *p){
1307 /*
drh7b58dae2003-07-20 01:16:46 +00001308 ** "LIMIT -1" always shows all rows. There is some
1309 ** contraversy about what the correct behavior should be.
1310 ** The current implementation interprets "LIMIT 0" to mean
1311 ** no rows.
1312 */
danielk1977a2dc3b12005-02-05 12:48:48 +00001313 if( p->pLimit ){
drh7b58dae2003-07-20 01:16:46 +00001314 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001315 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001316 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001317 sqlite3ExprCode(pParse, p->pLimit);
1318 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1319 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001320 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001321 VdbeComment((v, "# LIMIT counter"));
drh7b58dae2003-07-20 01:16:46 +00001322 p->iLimit = iMem;
1323 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001324 if( p->pOffset ){
drh7b58dae2003-07-20 01:16:46 +00001325 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001326 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001327 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001328 sqlite3ExprCode(pParse, p->pOffset);
1329 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1330 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001331 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001332 VdbeComment((v, "# OFFSET counter"));
drh7b58dae2003-07-20 01:16:46 +00001333 p->iOffset = iMem;
1334 }
1335}
1336
1337/*
drh0342b1f2005-09-01 03:07:44 +00001338** Allocate a virtual index to use for sorting.
drhd3d39e92004-05-20 22:16:29 +00001339*/
drh0342b1f2005-09-01 03:07:44 +00001340static createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
1341 if( pOrderBy ){
1342 int addr;
1343 assert( pOrderBy->iTab==0 );
1344 pOrderBy->iTab = pParse->nTab++;
1345 addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenVirtual,
1346 pOrderBy->iTab, pOrderBy->nExpr+1);
1347 assert( p->addrOpenVirt[2] == -1 );
1348 p->addrOpenVirt[2] = addr;
drh736c22b2004-05-21 02:14:24 +00001349 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001350}
1351
drhb7f91642004-10-31 02:22:47 +00001352#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001353/*
drhfbc4ee72004-08-29 01:31:05 +00001354** Return the appropriate collating sequence for the iCol-th column of
1355** the result set for the compound-select statement "p". Return NULL if
1356** the column has no default collating sequence.
1357**
1358** The collating sequence for the compound select is taken from the
1359** left-most term of the select that has a collating sequence.
1360*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001361static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
drhfbc4ee72004-08-29 01:31:05 +00001362 CollSeq *pRet;
danielk1977dc1bdc42004-06-11 10:51:27 +00001363 if( p->pPrior ){
1364 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
drhfbc4ee72004-08-29 01:31:05 +00001365 }else{
1366 pRet = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001367 }
drhfbc4ee72004-08-29 01:31:05 +00001368 if( pRet==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001369 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1370 }
1371 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001372}
drhb7f91642004-10-31 02:22:47 +00001373#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd3d39e92004-05-20 22:16:29 +00001374
drhb7f91642004-10-31 02:22:47 +00001375#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhd3d39e92004-05-20 22:16:29 +00001376/*
drh82c3d632000-06-06 21:56:07 +00001377** This routine is called to process a query that is really the union
1378** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001379**
drhe78e8282003-01-19 03:59:45 +00001380** "p" points to the right-most of the two queries. the query on the
1381** left is p->pPrior. The left query could also be a compound query
1382** in which case this routine will be called recursively.
1383**
1384** The results of the total query are to be written into a destination
1385** of type eDest with parameter iParm.
1386**
1387** Example 1: Consider a three-way compound SQL statement.
1388**
1389** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1390**
1391** This statement is parsed up as follows:
1392**
1393** SELECT c FROM t3
1394** |
1395** `-----> SELECT b FROM t2
1396** |
jplyon4b11c6d2004-01-19 04:57:53 +00001397** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001398**
1399** The arrows in the diagram above represent the Select.pPrior pointer.
1400** So if this routine is called with p equal to the t3 query, then
1401** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1402**
1403** Notice that because of the way SQLite parses compound SELECTs, the
1404** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001405*/
danielk197784ac9d02004-05-18 09:58:06 +00001406static int multiSelect(
drhfbc4ee72004-08-29 01:31:05 +00001407 Parse *pParse, /* Parsing context */
1408 Select *p, /* The right-most of SELECTs to be coded */
1409 int eDest, /* \___ Store query results as specified */
1410 int iParm, /* / by these two parameters. */
1411 char *aff /* If eDest is SRT_Union, the affinity string */
danielk197784ac9d02004-05-18 09:58:06 +00001412){
drhfbc4ee72004-08-29 01:31:05 +00001413 int rc = SQLITE_OK; /* Success code from a subroutine */
1414 Select *pPrior; /* Another SELECT immediately to our left */
1415 Vdbe *v; /* Generate code to this VDBE */
drh8cdbf832004-08-29 16:25:03 +00001416 int nCol; /* Number of columns in the result set */
drh0342b1f2005-09-01 03:07:44 +00001417 ExprList *pOrderBy; /* The ORDER BY clause on p */
1418 int aSetP2[2]; /* Set P2 value of these op to number of columns */
1419 int nSetP2 = 0; /* Number of slots in aSetP2[] used */
drh82c3d632000-06-06 21:56:07 +00001420
drh7b58dae2003-07-20 01:16:46 +00001421 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
drhfbc4ee72004-08-29 01:31:05 +00001422 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001423 */
danielk197784ac9d02004-05-18 09:58:06 +00001424 if( p==0 || p->pPrior==0 ){
1425 rc = 1;
1426 goto multi_select_end;
1427 }
drhd8bc7082000-06-07 23:51:50 +00001428 pPrior = p->pPrior;
drh0342b1f2005-09-01 03:07:44 +00001429 assert( pPrior->pRightmost!=pPrior );
1430 assert( pPrior->pRightmost==p->pRightmost );
drhd8bc7082000-06-07 23:51:50 +00001431 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001432 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001433 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001434 rc = 1;
1435 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001436 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001437 if( pPrior->pLimit ){
danielk19774adee202004-05-08 08:23:19 +00001438 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001439 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001440 rc = 1;
1441 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001442 }
drh82c3d632000-06-06 21:56:07 +00001443
drhd8bc7082000-06-07 23:51:50 +00001444 /* Make sure we have a valid query engine. If not, create a new one.
1445 */
danielk19774adee202004-05-08 08:23:19 +00001446 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001447 if( v==0 ){
1448 rc = 1;
1449 goto multi_select_end;
1450 }
drhd8bc7082000-06-07 23:51:50 +00001451
drh1cc3d752002-03-23 00:31:29 +00001452 /* Create the destination temporary table if necessary
1453 */
1454 if( eDest==SRT_TempTable ){
danielk1977b4964b72004-05-18 01:23:38 +00001455 assert( p->pEList );
drh0342b1f2005-09-01 03:07:44 +00001456 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1457 aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 0);
drh1cc3d752002-03-23 00:31:29 +00001458 eDest = SRT_Table;
1459 }
1460
drhf46f9052002-06-22 02:33:38 +00001461 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001462 */
drh0342b1f2005-09-01 03:07:44 +00001463 pOrderBy = p->pOrderBy;
drh82c3d632000-06-06 21:56:07 +00001464 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001465 case TK_ALL: {
drh0342b1f2005-09-01 03:07:44 +00001466 if( pOrderBy==0 ){
danielk1977a2dc3b12005-02-05 12:48:48 +00001467 assert( !pPrior->pLimit );
1468 pPrior->pLimit = p->pLimit;
1469 pPrior->pOffset = p->pOffset;
danielk1977b3bce662005-01-29 08:32:43 +00001470 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001471 if( rc ){
1472 goto multi_select_end;
1473 }
drhf46f9052002-06-22 02:33:38 +00001474 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001475 p->iLimit = pPrior->iLimit;
1476 p->iOffset = pPrior->iOffset;
danielk1977a2dc3b12005-02-05 12:48:48 +00001477 p->pLimit = 0;
1478 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001479 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001480 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001481 if( rc ){
1482 goto multi_select_end;
1483 }
drhf46f9052002-06-22 02:33:38 +00001484 break;
1485 }
1486 /* For UNION ALL ... ORDER BY fall through to the next case */
1487 }
drh82c3d632000-06-06 21:56:07 +00001488 case TK_EXCEPT:
1489 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001490 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001491 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001492 int priorOp; /* The SRT_ operation to apply to prior selects */
danielk1977a2dc3b12005-02-05 12:48:48 +00001493 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
danielk1977dc1bdc42004-06-11 10:51:27 +00001494 int addr;
drh82c3d632000-06-06 21:56:07 +00001495
drhd8bc7082000-06-07 23:51:50 +00001496 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh0342b1f2005-09-01 03:07:44 +00001497 if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
drhd8bc7082000-06-07 23:51:50 +00001498 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001499 ** right.
drhd8bc7082000-06-07 23:51:50 +00001500 */
drh82c3d632000-06-06 21:56:07 +00001501 unionTab = iParm;
1502 }else{
drhd8bc7082000-06-07 23:51:50 +00001503 /* We will need to create our own temporary table to hold the
1504 ** intermediate results.
1505 */
1506 unionTab = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001507 if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001508 rc = 1;
1509 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001510 }
drh9170dd72005-07-08 17:13:46 +00001511 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, unionTab, 0);
drh0342b1f2005-09-01 03:07:44 +00001512 if( priorOp==SRT_Table ){
1513 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1514 aSetP2[nSetP2++] = addr;
1515 }else{
1516 assert( p->addrOpenVirt[0] == -1 );
1517 p->addrOpenVirt[0] = addr;
1518 p->pRightmost->usesVirt = 1;
drhd8bc7082000-06-07 23:51:50 +00001519 }
drh0342b1f2005-09-01 03:07:44 +00001520 createSortingIndex(pParse, p, pOrderBy);
danielk197784ac9d02004-05-18 09:58:06 +00001521 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001522 }
drhd8bc7082000-06-07 23:51:50 +00001523
1524 /* Code the SELECT statements to our left
1525 */
danielk1977b3bce662005-01-29 08:32:43 +00001526 assert( !pPrior->pOrderBy );
1527 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001528 if( rc ){
1529 goto multi_select_end;
1530 }
drhd8bc7082000-06-07 23:51:50 +00001531
1532 /* Code the current SELECT statement
1533 */
1534 switch( p->op ){
1535 case TK_EXCEPT: op = SRT_Except; break;
1536 case TK_UNION: op = SRT_Union; break;
1537 case TK_ALL: op = SRT_Table; break;
1538 }
drh82c3d632000-06-06 21:56:07 +00001539 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001540 p->pOrderBy = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001541 pLimit = p->pLimit;
1542 p->pLimit = 0;
1543 pOffset = p->pOffset;
1544 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001545 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001546 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001547 p->pOrderBy = pOrderBy;
danielk1977a2dc3b12005-02-05 12:48:48 +00001548 sqlite3ExprDelete(p->pLimit);
1549 p->pLimit = pLimit;
1550 p->pOffset = pOffset;
drhbe5fd492004-12-16 21:09:16 +00001551 p->iLimit = -1;
1552 p->iOffset = -1;
danielk197784ac9d02004-05-18 09:58:06 +00001553 if( rc ){
1554 goto multi_select_end;
1555 }
1556
drhd8bc7082000-06-07 23:51:50 +00001557
1558 /* Convert the data in the temporary table into whatever form
1559 ** it is that we currently need.
1560 */
drhc926afb2002-06-20 03:38:26 +00001561 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001562 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001563 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001564 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001565 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001566 }
danielk19774adee202004-05-08 08:23:19 +00001567 iBreak = sqlite3VdbeMakeLabel(v);
1568 iCont = sqlite3VdbeMakeLabel(v);
1569 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001570 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001571 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001572 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001573 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001574 iCont, iBreak, 0);
1575 if( rc ){
1576 rc = 1;
1577 goto multi_select_end;
1578 }
danielk19774adee202004-05-08 08:23:19 +00001579 sqlite3VdbeResolveLabel(v, iCont);
1580 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1581 sqlite3VdbeResolveLabel(v, iBreak);
1582 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001583 }
1584 break;
1585 }
1586 case TK_INTERSECT: {
1587 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001588 int iCont, iBreak, iStart;
danielk1977a2dc3b12005-02-05 12:48:48 +00001589 Expr *pLimit, *pOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001590 int addr;
drh82c3d632000-06-06 21:56:07 +00001591
drhd8bc7082000-06-07 23:51:50 +00001592 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001593 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001594 ** by allocating the tables we will need.
1595 */
drh82c3d632000-06-06 21:56:07 +00001596 tab1 = pParse->nTab++;
1597 tab2 = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001598 if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001599 rc = 1;
1600 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001601 }
drh0342b1f2005-09-01 03:07:44 +00001602 createSortingIndex(pParse, p, pOrderBy);
danielk1977dc1bdc42004-06-11 10:51:27 +00001603
drh9170dd72005-07-08 17:13:46 +00001604 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab1, 0);
drh0342b1f2005-09-01 03:07:44 +00001605 assert( p->addrOpenVirt[0] == -1 );
1606 p->addrOpenVirt[0] = addr;
1607 p->pRightmost->usesVirt = 1;
danielk197784ac9d02004-05-18 09:58:06 +00001608 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001609
1610 /* Code the SELECTs to our left into temporary table "tab1".
1611 */
danielk1977b3bce662005-01-29 08:32:43 +00001612 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001613 if( rc ){
1614 goto multi_select_end;
1615 }
drhd8bc7082000-06-07 23:51:50 +00001616
1617 /* Code the current SELECT into temporary table "tab2"
1618 */
drh9170dd72005-07-08 17:13:46 +00001619 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab2, 0);
drh0342b1f2005-09-01 03:07:44 +00001620 assert( p->addrOpenVirt[1] == -1 );
1621 p->addrOpenVirt[1] = addr;
drh82c3d632000-06-06 21:56:07 +00001622 p->pPrior = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001623 pLimit = p->pLimit;
1624 p->pLimit = 0;
1625 pOffset = p->pOffset;
1626 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001627 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001628 p->pPrior = pPrior;
danielk1977a2dc3b12005-02-05 12:48:48 +00001629 sqlite3ExprDelete(p->pLimit);
1630 p->pLimit = pLimit;
1631 p->pOffset = pOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001632 if( rc ){
1633 goto multi_select_end;
1634 }
drhd8bc7082000-06-07 23:51:50 +00001635
1636 /* Generate code to take the intersection of the two temporary
1637 ** tables.
1638 */
drh82c3d632000-06-06 21:56:07 +00001639 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001640 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001641 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001642 }
danielk19774adee202004-05-08 08:23:19 +00001643 iBreak = sqlite3VdbeMakeLabel(v);
1644 iCont = sqlite3VdbeMakeLabel(v);
1645 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001646 computeLimitRegisters(pParse, p);
drh4a9f2412005-06-12 12:01:19 +00001647 iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
danielk19774adee202004-05-08 08:23:19 +00001648 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001649 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001650 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001651 iCont, iBreak, 0);
1652 if( rc ){
1653 rc = 1;
1654 goto multi_select_end;
1655 }
danielk19774adee202004-05-08 08:23:19 +00001656 sqlite3VdbeResolveLabel(v, iCont);
1657 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1658 sqlite3VdbeResolveLabel(v, iBreak);
1659 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1660 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001661 break;
1662 }
1663 }
drh8cdbf832004-08-29 16:25:03 +00001664
1665 /* Make sure all SELECTs in the statement have the same number of elements
1666 ** in their result sets.
1667 */
drh82c3d632000-06-06 21:56:07 +00001668 assert( p->pEList && pPrior->pEList );
1669 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001670 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001671 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001672 rc = 1;
1673 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001674 }
danielk197784ac9d02004-05-18 09:58:06 +00001675
drh8cdbf832004-08-29 16:25:03 +00001676 /* Set the number of columns in temporary tables
1677 */
1678 nCol = p->pEList->nExpr;
drh0342b1f2005-09-01 03:07:44 +00001679 while( nSetP2 ){
1680 sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
drh8cdbf832004-08-29 16:25:03 +00001681 }
1682
drhfbc4ee72004-08-29 01:31:05 +00001683 /* Compute collating sequences used by either the ORDER BY clause or
1684 ** by any temporary tables needed to implement the compound select.
1685 ** Attach the KeyInfo structure to all temporary tables. Invoke the
1686 ** ORDER BY processing if there is an ORDER BY clause.
drh8cdbf832004-08-29 16:25:03 +00001687 **
1688 ** This section is run by the right-most SELECT statement only.
1689 ** SELECT statements to the left always skip this part. The right-most
1690 ** SELECT might also skip this part if it has no ORDER BY clause and
1691 ** no temp tables are required.
drhfbc4ee72004-08-29 01:31:05 +00001692 */
drh0342b1f2005-09-01 03:07:44 +00001693 if( pOrderBy || p->usesVirt ){
drhfbc4ee72004-08-29 01:31:05 +00001694 int i; /* Loop counter */
1695 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
drh0342b1f2005-09-01 03:07:44 +00001696 Select *pLoop; /* For looping through SELECT statements */
1697 CollSeq **apColl;
1698 CollSeq **aCopy;
drhfbc4ee72004-08-29 01:31:05 +00001699
drh0342b1f2005-09-01 03:07:44 +00001700 assert( p->pRightmost==p );
1701 pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*2*sizeof(CollSeq*));
danielk1977dc1bdc42004-06-11 10:51:27 +00001702 if( !pKeyInfo ){
1703 rc = SQLITE_NOMEM;
1704 goto multi_select_end;
1705 }
1706
1707 pKeyInfo->enc = pParse->db->enc;
1708 pKeyInfo->nField = nCol;
1709
drh0342b1f2005-09-01 03:07:44 +00001710 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
1711 *apColl = multiSelectCollSeq(pParse, p, i);
1712 if( 0==*apColl ){
1713 *apColl = pParse->db->pDfltColl;
danielk1977dc1bdc42004-06-11 10:51:27 +00001714 }
1715 }
1716
drh0342b1f2005-09-01 03:07:44 +00001717 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
1718 for(i=0; i<2; i++){
1719 int addr = pLoop->addrOpenVirt[i];
1720 if( addr<0 ){
1721 /* If [0] is unused then [1] is also unused. So we can
1722 ** always safely abort as soon as the first unused slot is found */
1723 assert( pLoop->addrOpenVirt[1]<0 );
1724 break;
1725 }
1726 sqlite3VdbeChangeP2(v, addr, nCol);
1727 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
1728 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001729 }
1730
drh0342b1f2005-09-01 03:07:44 +00001731 if( pOrderBy ){
1732 struct ExprList_item *pOTerm = pOrderBy->a;
1733 int nExpr = pOrderBy->nExpr;
1734 int addr;
1735
1736 aCopy = (CollSeq**)&pKeyInfo[1];
1737 memcpy(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
1738 apColl = pKeyInfo->aColl;
1739 for(i=0; i<pOrderBy->nExpr; i++, pOTerm++, apColl++){
1740 Expr *pExpr = pOTerm->pExpr;
1741 char *zName = pOTerm->zName;
danielk1977dc1bdc42004-06-11 10:51:27 +00001742 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
danielk1977dc1bdc42004-06-11 10:51:27 +00001743 if( zName ){
drh0342b1f2005-09-01 03:07:44 +00001744 *apColl = sqlite3LocateCollSeq(pParse, zName, -1);
danielk1977dc1bdc42004-06-11 10:51:27 +00001745 }else{
drh0342b1f2005-09-01 03:07:44 +00001746 *apColl = aCopy[pExpr->iColumn];
danielk1977dc1bdc42004-06-11 10:51:27 +00001747 }
1748 }
drh0342b1f2005-09-01 03:07:44 +00001749 assert( p->pRightmost==p );
1750 assert( p->addrOpenVirt[2]>=0 );
1751 addr = p->addrOpenVirt[2];
1752 sqlite3VdbeChangeP2(v, addr, p->pEList->nExpr+1);
1753 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
danielk1977dc1bdc42004-06-11 10:51:27 +00001754 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1755 }
1756
drh0342b1f2005-09-01 03:07:44 +00001757 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001758 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001759
1760multi_select_end:
danielk197784ac9d02004-05-18 09:58:06 +00001761 return rc;
drh22827922000-06-06 17:27:05 +00001762}
drhb7f91642004-10-31 02:22:47 +00001763#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drh22827922000-06-06 17:27:05 +00001764
drhb7f91642004-10-31 02:22:47 +00001765#ifndef SQLITE_OMIT_VIEW
drh22827922000-06-06 17:27:05 +00001766/*
drh832508b2002-03-02 17:04:07 +00001767** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001768** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001769** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001770** unchanged.)
drh832508b2002-03-02 17:04:07 +00001771**
1772** This routine is part of the flattening procedure. A subquery
1773** whose result set is defined by pEList appears as entry in the
1774** FROM clause of a SELECT such that the VDBE cursor assigned to that
1775** FORM clause entry is iTable. This routine make the necessary
1776** changes to pExpr so that it refers directly to the source table
1777** of the subquery rather the result set of the subquery.
1778*/
drh6a3ea0e2003-05-02 14:32:12 +00001779static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
danielk1977b3bce662005-01-29 08:32:43 +00001780static void substSelect(Select *, int, ExprList *); /* Forward Decl */
drh6a3ea0e2003-05-02 14:32:12 +00001781static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001782 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001783 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1784 if( pExpr->iColumn<0 ){
1785 pExpr->op = TK_NULL;
1786 }else{
1787 Expr *pNew;
1788 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1789 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1790 pNew = pEList->a[pExpr->iColumn].pExpr;
1791 assert( pNew!=0 );
1792 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001793 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001794 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001795 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001796 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001797 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001798 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001799 pExpr->iTable = pNew->iTable;
1800 pExpr->iColumn = pNew->iColumn;
1801 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001802 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1803 sqlite3TokenCopy(&pExpr->span, &pNew->span);
danielk1977a1cb1832005-02-12 08:59:55 +00001804 pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
1805 pExpr->flags = pNew->flags;
drh50350a12004-02-13 16:22:22 +00001806 }
drh832508b2002-03-02 17:04:07 +00001807 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001808 substExpr(pExpr->pLeft, iTable, pEList);
1809 substExpr(pExpr->pRight, iTable, pEList);
danielk1977b3bce662005-01-29 08:32:43 +00001810 substSelect(pExpr->pSelect, iTable, pEList);
drh6a3ea0e2003-05-02 14:32:12 +00001811 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001812 }
1813}
danielk1977b3bce662005-01-29 08:32:43 +00001814static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001815 int i;
1816 if( pList==0 ) return;
1817 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001818 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001819 }
1820}
danielk1977b3bce662005-01-29 08:32:43 +00001821static void substSelect(Select *p, int iTable, ExprList *pEList){
1822 if( !p ) return;
1823 substExprList(p->pEList, iTable, pEList);
1824 substExprList(p->pGroupBy, iTable, pEList);
1825 substExprList(p->pOrderBy, iTable, pEList);
1826 substExpr(p->pHaving, iTable, pEList);
1827 substExpr(p->pWhere, iTable, pEList);
1828}
drhb7f91642004-10-31 02:22:47 +00001829#endif /* !defined(SQLITE_OMIT_VIEW) */
drh832508b2002-03-02 17:04:07 +00001830
drhb7f91642004-10-31 02:22:47 +00001831#ifndef SQLITE_OMIT_VIEW
drh832508b2002-03-02 17:04:07 +00001832/*
drh1350b032002-02-27 19:00:20 +00001833** This routine attempts to flatten subqueries in order to speed
1834** execution. It returns 1 if it makes changes and 0 if no flattening
1835** occurs.
1836**
1837** To understand the concept of flattening, consider the following
1838** query:
1839**
1840** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1841**
1842** The default way of implementing this query is to execute the
1843** subquery first and store the results in a temporary table, then
1844** run the outer query on that temporary table. This requires two
1845** passes over the data. Furthermore, because the temporary table
1846** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001847** optimized.
drh1350b032002-02-27 19:00:20 +00001848**
drh832508b2002-03-02 17:04:07 +00001849** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001850** a single flat select, like this:
1851**
1852** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1853**
1854** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001855** but only has to scan the data once. And because indices might
1856** exist on the table t1, a complete scan of the data might be
1857** avoided.
drh1350b032002-02-27 19:00:20 +00001858**
drh832508b2002-03-02 17:04:07 +00001859** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001860**
drh832508b2002-03-02 17:04:07 +00001861** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001862**
drh832508b2002-03-02 17:04:07 +00001863** (2) The subquery is not an aggregate or the outer query is not a join.
1864**
drh8af4d3a2003-05-06 20:35:16 +00001865** (3) The subquery is not the right operand of a left outer join, or
1866** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001867**
1868** (4) The subquery is not DISTINCT or the outer query is not a join.
1869**
1870** (5) The subquery is not DISTINCT or the outer query does not use
1871** aggregates.
1872**
1873** (6) The subquery does not use aggregates or the outer query is not
1874** DISTINCT.
1875**
drh08192d52002-04-30 19:20:28 +00001876** (7) The subquery has a FROM clause.
1877**
drhdf199a22002-06-14 22:38:41 +00001878** (8) The subquery does not use LIMIT or the outer query is not a join.
1879**
1880** (9) The subquery does not use LIMIT or the outer query does not use
1881** aggregates.
1882**
1883** (10) The subquery does not use aggregates or the outer query does not
1884** use LIMIT.
1885**
drh174b6192002-12-03 02:22:52 +00001886** (11) The subquery and the outer query do not both have ORDER BY clauses.
1887**
drh3fc673e2003-06-16 00:40:34 +00001888** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1889** subquery has no WHERE clause. (added by ticket #350)
1890**
drh832508b2002-03-02 17:04:07 +00001891** In this routine, the "p" parameter is a pointer to the outer query.
1892** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1893** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1894**
drh665de472003-03-31 13:36:09 +00001895** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001896** If flattening is attempted this routine returns 1.
1897**
1898** All of the expression analysis must occur on both the outer query and
1899** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001900*/
drh8c74a8c2002-08-25 19:20:40 +00001901static int flattenSubquery(
1902 Parse *pParse, /* The parsing context */
1903 Select *p, /* The parent or outer SELECT statement */
1904 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1905 int isAgg, /* True if outer SELECT uses aggregate functions */
1906 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1907){
drh0bb28102002-05-08 11:54:14 +00001908 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001909 SrcList *pSrc; /* The FROM clause of the outer query */
1910 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001911 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001912 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh91bb0ee2004-09-01 03:06:34 +00001913 int i; /* Loop counter */
1914 Expr *pWhere; /* The WHERE clause */
1915 struct SrcList_item *pSubitem; /* The subquery */
drh1350b032002-02-27 19:00:20 +00001916
drh832508b2002-03-02 17:04:07 +00001917 /* Check to see if flattening is permitted. Return 0 if not.
1918 */
1919 if( p==0 ) return 0;
1920 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001921 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh91bb0ee2004-09-01 03:06:34 +00001922 pSubitem = &pSrc->a[iFrom];
1923 pSub = pSubitem->pSelect;
drh832508b2002-03-02 17:04:07 +00001924 assert( pSub!=0 );
1925 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001926 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001927 pSubSrc = pSub->pSrc;
1928 assert( pSubSrc );
danielk1977a2dc3b12005-02-05 12:48:48 +00001929 if( (pSub->pLimit && p->pLimit) || pSub->pOffset ||
1930 (pSub->pLimit && isAgg) ) return 0;
drhc31c2eb2003-05-02 16:04:17 +00001931 if( pSubSrc->nSrc==0 ) return 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001932 if( pSub->isDistinct && (pSrc->nSrc>1 || isAgg) ){
drhdf199a22002-06-14 22:38:41 +00001933 return 0;
1934 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001935 if( p->isDistinct && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001936 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001937
drh8af4d3a2003-05-06 20:35:16 +00001938 /* Restriction 3: If the subquery is a join, make sure the subquery is
1939 ** not used as the right operand of an outer join. Examples of why this
1940 ** is not allowed:
1941 **
1942 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1943 **
1944 ** If we flatten the above, we would get
1945 **
1946 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1947 **
1948 ** which is not at all the same thing.
1949 */
1950 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1951 return 0;
1952 }
1953
drh3fc673e2003-06-16 00:40:34 +00001954 /* Restriction 12: If the subquery is the right operand of a left outer
1955 ** join, make sure the subquery has no WHERE clause.
1956 ** An examples of why this is not allowed:
1957 **
1958 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1959 **
1960 ** If we flatten the above, we would get
1961 **
1962 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1963 **
1964 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1965 ** effectively converts the OUTER JOIN into an INNER JOIN.
1966 */
1967 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1968 && pSub->pWhere!=0 ){
1969 return 0;
1970 }
1971
drh0bb28102002-05-08 11:54:14 +00001972 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001973 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001974 */
drhc31c2eb2003-05-02 16:04:17 +00001975
1976 /* Move all of the FROM elements of the subquery into the
1977 ** the FROM clause of the outer query. Before doing this, remember
1978 ** the cursor number for the original outer query FROM element in
1979 ** iParent. The iParent cursor will never be used. Subsequent code
1980 ** will scan expressions looking for iParent references and replace
1981 ** those references with expressions that resolve to the subquery FROM
1982 ** elements we are now copying in.
1983 */
drh91bb0ee2004-09-01 03:06:34 +00001984 iParent = pSubitem->iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001985 {
1986 int nSubSrc = pSubSrc->nSrc;
drh91bb0ee2004-09-01 03:06:34 +00001987 int jointype = pSubitem->jointype;
drhc31c2eb2003-05-02 16:04:17 +00001988
drhed8a3bb2005-06-06 21:19:56 +00001989 sqlite3DeleteTable(0, pSubitem->pTab);
drh91bb0ee2004-09-01 03:06:34 +00001990 sqliteFree(pSubitem->zDatabase);
1991 sqliteFree(pSubitem->zName);
1992 sqliteFree(pSubitem->zAlias);
drhc31c2eb2003-05-02 16:04:17 +00001993 if( nSubSrc>1 ){
1994 int extra = nSubSrc - 1;
1995 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00001996 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00001997 }
1998 p->pSrc = pSrc;
1999 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2000 pSrc->a[i] = pSrc->a[i-extra];
2001 }
2002 }
2003 for(i=0; i<nSubSrc; i++){
2004 pSrc->a[i+iFrom] = pSubSrc->a[i];
2005 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2006 }
drh8af4d3a2003-05-06 20:35:16 +00002007 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00002008 }
2009
2010 /* Now begin substituting subquery result set expressions for
2011 ** references to the iParent in the outer query.
2012 **
2013 ** Example:
2014 **
2015 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2016 ** \ \_____________ subquery __________/ /
2017 ** \_____________________ outer query ______________________________/
2018 **
2019 ** We look at every expression in the outer query and every place we see
2020 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2021 */
drh6a3ea0e2003-05-02 14:32:12 +00002022 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00002023 pList = p->pEList;
2024 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00002025 Expr *pExpr;
2026 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
2027 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00002028 }
2029 }
drh1b2e0322002-03-03 02:49:51 +00002030 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00002031 substExprList(p->pGroupBy, iParent, pSub->pEList);
2032 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00002033 }
drh174b6192002-12-03 02:22:52 +00002034 if( pSub->pOrderBy ){
2035 assert( p->pOrderBy==0 );
2036 p->pOrderBy = pSub->pOrderBy;
2037 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00002038 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00002039 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00002040 }
drh832508b2002-03-02 17:04:07 +00002041 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002042 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00002043 }else{
2044 pWhere = 0;
2045 }
2046 if( subqueryIsAgg ){
2047 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00002048 p->pHaving = p->pWhere;
2049 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00002050 substExpr(p->pHaving, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002051 p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
drh1b2e0322002-03-03 02:49:51 +00002052 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00002053 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00002054 }else{
drh6a3ea0e2003-05-02 14:32:12 +00002055 substExpr(p->pWhere, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002056 p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
drh832508b2002-03-02 17:04:07 +00002057 }
drhc31c2eb2003-05-02 16:04:17 +00002058
2059 /* The flattened query is distinct if either the inner or the
2060 ** outer query is distinct.
2061 */
drh832508b2002-03-02 17:04:07 +00002062 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00002063
danielk1977a58fdfb2005-02-08 07:50:40 +00002064 /*
2065 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2066 */
danielk1977a2dc3b12005-02-05 12:48:48 +00002067 if( pSub->pLimit ){
2068 p->pLimit = pSub->pLimit;
2069 pSub->pLimit = 0;
drhdf199a22002-06-14 22:38:41 +00002070 }
drh8c74a8c2002-08-25 19:20:40 +00002071
drhc31c2eb2003-05-02 16:04:17 +00002072 /* Finially, delete what is left of the subquery and return
2073 ** success.
2074 */
danielk19774adee202004-05-08 08:23:19 +00002075 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00002076 return 1;
2077}
drhb7f91642004-10-31 02:22:47 +00002078#endif /* SQLITE_OMIT_VIEW */
drh1350b032002-02-27 19:00:20 +00002079
2080/*
drh9562b552002-02-19 15:00:07 +00002081** Analyze the SELECT statement passed in as an argument to see if it
2082** is a simple min() or max() query. If it is and this query can be
2083** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00002084** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00002085** simple min() or max() query, then return 0;
2086**
2087** A simply min() or max() query looks like this:
2088**
2089** SELECT min(a) FROM table;
2090** SELECT max(a) FROM table;
2091**
2092** The query may have only a single table in its FROM argument. There
2093** can be no GROUP BY or HAVING or WHERE clauses. The result set must
2094** be the min() or max() of a single column of the table. The column
2095** in the min() or max() function must be indexed.
2096**
danielk19774adee202004-05-08 08:23:19 +00002097** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00002098** See the header comment on that routine for additional information.
2099*/
2100static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2101 Expr *pExpr;
2102 int iCol;
2103 Table *pTab;
2104 Index *pIdx;
2105 int base;
2106 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00002107 int seekOp;
2108 int cont;
drh6e175292004-03-13 14:00:36 +00002109 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00002110 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00002111 SrcList *pSrc;
drh9562b552002-02-19 15:00:07 +00002112
2113 /* Check to see if this query is a simple min() or max() query. Return
2114 ** zero if it is not.
2115 */
2116 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00002117 pSrc = p->pSrc;
2118 if( pSrc->nSrc!=1 ) return 0;
2119 pEList = p->pEList;
2120 if( pEList->nExpr!=1 ) return 0;
2121 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002122 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002123 pList = pExpr->pList;
2124 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002125 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00002126 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002127 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00002128 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002129 seekOp = OP_Last;
2130 }else{
2131 return 0;
2132 }
drh6e175292004-03-13 14:00:36 +00002133 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002134 if( pExpr->op!=TK_COLUMN ) return 0;
2135 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002136 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002137
2138 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002139 ** Check to make sure we have an index and make pIdx point to the
2140 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2141 ** key column, no index is necessary so set pIdx to NULL. If no
2142 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002143 */
2144 if( iCol<0 ){
2145 pIdx = 0;
2146 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002147 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002148 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2149 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002150 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002151 }
2152 if( pIdx==0 ) return 0;
2153 }
2154
drhe5f50722003-07-19 00:44:14 +00002155 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002156 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002157 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002158 */
danielk19774adee202004-05-08 08:23:19 +00002159 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002160 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002161
drh0c37e632004-01-30 02:01:03 +00002162 /* If the output is destined for a temporary table, open that table.
2163 */
2164 if( eDest==SRT_TempTable ){
drh9170dd72005-07-08 17:13:46 +00002165 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002166 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002167 }
2168
drh17f71932002-02-21 12:01:27 +00002169 /* Generating code to find the min or the max. Basically all we have
2170 ** to do is find the first or the last entry in the chosen index. If
2171 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2172 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002173 */
danielk19774adee202004-05-08 08:23:19 +00002174 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00002175 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00002176 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00002177 if( pSrc->a[0].pSelect==0 ){
drhad6d9462004-09-19 02:15:24 +00002178 sqlite3OpenTableForReading(v, base, pTab);
drh6e175292004-03-13 14:00:36 +00002179 }
danielk19774adee202004-05-08 08:23:19 +00002180 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00002181 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002182 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002183 }else{
danielk19773719d7f2005-01-17 08:57:09 +00002184 /* Even though the cursor used to open the index here is closed
2185 ** as soon as a single value has been read from it, allocate it
2186 ** using (pParse->nTab++) to prevent the cursor id from being
2187 ** reused. This is important for statements of the form
2188 ** "INSERT INTO x SELECT max() FROM x".
2189 */
2190 int iIdx;
2191 iIdx = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +00002192 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002193 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
drhd3d39e92004-05-20 22:16:29 +00002194 (char*)&pIdx->keyInfo, P3_KEYINFO);
drh9eb516c2004-07-18 20:52:32 +00002195 if( seekOp==OP_Rewind ){
drhf0863fe2005-06-12 21:35:51 +00002196 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh1af3fdb2004-07-18 21:33:01 +00002197 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2198 seekOp = OP_MoveGt;
drh9eb516c2004-07-18 20:52:32 +00002199 }
danielk19773719d7f2005-01-17 08:57:09 +00002200 sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
drhf0863fe2005-06-12 21:35:51 +00002201 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002202 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002203 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002204 }
drh5cf8e8c2002-02-19 22:42:05 +00002205 eList.nExpr = 1;
2206 memset(&eListItem, 0, sizeof(eListItem));
2207 eList.a = &eListItem;
2208 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00002209 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00002210 sqlite3VdbeResolveLabel(v, cont);
2211 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002212
drh9562b552002-02-19 15:00:07 +00002213 return 1;
2214}
2215
2216/*
drh290c1942004-08-21 17:54:45 +00002217** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
2218** the number of errors seen.
2219**
2220** An ORDER BY or GROUP BY is a list of expressions. If any expression
2221** is an integer constant, then that expression is replaced by the
2222** corresponding entry in the result set.
2223*/
2224static int processOrderGroupBy(
danielk1977b3bce662005-01-29 08:32:43 +00002225 NameContext *pNC, /* Name context of the SELECT statement. */
drh290c1942004-08-21 17:54:45 +00002226 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
drh290c1942004-08-21 17:54:45 +00002227 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
2228){
2229 int i;
danielk1977b3bce662005-01-29 08:32:43 +00002230 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */
2231 Parse *pParse = pNC->pParse; /* The result set of the SELECT */
2232 assert( pEList );
2233
drh290c1942004-08-21 17:54:45 +00002234 if( pOrderBy==0 ) return 0;
2235 for(i=0; i<pOrderBy->nExpr; i++){
2236 int iCol;
2237 Expr *pE = pOrderBy->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +00002238 if( sqlite3ExprIsInteger(pE, &iCol) ){
2239 if( iCol>0 && iCol<=pEList->nExpr ){
2240 sqlite3ExprDelete(pE);
2241 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2242 }else{
drh290c1942004-08-21 17:54:45 +00002243 sqlite3ErrorMsg(pParse,
2244 "%s BY column number %d out of range - should be "
2245 "between 1 and %d", zType, iCol, pEList->nExpr);
2246 return 1;
2247 }
2248 }
danielk1977b3bce662005-01-29 08:32:43 +00002249 if( sqlite3ExprResolveNames(pNC, pE) ){
2250 return 1;
2251 }
2252 if( sqlite3ExprIsConstant(pE) ){
2253 sqlite3ErrorMsg(pParse,
2254 "%s BY terms must not be non-integer constants", zType);
2255 return 1;
2256 }
drh290c1942004-08-21 17:54:45 +00002257 }
2258 return 0;
2259}
2260
2261/*
danielk1977b3bce662005-01-29 08:32:43 +00002262** This routine resolves any names used in the result set of the
2263** supplied SELECT statement. If the SELECT statement being resolved
2264** is a sub-select, then pOuterNC is a pointer to the NameContext
2265** of the parent SELECT.
2266*/
2267int sqlite3SelectResolve(
2268 Parse *pParse, /* The parser context */
2269 Select *p, /* The SELECT statement being coded. */
2270 NameContext *pOuterNC /* The outer name context. May be NULL. */
2271){
2272 ExprList *pEList; /* Result set. */
2273 int i; /* For-loop variable used in multiple places */
2274 NameContext sNC; /* Local name-context */
2275
2276 /* If this routine has run before, return immediately. */
2277 if( p->isResolved ){
2278 assert( !pOuterNC );
2279 return SQLITE_OK;
2280 }
2281 p->isResolved = 1;
2282
2283 /* If there have already been errors, do nothing. */
2284 if( pParse->nErr>0 ){
2285 return SQLITE_ERROR;
2286 }
2287
2288 /* Prepare the select statement. This call will allocate all cursors
2289 ** required to handle the tables and subqueries in the FROM clause.
2290 */
2291 if( prepSelectStmt(pParse, p) ){
2292 return SQLITE_ERROR;
2293 }
2294
danielk1977a2dc3b12005-02-05 12:48:48 +00002295 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2296 ** are not allowed to refer to any names, so pass an empty NameContext.
2297 */
danielk1977b3bce662005-01-29 08:32:43 +00002298 sNC.pParse = pParse;
danielk1977b3bce662005-01-29 08:32:43 +00002299 sNC.hasAgg = 0;
2300 sNC.nErr = 0;
2301 sNC.nRef = 0;
2302 sNC.pEList = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00002303 sNC.allowAgg = 0;
2304 sNC.pSrcList = 0;
2305 sNC.pNext = 0;
2306 if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2307 sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2308 return SQLITE_ERROR;
2309 }
2310
2311 /* Set up the local name-context to pass to ExprResolveNames() to
2312 ** resolve the expression-list.
2313 */
2314 sNC.allowAgg = 1;
2315 sNC.pSrcList = p->pSrc;
2316 sNC.pNext = pOuterNC;
danielk1977b3bce662005-01-29 08:32:43 +00002317
2318 /* NameContext.nDepth stores the depth of recursion for this query. For
2319 ** an outer query (e.g. SELECT * FROM sqlite_master) this is 1. For
2320 ** a subquery it is 2. For a subquery of a subquery, 3. And so on.
2321 ** Parse.nMaxDepth is the maximum depth for any subquery resolved so
2322 ** far. This is used to determine the number of aggregate contexts
2323 ** required at runtime.
2324 */
2325 sNC.nDepth = (pOuterNC?pOuterNC->nDepth+1:1);
2326 if( sNC.nDepth>pParse->nMaxDepth ){
2327 pParse->nMaxDepth = sNC.nDepth;
2328 }
2329
2330 /* Resolve names in the result set. */
2331 pEList = p->pEList;
2332 if( !pEList ) return SQLITE_ERROR;
2333 for(i=0; i<pEList->nExpr; i++){
2334 Expr *pX = pEList->a[i].pExpr;
2335 if( sqlite3ExprResolveNames(&sNC, pX) ){
2336 return SQLITE_ERROR;
2337 }
2338 }
2339
2340 /* If there are no aggregate functions in the result-set, and no GROUP BY
2341 ** expression, do not allow aggregates in any of the other expressions.
2342 */
2343 assert( !p->isAgg );
2344 if( p->pGroupBy || sNC.hasAgg ){
2345 p->isAgg = 1;
2346 }else{
2347 sNC.allowAgg = 0;
2348 }
2349
2350 /* If a HAVING clause is present, then there must be a GROUP BY clause.
2351 */
2352 if( p->pHaving && !p->pGroupBy ){
2353 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2354 return SQLITE_ERROR;
2355 }
2356
2357 /* Add the expression list to the name-context before parsing the
2358 ** other expressions in the SELECT statement. This is so that
2359 ** expressions in the WHERE clause (etc.) can refer to expressions by
2360 ** aliases in the result set.
2361 **
2362 ** Minor point: If this is the case, then the expression will be
2363 ** re-evaluated for each reference to it.
2364 */
2365 sNC.pEList = p->pEList;
2366 if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2367 sqlite3ExprResolveNames(&sNC, p->pHaving) ||
2368 processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
2369 processOrderGroupBy(&sNC, p->pGroupBy, "GROUP")
2370 ){
2371 return SQLITE_ERROR;
2372 }
2373
2374 return SQLITE_OK;
2375}
2376
2377/*
2378** An instance of the following struct is used by sqlite3Select()
2379** to save aggregate related information from the Parse object
2380** at the start of each call and to restore it at the end. See
2381** saveAggregateInfo() and restoreAggregateInfo().
2382*/
2383struct AggregateInfo {
danielk1977b3bce662005-01-29 08:32:43 +00002384 int nAgg;
2385 AggExpr *aAgg;
2386};
2387typedef struct AggregateInfo AggregateInfo;
2388
2389/*
2390** Copy aggregate related information from the Parse structure
2391** into the AggregateInfo structure. Zero the aggregate related
2392** values in the Parse struct.
2393*/
2394static void saveAggregateInfo(Parse *pParse, AggregateInfo *pInfo){
2395 pInfo->aAgg = pParse->aAgg;
2396 pInfo->nAgg = pParse->nAgg;
danielk1977b3bce662005-01-29 08:32:43 +00002397 pParse->aAgg = 0;
2398 pParse->nAgg = 0;
danielk1977b3bce662005-01-29 08:32:43 +00002399}
2400
2401/*
2402** Copy aggregate related information from the AggregateInfo struct
2403** back into the Parse structure. The aggregate related information
2404** currently stored in the Parse structure is deleted.
2405*/
2406static void restoreAggregateInfo(Parse *pParse, AggregateInfo *pInfo){
2407 sqliteFree(pParse->aAgg);
2408 pParse->aAgg = pInfo->aAgg;
2409 pParse->nAgg = pInfo->nAgg;
danielk1977b3bce662005-01-29 08:32:43 +00002410}
2411
2412/*
drh9bb61fe2000-06-05 16:01:39 +00002413** Generate code for the given SELECT statement.
2414**
drhfef52082000-06-06 01:50:43 +00002415** The results are distributed in various ways depending on the
2416** value of eDest and iParm.
2417**
2418** eDest Value Result
2419** ------------ -------------------------------------------
2420** SRT_Callback Invoke the callback for each row of the result.
2421**
2422** SRT_Mem Store first result in memory cell iParm
2423**
danielk1977e014a832004-05-17 10:48:57 +00002424** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002425**
drh82c3d632000-06-06 21:56:07 +00002426** SRT_Union Store results as a key in a temporary table iParm
2427**
jplyon4b11c6d2004-01-19 04:57:53 +00002428** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002429**
2430** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002431**
drhe78e8282003-01-19 03:59:45 +00002432** The table above is incomplete. Additional eDist value have be added
2433** since this comment was written. See the selectInnerLoop() function for
2434** a complete listing of the allowed values of eDest and their meanings.
2435**
drh9bb61fe2000-06-05 16:01:39 +00002436** This routine returns the number of errors. If any errors are
2437** encountered, then an appropriate error message is left in
2438** pParse->zErrMsg.
2439**
2440** This routine does NOT free the Select structure passed in. The
2441** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002442**
2443** The pParent, parentTab, and *pParentAgg fields are filled in if this
2444** SELECT is a subquery. This routine may try to combine this SELECT
2445** with its parent to form a single flat query. In so doing, it might
2446** change the parent query from a non-aggregate to an aggregate query.
2447** For that reason, the pParentAgg flag is passed as a pointer, so it
2448** can be changed.
drhe78e8282003-01-19 03:59:45 +00002449**
2450** Example 1: The meaning of the pParent parameter.
2451**
2452** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2453** \ \_______ subquery _______/ /
2454** \ /
2455** \____________________ outer query ___________________/
2456**
2457** This routine is called for the outer query first. For that call,
2458** pParent will be NULL. During the processing of the outer query, this
2459** routine is called recursively to handle the subquery. For the recursive
2460** call, pParent will point to the outer query. Because the subquery is
2461** the second element in a three-way join, the parentTab parameter will
2462** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002463*/
danielk19774adee202004-05-08 08:23:19 +00002464int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002465 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002466 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002467 int eDest, /* How to dispose of the results */
2468 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002469 Select *pParent, /* Another SELECT for which this is a sub-query */
2470 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002471 int *pParentAgg, /* True if pParent uses aggregate functions */
danielk1977b3bce662005-01-29 08:32:43 +00002472 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002473){
drhd8bc7082000-06-07 23:51:50 +00002474 int i;
drhcce7d172000-05-31 15:34:51 +00002475 WhereInfo *pWInfo;
2476 Vdbe *v;
danielk1977b3bce662005-01-29 08:32:43 +00002477 int isAgg; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002478 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002479 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002480 Expr *pWhere; /* The WHERE clause. May be NULL */
2481 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002482 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2483 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002484 int isDistinct; /* True if the DISTINCT keyword is present */
2485 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002486 int rc = 1; /* Value to return from this function */
danielk1977b3bce662005-01-29 08:32:43 +00002487 AggregateInfo sAggInfo;
drh9bb61fe2000-06-05 16:01:39 +00002488
danielk19776f8a5032004-05-10 10:34:51 +00002489 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002490 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002491
drhb7f91642004-10-31 02:22:47 +00002492#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +00002493 /* If there is are a sequence of queries, do the earlier ones first.
2494 */
2495 if( p->pPrior ){
drh0342b1f2005-09-01 03:07:44 +00002496 if( p->pRightmost==0 ){
2497 Select *pLoop;
2498 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
2499 pLoop->pRightmost = p;
2500 }
2501 }
danielk197784ac9d02004-05-18 09:58:06 +00002502 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002503 }
drhb7f91642004-10-31 02:22:47 +00002504#endif
drh82c3d632000-06-06 21:56:07 +00002505
danielk1977b3bce662005-01-29 08:32:43 +00002506 saveAggregateInfo(pParse, &sAggInfo);
2507 pOrderBy = p->pOrderBy;
2508 if( eDest==SRT_Union || eDest==SRT_Except || eDest==SRT_Discard ){
2509 p->pOrderBy = 0;
2510 }
2511 if( sqlite3SelectResolve(pParse, p, 0) ){
2512 goto select_end;
2513 }
2514 p->pOrderBy = pOrderBy;
2515
drh82c3d632000-06-06 21:56:07 +00002516 /* Make local copies of the parameters for this query.
2517 */
drh9bb61fe2000-06-05 16:01:39 +00002518 pTabList = p->pSrc;
2519 pWhere = p->pWhere;
drh22827922000-06-06 17:27:05 +00002520 pGroupBy = p->pGroupBy;
2521 pHaving = p->pHaving;
danielk1977b3bce662005-01-29 08:32:43 +00002522 isAgg = p->isAgg;
drh19a775c2000-06-05 18:54:46 +00002523 isDistinct = p->isDistinct;
danielk1977b3bce662005-01-29 08:32:43 +00002524 pEList = p->pEList;
2525 if( pEList==0 ) goto select_end;
drh9bb61fe2000-06-05 16:01:39 +00002526
2527 /*
2528 ** Do not even attempt to generate any code if we have already seen
2529 ** errors before this routine starts.
2530 */
drh1d83f052002-02-17 00:30:36 +00002531 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002532
drh22827922000-06-06 17:27:05 +00002533 /* If writing to memory or generating a set
2534 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002535 */
drh51522cd2005-01-20 13:36:19 +00002536 assert( eDest!=SRT_Exists || pEList->nExpr==1 );
danielk197793758c82005-01-21 08:13:14 +00002537#ifndef SQLITE_OMIT_SUBQUERY
drhfef52082000-06-06 01:50:43 +00002538 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002539 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002540 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002541 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002542 }
danielk197793758c82005-01-21 08:13:14 +00002543#endif
drh19a775c2000-06-05 18:54:46 +00002544
drhc926afb2002-06-20 03:38:26 +00002545 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002546 */
drhc926afb2002-06-20 03:38:26 +00002547 switch( eDest ){
2548 case SRT_Union:
2549 case SRT_Except:
2550 case SRT_Discard:
2551 pOrderBy = 0;
2552 break;
2553 default:
2554 break;
drh22827922000-06-06 17:27:05 +00002555 }
2556
drhd820cb12002-02-18 03:21:45 +00002557 /* Begin generating code.
2558 */
danielk19774adee202004-05-08 08:23:19 +00002559 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002560 if( v==0 ) goto select_end;
2561
drhe78e8282003-01-19 03:59:45 +00002562 /* Identify column names if we will be using them in a callback. This
2563 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002564 */
2565 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002566 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002567 }
2568
drhd820cb12002-02-18 03:21:45 +00002569 /* Generate code for all sub-queries in the FROM clause
2570 */
drh51522cd2005-01-20 13:36:19 +00002571#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
drhad3cab52002-05-24 02:04:32 +00002572 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002573 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002574 int needRestoreContext;
2575
drha76b5df2002-02-23 02:32:10 +00002576 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002577 if( pTabList->a[i].zName!=0 ){
2578 zSavedAuthContext = pParse->zAuthContext;
2579 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002580 needRestoreContext = 1;
2581 }else{
2582 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002583 }
danielk19774adee202004-05-08 08:23:19 +00002584 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
danielk1977b3bce662005-01-29 08:32:43 +00002585 pTabList->a[i].iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002586 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002587 pParse->zAuthContext = zSavedAuthContext;
2588 }
drh1b2e0322002-03-03 02:49:51 +00002589 pTabList = p->pSrc;
2590 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002591 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002592 pOrderBy = p->pOrderBy;
2593 }
drh1b2e0322002-03-03 02:49:51 +00002594 pGroupBy = p->pGroupBy;
2595 pHaving = p->pHaving;
2596 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002597 }
drh51522cd2005-01-20 13:36:19 +00002598#endif
drhd820cb12002-02-18 03:21:45 +00002599
drh6e175292004-03-13 14:00:36 +00002600 /* Check for the special case of a min() or max() function by itself
2601 ** in the result set.
2602 */
2603 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2604 rc = 0;
2605 goto select_end;
2606 }
2607
drh832508b2002-03-02 17:04:07 +00002608 /* Check to see if this is a subquery that can be "flattened" into its parent.
2609 ** If flattening is a possiblity, do so and return immediately.
2610 */
drhb7f91642004-10-31 02:22:47 +00002611#ifndef SQLITE_OMIT_VIEW
drh1b2e0322002-03-03 02:49:51 +00002612 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002613 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002614 if( isAgg ) *pParentAgg = 1;
danielk1977b3bce662005-01-29 08:32:43 +00002615 goto select_end;
drh832508b2002-03-02 17:04:07 +00002616 }
drhb7f91642004-10-31 02:22:47 +00002617#endif
drh832508b2002-03-02 17:04:07 +00002618
danielk19777cedc8d2004-06-10 10:50:08 +00002619 /* If there is an ORDER BY clause, resolve any collation sequences
2620 ** names that have been explicitly specified.
2621 */
2622 if( pOrderBy ){
drh5d9a4af2005-08-30 00:54:01 +00002623 struct ExprList_item *pTerm;
drh0342b1f2005-09-01 03:07:44 +00002624 KeyInfo *pKeyInfo;
2625 int addr;
drh5d9a4af2005-08-30 00:54:01 +00002626 for(i=0, pTerm=pOrderBy->a; i<pOrderBy->nExpr; i++, pTerm++){
2627 if( pTerm->zName ){
2628 pTerm->pExpr->pColl = sqlite3LocateCollSeq(pParse, pTerm->zName, -1);
danielk19777cedc8d2004-06-10 10:50:08 +00002629 }
2630 }
2631 if( pParse->nErr ){
2632 goto select_end;
2633 }
drh0342b1f2005-09-01 03:07:44 +00002634 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
2635 pOrderBy->iTab = pParse->nTab++;
2636 addr = sqlite3VdbeOp3(v, OP_OpenVirtual, pOrderBy->iTab, pOrderBy->nExpr+1,
2637 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2638 p->addrOpenVirt[2] = addr;
danielk19777cedc8d2004-06-10 10:50:08 +00002639 }
2640
drh7b58dae2003-07-20 01:16:46 +00002641 /* Set the limiter.
2642 */
2643 computeLimitRegisters(pParse, p);
2644
drh2d0794e2002-03-03 03:03:52 +00002645 /* If the output is destined for a temporary table, open that table.
2646 */
2647 if( eDest==SRT_TempTable ){
drh0342b1f2005-09-01 03:07:44 +00002648 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002649 }
2650
drh22827922000-06-06 17:27:05 +00002651 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002652 */
drhbb999ef2003-02-02 12:41:25 +00002653 if( isAgg || pGroupBy ){
danielk1977a58fdfb2005-02-08 07:50:40 +00002654 NameContext sNC;
2655 memset(&sNC, 0, sizeof(sNC));
2656 sNC.pParse = pParse;
2657 sNC.pSrcList = pTabList;
2658
drh0bce8352002-02-28 00:41:10 +00002659 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002660 isAgg = 1;
drh5d9a4af2005-08-30 00:54:01 +00002661 if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
2662 goto select_end;
drh22827922000-06-06 17:27:05 +00002663 }
drh5d9a4af2005-08-30 00:54:01 +00002664 if( sqlite3ExprAnalyzeAggList(&sNC, pGroupBy) ){
2665 goto select_end;
drh22827922000-06-06 17:27:05 +00002666 }
danielk1977a58fdfb2005-02-08 07:50:40 +00002667 if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002668 goto select_end;
drh22827922000-06-06 17:27:05 +00002669 }
drh5d9a4af2005-08-30 00:54:01 +00002670 if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
2671 goto select_end;
drh191b6902000-06-08 11:13:01 +00002672 }
drhefb72512000-05-31 20:00:52 +00002673 }
2674
drh22827922000-06-06 17:27:05 +00002675 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002676 */
2677 if( isAgg ){
danielk1977e159fdf2004-06-21 10:45:06 +00002678 int addr = sqlite3VdbeAddOp(v, OP_AggReset, (pGroupBy?0:1), pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002679 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002680 FuncDef *pFunc;
2681 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
danielk19775c2d9152005-05-26 14:41:47 +00002682 int nExpr = 0;
2683#ifdef SQLITE_SSE
2684 Expr *pAggExpr = pParse->aAgg[i].pExpr;
2685 if( pAggExpr && pAggExpr->pList ){
2686 nExpr = pAggExpr->pList->nExpr;
2687 }
2688#endif
2689 sqlite3VdbeOp3(v, OP_AggInit, nExpr, i, (char*)pFunc, P3_FUNCDEF);
drhe5095352002-02-24 03:25:14 +00002690 }
2691 }
danielk1977e159fdf2004-06-21 10:45:06 +00002692 if( pGroupBy ){
drhdece1a82005-08-31 18:20:00 +00002693 KeyInfo *pKey = keyInfoFromExprList(pParse, pGroupBy);
danielk1977ce2663c2004-06-11 13:19:21 +00002694 if( 0==pKey ){
2695 goto select_end;
2696 }
danielk1977ce2663c2004-06-11 13:19:21 +00002697 sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF);
drh1bee3d72001-10-15 00:44:35 +00002698 }
drhcce7d172000-05-31 15:34:51 +00002699 }
2700
drh51522cd2005-01-20 13:36:19 +00002701 /* Initialize the memory cell to NULL for SRT_Mem or 0 for SRT_Exists
drh19a775c2000-06-05 18:54:46 +00002702 */
drh51522cd2005-01-20 13:36:19 +00002703 if( eDest==SRT_Mem || eDest==SRT_Exists ){
drhf0863fe2005-06-12 21:35:51 +00002704 sqlite3VdbeAddOp(v, eDest==SRT_Mem ? OP_Null : OP_Integer, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00002705 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002706 }
2707
drhdece1a82005-08-31 18:20:00 +00002708 /* Open a virtual index to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002709 */
drh19a775c2000-06-05 18:54:46 +00002710 if( isDistinct ){
drh0342b1f2005-09-01 03:07:44 +00002711 KeyInfo *pKeyInfo;
drh832508b2002-03-02 17:04:07 +00002712 distinct = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00002713 pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
2714 sqlite3VdbeOp3(v, OP_OpenVirtual, distinct, 0,
2715 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drh832508b2002-03-02 17:04:07 +00002716 }else{
2717 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002718 }
drh832508b2002-03-02 17:04:07 +00002719
2720 /* Begin the database scan
2721 */
drhe6f85e72004-12-25 01:03:13 +00002722 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,
drhf8db1bc2005-04-22 02:38:37 +00002723 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002724 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002725
drh22827922000-06-06 17:27:05 +00002726 /* Use the standard inner loop if we are not dealing with
2727 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002728 */
drhda9d6c42000-05-31 18:20:14 +00002729 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002730 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002731 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002732 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002733 }
drhcce7d172000-05-31 15:34:51 +00002734 }
drhefb72512000-05-31 20:00:52 +00002735
drhe3184742002-06-19 14:27:05 +00002736 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002737 ** processing.
drhefb72512000-05-31 20:00:52 +00002738 */
drh22827922000-06-06 17:27:05 +00002739 else{
drh268380c2004-02-25 13:47:31 +00002740 AggExpr *pAgg;
danielk1977a58fdfb2005-02-08 07:50:40 +00002741 int lbl1 = 0;
2742 pParse->fillAgg = 1;
drh22827922000-06-06 17:27:05 +00002743 if( pGroupBy ){
drhc182d162005-08-14 20:47:16 +00002744 sqlite3ExprCodeExprList(pParse, pGroupBy);
danielk1977ededfd52004-06-17 07:53:01 +00002745 /* No affinity string is attached to the following OP_MakeRecord
drhd3d39e92004-05-20 22:16:29 +00002746 ** because we do not need to do any coercion of datatypes. */
danielk1977ededfd52004-06-17 07:53:01 +00002747 sqlite3VdbeAddOp(v, OP_MakeRecord, pGroupBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +00002748 lbl1 = sqlite3VdbeMakeLabel(v);
2749 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
danielk1977a58fdfb2005-02-08 07:50:40 +00002750 }
2751 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2752 if( pAgg->isAgg ) continue;
2753 sqlite3ExprCode(pParse, pAgg->pExpr);
2754 sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
2755 }
2756 pParse->fillAgg = 0;
2757 if( lbl1<0 ){
danielk19774adee202004-05-08 08:23:19 +00002758 sqlite3VdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002759 }
drh268380c2004-02-25 13:47:31 +00002760 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002761 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002762 int nExpr;
2763 FuncDef *pDef;
2764 if( !pAgg->isAgg ) continue;
2765 assert( pAgg->pFunc!=0 );
2766 assert( pAgg->pFunc->xStep!=0 );
2767 pDef = pAgg->pFunc;
2768 pE = pAgg->pExpr;
2769 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002770 assert( pE->op==TK_AGG_FUNCTION );
drhf9b596e2004-05-26 16:54:42 +00002771 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
danielk19774adee202004-05-08 08:23:19 +00002772 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
danielk1977dc1bdc42004-06-11 10:51:27 +00002773 if( pDef->needCollSeq ){
2774 CollSeq *pColl = 0;
2775 int j;
2776 for(j=0; !pColl && j<nExpr; j++){
2777 pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr);
2778 }
2779 if( !pColl ) pColl = pParse->db->pDfltColl;
2780 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2781 }
danielk19771f55c052005-05-19 08:42:59 +00002782 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_FUNCDEF);
drh22827922000-06-06 17:27:05 +00002783 }
drhcce7d172000-05-31 15:34:51 +00002784 }
2785
2786 /* End the database scan loop.
2787 */
danielk19774adee202004-05-08 08:23:19 +00002788 sqlite3WhereEnd(pWInfo);
drhcce7d172000-05-31 15:34:51 +00002789
drh22827922000-06-06 17:27:05 +00002790 /* If we are processing aggregates, we need to set up a second loop
2791 ** over all of the aggregate values and process them.
2792 */
2793 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002794 int endagg = sqlite3VdbeMakeLabel(v);
drh22827922000-06-06 17:27:05 +00002795 int startagg;
danielk19774adee202004-05-08 08:23:19 +00002796 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002797 if( pHaving ){
danielk19774adee202004-05-08 08:23:19 +00002798 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002799 }
drhdf199a22002-06-14 22:38:41 +00002800 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002801 iParm, startagg, endagg, aff) ){
drh1d83f052002-02-17 00:30:36 +00002802 goto select_end;
drh22827922000-06-06 17:27:05 +00002803 }
danielk19774adee202004-05-08 08:23:19 +00002804 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2805 sqlite3VdbeResolveLabel(v, endagg);
2806 sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002807 }
2808
drhcce7d172000-05-31 15:34:51 +00002809 /* If there is an ORDER BY clause, then we need to sort the results
2810 ** and send them to the callback one by one.
2811 */
2812 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00002813 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002814 }
drh6a535342001-10-19 16:44:56 +00002815
danielk197793758c82005-01-21 08:13:14 +00002816#ifndef SQLITE_OMIT_SUBQUERY
drhf620b4e2004-02-09 14:37:50 +00002817 /* If this was a subquery, we have now converted the subquery into a
2818 ** temporary table. So delete the subquery structure from the parent
2819 ** to prevent this subquery from being evaluated again and to force the
2820 ** the use of the temporary table.
2821 */
2822 if( pParent ){
2823 assert( pParent->pSrc->nSrc>parentTab );
2824 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00002825 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00002826 pParent->pSrc->a[parentTab].pSelect = 0;
2827 }
danielk197793758c82005-01-21 08:13:14 +00002828#endif
drhf620b4e2004-02-09 14:37:50 +00002829
drh1d83f052002-02-17 00:30:36 +00002830 /* The SELECT was successfully coded. Set the return code to 0
2831 ** to indicate no errors.
2832 */
2833 rc = 0;
2834
2835 /* Control jumps to here if an error is encountered above, or upon
2836 ** successful coding of the SELECT.
2837 */
2838select_end:
danielk1977b3bce662005-01-29 08:32:43 +00002839 restoreAggregateInfo(pParse, &sAggInfo);
drh1d83f052002-02-17 00:30:36 +00002840 return rc;
drhcce7d172000-05-31 15:34:51 +00002841}