blob: 265a4022844da08c59d06edfbb06d6a124bed386 [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**
drhad6d9462004-09-19 02:15:24 +000015** $Id: select.c,v 1.209 2004/09/19 02:15:26 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
drh315555c2002-10-20 15:53:03 +000019
drhcce7d172000-05-31 15:34:51 +000020/*
drh9bb61fe2000-06-05 16:01:39 +000021** Allocate a new Select structure and return a pointer to that
22** structure.
drhcce7d172000-05-31 15:34:51 +000023*/
danielk19774adee202004-05-08 08:23:19 +000024Select *sqlite3SelectNew(
drhdaffd0e2001-04-11 14:28:42 +000025 ExprList *pEList, /* which columns to include in the result */
drhad3cab52002-05-24 02:04:32 +000026 SrcList *pSrc, /* the FROM clause -- which tables to scan */
drhdaffd0e2001-04-11 14:28:42 +000027 Expr *pWhere, /* the WHERE clause */
28 ExprList *pGroupBy, /* the GROUP BY clause */
29 Expr *pHaving, /* the HAVING clause */
30 ExprList *pOrderBy, /* the ORDER BY clause */
drh9bbca4c2001-11-06 04:00:18 +000031 int isDistinct, /* true if the DISTINCT keyword is present */
32 int nLimit, /* LIMIT value. -1 means not used */
drhef0cae52003-07-16 02:19:37 +000033 int nOffset /* OFFSET value. 0 means no offset */
drh9bb61fe2000-06-05 16:01:39 +000034){
35 Select *pNew;
36 pNew = sqliteMalloc( sizeof(*pNew) );
drhdaffd0e2001-04-11 14:28:42 +000037 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +000038 sqlite3ExprListDelete(pEList);
39 sqlite3SrcListDelete(pSrc);
40 sqlite3ExprDelete(pWhere);
41 sqlite3ExprListDelete(pGroupBy);
42 sqlite3ExprDelete(pHaving);
43 sqlite3ExprListDelete(pOrderBy);
drhdaffd0e2001-04-11 14:28:42 +000044 }else{
drhb733d032004-01-24 20:18:12 +000045 if( pEList==0 ){
danielk19774adee202004-05-08 08:23:19 +000046 pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
drhb733d032004-01-24 20:18:12 +000047 }
drhdaffd0e2001-04-11 14:28:42 +000048 pNew->pEList = pEList;
49 pNew->pSrc = pSrc;
50 pNew->pWhere = pWhere;
51 pNew->pGroupBy = pGroupBy;
52 pNew->pHaving = pHaving;
53 pNew->pOrderBy = pOrderBy;
54 pNew->isDistinct = isDistinct;
55 pNew->op = TK_SELECT;
drh9bbca4c2001-11-06 04:00:18 +000056 pNew->nLimit = nLimit;
57 pNew->nOffset = nOffset;
drh7b58dae2003-07-20 01:16:46 +000058 pNew->iLimit = -1;
59 pNew->iOffset = -1;
drhdaffd0e2001-04-11 14:28:42 +000060 }
drh9bb61fe2000-06-05 16:01:39 +000061 return pNew;
62}
63
64/*
drh01f3f252002-05-24 16:14:15 +000065** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
66** type of join. Return an integer constant that expresses that type
67** in terms of the following bit values:
68**
69** JT_INNER
70** JT_OUTER
71** JT_NATURAL
72** JT_LEFT
73** JT_RIGHT
74**
75** A full outer join is the combination of JT_LEFT and JT_RIGHT.
76**
77** If an illegal or unsupported join type is seen, then still return
78** a join type, but put an error in the pParse structure.
79*/
danielk19774adee202004-05-08 08:23:19 +000080int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
drh01f3f252002-05-24 16:14:15 +000081 int jointype = 0;
82 Token *apAll[3];
83 Token *p;
84 static struct {
85 const char *zKeyword;
drh290c1942004-08-21 17:54:45 +000086 u8 nChar;
87 u8 code;
drh01f3f252002-05-24 16:14:15 +000088 } keywords[] = {
89 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000090 { "left", 4, JT_LEFT|JT_OUTER },
91 { "right", 5, JT_RIGHT|JT_OUTER },
92 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +000093 { "outer", 5, JT_OUTER },
94 { "inner", 5, JT_INNER },
95 { "cross", 5, JT_INNER },
96 };
97 int i, j;
98 apAll[0] = pA;
99 apAll[1] = pB;
100 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +0000101 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +0000102 p = apAll[i];
103 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
104 if( p->n==keywords[j].nChar
danielk19774adee202004-05-08 08:23:19 +0000105 && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
drh01f3f252002-05-24 16:14:15 +0000106 jointype |= keywords[j].code;
107 break;
108 }
109 }
110 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
111 jointype |= JT_ERROR;
112 break;
113 }
114 }
drhad2d8302002-05-24 20:31:36 +0000115 if(
116 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000117 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000118 ){
drh01f3f252002-05-24 16:14:15 +0000119 static Token dummy = { 0, 0 };
120 char *zSp1 = " ", *zSp2 = " ";
121 if( pB==0 ){ pB = &dummy; zSp1 = 0; }
122 if( pC==0 ){ pC = &dummy; zSp2 = 0; }
danielk19774adee202004-05-08 08:23:19 +0000123 sqlite3SetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
drh03c89882004-09-08 15:09:40 +0000124 pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, (char*)0);
drh01f3f252002-05-24 16:14:15 +0000125 pParse->nErr++;
126 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000127 }else if( jointype & JT_RIGHT ){
danielk19774adee202004-05-08 08:23:19 +0000128 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000129 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000130 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000131 }
132 return jointype;
133}
134
135/*
drhad2d8302002-05-24 20:31:36 +0000136** Return the index of a column in a table. Return -1 if the column
137** is not contained in the table.
138*/
139static int columnIndex(Table *pTab, const char *zCol){
140 int i;
141 for(i=0; i<pTab->nCol; i++){
danielk19774adee202004-05-08 08:23:19 +0000142 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
drhad2d8302002-05-24 20:31:36 +0000143 }
144 return -1;
145}
146
147/*
drh91bb0ee2004-09-01 03:06:34 +0000148** Set the value of a token to a '\000'-terminated string.
149*/
150static void setToken(Token *p, const char *z){
151 p->z = z;
152 p->n = strlen(z);
153 p->dyn = 0;
154}
155
156
157/*
drhad2d8302002-05-24 20:31:36 +0000158** Add a term to the WHERE expression in *ppExpr that requires the
159** zCol column to be equal in the two tables pTab1 and pTab2.
160*/
161static void addWhereTerm(
162 const char *zCol, /* Name of the column */
163 const Table *pTab1, /* First table */
164 const Table *pTab2, /* Second table */
165 Expr **ppExpr /* Add the equality term to this expression */
166){
167 Token dummy;
168 Expr *pE1a, *pE1b, *pE1c;
169 Expr *pE2a, *pE2b, *pE2c;
170 Expr *pE;
171
drh91bb0ee2004-09-01 03:06:34 +0000172 setToken(&dummy, zCol);
danielk19774adee202004-05-08 08:23:19 +0000173 pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy);
174 pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy);
drh91bb0ee2004-09-01 03:06:34 +0000175 setToken(&dummy, pTab1->zName);
danielk19774adee202004-05-08 08:23:19 +0000176 pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy);
drh91bb0ee2004-09-01 03:06:34 +0000177 setToken(&dummy, pTab2->zName);
danielk19774adee202004-05-08 08:23:19 +0000178 pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy);
179 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
180 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
181 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000182 ExprSetProperty(pE, EP_FromJoin);
drh91bb0ee2004-09-01 03:06:34 +0000183 *ppExpr = sqlite3ExprAnd(*ppExpr, pE);
drhad2d8302002-05-24 20:31:36 +0000184}
185
186/*
drh1f162302002-10-27 19:35:33 +0000187** Set the EP_FromJoin property on all terms of the given expression.
drh1cc093c2002-06-24 22:01:57 +0000188**
drhe78e8282003-01-19 03:59:45 +0000189** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000190** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000191** join restriction specified in the ON or USING clause and not a part
192** of the more general WHERE clause. These terms are moved over to the
193** WHERE clause during join processing but we need to remember that they
194** originated in the ON or USING clause.
drh1cc093c2002-06-24 22:01:57 +0000195*/
196static void setJoinExpr(Expr *p){
197 while( p ){
drh1f162302002-10-27 19:35:33 +0000198 ExprSetProperty(p, EP_FromJoin);
drh1cc093c2002-06-24 22:01:57 +0000199 setJoinExpr(p->pLeft);
200 p = p->pRight;
201 }
202}
203
204/*
drhad2d8302002-05-24 20:31:36 +0000205** This routine processes the join information for a SELECT statement.
206** ON and USING clauses are converted into extra terms of the WHERE clause.
207** NATURAL joins also create extra WHERE clause terms.
208**
drh91bb0ee2004-09-01 03:06:34 +0000209** The terms of a FROM clause are contained in the Select.pSrc structure.
210** The left most table is the first entry in Select.pSrc. The right-most
211** table is the last entry. The join operator is held in the entry to
212** the left. Thus entry 0 contains the join operator for the join between
213** entries 0 and 1. Any ON or USING clauses associated with the join are
214** also attached to the left entry.
215**
drhad2d8302002-05-24 20:31:36 +0000216** This routine returns the number of errors encountered.
217*/
218static int sqliteProcessJoin(Parse *pParse, Select *p){
drh91bb0ee2004-09-01 03:06:34 +0000219 SrcList *pSrc; /* All tables in the FROM clause */
220 int i, j; /* Loop counters */
221 struct SrcList_item *pLeft; /* Left table being joined */
222 struct SrcList_item *pRight; /* Right table being joined */
drhad2d8302002-05-24 20:31:36 +0000223
drh91bb0ee2004-09-01 03:06:34 +0000224 pSrc = p->pSrc;
225 pLeft = &pSrc->a[0];
226 pRight = &pLeft[1];
227 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
228 Table *pLeftTab = pLeft->pTab;
229 Table *pRightTab = pRight->pTab;
230
231 if( pLeftTab==0 || pRightTab==0 ) continue;
drhad2d8302002-05-24 20:31:36 +0000232
233 /* When the NATURAL keyword is present, add WHERE clause terms for
234 ** every column that the two tables have in common.
235 */
drh91bb0ee2004-09-01 03:06:34 +0000236 if( pLeft->jointype & JT_NATURAL ){
237 if( pLeft->pOn || pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000238 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000239 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000240 return 1;
241 }
drh91bb0ee2004-09-01 03:06:34 +0000242 for(j=0; j<pLeftTab->nCol; j++){
243 char *zName = pLeftTab->aCol[j].zName;
244 if( columnIndex(pRightTab, zName)>=0 ){
245 addWhereTerm(zName, pLeftTab, pRightTab, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000246 }
247 }
248 }
249
250 /* Disallow both ON and USING clauses in the same join
251 */
drh91bb0ee2004-09-01 03:06:34 +0000252 if( pLeft->pOn && pLeft->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000253 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
drhda93d232003-03-31 02:12:46 +0000254 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000255 return 1;
256 }
257
258 /* Add the ON clause to the end of the WHERE clause, connected by
drh91bb0ee2004-09-01 03:06:34 +0000259 ** an AND operator.
drhad2d8302002-05-24 20:31:36 +0000260 */
drh91bb0ee2004-09-01 03:06:34 +0000261 if( pLeft->pOn ){
262 setJoinExpr(pLeft->pOn);
263 p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn);
264 pLeft->pOn = 0;
drhad2d8302002-05-24 20:31:36 +0000265 }
266
267 /* Create extra terms on the WHERE clause for each column named
268 ** in the USING clause. Example: If the two tables to be joined are
269 ** A and B and the USING clause names X, Y, and Z, then add this
270 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
271 ** Report an error if any column mentioned in the USING clause is
272 ** not contained in both tables to be joined.
273 */
drh91bb0ee2004-09-01 03:06:34 +0000274 if( pLeft->pUsing ){
275 IdList *pList = pLeft->pUsing;
drhad2d8302002-05-24 20:31:36 +0000276 for(j=0; j<pList->nId; j++){
drh91bb0ee2004-09-01 03:06:34 +0000277 char *zName = pList->a[j].zName;
278 if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
danielk19774adee202004-05-08 08:23:19 +0000279 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
drh91bb0ee2004-09-01 03:06:34 +0000280 "not present in both tables", zName);
drhad2d8302002-05-24 20:31:36 +0000281 return 1;
282 }
drh91bb0ee2004-09-01 03:06:34 +0000283 addWhereTerm(zName, pLeftTab, pRightTab, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000284 }
285 }
286 }
287 return 0;
288}
289
290/*
drh9bb61fe2000-06-05 16:01:39 +0000291** Delete the given Select structure and all of its substructures.
292*/
danielk19774adee202004-05-08 08:23:19 +0000293void sqlite3SelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000294 if( p==0 ) return;
danielk19774adee202004-05-08 08:23:19 +0000295 sqlite3ExprListDelete(p->pEList);
296 sqlite3SrcListDelete(p->pSrc);
297 sqlite3ExprDelete(p->pWhere);
298 sqlite3ExprListDelete(p->pGroupBy);
299 sqlite3ExprDelete(p->pHaving);
300 sqlite3ExprListDelete(p->pOrderBy);
301 sqlite3SelectDelete(p->pPrior);
drha76b5df2002-02-23 02:32:10 +0000302 sqliteFree(p->zSelect);
drh9bb61fe2000-06-05 16:01:39 +0000303 sqliteFree(p);
304}
305
306/*
drh22827922000-06-06 17:27:05 +0000307** Delete the aggregate information from the parse structure.
308*/
drh1d83f052002-02-17 00:30:36 +0000309static void sqliteAggregateInfoReset(Parse *pParse){
drh22827922000-06-06 17:27:05 +0000310 sqliteFree(pParse->aAgg);
311 pParse->aAgg = 0;
312 pParse->nAgg = 0;
drh22827922000-06-06 17:27:05 +0000313 pParse->useAgg = 0;
314}
315
316/*
drhc926afb2002-06-20 03:38:26 +0000317** Insert code into "v" that will push the record on the top of the
318** stack into the sorter.
319*/
320static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
drhc926afb2002-06-20 03:38:26 +0000321 int i;
drhc926afb2002-06-20 03:38:26 +0000322 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000323 sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
drhc926afb2002-06-20 03:38:26 +0000324 }
danielk1977ededfd52004-06-17 07:53:01 +0000325 sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +0000326 sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000327}
328
329/*
drhea48eb22004-07-19 23:16:38 +0000330** Add code to implement the OFFSET and LIMIT
331*/
332static void codeLimiter(
drhbab39e12004-07-19 23:38:11 +0000333 Vdbe *v, /* Generate code into this VM */
drhea48eb22004-07-19 23:16:38 +0000334 Select *p, /* The SELECT statement being coded */
335 int iContinue, /* Jump here to skip the current record */
336 int iBreak, /* Jump here to end the loop */
337 int nPop /* Number of times to pop stack when jumping */
338){
drhea48eb22004-07-19 23:16:38 +0000339 if( p->iOffset>=0 ){
340 int addr = sqlite3VdbeCurrentAddr(v) + 2;
341 if( nPop>0 ) addr++;
342 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr);
343 if( nPop>0 ){
344 sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
345 }
346 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000347 VdbeComment((v, "# skip OFFSET records"));
drhea48eb22004-07-19 23:16:38 +0000348 }
349 if( p->iLimit>=0 ){
350 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhad6d9462004-09-19 02:15:24 +0000351 VdbeComment((v, "# exit when LIMIT reached"));
drhea48eb22004-07-19 23:16:38 +0000352 }
353}
354
355/*
drh22827922000-06-06 17:27:05 +0000356** This routine generates the code for the inside of the inner loop
357** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000358**
drh38640e12002-07-05 21:42:36 +0000359** If srcTab and nColumn are both zero, then the pEList expressions
360** are evaluated in order to get the data for this row. If nColumn>0
361** then data is pulled from srcTab and pEList is used only to get the
362** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000363*/
364static int selectInnerLoop(
365 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000366 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000367 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000368 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000369 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000370 ExprList *pOrderBy, /* If not NULL, sort results using this key */
371 int distinct, /* If >=0, make sure results are distinct */
372 int eDest, /* How to dispose of the results */
373 int iParm, /* An argument to the disposal method */
374 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000375 int iBreak, /* Jump here to break out of the inner loop */
376 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000377){
378 Vdbe *v = pParse->pVdbe;
379 int i;
drhea48eb22004-07-19 23:16:38 +0000380 int hasDistinct; /* True if the DISTINCT keyword is present */
drh38640e12002-07-05 21:42:36 +0000381
drhdaffd0e2001-04-11 14:28:42 +0000382 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000383 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000384
drhdf199a22002-06-14 22:38:41 +0000385 /* If there was a LIMIT clause on the SELECT statement, then do the check
386 ** to see if this row should be output.
387 */
drhea48eb22004-07-19 23:16:38 +0000388 hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
389 if( pOrderBy==0 && !hasDistinct ){
drhbab39e12004-07-19 23:38:11 +0000390 codeLimiter(v, p, iContinue, iBreak, 0);
drhdf199a22002-06-14 22:38:41 +0000391 }
392
drh967e8b72000-06-21 13:59:10 +0000393 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000394 */
drh38640e12002-07-05 21:42:36 +0000395 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000396 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000397 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000398 }
drh38640e12002-07-05 21:42:36 +0000399 }else{
400 nColumn = pEList->nExpr;
401 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000402 sqlite3ExprCode(pParse, pEList->a[i].pExpr);
drh38640e12002-07-05 21:42:36 +0000403 }
drh22827922000-06-06 17:27:05 +0000404 }
405
drhdaffd0e2001-04-11 14:28:42 +0000406 /* If the DISTINCT keyword was present on the SELECT statement
407 ** and this row has been seen before, then do not make this row
408 ** part of the result.
drh22827922000-06-06 17:27:05 +0000409 */
drhea48eb22004-07-19 23:16:38 +0000410 if( hasDistinct ){
drh0bd1f4e2002-06-06 18:54:39 +0000411#if NULL_ALWAYS_DISTINCT
danielk19774adee202004-05-08 08:23:19 +0000412 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
drh0bd1f4e2002-06-06 18:54:39 +0000413#endif
danielk1977ededfd52004-06-17 07:53:01 +0000414 /* Deliberately leave the affinity string off of the following
415 ** OP_MakeRecord */
416 sqlite3VdbeAddOp(v, OP_MakeRecord, pEList->nExpr * -1, 0);
danielk19774adee202004-05-08 08:23:19 +0000417 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
418 sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
419 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhad6d9462004-09-19 02:15:24 +0000420 VdbeComment((v, "# skip indistinct records"));
danielk19770f69c1e2004-05-29 11:24:50 +0000421 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000422 sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
drhea48eb22004-07-19 23:16:38 +0000423 if( pOrderBy==0 ){
drhbab39e12004-07-19 23:38:11 +0000424 codeLimiter(v, p, iContinue, iBreak, nColumn);
drhea48eb22004-07-19 23:16:38 +0000425 }
drh22827922000-06-06 17:27:05 +0000426 }
drh82c3d632000-06-06 21:56:07 +0000427
drhc926afb2002-06-20 03:38:26 +0000428 switch( eDest ){
429 /* In this mode, write each query result to the key of the temporary
430 ** table iParm.
431 */
432 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000433 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000434 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000435 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000436 sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000437 break;
drh22827922000-06-06 17:27:05 +0000438 }
drh22827922000-06-06 17:27:05 +0000439
drhc926afb2002-06-20 03:38:26 +0000440 /* Store the result as data using a unique key.
441 */
442 case SRT_Table:
443 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000444 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000445 if( pOrderBy ){
446 pushOntoSorter(pParse, v, pOrderBy);
447 }else{
danielk19774adee202004-05-08 08:23:19 +0000448 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
449 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
450 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000451 }
452 break;
453 }
drh82c3d632000-06-06 21:56:07 +0000454
drhc926afb2002-06-20 03:38:26 +0000455 /* Construct a record from the query result, but instead of
456 ** saving that record, use it as a key to delete elements from
457 ** the temporary table iParm.
458 */
459 case SRT_Except: {
460 int addr;
danielk19774adee202004-05-08 08:23:19 +0000461 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000462 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000463 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
464 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000465 break;
466 }
drh5974a302000-06-07 14:42:26 +0000467
drhc926afb2002-06-20 03:38:26 +0000468 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
469 ** then there should be a single item on the stack. Write this
470 ** item into the set table with bogus data.
471 */
472 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000473 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000474 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000475
drhc926afb2002-06-20 03:38:26 +0000476 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000477 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
478 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
479 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000480 if( pOrderBy ){
481 pushOntoSorter(pParse, v, pOrderBy);
482 }else{
danielk1977e014a832004-05-17 10:48:57 +0000483 char const *affStr;
484 char aff = (iParm>>16)&0xFF;
485 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
486 affStr = sqlite3AffinityString(aff);
danielk1977ededfd52004-06-17 07:53:01 +0000487 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, affStr, P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000488 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000489 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000490 }
danielk19774adee202004-05-08 08:23:19 +0000491 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000492 break;
493 }
drh22827922000-06-06 17:27:05 +0000494
drhc926afb2002-06-20 03:38:26 +0000495 /* If this is a scalar select that is part of an expression, then
496 ** store the results in the appropriate memory cell and break out
497 ** of the scan loop.
498 */
499 case SRT_Mem: {
500 assert( nColumn==1 );
501 if( pOrderBy ){
502 pushOntoSorter(pParse, v, pOrderBy);
503 }else{
danielk19774adee202004-05-08 08:23:19 +0000504 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
505 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000506 }
507 break;
508 }
drh22827922000-06-06 17:27:05 +0000509
drhf46f9052002-06-22 02:33:38 +0000510 /* Send the data to the callback function.
511 */
512 case SRT_Callback:
513 case SRT_Sorter: {
514 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000515 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000516 pushOntoSorter(pParse, v, pOrderBy);
517 }else{
518 assert( eDest==SRT_Callback );
danielk19774adee202004-05-08 08:23:19 +0000519 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000520 }
521 break;
522 }
523
drh142e30d2002-08-28 03:00:58 +0000524 /* Invoke a subroutine to handle the results. The subroutine itself
525 ** is responsible for popping the results off of the stack.
526 */
527 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000528 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000529 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000530 pushOntoSorter(pParse, v, pOrderBy);
531 }else{
danielk19774adee202004-05-08 08:23:19 +0000532 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhac82fcf2002-09-08 17:23:41 +0000533 }
drh142e30d2002-08-28 03:00:58 +0000534 break;
535 }
536
drhc926afb2002-06-20 03:38:26 +0000537 /* Discard the results. This is used for SELECT statements inside
538 ** the body of a TRIGGER. The purpose of such selects is to call
539 ** user-defined functions that have side effects. We do not care
540 ** about the actual results of the select.
541 */
drhc926afb2002-06-20 03:38:26 +0000542 default: {
drhf46f9052002-06-22 02:33:38 +0000543 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000544 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000545 break;
546 }
drh82c3d632000-06-06 21:56:07 +0000547 }
548 return 0;
549}
550
551/*
drhd8bc7082000-06-07 23:51:50 +0000552** If the inner loop was generated using a non-null pOrderBy argument,
553** then the results were placed in a sorter. After the loop is terminated
554** we need to run the sorter and output the results. The following
555** routine generates the code needed to do that.
556*/
drhc926afb2002-06-20 03:38:26 +0000557static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000558 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000559 Select *p, /* The SELECT statement */
560 Vdbe *v, /* Generate code into this VDBE */
561 int nColumn, /* Number of columns of data */
562 int eDest, /* Write the sorted results here */
563 int iParm /* Optional parameter associated with eDest */
564){
danielk19774adee202004-05-08 08:23:19 +0000565 int end1 = sqlite3VdbeMakeLabel(v);
566 int end2 = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000567 int addr;
drhffbc3082004-05-21 01:29:06 +0000568 KeyInfo *pInfo;
569 ExprList *pOrderBy;
570 int nCol, i;
drh9bb575f2004-09-06 17:24:11 +0000571 sqlite3 *db = pParse->db;
drhffbc3082004-05-21 01:29:06 +0000572
drhf46f9052002-06-22 02:33:38 +0000573 if( eDest==SRT_Sorter ) return;
drhffbc3082004-05-21 01:29:06 +0000574 pOrderBy = p->pOrderBy;
575 nCol = pOrderBy->nExpr;
576 pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
577 if( pInfo==0 ) return;
578 pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
579 pInfo->nField = nCol;
580 for(i=0; i<nCol; i++){
danielk19770202b292004-06-09 09:55:16 +0000581 /* If a collation sequence was specified explicity, then it
582 ** is stored in pOrderBy->a[i].zName. Otherwise, use the default
583 ** collation type for the expression.
584 */
danielk19777cedc8d2004-06-10 10:50:08 +0000585 pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr);
danielk19770202b292004-06-09 09:55:16 +0000586 if( !pInfo->aColl[i] ){
587 pInfo->aColl[i] = db->pDfltColl;
588 }
drhffbc3082004-05-21 01:29:06 +0000589 pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
590 }
591 sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
danielk19774adee202004-05-08 08:23:19 +0000592 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
drhbab39e12004-07-19 23:38:11 +0000593 codeLimiter(v, p, addr, end2, 1);
drhc926afb2002-06-20 03:38:26 +0000594 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000595 case SRT_Table:
596 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000597 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
598 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
599 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000600 break;
601 }
602 case SRT_Set: {
603 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000604 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
605 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
606 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
danielk1977ededfd52004-06-17 07:53:01 +0000607 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
danielk19770f69c1e2004-05-29 11:24:50 +0000608 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000609 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000610 break;
611 }
612 case SRT_Mem: {
613 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000614 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
615 sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
drhc926afb2002-06-20 03:38:26 +0000616 break;
617 }
drhce665cf2004-05-21 03:01:58 +0000618 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000619 case SRT_Subroutine: {
620 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000621 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
622 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000623 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000624 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000625 }
drhce665cf2004-05-21 03:01:58 +0000626 if( eDest==SRT_Callback ){
627 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
628 }else{
629 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
630 }
danielk197784ac9d02004-05-18 09:58:06 +0000631 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000632 break;
633 }
drhc926afb2002-06-20 03:38:26 +0000634 default: {
drhf46f9052002-06-22 02:33:38 +0000635 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000636 break;
637 }
638 }
danielk19774adee202004-05-08 08:23:19 +0000639 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
640 sqlite3VdbeResolveLabel(v, end2);
641 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
642 sqlite3VdbeResolveLabel(v, end1);
643 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000644}
645
646/*
danielk1977517eb642004-06-07 10:00:31 +0000647** Return a pointer to a string containing the 'declaration type' of the
648** expression pExpr. The string may be treated as static by the caller.
drhe78e8282003-01-19 03:59:45 +0000649**
danielk1977517eb642004-06-07 10:00:31 +0000650** If the declaration type is the exact datatype definition extracted from
651** the original CREATE TABLE statement if the expression is a column.
652**
653** The declaration type for an expression is either TEXT, NUMERIC or ANY.
654** The declaration type for a ROWID field is INTEGER.
655*/
656static const char *columnType(Parse *pParse, SrcList *pTabList, Expr *pExpr){
danielk197700e279d2004-06-21 07:36:32 +0000657 char const *zType;
danielk1977517eb642004-06-07 10:00:31 +0000658 int j;
danielk197700e279d2004-06-21 07:36:32 +0000659 if( pExpr==0 || pTabList==0 ) return 0;
660
661 switch( pExpr->op ){
662 case TK_COLUMN: {
663 Table *pTab;
664 int iCol = pExpr->iColumn;
665 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable; j++){}
666 assert( j<pTabList->nSrc );
667 pTab = pTabList->a[j].pTab;
668 if( iCol<0 ) iCol = pTab->iPKey;
669 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
670 if( iCol<0 ){
671 zType = "INTEGER";
672 }else{
673 zType = pTab->aCol[iCol].zType;
674 }
675 break;
danielk1977517eb642004-06-07 10:00:31 +0000676 }
danielk197700e279d2004-06-21 07:36:32 +0000677 case TK_AS:
678 zType = columnType(pParse, pTabList, pExpr->pLeft);
679 break;
680 case TK_SELECT: {
681 Select *pS = pExpr->pSelect;
682 zType = columnType(pParse, pS->pSrc, pS->pEList->a[0].pExpr);
683 break;
danielk1977517eb642004-06-07 10:00:31 +0000684 }
danielk197700e279d2004-06-21 07:36:32 +0000685 default:
686 zType = 0;
danielk1977517eb642004-06-07 10:00:31 +0000687 }
danielk197700e279d2004-06-21 07:36:32 +0000688
danielk1977517eb642004-06-07 10:00:31 +0000689 return zType;
690}
691
692/*
693** Generate code that will tell the VDBE the declaration types of columns
694** in the result set.
drhfcb78a42003-01-18 20:11:05 +0000695*/
696static void generateColumnTypes(
697 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000698 SrcList *pTabList, /* List of tables */
699 ExprList *pEList /* Expressions defining the result set */
700){
701 Vdbe *v = pParse->pVdbe;
danielk1977517eb642004-06-07 10:00:31 +0000702 int i;
drhfcb78a42003-01-18 20:11:05 +0000703 for(i=0; i<pEList->nExpr; i++){
704 Expr *p = pEList->a[i].pExpr;
danielk1977517eb642004-06-07 10:00:31 +0000705 const char *zType = columnType(pParse, pTabList, p);
danielk197700e279d2004-06-21 07:36:32 +0000706 if( zType==0 ) continue;
danielk1977fbcd5852004-06-15 02:44:18 +0000707 /* The vdbe must make it's own copy of the column-type, in case the
708 ** schema is reset before this virtual machine is deleted.
709 */
710 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
drhfcb78a42003-01-18 20:11:05 +0000711 }
712}
713
714/*
715** Generate code that will tell the VDBE the names of columns
716** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000717** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000718*/
drh832508b2002-03-02 17:04:07 +0000719static void generateColumnNames(
720 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000721 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000722 ExprList *pEList /* Expressions defining the result set */
723){
drhd8bc7082000-06-07 23:51:50 +0000724 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000725 int i, j;
drh9bb575f2004-09-06 17:24:11 +0000726 sqlite3 *db = pParse->db;
drhfcabd462004-02-20 14:50:58 +0000727 int fullNames, shortNames;
728
danielk19773cf86062004-05-26 10:11:05 +0000729 /* If this is an EXPLAIN, skip this step */
730 if( pParse->explain ){
danielk197761de0d12004-05-27 23:56:16 +0000731 return;
danielk19773cf86062004-05-26 10:11:05 +0000732 }
733
drhd6502752004-02-16 03:44:01 +0000734 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000735 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000736 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000737 fullNames = (db->flags & SQLITE_FullColNames)!=0;
738 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
danielk197722322fd2004-05-25 23:35:17 +0000739 sqlite3VdbeSetNumCols(v, pEList->nExpr);
drh82c3d632000-06-06 21:56:07 +0000740 for(i=0; i<pEList->nExpr; i++){
741 Expr *p;
drh5a387052003-01-11 14:19:51 +0000742 p = pEList->a[i].pExpr;
743 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000744 if( pEList->a[i].zName ){
745 char *zName = pEList->a[i].zName;
danielk1977d8123362004-06-12 09:25:12 +0000746 sqlite3VdbeSetColName(v, i, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000747 continue;
748 }
drhfa173a72002-07-10 21:26:00 +0000749 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000750 Table *pTab;
drh97665872002-02-13 23:22:53 +0000751 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000752 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000753 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
754 assert( j<pTabList->nSrc );
755 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000756 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000757 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000758 if( iCol<0 ){
759 zCol = "_ROWID_";
drhb1363202002-06-26 02:45:03 +0000760 }else{
761 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000762 }
drhfcabd462004-02-20 14:50:58 +0000763 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000764 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
drhfcabd462004-02-20 14:50:58 +0000765 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000766 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000767 char *zTab;
768
drh6a3ea0e2003-05-02 14:32:12 +0000769 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000770 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000771 sqlite3SetString(&zName, zTab, ".", zCol, 0);
danielk19773cf86062004-05-26 10:11:05 +0000772 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000773 }else{
danielk19773cf86062004-05-26 10:11:05 +0000774 sqlite3VdbeSetColName(v, i, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000775 }
drh6977fea2002-10-22 23:38:04 +0000776 }else if( p->span.z && p->span.z[0] ){
danielk19773cf86062004-05-26 10:11:05 +0000777 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
778 /* sqlite3VdbeCompressSpace(v, addr); */
drh1bee3d72001-10-15 00:44:35 +0000779 }else{
780 char zName[30];
781 assert( p->op!=TK_COLUMN || pTabList==0 );
782 sprintf(zName, "column%d", i+1);
danielk19773cf86062004-05-26 10:11:05 +0000783 sqlite3VdbeSetColName(v, i, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000784 }
785 }
danielk197776d505b2004-05-28 13:13:02 +0000786 generateColumnTypes(pParse, pTabList, pEList);
drh82c3d632000-06-06 21:56:07 +0000787}
788
789/*
drhd8bc7082000-06-07 23:51:50 +0000790** Name of the connection operator, used for error messages.
791*/
792static const char *selectOpName(int id){
793 char *z;
794 switch( id ){
795 case TK_ALL: z = "UNION ALL"; break;
796 case TK_INTERSECT: z = "INTERSECT"; break;
797 case TK_EXCEPT: z = "EXCEPT"; break;
798 default: z = "UNION"; break;
799 }
800 return z;
801}
802
803/*
drh315555c2002-10-20 15:53:03 +0000804** Forward declaration
805*/
806static int fillInColumnList(Parse*, Select*);
807
808/*
drh22f70c32002-02-18 01:17:00 +0000809** Given a SELECT statement, generate a Table structure that describes
810** the result set of that SELECT.
811*/
danielk19774adee202004-05-08 08:23:19 +0000812Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000813 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000814 int i, j;
drh22f70c32002-02-18 01:17:00 +0000815 ExprList *pEList;
drh290c1942004-08-21 17:54:45 +0000816 Column *aCol, *pCol;
drh22f70c32002-02-18 01:17:00 +0000817
818 if( fillInColumnList(pParse, pSelect) ){
819 return 0;
820 }
821 pTab = sqliteMalloc( sizeof(Table) );
822 if( pTab==0 ){
823 return 0;
824 }
825 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
826 pEList = pSelect->pEList;
827 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000828 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000829 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh290c1942004-08-21 17:54:45 +0000830 for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
danielk1977517eb642004-06-07 10:00:31 +0000831 Expr *pR;
832 char *zType;
drh91bb0ee2004-09-01 03:06:34 +0000833 char *zName;
danielk1977517eb642004-06-07 10:00:31 +0000834 Expr *p = pEList->a[i].pExpr;
drh290c1942004-08-21 17:54:45 +0000835 assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
drh91bb0ee2004-09-01 03:06:34 +0000836 if( (zName = pEList->a[i].zName)!=0 ){
837 zName = sqliteStrDup(zName);
danielk1977517eb642004-06-07 10:00:31 +0000838 }else if( p->op==TK_DOT
drhb733d032004-01-24 20:18:12 +0000839 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
840 int cnt;
drh91bb0ee2004-09-01 03:06:34 +0000841 zName = sqlite3MPrintf("%T", &pR->token);
drhb733d032004-01-24 20:18:12 +0000842 for(j=cnt=0; j<i; j++){
drh91bb0ee2004-09-01 03:06:34 +0000843 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
844 sqliteFree(zName);
845 zName = sqlite3MPrintf("%T_%d", &pR->token, ++cnt);
drhb733d032004-01-24 20:18:12 +0000846 j = -1;
847 }
848 }
849 }else if( p->span.z && p->span.z[0] ){
drh91bb0ee2004-09-01 03:06:34 +0000850 zName = sqlite3MPrintf("%T", &p->span);
drh22f70c32002-02-18 01:17:00 +0000851 }else{
drh91bb0ee2004-09-01 03:06:34 +0000852 zName = sqlite3MPrintf("column%d", i+1);
drh22f70c32002-02-18 01:17:00 +0000853 }
drh91bb0ee2004-09-01 03:06:34 +0000854 sqlite3Dequote(zName);
855 pCol->zName = zName;
danielk1977517eb642004-06-07 10:00:31 +0000856
857 zType = sqliteStrDup(columnType(pParse, pSelect->pSrc ,p));
drh290c1942004-08-21 17:54:45 +0000858 pCol->zType = zType;
859 pCol->affinity = SQLITE_AFF_NUMERIC;
danielk1977517eb642004-06-07 10:00:31 +0000860 if( zType ){
drh290c1942004-08-21 17:54:45 +0000861 pCol->affinity = sqlite3AffinityType(zType, strlen(zType));
danielk1977517eb642004-06-07 10:00:31 +0000862 }
drh290c1942004-08-21 17:54:45 +0000863 pCol->pColl = sqlite3ExprCollSeq(pParse, p);
864 if( !pCol->pColl ){
865 pCol->pColl = pParse->db->pDfltColl;
danielk19770202b292004-06-09 09:55:16 +0000866 }
drh22f70c32002-02-18 01:17:00 +0000867 }
868 pTab->iPKey = -1;
869 return pTab;
870}
871
872/*
drhad2d8302002-05-24 20:31:36 +0000873** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000874**
drhad3cab52002-05-24 02:04:32 +0000875** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh63eb5f22003-04-29 16:20:44 +0000876** defines the set of tables that should be scanned. For views,
877** fill pTabList->a[].pSelect with a copy of the SELECT statement
878** that implements the view. A copy is made of the view's SELECT
879** statement so that we can freely modify or delete that statement
880** without worrying about messing up the presistent representation
881** of the view.
drhd8bc7082000-06-07 23:51:50 +0000882**
drhad2d8302002-05-24 20:31:36 +0000883** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
884** on joins and the ON and USING clause of joins.
885**
886** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000887** for instances of the "*" operator or the TABLE.* operator.
888** If found, expand each "*" to be every column in every table
889** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000890**
891** Return 0 on success. If there are problems, leave an error message
892** in pParse and return non-zero.
893*/
894static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000895 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000896 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000897 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000898 Table *pTab;
drh290c1942004-08-21 17:54:45 +0000899 struct SrcList_item *pFrom;
drhdaffd0e2001-04-11 14:28:42 +0000900
901 if( p==0 || p->pSrc==0 ) return 1;
902 pTabList = p->pSrc;
903 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000904
905 /* Look up every table in the table list.
906 */
drh290c1942004-08-21 17:54:45 +0000907 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
908 if( pFrom->pTab ){
drhd8bc7082000-06-07 23:51:50 +0000909 /* This routine has run before! No need to continue */
910 return 0;
911 }
drh290c1942004-08-21 17:54:45 +0000912 if( pFrom->zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000913 /* A sub-query in the FROM clause of a SELECT */
drh290c1942004-08-21 17:54:45 +0000914 assert( pFrom->pSelect!=0 );
915 if( pFrom->zAlias==0 ){
drh91bb0ee2004-09-01 03:06:34 +0000916 pFrom->zAlias =
917 sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
drhad2d8302002-05-24 20:31:36 +0000918 }
drh290c1942004-08-21 17:54:45 +0000919 pFrom->pTab = pTab =
920 sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
drh22f70c32002-02-18 01:17:00 +0000921 if( pTab==0 ){
922 return 1;
923 }
drh5cf590c2003-04-24 01:45:04 +0000924 /* The isTransient flag indicates that the Table structure has been
925 ** dynamically allocated and may be freed at any time. In other words,
926 ** pTab is not pointing to a persistent table structure that defines
927 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000928 pTab->isTransient = 1;
929 }else{
drha76b5df2002-02-23 02:32:10 +0000930 /* An ordinary table or view name in the FROM clause */
drh290c1942004-08-21 17:54:45 +0000931 pFrom->pTab = pTab =
932 sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
drha76b5df2002-02-23 02:32:10 +0000933 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000934 return 1;
935 }
drha76b5df2002-02-23 02:32:10 +0000936 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +0000937 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +0000938 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +0000939 return 1;
940 }
drh290c1942004-08-21 17:54:45 +0000941 /* If pFrom->pSelect!=0 it means we are dealing with a
drh63eb5f22003-04-29 16:20:44 +0000942 ** view within a view. The SELECT structure has already been
943 ** copied by the outer view so we can skip the copy step here
944 ** in the inner view.
945 */
drh290c1942004-08-21 17:54:45 +0000946 if( pFrom->pSelect==0 ){
947 pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +0000948 }
drha76b5df2002-02-23 02:32:10 +0000949 }
drhd8bc7082000-06-07 23:51:50 +0000950 }
951 }
952
drhad2d8302002-05-24 20:31:36 +0000953 /* Process NATURAL keywords, and ON and USING clauses of joins.
954 */
955 if( sqliteProcessJoin(pParse, p) ) return 1;
956
drh7c917d12001-12-16 20:05:05 +0000957 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000958 ** all columns in all tables. And for every TABLE.* insert the names
959 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000960 ** with the TK_ALL operator for each "*" that it found in the column list.
961 ** The following code just has to locate the TK_ALL expressions and expand
962 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000963 **
964 ** The first loop just checks to see if there are any "*" operators
965 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000966 */
drh7c917d12001-12-16 20:05:05 +0000967 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000968 Expr *pE = pEList->a[k].pExpr;
969 if( pE->op==TK_ALL ) break;
970 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
971 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000972 }
drh54473222002-04-04 02:10:55 +0000973 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000974 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000975 /*
976 ** If we get here it means the result set contains one or more "*"
977 ** operators that need to be expanded. Loop through each expression
978 ** in the result set and expand them one by one.
979 */
drh7c917d12001-12-16 20:05:05 +0000980 struct ExprList_item *a = pEList->a;
981 ExprList *pNew = 0;
982 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000983 Expr *pE = a[k].pExpr;
984 if( pE->op!=TK_ALL &&
985 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
986 /* This particular expression does not need to be expanded.
987 */
danielk19774adee202004-05-08 08:23:19 +0000988 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +0000989 pNew->a[pNew->nExpr-1].zName = a[k].zName;
990 a[k].pExpr = 0;
991 a[k].zName = 0;
992 }else{
drh54473222002-04-04 02:10:55 +0000993 /* This expression is a "*" or a "TABLE.*" and needs to be
994 ** expanded. */
995 int tableSeen = 0; /* Set to 1 when TABLE matches */
drhcf55b7a2004-07-20 01:45:19 +0000996 char *zTName; /* text of name of TABLE */
drh54473222002-04-04 02:10:55 +0000997 if( pE->op==TK_DOT && pE->pLeft ){
drhcf55b7a2004-07-20 01:45:19 +0000998 zTName = sqlite3NameFromToken(&pE->pLeft->token);
drh54473222002-04-04 02:10:55 +0000999 }else{
drhcf55b7a2004-07-20 01:45:19 +00001000 zTName = 0;
drh54473222002-04-04 02:10:55 +00001001 }
drh290c1942004-08-21 17:54:45 +00001002 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1003 Table *pTab = pFrom->pTab;
1004 char *zTabName = pFrom->zAlias;
drh54473222002-04-04 02:10:55 +00001005 if( zTabName==0 || zTabName[0]==0 ){
1006 zTabName = pTab->zName;
1007 }
drhcf55b7a2004-07-20 01:45:19 +00001008 if( zTName && (zTabName==0 || zTabName[0]==0 ||
1009 sqlite3StrICmp(zTName, zTabName)!=0) ){
drh54473222002-04-04 02:10:55 +00001010 continue;
1011 }
1012 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +00001013 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +00001014 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +00001015 char *zName = pTab->aCol[j].zName;
1016
drh91bb0ee2004-09-01 03:06:34 +00001017 if( i>0 ){
1018 struct SrcList_item *pLeft = &pTabList->a[i-1];
1019 if( (pLeft->jointype & JT_NATURAL)!=0 &&
1020 columnIndex(pLeft->pTab, zName)>=0 ){
1021 /* In a NATURAL join, omit the join columns from the
1022 ** table on the right */
1023 continue;
1024 }
1025 if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1026 /* In a join with a USING clause, omit columns in the
1027 ** using clause from the table on the right. */
1028 continue;
1029 }
drhad2d8302002-05-24 20:31:36 +00001030 }
danielk19774adee202004-05-08 08:23:19 +00001031 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +00001032 if( pRight==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001033 setToken(&pRight->token, zName);
drh4b59ab52002-08-24 18:24:51 +00001034 if( zTabName && pTabList->nSrc>1 ){
danielk19774adee202004-05-08 08:23:19 +00001035 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1036 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001037 if( pExpr==0 ) break;
drh91bb0ee2004-09-01 03:06:34 +00001038 setToken(&pLeft->token, zTabName);
1039 setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
drh6977fea2002-10-22 23:38:04 +00001040 pExpr->span.dyn = 1;
1041 pExpr->token.z = 0;
1042 pExpr->token.n = 0;
1043 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001044 }else{
drh22f70c32002-02-18 01:17:00 +00001045 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001046 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001047 }
danielk19774adee202004-05-08 08:23:19 +00001048 pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001049 }
drh17e24df2001-11-06 14:10:41 +00001050 }
drh54473222002-04-04 02:10:55 +00001051 if( !tableSeen ){
drhcf55b7a2004-07-20 01:45:19 +00001052 if( zTName ){
1053 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
drhf5db2d32002-06-06 23:42:27 +00001054 }else{
danielk19774adee202004-05-08 08:23:19 +00001055 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001056 }
drh54473222002-04-04 02:10:55 +00001057 rc = 1;
1058 }
drhcf55b7a2004-07-20 01:45:19 +00001059 sqliteFree(zTName);
drhd8bc7082000-06-07 23:51:50 +00001060 }
1061 }
danielk19774adee202004-05-08 08:23:19 +00001062 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001063 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001064 }
drh54473222002-04-04 02:10:55 +00001065 return rc;
drhd8bc7082000-06-07 23:51:50 +00001066}
1067
1068/*
drhff78bd22002-02-27 01:47:11 +00001069** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1070** in a select structure. It just sets the pointers to NULL. This
1071** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1072** pointer is not NULL, this routine is called recursively on that pointer.
1073**
1074** This routine is called on the Select structure that defines a
1075** VIEW in order to undo any bindings to tables. This is necessary
1076** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001077** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1078** will be left pointing to a deallocated Table structure after the
1079** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001080*/
danielk19774adee202004-05-08 08:23:19 +00001081void sqlite3SelectUnbind(Select *p){
drhff78bd22002-02-27 01:47:11 +00001082 int i;
drhad3cab52002-05-24 02:04:32 +00001083 SrcList *pSrc = p->pSrc;
drh91bb0ee2004-09-01 03:06:34 +00001084 struct SrcList_item *pItem;
drhff78bd22002-02-27 01:47:11 +00001085 Table *pTab;
1086 if( p==0 ) return;
drh91bb0ee2004-09-01 03:06:34 +00001087 for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
1088 if( (pTab = pItem->pTab)!=0 ){
drhff78bd22002-02-27 01:47:11 +00001089 if( pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001090 sqlite3DeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001091 }
drh91bb0ee2004-09-01 03:06:34 +00001092 pItem->pTab = 0;
1093 if( pItem->pSelect ){
1094 sqlite3SelectUnbind(pItem->pSelect);
drhff78bd22002-02-27 01:47:11 +00001095 }
1096 }
1097 }
1098}
1099
1100/*
drhd8bc7082000-06-07 23:51:50 +00001101** This routine associates entries in an ORDER BY expression list with
1102** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001103** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001104** the top-level node is filled in with column number and the iTable
1105** value of the top-level node is filled with iTable parameter.
1106**
1107** If there are prior SELECT clauses, they are processed first. A match
1108** in an earlier SELECT takes precedence over a later SELECT.
1109**
1110** Any entry that does not match is flagged as an error. The number
1111** of errors is returned.
1112*/
1113static int matchOrderbyToColumn(
1114 Parse *pParse, /* A place to leave error messages */
1115 Select *pSelect, /* Match to result columns of this SELECT */
1116 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001117 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001118 int mustComplete /* If TRUE all ORDER BYs must match */
1119){
1120 int nErr = 0;
1121 int i, j;
1122 ExprList *pEList;
1123
drhdaffd0e2001-04-11 14:28:42 +00001124 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001125 if( mustComplete ){
1126 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1127 }
1128 if( fillInColumnList(pParse, pSelect) ){
1129 return 1;
1130 }
1131 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001132 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1133 return 1;
1134 }
drhd8bc7082000-06-07 23:51:50 +00001135 }
1136 pEList = pSelect->pEList;
1137 for(i=0; i<pOrderBy->nExpr; i++){
1138 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001139 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001140 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001141 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001142 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001143 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001144 "ORDER BY position %d should be between 1 and %d",
1145 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001146 nErr++;
1147 break;
1148 }
drhfcb78a42003-01-18 20:11:05 +00001149 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001150 iCol--;
1151 }
1152 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001153 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001154 char *zName, *zLabel;
1155 zName = pEList->a[j].zName;
drha99db3b2004-06-19 14:49:12 +00001156 zLabel = sqlite3NameFromToken(&pE->token);
1157 assert( zLabel!=0 );
danielk19774adee202004-05-08 08:23:19 +00001158 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001159 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001160 }
drh6e142f52000-06-08 13:36:40 +00001161 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001162 }
danielk19774adee202004-05-08 08:23:19 +00001163 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001164 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001165 }
1166 }
drhe4de1fe2002-06-02 16:09:01 +00001167 if( iCol>=0 ){
1168 pE->op = TK_COLUMN;
1169 pE->iColumn = iCol;
1170 pE->iTable = iTable;
1171 pOrderBy->a[i].done = 1;
1172 }
1173 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001174 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001175 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001176 nErr++;
1177 break;
1178 }
1179 }
1180 return nErr;
1181}
1182
1183/*
1184** Get a VDBE for the given parser context. Create a new one if necessary.
1185** If an error occurs, return NULL and leave a message in pParse.
1186*/
danielk19774adee202004-05-08 08:23:19 +00001187Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001188 Vdbe *v = pParse->pVdbe;
1189 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001190 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001191 }
drhd8bc7082000-06-07 23:51:50 +00001192 return v;
1193}
drhfcb78a42003-01-18 20:11:05 +00001194
drhd8bc7082000-06-07 23:51:50 +00001195/*
drh7b58dae2003-07-20 01:16:46 +00001196** Compute the iLimit and iOffset fields of the SELECT based on the
1197** nLimit and nOffset fields. nLimit and nOffset hold the integers
1198** that appear in the original SQL statement after the LIMIT and OFFSET
1199** keywords. Or that hold -1 and 0 if those keywords are omitted.
1200** iLimit and iOffset are the integer memory register numbers for
1201** counters used to compute the limit and offset. If there is no
1202** limit and/or offset, then iLimit and iOffset are negative.
1203**
1204** This routine changes the values if iLimit and iOffset only if
1205** a limit or offset is defined by nLimit and nOffset. iLimit and
1206** iOffset should have been preset to appropriate default values
1207** (usually but not always -1) prior to calling this routine.
1208** Only if nLimit>=0 or nOffset>0 do the limit registers get
1209** redefined. The UNION ALL operator uses this property to force
1210** the reuse of the same limit and offset registers across multiple
1211** SELECT statements.
1212*/
1213static void computeLimitRegisters(Parse *pParse, Select *p){
1214 /*
1215 ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
1216 ** all rows. It is the same as no limit. If the comparision is
1217 ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
1218 ** "LIMIT -1" always shows all rows. There is some
1219 ** contraversy about what the correct behavior should be.
1220 ** The current implementation interprets "LIMIT 0" to mean
1221 ** no rows.
1222 */
1223 if( p->nLimit>=0 ){
1224 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001225 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001226 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001227 sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1228 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001229 VdbeComment((v, "# LIMIT counter"));
drh7b58dae2003-07-20 01:16:46 +00001230 p->iLimit = iMem;
1231 }
1232 if( p->nOffset>0 ){
1233 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001234 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001235 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001236 sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1237 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drhad6d9462004-09-19 02:15:24 +00001238 VdbeComment((v, "# OFFSET counter"));
drh7b58dae2003-07-20 01:16:46 +00001239 p->iOffset = iMem;
1240 }
1241}
1242
1243/*
drhd3d39e92004-05-20 22:16:29 +00001244** Generate VDBE instructions that will open a transient table that
1245** will be used for an index or to store keyed results for a compound
1246** select. In other words, open a transient table that needs a
1247** KeyInfo structure. The number of columns in the KeyInfo is determined
1248** by the result set of the SELECT statement in the second argument.
1249**
danielk1977dc1bdc42004-06-11 10:51:27 +00001250** Specifically, this routine is called to open an index table for
1251** DISTINCT, UNION, INTERSECT and EXCEPT select statements (but not
1252** UNION ALL).
1253**
drhd3d39e92004-05-20 22:16:29 +00001254** Make the new table a KeyAsData table if keyAsData is true.
danielk1977dc1bdc42004-06-11 10:51:27 +00001255**
1256** The value returned is the address of the OP_OpenTemp instruction.
drhd3d39e92004-05-20 22:16:29 +00001257*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001258static int openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
drhd3d39e92004-05-20 22:16:29 +00001259 KeyInfo *pKeyInfo;
drh736c22b2004-05-21 02:14:24 +00001260 int nColumn;
drh9bb575f2004-09-06 17:24:11 +00001261 sqlite3 *db = pParse->db;
drhd3d39e92004-05-20 22:16:29 +00001262 int i;
1263 Vdbe *v = pParse->pVdbe;
danielk1977dc1bdc42004-06-11 10:51:27 +00001264 int addr;
drhd3d39e92004-05-20 22:16:29 +00001265
drh736c22b2004-05-21 02:14:24 +00001266 if( fillInColumnList(pParse, p) ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001267 return 0;
drh736c22b2004-05-21 02:14:24 +00001268 }
1269 nColumn = p->pEList->nExpr;
drhd3d39e92004-05-20 22:16:29 +00001270 pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
danielk1977dc1bdc42004-06-11 10:51:27 +00001271 if( pKeyInfo==0 ) return 0;
drh91bb0ee2004-09-01 03:06:34 +00001272 pKeyInfo->enc = db->enc;
drhd3d39e92004-05-20 22:16:29 +00001273 pKeyInfo->nField = nColumn;
1274 for(i=0; i<nColumn; i++){
danielk1977dc1bdc42004-06-11 10:51:27 +00001275 pKeyInfo->aColl[i] = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
1276 if( !pKeyInfo->aColl[i] ){
1277 pKeyInfo->aColl[i] = db->pDfltColl;
1278 }
drhd3d39e92004-05-20 22:16:29 +00001279 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001280 addr = sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0,
1281 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drhd3d39e92004-05-20 22:16:29 +00001282 if( keyAsData ){
1283 sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1284 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001285 return addr;
1286}
1287
drhfbc4ee72004-08-29 01:31:05 +00001288/*
drh8cdbf832004-08-29 16:25:03 +00001289** Add the address "addr" to the set of all OpenTemp opcode addresses
1290** that are being accumulated in p->ppOpenTemp.
drhfbc4ee72004-08-29 01:31:05 +00001291*/
drh8cdbf832004-08-29 16:25:03 +00001292static int multiSelectOpenTempAddr(Select *p, int addr){
1293 IdList *pList = *p->ppOpenTemp = sqlite3IdListAppend(*p->ppOpenTemp, 0);
drhfbc4ee72004-08-29 01:31:05 +00001294 if( pList==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001295 return SQLITE_NOMEM;
1296 }
drhfbc4ee72004-08-29 01:31:05 +00001297 pList->a[pList->nId-1].idx = addr;
danielk1977dc1bdc42004-06-11 10:51:27 +00001298 return SQLITE_OK;
1299}
1300
drhfbc4ee72004-08-29 01:31:05 +00001301/*
1302** Return the appropriate collating sequence for the iCol-th column of
1303** the result set for the compound-select statement "p". Return NULL if
1304** the column has no default collating sequence.
1305**
1306** The collating sequence for the compound select is taken from the
1307** left-most term of the select that has a collating sequence.
1308*/
danielk1977dc1bdc42004-06-11 10:51:27 +00001309static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
drhfbc4ee72004-08-29 01:31:05 +00001310 CollSeq *pRet;
danielk1977dc1bdc42004-06-11 10:51:27 +00001311 if( p->pPrior ){
1312 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
drhfbc4ee72004-08-29 01:31:05 +00001313 }else{
1314 pRet = 0;
danielk1977dc1bdc42004-06-11 10:51:27 +00001315 }
drhfbc4ee72004-08-29 01:31:05 +00001316 if( pRet==0 ){
danielk1977dc1bdc42004-06-11 10:51:27 +00001317 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1318 }
1319 return pRet;
drhd3d39e92004-05-20 22:16:29 +00001320}
1321
1322/*
drh82c3d632000-06-06 21:56:07 +00001323** This routine is called to process a query that is really the union
1324** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001325**
drhe78e8282003-01-19 03:59:45 +00001326** "p" points to the right-most of the two queries. the query on the
1327** left is p->pPrior. The left query could also be a compound query
1328** in which case this routine will be called recursively.
1329**
1330** The results of the total query are to be written into a destination
1331** of type eDest with parameter iParm.
1332**
1333** Example 1: Consider a three-way compound SQL statement.
1334**
1335** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1336**
1337** This statement is parsed up as follows:
1338**
1339** SELECT c FROM t3
1340** |
1341** `-----> SELECT b FROM t2
1342** |
jplyon4b11c6d2004-01-19 04:57:53 +00001343** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001344**
1345** The arrows in the diagram above represent the Select.pPrior pointer.
1346** So if this routine is called with p equal to the t3 query, then
1347** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1348**
1349** Notice that because of the way SQLite parses compound SELECTs, the
1350** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001351*/
danielk197784ac9d02004-05-18 09:58:06 +00001352static int multiSelect(
drhfbc4ee72004-08-29 01:31:05 +00001353 Parse *pParse, /* Parsing context */
1354 Select *p, /* The right-most of SELECTs to be coded */
1355 int eDest, /* \___ Store query results as specified */
1356 int iParm, /* / by these two parameters. */
1357 char *aff /* If eDest is SRT_Union, the affinity string */
danielk197784ac9d02004-05-18 09:58:06 +00001358){
drhfbc4ee72004-08-29 01:31:05 +00001359 int rc = SQLITE_OK; /* Success code from a subroutine */
1360 Select *pPrior; /* Another SELECT immediately to our left */
1361 Vdbe *v; /* Generate code to this VDBE */
1362 IdList *pOpenTemp = 0;/* OP_OpenTemp opcodes that need a KeyInfo */
drh8cdbf832004-08-29 16:25:03 +00001363 int aAddr[5]; /* Addresses of SetNumColumns operators */
1364 int nAddr = 0; /* Number used */
1365 int nCol; /* Number of columns in the result set */
drh82c3d632000-06-06 21:56:07 +00001366
drh7b58dae2003-07-20 01:16:46 +00001367 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
drhfbc4ee72004-08-29 01:31:05 +00001368 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001369 */
danielk197784ac9d02004-05-18 09:58:06 +00001370 if( p==0 || p->pPrior==0 ){
1371 rc = 1;
1372 goto multi_select_end;
1373 }
drhd8bc7082000-06-07 23:51:50 +00001374 pPrior = p->pPrior;
1375 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001376 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001377 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001378 rc = 1;
1379 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001380 }
drh7b58dae2003-07-20 01:16:46 +00001381 if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
danielk19774adee202004-05-08 08:23:19 +00001382 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001383 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001384 rc = 1;
1385 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001386 }
drh82c3d632000-06-06 21:56:07 +00001387
drhd8bc7082000-06-07 23:51:50 +00001388 /* Make sure we have a valid query engine. If not, create a new one.
1389 */
danielk19774adee202004-05-08 08:23:19 +00001390 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001391 if( v==0 ){
1392 rc = 1;
1393 goto multi_select_end;
1394 }
drhd8bc7082000-06-07 23:51:50 +00001395
drh8cdbf832004-08-29 16:25:03 +00001396 /* If *p this is the right-most select statement, then initialize
1397 ** p->ppOpenTemp to point to pOpenTemp. If *p is not the right most
1398 ** statement then p->ppOpenTemp will have already been initialized
1399 ** by a prior call to this same procedure. Pass along the pOpenTemp
1400 ** pointer to pPrior, the next statement to our left.
drhfbc4ee72004-08-29 01:31:05 +00001401 */
1402 if( p->ppOpenTemp==0 ){
1403 p->ppOpenTemp = &pOpenTemp;
1404 }
1405 pPrior->ppOpenTemp = p->ppOpenTemp;
1406
drh1cc3d752002-03-23 00:31:29 +00001407 /* Create the destination temporary table if necessary
1408 */
1409 if( eDest==SRT_TempTable ){
danielk1977b4964b72004-05-18 01:23:38 +00001410 assert( p->pEList );
danielk19774adee202004-05-08 08:23:19 +00001411 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
drh8cdbf832004-08-29 16:25:03 +00001412 assert( nAddr==0 );
1413 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 0);
drh1cc3d752002-03-23 00:31:29 +00001414 eDest = SRT_Table;
1415 }
1416
drhf46f9052002-06-22 02:33:38 +00001417 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001418 */
drh82c3d632000-06-06 21:56:07 +00001419 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001420 case TK_ALL: {
1421 if( p->pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +00001422 pPrior->nLimit = p->nLimit;
1423 pPrior->nOffset = p->nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001424 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1425 if( rc ){
1426 goto multi_select_end;
1427 }
drhf46f9052002-06-22 02:33:38 +00001428 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001429 p->iLimit = pPrior->iLimit;
1430 p->iOffset = pPrior->iOffset;
1431 p->nLimit = -1;
1432 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001433 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001434 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001435 if( rc ){
1436 goto multi_select_end;
1437 }
drhf46f9052002-06-22 02:33:38 +00001438 break;
1439 }
1440 /* For UNION ALL ... ORDER BY fall through to the next case */
1441 }
drh82c3d632000-06-06 21:56:07 +00001442 case TK_EXCEPT:
1443 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001444 int unionTab; /* Cursor number of the temporary table holding result */
danielk1977742f9472004-06-16 12:02:43 +00001445 int op = 0; /* One of the SRT_ operations to apply to self */
drhd8bc7082000-06-07 23:51:50 +00001446 int priorOp; /* The SRT_ operation to apply to prior selects */
drh7b58dae2003-07-20 01:16:46 +00001447 int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
drhc926afb2002-06-20 03:38:26 +00001448 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
danielk1977dc1bdc42004-06-11 10:51:27 +00001449 int addr;
drh82c3d632000-06-06 21:56:07 +00001450
drhd8bc7082000-06-07 23:51:50 +00001451 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh7b58dae2003-07-20 01:16:46 +00001452 if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
drhd8bc7082000-06-07 23:51:50 +00001453 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001454 ** right.
drhd8bc7082000-06-07 23:51:50 +00001455 */
drh82c3d632000-06-06 21:56:07 +00001456 unionTab = iParm;
1457 }else{
drhd8bc7082000-06-07 23:51:50 +00001458 /* We will need to create our own temporary table to hold the
1459 ** intermediate results.
1460 */
1461 unionTab = pParse->nTab++;
1462 if( p->pOrderBy
1463 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001464 rc = 1;
1465 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001466 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001467 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001468 if( p->op!=TK_ALL ){
drh8cdbf832004-08-29 16:25:03 +00001469 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001470 if( rc!=SQLITE_OK ){
1471 goto multi_select_end;
1472 }
1473 sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drhd8bc7082000-06-07 23:51:50 +00001474 }
drh8cdbf832004-08-29 16:25:03 +00001475 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1476 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, 0);
danielk197784ac9d02004-05-18 09:58:06 +00001477 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001478 }
drhd8bc7082000-06-07 23:51:50 +00001479
1480 /* Code the SELECT statements to our left
1481 */
danielk197784ac9d02004-05-18 09:58:06 +00001482 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
1483 if( rc ){
1484 goto multi_select_end;
1485 }
drhd8bc7082000-06-07 23:51:50 +00001486
1487 /* Code the current SELECT statement
1488 */
1489 switch( p->op ){
1490 case TK_EXCEPT: op = SRT_Except; break;
1491 case TK_UNION: op = SRT_Union; break;
1492 case TK_ALL: op = SRT_Table; break;
1493 }
drh82c3d632000-06-06 21:56:07 +00001494 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001495 pOrderBy = p->pOrderBy;
1496 p->pOrderBy = 0;
drh7b58dae2003-07-20 01:16:46 +00001497 nLimit = p->nLimit;
1498 p->nLimit = -1;
1499 nOffset = p->nOffset;
1500 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001501 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001502 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001503 p->pOrderBy = pOrderBy;
drh7b58dae2003-07-20 01:16:46 +00001504 p->nLimit = nLimit;
1505 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001506 if( rc ){
1507 goto multi_select_end;
1508 }
1509
drhd8bc7082000-06-07 23:51:50 +00001510
1511 /* Convert the data in the temporary table into whatever form
1512 ** it is that we currently need.
1513 */
drhc926afb2002-06-20 03:38:26 +00001514 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001515 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001516 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001517 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001518 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001519 }
danielk19774adee202004-05-08 08:23:19 +00001520 iBreak = sqlite3VdbeMakeLabel(v);
1521 iCont = sqlite3VdbeMakeLabel(v);
1522 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001523 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001524 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001525 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001526 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001527 iCont, iBreak, 0);
1528 if( rc ){
1529 rc = 1;
1530 goto multi_select_end;
1531 }
danielk19774adee202004-05-08 08:23:19 +00001532 sqlite3VdbeResolveLabel(v, iCont);
1533 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1534 sqlite3VdbeResolveLabel(v, iBreak);
1535 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drh82c3d632000-06-06 21:56:07 +00001536 }
1537 break;
1538 }
1539 case TK_INTERSECT: {
1540 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001541 int iCont, iBreak, iStart;
drh7b58dae2003-07-20 01:16:46 +00001542 int nLimit, nOffset;
danielk1977dc1bdc42004-06-11 10:51:27 +00001543 int addr;
drh82c3d632000-06-06 21:56:07 +00001544
drhd8bc7082000-06-07 23:51:50 +00001545 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001546 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001547 ** by allocating the tables we will need.
1548 */
drh82c3d632000-06-06 21:56:07 +00001549 tab1 = pParse->nTab++;
1550 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001551 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001552 rc = 1;
1553 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001554 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001555
1556 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 0);
drh8cdbf832004-08-29 16:25:03 +00001557 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001558 if( rc!=SQLITE_OK ){
1559 goto multi_select_end;
1560 }
1561 sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
drh8cdbf832004-08-29 16:25:03 +00001562 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1563 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab1, 0);
danielk197784ac9d02004-05-18 09:58:06 +00001564 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001565
1566 /* Code the SELECTs to our left into temporary table "tab1".
1567 */
danielk197784ac9d02004-05-18 09:58:06 +00001568 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
1569 if( rc ){
1570 goto multi_select_end;
1571 }
drhd8bc7082000-06-07 23:51:50 +00001572
1573 /* Code the current SELECT into temporary table "tab2"
1574 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001575 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0);
drh8cdbf832004-08-29 16:25:03 +00001576 rc = multiSelectOpenTempAddr(p, addr);
danielk1977dc1bdc42004-06-11 10:51:27 +00001577 if( rc!=SQLITE_OK ){
1578 goto multi_select_end;
1579 }
1580 sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh8cdbf832004-08-29 16:25:03 +00001581 assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
1582 aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab2, 0);
drh82c3d632000-06-06 21:56:07 +00001583 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001584 nLimit = p->nLimit;
1585 p->nLimit = -1;
1586 nOffset = p->nOffset;
1587 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001588 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001589 p->pPrior = pPrior;
drh7b58dae2003-07-20 01:16:46 +00001590 p->nLimit = nLimit;
1591 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001592 if( rc ){
1593 goto multi_select_end;
1594 }
drhd8bc7082000-06-07 23:51:50 +00001595
1596 /* Generate code to take the intersection of the two temporary
1597 ** tables.
1598 */
drh82c3d632000-06-06 21:56:07 +00001599 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001600 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001601 generateColumnNames(pParse, 0, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001602 }
danielk19774adee202004-05-08 08:23:19 +00001603 iBreak = sqlite3VdbeMakeLabel(v);
1604 iCont = sqlite3VdbeMakeLabel(v);
1605 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001606 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001607 iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
1608 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001609 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001610 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001611 iCont, iBreak, 0);
1612 if( rc ){
1613 rc = 1;
1614 goto multi_select_end;
1615 }
danielk19774adee202004-05-08 08:23:19 +00001616 sqlite3VdbeResolveLabel(v, iCont);
1617 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1618 sqlite3VdbeResolveLabel(v, iBreak);
1619 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1620 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drh82c3d632000-06-06 21:56:07 +00001621 break;
1622 }
1623 }
drh8cdbf832004-08-29 16:25:03 +00001624
1625 /* Make sure all SELECTs in the statement have the same number of elements
1626 ** in their result sets.
1627 */
drh82c3d632000-06-06 21:56:07 +00001628 assert( p->pEList && pPrior->pEList );
1629 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001630 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001631 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001632 rc = 1;
1633 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001634 }
danielk197784ac9d02004-05-18 09:58:06 +00001635
drh8cdbf832004-08-29 16:25:03 +00001636 /* Set the number of columns in temporary tables
1637 */
1638 nCol = p->pEList->nExpr;
1639 while( nAddr>0 ){
1640 nAddr--;
1641 sqlite3VdbeChangeP2(v, aAddr[nAddr], nCol);
1642 }
1643
drhfbc4ee72004-08-29 01:31:05 +00001644 /* Compute collating sequences used by either the ORDER BY clause or
1645 ** by any temporary tables needed to implement the compound select.
1646 ** Attach the KeyInfo structure to all temporary tables. Invoke the
1647 ** ORDER BY processing if there is an ORDER BY clause.
drh8cdbf832004-08-29 16:25:03 +00001648 **
1649 ** This section is run by the right-most SELECT statement only.
1650 ** SELECT statements to the left always skip this part. The right-most
1651 ** SELECT might also skip this part if it has no ORDER BY clause and
1652 ** no temp tables are required.
drhfbc4ee72004-08-29 01:31:05 +00001653 */
danielk1977dc1bdc42004-06-11 10:51:27 +00001654 if( p->pOrderBy || (pOpenTemp && pOpenTemp->nId>0) ){
drhfbc4ee72004-08-29 01:31:05 +00001655 int i; /* Loop counter */
1656 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
1657
drh8cdbf832004-08-29 16:25:03 +00001658 assert( p->ppOpenTemp == &pOpenTemp );
drhfbc4ee72004-08-29 01:31:05 +00001659 pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*sizeof(CollSeq*));
danielk1977dc1bdc42004-06-11 10:51:27 +00001660 if( !pKeyInfo ){
1661 rc = SQLITE_NOMEM;
1662 goto multi_select_end;
1663 }
1664
1665 pKeyInfo->enc = pParse->db->enc;
1666 pKeyInfo->nField = nCol;
1667
1668 for(i=0; i<nCol; i++){
1669 pKeyInfo->aColl[i] = multiSelectCollSeq(pParse, p, i);
1670 if( !pKeyInfo->aColl[i] ){
1671 pKeyInfo->aColl[i] = pParse->db->pDfltColl;
1672 }
1673 }
1674
1675 for(i=0; pOpenTemp && i<pOpenTemp->nId; i++){
1676 int p3type = (i==0?P3_KEYINFO_HANDOFF:P3_KEYINFO);
1677 int addr = pOpenTemp->a[i].idx;
1678 sqlite3VdbeChangeP3(v, addr, (char *)pKeyInfo, p3type);
1679 }
1680
1681 if( p->pOrderBy ){
drhfbc4ee72004-08-29 01:31:05 +00001682 struct ExprList_item *pOrderByTerm = p->pOrderBy->a;
1683 for(i=0; i<p->pOrderBy->nExpr; i++, pOrderByTerm++){
1684 Expr *pExpr = pOrderByTerm->pExpr;
1685 char *zName = pOrderByTerm->zName;
danielk1977dc1bdc42004-06-11 10:51:27 +00001686 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
1687 assert( !pExpr->pColl );
1688 if( zName ){
1689 pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1);
1690 }else{
1691 pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn];
1692 }
1693 }
1694 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1695 }
1696
1697 if( !pOpenTemp ){
1698 /* This happens for UNION ALL ... ORDER BY */
1699 sqliteFree(pKeyInfo);
danielk197784ac9d02004-05-18 09:58:06 +00001700 }
1701 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001702
1703multi_select_end:
1704 if( pOpenTemp ){
1705 sqlite3IdListDelete(pOpenTemp);
1706 }
1707 p->ppOpenTemp = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001708 return rc;
drh22827922000-06-06 17:27:05 +00001709}
1710
1711/*
drh832508b2002-03-02 17:04:07 +00001712** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001713** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001714** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001715** unchanged.)
drh832508b2002-03-02 17:04:07 +00001716**
1717** This routine is part of the flattening procedure. A subquery
1718** whose result set is defined by pEList appears as entry in the
1719** FROM clause of a SELECT such that the VDBE cursor assigned to that
1720** FORM clause entry is iTable. This routine make the necessary
1721** changes to pExpr so that it refers directly to the source table
1722** of the subquery rather the result set of the subquery.
1723*/
drh6a3ea0e2003-05-02 14:32:12 +00001724static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1725static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001726 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001727 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1728 if( pExpr->iColumn<0 ){
1729 pExpr->op = TK_NULL;
1730 }else{
1731 Expr *pNew;
1732 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1733 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1734 pNew = pEList->a[pExpr->iColumn].pExpr;
1735 assert( pNew!=0 );
1736 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001737 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001738 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001739 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001740 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001741 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001742 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001743 pExpr->iTable = pNew->iTable;
1744 pExpr->iColumn = pNew->iColumn;
1745 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001746 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1747 sqlite3TokenCopy(&pExpr->span, &pNew->span);
drh50350a12004-02-13 16:22:22 +00001748 }
drh832508b2002-03-02 17:04:07 +00001749 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001750 substExpr(pExpr->pLeft, iTable, pEList);
1751 substExpr(pExpr->pRight, iTable, pEList);
1752 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001753 }
1754}
1755static void
drh6a3ea0e2003-05-02 14:32:12 +00001756substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001757 int i;
1758 if( pList==0 ) return;
1759 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001760 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001761 }
1762}
1763
1764/*
drh1350b032002-02-27 19:00:20 +00001765** This routine attempts to flatten subqueries in order to speed
1766** execution. It returns 1 if it makes changes and 0 if no flattening
1767** occurs.
1768**
1769** To understand the concept of flattening, consider the following
1770** query:
1771**
1772** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1773**
1774** The default way of implementing this query is to execute the
1775** subquery first and store the results in a temporary table, then
1776** run the outer query on that temporary table. This requires two
1777** passes over the data. Furthermore, because the temporary table
1778** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001779** optimized.
drh1350b032002-02-27 19:00:20 +00001780**
drh832508b2002-03-02 17:04:07 +00001781** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001782** a single flat select, like this:
1783**
1784** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1785**
1786** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001787** but only has to scan the data once. And because indices might
1788** exist on the table t1, a complete scan of the data might be
1789** avoided.
drh1350b032002-02-27 19:00:20 +00001790**
drh832508b2002-03-02 17:04:07 +00001791** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001792**
drh832508b2002-03-02 17:04:07 +00001793** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001794**
drh832508b2002-03-02 17:04:07 +00001795** (2) The subquery is not an aggregate or the outer query is not a join.
1796**
drh8af4d3a2003-05-06 20:35:16 +00001797** (3) The subquery is not the right operand of a left outer join, or
1798** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001799**
1800** (4) The subquery is not DISTINCT or the outer query is not a join.
1801**
1802** (5) The subquery is not DISTINCT or the outer query does not use
1803** aggregates.
1804**
1805** (6) The subquery does not use aggregates or the outer query is not
1806** DISTINCT.
1807**
drh08192d52002-04-30 19:20:28 +00001808** (7) The subquery has a FROM clause.
1809**
drhdf199a22002-06-14 22:38:41 +00001810** (8) The subquery does not use LIMIT or the outer query is not a join.
1811**
1812** (9) The subquery does not use LIMIT or the outer query does not use
1813** aggregates.
1814**
1815** (10) The subquery does not use aggregates or the outer query does not
1816** use LIMIT.
1817**
drh174b6192002-12-03 02:22:52 +00001818** (11) The subquery and the outer query do not both have ORDER BY clauses.
1819**
drh3fc673e2003-06-16 00:40:34 +00001820** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1821** subquery has no WHERE clause. (added by ticket #350)
1822**
drh832508b2002-03-02 17:04:07 +00001823** In this routine, the "p" parameter is a pointer to the outer query.
1824** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1825** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1826**
drh665de472003-03-31 13:36:09 +00001827** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001828** If flattening is attempted this routine returns 1.
1829**
1830** All of the expression analysis must occur on both the outer query and
1831** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001832*/
drh8c74a8c2002-08-25 19:20:40 +00001833static int flattenSubquery(
1834 Parse *pParse, /* The parsing context */
1835 Select *p, /* The parent or outer SELECT statement */
1836 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1837 int isAgg, /* True if outer SELECT uses aggregate functions */
1838 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1839){
drh0bb28102002-05-08 11:54:14 +00001840 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001841 SrcList *pSrc; /* The FROM clause of the outer query */
1842 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001843 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001844 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh91bb0ee2004-09-01 03:06:34 +00001845 int i; /* Loop counter */
1846 Expr *pWhere; /* The WHERE clause */
1847 struct SrcList_item *pSubitem; /* The subquery */
drh1350b032002-02-27 19:00:20 +00001848
drh832508b2002-03-02 17:04:07 +00001849 /* Check to see if flattening is permitted. Return 0 if not.
1850 */
1851 if( p==0 ) return 0;
1852 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001853 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh91bb0ee2004-09-01 03:06:34 +00001854 pSubitem = &pSrc->a[iFrom];
1855 pSub = pSubitem->pSelect;
drh832508b2002-03-02 17:04:07 +00001856 assert( pSub!=0 );
1857 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001858 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001859 pSubSrc = pSub->pSrc;
1860 assert( pSubSrc );
drhc31c2eb2003-05-02 16:04:17 +00001861 if( pSubSrc->nSrc==0 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001862 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1863 return 0;
1864 }
drhd11d3822002-06-21 23:01:49 +00001865 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001866 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001867
drh8af4d3a2003-05-06 20:35:16 +00001868 /* Restriction 3: If the subquery is a join, make sure the subquery is
1869 ** not used as the right operand of an outer join. Examples of why this
1870 ** is not allowed:
1871 **
1872 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1873 **
1874 ** If we flatten the above, we would get
1875 **
1876 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1877 **
1878 ** which is not at all the same thing.
1879 */
1880 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1881 return 0;
1882 }
1883
drh3fc673e2003-06-16 00:40:34 +00001884 /* Restriction 12: If the subquery is the right operand of a left outer
1885 ** join, make sure the subquery has no WHERE clause.
1886 ** An examples of why this is not allowed:
1887 **
1888 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1889 **
1890 ** If we flatten the above, we would get
1891 **
1892 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1893 **
1894 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1895 ** effectively converts the OUTER JOIN into an INNER JOIN.
1896 */
1897 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1898 && pSub->pWhere!=0 ){
1899 return 0;
1900 }
1901
drh0bb28102002-05-08 11:54:14 +00001902 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001903 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001904 */
drhc31c2eb2003-05-02 16:04:17 +00001905
1906 /* Move all of the FROM elements of the subquery into the
1907 ** the FROM clause of the outer query. Before doing this, remember
1908 ** the cursor number for the original outer query FROM element in
1909 ** iParent. The iParent cursor will never be used. Subsequent code
1910 ** will scan expressions looking for iParent references and replace
1911 ** those references with expressions that resolve to the subquery FROM
1912 ** elements we are now copying in.
1913 */
drh91bb0ee2004-09-01 03:06:34 +00001914 iParent = pSubitem->iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001915 {
1916 int nSubSrc = pSubSrc->nSrc;
drh91bb0ee2004-09-01 03:06:34 +00001917 int jointype = pSubitem->jointype;
1918 Table *pTab = pSubitem->pTab;
drhc31c2eb2003-05-02 16:04:17 +00001919
drh91bb0ee2004-09-01 03:06:34 +00001920 if( pTab && pTab->isTransient ){
1921 sqlite3DeleteTable(0, pSubitem->pTab);
drhc31c2eb2003-05-02 16:04:17 +00001922 }
drh91bb0ee2004-09-01 03:06:34 +00001923 sqliteFree(pSubitem->zDatabase);
1924 sqliteFree(pSubitem->zName);
1925 sqliteFree(pSubitem->zAlias);
drhc31c2eb2003-05-02 16:04:17 +00001926 if( nSubSrc>1 ){
1927 int extra = nSubSrc - 1;
1928 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00001929 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00001930 }
1931 p->pSrc = pSrc;
1932 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1933 pSrc->a[i] = pSrc->a[i-extra];
1934 }
1935 }
1936 for(i=0; i<nSubSrc; i++){
1937 pSrc->a[i+iFrom] = pSubSrc->a[i];
1938 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1939 }
drh8af4d3a2003-05-06 20:35:16 +00001940 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00001941 }
1942
1943 /* Now begin substituting subquery result set expressions for
1944 ** references to the iParent in the outer query.
1945 **
1946 ** Example:
1947 **
1948 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1949 ** \ \_____________ subquery __________/ /
1950 ** \_____________________ outer query ______________________________/
1951 **
1952 ** We look at every expression in the outer query and every place we see
1953 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1954 */
drh6a3ea0e2003-05-02 14:32:12 +00001955 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001956 pList = p->pEList;
1957 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001958 Expr *pExpr;
1959 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1960 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001961 }
1962 }
drh1b2e0322002-03-03 02:49:51 +00001963 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00001964 substExprList(p->pGroupBy, iParent, pSub->pEList);
1965 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001966 }
drh174b6192002-12-03 02:22:52 +00001967 if( pSub->pOrderBy ){
1968 assert( p->pOrderBy==0 );
1969 p->pOrderBy = pSub->pOrderBy;
1970 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00001971 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00001972 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00001973 }
drh832508b2002-03-02 17:04:07 +00001974 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001975 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00001976 }else{
1977 pWhere = 0;
1978 }
1979 if( subqueryIsAgg ){
1980 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001981 p->pHaving = p->pWhere;
1982 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00001983 substExpr(p->pHaving, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00001984 p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
drh1b2e0322002-03-03 02:49:51 +00001985 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00001986 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00001987 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001988 substExpr(p->pWhere, iParent, pSub->pEList);
drh91bb0ee2004-09-01 03:06:34 +00001989 p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
drh832508b2002-03-02 17:04:07 +00001990 }
drhc31c2eb2003-05-02 16:04:17 +00001991
1992 /* The flattened query is distinct if either the inner or the
1993 ** outer query is distinct.
1994 */
drh832508b2002-03-02 17:04:07 +00001995 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00001996
drhc31c2eb2003-05-02 16:04:17 +00001997 /* Transfer the limit expression from the subquery to the outer
1998 ** query.
1999 */
drhdf199a22002-06-14 22:38:41 +00002000 if( pSub->nLimit>=0 ){
2001 if( p->nLimit<0 ){
2002 p->nLimit = pSub->nLimit;
2003 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
2004 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
2005 }
2006 }
2007 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00002008
drhc31c2eb2003-05-02 16:04:17 +00002009 /* Finially, delete what is left of the subquery and return
2010 ** success.
2011 */
danielk19774adee202004-05-08 08:23:19 +00002012 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00002013 return 1;
2014}
drh1350b032002-02-27 19:00:20 +00002015
2016/*
drh9562b552002-02-19 15:00:07 +00002017** Analyze the SELECT statement passed in as an argument to see if it
2018** is a simple min() or max() query. If it is and this query can be
2019** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00002020** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00002021** simple min() or max() query, then return 0;
2022**
2023** A simply min() or max() query looks like this:
2024**
2025** SELECT min(a) FROM table;
2026** SELECT max(a) FROM table;
2027**
2028** The query may have only a single table in its FROM argument. There
2029** can be no GROUP BY or HAVING or WHERE clauses. The result set must
2030** be the min() or max() of a single column of the table. The column
2031** in the min() or max() function must be indexed.
2032**
danielk19774adee202004-05-08 08:23:19 +00002033** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00002034** See the header comment on that routine for additional information.
2035*/
2036static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
2037 Expr *pExpr;
2038 int iCol;
2039 Table *pTab;
2040 Index *pIdx;
2041 int base;
2042 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00002043 int seekOp;
2044 int cont;
drh6e175292004-03-13 14:00:36 +00002045 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00002046 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00002047 SrcList *pSrc;
2048
drh9562b552002-02-19 15:00:07 +00002049
2050 /* Check to see if this query is a simple min() or max() query. Return
2051 ** zero if it is not.
2052 */
2053 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00002054 pSrc = p->pSrc;
2055 if( pSrc->nSrc!=1 ) return 0;
2056 pEList = p->pEList;
2057 if( pEList->nExpr!=1 ) return 0;
2058 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002059 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00002060 pList = pExpr->pList;
2061 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002062 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00002063 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002064 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00002065 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00002066 seekOp = OP_Last;
2067 }else{
2068 return 0;
2069 }
drh6e175292004-03-13 14:00:36 +00002070 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00002071 if( pExpr->op!=TK_COLUMN ) return 0;
2072 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00002073 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00002074
2075 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00002076 ** Check to make sure we have an index and make pIdx point to the
2077 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
2078 ** key column, no index is necessary so set pIdx to NULL. If no
2079 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00002080 */
2081 if( iCol<0 ){
2082 pIdx = 0;
2083 }else{
danielk1977dc1bdc42004-06-11 10:51:27 +00002084 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
drh9562b552002-02-19 15:00:07 +00002085 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2086 assert( pIdx->nColumn>=1 );
danielk1977dc1bdc42004-06-11 10:51:27 +00002087 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
drh9562b552002-02-19 15:00:07 +00002088 }
2089 if( pIdx==0 ) return 0;
2090 }
2091
drhe5f50722003-07-19 00:44:14 +00002092 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00002093 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00002094 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00002095 */
danielk19774adee202004-05-08 08:23:19 +00002096 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00002097 if( v==0 ) return 0;
drh9562b552002-02-19 15:00:07 +00002098
drh0c37e632004-01-30 02:01:03 +00002099 /* If the output is destined for a temporary table, open that table.
2100 */
2101 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002102 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002103 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002104 }
2105
drh17f71932002-02-21 12:01:27 +00002106 /* Generating code to find the min or the max. Basically all we have
2107 ** to do is find the first or the last entry in the chosen index. If
2108 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2109 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002110 */
danielk19774adee202004-05-08 08:23:19 +00002111 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00002112 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00002113 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00002114 if( pSrc->a[0].pSelect==0 ){
drhad6d9462004-09-19 02:15:24 +00002115 sqlite3OpenTableForReading(v, base, pTab);
drh6e175292004-03-13 14:00:36 +00002116 }
danielk19774adee202004-05-08 08:23:19 +00002117 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00002118 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002119 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002120 }else{
danielk19774adee202004-05-08 08:23:19 +00002121 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00002122 sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum,
2123 (char*)&pIdx->keyInfo, P3_KEYINFO);
drh9eb516c2004-07-18 20:52:32 +00002124 if( seekOp==OP_Rewind ){
drh1af3fdb2004-07-18 21:33:01 +00002125 sqlite3VdbeAddOp(v, OP_String, 0, 0);
2126 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
2127 seekOp = OP_MoveGt;
drh9eb516c2004-07-18 20:52:32 +00002128 }
drh1af3fdb2004-07-18 21:33:01 +00002129 sqlite3VdbeAddOp(v, seekOp, base+1, 0);
danielk19774adee202004-05-08 08:23:19 +00002130 sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
2131 sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
drh7cf6e4d2004-05-19 14:56:55 +00002132 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00002133 }
drh5cf8e8c2002-02-19 22:42:05 +00002134 eList.nExpr = 1;
2135 memset(&eListItem, 0, sizeof(eListItem));
2136 eList.a = &eListItem;
2137 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00002138 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00002139 sqlite3VdbeResolveLabel(v, cont);
2140 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002141
drh9562b552002-02-19 15:00:07 +00002142 return 1;
2143}
2144
2145/*
drh290c1942004-08-21 17:54:45 +00002146** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
2147** the number of errors seen.
2148**
2149** An ORDER BY or GROUP BY is a list of expressions. If any expression
2150** is an integer constant, then that expression is replaced by the
2151** corresponding entry in the result set.
2152*/
2153static int processOrderGroupBy(
2154 Parse *pParse, /* Parsing context */
2155 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
2156 SrcList *pTabList, /* The FROM clause */
2157 ExprList *pEList, /* The result set */
2158 int isAgg, /* True if aggregate functions are involved */
2159 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
2160){
2161 int i;
2162 if( pOrderBy==0 ) return 0;
2163 for(i=0; i<pOrderBy->nExpr; i++){
2164 int iCol;
2165 Expr *pE = pOrderBy->a[i].pExpr;
2166 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2167 sqlite3ExprDelete(pE);
2168 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2169 }
2170 if( sqlite3ExprResolveAndCheck(pParse, pTabList, pEList, pE, isAgg, 0) ){
2171 return 1;
2172 }
2173 if( sqlite3ExprIsConstant(pE) ){
2174 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2175 sqlite3ErrorMsg(pParse,
2176 "%s BY terms must not be non-integer constants", zType);
2177 return 1;
2178 }else if( iCol<=0 || iCol>pEList->nExpr ){
2179 sqlite3ErrorMsg(pParse,
2180 "%s BY column number %d out of range - should be "
2181 "between 1 and %d", zType, iCol, pEList->nExpr);
2182 return 1;
2183 }
2184 }
2185 }
2186 return 0;
2187}
2188
2189/*
drh9bb61fe2000-06-05 16:01:39 +00002190** Generate code for the given SELECT statement.
2191**
drhfef52082000-06-06 01:50:43 +00002192** The results are distributed in various ways depending on the
2193** value of eDest and iParm.
2194**
2195** eDest Value Result
2196** ------------ -------------------------------------------
2197** SRT_Callback Invoke the callback for each row of the result.
2198**
2199** SRT_Mem Store first result in memory cell iParm
2200**
danielk1977e014a832004-05-17 10:48:57 +00002201** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002202**
drh82c3d632000-06-06 21:56:07 +00002203** SRT_Union Store results as a key in a temporary table iParm
2204**
jplyon4b11c6d2004-01-19 04:57:53 +00002205** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002206**
2207** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002208**
drhe78e8282003-01-19 03:59:45 +00002209** The table above is incomplete. Additional eDist value have be added
2210** since this comment was written. See the selectInnerLoop() function for
2211** a complete listing of the allowed values of eDest and their meanings.
2212**
drh9bb61fe2000-06-05 16:01:39 +00002213** This routine returns the number of errors. If any errors are
2214** encountered, then an appropriate error message is left in
2215** pParse->zErrMsg.
2216**
2217** This routine does NOT free the Select structure passed in. The
2218** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002219**
2220** The pParent, parentTab, and *pParentAgg fields are filled in if this
2221** SELECT is a subquery. This routine may try to combine this SELECT
2222** with its parent to form a single flat query. In so doing, it might
2223** change the parent query from a non-aggregate to an aggregate query.
2224** For that reason, the pParentAgg flag is passed as a pointer, so it
2225** can be changed.
drhe78e8282003-01-19 03:59:45 +00002226**
2227** Example 1: The meaning of the pParent parameter.
2228**
2229** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2230** \ \_______ subquery _______/ /
2231** \ /
2232** \____________________ outer query ___________________/
2233**
2234** This routine is called for the outer query first. For that call,
2235** pParent will be NULL. During the processing of the outer query, this
2236** routine is called recursively to handle the subquery. For the recursive
2237** call, pParent will point to the outer query. Because the subquery is
2238** the second element in a three-way join, the parentTab parameter will
2239** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002240*/
danielk19774adee202004-05-08 08:23:19 +00002241int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002242 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002243 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002244 int eDest, /* How to dispose of the results */
2245 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002246 Select *pParent, /* Another SELECT for which this is a sub-query */
2247 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002248 int *pParentAgg, /* True if pParent uses aggregate functions */
2249 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002250){
drhd8bc7082000-06-07 23:51:50 +00002251 int i;
drhcce7d172000-05-31 15:34:51 +00002252 WhereInfo *pWInfo;
2253 Vdbe *v;
2254 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002255 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002256 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002257 Expr *pWhere; /* The WHERE clause. May be NULL */
2258 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002259 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2260 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002261 int isDistinct; /* True if the DISTINCT keyword is present */
2262 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002263 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00002264
danielk19776f8a5032004-05-10 10:34:51 +00002265 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002266 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002267
drh82c3d632000-06-06 21:56:07 +00002268 /* If there is are a sequence of queries, do the earlier ones first.
2269 */
2270 if( p->pPrior ){
danielk197784ac9d02004-05-18 09:58:06 +00002271 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002272 }
2273
2274 /* Make local copies of the parameters for this query.
2275 */
drh9bb61fe2000-06-05 16:01:39 +00002276 pTabList = p->pSrc;
2277 pWhere = p->pWhere;
2278 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00002279 pGroupBy = p->pGroupBy;
2280 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00002281 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00002282
drh6a3ea0e2003-05-02 14:32:12 +00002283 /* Allocate VDBE cursors for each table in the FROM clause
drh10e5e3c2000-06-08 00:19:02 +00002284 */
danielk19774adee202004-05-08 08:23:19 +00002285 sqlite3SrcListAssignCursors(pParse, pTabList);
drh10e5e3c2000-06-08 00:19:02 +00002286
drh9bb61fe2000-06-05 16:01:39 +00002287 /*
2288 ** Do not even attempt to generate any code if we have already seen
2289 ** errors before this routine starts.
2290 */
drh1d83f052002-02-17 00:30:36 +00002291 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002292
drhe78e8282003-01-19 03:59:45 +00002293 /* Expand any "*" terms in the result set. (For example the "*" in
2294 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
2295 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00002296 */
drhd8bc7082000-06-07 23:51:50 +00002297 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00002298 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002299 }
drhad2d8302002-05-24 20:31:36 +00002300 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00002301 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00002302 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002303
drh22827922000-06-06 17:27:05 +00002304 /* If writing to memory or generating a set
2305 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002306 */
drhfef52082000-06-06 01:50:43 +00002307 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002308 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002309 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002310 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002311 }
2312
drhc926afb2002-06-20 03:38:26 +00002313 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002314 */
drhc926afb2002-06-20 03:38:26 +00002315 switch( eDest ){
2316 case SRT_Union:
2317 case SRT_Except:
2318 case SRT_Discard:
2319 pOrderBy = 0;
2320 break;
2321 default:
2322 break;
drh22827922000-06-06 17:27:05 +00002323 }
2324
drh10e5e3c2000-06-08 00:19:02 +00002325 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002326 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002327 **
drh967e8b72000-06-21 13:59:10 +00002328 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002329 */
drh4794b982000-06-06 13:54:14 +00002330 for(i=0; i<pEList->nExpr; i++){
drh290c1942004-08-21 17:54:45 +00002331 if( sqlite3ExprResolveAndCheck(pParse, pTabList, 0, pEList->a[i].pExpr,
2332 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002333 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002334 }
2335 }
drh290c1942004-08-21 17:54:45 +00002336 if( sqlite3ExprResolveAndCheck(pParse, pTabList, pEList, pWhere, 0, 0) ){
2337 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002338 }
drhc66c5a22002-12-03 02:34:49 +00002339 if( pHaving ){
2340 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002341 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
drhc66c5a22002-12-03 02:34:49 +00002342 goto select_end;
2343 }
drh290c1942004-08-21 17:54:45 +00002344 if( sqlite3ExprResolveAndCheck(pParse, pTabList, pEList,pHaving,1,&isAgg) ){
drhc66c5a22002-12-03 02:34:49 +00002345 goto select_end;
2346 }
2347 }
drh290c1942004-08-21 17:54:45 +00002348 if( processOrderGroupBy(pParse, pOrderBy, pTabList, pEList, isAgg, "ORDER")
2349 || processOrderGroupBy(pParse, pGroupBy, pTabList, pEList, isAgg, "GROUP")
2350 ){
2351 goto select_end;
drh22827922000-06-06 17:27:05 +00002352 }
drhcce7d172000-05-31 15:34:51 +00002353
drhd820cb12002-02-18 03:21:45 +00002354 /* Begin generating code.
2355 */
danielk19774adee202004-05-08 08:23:19 +00002356 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002357 if( v==0 ) goto select_end;
2358
drhe78e8282003-01-19 03:59:45 +00002359 /* Identify column names if we will be using them in a callback. This
2360 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002361 */
2362 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002363 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002364 }
2365
drhd820cb12002-02-18 03:21:45 +00002366 /* Generate code for all sub-queries in the FROM clause
2367 */
drhad3cab52002-05-24 02:04:32 +00002368 for(i=0; i<pTabList->nSrc; i++){
danielk1977742f9472004-06-16 12:02:43 +00002369 const char *zSavedAuthContext = 0;
drhc31c2eb2003-05-02 16:04:17 +00002370 int needRestoreContext;
2371
drha76b5df2002-02-23 02:32:10 +00002372 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002373 if( pTabList->a[i].zName!=0 ){
2374 zSavedAuthContext = pParse->zAuthContext;
2375 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002376 needRestoreContext = 1;
2377 }else{
2378 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002379 }
danielk19774adee202004-05-08 08:23:19 +00002380 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
danielk197784ac9d02004-05-18 09:58:06 +00002381 pTabList->a[i].iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002382 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002383 pParse->zAuthContext = zSavedAuthContext;
2384 }
drh1b2e0322002-03-03 02:49:51 +00002385 pTabList = p->pSrc;
2386 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002387 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002388 pOrderBy = p->pOrderBy;
2389 }
drh1b2e0322002-03-03 02:49:51 +00002390 pGroupBy = p->pGroupBy;
2391 pHaving = p->pHaving;
2392 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002393 }
2394
drh6e175292004-03-13 14:00:36 +00002395 /* Check for the special case of a min() or max() function by itself
2396 ** in the result set.
2397 */
2398 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2399 rc = 0;
2400 goto select_end;
2401 }
2402
drh832508b2002-03-02 17:04:07 +00002403 /* Check to see if this is a subquery that can be "flattened" into its parent.
2404 ** If flattening is a possiblity, do so and return immediately.
2405 */
drh1b2e0322002-03-03 02:49:51 +00002406 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002407 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002408 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002409 return rc;
2410 }
drh832508b2002-03-02 17:04:07 +00002411
danielk19777cedc8d2004-06-10 10:50:08 +00002412 /* If there is an ORDER BY clause, resolve any collation sequences
2413 ** names that have been explicitly specified.
2414 */
2415 if( pOrderBy ){
2416 for(i=0; i<pOrderBy->nExpr; i++){
2417 if( pOrderBy->a[i].zName ){
2418 pOrderBy->a[i].pExpr->pColl =
2419 sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1);
2420 }
2421 }
2422 if( pParse->nErr ){
2423 goto select_end;
2424 }
2425 }
2426
drh7b58dae2003-07-20 01:16:46 +00002427 /* Set the limiter.
2428 */
2429 computeLimitRegisters(pParse, p);
2430
drh2d0794e2002-03-03 03:03:52 +00002431 /* If the output is destined for a temporary table, open that table.
2432 */
2433 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002434 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002435 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002436 }
2437
drh22827922000-06-06 17:27:05 +00002438 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002439 */
drhd820cb12002-02-18 03:21:45 +00002440 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002441 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002442 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002443 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002444 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002445 if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002446 goto select_end;
drh22827922000-06-06 17:27:05 +00002447 }
2448 }
2449 if( pGroupBy ){
2450 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002451 if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002452 goto select_end;
drh22827922000-06-06 17:27:05 +00002453 }
2454 }
2455 }
danielk19774adee202004-05-08 08:23:19 +00002456 if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002457 goto select_end;
drh22827922000-06-06 17:27:05 +00002458 }
drh191b6902000-06-08 11:13:01 +00002459 if( pOrderBy ){
2460 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002461 if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002462 goto select_end;
drh191b6902000-06-08 11:13:01 +00002463 }
2464 }
2465 }
drhefb72512000-05-31 20:00:52 +00002466 }
2467
drh22827922000-06-06 17:27:05 +00002468 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002469 */
2470 if( isAgg ){
danielk1977e159fdf2004-06-21 10:45:06 +00002471 int addr = sqlite3VdbeAddOp(v, OP_AggReset, (pGroupBy?0:1), pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002472 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002473 FuncDef *pFunc;
2474 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drhf9b596e2004-05-26 16:54:42 +00002475 sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_FUNCDEF);
drhe5095352002-02-24 03:25:14 +00002476 }
2477 }
danielk1977e159fdf2004-06-21 10:45:06 +00002478 if( pGroupBy ){
danielk1977ce2663c2004-06-11 13:19:21 +00002479 int sz = sizeof(KeyInfo) + pGroupBy->nExpr*sizeof(CollSeq*);
2480 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(sz);
2481 if( 0==pKey ){
2482 goto select_end;
2483 }
2484 pKey->enc = pParse->db->enc;
2485 pKey->nField = pGroupBy->nExpr;
2486 for(i=0; i<pGroupBy->nExpr; i++){
2487 pKey->aColl[i] = sqlite3ExprCollSeq(pParse, pGroupBy->a[i].pExpr);
2488 if( !pKey->aColl[i] ){
2489 pKey->aColl[i] = pParse->db->pDfltColl;
2490 }
2491 }
2492 sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF);
drh1bee3d72001-10-15 00:44:35 +00002493 }
drhcce7d172000-05-31 15:34:51 +00002494 }
2495
drh19a775c2000-06-05 18:54:46 +00002496 /* Initialize the memory cell to NULL
2497 */
drhfef52082000-06-06 01:50:43 +00002498 if( eDest==SRT_Mem ){
danielk19770f69c1e2004-05-29 11:24:50 +00002499 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00002500 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002501 }
2502
drh832508b2002-03-02 17:04:07 +00002503 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002504 */
drh19a775c2000-06-05 18:54:46 +00002505 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002506 distinct = pParse->nTab++;
drhd3d39e92004-05-20 22:16:29 +00002507 openTempIndex(pParse, p, distinct, 0);
drh832508b2002-03-02 17:04:07 +00002508 }else{
2509 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002510 }
drh832508b2002-03-02 17:04:07 +00002511
2512 /* Begin the database scan
2513 */
danielk19774adee202004-05-08 08:23:19 +00002514 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
drh68d2e592002-08-04 00:52:38 +00002515 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002516 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002517
drh22827922000-06-06 17:27:05 +00002518 /* Use the standard inner loop if we are not dealing with
2519 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002520 */
drhda9d6c42000-05-31 18:20:14 +00002521 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002522 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002523 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002524 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002525 }
drhcce7d172000-05-31 15:34:51 +00002526 }
drhefb72512000-05-31 20:00:52 +00002527
drhe3184742002-06-19 14:27:05 +00002528 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002529 ** processing.
drhefb72512000-05-31 20:00:52 +00002530 */
drh22827922000-06-06 17:27:05 +00002531 else{
drh268380c2004-02-25 13:47:31 +00002532 AggExpr *pAgg;
drh22827922000-06-06 17:27:05 +00002533 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002534 int lbl1;
drh22827922000-06-06 17:27:05 +00002535 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002536 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
drh22827922000-06-06 17:27:05 +00002537 }
danielk1977ededfd52004-06-17 07:53:01 +00002538 /* No affinity string is attached to the following OP_MakeRecord
drhd3d39e92004-05-20 22:16:29 +00002539 ** because we do not need to do any coercion of datatypes. */
danielk1977ededfd52004-06-17 07:53:01 +00002540 sqlite3VdbeAddOp(v, OP_MakeRecord, pGroupBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +00002541 lbl1 = sqlite3VdbeMakeLabel(v);
2542 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh268380c2004-02-25 13:47:31 +00002543 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2544 if( pAgg->isAgg ) continue;
danielk19774adee202004-05-08 08:23:19 +00002545 sqlite3ExprCode(pParse, pAgg->pExpr);
2546 sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002547 }
danielk19774adee202004-05-08 08:23:19 +00002548 sqlite3VdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002549 }
drh268380c2004-02-25 13:47:31 +00002550 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002551 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002552 int nExpr;
2553 FuncDef *pDef;
2554 if( !pAgg->isAgg ) continue;
2555 assert( pAgg->pFunc!=0 );
2556 assert( pAgg->pFunc->xStep!=0 );
2557 pDef = pAgg->pFunc;
2558 pE = pAgg->pExpr;
2559 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002560 assert( pE->op==TK_AGG_FUNCTION );
drhf9b596e2004-05-26 16:54:42 +00002561 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
danielk19774adee202004-05-08 08:23:19 +00002562 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
danielk1977dc1bdc42004-06-11 10:51:27 +00002563 if( pDef->needCollSeq ){
2564 CollSeq *pColl = 0;
2565 int j;
2566 for(j=0; !pColl && j<nExpr; j++){
2567 pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr);
2568 }
2569 if( !pColl ) pColl = pParse->db->pDfltColl;
2570 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2571 }
danielk19774adee202004-05-08 08:23:19 +00002572 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002573 }
drhcce7d172000-05-31 15:34:51 +00002574 }
2575
2576 /* End the database scan loop.
2577 */
danielk19774adee202004-05-08 08:23:19 +00002578 sqlite3WhereEnd(pWInfo);
drhcce7d172000-05-31 15:34:51 +00002579
drh22827922000-06-06 17:27:05 +00002580 /* If we are processing aggregates, we need to set up a second loop
2581 ** over all of the aggregate values and process them.
2582 */
2583 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002584 int endagg = sqlite3VdbeMakeLabel(v);
drh22827922000-06-06 17:27:05 +00002585 int startagg;
danielk19774adee202004-05-08 08:23:19 +00002586 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002587 pParse->useAgg = 1;
2588 if( pHaving ){
danielk19774adee202004-05-08 08:23:19 +00002589 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002590 }
drhdf199a22002-06-14 22:38:41 +00002591 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002592 iParm, startagg, endagg, aff) ){
drh1d83f052002-02-17 00:30:36 +00002593 goto select_end;
drh22827922000-06-06 17:27:05 +00002594 }
danielk19774adee202004-05-08 08:23:19 +00002595 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2596 sqlite3VdbeResolveLabel(v, endagg);
2597 sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002598 pParse->useAgg = 0;
2599 }
2600
drhcce7d172000-05-31 15:34:51 +00002601 /* If there is an ORDER BY clause, then we need to sort the results
2602 ** and send them to the callback one by one.
2603 */
2604 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00002605 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002606 }
drh6a535342001-10-19 16:44:56 +00002607
drhf620b4e2004-02-09 14:37:50 +00002608 /* If this was a subquery, we have now converted the subquery into a
2609 ** temporary table. So delete the subquery structure from the parent
2610 ** to prevent this subquery from being evaluated again and to force the
2611 ** the use of the temporary table.
2612 */
2613 if( pParent ){
2614 assert( pParent->pSrc->nSrc>parentTab );
2615 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00002616 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00002617 pParent->pSrc->a[parentTab].pSelect = 0;
2618 }
2619
drh1d83f052002-02-17 00:30:36 +00002620 /* The SELECT was successfully coded. Set the return code to 0
2621 ** to indicate no errors.
2622 */
2623 rc = 0;
2624
2625 /* Control jumps to here if an error is encountered above, or upon
2626 ** successful coding of the SELECT.
2627 */
2628select_end:
2629 sqliteAggregateInfoReset(pParse);
2630 return rc;
drhcce7d172000-05-31 15:34:51 +00002631}