blob: da7c2ab4c060f1af69d546382d1139c2dca24ba7 [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**
drh3dec2232005-09-10 15:28:09 +000015** $Id: select.c,v 1.267 2005/09/10 15:28:09 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
drh3dec2232005-09-10 15:28:09 +000076** JT_CROSS
drh01f3f252002-05-24 16:14:15 +000077** JT_OUTER
78** JT_NATURAL
79** JT_LEFT
80** JT_RIGHT
81**
82** A full outer join is the combination of JT_LEFT and JT_RIGHT.
83**
84** If an illegal or unsupported join type is seen, then still return
85** a join type, but put an error in the pParse structure.
86*/
danielk19774adee202004-05-08 08:23:19 +000087int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
drh01f3f252002-05-24 16:14:15 +000088 int jointype = 0;
89 Token *apAll[3];
90 Token *p;
drh57196282004-10-06 15:41:16 +000091 static const struct {
drhc182d162005-08-14 20:47:16 +000092 const char zKeyword[8];
drh290c1942004-08-21 17:54:45 +000093 u8 nChar;
94 u8 code;
drh01f3f252002-05-24 16:14:15 +000095 } keywords[] = {
96 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000097 { "left", 4, JT_LEFT|JT_OUTER },
98 { "right", 5, JT_RIGHT|JT_OUTER },
99 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +0000100 { "outer", 5, JT_OUTER },
101 { "inner", 5, JT_INNER },
drh3dec2232005-09-10 15:28:09 +0000102 { "cross", 5, JT_INNER|JT_CROSS },
drh01f3f252002-05-24 16:14:15 +0000103 };
104 int i, j;
105 apAll[0] = pA;
106 apAll[1] = pB;
107 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +0000108 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +0000109 p = apAll[i];
110 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
111 if( p->n==keywords[j].nChar
danielk19774adee202004-05-08 08:23:19 +0000112 && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
drh01f3f252002-05-24 16:14:15 +0000113 jointype |= keywords[j].code;
114 break;
115 }
116 }
117 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
118 jointype |= JT_ERROR;
119 break;
120 }
121 }
drhad2d8302002-05-24 20:31:36 +0000122 if(
123 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000124 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000125 ){
drhae29ffb2004-09-25 14:39:18 +0000126 const char *zSp1 = " ";
127 const char *zSp2 = " ";
128 if( pB==0 ){ zSp1++; }
129 if( pC==0 ){ zSp2++; }
130 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
131 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
drh01f3f252002-05-24 16:14:15 +0000132 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000133 }else if( jointype & JT_RIGHT ){
danielk19774adee202004-05-08 08:23:19 +0000134 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000135 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000136 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000137 }
138 return jointype;
139}
140
141/*
drhad2d8302002-05-24 20:31:36 +0000142** Return the index of a column in a table. Return -1 if the column
143** is not contained in the table.
144*/
145static int columnIndex(Table *pTab, const char *zCol){
146 int i;
147 for(i=0; i<pTab->nCol; i++){
danielk19774adee202004-05-08 08:23:19 +0000148 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
drhad2d8302002-05-24 20:31:36 +0000149 }
150 return -1;
151}
152
153/*
drh91bb0ee2004-09-01 03:06:34 +0000154** Set the value of a token to a '\000'-terminated string.
155*/
156static void setToken(Token *p, const char *z){
157 p->z = z;
158 p->n = strlen(z);
159 p->dyn = 0;
160}
161
drhc182d162005-08-14 20:47:16 +0000162/*
163** Create an expression node for an identifier with the name of zName
164*/
165static Expr *createIdExpr(const char *zName){
166 Token dummy;
167 setToken(&dummy, zName);
168 return sqlite3Expr(TK_ID, 0, 0, &dummy);
169}
170
drh91bb0ee2004-09-01 03:06:34 +0000171
172/*
drhad2d8302002-05-24 20:31:36 +0000173** Add a term to the WHERE expression in *ppExpr that requires the
174** zCol column to be equal in the two tables pTab1 and pTab2.
175*/
176static void addWhereTerm(
177 const char *zCol, /* Name of the column */
178 const Table *pTab1, /* First table */
drh030530d2005-01-18 17:40:04 +0000179 const char *zAlias1, /* Alias for first table. May be NULL */
drhad2d8302002-05-24 20:31:36 +0000180 const Table *pTab2, /* Second table */
drh030530d2005-01-18 17:40:04 +0000181 const char *zAlias2, /* Alias for second table. May be NULL */
drhad2d8302002-05-24 20:31:36 +0000182 Expr **ppExpr /* Add the equality term to this expression */
183){
drhad2d8302002-05-24 20:31:36 +0000184 Expr *pE1a, *pE1b, *pE1c;
185 Expr *pE2a, *pE2b, *pE2c;
186 Expr *pE;
187
drhc182d162005-08-14 20:47:16 +0000188 pE1a = createIdExpr(zCol);
189 pE2a = createIdExpr(zCol);
drh030530d2005-01-18 17:40:04 +0000190 if( zAlias1==0 ){
191 zAlias1 = pTab1->zName;
192 }
drhc182d162005-08-14 20:47:16 +0000193 pE1b = createIdExpr(zAlias1);
drh030530d2005-01-18 17:40:04 +0000194 if( zAlias2==0 ){
195 zAlias2 = pTab2->zName;
196 }
drhc182d162005-08-14 20:47:16 +0000197 pE2b = createIdExpr(zAlias2);
danielk19774adee202004-05-08 08:23:19 +0000198 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
199 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
200 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000201 ExprSetProperty(pE, EP_FromJoin);
drh91bb0ee2004-09-01 03:06:34 +0000202 *ppExpr = sqlite3ExprAnd(*ppExpr, pE);
drhad2d8302002-05-24 20:31:36 +0000203}
204
205/*
drh1f162302002-10-27 19:35:33 +0000206** Set the EP_FromJoin property on all terms of the given expression.
drh1cc093c2002-06-24 22:01:57 +0000207**
drhe78e8282003-01-19 03:59:45 +0000208** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000209** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000210** join restriction specified in the ON or USING clause and not a part
211** of the more general WHERE clause. These terms are moved over to the
212** WHERE clause during join processing but we need to remember that they
213** originated in the ON or USING clause.
drh1cc093c2002-06-24 22:01:57 +0000214*/
215static void setJoinExpr(Expr *p){
216 while( p ){
drh1f162302002-10-27 19:35:33 +0000217 ExprSetProperty(p, EP_FromJoin);
drh1cc093c2002-06-24 22:01:57 +0000218 setJoinExpr(p->pLeft);
219 p = p->pRight;
220 }
221}
222
223/*
drhad2d8302002-05-24 20:31:36 +0000224** This routine processes the join information for a SELECT statement.
225** ON and USING clauses are converted into extra terms of the WHERE clause.
226** NATURAL joins also create extra WHERE clause terms.
227**
drh91bb0ee2004-09-01 03:06:34 +0000228** The terms of a FROM clause are contained in the Select.pSrc structure.
229** The left most table is the first entry in Select.pSrc. The right-most
230** table is the last entry. The join operator is held in the entry to
231** the left. Thus entry 0 contains the join operator for the join between
232** entries 0 and 1. Any ON or USING clauses associated with the join are
233** also attached to the left entry.
234**
drhad2d8302002-05-24 20:31:36 +0000235** This routine returns the number of errors encountered.
236*/
237static int sqliteProcessJoin(Parse *pParse, Select *p){
drh91bb0ee2004-09-01 03:06:34 +0000238 SrcList *pSrc; /* All tables in the FROM clause */
239 int i, j; /* Loop counters */
240 struct SrcList_item *pLeft; /* Left table being joined */
241 struct SrcList_item *pRight; /* Right table being joined */
drhad2d8302002-05-24 20:31:36 +0000242
drh91bb0ee2004-09-01 03:06:34 +0000243 pSrc = p->pSrc;
244 pLeft = &pSrc->a[0];
245 pRight = &pLeft[1];
246 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
247 Table *pLeftTab = pLeft->pTab;
248 Table *pRightTab = pRight->pTab;
249
250 if( pLeftTab==0 || pRightTab==0 ) continue;
drhad2d8302002-05-24 20:31:36 +0000251
252 /* When the NATURAL keyword is present, add WHERE clause terms for
253 ** every column that the two tables have in common.
254 */
drh91bb0ee2004-09-01 03:06:34 +0000255 if( pLeft->jointype & JT_NATURAL ){
256 if( pLeft->pOn || pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000257 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000258 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000259 return 1;
260 }
drh91bb0ee2004-09-01 03:06:34 +0000261 for(j=0; j<pLeftTab->nCol; j++){
262 char *zName = pLeftTab->aCol[j].zName;
263 if( columnIndex(pRightTab, zName)>=0 ){
drh030530d2005-01-18 17:40:04 +0000264 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
265 pRightTab, pRight->zAlias, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000266 }
267 }
268 }
269
270 /* Disallow both ON and USING clauses in the same join
271 */
drh91bb0ee2004-09-01 03:06:34 +0000272 if( pLeft->pOn && pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000273 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
drhda93d232003-03-31 02:12:46 +0000274 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000275 return 1;
276 }
277
278 /* Add the ON clause to the end of the WHERE clause, connected by
drh91bb0ee2004-09-01 03:06:34 +0000279 ** an AND operator.
drhad2d8302002-05-24 20:31:36 +0000280 */
drh91bb0ee2004-09-01 03:06:34 +0000281 if( pLeft->pOn ){
282 setJoinExpr(pLeft->pOn);
283 p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn);
284 pLeft->pOn = 0;
drhad2d8302002-05-24 20:31:36 +0000285 }
286
287 /* Create extra terms on the WHERE clause for each column named
288 ** in the USING clause. Example: If the two tables to be joined are
289 ** A and B and the USING clause names X, Y, and Z, then add this
290 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
291 ** Report an error if any column mentioned in the USING clause is
292 ** not contained in both tables to be joined.
293 */
drh91bb0ee2004-09-01 03:06:34 +0000294 if( pLeft->pUsing ){
295 IdList *pList = pLeft->pUsing;
drhad2d8302002-05-24 20:31:36 +0000296 for(j=0; j<pList->nId; j++){
drh91bb0ee2004-09-01 03:06:34 +0000297 char *zName = pList->a[j].zName;
298 if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
danielk19774adee202004-05-08 08:23:19 +0000299 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
drh91bb0ee2004-09-01 03:06:34 +0000300 "not present in both tables", zName);
drhad2d8302002-05-24 20:31:36 +0000301 return 1;
302 }
drh030530d2005-01-18 17:40:04 +0000303 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
304 pRightTab, pRight->zAlias, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000305 }
306 }
307 }
308 return 0;
309}
310
311/*
drh9bb61fe2000-06-05 16:01:39 +0000312** Delete the given Select structure and all of its substructures.
313*/
danielk19774adee202004-05-08 08:23:19 +0000314void sqlite3SelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000315 if( p==0 ) return;
danielk19774adee202004-05-08 08:23:19 +0000316 sqlite3ExprListDelete(p->pEList);
317 sqlite3SrcListDelete(p->pSrc);
318 sqlite3ExprDelete(p->pWhere);
319 sqlite3ExprListDelete(p->pGroupBy);
320 sqlite3ExprDelete(p->pHaving);
321 sqlite3ExprListDelete(p->pOrderBy);
322 sqlite3SelectDelete(p->pPrior);
danielk1977a2dc3b12005-02-05 12:48:48 +0000323 sqlite3ExprDelete(p->pLimit);
324 sqlite3ExprDelete(p->pOffset);
drh9bb61fe2000-06-05 16:01:39 +0000325 sqliteFree(p);
326}
327
328/*
drhc926afb2002-06-20 03:38:26 +0000329** Insert code into "v" that will push the record on the top of the
330** stack into the sorter.
331*/
332static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
drhc182d162005-08-14 20:47:16 +0000333 sqlite3ExprCodeExprList(pParse, pOrderBy);
drh9d2985c2005-09-08 01:58:42 +0000334 sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0);
drh4db38a72005-09-01 12:16:28 +0000335 sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0);
336 sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0);
drh9d2985c2005-09-08 01:58:42 +0000337 sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0);
drhc926afb2002-06-20 03:38:26 +0000338}
339
340/*
drhea48eb22004-07-19 23:16:38 +0000341** Add code to implement the OFFSET and LIMIT
342*/
343static void codeLimiter(
drhbab39e12004-07-19 23:38:11 +0000344 Vdbe *v, /* Generate code into this VM */
drhea48eb22004-07-19 23:16:38 +0000345 Select *p, /* The SELECT statement being coded */
346 int iContinue, /* Jump here to skip the current record */
347 int iBreak, /* Jump here to end the loop */
348 int nPop /* Number of times to pop stack when jumping */
349){
drh13449892005-09-07 21:22:45 +0000350 if( p->iOffset>=0 && iContinue!=0 ){
danielk1977a2dc3b12005-02-05 12:48:48 +0000351 int addr = sqlite3VdbeCurrentAddr(v) + 3;
drhea48eb22004-07-19 23:16:38 +0000352 if( nPop>0 ) addr++;
danielk1977a2dc3b12005-02-05 12:48:48 +0000353 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, 0);
354 sqlite3VdbeAddOp(v, OP_IfMemPos, p->iOffset, addr);
drhea48eb22004-07-19 23:16:38 +0000355 if( nPop>0 ){
356 sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
357 }
358 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000359 VdbeComment((v, "# skip OFFSET records"));
drhea48eb22004-07-19 23:16:38 +0000360 }
drh13449892005-09-07 21:22:45 +0000361 if( p->iLimit>=0 && iBreak!=0 ){
drhea48eb22004-07-19 23:16:38 +0000362 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhad6d9462004-09-19 02:15:24 +0000363 VdbeComment((v, "# exit when LIMIT reached"));
drhea48eb22004-07-19 23:16:38 +0000364 }
365}
366
367/*
drh22827922000-06-06 17:27:05 +0000368** This routine generates the code for the inside of the inner loop
369** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000370**
drh38640e12002-07-05 21:42:36 +0000371** If srcTab and nColumn are both zero, then the pEList expressions
372** are evaluated in order to get the data for this row. If nColumn>0
373** then data is pulled from srcTab and pEList is used only to get the
374** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000375*/
376static int selectInnerLoop(
377 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000378 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000379 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000380 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000381 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000382 ExprList *pOrderBy, /* If not NULL, sort results using this key */
383 int distinct, /* If >=0, make sure results are distinct */
384 int eDest, /* How to dispose of the results */
385 int iParm, /* An argument to the disposal method */
386 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000387 int iBreak, /* Jump here to break out of the inner loop */
388 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000389){
390 Vdbe *v = pParse->pVdbe;
391 int i;
drhea48eb22004-07-19 23:16:38 +0000392 int hasDistinct; /* True if the DISTINCT keyword is present */
drh38640e12002-07-05 21:42:36 +0000393
drhdaffd0e2001-04-11 14:28:42 +0000394 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000395 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000396
drhdf199a22002-06-14 22:38:41 +0000397 /* If there was a LIMIT clause on the SELECT statement, then do the check
398 ** to see if this row should be output.
399 */
drhea48eb22004-07-19 23:16:38 +0000400 hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
401 if( pOrderBy==0 && !hasDistinct ){
drhbab39e12004-07-19 23:38:11 +0000402 codeLimiter(v, p, iContinue, iBreak, 0);
drhdf199a22002-06-14 22:38:41 +0000403 }
404
drh967e8b72000-06-21 13:59:10 +0000405 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000406 */
drh38640e12002-07-05 21:42:36 +0000407 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000408 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000409 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000410 }
drh38640e12002-07-05 21:42:36 +0000411 }else{
412 nColumn = pEList->nExpr;
drhc182d162005-08-14 20:47:16 +0000413 sqlite3ExprCodeExprList(pParse, pEList);
drh22827922000-06-06 17:27:05 +0000414 }
415
drhdaffd0e2001-04-11 14:28:42 +0000416 /* If the DISTINCT keyword was present on the SELECT statement
417 ** and this row has been seen before, then do not make this row
418 ** part of the result.
drh22827922000-06-06 17:27:05 +0000419 */
drhea48eb22004-07-19 23:16:38 +0000420 if( hasDistinct ){
drhc182d162005-08-14 20:47:16 +0000421 int n = pEList->nExpr;
drh0bd1f4e2002-06-06 18:54:39 +0000422#if NULL_ALWAYS_DISTINCT
danielk19774adee202004-05-08 08:23:19 +0000423 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
drh0bd1f4e2002-06-06 18:54:39 +0000424#endif
danielk1977ededfd52004-06-17 07:53:01 +0000425 /* Deliberately leave the affinity string off of the following
426 ** OP_MakeRecord */
drhc182d162005-08-14 20:47:16 +0000427 sqlite3VdbeAddOp(v, OP_MakeRecord, -n, 0);
danielk19774adee202004-05-08 08:23:19 +0000428 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
drhc182d162005-08-14 20:47:16 +0000429 sqlite3VdbeAddOp(v, OP_Pop, n+1, 0);
danielk19774adee202004-05-08 08:23:19 +0000430 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000431 VdbeComment((v, "# skip indistinct records"));
drhf0863fe2005-06-12 21:35:51 +0000432 sqlite3VdbeAddOp(v, OP_IdxInsert, distinct, 0);
drhea48eb22004-07-19 23:16:38 +0000433 if( pOrderBy==0 ){
drhbab39e12004-07-19 23:38:11 +0000434 codeLimiter(v, p, iContinue, iBreak, nColumn);
drhea48eb22004-07-19 23:16:38 +0000435 }
drh22827922000-06-06 17:27:05 +0000436 }
drh82c3d632000-06-06 21:56:07 +0000437
drhc926afb2002-06-20 03:38:26 +0000438 switch( eDest ){
439 /* In this mode, write each query result to the key of the temporary
440 ** table iParm.
441 */
drh13449892005-09-07 21:22:45 +0000442#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhc926afb2002-06-20 03:38:26 +0000443 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000444 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
drh13449892005-09-07 21:22:45 +0000445 if( aff ){
446 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
447 }
drhf0863fe2005-06-12 21:35:51 +0000448 sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000449 break;
drh22827922000-06-06 17:27:05 +0000450 }
drh22827922000-06-06 17:27:05 +0000451
drhc926afb2002-06-20 03:38:26 +0000452 /* Construct a record from the query result, but instead of
453 ** saving that record, use it as a key to delete elements from
454 ** the temporary table iParm.
455 */
456 case SRT_Except: {
457 int addr;
danielk19774adee202004-05-08 08:23:19 +0000458 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000459 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000460 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
461 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000462 break;
463 }
danielk19775338a5f2005-01-20 13:03:10 +0000464#endif
465
466 /* Store the result as data using a unique key.
467 */
468 case SRT_Table:
drh9d2985c2005-09-08 01:58:42 +0000469 case SRT_VirtualTab: {
danielk19775338a5f2005-01-20 13:03:10 +0000470 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
471 if( pOrderBy ){
472 pushOntoSorter(pParse, v, pOrderBy);
473 }else{
drhf0863fe2005-06-12 21:35:51 +0000474 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
danielk19775338a5f2005-01-20 13:03:10 +0000475 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhf0863fe2005-06-12 21:35:51 +0000476 sqlite3VdbeAddOp(v, OP_Insert, iParm, 0);
danielk19775338a5f2005-01-20 13:03:10 +0000477 }
478 break;
479 }
drh5974a302000-06-07 14:42:26 +0000480
danielk197793758c82005-01-21 08:13:14 +0000481#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000482 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
483 ** then there should be a single item on the stack. Write this
484 ** item into the set table with bogus data.
485 */
486 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000487 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000488 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000489
drhc926afb2002-06-20 03:38:26 +0000490 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000491 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
492 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
493 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000494 if( pOrderBy ){
drhde941c62005-08-28 01:34:21 +0000495 /* At first glance you would think we could optimize out the
496 ** ORDER BY in this case since the order of entries in the set
497 ** does not matter. But there might be a LIMIT clause, in which
498 ** case the order does matter */
drhc926afb2002-06-20 03:38:26 +0000499 pushOntoSorter(pParse, v, pOrderBy);
500 }else{
danielk1977e014a832004-05-17 10:48:57 +0000501 char aff = (iParm>>16)&0xFF;
502 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
drh94a11212004-09-25 13:12:14 +0000503 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1);
drhf0863fe2005-06-12 21:35:51 +0000504 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000505 }
danielk19774adee202004-05-08 08:23:19 +0000506 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000507 break;
508 }
drh22827922000-06-06 17:27:05 +0000509
drhc926afb2002-06-20 03:38:26 +0000510 /* If this is a scalar select that is part of an expression, then
511 ** store the results in the appropriate memory cell and break out
512 ** of the scan loop.
513 */
drh51522cd2005-01-20 13:36:19 +0000514 case SRT_Exists:
drhc926afb2002-06-20 03:38:26 +0000515 case SRT_Mem: {
516 assert( nColumn==1 );
517 if( pOrderBy ){
518 pushOntoSorter(pParse, v, pOrderBy);
519 }else{
danielk19774adee202004-05-08 08:23:19 +0000520 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
521 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000522 }
523 break;
524 }
danielk197793758c82005-01-21 08:13:14 +0000525#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
drh22827922000-06-06 17:27:05 +0000526
drhc182d162005-08-14 20:47:16 +0000527 /* Send the data to the callback function or to a subroutine. In the
528 ** case of a subroutine, the subroutine itself is responsible for
529 ** popping the data from the stack.
drhf46f9052002-06-22 02:33:38 +0000530 */
drhc182d162005-08-14 20:47:16 +0000531 case SRT_Subroutine:
drh9d2985c2005-09-08 01:58:42 +0000532 case SRT_Callback: {
drhf46f9052002-06-22 02:33:38 +0000533 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000534 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000535 pushOntoSorter(pParse, v, pOrderBy);
drhc182d162005-08-14 20:47:16 +0000536 }else if( eDest==SRT_Subroutine ){
danielk19774adee202004-05-08 08:23:19 +0000537 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhc182d162005-08-14 20:47:16 +0000538 }else{
drhc182d162005-08-14 20:47:16 +0000539 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000540 }
drh142e30d2002-08-28 03:00:58 +0000541 break;
542 }
543
danielk19776a67fe82005-02-04 04:07:16 +0000544#if !defined(SQLITE_OMIT_TRIGGER)
drhc926afb2002-06-20 03:38:26 +0000545 /* Discard the results. This is used for SELECT statements inside
546 ** the body of a TRIGGER. The purpose of such selects is to call
547 ** user-defined functions that have side effects. We do not care
548 ** about the actual results of the select.
549 */
drhc926afb2002-06-20 03:38:26 +0000550 default: {
drhf46f9052002-06-22 02:33:38 +0000551 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000552 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000553 break;
554 }
danielk197793758c82005-01-21 08:13:14 +0000555#endif
drh82c3d632000-06-06 21:56:07 +0000556 }
557 return 0;
558}
559
560/*
drhdece1a82005-08-31 18:20:00 +0000561** Given an expression list, generate a KeyInfo structure that records
562** the collating sequence for each expression in that expression list.
563**
drh0342b1f2005-09-01 03:07:44 +0000564** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
565** KeyInfo structure is appropriate for initializing a virtual index to
566** implement that clause. If the ExprList is the result set of a SELECT
567** then the KeyInfo structure is appropriate for initializing a virtual
568** index to implement a DISTINCT test.
569**
drhdece1a82005-08-31 18:20:00 +0000570** Space to hold the KeyInfo structure is obtain from malloc. The calling
571** function is responsible for seeing that this structure is eventually
572** freed. Add the KeyInfo structure to the P3 field of an opcode using
573** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
574*/
575static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
576 sqlite3 *db = pParse->db;
577 int nExpr;
578 KeyInfo *pInfo;
579 struct ExprList_item *pItem;
580 int i;
581
582 nExpr = pList->nExpr;
583 pInfo = sqliteMalloc( sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
584 if( pInfo ){
585 pInfo->aSortOrder = (char*)&pInfo->aColl[nExpr];
586 pInfo->nField = nExpr;
587 pInfo->enc = db->enc;
588 for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
589 CollSeq *pColl;
590 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
591 if( !pColl ){
592 pColl = db->pDfltColl;
593 }
594 pInfo->aColl[i] = pColl;
595 pInfo->aSortOrder[i] = pItem->sortOrder;
596 }
597 }
598 return pInfo;
599}
600
601
602/*
drhd8bc7082000-06-07 23:51:50 +0000603** If the inner loop was generated using a non-null pOrderBy argument,
604** then the results were placed in a sorter. After the loop is terminated
605** we need to run the sorter and output the results. The following
606** routine generates the code needed to do that.
607*/
drhc926afb2002-06-20 03:38:26 +0000608static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000609 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000610 Select *p, /* The SELECT statement */
611 Vdbe *v, /* Generate code into this VDBE */
612 int nColumn, /* Number of columns of data */
613 int eDest, /* Write the sorted results here */
614 int iParm /* Optional parameter associated with eDest */
615){
drh0342b1f2005-09-01 03:07:44 +0000616 int brk = sqlite3VdbeMakeLabel(v);
617 int cont = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000618 int addr;
drh0342b1f2005-09-01 03:07:44 +0000619 int iTab;
620 ExprList *pOrderBy = p->pOrderBy;
drhffbc3082004-05-21 01:29:06 +0000621
drh9d2985c2005-09-08 01:58:42 +0000622 iTab = pOrderBy->iECursor;
drh0342b1f2005-09-01 03:07:44 +0000623 addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
624 codeLimiter(v, p, cont, brk, 0);
drh4db38a72005-09-01 12:16:28 +0000625 sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1);
drhc926afb2002-06-20 03:38:26 +0000626 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000627 case SRT_Table:
drh9d2985c2005-09-08 01:58:42 +0000628 case SRT_VirtualTab: {
drhf0863fe2005-06-12 21:35:51 +0000629 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
danielk19774adee202004-05-08 08:23:19 +0000630 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhf0863fe2005-06-12 21:35:51 +0000631 sqlite3VdbeAddOp(v, OP_Insert, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000632 break;
633 }
danielk197793758c82005-01-21 08:13:14 +0000634#ifndef SQLITE_OMIT_SUBQUERY
drhc926afb2002-06-20 03:38:26 +0000635 case SRT_Set: {
636 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000637 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
638 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
639 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
danielk1977ededfd52004-06-17 07:53:01 +0000640 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
drhf0863fe2005-06-12 21:35:51 +0000641 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000642 break;
643 }
drh51522cd2005-01-20 13:36:19 +0000644 case SRT_Exists:
drhc926afb2002-06-20 03:38:26 +0000645 case SRT_Mem: {
646 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000647 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh0342b1f2005-09-01 03:07:44 +0000648 sqlite3VdbeAddOp(v, OP_Goto, 0, brk);
drhc926afb2002-06-20 03:38:26 +0000649 break;
650 }
danielk197793758c82005-01-21 08:13:14 +0000651#endif
drhce665cf2004-05-21 03:01:58 +0000652 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000653 case SRT_Subroutine: {
654 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000655 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
656 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000657 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000658 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000659 }
drhce665cf2004-05-21 03:01:58 +0000660 if( eDest==SRT_Callback ){
661 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
662 }else{
663 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
664 }
danielk197784ac9d02004-05-18 09:58:06 +0000665 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000666 break;
667 }
drhc926afb2002-06-20 03:38:26 +0000668 default: {
drhf46f9052002-06-22 02:33:38 +0000669 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000670 break;
671 }
672 }
drh0342b1f2005-09-01 03:07:44 +0000673 sqlite3VdbeResolveLabel(v, cont);
674 sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
675 sqlite3VdbeResolveLabel(v, brk);
drhd8bc7082000-06-07 23:51:50 +0000676}
677
678/*
danielk1977517eb642004-06-07 10:00:31 +0000679** Return a pointer to a string containing the 'declaration type' of the
680** expression pExpr. The string may be treated as static by the caller.
drhe78e8282003-01-19 03:59:45 +0000681**
danielk1977517eb642004-06-07 10:00:31 +0000682** If the declaration type is the exact datatype definition extracted from
683** the original CREATE TABLE statement if the expression is a column.
684**
685** The declaration type for an expression is either TEXT, NUMERIC or ANY.
686** The declaration type for a ROWID field is INTEGER.
687*/
danielk1977b3bce662005-01-29 08:32:43 +0000688static const char *columnType(NameContext *pNC, Expr *pExpr){
danielk197700e279d2004-06-21 07:36:32 +0000689 char const *zType;
danielk1977517eb642004-06-07 10:00:31 +0000690 int j;
danielk1977b3bce662005-01-29 08:32:43 +0000691 if( pExpr==0 || pNC->pSrcList==0 ) return 0;
danielk19775338a5f2005-01-20 13:03:10 +0000692
693 /* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING,
694 ** and LIMIT clauses. But pExpr originates in the result set of a
695 ** SELECT. So pExpr can never contain an AS operator.
696 */
697 assert( pExpr->op!=TK_AS );
698
danielk197700e279d2004-06-21 07:36:32 +0000699 switch( pExpr->op ){
700 case TK_COLUMN: {
danielk1977b3bce662005-01-29 08:32:43 +0000701 Table *pTab = 0;
danielk197700e279d2004-06-21 07:36:32 +0000702 int iCol = pExpr->iColumn;
danielk1977b3bce662005-01-29 08:32:43 +0000703 while( pNC && !pTab ){
704 SrcList *pTabList = pNC->pSrcList;
705 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
706 if( j<pTabList->nSrc ){
707 pTab = pTabList->a[j].pTab;
708 }else{
709 pNC = pNC->pNext;
710 }
711 }
drh7e627792005-04-29 02:10:00 +0000712 if( pTab==0 ){
713 /* FIX ME:
714 ** This can occurs if you have something like "SELECT new.x;" inside
715 ** a trigger. In other words, if you reference the special "new"
716 ** table in the result set of a select. We do not have a good way
717 ** to find the actual table type, so call it "TEXT". This is really
718 ** something of a bug, but I do not know how to fix it.
719 **
720 ** This code does not produce the correct answer - it just prevents
721 ** a segfault. See ticket #1229.
722 */
723 zType = "TEXT";
724 break;
725 }
danielk1977b3bce662005-01-29 08:32:43 +0000726 assert( pTab );
danielk197700e279d2004-06-21 07:36:32 +0000727 if( iCol<0 ) iCol = pTab->iPKey;
728 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
729 if( iCol<0 ){
730 zType = "INTEGER";
731 }else{
732 zType = pTab->aCol[iCol].zType;
733 }
734 break;
danielk1977517eb642004-06-07 10:00:31 +0000735 }
danielk197793758c82005-01-21 08:13:14 +0000736#ifndef SQLITE_OMIT_SUBQUERY
danielk197700e279d2004-06-21 07:36:32 +0000737 case TK_SELECT: {
danielk1977b3bce662005-01-29 08:32:43 +0000738 NameContext sNC;
danielk197700e279d2004-06-21 07:36:32 +0000739 Select *pS = pExpr->pSelect;
danielk1977b3bce662005-01-29 08:32:43 +0000740 sNC.pSrcList = pExpr->pSelect->pSrc;
741 sNC.pNext = pNC;
742 zType = columnType(&sNC, pS->pEList->a[0].pExpr);
danielk197700e279d2004-06-21 07:36:32 +0000743 break;
danielk1977517eb642004-06-07 10:00:31 +0000744 }
danielk197793758c82005-01-21 08:13:14 +0000745#endif
danielk197700e279d2004-06-21 07:36:32 +0000746 default:
747 zType = 0;
danielk1977517eb642004-06-07 10:00:31 +0000748 }
danielk197700e279d2004-06-21 07:36:32 +0000749
danielk1977517eb642004-06-07 10:00:31 +0000750 return zType;
751}
752
753/*
754** Generate code that will tell the VDBE the declaration types of columns
755** in the result set.
drhfcb78a42003-01-18 20:11:05 +0000756*/
757static void generateColumnTypes(
758 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000759 SrcList *pTabList, /* List of tables */
760 ExprList *pEList /* Expressions defining the result set */
761){
762 Vdbe *v = pParse->pVdbe;
danielk1977517eb642004-06-07 10:00:31 +0000763 int i;
danielk1977b3bce662005-01-29 08:32:43 +0000764 NameContext sNC;
765 sNC.pSrcList = pTabList;
drhfcb78a42003-01-18 20:11:05 +0000766 for(i=0; i<pEList->nExpr; i++){
767 Expr *p = pEList->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +0000768 const char *zType = columnType(&sNC, p);
danielk197700e279d2004-06-21 07:36:32 +0000769 if( zType==0 ) continue;
danielk1977fbcd5852004-06-15 02:44:18 +0000770 /* The vdbe must make it's own copy of the column-type, in case the
771 ** schema is reset before this virtual machine is deleted.
772 */
773 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
drhfcb78a42003-01-18 20:11:05 +0000774 }
775}
776
777/*
778** Generate code that will tell the VDBE the names of columns
779** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000780** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000781*/
drh832508b2002-03-02 17:04:07 +0000782static void generateColumnNames(
783 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000784 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000785 ExprList *pEList /* Expressions defining the result set */
786){
drhd8bc7082000-06-07 23:51:50 +0000787 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000788 int i, j;
drh9bb575f2004-09-06 17:24:11 +0000789 sqlite3 *db = pParse->db;
drhfcabd462004-02-20 14:50:58 +0000790 int fullNames, shortNames;
791
drhfe2093d2005-01-20 22:48:47 +0000792#ifndef SQLITE_OMIT_EXPLAIN
danielk19773cf86062004-05-26 10:11:05 +0000793 /* If this is an EXPLAIN, skip this step */
794 if( pParse->explain ){
danielk197761de0d12004-05-27 23:56:16 +0000795 return;
danielk19773cf86062004-05-26 10:11:05 +0000796 }
danielk19775338a5f2005-01-20 13:03:10 +0000797#endif
danielk19773cf86062004-05-26 10:11:05 +0000798
drhd6502752004-02-16 03:44:01 +0000799 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000800 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000801 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000802 fullNames = (db->flags & SQLITE_FullColNames)!=0;
803 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
danielk197722322fd2004-05-25 23:35:17 +0000804 sqlite3VdbeSetNumCols(v, pEList->nExpr);
drh82c3d632000-06-06 21:56:07 +0000805 for(i=0; i<pEList->nExpr; i++){
806 Expr *p;
drh5a387052003-01-11 14:19:51 +0000807 p = pEList->a[i].pExpr;
808 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000809 if( pEList->a[i].zName ){
810 char *zName = pEList->a[i].zName;
danielk1977d8123362004-06-12 09:25:12 +0000811 sqlite3VdbeSetColName(v, i, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000812 continue;
813 }
drhfa173a72002-07-10 21:26:00 +0000814 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000815 Table *pTab;
drh97665872002-02-13 23:22:53 +0000816 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000817 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000818 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
819 assert( j<pTabList->nSrc );
820 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000821 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000822 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000823 if( iCol<0 ){
drh47a6db22005-01-18 16:02:40 +0000824 zCol = "rowid";
drhb1363202002-06-26 02:45:03 +0000825 }else{
826 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000827 }
drhfcabd462004-02-20 14:50:58 +0000828 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000829 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
drhfcabd462004-02-20 14:50:58 +0000830 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000831 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000832 char *zTab;
833
drh6a3ea0e2003-05-02 14:32:12 +0000834 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000835 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000836 sqlite3SetString(&zName, zTab, ".", zCol, 0);
danielk19773cf86062004-05-26 10:11:05 +0000837 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000838 }else{
drh47a6db22005-01-18 16:02:40 +0000839 sqlite3VdbeSetColName(v, i, zCol, strlen(zCol));
drh82c3d632000-06-06 21:56:07 +0000840 }
drh6977fea2002-10-22 23:38:04 +0000841 }else if( p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000842 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
843 /* sqlite3VdbeCompressSpace(v, addr); */
drh1bee3d72001-10-15 00:44:35 +0000844 }else{
845 char zName[30];
846 assert( p->op!=TK_COLUMN || pTabList==0 );
847 sprintf(zName, "column%d", i+1);
danielk19773cf86062004-05-26 10:11:05 +0000848 sqlite3VdbeSetColName(v, i, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000849 }
850 }
danielk197776d505b2004-05-28 13:13:02 +0000851 generateColumnTypes(pParse, pTabList, pEList);
drh82c3d632000-06-06 21:56:07 +0000852}
853
danielk197793758c82005-01-21 08:13:14 +0000854#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +0000855/*
drhd8bc7082000-06-07 23:51:50 +0000856** Name of the connection operator, used for error messages.
857*/
858static const char *selectOpName(int id){
859 char *z;
860 switch( id ){
861 case TK_ALL: z = "UNION ALL"; break;
862 case TK_INTERSECT: z = "INTERSECT"; break;
863 case TK_EXCEPT: z = "EXCEPT"; break;
864 default: z = "UNION"; break;
865 }
866 return z;
867}
danielk197793758c82005-01-21 08:13:14 +0000868#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +0000869
870/*
drh315555c2002-10-20 15:53:03 +0000871** Forward declaration
872*/
drh9b3187e2005-01-18 14:45:47 +0000873static int prepSelectStmt(Parse*, Select*);
drh315555c2002-10-20 15:53:03 +0000874
875/*
drh22f70c32002-02-18 01:17:00 +0000876** Given a SELECT statement, generate a Table structure that describes
877** the result set of that SELECT.
878*/
danielk19774adee202004-05-08 08:23:19 +0000879Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000880 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000881 int i, j;
drh22f70c32002-02-18 01:17:00 +0000882 ExprList *pEList;
drh290c1942004-08-21 17:54:45 +0000883 Column *aCol, *pCol;
drh22f70c32002-02-18 01:17:00 +0000884
drh9b3187e2005-01-18 14:45:47 +0000885 if( prepSelectStmt(pParse, pSelect) ){
drh22f70c32002-02-18 01:17:00 +0000886 return 0;
887 }
danielk1977142bdf42005-01-30 11:11:44 +0000888 if( sqlite3SelectResolve(pParse, pSelect, 0) ){
889 return 0;
890 }
drh22f70c32002-02-18 01:17:00 +0000891 pTab = sqliteMalloc( sizeof(Table) );
892 if( pTab==0 ){
893 return 0;
894 }
drhed8a3bb2005-06-06 21:19:56 +0000895 pTab->nRef = 1;
drh22f70c32002-02-18 01:17:00 +0000896 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
897 pEList = pSelect->pEList;
898 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000899 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000900 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh290c1942004-08-21 17:54:45 +0000901 for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
drh79d5f632005-01-18 17:20:10 +0000902 Expr *p, *pR;
danielk1977517eb642004-06-07 10:00:31 +0000903 char *zType;
drh91bb0ee2004-09-01 03:06:34 +0000904 char *zName;
drh79d5f632005-01-18 17:20:10 +0000905 char *zBasename;
906 int cnt;
danielk1977b3bce662005-01-29 08:32:43 +0000907 NameContext sNC;
drh79d5f632005-01-18 17:20:10 +0000908
909 /* Get an appropriate name for the column
910 */
911 p = pEList->a[i].pExpr;
drh290c1942004-08-21 17:54:45 +0000912 assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
drh91bb0ee2004-09-01 03:06:34 +0000913 if( (zName = pEList->a[i].zName)!=0 ){
drh79d5f632005-01-18 17:20:10 +0000914 /* If the column contains an "AS <name>" phrase, use <name> as the name */
drh91bb0ee2004-09-01 03:06:34 +0000915 zName = sqliteStrDup(zName);
danielk1977517eb642004-06-07 10:00:31 +0000916 }else if( p->op==TK_DOT
drh79d5f632005-01-18 17:20:10 +0000917 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
918 /* For columns of the from A.B use B as the name */
drh91bb0ee2004-09-01 03:06:34 +0000919 zName = sqlite3MPrintf("%T", &pR->token);
drhb733d032004-01-24 20:18:12 +0000920 }else if( p->span.z && p->span.z[0] ){
drh79d5f632005-01-18 17:20:10 +0000921 /* Use the original text of the column expression as its name */
drh91bb0ee2004-09-01 03:06:34 +0000922 zName = sqlite3MPrintf("%T", &p->span);
drh22f70c32002-02-18 01:17:00 +0000923 }else{
drh79d5f632005-01-18 17:20:10 +0000924 /* If all else fails, make up a name */
drh91bb0ee2004-09-01 03:06:34 +0000925 zName = sqlite3MPrintf("column%d", i+1);
drh22f70c32002-02-18 01:17:00 +0000926 }
drh91bb0ee2004-09-01 03:06:34 +0000927 sqlite3Dequote(zName);
drhdd5b2fa2005-03-28 03:39:55 +0000928 if( sqlite3_malloc_failed ){
929 sqliteFree(zName);
930 sqlite3DeleteTable(0, pTab);
931 return 0;
932 }
drh79d5f632005-01-18 17:20:10 +0000933
934 /* Make sure the column name is unique. If the name is not unique,
935 ** append a integer to the name so that it becomes unique.
936 */
937 zBasename = zName;
938 for(j=cnt=0; j<i; j++){
939 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
940 zName = sqlite3MPrintf("%s:%d", zBasename, ++cnt);
941 j = -1;
drhdd5b2fa2005-03-28 03:39:55 +0000942 if( zName==0 ) break;
drh79d5f632005-01-18 17:20:10 +0000943 }
944 }
945 if( zBasename!=zName ){
946 sqliteFree(zBasename);
947 }
drh91bb0ee2004-09-01 03:06:34 +0000948 pCol->zName = zName;
danielk1977517eb642004-06-07 10:00:31 +0000949
drh79d5f632005-01-18 17:20:10 +0000950 /* Get the typename, type affinity, and collating sequence for the
951 ** column.
952 */
drhc43e8be2005-05-16 22:37:54 +0000953 memset(&sNC, 0, sizeof(sNC));
danielk1977b3bce662005-01-29 08:32:43 +0000954 sNC.pSrcList = pSelect->pSrc;
955 zType = sqliteStrDup(columnType(&sNC, p));
drh290c1942004-08-21 17:54:45 +0000956 pCol->zType = zType;
danielk1977c60e9b82005-01-31 12:42:29 +0000957 pCol->affinity = sqlite3ExprAffinity(p);
drh290c1942004-08-21 17:54:45 +0000958 pCol->pColl = sqlite3ExprCollSeq(pParse, p);
959 if( !pCol->pColl ){
960 pCol->pColl = pParse->db->pDfltColl;
danielk19770202b292004-06-09 09:55:16 +0000961 }
drh22f70c32002-02-18 01:17:00 +0000962 }
963 pTab->iPKey = -1;
964 return pTab;
965}
966
967/*
drh9b3187e2005-01-18 14:45:47 +0000968** Prepare a SELECT statement for processing by doing the following
969** things:
drhd8bc7082000-06-07 23:51:50 +0000970**
drh9b3187e2005-01-18 14:45:47 +0000971** (1) Make sure VDBE cursor numbers have been assigned to every
972** element of the FROM clause.
973**
974** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
975** defines FROM clause. When views appear in the FROM clause,
drh63eb5f22003-04-29 16:20:44 +0000976** fill pTabList->a[].pSelect with a copy of the SELECT statement
977** that implements the view. A copy is made of the view's SELECT
978** statement so that we can freely modify or delete that statement
979** without worrying about messing up the presistent representation
980** of the view.
drhd8bc7082000-06-07 23:51:50 +0000981**
drh9b3187e2005-01-18 14:45:47 +0000982** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
drhad2d8302002-05-24 20:31:36 +0000983** on joins and the ON and USING clause of joins.
984**
drh9b3187e2005-01-18 14:45:47 +0000985** (4) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000986** for instances of the "*" operator or the TABLE.* operator.
987** If found, expand each "*" to be every column in every table
988** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000989**
990** Return 0 on success. If there are problems, leave an error message
991** in pParse and return non-zero.
992*/
drh9b3187e2005-01-18 14:45:47 +0000993static int prepSelectStmt(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000994 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000995 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000996 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000997 Table *pTab;
drh290c1942004-08-21 17:54:45 +0000998 struct SrcList_item *pFrom;
drhdaffd0e2001-04-11 14:28:42 +0000999
danielk1977e94ddc92005-03-21 03:53:38 +00001000 if( p==0 || p->pSrc==0 || sqlite3_malloc_failed ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00001001 pTabList = p->pSrc;
1002 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +00001003
drh9b3187e2005-01-18 14:45:47 +00001004 /* Make sure cursor numbers have been assigned to all entries in
1005 ** the FROM clause of the SELECT statement.
1006 */
1007 sqlite3SrcListAssignCursors(pParse, p->pSrc);
1008
1009 /* Look up every table named in the FROM clause of the select. If
1010 ** an entry of the FROM clause is a subquery instead of a table or view,
1011 ** then create a transient table structure to describe the subquery.
drhd8bc7082000-06-07 23:51:50 +00001012 */
drh290c1942004-08-21 17:54:45 +00001013 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
drh9b3187e2005-01-18 14:45:47 +00001014 if( pFrom->pTab!=0 ){
1015 /* This statement has already been prepared. There is no need
1016 ** to go further. */
1017 assert( i==0 );
drhd8bc7082000-06-07 23:51:50 +00001018 return 0;
1019 }
drh290c1942004-08-21 17:54:45 +00001020 if( pFrom->zName==0 ){
danielk197793758c82005-01-21 08:13:14 +00001021#ifndef SQLITE_OMIT_SUBQUERY
drh22f70c32002-02-18 01:17:00 +00001022 /* A sub-query in the FROM clause of a SELECT */
drh290c1942004-08-21 17:54:45 +00001023 assert( pFrom->pSelect!=0 );
1024 if( pFrom->zAlias==0 ){
drh91bb0ee2004-09-01 03:06:34 +00001025 pFrom->zAlias =
1026 sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
drhad2d8302002-05-24 20:31:36 +00001027 }
drhed8a3bb2005-06-06 21:19:56 +00001028 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001029 pFrom->pTab = pTab =
1030 sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
drh22f70c32002-02-18 01:17:00 +00001031 if( pTab==0 ){
1032 return 1;
1033 }
drh5cf590c2003-04-24 01:45:04 +00001034 /* The isTransient flag indicates that the Table structure has been
1035 ** dynamically allocated and may be freed at any time. In other words,
1036 ** pTab is not pointing to a persistent table structure that defines
1037 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +00001038 pTab->isTransient = 1;
danielk197793758c82005-01-21 08:13:14 +00001039#endif
drh22f70c32002-02-18 01:17:00 +00001040 }else{
drha76b5df2002-02-23 02:32:10 +00001041 /* An ordinary table or view name in the FROM clause */
drhed8a3bb2005-06-06 21:19:56 +00001042 assert( pFrom->pTab==0 );
drh290c1942004-08-21 17:54:45 +00001043 pFrom->pTab = pTab =
1044 sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
drha76b5df2002-02-23 02:32:10 +00001045 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +00001046 return 1;
1047 }
drhed8a3bb2005-06-06 21:19:56 +00001048 pTab->nRef++;
danielk197793758c82005-01-21 08:13:14 +00001049#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00001050 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +00001051 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +00001052 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +00001053 return 1;
1054 }
drh290c1942004-08-21 17:54:45 +00001055 /* If pFrom->pSelect!=0 it means we are dealing with a
drh63eb5f22003-04-29 16:20:44 +00001056 ** view within a view. The SELECT structure has already been
1057 ** copied by the outer view so we can skip the copy step here
1058 ** in the inner view.
1059 */
drh290c1942004-08-21 17:54:45 +00001060 if( pFrom->pSelect==0 ){
1061 pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +00001062 }
drha76b5df2002-02-23 02:32:10 +00001063 }
danielk197793758c82005-01-21 08:13:14 +00001064#endif
drhd8bc7082000-06-07 23:51:50 +00001065 }
1066 }
1067
drhad2d8302002-05-24 20:31:36 +00001068 /* Process NATURAL keywords, and ON and USING clauses of joins.
1069 */
1070 if( sqliteProcessJoin(pParse, p) ) return 1;
1071
drh7c917d12001-12-16 20:05:05 +00001072 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +00001073 ** all columns in all tables. And for every TABLE.* insert the names
1074 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +00001075 ** with the TK_ALL operator for each "*" that it found in the column list.
1076 ** The following code just has to locate the TK_ALL expressions and expand
1077 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +00001078 **
1079 ** The first loop just checks to see if there are any "*" operators
1080 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +00001081 */
drh7c917d12001-12-16 20:05:05 +00001082 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001083 Expr *pE = pEList->a[k].pExpr;
1084 if( pE->op==TK_ALL ) break;
1085 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
1086 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +00001087 }
drh54473222002-04-04 02:10:55 +00001088 rc = 0;
drh7c917d12001-12-16 20:05:05 +00001089 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +00001090 /*
1091 ** If we get here it means the result set contains one or more "*"
1092 ** operators that need to be expanded. Loop through each expression
1093 ** in the result set and expand them one by one.
1094 */
drh7c917d12001-12-16 20:05:05 +00001095 struct ExprList_item *a = pEList->a;
1096 ExprList *pNew = 0;
drhd70dc522005-06-06 16:34:33 +00001097 int flags = pParse->db->flags;
1098 int longNames = (flags & SQLITE_FullColNames)!=0 &&
1099 (flags & SQLITE_ShortColNames)==0;
1100
drh7c917d12001-12-16 20:05:05 +00001101 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +00001102 Expr *pE = a[k].pExpr;
1103 if( pE->op!=TK_ALL &&
1104 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
1105 /* This particular expression does not need to be expanded.
1106 */
danielk19774adee202004-05-08 08:23:19 +00001107 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001108 pNew->a[pNew->nExpr-1].zName = a[k].zName;
1109 a[k].pExpr = 0;
1110 a[k].zName = 0;
1111 }else{
drh54473222002-04-04 02:10:55 +00001112 /* This expression is a "*" or a "TABLE.*" and needs to be
1113 ** expanded. */
1114 int tableSeen = 0; /* Set to 1 when TABLE matches */
drhcf55b7a2004-07-20 01:45:19 +00001115 char *zTName; /* text of name of TABLE */
drh54473222002-04-04 02:10:55 +00001116 if( pE->op==TK_DOT && pE->pLeft ){
drhcf55b7a2004-07-20 01:45:19 +00001117 zTName = sqlite3NameFromToken(&pE->pLeft->token);
drh54473222002-04-04 02:10:55 +00001118 }else{
drhcf55b7a2004-07-20 01:45:19 +00001119 zTName = 0;
drh54473222002-04-04 02:10:55 +00001120 }
drh290c1942004-08-21 17:54:45 +00001121 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1122 Table *pTab = pFrom->pTab;
1123 char *zTabName = pFrom->zAlias;
drh54473222002-04-04 02:10:55 +00001124 if( zTabName==0 || zTabName[0]==0 ){
1125 zTabName = pTab->zName;
1126 }
drhcf55b7a2004-07-20 01:45:19 +00001127 if( zTName && (zTabName==0 || zTabName[0]==0 ||
1128 sqlite3StrICmp(zTName, zTabName)!=0) ){
drh54473222002-04-04 02:10:55 +00001129 continue;
1130 }
1131 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001132 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001133 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001134 char *zName = pTab->aCol[j].zName;
1135
drh91bb0ee2004-09-01 03:06:34 +00001136 if( i>0 ){
1137 struct SrcList_item *pLeft = &pTabList->a[i-1];
1138 if( (pLeft->jointype & JT_NATURAL)!=0 &&
1139 columnIndex(pLeft->pTab, zName)>=0 ){
1140 /* In a NATURAL join, omit the join columns from the
1141 ** table on the right */
1142 continue;
1143 }
1144 if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1145 /* In a join with a USING clause, omit columns in the
1146 ** using clause from the table on the right. */
1147 continue;
1148 }
drhad2d8302002-05-24 20:31:36 +00001149 }
danielk19774adee202004-05-08 08:23:19 +00001150 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001151 if( pRight==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001152 setToken(&pRight->token, zName);
drhd70dc522005-06-06 16:34:33 +00001153 if( zTabName && (longNames || pTabList->nSrc>1) ){
danielk19774adee202004-05-08 08:23:19 +00001154 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1155 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001156 if( pExpr==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001157 setToken(&pLeft->token, zTabName);
1158 setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
drh6977fea2002-10-22 23:38:04 +00001159 pExpr->span.dyn = 1;
1160 pExpr->token.z = 0;
1161 pExpr->token.n = 0;
1162 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001163 }else{
drh22f70c32002-02-18 01:17:00 +00001164 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001165 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001166 }
drhd70dc522005-06-06 16:34:33 +00001167 if( longNames ){
1168 pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span);
1169 }else{
1170 pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
1171 }
drh7c917d12001-12-16 20:05:05 +00001172 }
drh17e24df2001-11-06 14:10:41 +00001173 }
drh54473222002-04-04 02:10:55 +00001174 if( !tableSeen ){
drhcf55b7a2004-07-20 01:45:19 +00001175 if( zTName ){
1176 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
drhf5db2d32002-06-06 23:42:27 +00001177 }else{
danielk19774adee202004-05-08 08:23:19 +00001178 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001179 }
drh54473222002-04-04 02:10:55 +00001180 rc = 1;
1181 }
drhcf55b7a2004-07-20 01:45:19 +00001182 sqliteFree(zTName);
drhd8bc7082000-06-07 23:51:50 +00001183 }
1184 }
danielk19774adee202004-05-08 08:23:19 +00001185 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001186 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001187 }
drh54473222002-04-04 02:10:55 +00001188 return rc;
drhd8bc7082000-06-07 23:51:50 +00001189}
1190
danielk197793758c82005-01-21 08:13:14 +00001191#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhff78bd22002-02-27 01:47:11 +00001192/*
drhd8bc7082000-06-07 23:51:50 +00001193** This routine associates entries in an ORDER BY expression list with
1194** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001195** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001196** the top-level node is filled in with column number and the iTable
1197** value of the top-level node is filled with iTable parameter.
1198**
1199** If there are prior SELECT clauses, they are processed first. A match
1200** in an earlier SELECT takes precedence over a later SELECT.
1201**
1202** Any entry that does not match is flagged as an error. The number
1203** of errors is returned.
1204*/
1205static int matchOrderbyToColumn(
1206 Parse *pParse, /* A place to leave error messages */
1207 Select *pSelect, /* Match to result columns of this SELECT */
1208 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001209 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001210 int mustComplete /* If TRUE all ORDER BYs must match */
1211){
1212 int nErr = 0;
1213 int i, j;
1214 ExprList *pEList;
1215
drhdaffd0e2001-04-11 14:28:42 +00001216 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001217 if( mustComplete ){
1218 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1219 }
drh9b3187e2005-01-18 14:45:47 +00001220 if( prepSelectStmt(pParse, pSelect) ){
drhd8bc7082000-06-07 23:51:50 +00001221 return 1;
1222 }
1223 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001224 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1225 return 1;
1226 }
drhd8bc7082000-06-07 23:51:50 +00001227 }
1228 pEList = pSelect->pEList;
1229 for(i=0; i<pOrderBy->nExpr; i++){
1230 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001231 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001232 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001233 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001234 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001235 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001236 "ORDER BY position %d should be between 1 and %d",
1237 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001238 nErr++;
1239 break;
1240 }
drhfcb78a42003-01-18 20:11:05 +00001241 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001242 iCol--;
1243 }
1244 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001245 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001246 char *zName, *zLabel;
1247 zName = pEList->a[j].zName;
drha99db3b2004-06-19 14:49:12 +00001248 zLabel = sqlite3NameFromToken(&pE->token);
1249 assert( zLabel!=0 );
danielk19774adee202004-05-08 08:23:19 +00001250 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001251 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001252 }
drh6e142f52000-06-08 13:36:40 +00001253 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001254 }
danielk19774adee202004-05-08 08:23:19 +00001255 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001256 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001257 }
1258 }
drhe4de1fe2002-06-02 16:09:01 +00001259 if( iCol>=0 ){
1260 pE->op = TK_COLUMN;
1261 pE->iColumn = iCol;
1262 pE->iTable = iTable;
danielk1977a58fdfb2005-02-08 07:50:40 +00001263 pE->iAgg = -1;
drhe4de1fe2002-06-02 16:09:01 +00001264 pOrderBy->a[i].done = 1;
1265 }
1266 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001267 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001268 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001269 nErr++;
1270 break;
1271 }
1272 }
1273 return nErr;
1274}
danielk197793758c82005-01-21 08:13:14 +00001275#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
drhd8bc7082000-06-07 23:51:50 +00001276
1277/*
1278** Get a VDBE for the given parser context. Create a new one if necessary.
1279** If an error occurs, return NULL and leave a message in pParse.
1280*/
danielk19774adee202004-05-08 08:23:19 +00001281Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001282 Vdbe *v = pParse->pVdbe;
1283 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001284 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001285 }
drhd8bc7082000-06-07 23:51:50 +00001286 return v;
1287}
drhfcb78a42003-01-18 20:11:05 +00001288
drhd8bc7082000-06-07 23:51:50 +00001289/*
drh7b58dae2003-07-20 01:16:46 +00001290** Compute the iLimit and iOffset fields of the SELECT based on the
danielk1977a2dc3b12005-02-05 12:48:48 +00001291** pLimit and pOffset expressions. nLimit and nOffset hold the expressions
drh7b58dae2003-07-20 01:16:46 +00001292** that appear in the original SQL statement after the LIMIT and OFFSET
danielk1977a2dc3b12005-02-05 12:48:48 +00001293** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
1294** are the integer memory register numbers for counters used to compute
1295** the limit and offset. If there is no limit and/or offset, then
1296** iLimit and iOffset are negative.
drh7b58dae2003-07-20 01:16:46 +00001297**
1298** This routine changes the values if iLimit and iOffset only if
1299** a limit or offset is defined by nLimit and nOffset. iLimit and
1300** iOffset should have been preset to appropriate default values
1301** (usually but not always -1) prior to calling this routine.
1302** Only if nLimit>=0 or nOffset>0 do the limit registers get
1303** redefined. The UNION ALL operator uses this property to force
1304** the reuse of the same limit and offset registers across multiple
1305** SELECT statements.
1306*/
1307static void computeLimitRegisters(Parse *pParse, Select *p){
1308 /*
drh7b58dae2003-07-20 01:16:46 +00001309 ** "LIMIT -1" always shows all rows. There is some
1310 ** contraversy about what the correct behavior should be.
1311 ** The current implementation interprets "LIMIT 0" to mean
1312 ** no rows.
1313 */
danielk1977a2dc3b12005-02-05 12:48:48 +00001314 if( p->pLimit ){
drh7b58dae2003-07-20 01:16:46 +00001315 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001316 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001317 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001318 sqlite3ExprCode(pParse, p->pLimit);
1319 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1320 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001321 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001322 VdbeComment((v, "# LIMIT counter"));
drh7b58dae2003-07-20 01:16:46 +00001323 p->iLimit = iMem;
1324 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001325 if( p->pOffset ){
drh7b58dae2003-07-20 01:16:46 +00001326 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001327 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001328 if( v==0 ) return;
danielk1977a2dc3b12005-02-05 12:48:48 +00001329 sqlite3ExprCode(pParse, p->pOffset);
1330 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1331 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001332 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001333 VdbeComment((v, "# OFFSET counter"));
drh7b58dae2003-07-20 01:16:46 +00001334 p->iOffset = iMem;
1335 }
1336}
1337
1338/*
drh0342b1f2005-09-01 03:07:44 +00001339** Allocate a virtual index to use for sorting.
drhd3d39e92004-05-20 22:16:29 +00001340*/
drh4db38a72005-09-01 12:16:28 +00001341static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
drh0342b1f2005-09-01 03:07:44 +00001342 if( pOrderBy ){
1343 int addr;
drh9d2985c2005-09-08 01:58:42 +00001344 assert( pOrderBy->iECursor==0 );
1345 pOrderBy->iECursor = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001346 addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenVirtual,
drh9d2985c2005-09-08 01:58:42 +00001347 pOrderBy->iECursor, pOrderBy->nExpr+1);
drh0342b1f2005-09-01 03:07:44 +00001348 assert( p->addrOpenVirt[2] == -1 );
1349 p->addrOpenVirt[2] = addr;
drh736c22b2004-05-21 02:14:24 +00001350 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001351}
1352
drh13449892005-09-07 21:22:45 +00001353/*
1354** The opcode at addr is an OP_OpenVirtual that created a sorting
1355** index tha we ended up not needing. This routine changes that
1356** opcode to OP_Noop.
1357*/
1358static void uncreateSortingIndex(Parse *pParse, int addr){
1359 Vdbe *v = pParse->pVdbe;
1360 VdbeOp *pOp = sqlite3VdbeGetOp(v, addr);
1361 sqlite3VdbeChangeP3(v, addr, 0, 0);
1362 pOp->opcode = OP_Noop;
1363 pOp->p1 = 0;
1364 pOp->p2 = 0;
1365}
1366
drhb7f91642004-10-31 02:22:47 +00001367#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhfbc4ee72004-08-29 01:31:05 +00001368/*
drhfbc4ee72004-08-29 01:31:05 +00001369** Return the appropriate collating sequence for the iCol-th column of
1370** the result set for the compound-select statement "p". Return NULL if
1371** the column has no default collating sequence.
1372**
1373** The collating sequence for the compound select is taken from the
1374** left-most term of the select that has a collating sequence.
1375*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001376static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
drhfbc4ee72004-08-29 01:31:05 +00001377 CollSeq *pRet;
danielk1977dc1bdc42004-06-11 10:51:27 +00001378 if( p->pPrior ){
1379 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
drhfbc4ee72004-08-29 01:31:05 +00001380 }else{
1381 pRet = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001382 }
drhfbc4ee72004-08-29 01:31:05 +00001383 if( pRet==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001384 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1385 }
1386 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001387}
drhb7f91642004-10-31 02:22:47 +00001388#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drhd3d39e92004-05-20 22:16:29 +00001389
drhb7f91642004-10-31 02:22:47 +00001390#ifndef SQLITE_OMIT_COMPOUND_SELECT
drhd3d39e92004-05-20 22:16:29 +00001391/*
drh82c3d632000-06-06 21:56:07 +00001392** This routine is called to process a query that is really the union
1393** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001394**
drhe78e8282003-01-19 03:59:45 +00001395** "p" points to the right-most of the two queries. the query on the
1396** left is p->pPrior. The left query could also be a compound query
1397** in which case this routine will be called recursively.
1398**
1399** The results of the total query are to be written into a destination
1400** of type eDest with parameter iParm.
1401**
1402** Example 1: Consider a three-way compound SQL statement.
1403**
1404** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1405**
1406** This statement is parsed up as follows:
1407**
1408** SELECT c FROM t3
1409** |
1410** `-----> SELECT b FROM t2
1411** |
jplyon4b11c6d2004-01-19 04:57:53 +00001412** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001413**
1414** The arrows in the diagram above represent the Select.pPrior pointer.
1415** So if this routine is called with p equal to the t3 query, then
1416** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1417**
1418** Notice that because of the way SQLite parses compound SELECTs, the
1419** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001420*/
danielk197784ac9d02004-05-18 09:58:06 +00001421static int multiSelect(
drhfbc4ee72004-08-29 01:31:05 +00001422 Parse *pParse, /* Parsing context */
1423 Select *p, /* The right-most of SELECTs to be coded */
1424 int eDest, /* \___ Store query results as specified */
1425 int iParm, /* / by these two parameters. */
1426 char *aff /* If eDest is SRT_Union, the affinity string */
danielk197784ac9d02004-05-18 09:58:06 +00001427){
drhfbc4ee72004-08-29 01:31:05 +00001428 int rc = SQLITE_OK; /* Success code from a subroutine */
1429 Select *pPrior; /* Another SELECT immediately to our left */
1430 Vdbe *v; /* Generate code to this VDBE */
drh8cdbf832004-08-29 16:25:03 +00001431 int nCol; /* Number of columns in the result set */
drh0342b1f2005-09-01 03:07:44 +00001432 ExprList *pOrderBy; /* The ORDER BY clause on p */
1433 int aSetP2[2]; /* Set P2 value of these op to number of columns */
1434 int nSetP2 = 0; /* Number of slots in aSetP2[] used */
drh82c3d632000-06-06 21:56:07 +00001435
drh7b58dae2003-07-20 01:16:46 +00001436 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
drhfbc4ee72004-08-29 01:31:05 +00001437 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001438 */
danielk197784ac9d02004-05-18 09:58:06 +00001439 if( p==0 || p->pPrior==0 ){
1440 rc = 1;
1441 goto multi_select_end;
1442 }
drhd8bc7082000-06-07 23:51:50 +00001443 pPrior = p->pPrior;
drh0342b1f2005-09-01 03:07:44 +00001444 assert( pPrior->pRightmost!=pPrior );
1445 assert( pPrior->pRightmost==p->pRightmost );
drhd8bc7082000-06-07 23:51:50 +00001446 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001447 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001448 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001449 rc = 1;
1450 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001451 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001452 if( pPrior->pLimit ){
danielk19774adee202004-05-08 08:23:19 +00001453 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001454 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001455 rc = 1;
1456 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001457 }
drh82c3d632000-06-06 21:56:07 +00001458
drhd8bc7082000-06-07 23:51:50 +00001459 /* Make sure we have a valid query engine. If not, create a new one.
1460 */
danielk19774adee202004-05-08 08:23:19 +00001461 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001462 if( v==0 ){
1463 rc = 1;
1464 goto multi_select_end;
1465 }
drhd8bc7082000-06-07 23:51:50 +00001466
drh1cc3d752002-03-23 00:31:29 +00001467 /* Create the destination temporary table if necessary
1468 */
drh9d2985c2005-09-08 01:58:42 +00001469 if( eDest==SRT_VirtualTab ){
danielk1977b4964b72004-05-18 01:23:38 +00001470 assert( p->pEList );
drh0342b1f2005-09-01 03:07:44 +00001471 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1472 aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 0);
drh1cc3d752002-03-23 00:31:29 +00001473 eDest = SRT_Table;
1474 }
1475
drhf46f9052002-06-22 02:33:38 +00001476 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001477 */
drh0342b1f2005-09-01 03:07:44 +00001478 pOrderBy = p->pOrderBy;
drh82c3d632000-06-06 21:56:07 +00001479 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001480 case TK_ALL: {
drh0342b1f2005-09-01 03:07:44 +00001481 if( pOrderBy==0 ){
danielk1977a2dc3b12005-02-05 12:48:48 +00001482 assert( !pPrior->pLimit );
1483 pPrior->pLimit = p->pLimit;
1484 pPrior->pOffset = p->pOffset;
danielk1977b3bce662005-01-29 08:32:43 +00001485 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001486 if( rc ){
1487 goto multi_select_end;
1488 }
drhf46f9052002-06-22 02:33:38 +00001489 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001490 p->iLimit = pPrior->iLimit;
1491 p->iOffset = pPrior->iOffset;
danielk1977a2dc3b12005-02-05 12:48:48 +00001492 p->pLimit = 0;
1493 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001494 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001495 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001496 if( rc ){
1497 goto multi_select_end;
1498 }
drhf46f9052002-06-22 02:33:38 +00001499 break;
1500 }
1501 /* For UNION ALL ... ORDER BY fall through to the next case */
1502 }
drh82c3d632000-06-06 21:56:07 +00001503 case TK_EXCEPT:
1504 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001505 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001506 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001507 int priorOp; /* The SRT_ operation to apply to prior selects */
danielk1977a2dc3b12005-02-05 12:48:48 +00001508 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
danielk1977dc1bdc42004-06-11 10:51:27 +00001509 int addr;
drh82c3d632000-06-06 21:56:07 +00001510
drhd8bc7082000-06-07 23:51:50 +00001511 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh0342b1f2005-09-01 03:07:44 +00001512 if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
drhd8bc7082000-06-07 23:51:50 +00001513 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001514 ** right.
drhd8bc7082000-06-07 23:51:50 +00001515 */
drh82c3d632000-06-06 21:56:07 +00001516 unionTab = iParm;
1517 }else{
drhd8bc7082000-06-07 23:51:50 +00001518 /* We will need to create our own temporary table to hold the
1519 ** intermediate results.
1520 */
1521 unionTab = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001522 if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001523 rc = 1;
1524 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001525 }
drh9170dd72005-07-08 17:13:46 +00001526 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, unionTab, 0);
drh0342b1f2005-09-01 03:07:44 +00001527 if( priorOp==SRT_Table ){
1528 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
1529 aSetP2[nSetP2++] = addr;
1530 }else{
1531 assert( p->addrOpenVirt[0] == -1 );
1532 p->addrOpenVirt[0] = addr;
1533 p->pRightmost->usesVirt = 1;
drhd8bc7082000-06-07 23:51:50 +00001534 }
drh0342b1f2005-09-01 03:07:44 +00001535 createSortingIndex(pParse, p, pOrderBy);
danielk197784ac9d02004-05-18 09:58:06 +00001536 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001537 }
drhd8bc7082000-06-07 23:51:50 +00001538
1539 /* Code the SELECT statements to our left
1540 */
danielk1977b3bce662005-01-29 08:32:43 +00001541 assert( !pPrior->pOrderBy );
1542 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001543 if( rc ){
1544 goto multi_select_end;
1545 }
drhd8bc7082000-06-07 23:51:50 +00001546
1547 /* Code the current SELECT statement
1548 */
1549 switch( p->op ){
1550 case TK_EXCEPT: op = SRT_Except; break;
1551 case TK_UNION: op = SRT_Union; break;
1552 case TK_ALL: op = SRT_Table; break;
1553 }
drh82c3d632000-06-06 21:56:07 +00001554 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001555 p->pOrderBy = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001556 pLimit = p->pLimit;
1557 p->pLimit = 0;
1558 pOffset = p->pOffset;
1559 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001560 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001561 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001562 p->pOrderBy = pOrderBy;
danielk1977a2dc3b12005-02-05 12:48:48 +00001563 sqlite3ExprDelete(p->pLimit);
1564 p->pLimit = pLimit;
1565 p->pOffset = pOffset;
drhbe5fd492004-12-16 21:09:16 +00001566 p->iLimit = -1;
1567 p->iOffset = -1;
danielk197784ac9d02004-05-18 09:58:06 +00001568 if( rc ){
1569 goto multi_select_end;
1570 }
1571
drhd8bc7082000-06-07 23:51:50 +00001572
1573 /* Convert the data in the temporary table into whatever form
1574 ** it is that we currently need.
1575 */
drhc926afb2002-06-20 03:38:26 +00001576 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001577 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001578 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001579 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001580 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001581 }
danielk19774adee202004-05-08 08:23:19 +00001582 iBreak = sqlite3VdbeMakeLabel(v);
1583 iCont = sqlite3VdbeMakeLabel(v);
1584 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001585 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001586 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001587 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001588 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001589 iCont, iBreak, 0);
1590 if( rc ){
1591 rc = 1;
1592 goto multi_select_end;
1593 }
danielk19774adee202004-05-08 08:23:19 +00001594 sqlite3VdbeResolveLabel(v, iCont);
1595 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1596 sqlite3VdbeResolveLabel(v, iBreak);
1597 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001598 }
1599 break;
1600 }
1601 case TK_INTERSECT: {
1602 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001603 int iCont, iBreak, iStart;
danielk1977a2dc3b12005-02-05 12:48:48 +00001604 Expr *pLimit, *pOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001605 int addr;
drh82c3d632000-06-06 21:56:07 +00001606
drhd8bc7082000-06-07 23:51:50 +00001607 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001608 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001609 ** by allocating the tables we will need.
1610 */
drh82c3d632000-06-06 21:56:07 +00001611 tab1 = pParse->nTab++;
1612 tab2 = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00001613 if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001614 rc = 1;
1615 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001616 }
drh0342b1f2005-09-01 03:07:44 +00001617 createSortingIndex(pParse, p, pOrderBy);
danielk1977dc1bdc42004-06-11 10:51:27 +00001618
drh9170dd72005-07-08 17:13:46 +00001619 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab1, 0);
drh0342b1f2005-09-01 03:07:44 +00001620 assert( p->addrOpenVirt[0] == -1 );
1621 p->addrOpenVirt[0] = addr;
1622 p->pRightmost->usesVirt = 1;
danielk197784ac9d02004-05-18 09:58:06 +00001623 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001624
1625 /* Code the SELECTs to our left into temporary table "tab1".
1626 */
danielk1977b3bce662005-01-29 08:32:43 +00001627 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
danielk197784ac9d02004-05-18 09:58:06 +00001628 if( rc ){
1629 goto multi_select_end;
1630 }
drhd8bc7082000-06-07 23:51:50 +00001631
1632 /* Code the current SELECT into temporary table "tab2"
1633 */
drh9170dd72005-07-08 17:13:46 +00001634 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab2, 0);
drh0342b1f2005-09-01 03:07:44 +00001635 assert( p->addrOpenVirt[1] == -1 );
1636 p->addrOpenVirt[1] = addr;
drh82c3d632000-06-06 21:56:07 +00001637 p->pPrior = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001638 pLimit = p->pLimit;
1639 p->pLimit = 0;
1640 pOffset = p->pOffset;
1641 p->pOffset = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001642 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001643 p->pPrior = pPrior;
danielk1977a2dc3b12005-02-05 12:48:48 +00001644 sqlite3ExprDelete(p->pLimit);
1645 p->pLimit = pLimit;
1646 p->pOffset = pOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001647 if( rc ){
1648 goto multi_select_end;
1649 }
drhd8bc7082000-06-07 23:51:50 +00001650
1651 /* Generate code to take the intersection of the two temporary
1652 ** tables.
1653 */
drh82c3d632000-06-06 21:56:07 +00001654 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001655 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001656 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001657 }
danielk19774adee202004-05-08 08:23:19 +00001658 iBreak = sqlite3VdbeMakeLabel(v);
1659 iCont = sqlite3VdbeMakeLabel(v);
1660 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001661 computeLimitRegisters(pParse, p);
drh4a9f2412005-06-12 12:01:19 +00001662 iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
danielk19774adee202004-05-08 08:23:19 +00001663 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001664 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drh0342b1f2005-09-01 03:07:44 +00001665 pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001666 iCont, iBreak, 0);
1667 if( rc ){
1668 rc = 1;
1669 goto multi_select_end;
1670 }
danielk19774adee202004-05-08 08:23:19 +00001671 sqlite3VdbeResolveLabel(v, iCont);
1672 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1673 sqlite3VdbeResolveLabel(v, iBreak);
1674 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1675 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001676 break;
1677 }
1678 }
drh8cdbf832004-08-29 16:25:03 +00001679
1680 /* Make sure all SELECTs in the statement have the same number of elements
1681 ** in their result sets.
1682 */
drh82c3d632000-06-06 21:56:07 +00001683 assert( p->pEList && pPrior->pEList );
1684 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001685 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001686 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001687 rc = 1;
1688 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001689 }
danielk197784ac9d02004-05-18 09:58:06 +00001690
drh8cdbf832004-08-29 16:25:03 +00001691 /* Set the number of columns in temporary tables
1692 */
1693 nCol = p->pEList->nExpr;
drh0342b1f2005-09-01 03:07:44 +00001694 while( nSetP2 ){
1695 sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
drh8cdbf832004-08-29 16:25:03 +00001696 }
1697
drhfbc4ee72004-08-29 01:31:05 +00001698 /* Compute collating sequences used by either the ORDER BY clause or
1699 ** by any temporary tables needed to implement the compound select.
1700 ** Attach the KeyInfo structure to all temporary tables. Invoke the
1701 ** ORDER BY processing if there is an ORDER BY clause.
drh8cdbf832004-08-29 16:25:03 +00001702 **
1703 ** This section is run by the right-most SELECT statement only.
1704 ** SELECT statements to the left always skip this part. The right-most
1705 ** SELECT might also skip this part if it has no ORDER BY clause and
1706 ** no temp tables are required.
drhfbc4ee72004-08-29 01:31:05 +00001707 */
drh0342b1f2005-09-01 03:07:44 +00001708 if( pOrderBy || p->usesVirt ){
drhfbc4ee72004-08-29 01:31:05 +00001709 int i; /* Loop counter */
1710 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
drh0342b1f2005-09-01 03:07:44 +00001711 Select *pLoop; /* For looping through SELECT statements */
1712 CollSeq **apColl;
1713 CollSeq **aCopy;
drhfbc4ee72004-08-29 01:31:05 +00001714
drh0342b1f2005-09-01 03:07:44 +00001715 assert( p->pRightmost==p );
drh4db38a72005-09-01 12:16:28 +00001716 pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*2*sizeof(CollSeq*) + nCol);
danielk1977dc1bdc42004-06-11 10:51:27 +00001717 if( !pKeyInfo ){
1718 rc = SQLITE_NOMEM;
1719 goto multi_select_end;
1720 }
1721
1722 pKeyInfo->enc = pParse->db->enc;
1723 pKeyInfo->nField = nCol;
1724
drh0342b1f2005-09-01 03:07:44 +00001725 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
1726 *apColl = multiSelectCollSeq(pParse, p, i);
1727 if( 0==*apColl ){
1728 *apColl = pParse->db->pDfltColl;
danielk1977dc1bdc42004-06-11 10:51:27 +00001729 }
1730 }
1731
drh0342b1f2005-09-01 03:07:44 +00001732 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
1733 for(i=0; i<2; i++){
1734 int addr = pLoop->addrOpenVirt[i];
1735 if( addr<0 ){
1736 /* If [0] is unused then [1] is also unused. So we can
1737 ** always safely abort as soon as the first unused slot is found */
1738 assert( pLoop->addrOpenVirt[1]<0 );
1739 break;
1740 }
1741 sqlite3VdbeChangeP2(v, addr, nCol);
1742 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
1743 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001744 }
1745
drh0342b1f2005-09-01 03:07:44 +00001746 if( pOrderBy ){
1747 struct ExprList_item *pOTerm = pOrderBy->a;
1748 int nExpr = pOrderBy->nExpr;
1749 int addr;
drh4db38a72005-09-01 12:16:28 +00001750 u8 *pSortOrder;
drh0342b1f2005-09-01 03:07:44 +00001751
1752 aCopy = (CollSeq**)&pKeyInfo[1];
drh4db38a72005-09-01 12:16:28 +00001753 pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nExpr];
drh0342b1f2005-09-01 03:07:44 +00001754 memcpy(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
1755 apColl = pKeyInfo->aColl;
drh4db38a72005-09-01 12:16:28 +00001756 for(i=0; i<pOrderBy->nExpr; i++, pOTerm++, apColl++, pSortOrder++){
drh0342b1f2005-09-01 03:07:44 +00001757 Expr *pExpr = pOTerm->pExpr;
1758 char *zName = pOTerm->zName;
danielk1977dc1bdc42004-06-11 10:51:27 +00001759 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
danielk1977dc1bdc42004-06-11 10:51:27 +00001760 if( zName ){
drh0342b1f2005-09-01 03:07:44 +00001761 *apColl = sqlite3LocateCollSeq(pParse, zName, -1);
danielk1977dc1bdc42004-06-11 10:51:27 +00001762 }else{
drh0342b1f2005-09-01 03:07:44 +00001763 *apColl = aCopy[pExpr->iColumn];
danielk1977dc1bdc42004-06-11 10:51:27 +00001764 }
drh4db38a72005-09-01 12:16:28 +00001765 *pSortOrder = pOTerm->sortOrder;
danielk1977dc1bdc42004-06-11 10:51:27 +00001766 }
drh0342b1f2005-09-01 03:07:44 +00001767 assert( p->pRightmost==p );
1768 assert( p->addrOpenVirt[2]>=0 );
1769 addr = p->addrOpenVirt[2];
drh4db38a72005-09-01 12:16:28 +00001770 sqlite3VdbeChangeP2(v, addr, p->pEList->nExpr+2);
1771 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
1772 pKeyInfo = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001773 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1774 }
1775
drh0342b1f2005-09-01 03:07:44 +00001776 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001777 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001778
1779multi_select_end:
danielk197784ac9d02004-05-18 09:58:06 +00001780 return rc;
drh22827922000-06-06 17:27:05 +00001781}
drhb7f91642004-10-31 02:22:47 +00001782#endif /* SQLITE_OMIT_COMPOUND_SELECT */
drh22827922000-06-06 17:27:05 +00001783
drhb7f91642004-10-31 02:22:47 +00001784#ifndef SQLITE_OMIT_VIEW
drh22827922000-06-06 17:27:05 +00001785/*
drh832508b2002-03-02 17:04:07 +00001786** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001787** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001788** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001789** unchanged.)
drh832508b2002-03-02 17:04:07 +00001790**
1791** This routine is part of the flattening procedure. A subquery
1792** whose result set is defined by pEList appears as entry in the
1793** FROM clause of a SELECT such that the VDBE cursor assigned to that
1794** FORM clause entry is iTable. This routine make the necessary
1795** changes to pExpr so that it refers directly to the source table
1796** of the subquery rather the result set of the subquery.
1797*/
drh6a3ea0e2003-05-02 14:32:12 +00001798static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
danielk1977b3bce662005-01-29 08:32:43 +00001799static void substSelect(Select *, int, ExprList *); /* Forward Decl */
drh6a3ea0e2003-05-02 14:32:12 +00001800static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001801 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001802 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1803 if( pExpr->iColumn<0 ){
1804 pExpr->op = TK_NULL;
1805 }else{
1806 Expr *pNew;
1807 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1808 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1809 pNew = pEList->a[pExpr->iColumn].pExpr;
1810 assert( pNew!=0 );
1811 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001812 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001813 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001814 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001815 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001816 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001817 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001818 pExpr->iTable = pNew->iTable;
1819 pExpr->iColumn = pNew->iColumn;
1820 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001821 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1822 sqlite3TokenCopy(&pExpr->span, &pNew->span);
danielk1977a1cb1832005-02-12 08:59:55 +00001823 pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
1824 pExpr->flags = pNew->flags;
drh50350a12004-02-13 16:22:22 +00001825 }
drh832508b2002-03-02 17:04:07 +00001826 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001827 substExpr(pExpr->pLeft, iTable, pEList);
1828 substExpr(pExpr->pRight, iTable, pEList);
danielk1977b3bce662005-01-29 08:32:43 +00001829 substSelect(pExpr->pSelect, iTable, pEList);
drh6a3ea0e2003-05-02 14:32:12 +00001830 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001831 }
1832}
danielk1977b3bce662005-01-29 08:32:43 +00001833static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001834 int i;
1835 if( pList==0 ) return;
1836 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001837 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001838 }
1839}
danielk1977b3bce662005-01-29 08:32:43 +00001840static void substSelect(Select *p, int iTable, ExprList *pEList){
1841 if( !p ) return;
1842 substExprList(p->pEList, iTable, pEList);
1843 substExprList(p->pGroupBy, iTable, pEList);
1844 substExprList(p->pOrderBy, iTable, pEList);
1845 substExpr(p->pHaving, iTable, pEList);
1846 substExpr(p->pWhere, iTable, pEList);
1847}
drhb7f91642004-10-31 02:22:47 +00001848#endif /* !defined(SQLITE_OMIT_VIEW) */
drh832508b2002-03-02 17:04:07 +00001849
drhb7f91642004-10-31 02:22:47 +00001850#ifndef SQLITE_OMIT_VIEW
drh832508b2002-03-02 17:04:07 +00001851/*
drh1350b032002-02-27 19:00:20 +00001852** This routine attempts to flatten subqueries in order to speed
1853** execution. It returns 1 if it makes changes and 0 if no flattening
1854** occurs.
1855**
1856** To understand the concept of flattening, consider the following
1857** query:
1858**
1859** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1860**
1861** The default way of implementing this query is to execute the
1862** subquery first and store the results in a temporary table, then
1863** run the outer query on that temporary table. This requires two
1864** passes over the data. Furthermore, because the temporary table
1865** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001866** optimized.
drh1350b032002-02-27 19:00:20 +00001867**
drh832508b2002-03-02 17:04:07 +00001868** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001869** a single flat select, like this:
1870**
1871** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1872**
1873** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001874** but only has to scan the data once. And because indices might
1875** exist on the table t1, a complete scan of the data might be
1876** avoided.
drh1350b032002-02-27 19:00:20 +00001877**
drh832508b2002-03-02 17:04:07 +00001878** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001879**
drh832508b2002-03-02 17:04:07 +00001880** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001881**
drh832508b2002-03-02 17:04:07 +00001882** (2) The subquery is not an aggregate or the outer query is not a join.
1883**
drh8af4d3a2003-05-06 20:35:16 +00001884** (3) The subquery is not the right operand of a left outer join, or
1885** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001886**
1887** (4) The subquery is not DISTINCT or the outer query is not a join.
1888**
1889** (5) The subquery is not DISTINCT or the outer query does not use
1890** aggregates.
1891**
1892** (6) The subquery does not use aggregates or the outer query is not
1893** DISTINCT.
1894**
drh08192d52002-04-30 19:20:28 +00001895** (7) The subquery has a FROM clause.
1896**
drhdf199a22002-06-14 22:38:41 +00001897** (8) The subquery does not use LIMIT or the outer query is not a join.
1898**
1899** (9) The subquery does not use LIMIT or the outer query does not use
1900** aggregates.
1901**
1902** (10) The subquery does not use aggregates or the outer query does not
1903** use LIMIT.
1904**
drh174b6192002-12-03 02:22:52 +00001905** (11) The subquery and the outer query do not both have ORDER BY clauses.
1906**
drh3fc673e2003-06-16 00:40:34 +00001907** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1908** subquery has no WHERE clause. (added by ticket #350)
1909**
drh832508b2002-03-02 17:04:07 +00001910** In this routine, the "p" parameter is a pointer to the outer query.
1911** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1912** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1913**
drh665de472003-03-31 13:36:09 +00001914** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001915** If flattening is attempted this routine returns 1.
1916**
1917** All of the expression analysis must occur on both the outer query and
1918** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001919*/
drh8c74a8c2002-08-25 19:20:40 +00001920static int flattenSubquery(
1921 Parse *pParse, /* The parsing context */
1922 Select *p, /* The parent or outer SELECT statement */
1923 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1924 int isAgg, /* True if outer SELECT uses aggregate functions */
1925 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1926){
drh0bb28102002-05-08 11:54:14 +00001927 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001928 SrcList *pSrc; /* The FROM clause of the outer query */
1929 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001930 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001931 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh91bb0ee2004-09-01 03:06:34 +00001932 int i; /* Loop counter */
1933 Expr *pWhere; /* The WHERE clause */
1934 struct SrcList_item *pSubitem; /* The subquery */
drh1350b032002-02-27 19:00:20 +00001935
drh832508b2002-03-02 17:04:07 +00001936 /* Check to see if flattening is permitted. Return 0 if not.
1937 */
1938 if( p==0 ) return 0;
1939 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001940 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh91bb0ee2004-09-01 03:06:34 +00001941 pSubitem = &pSrc->a[iFrom];
1942 pSub = pSubitem->pSelect;
drh832508b2002-03-02 17:04:07 +00001943 assert( pSub!=0 );
1944 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001945 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001946 pSubSrc = pSub->pSrc;
1947 assert( pSubSrc );
danielk1977a2dc3b12005-02-05 12:48:48 +00001948 if( (pSub->pLimit && p->pLimit) || pSub->pOffset ||
1949 (pSub->pLimit && isAgg) ) return 0;
drhc31c2eb2003-05-02 16:04:17 +00001950 if( pSubSrc->nSrc==0 ) return 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00001951 if( pSub->isDistinct && (pSrc->nSrc>1 || isAgg) ){
drhdf199a22002-06-14 22:38:41 +00001952 return 0;
1953 }
danielk1977a2dc3b12005-02-05 12:48:48 +00001954 if( p->isDistinct && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001955 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001956
drh8af4d3a2003-05-06 20:35:16 +00001957 /* Restriction 3: If the subquery is a join, make sure the subquery is
1958 ** not used as the right operand of an outer join. Examples of why this
1959 ** is not allowed:
1960 **
1961 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1962 **
1963 ** If we flatten the above, we would get
1964 **
1965 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1966 **
1967 ** which is not at all the same thing.
1968 */
1969 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1970 return 0;
1971 }
1972
drh3fc673e2003-06-16 00:40:34 +00001973 /* Restriction 12: If the subquery is the right operand of a left outer
1974 ** join, make sure the subquery has no WHERE clause.
1975 ** An examples of why this is not allowed:
1976 **
1977 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1978 **
1979 ** If we flatten the above, we would get
1980 **
1981 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1982 **
1983 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1984 ** effectively converts the OUTER JOIN into an INNER JOIN.
1985 */
1986 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1987 && pSub->pWhere!=0 ){
1988 return 0;
1989 }
1990
drh0bb28102002-05-08 11:54:14 +00001991 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001992 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001993 */
drhc31c2eb2003-05-02 16:04:17 +00001994
1995 /* Move all of the FROM elements of the subquery into the
1996 ** the FROM clause of the outer query. Before doing this, remember
1997 ** the cursor number for the original outer query FROM element in
1998 ** iParent. The iParent cursor will never be used. Subsequent code
1999 ** will scan expressions looking for iParent references and replace
2000 ** those references with expressions that resolve to the subquery FROM
2001 ** elements we are now copying in.
2002 */
drh91bb0ee2004-09-01 03:06:34 +00002003 iParent = pSubitem->iCursor;
drhc31c2eb2003-05-02 16:04:17 +00002004 {
2005 int nSubSrc = pSubSrc->nSrc;
drh91bb0ee2004-09-01 03:06:34 +00002006 int jointype = pSubitem->jointype;
drhc31c2eb2003-05-02 16:04:17 +00002007
drhed8a3bb2005-06-06 21:19:56 +00002008 sqlite3DeleteTable(0, pSubitem->pTab);
drh91bb0ee2004-09-01 03:06:34 +00002009 sqliteFree(pSubitem->zDatabase);
2010 sqliteFree(pSubitem->zName);
2011 sqliteFree(pSubitem->zAlias);
drhc31c2eb2003-05-02 16:04:17 +00002012 if( nSubSrc>1 ){
2013 int extra = nSubSrc - 1;
2014 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00002015 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00002016 }
2017 p->pSrc = pSrc;
2018 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2019 pSrc->a[i] = pSrc->a[i-extra];
2020 }
2021 }
2022 for(i=0; i<nSubSrc; i++){
2023 pSrc->a[i+iFrom] = pSubSrc->a[i];
2024 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2025 }
drh8af4d3a2003-05-06 20:35:16 +00002026 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00002027 }
2028
2029 /* Now begin substituting subquery result set expressions for
2030 ** references to the iParent in the outer query.
2031 **
2032 ** Example:
2033 **
2034 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2035 ** \ \_____________ subquery __________/ /
2036 ** \_____________________ outer query ______________________________/
2037 **
2038 ** We look at every expression in the outer query and every place we see
2039 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2040 */
drh6a3ea0e2003-05-02 14:32:12 +00002041 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00002042 pList = p->pEList;
2043 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00002044 Expr *pExpr;
2045 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
2046 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00002047 }
2048 }
drh1b2e0322002-03-03 02:49:51 +00002049 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00002050 substExprList(p->pGroupBy, iParent, pSub->pEList);
2051 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00002052 }
drh174b6192002-12-03 02:22:52 +00002053 if( pSub->pOrderBy ){
2054 assert( p->pOrderBy==0 );
2055 p->pOrderBy = pSub->pOrderBy;
2056 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00002057 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00002058 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00002059 }
drh832508b2002-03-02 17:04:07 +00002060 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002061 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00002062 }else{
2063 pWhere = 0;
2064 }
2065 if( subqueryIsAgg ){
2066 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00002067 p->pHaving = p->pWhere;
2068 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00002069 substExpr(p->pHaving, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002070 p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
drh1b2e0322002-03-03 02:49:51 +00002071 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00002072 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00002073 }else{
drh6a3ea0e2003-05-02 14:32:12 +00002074 substExpr(p->pWhere, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00002075 p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
drh832508b2002-03-02 17:04:07 +00002076 }
drhc31c2eb2003-05-02 16:04:17 +00002077
2078 /* The flattened query is distinct if either the inner or the
2079 ** outer query is distinct.
2080 */
drh832508b2002-03-02 17:04:07 +00002081 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00002082
danielk1977a58fdfb2005-02-08 07:50:40 +00002083 /*
2084 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2085 */
danielk1977a2dc3b12005-02-05 12:48:48 +00002086 if( pSub->pLimit ){
2087 p->pLimit = pSub->pLimit;
2088 pSub->pLimit = 0;
drhdf199a22002-06-14 22:38:41 +00002089 }
drh8c74a8c2002-08-25 19:20:40 +00002090
drhc31c2eb2003-05-02 16:04:17 +00002091 /* Finially, delete what is left of the subquery and return
2092 ** success.
2093 */
danielk19774adee202004-05-08 08:23:19 +00002094 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00002095 return 1;
2096}
drhb7f91642004-10-31 02:22:47 +00002097#endif /* SQLITE_OMIT_VIEW */
drh1350b032002-02-27 19:00:20 +00002098
2099/*
drh9562b552002-02-19 15:00:07 +00002100** Analyze the SELECT statement passed in as an argument to see if it
2101** is a simple min() or max() query. If it is and this query can be
2102** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00002103** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00002104** simple min() or max() query, then return 0;
2105**
2106** A simply min() or max() query looks like this:
2107**
2108** SELECT min(a) FROM table;
2109** SELECT max(a) FROM table;
2110**
2111** The query may have only a single table in its FROM argument. There
2112** can be no GROUP BY or HAVING or WHERE clauses. The result set must
2113** be the min() or max() of a single column of the table. The column
2114** in the min() or max() function must be indexed.
2115**
danielk19774adee202004-05-08 08:23:19 +00002116** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00002117** See the header comment on that routine for additional information.
2118*/
2119static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2120 Expr *pExpr;
2121 int iCol;
2122 Table *pTab;
2123 Index *pIdx;
2124 int base;
2125 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00002126 int seekOp;
2127 int cont;
drh6e175292004-03-13 14:00:36 +00002128 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00002129 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00002130 SrcList *pSrc;
drh9562b552002-02-19 15:00:07 +00002131
2132 /* Check to see if this query is a simple min() or max() query. Return
2133 ** zero if it is not.
2134 */
2135 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00002136 pSrc = p->pSrc;
2137 if( pSrc->nSrc!=1 ) return 0;
2138 pEList = p->pEList;
2139 if( pEList->nExpr!=1 ) return 0;
2140 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002141 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002142 pList = pExpr->pList;
2143 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002144 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00002145 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002146 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00002147 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002148 seekOp = OP_Last;
2149 }else{
2150 return 0;
2151 }
drh6e175292004-03-13 14:00:36 +00002152 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002153 if( pExpr->op!=TK_COLUMN ) return 0;
2154 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002155 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002156
2157 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002158 ** Check to make sure we have an index and make pIdx point to the
2159 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2160 ** key column, no index is necessary so set pIdx to NULL. If no
2161 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002162 */
2163 if( iCol<0 ){
2164 pIdx = 0;
2165 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002166 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002167 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2168 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002169 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002170 }
2171 if( pIdx==0 ) return 0;
2172 }
2173
drhe5f50722003-07-19 00:44:14 +00002174 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002175 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002176 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002177 */
danielk19774adee202004-05-08 08:23:19 +00002178 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002179 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002180
drh0c37e632004-01-30 02:01:03 +00002181 /* If the output is destined for a temporary table, open that table.
2182 */
drh9d2985c2005-09-08 01:58:42 +00002183 if( eDest==SRT_VirtualTab ){
drhd81bd4e2005-09-05 20:06:49 +00002184 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002185 }
2186
drh17f71932002-02-21 12:01:27 +00002187 /* Generating code to find the min or the max. Basically all we have
2188 ** to do is find the first or the last entry in the chosen index. If
2189 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2190 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002191 */
danielk19774adee202004-05-08 08:23:19 +00002192 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00002193 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00002194 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00002195 if( pSrc->a[0].pSelect==0 ){
drhad6d9462004-09-19 02:15:24 +00002196 sqlite3OpenTableForReading(v, base, pTab);
drh6e175292004-03-13 14:00:36 +00002197 }
danielk19774adee202004-05-08 08:23:19 +00002198 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00002199 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002200 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002201 }else{
danielk19773719d7f2005-01-17 08:57:09 +00002202 /* Even though the cursor used to open the index here is closed
2203 ** as soon as a single value has been read from it, allocate it
2204 ** using (pParse->nTab++) to prevent the cursor id from being
2205 ** reused. This is important for statements of the form
2206 ** "INSERT INTO x SELECT max() FROM x".
2207 */
2208 int iIdx;
2209 iIdx = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +00002210 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002211 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
drhd3d39e92004-05-20 22:16:29 +00002212 (char*)&pIdx->keyInfo, P3_KEYINFO);
drh9eb516c2004-07-18 20:52:32 +00002213 if( seekOp==OP_Rewind ){
drhf0863fe2005-06-12 21:35:51 +00002214 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh1af3fdb2004-07-18 21:33:01 +00002215 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2216 seekOp = OP_MoveGt;
drh9eb516c2004-07-18 20:52:32 +00002217 }
danielk19773719d7f2005-01-17 08:57:09 +00002218 sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
drhf0863fe2005-06-12 21:35:51 +00002219 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
danielk19773719d7f2005-01-17 08:57:09 +00002220 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002221 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002222 }
drh5cf8e8c2002-02-19 22:42:05 +00002223 eList.nExpr = 1;
2224 memset(&eListItem, 0, sizeof(eListItem));
2225 eList.a = &eListItem;
2226 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00002227 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00002228 sqlite3VdbeResolveLabel(v, cont);
2229 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002230
drh9562b552002-02-19 15:00:07 +00002231 return 1;
2232}
2233
2234/*
drh290c1942004-08-21 17:54:45 +00002235** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
2236** the number of errors seen.
2237**
2238** An ORDER BY or GROUP BY is a list of expressions. If any expression
2239** is an integer constant, then that expression is replaced by the
2240** corresponding entry in the result set.
2241*/
2242static int processOrderGroupBy(
danielk1977b3bce662005-01-29 08:32:43 +00002243 NameContext *pNC, /* Name context of the SELECT statement. */
drh290c1942004-08-21 17:54:45 +00002244 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
drh290c1942004-08-21 17:54:45 +00002245 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
2246){
2247 int i;
danielk1977b3bce662005-01-29 08:32:43 +00002248 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */
2249 Parse *pParse = pNC->pParse; /* The result set of the SELECT */
2250 assert( pEList );
2251
drh290c1942004-08-21 17:54:45 +00002252 if( pOrderBy==0 ) return 0;
2253 for(i=0; i<pOrderBy->nExpr; i++){
2254 int iCol;
2255 Expr *pE = pOrderBy->a[i].pExpr;
danielk1977b3bce662005-01-29 08:32:43 +00002256 if( sqlite3ExprIsInteger(pE, &iCol) ){
2257 if( iCol>0 && iCol<=pEList->nExpr ){
2258 sqlite3ExprDelete(pE);
2259 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2260 }else{
drh290c1942004-08-21 17:54:45 +00002261 sqlite3ErrorMsg(pParse,
2262 "%s BY column number %d out of range - should be "
2263 "between 1 and %d", zType, iCol, pEList->nExpr);
2264 return 1;
2265 }
2266 }
danielk1977b3bce662005-01-29 08:32:43 +00002267 if( sqlite3ExprResolveNames(pNC, pE) ){
2268 return 1;
2269 }
2270 if( sqlite3ExprIsConstant(pE) ){
2271 sqlite3ErrorMsg(pParse,
2272 "%s BY terms must not be non-integer constants", zType);
2273 return 1;
2274 }
drh290c1942004-08-21 17:54:45 +00002275 }
2276 return 0;
2277}
2278
2279/*
danielk1977b3bce662005-01-29 08:32:43 +00002280** This routine resolves any names used in the result set of the
2281** supplied SELECT statement. If the SELECT statement being resolved
2282** is a sub-select, then pOuterNC is a pointer to the NameContext
2283** of the parent SELECT.
2284*/
2285int sqlite3SelectResolve(
2286 Parse *pParse, /* The parser context */
2287 Select *p, /* The SELECT statement being coded. */
2288 NameContext *pOuterNC /* The outer name context. May be NULL. */
2289){
2290 ExprList *pEList; /* Result set. */
2291 int i; /* For-loop variable used in multiple places */
2292 NameContext sNC; /* Local name-context */
drh13449892005-09-07 21:22:45 +00002293 ExprList *pGroupBy; /* The group by clause */
danielk1977b3bce662005-01-29 08:32:43 +00002294
2295 /* If this routine has run before, return immediately. */
2296 if( p->isResolved ){
2297 assert( !pOuterNC );
2298 return SQLITE_OK;
2299 }
2300 p->isResolved = 1;
2301
2302 /* If there have already been errors, do nothing. */
2303 if( pParse->nErr>0 ){
2304 return SQLITE_ERROR;
2305 }
2306
2307 /* Prepare the select statement. This call will allocate all cursors
2308 ** required to handle the tables and subqueries in the FROM clause.
2309 */
2310 if( prepSelectStmt(pParse, p) ){
2311 return SQLITE_ERROR;
2312 }
2313
danielk1977a2dc3b12005-02-05 12:48:48 +00002314 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2315 ** are not allowed to refer to any names, so pass an empty NameContext.
2316 */
danielk1977b3bce662005-01-29 08:32:43 +00002317 sNC.pParse = pParse;
danielk1977b3bce662005-01-29 08:32:43 +00002318 sNC.hasAgg = 0;
2319 sNC.nErr = 0;
2320 sNC.nRef = 0;
2321 sNC.pEList = 0;
danielk1977a2dc3b12005-02-05 12:48:48 +00002322 sNC.allowAgg = 0;
2323 sNC.pSrcList = 0;
2324 sNC.pNext = 0;
2325 if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2326 sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2327 return SQLITE_ERROR;
2328 }
2329
2330 /* Set up the local name-context to pass to ExprResolveNames() to
2331 ** resolve the expression-list.
2332 */
2333 sNC.allowAgg = 1;
2334 sNC.pSrcList = p->pSrc;
2335 sNC.pNext = pOuterNC;
danielk1977b3bce662005-01-29 08:32:43 +00002336
danielk1977b3bce662005-01-29 08:32:43 +00002337 /* Resolve names in the result set. */
2338 pEList = p->pEList;
2339 if( !pEList ) return SQLITE_ERROR;
2340 for(i=0; i<pEList->nExpr; i++){
2341 Expr *pX = pEList->a[i].pExpr;
2342 if( sqlite3ExprResolveNames(&sNC, pX) ){
2343 return SQLITE_ERROR;
2344 }
2345 }
2346
2347 /* If there are no aggregate functions in the result-set, and no GROUP BY
2348 ** expression, do not allow aggregates in any of the other expressions.
2349 */
2350 assert( !p->isAgg );
drh13449892005-09-07 21:22:45 +00002351 pGroupBy = p->pGroupBy;
2352 if( pGroupBy || sNC.hasAgg ){
danielk1977b3bce662005-01-29 08:32:43 +00002353 p->isAgg = 1;
2354 }else{
2355 sNC.allowAgg = 0;
2356 }
2357
2358 /* If a HAVING clause is present, then there must be a GROUP BY clause.
2359 */
drh13449892005-09-07 21:22:45 +00002360 if( p->pHaving && !pGroupBy ){
danielk1977b3bce662005-01-29 08:32:43 +00002361 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2362 return SQLITE_ERROR;
2363 }
2364
2365 /* Add the expression list to the name-context before parsing the
2366 ** other expressions in the SELECT statement. This is so that
2367 ** expressions in the WHERE clause (etc.) can refer to expressions by
2368 ** aliases in the result set.
2369 **
2370 ** Minor point: If this is the case, then the expression will be
2371 ** re-evaluated for each reference to it.
2372 */
2373 sNC.pEList = p->pEList;
2374 if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2375 sqlite3ExprResolveNames(&sNC, p->pHaving) ||
2376 processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
drh13449892005-09-07 21:22:45 +00002377 processOrderGroupBy(&sNC, pGroupBy, "GROUP")
danielk1977b3bce662005-01-29 08:32:43 +00002378 ){
2379 return SQLITE_ERROR;
2380 }
2381
drh13449892005-09-07 21:22:45 +00002382 /* Make sure the GROUP BY clause does not contain aggregate functions.
2383 */
2384 if( pGroupBy ){
2385 struct ExprList_item *pItem;
2386
2387 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
2388 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
2389 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
2390 "the GROUP BY clause");
2391 return SQLITE_ERROR;
2392 }
2393 }
2394 }
2395
danielk1977b3bce662005-01-29 08:32:43 +00002396 return SQLITE_OK;
2397}
2398
2399/*
drh13449892005-09-07 21:22:45 +00002400** Reset the aggregate accumulator.
2401**
2402** The aggregate accumulator is a set of memory cells that hold
2403** intermediate results while calculating an aggregate. This
2404** routine simply stores NULLs in all of those memory cells.
danielk1977b3bce662005-01-29 08:32:43 +00002405*/
drh13449892005-09-07 21:22:45 +00002406static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
2407 Vdbe *v = pParse->pVdbe;
2408 int i;
2409 int addr;
2410 if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
2411 return;
2412 }
2413 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
2414 for(i=0; i<pAggInfo->nColumn; i++){
2415 addr = sqlite3VdbeAddOp(v, OP_MemStore, pAggInfo->aCol[i].iMem, 0);
2416 }
2417 for(i=0; i<pAggInfo->nFunc; i++){
2418 addr = sqlite3VdbeAddOp(v, OP_MemStore, pAggInfo->aFunc[i].iMem, 0);
2419 }
2420 sqlite3VdbeChangeP2(v, addr, 1);
danielk1977b3bce662005-01-29 08:32:43 +00002421}
2422
2423/*
drh13449892005-09-07 21:22:45 +00002424** Invoke the OP_AggFinalize opcode for every aggregate function
2425** in the AggInfo structure.
danielk1977b3bce662005-01-29 08:32:43 +00002426*/
drh13449892005-09-07 21:22:45 +00002427static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
2428 Vdbe *v = pParse->pVdbe;
2429 int i;
2430 struct AggInfo_func *pF;
2431 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
drha10a34b2005-09-07 22:09:48 +00002432 ExprList *pList = pF->pExpr->pList;
2433 sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
2434 (void*)pF->pFunc, P3_FUNCDEF);
drh13449892005-09-07 21:22:45 +00002435 }
danielk1977b3bce662005-01-29 08:32:43 +00002436}
drh13449892005-09-07 21:22:45 +00002437
2438/*
2439** Update the accumulator memory cells for an aggregate based on
2440** the current cursor position.
2441*/
2442static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
2443 Vdbe *v = pParse->pVdbe;
2444 int i;
2445 struct AggInfo_func *pF;
2446 struct AggInfo_col *pC;
drh13449892005-09-07 21:22:45 +00002447
2448 pAggInfo->directMode = 1;
2449 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
2450 int nArg;
2451 ExprList *pList = pF->pExpr->pList;
2452 if( pList ){
2453 nArg = pList->nExpr;
2454 sqlite3ExprCodeExprList(pParse, pList);
2455 }else{
2456 nArg = 0;
2457 }
2458 if( pF->pFunc->needCollSeq ){
2459 CollSeq *pColl = 0;
2460 struct ExprList_item *pItem;
2461 int j;
2462 for(j=0, pItem=pList->a; !pColl && j<pList->nExpr; j++, pItem++){
2463 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
2464 }
2465 if( !pColl ){
2466 pColl = pParse->db->pDfltColl;
2467 }
2468 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2469 }
2470 sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
2471 }
drh13449892005-09-07 21:22:45 +00002472 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
drh5774b802005-09-07 22:48:16 +00002473 sqlite3ExprCode(pParse, pC->pExpr);
drh13449892005-09-07 21:22:45 +00002474 sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
2475 }
2476 pAggInfo->directMode = 0;
2477}
2478
2479
danielk1977b3bce662005-01-29 08:32:43 +00002480/*
drh9bb61fe2000-06-05 16:01:39 +00002481** Generate code for the given SELECT statement.
2482**
drhfef52082000-06-06 01:50:43 +00002483** The results are distributed in various ways depending on the
2484** value of eDest and iParm.
2485**
2486** eDest Value Result
2487** ------------ -------------------------------------------
2488** SRT_Callback Invoke the callback for each row of the result.
2489**
2490** SRT_Mem Store first result in memory cell iParm
2491**
danielk1977e014a832004-05-17 10:48:57 +00002492** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002493**
drh82c3d632000-06-06 21:56:07 +00002494** SRT_Union Store results as a key in a temporary table iParm
2495**
jplyon4b11c6d2004-01-19 04:57:53 +00002496** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002497**
2498** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002499**
drhe78e8282003-01-19 03:59:45 +00002500** The table above is incomplete. Additional eDist value have be added
2501** since this comment was written. See the selectInnerLoop() function for
2502** a complete listing of the allowed values of eDest and their meanings.
2503**
drh9bb61fe2000-06-05 16:01:39 +00002504** This routine returns the number of errors. If any errors are
2505** encountered, then an appropriate error message is left in
2506** pParse->zErrMsg.
2507**
2508** This routine does NOT free the Select structure passed in. The
2509** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002510**
2511** The pParent, parentTab, and *pParentAgg fields are filled in if this
2512** SELECT is a subquery. This routine may try to combine this SELECT
2513** with its parent to form a single flat query. In so doing, it might
2514** change the parent query from a non-aggregate to an aggregate query.
2515** For that reason, the pParentAgg flag is passed as a pointer, so it
2516** can be changed.
drhe78e8282003-01-19 03:59:45 +00002517**
2518** Example 1: The meaning of the pParent parameter.
2519**
2520** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2521** \ \_______ subquery _______/ /
2522** \ /
2523** \____________________ outer query ___________________/
2524**
2525** This routine is called for the outer query first. For that call,
2526** pParent will be NULL. During the processing of the outer query, this
2527** routine is called recursively to handle the subquery. For the recursive
2528** call, pParent will point to the outer query. Because the subquery is
2529** the second element in a three-way join, the parentTab parameter will
2530** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002531*/
danielk19774adee202004-05-08 08:23:19 +00002532int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002533 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002534 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002535 int eDest, /* How to dispose of the results */
2536 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002537 Select *pParent, /* Another SELECT for which this is a sub-query */
2538 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002539 int *pParentAgg, /* True if pParent uses aggregate functions */
danielk1977b3bce662005-01-29 08:32:43 +00002540 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002541){
drh13449892005-09-07 21:22:45 +00002542 int i, j; /* Loop counters */
2543 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
2544 Vdbe *v; /* The virtual machine under construction */
danielk1977b3bce662005-01-29 08:32:43 +00002545 int isAgg; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002546 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002547 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002548 Expr *pWhere; /* The WHERE clause. May be NULL */
2549 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002550 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2551 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002552 int isDistinct; /* True if the DISTINCT keyword is present */
2553 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002554 int rc = 1; /* Value to return from this function */
drh9d2985c2005-09-08 01:58:42 +00002555 int addrSortIndex; /* Address of an OP_OpenVirtual instruction */
drh13449892005-09-07 21:22:45 +00002556 AggInfo sAggInfo; /* Information used by aggregate queries */
drh9bb61fe2000-06-05 16:01:39 +00002557
danielk19776f8a5032004-05-10 10:34:51 +00002558 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002559 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drh13449892005-09-07 21:22:45 +00002560 memset(&sAggInfo, 0, sizeof(sAggInfo));
drhdaffd0e2001-04-11 14:28:42 +00002561
drhb7f91642004-10-31 02:22:47 +00002562#ifndef SQLITE_OMIT_COMPOUND_SELECT
drh82c3d632000-06-06 21:56:07 +00002563 /* If there is are a sequence of queries, do the earlier ones first.
2564 */
2565 if( p->pPrior ){
drh0342b1f2005-09-01 03:07:44 +00002566 if( p->pRightmost==0 ){
2567 Select *pLoop;
2568 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
2569 pLoop->pRightmost = p;
2570 }
2571 }
danielk197784ac9d02004-05-18 09:58:06 +00002572 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002573 }
drhb7f91642004-10-31 02:22:47 +00002574#endif
drh82c3d632000-06-06 21:56:07 +00002575
danielk1977b3bce662005-01-29 08:32:43 +00002576 pOrderBy = p->pOrderBy;
drh13449892005-09-07 21:22:45 +00002577 if( IgnorableOrderby(eDest) ){
danielk1977b3bce662005-01-29 08:32:43 +00002578 p->pOrderBy = 0;
2579 }
2580 if( sqlite3SelectResolve(pParse, p, 0) ){
2581 goto select_end;
2582 }
2583 p->pOrderBy = pOrderBy;
2584
drh82c3d632000-06-06 21:56:07 +00002585 /* Make local copies of the parameters for this query.
2586 */
drh9bb61fe2000-06-05 16:01:39 +00002587 pTabList = p->pSrc;
2588 pWhere = p->pWhere;
drh22827922000-06-06 17:27:05 +00002589 pGroupBy = p->pGroupBy;
2590 pHaving = p->pHaving;
danielk1977b3bce662005-01-29 08:32:43 +00002591 isAgg = p->isAgg;
drh19a775c2000-06-05 18:54:46 +00002592 isDistinct = p->isDistinct;
danielk1977b3bce662005-01-29 08:32:43 +00002593 pEList = p->pEList;
2594 if( pEList==0 ) goto select_end;
drh9bb61fe2000-06-05 16:01:39 +00002595
2596 /*
2597 ** Do not even attempt to generate any code if we have already seen
2598 ** errors before this routine starts.
2599 */
drh1d83f052002-02-17 00:30:36 +00002600 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002601
drh22827922000-06-06 17:27:05 +00002602 /* If writing to memory or generating a set
2603 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002604 */
drh51522cd2005-01-20 13:36:19 +00002605 assert( eDest!=SRT_Exists || pEList->nExpr==1 );
danielk197793758c82005-01-21 08:13:14 +00002606#ifndef SQLITE_OMIT_SUBQUERY
drhfef52082000-06-06 01:50:43 +00002607 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002608 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002609 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002610 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002611 }
danielk197793758c82005-01-21 08:13:14 +00002612#endif
drh19a775c2000-06-05 18:54:46 +00002613
drhc926afb2002-06-20 03:38:26 +00002614 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002615 */
drh13449892005-09-07 21:22:45 +00002616 if( IgnorableOrderby(eDest) ){
2617 pOrderBy = 0;
drh22827922000-06-06 17:27:05 +00002618 }
2619
drhd820cb12002-02-18 03:21:45 +00002620 /* Begin generating code.
2621 */
danielk19774adee202004-05-08 08:23:19 +00002622 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002623 if( v==0 ) goto select_end;
2624
drhe78e8282003-01-19 03:59:45 +00002625 /* Identify column names if we will be using them in a callback. This
2626 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002627 */
2628 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002629 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002630 }
2631
drhd820cb12002-02-18 03:21:45 +00002632 /* Generate code for all sub-queries in the FROM clause
2633 */
drh51522cd2005-01-20 13:36:19 +00002634#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
drhad3cab52002-05-24 02:04:32 +00002635 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002636 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002637 int needRestoreContext;
drh13449892005-09-07 21:22:45 +00002638 struct SrcList_item *pItem = &pTabList->a[i];
drhc31c2eb2003-05-02 16:04:17 +00002639
drh13449892005-09-07 21:22:45 +00002640 if( pItem->pSelect==0 ) continue;
2641 if( pItem->zName!=0 ){
drh5cf590c2003-04-24 01:45:04 +00002642 zSavedAuthContext = pParse->zAuthContext;
drh13449892005-09-07 21:22:45 +00002643 pParse->zAuthContext = pItem->zName;
drhc31c2eb2003-05-02 16:04:17 +00002644 needRestoreContext = 1;
2645 }else{
2646 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002647 }
drh9d2985c2005-09-08 01:58:42 +00002648 sqlite3Select(pParse, pItem->pSelect, SRT_VirtualTab,
drh13449892005-09-07 21:22:45 +00002649 pItem->iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002650 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002651 pParse->zAuthContext = zSavedAuthContext;
2652 }
drh1b2e0322002-03-03 02:49:51 +00002653 pTabList = p->pSrc;
2654 pWhere = p->pWhere;
drh13449892005-09-07 21:22:45 +00002655 if( !IgnorableOrderby(eDest) ){
drhacd4c692002-03-07 02:02:51 +00002656 pOrderBy = p->pOrderBy;
2657 }
drh1b2e0322002-03-03 02:49:51 +00002658 pGroupBy = p->pGroupBy;
2659 pHaving = p->pHaving;
2660 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002661 }
drh51522cd2005-01-20 13:36:19 +00002662#endif
drhd820cb12002-02-18 03:21:45 +00002663
drh6e175292004-03-13 14:00:36 +00002664 /* Check for the special case of a min() or max() function by itself
2665 ** in the result set.
2666 */
2667 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2668 rc = 0;
2669 goto select_end;
2670 }
2671
drh832508b2002-03-02 17:04:07 +00002672 /* Check to see if this is a subquery that can be "flattened" into its parent.
2673 ** If flattening is a possiblity, do so and return immediately.
2674 */
drhb7f91642004-10-31 02:22:47 +00002675#ifndef SQLITE_OMIT_VIEW
drh1b2e0322002-03-03 02:49:51 +00002676 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002677 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002678 if( isAgg ) *pParentAgg = 1;
danielk1977b3bce662005-01-29 08:32:43 +00002679 goto select_end;
drh832508b2002-03-02 17:04:07 +00002680 }
drhb7f91642004-10-31 02:22:47 +00002681#endif
drh832508b2002-03-02 17:04:07 +00002682
danielk19777cedc8d2004-06-10 10:50:08 +00002683 /* If there is an ORDER BY clause, resolve any collation sequences
drh9d2985c2005-09-08 01:58:42 +00002684 ** names that have been explicitly specified and create a sorting index.
2685 **
2686 ** This sorting index might end up being unused if the data can be
2687 ** extracted in pre-sorted order. If that is the case, then the
2688 ** OP_OpenVirtual instruction will be changed to an OP_Noop once
2689 ** we figure out that the sorting index is not needed. The addrSortIndex
2690 ** variable is used to facilitate that change.
danielk19777cedc8d2004-06-10 10:50:08 +00002691 */
2692 if( pOrderBy ){
drh5d9a4af2005-08-30 00:54:01 +00002693 struct ExprList_item *pTerm;
drh0342b1f2005-09-01 03:07:44 +00002694 KeyInfo *pKeyInfo;
drh5d9a4af2005-08-30 00:54:01 +00002695 for(i=0, pTerm=pOrderBy->a; i<pOrderBy->nExpr; i++, pTerm++){
2696 if( pTerm->zName ){
2697 pTerm->pExpr->pColl = sqlite3LocateCollSeq(pParse, pTerm->zName, -1);
danielk19777cedc8d2004-06-10 10:50:08 +00002698 }
2699 }
2700 if( pParse->nErr ){
2701 goto select_end;
2702 }
drh0342b1f2005-09-01 03:07:44 +00002703 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
drh9d2985c2005-09-08 01:58:42 +00002704 pOrderBy->iECursor = pParse->nTab++;
2705 p->addrOpenVirt[2] = addrSortIndex =
2706 sqlite3VdbeOp3(v, OP_OpenVirtual, pOrderBy->iECursor, pOrderBy->nExpr+2,
drh0342b1f2005-09-01 03:07:44 +00002707 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drh9d2985c2005-09-08 01:58:42 +00002708 }else{
2709 addrSortIndex = -1;
danielk19777cedc8d2004-06-10 10:50:08 +00002710 }
2711
drh7b58dae2003-07-20 01:16:46 +00002712 /* Set the limiter.
2713 */
2714 computeLimitRegisters(pParse, p);
2715
drh2d0794e2002-03-03 03:03:52 +00002716 /* If the output is destined for a temporary table, open that table.
2717 */
drh9d2985c2005-09-08 01:58:42 +00002718 if( eDest==SRT_VirtualTab ){
drh0342b1f2005-09-01 03:07:44 +00002719 sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002720 }
2721
drhcce7d172000-05-31 15:34:51 +00002722
drh51522cd2005-01-20 13:36:19 +00002723 /* Initialize the memory cell to NULL for SRT_Mem or 0 for SRT_Exists
drh19a775c2000-06-05 18:54:46 +00002724 */
drh51522cd2005-01-20 13:36:19 +00002725 if( eDest==SRT_Mem || eDest==SRT_Exists ){
drhf0863fe2005-06-12 21:35:51 +00002726 sqlite3VdbeAddOp(v, eDest==SRT_Mem ? OP_Null : OP_Integer, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00002727 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002728 }
2729
drhdece1a82005-08-31 18:20:00 +00002730 /* Open a virtual index to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002731 */
drh19a775c2000-06-05 18:54:46 +00002732 if( isDistinct ){
drh0342b1f2005-09-01 03:07:44 +00002733 KeyInfo *pKeyInfo;
drh832508b2002-03-02 17:04:07 +00002734 distinct = pParse->nTab++;
drh0342b1f2005-09-01 03:07:44 +00002735 pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
2736 sqlite3VdbeOp3(v, OP_OpenVirtual, distinct, 0,
2737 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drh832508b2002-03-02 17:04:07 +00002738 }else{
2739 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002740 }
drh832508b2002-03-02 17:04:07 +00002741
drh13449892005-09-07 21:22:45 +00002742 /* Aggregate and non-aggregate queries are handled differently */
2743 if( !isAgg && pGroupBy==0 ){
2744 /* This case is for non-aggregate queries
2745 ** Begin the database scan
2746 */
2747 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
2748 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002749
drh9d2985c2005-09-08 01:58:42 +00002750 /* If sorting index that was created by a prior OP_OpenVirtual
2751 ** instruction ended up not being needed, then change the OP_OpenVirtual
2752 ** into an OP_Noop.
2753 */
2754 if( addrSortIndex>=0 && pOrderBy==0 ){
2755 uncreateSortingIndex(pParse, addrSortIndex);
2756 p->addrOpenVirt[2] = -1;
2757 }
2758
drh13449892005-09-07 21:22:45 +00002759 /* Use the standard inner loop
2760 */
drhdf199a22002-06-14 22:38:41 +00002761 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002762 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002763 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002764 }
drhefb72512000-05-31 20:00:52 +00002765
drh13449892005-09-07 21:22:45 +00002766 /* End the database scan loop.
2767 */
2768 sqlite3WhereEnd(pWInfo);
2769 }else{
2770 /* This is the processing for aggregate queries */
2771 NameContext sNC; /* Name context for processing aggregate information */
2772 int iAMem; /* First Mem address for storing current GROUP BY */
2773 int iBMem; /* First Mem address for previous GROUP BY */
2774 int iUseFlag; /* Mem address holding flag indicating that at least
2775 ** one row of the input to the aggregator has been
2776 ** processed */
2777 int iAbortFlag; /* Mem address which causes query abort if positive */
2778 int groupBySort; /* Rows come from source in GROUP BY order */
drhcce7d172000-05-31 15:34:51 +00002779
drhcce7d172000-05-31 15:34:51 +00002780
drh13449892005-09-07 21:22:45 +00002781 /* The following variables hold addresses or labels for parts of the
2782 ** virtual machine program we are putting together */
2783 int addrOutputRow; /* Start of subroutine that outputs a result row */
2784 int addrSetAbort; /* Set the abort flag and return */
2785 int addrInitializeLoop; /* Start of code that initializes the input loop */
2786 int addrTopOfLoop; /* Top of the input loop */
2787 int addrGroupByChange; /* Code that runs when any GROUP BY term changes */
2788 int addrProcessRow; /* Code to process a single input row */
2789 int addrEnd; /* End of all processing */
2790 int addrSortingIdx; /* The OP_OpenVirtual for the sorting index */
2791
2792 addrEnd = sqlite3VdbeMakeLabel(v);
2793
2794 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
2795 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
2796 ** SELECT statement.
2797 */
2798 memset(&sNC, 0, sizeof(sNC));
2799 sNC.pParse = pParse;
2800 sNC.pSrcList = pTabList;
2801 sNC.pAggInfo = &sAggInfo;
2802 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
drh9d2985c2005-09-08 01:58:42 +00002803 sAggInfo.pGroupBy = pGroupBy;
drh13449892005-09-07 21:22:45 +00002804 if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
drh1d83f052002-02-17 00:30:36 +00002805 goto select_end;
drh22827922000-06-06 17:27:05 +00002806 }
drh13449892005-09-07 21:22:45 +00002807 if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
2808 goto select_end;
2809 }
2810 if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
2811 goto select_end;
2812 }
2813 sAggInfo.nAccumulator = sAggInfo.nColumn;
2814 for(i=0; i<sAggInfo.nFunc; i++){
2815 if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
2816 goto select_end;
2817 }
2818 }
drh5360ad32005-09-08 00:13:27 +00002819 if( sqlite3_malloc_failed ) goto select_end;
drh13449892005-09-07 21:22:45 +00002820
2821 /* Processing for aggregates with GROUP BY is very different and
2822 ** much more complex tha aggregates without a GROUP BY.
2823 */
2824 if( pGroupBy ){
2825 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
2826
2827 /* Create labels that we will be needing
2828 */
2829
2830 addrInitializeLoop = sqlite3VdbeMakeLabel(v);
2831 addrGroupByChange = sqlite3VdbeMakeLabel(v);
2832 addrProcessRow = sqlite3VdbeMakeLabel(v);
2833
2834 /* If there is a GROUP BY clause we might need a sorting index to
2835 ** implement it. Allocate that sorting index now. If it turns out
2836 ** that we do not need it after all, the OpenVirtual instruction
2837 ** will be converted into a Noop.
2838 */
2839 sAggInfo.sortingIdx = pParse->nTab++;
2840 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
2841 addrSortingIdx =
2842 sqlite3VdbeOp3(v, OP_OpenVirtual, sAggInfo.sortingIdx,
2843 sAggInfo.nSortingColumn,
2844 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
2845
2846 /* Initialize memory locations used by GROUP BY aggregate processing
2847 */
2848 iUseFlag = pParse->nMem++;
2849 iAbortFlag = pParse->nMem++;
2850 iAMem = pParse->nMem;
2851 pParse->nMem += pGroupBy->nExpr;
2852 iBMem = pParse->nMem;
2853 pParse->nMem += pGroupBy->nExpr;
2854 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
2855 sqlite3VdbeAddOp(v, OP_MemStore, iAbortFlag, 0);
2856 sqlite3VdbeAddOp(v, OP_MemStore, iUseFlag, 1);
2857 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
2858 sqlite3VdbeAddOp(v, OP_MemStore, iAMem, 1);
2859 sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
2860
2861 /* Generate a subroutine that outputs a single row of the result
2862 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
2863 ** is less than or equal to zero, the subroutine is a no-op. If
2864 ** the processing calls for the query to abort, this subroutine
2865 ** increments the iAbortFlag memory location before returning in
2866 ** order to signal the caller to abort.
2867 */
2868 addrSetAbort = sqlite3VdbeCurrentAddr(v);
2869 sqlite3VdbeAddOp(v, OP_MemIncr, iAbortFlag, 0);
2870 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2871 addrOutputRow = sqlite3VdbeCurrentAddr(v);
2872 sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
2873 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2874 finalizeAggFunctions(pParse, &sAggInfo);
2875 if( pHaving ){
2876 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
2877 }
2878 rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
2879 distinct, eDest, iParm,
2880 addrOutputRow+1, addrSetAbort, aff);
2881 if( rc ){
2882 goto select_end;
2883 }
2884 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
2885
2886 /* Begin a loop that will extract all source rows in GROUP BY order.
2887 ** This might involve two separate loops with an OP_Sort in between, or
2888 ** it might be a single loop that uses an index to extract information
2889 ** in the right order to begin with.
2890 */
2891 sqlite3VdbeResolveLabel(v, addrInitializeLoop);
2892 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
drh5360ad32005-09-08 00:13:27 +00002893 if( pWInfo==0 ) goto select_end;
drh13449892005-09-07 21:22:45 +00002894 if( pGroupBy==0 ){
2895 /* The optimizer is able to deliver rows in group by order so
2896 ** we do not have to sort. The OP_OpenVirtual table will be
2897 ** cancelled later because we still need to use the pKeyInfo
2898 */
2899 pGroupBy = p->pGroupBy;
2900 groupBySort = 0;
2901 }else{
2902 /* Rows are coming out in undetermined order. We have to push
2903 ** each row into a sorting index, terminate the first loop,
2904 ** then loop over the sorting index in order to get the output
2905 ** in sorted order
2906 */
2907 groupBySort = 1;
2908 sqlite3ExprCodeExprList(pParse, pGroupBy);
2909 sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
2910 j = pGroupBy->nExpr+1;
2911 for(i=0; i<sAggInfo.nColumn; i++){
2912 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
2913 if( pCol->iSorterColumn<j ) continue;
2914 if( pCol->iColumn<0 ){
2915 sqlite3VdbeAddOp(v, OP_Rowid, pCol->iTable, 0);
2916 }else{
2917 sqlite3VdbeAddOp(v, OP_Column, pCol->iTable, pCol->iColumn);
2918 }
2919 j++;
2920 }
2921 sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
2922 sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
2923 sqlite3WhereEnd(pWInfo);
drh97571952005-09-08 12:57:28 +00002924 sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
drh13449892005-09-07 21:22:45 +00002925 sAggInfo.useSortingIdx = 1;
2926 }
2927
2928 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
2929 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
2930 ** Then compare the current GROUP BY terms against the GROUP BY terms
2931 ** from the previous row currently stored in a0, a1, a2...
2932 */
2933 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
2934 for(j=0; j<pGroupBy->nExpr; j++){
2935 if( groupBySort ){
2936 sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
2937 }else{
2938 sAggInfo.directMode = 1;
2939 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
2940 }
2941 sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
2942 }
2943 for(j=pGroupBy->nExpr-1; j>=0; j--){
2944 if( j<pGroupBy->nExpr-1 ){
2945 sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
2946 }
2947 sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
2948 if( j==0 ){
2949 sqlite3VdbeAddOp(v, OP_Eq, 0, addrProcessRow);
2950 }else{
2951 sqlite3VdbeAddOp(v, OP_Ne, 0x100, addrGroupByChange);
2952 }
2953 sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
2954 }
2955
2956 /* Generate code that runs whenever the GROUP BY changes.
2957 ** Change in the GROUP BY are detected by the previous code
2958 ** block. If there were no changes, this block is skipped.
2959 **
2960 ** This code copies current group by terms in b0,b1,b2,...
2961 ** over to a0,a1,a2. It then calls the output subroutine
2962 ** and resets the aggregate accumulator registers in preparation
2963 ** for the next GROUP BY batch.
2964 */
2965 sqlite3VdbeResolveLabel(v, addrGroupByChange);
2966 for(j=0; j<pGroupBy->nExpr; j++){
2967 sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
2968 sqlite3VdbeAddOp(v, OP_MemStore, iAMem+j, 1);
2969 }
2970 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
2971 sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
2972 resetAccumulator(pParse, &sAggInfo);
2973
2974 /* Update the aggregate accumulators based on the content of
2975 ** the current row
2976 */
2977 sqlite3VdbeResolveLabel(v, addrProcessRow);
2978 updateAccumulator(pParse, &sAggInfo);
2979 sqlite3VdbeAddOp(v, OP_MemIncr, iUseFlag, 0);
2980
2981 /* End of the loop
2982 */
2983 if( groupBySort ){
2984 sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
2985 }else{
2986 sqlite3WhereEnd(pWInfo);
2987 uncreateSortingIndex(pParse, addrSortingIdx);
2988 }
2989
2990 /* Output the final row of result
2991 */
2992 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
2993
2994 } /* endif pGroupBy */
2995 else {
2996 /* This case runs if the aggregate has no GROUP BY clause. The
2997 ** processing is much simpler since there is only a single row
2998 ** of output.
2999 */
3000 resetAccumulator(pParse, &sAggInfo);
3001 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
drh5360ad32005-09-08 00:13:27 +00003002 if( pWInfo==0 ) goto select_end;
drh13449892005-09-07 21:22:45 +00003003 updateAccumulator(pParse, &sAggInfo);
3004 sqlite3WhereEnd(pWInfo);
3005 finalizeAggFunctions(pParse, &sAggInfo);
3006 pOrderBy = 0;
drh5774b802005-09-07 22:48:16 +00003007 if( pHaving ){
3008 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
3009 }
drh13449892005-09-07 21:22:45 +00003010 selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
3011 eDest, iParm, addrEnd, addrEnd, aff);
3012 }
3013 sqlite3VdbeResolveLabel(v, addrEnd);
3014
3015 } /* endif aggregate query */
drh22827922000-06-06 17:27:05 +00003016
drhcce7d172000-05-31 15:34:51 +00003017 /* If there is an ORDER BY clause, then we need to sort the results
3018 ** and send them to the callback one by one.
3019 */
3020 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00003021 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00003022 }
drh6a535342001-10-19 16:44:56 +00003023
danielk197793758c82005-01-21 08:13:14 +00003024#ifndef SQLITE_OMIT_SUBQUERY
drhf620b4e2004-02-09 14:37:50 +00003025 /* If this was a subquery, we have now converted the subquery into a
3026 ** temporary table. So delete the subquery structure from the parent
3027 ** to prevent this subquery from being evaluated again and to force the
3028 ** the use of the temporary table.
3029 */
3030 if( pParent ){
3031 assert( pParent->pSrc->nSrc>parentTab );
3032 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00003033 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00003034 pParent->pSrc->a[parentTab].pSelect = 0;
3035 }
danielk197793758c82005-01-21 08:13:14 +00003036#endif
drhf620b4e2004-02-09 14:37:50 +00003037
drh1d83f052002-02-17 00:30:36 +00003038 /* The SELECT was successfully coded. Set the return code to 0
3039 ** to indicate no errors.
3040 */
3041 rc = 0;
3042
3043 /* Control jumps to here if an error is encountered above, or upon
3044 ** successful coding of the SELECT.
3045 */
3046select_end:
drh13449892005-09-07 21:22:45 +00003047 sqliteFree(sAggInfo.aCol);
3048 sqliteFree(sAggInfo.aFunc);
drh1d83f052002-02-17 00:30:36 +00003049 return rc;
drhcce7d172000-05-31 15:34:51 +00003050}