blob: 1db17c8a9db16acec782ea098dba8d95c0483a69 [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**
drhce665cf2004-05-21 03:01:58 +000015** $Id: select.c,v 1.174 2004/05/21 03:01:59 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
drh315555c2002-10-20 15:53:03 +000019
drhcce7d172000-05-31 15:34:51 +000020/*
drh9bb61fe2000-06-05 16:01:39 +000021** Allocate a new Select structure and return a pointer to that
22** structure.
drhcce7d172000-05-31 15:34:51 +000023*/
danielk19774adee202004-05-08 08:23:19 +000024Select *sqlite3SelectNew(
drhdaffd0e2001-04-11 14:28:42 +000025 ExprList *pEList, /* which columns to include in the result */
drhad3cab52002-05-24 02:04:32 +000026 SrcList *pSrc, /* the FROM clause -- which tables to scan */
drhdaffd0e2001-04-11 14:28:42 +000027 Expr *pWhere, /* the WHERE clause */
28 ExprList *pGroupBy, /* the GROUP BY clause */
29 Expr *pHaving, /* the HAVING clause */
30 ExprList *pOrderBy, /* the ORDER BY clause */
drh9bbca4c2001-11-06 04:00:18 +000031 int isDistinct, /* true if the DISTINCT keyword is present */
32 int nLimit, /* LIMIT value. -1 means not used */
drhef0cae52003-07-16 02:19:37 +000033 int nOffset /* OFFSET value. 0 means no offset */
drh9bb61fe2000-06-05 16:01:39 +000034){
35 Select *pNew;
36 pNew = sqliteMalloc( sizeof(*pNew) );
drhdaffd0e2001-04-11 14:28:42 +000037 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +000038 sqlite3ExprListDelete(pEList);
39 sqlite3SrcListDelete(pSrc);
40 sqlite3ExprDelete(pWhere);
41 sqlite3ExprListDelete(pGroupBy);
42 sqlite3ExprDelete(pHaving);
43 sqlite3ExprListDelete(pOrderBy);
drhdaffd0e2001-04-11 14:28:42 +000044 }else{
drhb733d032004-01-24 20:18:12 +000045 if( pEList==0 ){
danielk19774adee202004-05-08 08:23:19 +000046 pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
drhb733d032004-01-24 20:18:12 +000047 }
drhdaffd0e2001-04-11 14:28:42 +000048 pNew->pEList = pEList;
49 pNew->pSrc = pSrc;
50 pNew->pWhere = pWhere;
51 pNew->pGroupBy = pGroupBy;
52 pNew->pHaving = pHaving;
53 pNew->pOrderBy = pOrderBy;
54 pNew->isDistinct = isDistinct;
55 pNew->op = TK_SELECT;
drh9bbca4c2001-11-06 04:00:18 +000056 pNew->nLimit = nLimit;
57 pNew->nOffset = nOffset;
drh7b58dae2003-07-20 01:16:46 +000058 pNew->iLimit = -1;
59 pNew->iOffset = -1;
drhdaffd0e2001-04-11 14:28:42 +000060 }
drh9bb61fe2000-06-05 16:01:39 +000061 return pNew;
62}
63
64/*
drh01f3f252002-05-24 16:14:15 +000065** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
66** type of join. Return an integer constant that expresses that type
67** in terms of the following bit values:
68**
69** JT_INNER
70** JT_OUTER
71** JT_NATURAL
72** JT_LEFT
73** JT_RIGHT
74**
75** A full outer join is the combination of JT_LEFT and JT_RIGHT.
76**
77** If an illegal or unsupported join type is seen, then still return
78** a join type, but put an error in the pParse structure.
79*/
danielk19774adee202004-05-08 08:23:19 +000080int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
drh01f3f252002-05-24 16:14:15 +000081 int jointype = 0;
82 Token *apAll[3];
83 Token *p;
84 static struct {
85 const char *zKeyword;
86 int nChar;
87 int code;
88 } keywords[] = {
89 { "natural", 7, JT_NATURAL },
drh195e6962002-05-25 00:18:20 +000090 { "left", 4, JT_LEFT|JT_OUTER },
91 { "right", 5, JT_RIGHT|JT_OUTER },
92 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
drh01f3f252002-05-24 16:14:15 +000093 { "outer", 5, JT_OUTER },
94 { "inner", 5, JT_INNER },
95 { "cross", 5, JT_INNER },
96 };
97 int i, j;
98 apAll[0] = pA;
99 apAll[1] = pB;
100 apAll[2] = pC;
drh195e6962002-05-25 00:18:20 +0000101 for(i=0; i<3 && apAll[i]; i++){
drh01f3f252002-05-24 16:14:15 +0000102 p = apAll[i];
103 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
104 if( p->n==keywords[j].nChar
danielk19774adee202004-05-08 08:23:19 +0000105 && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
drh01f3f252002-05-24 16:14:15 +0000106 jointype |= keywords[j].code;
107 break;
108 }
109 }
110 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
111 jointype |= JT_ERROR;
112 break;
113 }
114 }
drhad2d8302002-05-24 20:31:36 +0000115 if(
116 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
drh195e6962002-05-25 00:18:20 +0000117 (jointype & JT_ERROR)!=0
drhad2d8302002-05-24 20:31:36 +0000118 ){
drh01f3f252002-05-24 16:14:15 +0000119 static Token dummy = { 0, 0 };
120 char *zSp1 = " ", *zSp2 = " ";
121 if( pB==0 ){ pB = &dummy; zSp1 = 0; }
122 if( pC==0 ){ pC = &dummy; zSp2 = 0; }
danielk19774adee202004-05-08 08:23:19 +0000123 sqlite3SetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
drh01f3f252002-05-24 16:14:15 +0000124 pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
125 pParse->nErr++;
126 jointype = JT_INNER;
drh195e6962002-05-25 00:18:20 +0000127 }else if( jointype & JT_RIGHT ){
danielk19774adee202004-05-08 08:23:19 +0000128 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +0000129 "RIGHT and FULL OUTER JOINs are not currently supported");
drh195e6962002-05-25 00:18:20 +0000130 jointype = JT_INNER;
drh01f3f252002-05-24 16:14:15 +0000131 }
132 return jointype;
133}
134
135/*
drhad2d8302002-05-24 20:31:36 +0000136** Return the index of a column in a table. Return -1 if the column
137** is not contained in the table.
138*/
139static int columnIndex(Table *pTab, const char *zCol){
140 int i;
141 for(i=0; i<pTab->nCol; i++){
danielk19774adee202004-05-08 08:23:19 +0000142 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
drhad2d8302002-05-24 20:31:36 +0000143 }
144 return -1;
145}
146
147/*
148** Add a term to the WHERE expression in *ppExpr that requires the
149** zCol column to be equal in the two tables pTab1 and pTab2.
150*/
151static void addWhereTerm(
152 const char *zCol, /* Name of the column */
153 const Table *pTab1, /* First table */
154 const Table *pTab2, /* Second table */
155 Expr **ppExpr /* Add the equality term to this expression */
156){
157 Token dummy;
158 Expr *pE1a, *pE1b, *pE1c;
159 Expr *pE2a, *pE2b, *pE2c;
160 Expr *pE;
161
162 dummy.z = zCol;
163 dummy.n = strlen(zCol);
drh4b59ab52002-08-24 18:24:51 +0000164 dummy.dyn = 0;
danielk19774adee202004-05-08 08:23:19 +0000165 pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy);
166 pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy);
drhad2d8302002-05-24 20:31:36 +0000167 dummy.z = pTab1->zName;
168 dummy.n = strlen(dummy.z);
danielk19774adee202004-05-08 08:23:19 +0000169 pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy);
drhad2d8302002-05-24 20:31:36 +0000170 dummy.z = pTab2->zName;
171 dummy.n = strlen(dummy.z);
danielk19774adee202004-05-08 08:23:19 +0000172 pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy);
173 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
174 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
175 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
drh1f162302002-10-27 19:35:33 +0000176 ExprSetProperty(pE, EP_FromJoin);
drhad2d8302002-05-24 20:31:36 +0000177 if( *ppExpr ){
danielk19774adee202004-05-08 08:23:19 +0000178 *ppExpr = sqlite3Expr(TK_AND, *ppExpr, pE, 0);
drhad2d8302002-05-24 20:31:36 +0000179 }else{
180 *ppExpr = pE;
181 }
182}
183
184/*
drh1f162302002-10-27 19:35:33 +0000185** Set the EP_FromJoin property on all terms of the given expression.
drh1cc093c2002-06-24 22:01:57 +0000186**
drhe78e8282003-01-19 03:59:45 +0000187** The EP_FromJoin property is used on terms of an expression to tell
drh1cc093c2002-06-24 22:01:57 +0000188** the LEFT OUTER JOIN processing logic that this term is part of the
drh1f162302002-10-27 19:35:33 +0000189** join restriction specified in the ON or USING clause and not a part
190** of the more general WHERE clause. These terms are moved over to the
191** WHERE clause during join processing but we need to remember that they
192** originated in the ON or USING clause.
drh1cc093c2002-06-24 22:01:57 +0000193*/
194static void setJoinExpr(Expr *p){
195 while( p ){
drh1f162302002-10-27 19:35:33 +0000196 ExprSetProperty(p, EP_FromJoin);
drh1cc093c2002-06-24 22:01:57 +0000197 setJoinExpr(p->pLeft);
198 p = p->pRight;
199 }
200}
201
202/*
drhad2d8302002-05-24 20:31:36 +0000203** This routine processes the join information for a SELECT statement.
204** ON and USING clauses are converted into extra terms of the WHERE clause.
205** NATURAL joins also create extra WHERE clause terms.
206**
207** This routine returns the number of errors encountered.
208*/
209static int sqliteProcessJoin(Parse *pParse, Select *p){
210 SrcList *pSrc;
211 int i, j;
212 pSrc = p->pSrc;
213 for(i=0; i<pSrc->nSrc-1; i++){
214 struct SrcList_item *pTerm = &pSrc->a[i];
215 struct SrcList_item *pOther = &pSrc->a[i+1];
216
217 if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
218
219 /* When the NATURAL keyword is present, add WHERE clause terms for
220 ** every column that the two tables have in common.
221 */
222 if( pTerm->jointype & JT_NATURAL ){
223 Table *pTab;
224 if( pTerm->pOn || pTerm->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000225 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
drhad2d8302002-05-24 20:31:36 +0000226 "an ON or USING clause", 0);
drhad2d8302002-05-24 20:31:36 +0000227 return 1;
228 }
229 pTab = pTerm->pTab;
230 for(j=0; j<pTab->nCol; j++){
231 if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
232 addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
233 }
234 }
235 }
236
237 /* Disallow both ON and USING clauses in the same join
238 */
239 if( pTerm->pOn && pTerm->pUsing ){
danielk19774adee202004-05-08 08:23:19 +0000240 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
drhda93d232003-03-31 02:12:46 +0000241 "clauses in the same join");
drhad2d8302002-05-24 20:31:36 +0000242 return 1;
243 }
244
245 /* Add the ON clause to the end of the WHERE clause, connected by
246 ** and AND operator.
247 */
248 if( pTerm->pOn ){
drh1cc093c2002-06-24 22:01:57 +0000249 setJoinExpr(pTerm->pOn);
drhad2d8302002-05-24 20:31:36 +0000250 if( p->pWhere==0 ){
251 p->pWhere = pTerm->pOn;
252 }else{
danielk19774adee202004-05-08 08:23:19 +0000253 p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pTerm->pOn, 0);
drhad2d8302002-05-24 20:31:36 +0000254 }
255 pTerm->pOn = 0;
256 }
257
258 /* Create extra terms on the WHERE clause for each column named
259 ** in the USING clause. Example: If the two tables to be joined are
260 ** A and B and the USING clause names X, Y, and Z, then add this
261 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
262 ** Report an error if any column mentioned in the USING clause is
263 ** not contained in both tables to be joined.
264 */
265 if( pTerm->pUsing ){
266 IdList *pList;
267 int j;
268 assert( i<pSrc->nSrc-1 );
269 pList = pTerm->pUsing;
270 for(j=0; j<pList->nId; j++){
drhbf5cd972002-06-24 12:20:23 +0000271 if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
272 columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
danielk19774adee202004-05-08 08:23:19 +0000273 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
drhda93d232003-03-31 02:12:46 +0000274 "not present in both tables", pList->a[j].zName);
drhad2d8302002-05-24 20:31:36 +0000275 return 1;
276 }
drhbf5cd972002-06-24 12:20:23 +0000277 addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
drhad2d8302002-05-24 20:31:36 +0000278 }
279 }
280 }
281 return 0;
282}
283
284/*
drh9bb61fe2000-06-05 16:01:39 +0000285** Delete the given Select structure and all of its substructures.
286*/
danielk19774adee202004-05-08 08:23:19 +0000287void sqlite3SelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +0000288 if( p==0 ) return;
danielk19774adee202004-05-08 08:23:19 +0000289 sqlite3ExprListDelete(p->pEList);
290 sqlite3SrcListDelete(p->pSrc);
291 sqlite3ExprDelete(p->pWhere);
292 sqlite3ExprListDelete(p->pGroupBy);
293 sqlite3ExprDelete(p->pHaving);
294 sqlite3ExprListDelete(p->pOrderBy);
295 sqlite3SelectDelete(p->pPrior);
drha76b5df2002-02-23 02:32:10 +0000296 sqliteFree(p->zSelect);
drh9bb61fe2000-06-05 16:01:39 +0000297 sqliteFree(p);
298}
299
300/*
drh22827922000-06-06 17:27:05 +0000301** Delete the aggregate information from the parse structure.
302*/
drh1d83f052002-02-17 00:30:36 +0000303static void sqliteAggregateInfoReset(Parse *pParse){
drh22827922000-06-06 17:27:05 +0000304 sqliteFree(pParse->aAgg);
305 pParse->aAgg = 0;
306 pParse->nAgg = 0;
drh22827922000-06-06 17:27:05 +0000307 pParse->useAgg = 0;
308}
309
310/*
drhc926afb2002-06-20 03:38:26 +0000311** Insert code into "v" that will push the record on the top of the
312** stack into the sorter.
drh428702d2004-05-18 22:38:31 +0000313**
314** FIX ME: Change this so that it uses the OP_MakeKey opcode
315** instead of OP_SortMakeKey. Delete the OP_SortMakeKey opcode.
316** All columns should have affinity NONE. Handle ASC versus
317** DESC sort order by defining a list of comparison functions to
318** be used by the OP_Sort opcode.
drhc926afb2002-06-20 03:38:26 +0000319*/
320static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
drhc926afb2002-06-20 03:38:26 +0000321 int i;
drhc926afb2002-06-20 03:38:26 +0000322 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000323 sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
drhc926afb2002-06-20 03:38:26 +0000324 }
drhffbc3082004-05-21 01:29:06 +0000325 sqlite3VdbeAddOp(v, OP_MakeKey, pOrderBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +0000326 sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000327}
328
329/*
drh22827922000-06-06 17:27:05 +0000330** This routine generates the code for the inside of the inner loop
331** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000332**
drh38640e12002-07-05 21:42:36 +0000333** If srcTab and nColumn are both zero, then the pEList expressions
334** are evaluated in order to get the data for this row. If nColumn>0
335** then data is pulled from srcTab and pEList is used only to get the
336** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000337*/
338static int selectInnerLoop(
339 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000340 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000341 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000342 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000343 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000344 ExprList *pOrderBy, /* If not NULL, sort results using this key */
345 int distinct, /* If >=0, make sure results are distinct */
346 int eDest, /* How to dispose of the results */
347 int iParm, /* An argument to the disposal method */
348 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000349 int iBreak, /* Jump here to break out of the inner loop */
350 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000351){
352 Vdbe *v = pParse->pVdbe;
353 int i;
drh38640e12002-07-05 21:42:36 +0000354
drhdaffd0e2001-04-11 14:28:42 +0000355 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000356 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000357
drhdf199a22002-06-14 22:38:41 +0000358 /* If there was a LIMIT clause on the SELECT statement, then do the check
359 ** to see if this row should be output.
360 */
361 if( pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +0000362 if( p->iOffset>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000363 int addr = sqlite3VdbeCurrentAddr(v);
364 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2);
365 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhdf199a22002-06-14 22:38:41 +0000366 }
drh7b58dae2003-07-20 01:16:46 +0000367 if( p->iLimit>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000368 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhdf199a22002-06-14 22:38:41 +0000369 }
370 }
371
drh967e8b72000-06-21 13:59:10 +0000372 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000373 */
drh38640e12002-07-05 21:42:36 +0000374 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000375 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000376 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000377 }
drh38640e12002-07-05 21:42:36 +0000378 }else{
379 nColumn = pEList->nExpr;
380 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000381 sqlite3ExprCode(pParse, pEList->a[i].pExpr);
drh38640e12002-07-05 21:42:36 +0000382 }
drh22827922000-06-06 17:27:05 +0000383 }
384
drhdaffd0e2001-04-11 14:28:42 +0000385 /* If the DISTINCT keyword was present on the SELECT statement
386 ** and this row has been seen before, then do not make this row
387 ** part of the result.
drh22827922000-06-06 17:27:05 +0000388 */
drhf5905aa2002-05-26 20:54:33 +0000389 if( distinct>=0 && pEList && pEList->nExpr>0 ){
drh0bd1f4e2002-06-06 18:54:39 +0000390#if NULL_ALWAYS_DISTINCT
danielk19774adee202004-05-08 08:23:19 +0000391 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
drh0bd1f4e2002-06-06 18:54:39 +0000392#endif
drhd3d39e92004-05-20 22:16:29 +0000393 /* Deliberately leave the affinity string off of the following OP_MakeKey */
danielk19774adee202004-05-08 08:23:19 +0000394 sqlite3VdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
danielk19774adee202004-05-08 08:23:19 +0000395 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
396 sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
397 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
398 sqlite3VdbeAddOp(v, OP_String, 0, 0);
399 sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
drh22827922000-06-06 17:27:05 +0000400 }
drh82c3d632000-06-06 21:56:07 +0000401
drhc926afb2002-06-20 03:38:26 +0000402 switch( eDest ){
403 /* In this mode, write each query result to the key of the temporary
404 ** table iParm.
405 */
406 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000407 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000408 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000409 sqlite3VdbeAddOp(v, OP_String, 0, 0);
410 sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000411 break;
drh22827922000-06-06 17:27:05 +0000412 }
drh22827922000-06-06 17:27:05 +0000413
drhc926afb2002-06-20 03:38:26 +0000414 /* Store the result as data using a unique key.
415 */
416 case SRT_Table:
417 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000418 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000419 if( pOrderBy ){
420 pushOntoSorter(pParse, v, pOrderBy);
421 }else{
danielk19774adee202004-05-08 08:23:19 +0000422 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
423 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
424 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000425 }
426 break;
427 }
drh82c3d632000-06-06 21:56:07 +0000428
drhc926afb2002-06-20 03:38:26 +0000429 /* Construct a record from the query result, but instead of
430 ** saving that record, use it as a key to delete elements from
431 ** the temporary table iParm.
432 */
433 case SRT_Except: {
434 int addr;
danielk19774adee202004-05-08 08:23:19 +0000435 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000436 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000437 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
438 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000439 break;
440 }
drh5974a302000-06-07 14:42:26 +0000441
drhc926afb2002-06-20 03:38:26 +0000442 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
443 ** then there should be a single item on the stack. Write this
444 ** item into the set table with bogus data.
445 */
446 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000447 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000448 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000449
drhc926afb2002-06-20 03:38:26 +0000450 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000451 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
452 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
453 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000454 if( pOrderBy ){
455 pushOntoSorter(pParse, v, pOrderBy);
456 }else{
danielk1977e014a832004-05-17 10:48:57 +0000457 char const *affStr;
458 char aff = (iParm>>16)&0xFF;
459 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
460 affStr = sqlite3AffinityString(aff);
danielk197784ac9d02004-05-18 09:58:06 +0000461 sqlite3VdbeOp3(v, OP_MakeKey, 1, 0, affStr, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000462 sqlite3VdbeAddOp(v, OP_String, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000463 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000464 }
danielk19774adee202004-05-08 08:23:19 +0000465 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000466 break;
467 }
drh22827922000-06-06 17:27:05 +0000468
drhc926afb2002-06-20 03:38:26 +0000469 /* If this is a scalar select that is part of an expression, then
470 ** store the results in the appropriate memory cell and break out
471 ** of the scan loop.
472 */
473 case SRT_Mem: {
474 assert( nColumn==1 );
475 if( pOrderBy ){
476 pushOntoSorter(pParse, v, pOrderBy);
477 }else{
danielk19774adee202004-05-08 08:23:19 +0000478 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
479 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000480 }
481 break;
482 }
drh22827922000-06-06 17:27:05 +0000483
drhf46f9052002-06-22 02:33:38 +0000484 /* Send the data to the callback function.
485 */
486 case SRT_Callback:
487 case SRT_Sorter: {
488 if( pOrderBy ){
drhce665cf2004-05-21 03:01:58 +0000489 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000490 pushOntoSorter(pParse, v, pOrderBy);
491 }else{
492 assert( eDest==SRT_Callback );
danielk19774adee202004-05-08 08:23:19 +0000493 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000494 }
495 break;
496 }
497
drh142e30d2002-08-28 03:00:58 +0000498 /* Invoke a subroutine to handle the results. The subroutine itself
499 ** is responsible for popping the results off of the stack.
500 */
501 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000502 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000503 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000504 pushOntoSorter(pParse, v, pOrderBy);
505 }else{
danielk19774adee202004-05-08 08:23:19 +0000506 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhac82fcf2002-09-08 17:23:41 +0000507 }
drh142e30d2002-08-28 03:00:58 +0000508 break;
509 }
510
drhc926afb2002-06-20 03:38:26 +0000511 /* Discard the results. This is used for SELECT statements inside
512 ** the body of a TRIGGER. The purpose of such selects is to call
513 ** user-defined functions that have side effects. We do not care
514 ** about the actual results of the select.
515 */
drhc926afb2002-06-20 03:38:26 +0000516 default: {
drhf46f9052002-06-22 02:33:38 +0000517 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000518 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000519 break;
520 }
drh82c3d632000-06-06 21:56:07 +0000521 }
522 return 0;
523}
524
525/*
drhd8bc7082000-06-07 23:51:50 +0000526** If the inner loop was generated using a non-null pOrderBy argument,
527** then the results were placed in a sorter. After the loop is terminated
528** we need to run the sorter and output the results. The following
529** routine generates the code needed to do that.
530*/
drhc926afb2002-06-20 03:38:26 +0000531static void generateSortTail(
drhffbc3082004-05-21 01:29:06 +0000532 Parse *pParse, /* The parsing context */
drhc926afb2002-06-20 03:38:26 +0000533 Select *p, /* The SELECT statement */
534 Vdbe *v, /* Generate code into this VDBE */
535 int nColumn, /* Number of columns of data */
536 int eDest, /* Write the sorted results here */
537 int iParm /* Optional parameter associated with eDest */
538){
danielk19774adee202004-05-08 08:23:19 +0000539 int end1 = sqlite3VdbeMakeLabel(v);
540 int end2 = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000541 int addr;
drhffbc3082004-05-21 01:29:06 +0000542 KeyInfo *pInfo;
543 ExprList *pOrderBy;
544 int nCol, i;
545 sqlite *db = pParse->db;
546
drhf46f9052002-06-22 02:33:38 +0000547 if( eDest==SRT_Sorter ) return;
drhffbc3082004-05-21 01:29:06 +0000548 pOrderBy = p->pOrderBy;
549 nCol = pOrderBy->nExpr;
550 pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
551 if( pInfo==0 ) return;
552 pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
553 pInfo->nField = nCol;
554 for(i=0; i<nCol; i++){
555 pInfo->aColl[i] = db->pDfltColl;
556 pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
557 }
558 sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
danielk19774adee202004-05-08 08:23:19 +0000559 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
drh7b58dae2003-07-20 01:16:46 +0000560 if( p->iOffset>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000561 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4);
562 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
563 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
drhdf199a22002-06-14 22:38:41 +0000564 }
drh7b58dae2003-07-20 01:16:46 +0000565 if( p->iLimit>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000566 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, end2);
drhdf199a22002-06-14 22:38:41 +0000567 }
drhc926afb2002-06-20 03:38:26 +0000568 switch( eDest ){
drhc926afb2002-06-20 03:38:26 +0000569 case SRT_Table:
570 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000571 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
572 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
573 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000574 break;
575 }
576 case SRT_Set: {
577 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000578 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
579 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
580 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
drhd6861792004-05-20 03:02:47 +0000581 sqlite3VdbeOp3(v, OP_MakeKey, 1, 0, "n", P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000582 sqlite3VdbeAddOp(v, OP_String, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000583 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000584 break;
585 }
586 case SRT_Mem: {
587 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000588 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
589 sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
drhc926afb2002-06-20 03:38:26 +0000590 break;
591 }
drhce665cf2004-05-21 03:01:58 +0000592 case SRT_Callback:
drhac82fcf2002-09-08 17:23:41 +0000593 case SRT_Subroutine: {
594 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000595 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
596 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000597 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000598 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000599 }
drhce665cf2004-05-21 03:01:58 +0000600 if( eDest==SRT_Callback ){
601 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
602 }else{
603 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
604 }
danielk197784ac9d02004-05-18 09:58:06 +0000605 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000606 break;
607 }
drhc926afb2002-06-20 03:38:26 +0000608 default: {
drhf46f9052002-06-22 02:33:38 +0000609 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000610 break;
611 }
612 }
danielk19774adee202004-05-08 08:23:19 +0000613 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
614 sqlite3VdbeResolveLabel(v, end2);
615 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
616 sqlite3VdbeResolveLabel(v, end1);
617 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000618}
619
620/*
drhfcb78a42003-01-18 20:11:05 +0000621** Generate code that will tell the VDBE the datatypes of
622** columns in the result set.
drhe78e8282003-01-19 03:59:45 +0000623**
624** This routine only generates code if the "PRAGMA show_datatypes=on"
625** has been executed. The datatypes are reported out in the azCol
626** parameter to the callback function. The first N azCol[] entries
627** are the names of the columns, and the second N entries are the
628** datatypes for the columns.
629**
630** The "datatype" for a result that is a column of a type is the
631** datatype definition extracted from the CREATE TABLE statement.
632** The datatype for an expression is either TEXT or NUMERIC. The
633** datatype for a ROWID field is INTEGER.
drhfcb78a42003-01-18 20:11:05 +0000634*/
635static void generateColumnTypes(
636 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000637 SrcList *pTabList, /* List of tables */
638 ExprList *pEList /* Expressions defining the result set */
639){
640 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000641 int i, j;
drhfcb78a42003-01-18 20:11:05 +0000642 for(i=0; i<pEList->nExpr; i++){
643 Expr *p = pEList->a[i].pExpr;
644 char *zType = 0;
645 if( p==0 ) continue;
646 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000647 Table *pTab;
drhfcb78a42003-01-18 20:11:05 +0000648 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000649 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
650 assert( j<pTabList->nSrc );
651 pTab = pTabList->a[j].pTab;
drhfcb78a42003-01-18 20:11:05 +0000652 if( iCol<0 ) iCol = pTab->iPKey;
653 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
654 if( iCol<0 ){
655 zType = "INTEGER";
656 }else{
657 zType = pTab->aCol[iCol].zType;
658 }
659 }else{
drh736c22b2004-05-21 02:14:24 +0000660 switch( sqlite3ExprType(p) ){
661 case SQLITE_AFF_TEXT: zType = "TEXT"; break;
662 case SQLITE_AFF_NUMERIC: zType = "NUMERIC"; break;
663 default: zType = "ANY"; break;
664 }
drhfcb78a42003-01-18 20:11:05 +0000665 }
danielk19774adee202004-05-08 08:23:19 +0000666 sqlite3VdbeOp3(v, OP_ColumnName, i + pEList->nExpr, 0, zType, 0);
drhfcb78a42003-01-18 20:11:05 +0000667 }
668}
669
670/*
671** Generate code that will tell the VDBE the names of columns
672** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000673** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000674*/
drh832508b2002-03-02 17:04:07 +0000675static void generateColumnNames(
676 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000677 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000678 ExprList *pEList /* Expressions defining the result set */
679){
drhd8bc7082000-06-07 23:51:50 +0000680 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000681 int i, j;
drhfcabd462004-02-20 14:50:58 +0000682 sqlite *db = pParse->db;
683 int fullNames, shortNames;
684
drhd6502752004-02-16 03:44:01 +0000685 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000686 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000687 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000688 fullNames = (db->flags & SQLITE_FullColNames)!=0;
689 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
drh82c3d632000-06-06 21:56:07 +0000690 for(i=0; i<pEList->nExpr; i++){
691 Expr *p;
drhd6502752004-02-16 03:44:01 +0000692 int p2 = i==pEList->nExpr-1;
drh5a387052003-01-11 14:19:51 +0000693 p = pEList->a[i].pExpr;
694 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000695 if( pEList->a[i].zName ){
696 char *zName = pEList->a[i].zName;
danielk19774adee202004-05-08 08:23:19 +0000697 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000698 continue;
699 }
drhfa173a72002-07-10 21:26:00 +0000700 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000701 Table *pTab;
drh97665872002-02-13 23:22:53 +0000702 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000703 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000704 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
705 assert( j<pTabList->nSrc );
706 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000707 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000708 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000709 if( iCol<0 ){
710 zCol = "_ROWID_";
drhb1363202002-06-26 02:45:03 +0000711 }else{
712 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000713 }
drhfcabd462004-02-20 14:50:58 +0000714 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000715 int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
716 sqlite3VdbeCompressSpace(v, addr);
drhfcabd462004-02-20 14:50:58 +0000717 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000718 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000719 char *zTab;
720
drh6a3ea0e2003-05-02 14:32:12 +0000721 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000722 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000723 sqlite3SetString(&zName, zTab, ".", zCol, 0);
724 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000725 }else{
danielk19774adee202004-05-08 08:23:19 +0000726 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000727 }
drh6977fea2002-10-22 23:38:04 +0000728 }else if( p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000729 int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
730 sqlite3VdbeCompressSpace(v, addr);
drh1bee3d72001-10-15 00:44:35 +0000731 }else{
732 char zName[30];
733 assert( p->op!=TK_COLUMN || pTabList==0 );
734 sprintf(zName, "column%d", i+1);
danielk19774adee202004-05-08 08:23:19 +0000735 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000736 }
737 }
738}
739
740/*
drhd8bc7082000-06-07 23:51:50 +0000741** Name of the connection operator, used for error messages.
742*/
743static const char *selectOpName(int id){
744 char *z;
745 switch( id ){
746 case TK_ALL: z = "UNION ALL"; break;
747 case TK_INTERSECT: z = "INTERSECT"; break;
748 case TK_EXCEPT: z = "EXCEPT"; break;
749 default: z = "UNION"; break;
750 }
751 return z;
752}
753
754/*
drh315555c2002-10-20 15:53:03 +0000755** Forward declaration
756*/
757static int fillInColumnList(Parse*, Select*);
758
759/*
drh22f70c32002-02-18 01:17:00 +0000760** Given a SELECT statement, generate a Table structure that describes
761** the result set of that SELECT.
762*/
danielk19774adee202004-05-08 08:23:19 +0000763Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000764 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000765 int i, j;
drh22f70c32002-02-18 01:17:00 +0000766 ExprList *pEList;
drhb733d032004-01-24 20:18:12 +0000767 Column *aCol;
drh22f70c32002-02-18 01:17:00 +0000768
769 if( fillInColumnList(pParse, pSelect) ){
770 return 0;
771 }
772 pTab = sqliteMalloc( sizeof(Table) );
773 if( pTab==0 ){
774 return 0;
775 }
776 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
777 pEList = pSelect->pEList;
778 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000779 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000780 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh22f70c32002-02-18 01:17:00 +0000781 for(i=0; i<pTab->nCol; i++){
drhb733d032004-01-24 20:18:12 +0000782 Expr *p, *pR;
drh22f70c32002-02-18 01:17:00 +0000783 if( pEList->a[i].zName ){
drhb733d032004-01-24 20:18:12 +0000784 aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
785 }else if( (p=pEList->a[i].pExpr)->op==TK_DOT
786 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
787 int cnt;
danielk19774adee202004-05-08 08:23:19 +0000788 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
drhb733d032004-01-24 20:18:12 +0000789 for(j=cnt=0; j<i; j++){
danielk19774adee202004-05-08 08:23:19 +0000790 if( sqlite3StrICmp(aCol[j].zName, aCol[i].zName)==0 ){
drhb733d032004-01-24 20:18:12 +0000791 int n;
792 char zBuf[30];
793 sprintf(zBuf,"_%d",++cnt);
794 n = strlen(zBuf);
danielk1977e014a832004-05-17 10:48:57 +0000795 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf,n,0);
drhb733d032004-01-24 20:18:12 +0000796 j = -1;
797 }
798 }
799 }else if( p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000800 sqlite3SetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drh22f70c32002-02-18 01:17:00 +0000801 }else{
802 char zBuf[30];
803 sprintf(zBuf, "column%d", i+1);
804 pTab->aCol[i].zName = sqliteStrDup(zBuf);
805 }
danielk1977e014a832004-05-17 10:48:57 +0000806
807 /* Affinity is always NONE, as there is no type name. */
808 pTab->aCol[i].affinity = SQLITE_AFF_NONE;
drh22f70c32002-02-18 01:17:00 +0000809 }
810 pTab->iPKey = -1;
811 return pTab;
812}
813
814/*
drhad2d8302002-05-24 20:31:36 +0000815** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000816**
drhad3cab52002-05-24 02:04:32 +0000817** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh63eb5f22003-04-29 16:20:44 +0000818** defines the set of tables that should be scanned. For views,
819** fill pTabList->a[].pSelect with a copy of the SELECT statement
820** that implements the view. A copy is made of the view's SELECT
821** statement so that we can freely modify or delete that statement
822** without worrying about messing up the presistent representation
823** of the view.
drhd8bc7082000-06-07 23:51:50 +0000824**
drhad2d8302002-05-24 20:31:36 +0000825** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
826** on joins and the ON and USING clause of joins.
827**
828** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000829** for instances of the "*" operator or the TABLE.* operator.
830** If found, expand each "*" to be every column in every table
831** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000832**
833** Return 0 on success. If there are problems, leave an error message
834** in pParse and return non-zero.
835*/
836static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000837 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000838 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000839 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000840 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000841
842 if( p==0 || p->pSrc==0 ) return 1;
843 pTabList = p->pSrc;
844 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000845
846 /* Look up every table in the table list.
847 */
drhad3cab52002-05-24 02:04:32 +0000848 for(i=0; i<pTabList->nSrc; i++){
drhd8bc7082000-06-07 23:51:50 +0000849 if( pTabList->a[i].pTab ){
850 /* This routine has run before! No need to continue */
851 return 0;
852 }
drhdaffd0e2001-04-11 14:28:42 +0000853 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000854 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000855 assert( pTabList->a[i].pSelect!=0 );
drhad2d8302002-05-24 20:31:36 +0000856 if( pTabList->a[i].zAlias==0 ){
857 char zFakeName[60];
858 sprintf(zFakeName, "sqlite_subquery_%p_",
859 (void*)pTabList->a[i].pSelect);
danielk19774adee202004-05-08 08:23:19 +0000860 sqlite3SetString(&pTabList->a[i].zAlias, zFakeName, 0);
drhad2d8302002-05-24 20:31:36 +0000861 }
drh22f70c32002-02-18 01:17:00 +0000862 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000863 sqlite3ResultSetOfSelect(pParse, pTabList->a[i].zAlias,
drh22f70c32002-02-18 01:17:00 +0000864 pTabList->a[i].pSelect);
865 if( pTab==0 ){
866 return 1;
867 }
drh5cf590c2003-04-24 01:45:04 +0000868 /* The isTransient flag indicates that the Table structure has been
869 ** dynamically allocated and may be freed at any time. In other words,
870 ** pTab is not pointing to a persistent table structure that defines
871 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000872 pTab->isTransient = 1;
873 }else{
drha76b5df2002-02-23 02:32:10 +0000874 /* An ordinary table or view name in the FROM clause */
875 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000876 sqlite3LocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
drha76b5df2002-02-23 02:32:10 +0000877 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000878 return 1;
879 }
drha76b5df2002-02-23 02:32:10 +0000880 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +0000881 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +0000882 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +0000883 return 1;
884 }
drh63eb5f22003-04-29 16:20:44 +0000885 /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
886 ** view within a view. The SELECT structure has already been
887 ** copied by the outer view so we can skip the copy step here
888 ** in the inner view.
889 */
890 if( pTabList->a[i].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +0000891 pTabList->a[i].pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +0000892 }
drha76b5df2002-02-23 02:32:10 +0000893 }
drhd8bc7082000-06-07 23:51:50 +0000894 }
895 }
896
drhad2d8302002-05-24 20:31:36 +0000897 /* Process NATURAL keywords, and ON and USING clauses of joins.
898 */
899 if( sqliteProcessJoin(pParse, p) ) return 1;
900
drh7c917d12001-12-16 20:05:05 +0000901 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000902 ** all columns in all tables. And for every TABLE.* insert the names
903 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000904 ** with the TK_ALL operator for each "*" that it found in the column list.
905 ** The following code just has to locate the TK_ALL expressions and expand
906 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000907 **
908 ** The first loop just checks to see if there are any "*" operators
909 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000910 */
drh7c917d12001-12-16 20:05:05 +0000911 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000912 Expr *pE = pEList->a[k].pExpr;
913 if( pE->op==TK_ALL ) break;
914 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
915 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000916 }
drh54473222002-04-04 02:10:55 +0000917 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000918 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000919 /*
920 ** If we get here it means the result set contains one or more "*"
921 ** operators that need to be expanded. Loop through each expression
922 ** in the result set and expand them one by one.
923 */
drh7c917d12001-12-16 20:05:05 +0000924 struct ExprList_item *a = pEList->a;
925 ExprList *pNew = 0;
926 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000927 Expr *pE = a[k].pExpr;
928 if( pE->op!=TK_ALL &&
929 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
930 /* This particular expression does not need to be expanded.
931 */
danielk19774adee202004-05-08 08:23:19 +0000932 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +0000933 pNew->a[pNew->nExpr-1].zName = a[k].zName;
934 a[k].pExpr = 0;
935 a[k].zName = 0;
936 }else{
drh54473222002-04-04 02:10:55 +0000937 /* This expression is a "*" or a "TABLE.*" and needs to be
938 ** expanded. */
939 int tableSeen = 0; /* Set to 1 when TABLE matches */
940 Token *pName; /* text of name of TABLE */
941 if( pE->op==TK_DOT && pE->pLeft ){
942 pName = &pE->pLeft->token;
943 }else{
944 pName = 0;
945 }
drhad3cab52002-05-24 02:04:32 +0000946 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000947 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000948 char *zTabName = pTabList->a[i].zAlias;
949 if( zTabName==0 || zTabName[0]==0 ){
950 zTabName = pTab->zName;
951 }
drhc754fa52002-05-27 03:25:51 +0000952 if( pName && (zTabName==0 || zTabName[0]==0 ||
danielk19774adee202004-05-08 08:23:19 +0000953 sqlite3StrNICmp(pName->z, zTabName, pName->n)!=0 ||
drhc754fa52002-05-27 03:25:51 +0000954 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +0000955 continue;
956 }
957 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +0000958 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000959 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +0000960 char *zName = pTab->aCol[j].zName;
961
962 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
963 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
964 /* In a NATURAL join, omit the join columns from the
965 ** table on the right */
966 continue;
967 }
danielk19774adee202004-05-08 08:23:19 +0000968 if( i>0 && sqlite3IdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
drhad2d8302002-05-24 20:31:36 +0000969 /* In a join with a USING clause, omit columns in the
970 ** using clause from the table on the right. */
971 continue;
972 }
danielk19774adee202004-05-08 08:23:19 +0000973 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +0000974 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +0000975 pRight->token.z = zName;
976 pRight->token.n = strlen(zName);
drh4b59ab52002-08-24 18:24:51 +0000977 pRight->token.dyn = 0;
drh4b59ab52002-08-24 18:24:51 +0000978 if( zTabName && pTabList->nSrc>1 ){
danielk19774adee202004-05-08 08:23:19 +0000979 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
980 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +0000981 if( pExpr==0 ) break;
drh4b59ab52002-08-24 18:24:51 +0000982 pLeft->token.z = zTabName;
983 pLeft->token.n = strlen(zTabName);
984 pLeft->token.dyn = 0;
danielk19774adee202004-05-08 08:23:19 +0000985 sqlite3SetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
drh6977fea2002-10-22 23:38:04 +0000986 pExpr->span.n = strlen(pExpr->span.z);
987 pExpr->span.dyn = 1;
988 pExpr->token.z = 0;
989 pExpr->token.n = 0;
990 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +0000991 }else{
drh22f70c32002-02-18 01:17:00 +0000992 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +0000993 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +0000994 }
danielk19774adee202004-05-08 08:23:19 +0000995 pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
drh7c917d12001-12-16 20:05:05 +0000996 }
drh17e24df2001-11-06 14:10:41 +0000997 }
drh54473222002-04-04 02:10:55 +0000998 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +0000999 if( pName ){
danielk19774adee202004-05-08 08:23:19 +00001000 sqlite3ErrorMsg(pParse, "no such table: %T", pName);
drhf5db2d32002-06-06 23:42:27 +00001001 }else{
danielk19774adee202004-05-08 08:23:19 +00001002 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001003 }
drh54473222002-04-04 02:10:55 +00001004 rc = 1;
1005 }
drhd8bc7082000-06-07 23:51:50 +00001006 }
1007 }
danielk19774adee202004-05-08 08:23:19 +00001008 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001009 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001010 }
drh54473222002-04-04 02:10:55 +00001011 return rc;
drhd8bc7082000-06-07 23:51:50 +00001012}
1013
1014/*
drhff78bd22002-02-27 01:47:11 +00001015** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1016** in a select structure. It just sets the pointers to NULL. This
1017** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1018** pointer is not NULL, this routine is called recursively on that pointer.
1019**
1020** This routine is called on the Select structure that defines a
1021** VIEW in order to undo any bindings to tables. This is necessary
1022** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001023** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1024** will be left pointing to a deallocated Table structure after the
1025** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001026*/
danielk19774adee202004-05-08 08:23:19 +00001027void sqlite3SelectUnbind(Select *p){
drhff78bd22002-02-27 01:47:11 +00001028 int i;
drhad3cab52002-05-24 02:04:32 +00001029 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +00001030 Table *pTab;
1031 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +00001032 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +00001033 if( (pTab = pSrc->a[i].pTab)!=0 ){
1034 if( pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001035 sqlite3DeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001036 }
1037 pSrc->a[i].pTab = 0;
1038 if( pSrc->a[i].pSelect ){
danielk19774adee202004-05-08 08:23:19 +00001039 sqlite3SelectUnbind(pSrc->a[i].pSelect);
drhff78bd22002-02-27 01:47:11 +00001040 }
1041 }
1042 }
1043}
1044
1045/*
drhd8bc7082000-06-07 23:51:50 +00001046** This routine associates entries in an ORDER BY expression list with
1047** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001048** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001049** the top-level node is filled in with column number and the iTable
1050** value of the top-level node is filled with iTable parameter.
1051**
1052** If there are prior SELECT clauses, they are processed first. A match
1053** in an earlier SELECT takes precedence over a later SELECT.
1054**
1055** Any entry that does not match is flagged as an error. The number
1056** of errors is returned.
1057*/
1058static int matchOrderbyToColumn(
1059 Parse *pParse, /* A place to leave error messages */
1060 Select *pSelect, /* Match to result columns of this SELECT */
1061 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001062 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001063 int mustComplete /* If TRUE all ORDER BYs must match */
1064){
1065 int nErr = 0;
1066 int i, j;
1067 ExprList *pEList;
1068
drhdaffd0e2001-04-11 14:28:42 +00001069 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001070 if( mustComplete ){
1071 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1072 }
1073 if( fillInColumnList(pParse, pSelect) ){
1074 return 1;
1075 }
1076 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001077 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1078 return 1;
1079 }
drhd8bc7082000-06-07 23:51:50 +00001080 }
1081 pEList = pSelect->pEList;
1082 for(i=0; i<pOrderBy->nExpr; i++){
1083 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001084 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001085 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001086 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001087 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001088 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001089 "ORDER BY position %d should be between 1 and %d",
1090 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001091 nErr++;
1092 break;
1093 }
drhfcb78a42003-01-18 20:11:05 +00001094 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001095 iCol--;
1096 }
1097 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001098 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001099 char *zName, *zLabel;
1100 zName = pEList->a[j].zName;
1101 assert( pE->token.z );
1102 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
danielk19774adee202004-05-08 08:23:19 +00001103 sqlite3Dequote(zLabel);
1104 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001105 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001106 }
drh6e142f52000-06-08 13:36:40 +00001107 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001108 }
danielk19774adee202004-05-08 08:23:19 +00001109 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001110 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001111 }
1112 }
drhe4de1fe2002-06-02 16:09:01 +00001113 if( iCol>=0 ){
1114 pE->op = TK_COLUMN;
1115 pE->iColumn = iCol;
1116 pE->iTable = iTable;
1117 pOrderBy->a[i].done = 1;
1118 }
1119 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001120 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001121 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001122 nErr++;
1123 break;
1124 }
1125 }
1126 return nErr;
1127}
1128
1129/*
1130** Get a VDBE for the given parser context. Create a new one if necessary.
1131** If an error occurs, return NULL and leave a message in pParse.
1132*/
danielk19774adee202004-05-08 08:23:19 +00001133Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001134 Vdbe *v = pParse->pVdbe;
1135 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001136 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001137 }
drhd8bc7082000-06-07 23:51:50 +00001138 return v;
1139}
drhfcb78a42003-01-18 20:11:05 +00001140
drhd3d39e92004-05-20 22:16:29 +00001141#if 0 /***** This routine needs deleting *****/
danielk197784ac9d02004-05-18 09:58:06 +00001142static void multiSelectAffinity(Select *p, char *zAff){
1143 int i;
1144
1145 if( !p ) return;
1146 multiSelectAffinity(p->pPrior, zAff);
1147
1148 for(i=0; i<p->pEList->nExpr; i++){
1149 if( zAff[i]=='\0' ){
1150 zAff[i] = sqlite3ExprAffinity(p->pEList->a[i].pExpr);
1151 }
1152 }
1153}
drhd3d39e92004-05-20 22:16:29 +00001154#endif
danielk197784ac9d02004-05-18 09:58:06 +00001155
drhd8bc7082000-06-07 23:51:50 +00001156/*
drh7b58dae2003-07-20 01:16:46 +00001157** Compute the iLimit and iOffset fields of the SELECT based on the
1158** nLimit and nOffset fields. nLimit and nOffset hold the integers
1159** that appear in the original SQL statement after the LIMIT and OFFSET
1160** keywords. Or that hold -1 and 0 if those keywords are omitted.
1161** iLimit and iOffset are the integer memory register numbers for
1162** counters used to compute the limit and offset. If there is no
1163** limit and/or offset, then iLimit and iOffset are negative.
1164**
1165** This routine changes the values if iLimit and iOffset only if
1166** a limit or offset is defined by nLimit and nOffset. iLimit and
1167** iOffset should have been preset to appropriate default values
1168** (usually but not always -1) prior to calling this routine.
1169** Only if nLimit>=0 or nOffset>0 do the limit registers get
1170** redefined. The UNION ALL operator uses this property to force
1171** the reuse of the same limit and offset registers across multiple
1172** SELECT statements.
1173*/
1174static void computeLimitRegisters(Parse *pParse, Select *p){
1175 /*
1176 ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
1177 ** all rows. It is the same as no limit. If the comparision is
1178 ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
1179 ** "LIMIT -1" always shows all rows. There is some
1180 ** contraversy about what the correct behavior should be.
1181 ** The current implementation interprets "LIMIT 0" to mean
1182 ** no rows.
1183 */
1184 if( p->nLimit>=0 ){
1185 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001186 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001187 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001188 sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1189 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001190 p->iLimit = iMem;
1191 }
1192 if( p->nOffset>0 ){
1193 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001194 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001195 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001196 sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1197 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001198 p->iOffset = iMem;
1199 }
1200}
1201
1202/*
drhd3d39e92004-05-20 22:16:29 +00001203** Generate VDBE instructions that will open a transient table that
1204** will be used for an index or to store keyed results for a compound
1205** select. In other words, open a transient table that needs a
1206** KeyInfo structure. The number of columns in the KeyInfo is determined
1207** by the result set of the SELECT statement in the second argument.
1208**
1209** Make the new table a KeyAsData table if keyAsData is true.
1210*/
1211static void openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
1212 KeyInfo *pKeyInfo;
drh736c22b2004-05-21 02:14:24 +00001213 int nColumn;
drhd3d39e92004-05-20 22:16:29 +00001214 sqlite *db = pParse->db;
1215 int i;
1216 Vdbe *v = pParse->pVdbe;
1217
drh736c22b2004-05-21 02:14:24 +00001218 if( fillInColumnList(pParse, p) ){
1219 return;
1220 }
1221 nColumn = p->pEList->nExpr;
drhd3d39e92004-05-20 22:16:29 +00001222 pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
1223 if( pKeyInfo==0 ) return;
1224 pKeyInfo->nField = nColumn;
1225 for(i=0; i<nColumn; i++){
1226 pKeyInfo->aColl[i] = db->pDfltColl;
1227 }
drhffbc3082004-05-21 01:29:06 +00001228 sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
drhd3d39e92004-05-20 22:16:29 +00001229 if( keyAsData ){
1230 sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1231 }
1232}
1233
1234/*
drh82c3d632000-06-06 21:56:07 +00001235** This routine is called to process a query that is really the union
1236** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001237**
drhe78e8282003-01-19 03:59:45 +00001238** "p" points to the right-most of the two queries. the query on the
1239** left is p->pPrior. The left query could also be a compound query
1240** in which case this routine will be called recursively.
1241**
1242** The results of the total query are to be written into a destination
1243** of type eDest with parameter iParm.
1244**
1245** Example 1: Consider a three-way compound SQL statement.
1246**
1247** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1248**
1249** This statement is parsed up as follows:
1250**
1251** SELECT c FROM t3
1252** |
1253** `-----> SELECT b FROM t2
1254** |
jplyon4b11c6d2004-01-19 04:57:53 +00001255** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001256**
1257** The arrows in the diagram above represent the Select.pPrior pointer.
1258** So if this routine is called with p equal to the t3 query, then
1259** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1260**
1261** Notice that because of the way SQLite parses compound SELECTs, the
1262** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001263*/
danielk197784ac9d02004-05-18 09:58:06 +00001264static int multiSelect(
1265 Parse *pParse,
1266 Select *p,
1267 int eDest,
1268 int iParm,
1269 char *aff /* If eDest is SRT_Union, the affinity string */
1270){
1271 int rc = SQLITE_OK; /* Success code from a subroutine */
drh10e5e3c2000-06-08 00:19:02 +00001272 Select *pPrior; /* Another SELECT immediately to our left */
1273 Vdbe *v; /* Generate code to this VDBE */
danielk197784ac9d02004-05-18 09:58:06 +00001274 char *affStr = 0;
1275
drhd3d39e92004-05-20 22:16:29 +00001276#if 0 /* NOT USED */
danielk197784ac9d02004-05-18 09:58:06 +00001277 if( !aff ){
1278 int len;
1279 rc = fillInColumnList(pParse, p);
1280 if( rc!=SQLITE_OK ){
1281 goto multi_select_end;
1282 }
1283 len = p->pEList->nExpr+1;
1284 affStr = (char *)sqliteMalloc(p->pEList->nExpr+1);
1285 if( !affStr ){
1286 rc = SQLITE_NOMEM;
1287 goto multi_select_end;
1288 }
1289 memset(affStr, (int)SQLITE_AFF_NUMERIC, len-1);
1290 aff = affStr;
1291 }
drhd3d39e92004-05-20 22:16:29 +00001292#endif
drh82c3d632000-06-06 21:56:07 +00001293
drh7b58dae2003-07-20 01:16:46 +00001294 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
1295 ** the last SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001296 */
danielk197784ac9d02004-05-18 09:58:06 +00001297 if( p==0 || p->pPrior==0 ){
1298 rc = 1;
1299 goto multi_select_end;
1300 }
drhd8bc7082000-06-07 23:51:50 +00001301 pPrior = p->pPrior;
1302 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001303 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001304 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001305 rc = 1;
1306 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001307 }
drh7b58dae2003-07-20 01:16:46 +00001308 if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
danielk19774adee202004-05-08 08:23:19 +00001309 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001310 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001311 rc = 1;
1312 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001313 }
drh82c3d632000-06-06 21:56:07 +00001314
drhd8bc7082000-06-07 23:51:50 +00001315 /* Make sure we have a valid query engine. If not, create a new one.
1316 */
danielk19774adee202004-05-08 08:23:19 +00001317 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001318 if( v==0 ){
1319 rc = 1;
1320 goto multi_select_end;
1321 }
drhd8bc7082000-06-07 23:51:50 +00001322
drh1cc3d752002-03-23 00:31:29 +00001323 /* Create the destination temporary table if necessary
1324 */
1325 if( eDest==SRT_TempTable ){
danielk1977b4964b72004-05-18 01:23:38 +00001326 assert( p->pEList );
danielk19774adee202004-05-08 08:23:19 +00001327 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00001328 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, p->pEList->nExpr);
drh1cc3d752002-03-23 00:31:29 +00001329 eDest = SRT_Table;
1330 }
1331
drhf46f9052002-06-22 02:33:38 +00001332 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001333 */
drh82c3d632000-06-06 21:56:07 +00001334 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001335 case TK_ALL: {
1336 if( p->pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +00001337 pPrior->nLimit = p->nLimit;
1338 pPrior->nOffset = p->nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001339 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1340 if( rc ){
1341 goto multi_select_end;
1342 }
drhf46f9052002-06-22 02:33:38 +00001343 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001344 p->iLimit = pPrior->iLimit;
1345 p->iOffset = pPrior->iOffset;
1346 p->nLimit = -1;
1347 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001348 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001349 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001350 if( rc ){
1351 goto multi_select_end;
1352 }
drhf46f9052002-06-22 02:33:38 +00001353 break;
1354 }
1355 /* For UNION ALL ... ORDER BY fall through to the next case */
1356 }
drh82c3d632000-06-06 21:56:07 +00001357 case TK_EXCEPT:
1358 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001359 int unionTab; /* Cursor number of the temporary table holding result */
1360 int op; /* One of the SRT_ operations to apply to self */
1361 int priorOp; /* The SRT_ operation to apply to prior selects */
drh7b58dae2003-07-20 01:16:46 +00001362 int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
drhc926afb2002-06-20 03:38:26 +00001363 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
drh82c3d632000-06-06 21:56:07 +00001364
drhd8bc7082000-06-07 23:51:50 +00001365 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh7b58dae2003-07-20 01:16:46 +00001366 if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
drhd8bc7082000-06-07 23:51:50 +00001367 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001368 ** right.
drhd8bc7082000-06-07 23:51:50 +00001369 */
drh82c3d632000-06-06 21:56:07 +00001370 unionTab = iParm;
1371 }else{
drhd8bc7082000-06-07 23:51:50 +00001372 /* We will need to create our own temporary table to hold the
1373 ** intermediate results.
1374 */
1375 unionTab = pParse->nTab++;
1376 if( p->pOrderBy
1377 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001378 rc = 1;
1379 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001380 }
drhd8bc7082000-06-07 23:51:50 +00001381 if( p->op!=TK_ALL ){
drhd3d39e92004-05-20 22:16:29 +00001382 openTempIndex(pParse, p, unionTab, 1);
drh345fda32001-01-15 22:51:08 +00001383 }else{
danielk19774adee202004-05-08 08:23:19 +00001384 sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001385 }
danielk197784ac9d02004-05-18 09:58:06 +00001386 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001387 }
drhd8bc7082000-06-07 23:51:50 +00001388
1389 /* Code the SELECT statements to our left
1390 */
danielk197784ac9d02004-05-18 09:58:06 +00001391 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
1392 if( rc ){
1393 goto multi_select_end;
1394 }
1395 if( p->op==TK_ALL ){
1396 sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, pPrior->pEList->nExpr);
1397 }
drhd8bc7082000-06-07 23:51:50 +00001398
1399 /* Code the current SELECT statement
1400 */
1401 switch( p->op ){
1402 case TK_EXCEPT: op = SRT_Except; break;
1403 case TK_UNION: op = SRT_Union; break;
1404 case TK_ALL: op = SRT_Table; break;
1405 }
drh82c3d632000-06-06 21:56:07 +00001406 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001407 pOrderBy = p->pOrderBy;
1408 p->pOrderBy = 0;
drh7b58dae2003-07-20 01:16:46 +00001409 nLimit = p->nLimit;
1410 p->nLimit = -1;
1411 nOffset = p->nOffset;
1412 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001413 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001414 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001415 p->pOrderBy = pOrderBy;
drh7b58dae2003-07-20 01:16:46 +00001416 p->nLimit = nLimit;
1417 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001418 if( rc ){
1419 goto multi_select_end;
1420 }
1421
drhd8bc7082000-06-07 23:51:50 +00001422
1423 /* Convert the data in the temporary table into whatever form
1424 ** it is that we currently need.
1425 */
drhc926afb2002-06-20 03:38:26 +00001426 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001427 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001428 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001429 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001430 generateColumnNames(pParse, 0, p->pEList);
1431 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001432 }
danielk19774adee202004-05-08 08:23:19 +00001433 iBreak = sqlite3VdbeMakeLabel(v);
1434 iCont = sqlite3VdbeMakeLabel(v);
1435 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001436 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001437 iStart = sqlite3VdbeCurrentAddr(v);
drh38640e12002-07-05 21:42:36 +00001438 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001439 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001440 iCont, iBreak, 0);
1441 if( rc ){
1442 rc = 1;
1443 goto multi_select_end;
1444 }
danielk19774adee202004-05-08 08:23:19 +00001445 sqlite3VdbeResolveLabel(v, iCont);
1446 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1447 sqlite3VdbeResolveLabel(v, iBreak);
1448 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001449 if( p->pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00001450 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001451 }
drh82c3d632000-06-06 21:56:07 +00001452 }
1453 break;
1454 }
1455 case TK_INTERSECT: {
1456 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001457 int iCont, iBreak, iStart;
drh7b58dae2003-07-20 01:16:46 +00001458 int nLimit, nOffset;
drh82c3d632000-06-06 21:56:07 +00001459
drhd8bc7082000-06-07 23:51:50 +00001460 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001461 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001462 ** by allocating the tables we will need.
1463 */
drh82c3d632000-06-06 21:56:07 +00001464 tab1 = pParse->nTab++;
1465 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001466 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001467 rc = 1;
1468 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001469 }
drhd3d39e92004-05-20 22:16:29 +00001470 openTempIndex(pParse, p, tab1, 1);
danielk197784ac9d02004-05-18 09:58:06 +00001471 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001472
1473 /* Code the SELECTs to our left into temporary table "tab1".
1474 */
danielk197784ac9d02004-05-18 09:58:06 +00001475 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
1476 if( rc ){
1477 goto multi_select_end;
1478 }
drhd8bc7082000-06-07 23:51:50 +00001479
1480 /* Code the current SELECT into temporary table "tab2"
1481 */
drhd3d39e92004-05-20 22:16:29 +00001482 openTempIndex(pParse, p, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001483 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001484 nLimit = p->nLimit;
1485 p->nLimit = -1;
1486 nOffset = p->nOffset;
1487 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001488 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001489 p->pPrior = pPrior;
drh7b58dae2003-07-20 01:16:46 +00001490 p->nLimit = nLimit;
1491 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001492 if( rc ){
1493 goto multi_select_end;
1494 }
drhd8bc7082000-06-07 23:51:50 +00001495
1496 /* Generate code to take the intersection of the two temporary
1497 ** tables.
1498 */
drh82c3d632000-06-06 21:56:07 +00001499 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001500 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001501 generateColumnNames(pParse, 0, p->pEList);
1502 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001503 }
danielk19774adee202004-05-08 08:23:19 +00001504 iBreak = sqlite3VdbeMakeLabel(v);
1505 iCont = sqlite3VdbeMakeLabel(v);
1506 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001507 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001508 iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
1509 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drh38640e12002-07-05 21:42:36 +00001510 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001511 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001512 iCont, iBreak, 0);
1513 if( rc ){
1514 rc = 1;
1515 goto multi_select_end;
1516 }
danielk19774adee202004-05-08 08:23:19 +00001517 sqlite3VdbeResolveLabel(v, iCont);
1518 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1519 sqlite3VdbeResolveLabel(v, iBreak);
1520 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1521 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drhd8bc7082000-06-07 23:51:50 +00001522 if( p->pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00001523 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001524 }
drh82c3d632000-06-06 21:56:07 +00001525 break;
1526 }
1527 }
1528 assert( p->pEList && pPrior->pEList );
1529 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001530 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001531 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001532 rc = 1;
1533 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001534 }
danielk197784ac9d02004-05-18 09:58:06 +00001535
1536multi_select_end:
drhd3d39e92004-05-20 22:16:29 +00001537#if 0 /*** NOT USED ****/
danielk197784ac9d02004-05-18 09:58:06 +00001538 if( affStr ){
1539 if( rc!=SQLITE_OK ){
1540 sqliteFree(affStr);
1541 }else{
1542 multiSelectAffinity(p, affStr);
1543 sqlite3VdbeOp3(v, OP_Noop, 0, 0, affStr, P3_DYNAMIC);
1544 }
1545 }
drhd3d39e92004-05-20 22:16:29 +00001546#endif
danielk197784ac9d02004-05-18 09:58:06 +00001547 return rc;
drh22827922000-06-06 17:27:05 +00001548}
1549
1550/*
drh832508b2002-03-02 17:04:07 +00001551** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001552** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001553** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001554** unchanged.)
drh832508b2002-03-02 17:04:07 +00001555**
1556** This routine is part of the flattening procedure. A subquery
1557** whose result set is defined by pEList appears as entry in the
1558** FROM clause of a SELECT such that the VDBE cursor assigned to that
1559** FORM clause entry is iTable. This routine make the necessary
1560** changes to pExpr so that it refers directly to the source table
1561** of the subquery rather the result set of the subquery.
1562*/
drh6a3ea0e2003-05-02 14:32:12 +00001563static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1564static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001565 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001566 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1567 if( pExpr->iColumn<0 ){
1568 pExpr->op = TK_NULL;
1569 }else{
1570 Expr *pNew;
1571 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1572 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1573 pNew = pEList->a[pExpr->iColumn].pExpr;
1574 assert( pNew!=0 );
1575 pExpr->op = pNew->op;
drh50350a12004-02-13 16:22:22 +00001576 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001577 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001578 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001579 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001580 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001581 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001582 pExpr->iTable = pNew->iTable;
1583 pExpr->iColumn = pNew->iColumn;
1584 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001585 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1586 sqlite3TokenCopy(&pExpr->span, &pNew->span);
drh50350a12004-02-13 16:22:22 +00001587 }
drh832508b2002-03-02 17:04:07 +00001588 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001589 substExpr(pExpr->pLeft, iTable, pEList);
1590 substExpr(pExpr->pRight, iTable, pEList);
1591 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001592 }
1593}
1594static void
drh6a3ea0e2003-05-02 14:32:12 +00001595substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001596 int i;
1597 if( pList==0 ) return;
1598 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001599 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001600 }
1601}
1602
1603/*
drh1350b032002-02-27 19:00:20 +00001604** This routine attempts to flatten subqueries in order to speed
1605** execution. It returns 1 if it makes changes and 0 if no flattening
1606** occurs.
1607**
1608** To understand the concept of flattening, consider the following
1609** query:
1610**
1611** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1612**
1613** The default way of implementing this query is to execute the
1614** subquery first and store the results in a temporary table, then
1615** run the outer query on that temporary table. This requires two
1616** passes over the data. Furthermore, because the temporary table
1617** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001618** optimized.
drh1350b032002-02-27 19:00:20 +00001619**
drh832508b2002-03-02 17:04:07 +00001620** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001621** a single flat select, like this:
1622**
1623** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1624**
1625** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001626** but only has to scan the data once. And because indices might
1627** exist on the table t1, a complete scan of the data might be
1628** avoided.
drh1350b032002-02-27 19:00:20 +00001629**
drh832508b2002-03-02 17:04:07 +00001630** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001631**
drh832508b2002-03-02 17:04:07 +00001632** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001633**
drh832508b2002-03-02 17:04:07 +00001634** (2) The subquery is not an aggregate or the outer query is not a join.
1635**
drh8af4d3a2003-05-06 20:35:16 +00001636** (3) The subquery is not the right operand of a left outer join, or
1637** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001638**
1639** (4) The subquery is not DISTINCT or the outer query is not a join.
1640**
1641** (5) The subquery is not DISTINCT or the outer query does not use
1642** aggregates.
1643**
1644** (6) The subquery does not use aggregates or the outer query is not
1645** DISTINCT.
1646**
drh08192d52002-04-30 19:20:28 +00001647** (7) The subquery has a FROM clause.
1648**
drhdf199a22002-06-14 22:38:41 +00001649** (8) The subquery does not use LIMIT or the outer query is not a join.
1650**
1651** (9) The subquery does not use LIMIT or the outer query does not use
1652** aggregates.
1653**
1654** (10) The subquery does not use aggregates or the outer query does not
1655** use LIMIT.
1656**
drh174b6192002-12-03 02:22:52 +00001657** (11) The subquery and the outer query do not both have ORDER BY clauses.
1658**
drh3fc673e2003-06-16 00:40:34 +00001659** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1660** subquery has no WHERE clause. (added by ticket #350)
1661**
drh832508b2002-03-02 17:04:07 +00001662** In this routine, the "p" parameter is a pointer to the outer query.
1663** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1664** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1665**
drh665de472003-03-31 13:36:09 +00001666** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001667** If flattening is attempted this routine returns 1.
1668**
1669** All of the expression analysis must occur on both the outer query and
1670** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001671*/
drh8c74a8c2002-08-25 19:20:40 +00001672static int flattenSubquery(
1673 Parse *pParse, /* The parsing context */
1674 Select *p, /* The parent or outer SELECT statement */
1675 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1676 int isAgg, /* True if outer SELECT uses aggregate functions */
1677 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1678){
drh0bb28102002-05-08 11:54:14 +00001679 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001680 SrcList *pSrc; /* The FROM clause of the outer query */
1681 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001682 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001683 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh832508b2002-03-02 17:04:07 +00001684 int i;
drh832508b2002-03-02 17:04:07 +00001685 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001686
drh832508b2002-03-02 17:04:07 +00001687 /* Check to see if flattening is permitted. Return 0 if not.
1688 */
1689 if( p==0 ) return 0;
1690 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001691 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001692 pSub = pSrc->a[iFrom].pSelect;
1693 assert( pSub!=0 );
1694 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001695 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001696 pSubSrc = pSub->pSrc;
1697 assert( pSubSrc );
drhc31c2eb2003-05-02 16:04:17 +00001698 if( pSubSrc->nSrc==0 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001699 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1700 return 0;
1701 }
drhd11d3822002-06-21 23:01:49 +00001702 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001703 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001704
drh8af4d3a2003-05-06 20:35:16 +00001705 /* Restriction 3: If the subquery is a join, make sure the subquery is
1706 ** not used as the right operand of an outer join. Examples of why this
1707 ** is not allowed:
1708 **
1709 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1710 **
1711 ** If we flatten the above, we would get
1712 **
1713 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1714 **
1715 ** which is not at all the same thing.
1716 */
1717 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1718 return 0;
1719 }
1720
drh3fc673e2003-06-16 00:40:34 +00001721 /* Restriction 12: If the subquery is the right operand of a left outer
1722 ** join, make sure the subquery has no WHERE clause.
1723 ** An examples of why this is not allowed:
1724 **
1725 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1726 **
1727 ** If we flatten the above, we would get
1728 **
1729 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1730 **
1731 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1732 ** effectively converts the OUTER JOIN into an INNER JOIN.
1733 */
1734 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1735 && pSub->pWhere!=0 ){
1736 return 0;
1737 }
1738
drh0bb28102002-05-08 11:54:14 +00001739 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001740 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001741 */
drhc31c2eb2003-05-02 16:04:17 +00001742
1743 /* Move all of the FROM elements of the subquery into the
1744 ** the FROM clause of the outer query. Before doing this, remember
1745 ** the cursor number for the original outer query FROM element in
1746 ** iParent. The iParent cursor will never be used. Subsequent code
1747 ** will scan expressions looking for iParent references and replace
1748 ** those references with expressions that resolve to the subquery FROM
1749 ** elements we are now copying in.
1750 */
drh6a3ea0e2003-05-02 14:32:12 +00001751 iParent = pSrc->a[iFrom].iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001752 {
1753 int nSubSrc = pSubSrc->nSrc;
drh8af4d3a2003-05-06 20:35:16 +00001754 int jointype = pSrc->a[iFrom].jointype;
drhc31c2eb2003-05-02 16:04:17 +00001755
1756 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001757 sqlite3DeleteTable(0, pSrc->a[iFrom].pTab);
drhc31c2eb2003-05-02 16:04:17 +00001758 }
drhf26e09c2003-05-31 16:21:12 +00001759 sqliteFree(pSrc->a[iFrom].zDatabase);
drhc31c2eb2003-05-02 16:04:17 +00001760 sqliteFree(pSrc->a[iFrom].zName);
1761 sqliteFree(pSrc->a[iFrom].zAlias);
1762 if( nSubSrc>1 ){
1763 int extra = nSubSrc - 1;
1764 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00001765 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00001766 }
1767 p->pSrc = pSrc;
1768 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1769 pSrc->a[i] = pSrc->a[i-extra];
1770 }
1771 }
1772 for(i=0; i<nSubSrc; i++){
1773 pSrc->a[i+iFrom] = pSubSrc->a[i];
1774 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1775 }
drh8af4d3a2003-05-06 20:35:16 +00001776 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00001777 }
1778
1779 /* Now begin substituting subquery result set expressions for
1780 ** references to the iParent in the outer query.
1781 **
1782 ** Example:
1783 **
1784 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1785 ** \ \_____________ subquery __________/ /
1786 ** \_____________________ outer query ______________________________/
1787 **
1788 ** We look at every expression in the outer query and every place we see
1789 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1790 */
drh6a3ea0e2003-05-02 14:32:12 +00001791 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001792 pList = p->pEList;
1793 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001794 Expr *pExpr;
1795 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1796 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001797 }
1798 }
drh1b2e0322002-03-03 02:49:51 +00001799 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00001800 substExprList(p->pGroupBy, iParent, pSub->pEList);
1801 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001802 }
drh174b6192002-12-03 02:22:52 +00001803 if( pSub->pOrderBy ){
1804 assert( p->pOrderBy==0 );
1805 p->pOrderBy = pSub->pOrderBy;
1806 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00001807 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00001808 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00001809 }
drh832508b2002-03-02 17:04:07 +00001810 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001811 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00001812 }else{
1813 pWhere = 0;
1814 }
1815 if( subqueryIsAgg ){
1816 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001817 p->pHaving = p->pWhere;
1818 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00001819 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001820 if( pSub->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001821 Expr *pHaving = sqlite3ExprDup(pSub->pHaving);
drh1b2e0322002-03-03 02:49:51 +00001822 if( p->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001823 p->pHaving = sqlite3Expr(TK_AND, p->pHaving, pHaving, 0);
drh1b2e0322002-03-03 02:49:51 +00001824 }else{
1825 p->pHaving = pHaving;
1826 }
1827 }
1828 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00001829 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00001830 }else if( p->pWhere==0 ){
1831 p->pWhere = pWhere;
1832 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001833 substExpr(p->pWhere, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001834 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001835 p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pWhere, 0);
drh832508b2002-03-02 17:04:07 +00001836 }
1837 }
drhc31c2eb2003-05-02 16:04:17 +00001838
1839 /* The flattened query is distinct if either the inner or the
1840 ** outer query is distinct.
1841 */
drh832508b2002-03-02 17:04:07 +00001842 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00001843
drhc31c2eb2003-05-02 16:04:17 +00001844 /* Transfer the limit expression from the subquery to the outer
1845 ** query.
1846 */
drhdf199a22002-06-14 22:38:41 +00001847 if( pSub->nLimit>=0 ){
1848 if( p->nLimit<0 ){
1849 p->nLimit = pSub->nLimit;
1850 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1851 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1852 }
1853 }
1854 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00001855
drhc31c2eb2003-05-02 16:04:17 +00001856 /* Finially, delete what is left of the subquery and return
1857 ** success.
1858 */
danielk19774adee202004-05-08 08:23:19 +00001859 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00001860 return 1;
1861}
drh1350b032002-02-27 19:00:20 +00001862
1863/*
drh9562b552002-02-19 15:00:07 +00001864** Analyze the SELECT statement passed in as an argument to see if it
1865** is a simple min() or max() query. If it is and this query can be
1866** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00001867** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00001868** simple min() or max() query, then return 0;
1869**
1870** A simply min() or max() query looks like this:
1871**
1872** SELECT min(a) FROM table;
1873** SELECT max(a) FROM table;
1874**
1875** The query may have only a single table in its FROM argument. There
1876** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1877** be the min() or max() of a single column of the table. The column
1878** in the min() or max() function must be indexed.
1879**
danielk19774adee202004-05-08 08:23:19 +00001880** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00001881** See the header comment on that routine for additional information.
1882*/
1883static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1884 Expr *pExpr;
1885 int iCol;
1886 Table *pTab;
1887 Index *pIdx;
1888 int base;
1889 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00001890 int seekOp;
1891 int cont;
drh6e175292004-03-13 14:00:36 +00001892 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00001893 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00001894 SrcList *pSrc;
1895
drh9562b552002-02-19 15:00:07 +00001896
1897 /* Check to see if this query is a simple min() or max() query. Return
1898 ** zero if it is not.
1899 */
1900 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00001901 pSrc = p->pSrc;
1902 if( pSrc->nSrc!=1 ) return 0;
1903 pEList = p->pEList;
1904 if( pEList->nExpr!=1 ) return 0;
1905 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00001906 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00001907 pList = pExpr->pList;
1908 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00001909 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00001910 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00001911 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00001912 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00001913 seekOp = OP_Last;
1914 }else{
1915 return 0;
1916 }
drh6e175292004-03-13 14:00:36 +00001917 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00001918 if( pExpr->op!=TK_COLUMN ) return 0;
1919 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00001920 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00001921
1922 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00001923 ** Check to make sure we have an index and make pIdx point to the
1924 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
1925 ** key column, no index is necessary so set pIdx to NULL. If no
1926 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00001927 */
1928 if( iCol<0 ){
1929 pIdx = 0;
1930 }else{
1931 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1932 assert( pIdx->nColumn>=1 );
1933 if( pIdx->aiColumn[0]==iCol ) break;
1934 }
1935 if( pIdx==0 ) return 0;
1936 }
1937
drhe5f50722003-07-19 00:44:14 +00001938 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00001939 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00001940 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00001941 */
danielk19774adee202004-05-08 08:23:19 +00001942 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00001943 if( v==0 ) return 0;
1944 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001945 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh9562b552002-02-19 15:00:07 +00001946 }
1947
drh0c37e632004-01-30 02:01:03 +00001948 /* If the output is destined for a temporary table, open that table.
1949 */
1950 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00001951 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00001952 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00001953 }
1954
drh17f71932002-02-21 12:01:27 +00001955 /* Generating code to find the min or the max. Basically all we have
1956 ** to do is find the first or the last entry in the chosen index. If
1957 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
1958 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00001959 */
danielk19774adee202004-05-08 08:23:19 +00001960 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00001961 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00001962 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00001963 if( pSrc->a[0].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +00001964 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00001965 sqlite3VdbeAddOp(v, OP_OpenRead, base, pTab->tnum);
danielk1977b4964b72004-05-18 01:23:38 +00001966 sqlite3VdbeAddOp(v, OP_SetNumColumns, base, pTab->nCol);
drh6e175292004-03-13 14:00:36 +00001967 }
danielk19774adee202004-05-08 08:23:19 +00001968 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00001969 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00001970 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00001971 }else{
danielk19774adee202004-05-08 08:23:19 +00001972 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
drhd3d39e92004-05-20 22:16:29 +00001973 sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum,
1974 (char*)&pIdx->keyInfo, P3_KEYINFO);
danielk19774adee202004-05-08 08:23:19 +00001975 sqlite3VdbeAddOp(v, seekOp, base+1, 0);
1976 sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
1977 sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
drh7cf6e4d2004-05-19 14:56:55 +00001978 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
drh9562b552002-02-19 15:00:07 +00001979 }
drh5cf8e8c2002-02-19 22:42:05 +00001980 eList.nExpr = 1;
1981 memset(&eListItem, 0, sizeof(eListItem));
1982 eList.a = &eListItem;
1983 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00001984 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00001985 sqlite3VdbeResolveLabel(v, cont);
1986 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00001987
drh9562b552002-02-19 15:00:07 +00001988 return 1;
1989}
1990
1991/*
drh9bb61fe2000-06-05 16:01:39 +00001992** Generate code for the given SELECT statement.
1993**
drhfef52082000-06-06 01:50:43 +00001994** The results are distributed in various ways depending on the
1995** value of eDest and iParm.
1996**
1997** eDest Value Result
1998** ------------ -------------------------------------------
1999** SRT_Callback Invoke the callback for each row of the result.
2000**
2001** SRT_Mem Store first result in memory cell iParm
2002**
danielk1977e014a832004-05-17 10:48:57 +00002003** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002004**
drh82c3d632000-06-06 21:56:07 +00002005** SRT_Union Store results as a key in a temporary table iParm
2006**
jplyon4b11c6d2004-01-19 04:57:53 +00002007** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002008**
2009** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002010**
drhe78e8282003-01-19 03:59:45 +00002011** The table above is incomplete. Additional eDist value have be added
2012** since this comment was written. See the selectInnerLoop() function for
2013** a complete listing of the allowed values of eDest and their meanings.
2014**
drh9bb61fe2000-06-05 16:01:39 +00002015** This routine returns the number of errors. If any errors are
2016** encountered, then an appropriate error message is left in
2017** pParse->zErrMsg.
2018**
2019** This routine does NOT free the Select structure passed in. The
2020** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002021**
2022** The pParent, parentTab, and *pParentAgg fields are filled in if this
2023** SELECT is a subquery. This routine may try to combine this SELECT
2024** with its parent to form a single flat query. In so doing, it might
2025** change the parent query from a non-aggregate to an aggregate query.
2026** For that reason, the pParentAgg flag is passed as a pointer, so it
2027** can be changed.
drhe78e8282003-01-19 03:59:45 +00002028**
2029** Example 1: The meaning of the pParent parameter.
2030**
2031** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2032** \ \_______ subquery _______/ /
2033** \ /
2034** \____________________ outer query ___________________/
2035**
2036** This routine is called for the outer query first. For that call,
2037** pParent will be NULL. During the processing of the outer query, this
2038** routine is called recursively to handle the subquery. For the recursive
2039** call, pParent will point to the outer query. Because the subquery is
2040** the second element in a three-way join, the parentTab parameter will
2041** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002042*/
danielk19774adee202004-05-08 08:23:19 +00002043int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002044 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002045 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002046 int eDest, /* How to dispose of the results */
2047 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002048 Select *pParent, /* Another SELECT for which this is a sub-query */
2049 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002050 int *pParentAgg, /* True if pParent uses aggregate functions */
2051 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002052){
drhd8bc7082000-06-07 23:51:50 +00002053 int i;
drhcce7d172000-05-31 15:34:51 +00002054 WhereInfo *pWInfo;
2055 Vdbe *v;
2056 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002057 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002058 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002059 Expr *pWhere; /* The WHERE clause. May be NULL */
2060 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002061 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2062 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002063 int isDistinct; /* True if the DISTINCT keyword is present */
2064 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002065 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00002066
danielk19776f8a5032004-05-10 10:34:51 +00002067 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002068 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002069
drh82c3d632000-06-06 21:56:07 +00002070 /* If there is are a sequence of queries, do the earlier ones first.
2071 */
2072 if( p->pPrior ){
danielk197784ac9d02004-05-18 09:58:06 +00002073 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002074 }
2075
2076 /* Make local copies of the parameters for this query.
2077 */
drh9bb61fe2000-06-05 16:01:39 +00002078 pTabList = p->pSrc;
2079 pWhere = p->pWhere;
2080 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00002081 pGroupBy = p->pGroupBy;
2082 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00002083 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00002084
drh6a3ea0e2003-05-02 14:32:12 +00002085 /* Allocate VDBE cursors for each table in the FROM clause
drh10e5e3c2000-06-08 00:19:02 +00002086 */
danielk19774adee202004-05-08 08:23:19 +00002087 sqlite3SrcListAssignCursors(pParse, pTabList);
drh10e5e3c2000-06-08 00:19:02 +00002088
drh9bb61fe2000-06-05 16:01:39 +00002089 /*
2090 ** Do not even attempt to generate any code if we have already seen
2091 ** errors before this routine starts.
2092 */
drh1d83f052002-02-17 00:30:36 +00002093 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002094
drhe78e8282003-01-19 03:59:45 +00002095 /* Expand any "*" terms in the result set. (For example the "*" in
2096 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
2097 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00002098 */
drhd8bc7082000-06-07 23:51:50 +00002099 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00002100 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002101 }
drhad2d8302002-05-24 20:31:36 +00002102 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00002103 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00002104 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002105
drh22827922000-06-06 17:27:05 +00002106 /* If writing to memory or generating a set
2107 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002108 */
drhfef52082000-06-06 01:50:43 +00002109 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002110 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002111 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002112 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002113 }
2114
drhc926afb2002-06-20 03:38:26 +00002115 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002116 */
drhc926afb2002-06-20 03:38:26 +00002117 switch( eDest ){
2118 case SRT_Union:
2119 case SRT_Except:
2120 case SRT_Discard:
2121 pOrderBy = 0;
2122 break;
2123 default:
2124 break;
drh22827922000-06-06 17:27:05 +00002125 }
2126
drh10e5e3c2000-06-08 00:19:02 +00002127 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002128 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002129 **
drh967e8b72000-06-21 13:59:10 +00002130 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002131 */
drh4794b982000-06-06 13:54:14 +00002132 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002133 if( sqlite3ExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002134 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002135 }
danielk19774adee202004-05-08 08:23:19 +00002136 if( sqlite3ExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002137 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002138 }
2139 }
drhcce7d172000-05-31 15:34:51 +00002140 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002141 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00002142 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002143 }
danielk19774adee202004-05-08 08:23:19 +00002144 if( sqlite3ExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00002145 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002146 }
2147 }
drhc66c5a22002-12-03 02:34:49 +00002148 if( pHaving ){
2149 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002150 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
drhc66c5a22002-12-03 02:34:49 +00002151 goto select_end;
2152 }
danielk19774adee202004-05-08 08:23:19 +00002153 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pHaving) ){
drhc66c5a22002-12-03 02:34:49 +00002154 goto select_end;
2155 }
danielk19774adee202004-05-08 08:23:19 +00002156 if( sqlite3ExprCheck(pParse, pHaving, 1, &isAgg) ){
drhc66c5a22002-12-03 02:34:49 +00002157 goto select_end;
2158 }
2159 }
drhcce7d172000-05-31 15:34:51 +00002160 if( pOrderBy ){
2161 for(i=0; i<pOrderBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002162 int iCol;
drh22827922000-06-06 17:27:05 +00002163 Expr *pE = pOrderBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002164 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2165 sqlite3ExprDelete(pE);
2166 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh88eee382003-01-31 17:16:36 +00002167 }
danielk19774adee202004-05-08 08:23:19 +00002168 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh88eee382003-01-31 17:16:36 +00002169 goto select_end;
2170 }
danielk19774adee202004-05-08 08:23:19 +00002171 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh88eee382003-01-31 17:16:36 +00002172 goto select_end;
2173 }
danielk19774adee202004-05-08 08:23:19 +00002174 if( sqlite3ExprIsConstant(pE) ){
2175 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2176 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002177 "ORDER BY terms must not be non-integer constants");
drhe4de1fe2002-06-02 16:09:01 +00002178 goto select_end;
2179 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002180 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002181 "ORDER BY column number %d out of range - should be "
drhe4de1fe2002-06-02 16:09:01 +00002182 "between 1 and %d", iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00002183 goto select_end;
2184 }
drhcce7d172000-05-31 15:34:51 +00002185 }
2186 }
2187 }
drh22827922000-06-06 17:27:05 +00002188 if( pGroupBy ){
2189 for(i=0; i<pGroupBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002190 int iCol;
drh22827922000-06-06 17:27:05 +00002191 Expr *pE = pGroupBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002192 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2193 sqlite3ExprDelete(pE);
2194 pE = pGroupBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00002195 }
danielk19774adee202004-05-08 08:23:19 +00002196 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00002197 goto select_end;
drh22827922000-06-06 17:27:05 +00002198 }
danielk19774adee202004-05-08 08:23:19 +00002199 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00002200 goto select_end;
drh22827922000-06-06 17:27:05 +00002201 }
danielk19774adee202004-05-08 08:23:19 +00002202 if( sqlite3ExprIsConstant(pE) ){
2203 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2204 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002205 "GROUP BY terms must not be non-integer constants");
drh88eee382003-01-31 17:16:36 +00002206 goto select_end;
2207 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002208 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002209 "GROUP BY column number %d out of range - should be "
drh88eee382003-01-31 17:16:36 +00002210 "between 1 and %d", iCol, pEList->nExpr);
drh88eee382003-01-31 17:16:36 +00002211 goto select_end;
2212 }
2213 }
drh22827922000-06-06 17:27:05 +00002214 }
2215 }
drhcce7d172000-05-31 15:34:51 +00002216
drhd820cb12002-02-18 03:21:45 +00002217 /* Begin generating code.
2218 */
danielk19774adee202004-05-08 08:23:19 +00002219 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002220 if( v==0 ) goto select_end;
2221
drhe78e8282003-01-19 03:59:45 +00002222 /* Identify column names if we will be using them in a callback. This
2223 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002224 */
2225 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002226 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002227 }
2228
drhd3d39e92004-05-20 22:16:29 +00002229#if 1 /* I do not think we need the following code any more.... */
danielk197784ac9d02004-05-18 09:58:06 +00002230 /* If the destination is SRT_Union, then set the number of columns in
2231 ** the records that will be inserted into the temporary table. The caller
2232 ** couldn't do this, in case the select statement is of the form
2233 ** "SELECT * FROM ....".
2234 **
2235 ** We need to do this before we start inserting records into the
2236 ** temporary table (which has had OP_KeyAsData executed on it), because
2237 ** it is required by the key comparison function. So do it now, even
2238 ** though this means that OP_SetNumColumns may be executed on the same
2239 ** cursor more than once.
2240 */
2241 if( eDest==SRT_Union ){
2242 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
2243 }
drhd3d39e92004-05-20 22:16:29 +00002244#endif
danielk197784ac9d02004-05-18 09:58:06 +00002245
drhd820cb12002-02-18 03:21:45 +00002246 /* Generate code for all sub-queries in the FROM clause
2247 */
drhad3cab52002-05-24 02:04:32 +00002248 for(i=0; i<pTabList->nSrc; i++){
drh5cf590c2003-04-24 01:45:04 +00002249 const char *zSavedAuthContext;
drhc31c2eb2003-05-02 16:04:17 +00002250 int needRestoreContext;
2251
drha76b5df2002-02-23 02:32:10 +00002252 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002253 if( pTabList->a[i].zName!=0 ){
2254 zSavedAuthContext = pParse->zAuthContext;
2255 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002256 needRestoreContext = 1;
2257 }else{
2258 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002259 }
danielk19774adee202004-05-08 08:23:19 +00002260 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
danielk197784ac9d02004-05-18 09:58:06 +00002261 pTabList->a[i].iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002262 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002263 pParse->zAuthContext = zSavedAuthContext;
2264 }
drh1b2e0322002-03-03 02:49:51 +00002265 pTabList = p->pSrc;
2266 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002267 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002268 pOrderBy = p->pOrderBy;
2269 }
drh1b2e0322002-03-03 02:49:51 +00002270 pGroupBy = p->pGroupBy;
2271 pHaving = p->pHaving;
2272 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002273 }
2274
drh6e175292004-03-13 14:00:36 +00002275 /* Check for the special case of a min() or max() function by itself
2276 ** in the result set.
2277 */
2278 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2279 rc = 0;
2280 goto select_end;
2281 }
2282
drh832508b2002-03-02 17:04:07 +00002283 /* Check to see if this is a subquery that can be "flattened" into its parent.
2284 ** If flattening is a possiblity, do so and return immediately.
2285 */
drh1b2e0322002-03-03 02:49:51 +00002286 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002287 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002288 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002289 return rc;
2290 }
drh832508b2002-03-02 17:04:07 +00002291
drh7b58dae2003-07-20 01:16:46 +00002292 /* Set the limiter.
2293 */
2294 computeLimitRegisters(pParse, p);
2295
drhe78e8282003-01-19 03:59:45 +00002296 /* Identify column types if we will be using a callback. This
2297 ** step is skipped if the output is going to a destination other
2298 ** than a callback.
drhe5f50722003-07-19 00:44:14 +00002299 **
2300 ** We have to do this separately from the creation of column names
2301 ** above because if the pTabList contains views then they will not
2302 ** have been resolved and we will not know the column types until
2303 ** now.
drhfcb78a42003-01-18 20:11:05 +00002304 */
2305 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002306 generateColumnTypes(pParse, pTabList, pEList);
drhfcb78a42003-01-18 20:11:05 +00002307 }
2308
drh2d0794e2002-03-03 03:03:52 +00002309 /* If the output is destined for a temporary table, open that table.
2310 */
2311 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002312 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002313 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002314 }
2315
drh22827922000-06-06 17:27:05 +00002316 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002317 */
drhd820cb12002-02-18 03:21:45 +00002318 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002319 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002320 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002321 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002322 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002323 if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002324 goto select_end;
drh22827922000-06-06 17:27:05 +00002325 }
2326 }
2327 if( pGroupBy ){
2328 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002329 if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002330 goto select_end;
drh22827922000-06-06 17:27:05 +00002331 }
2332 }
2333 }
danielk19774adee202004-05-08 08:23:19 +00002334 if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002335 goto select_end;
drh22827922000-06-06 17:27:05 +00002336 }
drh191b6902000-06-08 11:13:01 +00002337 if( pOrderBy ){
2338 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002339 if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002340 goto select_end;
drh191b6902000-06-08 11:13:01 +00002341 }
2342 }
2343 }
drhefb72512000-05-31 20:00:52 +00002344 }
2345
drh22827922000-06-06 17:27:05 +00002346 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002347 */
2348 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002349 sqlite3VdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002350 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002351 FuncDef *pFunc;
2352 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002353 sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_POINTER);
drhe5095352002-02-24 03:25:14 +00002354 }
2355 }
drh1bee3d72001-10-15 00:44:35 +00002356 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002357 sqlite3VdbeAddOp(v, OP_String, 0, 0);
2358 sqlite3VdbeAddOp(v, OP_AggFocus, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002359 }
drhcce7d172000-05-31 15:34:51 +00002360 }
2361
drh19a775c2000-06-05 18:54:46 +00002362 /* Initialize the memory cell to NULL
2363 */
drhfef52082000-06-06 01:50:43 +00002364 if( eDest==SRT_Mem ){
danielk19774adee202004-05-08 08:23:19 +00002365 sqlite3VdbeAddOp(v, OP_String, 0, 0);
2366 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002367 }
2368
drh832508b2002-03-02 17:04:07 +00002369 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002370 */
drh19a775c2000-06-05 18:54:46 +00002371 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002372 distinct = pParse->nTab++;
drhd3d39e92004-05-20 22:16:29 +00002373 openTempIndex(pParse, p, distinct, 0);
drh832508b2002-03-02 17:04:07 +00002374 }else{
2375 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002376 }
drh832508b2002-03-02 17:04:07 +00002377
2378 /* Begin the database scan
2379 */
danielk19774adee202004-05-08 08:23:19 +00002380 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
drh68d2e592002-08-04 00:52:38 +00002381 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002382 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002383
drh22827922000-06-06 17:27:05 +00002384 /* Use the standard inner loop if we are not dealing with
2385 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002386 */
drhda9d6c42000-05-31 18:20:14 +00002387 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002388 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002389 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002390 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002391 }
drhcce7d172000-05-31 15:34:51 +00002392 }
drhefb72512000-05-31 20:00:52 +00002393
drhe3184742002-06-19 14:27:05 +00002394 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002395 ** processing.
drhefb72512000-05-31 20:00:52 +00002396 */
drh22827922000-06-06 17:27:05 +00002397 else{
drh268380c2004-02-25 13:47:31 +00002398 AggExpr *pAgg;
drh22827922000-06-06 17:27:05 +00002399 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002400 int lbl1;
drh22827922000-06-06 17:27:05 +00002401 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002402 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
drh22827922000-06-06 17:27:05 +00002403 }
drhd3d39e92004-05-20 22:16:29 +00002404 /* No affinity string is attached to the following OP_MakeKey
2405 ** because we do not need to do any coercion of datatypes. */
danielk19774adee202004-05-08 08:23:19 +00002406 sqlite3VdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
danielk19774adee202004-05-08 08:23:19 +00002407 lbl1 = sqlite3VdbeMakeLabel(v);
2408 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh268380c2004-02-25 13:47:31 +00002409 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2410 if( pAgg->isAgg ) continue;
danielk19774adee202004-05-08 08:23:19 +00002411 sqlite3ExprCode(pParse, pAgg->pExpr);
2412 sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002413 }
danielk19774adee202004-05-08 08:23:19 +00002414 sqlite3VdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002415 }
drh268380c2004-02-25 13:47:31 +00002416 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002417 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002418 int nExpr;
2419 FuncDef *pDef;
2420 if( !pAgg->isAgg ) continue;
2421 assert( pAgg->pFunc!=0 );
2422 assert( pAgg->pFunc->xStep!=0 );
2423 pDef = pAgg->pFunc;
2424 pE = pAgg->pExpr;
2425 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002426 assert( pE->op==TK_AGG_FUNCTION );
danielk19774adee202004-05-08 08:23:19 +00002427 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList, pDef->includeTypes);
2428 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
2429 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002430 }
drhcce7d172000-05-31 15:34:51 +00002431 }
2432
2433 /* End the database scan loop.
2434 */
danielk19774adee202004-05-08 08:23:19 +00002435 sqlite3WhereEnd(pWInfo);
drhcce7d172000-05-31 15:34:51 +00002436
drh22827922000-06-06 17:27:05 +00002437 /* If we are processing aggregates, we need to set up a second loop
2438 ** over all of the aggregate values and process them.
2439 */
2440 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002441 int endagg = sqlite3VdbeMakeLabel(v);
drh22827922000-06-06 17:27:05 +00002442 int startagg;
danielk19774adee202004-05-08 08:23:19 +00002443 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002444 pParse->useAgg = 1;
2445 if( pHaving ){
danielk19774adee202004-05-08 08:23:19 +00002446 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002447 }
drhdf199a22002-06-14 22:38:41 +00002448 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002449 iParm, startagg, endagg, aff) ){
drh1d83f052002-02-17 00:30:36 +00002450 goto select_end;
drh22827922000-06-06 17:27:05 +00002451 }
danielk19774adee202004-05-08 08:23:19 +00002452 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2453 sqlite3VdbeResolveLabel(v, endagg);
2454 sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002455 pParse->useAgg = 0;
2456 }
2457
drhcce7d172000-05-31 15:34:51 +00002458 /* If there is an ORDER BY clause, then we need to sort the results
2459 ** and send them to the callback one by one.
2460 */
2461 if( pOrderBy ){
drhffbc3082004-05-21 01:29:06 +00002462 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002463 }
drh6a535342001-10-19 16:44:56 +00002464
drhf620b4e2004-02-09 14:37:50 +00002465 /* If this was a subquery, we have now converted the subquery into a
2466 ** temporary table. So delete the subquery structure from the parent
2467 ** to prevent this subquery from being evaluated again and to force the
2468 ** the use of the temporary table.
2469 */
2470 if( pParent ){
2471 assert( pParent->pSrc->nSrc>parentTab );
2472 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00002473 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00002474 pParent->pSrc->a[parentTab].pSelect = 0;
2475 }
2476
drh1d83f052002-02-17 00:30:36 +00002477 /* The SELECT was successfully coded. Set the return code to 0
2478 ** to indicate no errors.
2479 */
2480 rc = 0;
2481
2482 /* Control jumps to here if an error is encountered above, or upon
2483 ** successful coding of the SELECT.
2484 */
2485select_end:
2486 sqliteAggregateInfoReset(pParse);
2487 return rc;
drhcce7d172000-05-31 15:34:51 +00002488}