blob: 1e1ab300cda92587c9b1b50a1aeee2d35dc2372f [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**
drh428702d2004-05-18 22:38:31 +000015** $Id: select.c,v 1.168 2004/05/18 22:38:32 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){
321 char *zSortOrder;
322 int i;
323 zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
324 if( zSortOrder==0 ) return;
325 for(i=0; i<pOrderBy->nExpr; i++){
drh38640e12002-07-05 21:42:36 +0000326 int order = pOrderBy->a[i].sortOrder;
327 int type;
328 int c;
329 if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
330 type = SQLITE_SO_TEXT;
331 }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
332 type = SQLITE_SO_NUM;
drh38640e12002-07-05 21:42:36 +0000333 }else{
danielk197736a3c702004-05-11 06:55:14 +0000334 type = sqlite3ExprType(pOrderBy->a[i].pExpr);
drh38640e12002-07-05 21:42:36 +0000335 }
336 if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
337 c = type==SQLITE_SO_TEXT ? 'A' : '+';
338 }else{
339 c = type==SQLITE_SO_TEXT ? 'D' : '-';
340 }
341 zSortOrder[i] = c;
danielk19774adee202004-05-08 08:23:19 +0000342 sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
drhc926afb2002-06-20 03:38:26 +0000343 }
344 zSortOrder[pOrderBy->nExpr] = 0;
danielk19774adee202004-05-08 08:23:19 +0000345 sqlite3VdbeOp3(v, OP_SortMakeKey, pOrderBy->nExpr, 0, zSortOrder, P3_DYNAMIC);
346 sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000347}
348
349/*
drh38640e12002-07-05 21:42:36 +0000350** This routine adds a P3 argument to the last VDBE opcode that was
351** inserted. The P3 argument added is a string suitable for the
352** OP_MakeKey or OP_MakeIdxKey opcodes. The string consists of
353** characters 't' or 'n' depending on whether or not the various
354** fields of the key to be generated should be treated as numeric
355** or as text. See the OP_MakeKey and OP_MakeIdxKey opcode
356** documentation for additional information about the P3 string.
danielk19774adee202004-05-08 08:23:19 +0000357** See also the sqlite3AddIdxKeyType() routine.
drh38640e12002-07-05 21:42:36 +0000358*/
danielk19774adee202004-05-08 08:23:19 +0000359void sqlite3AddKeyType(Vdbe *v, ExprList *pEList){
drh38640e12002-07-05 21:42:36 +0000360 int nColumn = pEList->nExpr;
361 char *zType = sqliteMalloc( nColumn+1 );
362 int i;
363 if( zType==0 ) return;
364 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000365 zType[i] = sqlite3ExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
drh38640e12002-07-05 21:42:36 +0000366 }
367 zType[i] = 0;
danielk19774adee202004-05-08 08:23:19 +0000368 sqlite3VdbeChangeP3(v, -1, zType, P3_DYNAMIC);
drh38640e12002-07-05 21:42:36 +0000369}
370
371/*
drh22827922000-06-06 17:27:05 +0000372** This routine generates the code for the inside of the inner loop
373** of a SELECT.
drh82c3d632000-06-06 21:56:07 +0000374**
drh38640e12002-07-05 21:42:36 +0000375** If srcTab and nColumn are both zero, then the pEList expressions
376** are evaluated in order to get the data for this row. If nColumn>0
377** then data is pulled from srcTab and pEList is used only to get the
378** datatypes for each column.
drh22827922000-06-06 17:27:05 +0000379*/
380static int selectInnerLoop(
381 Parse *pParse, /* The parser context */
drhdf199a22002-06-14 22:38:41 +0000382 Select *p, /* The complete select statement being coded */
drh22827922000-06-06 17:27:05 +0000383 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +0000384 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +0000385 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +0000386 ExprList *pOrderBy, /* If not NULL, sort results using this key */
387 int distinct, /* If >=0, make sure results are distinct */
388 int eDest, /* How to dispose of the results */
389 int iParm, /* An argument to the disposal method */
390 int iContinue, /* Jump here to continue with next row */
danielk197784ac9d02004-05-18 09:58:06 +0000391 int iBreak, /* Jump here to break out of the inner loop */
392 char *aff /* affinity string if eDest is SRT_Union */
drh22827922000-06-06 17:27:05 +0000393){
394 Vdbe *v = pParse->pVdbe;
395 int i;
drh38640e12002-07-05 21:42:36 +0000396
drhdaffd0e2001-04-11 14:28:42 +0000397 if( v==0 ) return 0;
drh38640e12002-07-05 21:42:36 +0000398 assert( pEList!=0 );
drh22827922000-06-06 17:27:05 +0000399
drhdf199a22002-06-14 22:38:41 +0000400 /* If there was a LIMIT clause on the SELECT statement, then do the check
401 ** to see if this row should be output.
402 */
403 if( pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +0000404 if( p->iOffset>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000405 int addr = sqlite3VdbeCurrentAddr(v);
406 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2);
407 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
drhdf199a22002-06-14 22:38:41 +0000408 }
drh7b58dae2003-07-20 01:16:46 +0000409 if( p->iLimit>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000410 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
drhdf199a22002-06-14 22:38:41 +0000411 }
412 }
413
drh967e8b72000-06-21 13:59:10 +0000414 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000415 */
drh38640e12002-07-05 21:42:36 +0000416 if( nColumn>0 ){
drh967e8b72000-06-21 13:59:10 +0000417 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000418 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000419 }
drh38640e12002-07-05 21:42:36 +0000420 }else{
421 nColumn = pEList->nExpr;
422 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +0000423 sqlite3ExprCode(pParse, pEList->a[i].pExpr);
drh38640e12002-07-05 21:42:36 +0000424 }
drh22827922000-06-06 17:27:05 +0000425 }
426
drhdaffd0e2001-04-11 14:28:42 +0000427 /* If the DISTINCT keyword was present on the SELECT statement
428 ** and this row has been seen before, then do not make this row
429 ** part of the result.
drh22827922000-06-06 17:27:05 +0000430 */
drhf5905aa2002-05-26 20:54:33 +0000431 if( distinct>=0 && pEList && pEList->nExpr>0 ){
drh0bd1f4e2002-06-06 18:54:39 +0000432#if NULL_ALWAYS_DISTINCT
danielk19774adee202004-05-08 08:23:19 +0000433 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
drh0bd1f4e2002-06-06 18:54:39 +0000434#endif
danielk19774adee202004-05-08 08:23:19 +0000435 sqlite3VdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
danielk197736a3c702004-05-11 06:55:14 +0000436 sqlite3AddKeyType(v, pEList);
danielk19774adee202004-05-08 08:23:19 +0000437 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
438 sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
439 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
440 sqlite3VdbeAddOp(v, OP_String, 0, 0);
441 sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
drh22827922000-06-06 17:27:05 +0000442 }
drh82c3d632000-06-06 21:56:07 +0000443
drhc926afb2002-06-20 03:38:26 +0000444 switch( eDest ){
445 /* In this mode, write each query result to the key of the temporary
446 ** table iParm.
447 */
448 case SRT_Union: {
danielk19774adee202004-05-08 08:23:19 +0000449 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000450 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000451 sqlite3VdbeAddOp(v, OP_String, 0, 0);
452 sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000453 break;
drh22827922000-06-06 17:27:05 +0000454 }
drh22827922000-06-06 17:27:05 +0000455
drhc926afb2002-06-20 03:38:26 +0000456 /* Store the result as data using a unique key.
457 */
458 case SRT_Table:
459 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000460 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000461 if( pOrderBy ){
462 pushOntoSorter(pParse, v, pOrderBy);
463 }else{
danielk19774adee202004-05-08 08:23:19 +0000464 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
465 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
466 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000467 }
468 break;
469 }
drh82c3d632000-06-06 21:56:07 +0000470
drhc926afb2002-06-20 03:38:26 +0000471 /* Construct a record from the query result, but instead of
472 ** saving that record, use it as a key to delete elements from
473 ** the temporary table iParm.
474 */
475 case SRT_Except: {
476 int addr;
danielk19774adee202004-05-08 08:23:19 +0000477 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
danielk197784ac9d02004-05-18 09:58:06 +0000478 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000479 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
480 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000481 break;
482 }
drh5974a302000-06-07 14:42:26 +0000483
drhc926afb2002-06-20 03:38:26 +0000484 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
485 ** then there should be a single item on the stack. Write this
486 ** item into the set table with bogus data.
487 */
488 case SRT_Set: {
danielk19774adee202004-05-08 08:23:19 +0000489 int addr1 = sqlite3VdbeCurrentAddr(v);
drh52b36ca2004-01-14 13:38:54 +0000490 int addr2;
danielk1977e014a832004-05-17 10:48:57 +0000491
drhc926afb2002-06-20 03:38:26 +0000492 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000493 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
494 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
495 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
drhc926afb2002-06-20 03:38:26 +0000496 if( pOrderBy ){
497 pushOntoSorter(pParse, v, pOrderBy);
498 }else{
danielk1977e014a832004-05-17 10:48:57 +0000499 char const *affStr;
500 char aff = (iParm>>16)&0xFF;
501 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
502 affStr = sqlite3AffinityString(aff);
danielk197784ac9d02004-05-18 09:58:06 +0000503 sqlite3VdbeOp3(v, OP_MakeKey, 1, 0, affStr, P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000504 sqlite3VdbeAddOp(v, OP_String, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000505 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000506 }
danielk19774adee202004-05-08 08:23:19 +0000507 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
drhc926afb2002-06-20 03:38:26 +0000508 break;
509 }
drh22827922000-06-06 17:27:05 +0000510
drhc926afb2002-06-20 03:38:26 +0000511 /* If this is a scalar select that is part of an expression, then
512 ** store the results in the appropriate memory cell and break out
513 ** of the scan loop.
514 */
515 case SRT_Mem: {
516 assert( nColumn==1 );
517 if( pOrderBy ){
518 pushOntoSorter(pParse, v, pOrderBy);
519 }else{
danielk19774adee202004-05-08 08:23:19 +0000520 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
521 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
drhc926afb2002-06-20 03:38:26 +0000522 }
523 break;
524 }
drh22827922000-06-06 17:27:05 +0000525
drhf46f9052002-06-22 02:33:38 +0000526 /* Send the data to the callback function.
527 */
528 case SRT_Callback:
529 case SRT_Sorter: {
530 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000531 sqlite3VdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000532 pushOntoSorter(pParse, v, pOrderBy);
533 }else{
534 assert( eDest==SRT_Callback );
danielk19774adee202004-05-08 08:23:19 +0000535 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
drhf46f9052002-06-22 02:33:38 +0000536 }
537 break;
538 }
539
drh142e30d2002-08-28 03:00:58 +0000540 /* Invoke a subroutine to handle the results. The subroutine itself
541 ** is responsible for popping the results off of the stack.
542 */
543 case SRT_Subroutine: {
drhac82fcf2002-09-08 17:23:41 +0000544 if( pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +0000545 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
drhac82fcf2002-09-08 17:23:41 +0000546 pushOntoSorter(pParse, v, pOrderBy);
547 }else{
danielk19774adee202004-05-08 08:23:19 +0000548 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
drhac82fcf2002-09-08 17:23:41 +0000549 }
drh142e30d2002-08-28 03:00:58 +0000550 break;
551 }
552
drhc926afb2002-06-20 03:38:26 +0000553 /* Discard the results. This is used for SELECT statements inside
554 ** the body of a TRIGGER. The purpose of such selects is to call
555 ** user-defined functions that have side effects. We do not care
556 ** about the actual results of the select.
557 */
drhc926afb2002-06-20 03:38:26 +0000558 default: {
drhf46f9052002-06-22 02:33:38 +0000559 assert( eDest==SRT_Discard );
danielk19774adee202004-05-08 08:23:19 +0000560 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000561 break;
562 }
drh82c3d632000-06-06 21:56:07 +0000563 }
564 return 0;
565}
566
567/*
drhd8bc7082000-06-07 23:51:50 +0000568** If the inner loop was generated using a non-null pOrderBy argument,
569** then the results were placed in a sorter. After the loop is terminated
570** we need to run the sorter and output the results. The following
571** routine generates the code needed to do that.
572*/
drhc926afb2002-06-20 03:38:26 +0000573static void generateSortTail(
574 Select *p, /* The SELECT statement */
575 Vdbe *v, /* Generate code into this VDBE */
576 int nColumn, /* Number of columns of data */
577 int eDest, /* Write the sorted results here */
578 int iParm /* Optional parameter associated with eDest */
579){
danielk19774adee202004-05-08 08:23:19 +0000580 int end1 = sqlite3VdbeMakeLabel(v);
581 int end2 = sqlite3VdbeMakeLabel(v);
drhd8bc7082000-06-07 23:51:50 +0000582 int addr;
drhf46f9052002-06-22 02:33:38 +0000583 if( eDest==SRT_Sorter ) return;
danielk19774adee202004-05-08 08:23:19 +0000584 sqlite3VdbeAddOp(v, OP_Sort, 0, 0);
585 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
drh7b58dae2003-07-20 01:16:46 +0000586 if( p->iOffset>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000587 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4);
588 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
589 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
drhdf199a22002-06-14 22:38:41 +0000590 }
drh7b58dae2003-07-20 01:16:46 +0000591 if( p->iLimit>=0 ){
danielk19774adee202004-05-08 08:23:19 +0000592 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, end2);
drhdf199a22002-06-14 22:38:41 +0000593 }
drhc926afb2002-06-20 03:38:26 +0000594 switch( eDest ){
595 case SRT_Callback: {
danielk19774adee202004-05-08 08:23:19 +0000596 sqlite3VdbeAddOp(v, OP_SortCallback, nColumn, 0);
drhc926afb2002-06-20 03:38:26 +0000597 break;
598 }
599 case SRT_Table:
600 case SRT_TempTable: {
danielk19774adee202004-05-08 08:23:19 +0000601 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
602 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
603 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
drhc926afb2002-06-20 03:38:26 +0000604 break;
605 }
606 case SRT_Set: {
607 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000608 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
609 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
610 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
danielk1977e014a832004-05-17 10:48:57 +0000611 sqlite3VdbeOp3(v, OP_MakeKey, 1, 1, "n", P3_STATIC);
danielk19774adee202004-05-08 08:23:19 +0000612 sqlite3VdbeAddOp(v, OP_String, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +0000613 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
drhc926afb2002-06-20 03:38:26 +0000614 break;
615 }
616 case SRT_Mem: {
617 assert( nColumn==1 );
danielk19774adee202004-05-08 08:23:19 +0000618 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
619 sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
drhc926afb2002-06-20 03:38:26 +0000620 break;
621 }
drhac82fcf2002-09-08 17:23:41 +0000622 case SRT_Subroutine: {
623 int i;
danielk197784ac9d02004-05-18 09:58:06 +0000624 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
625 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhac82fcf2002-09-08 17:23:41 +0000626 for(i=0; i<nColumn; i++){
danielk19774adee202004-05-08 08:23:19 +0000627 sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
drhac82fcf2002-09-08 17:23:41 +0000628 }
danielk19774adee202004-05-08 08:23:19 +0000629 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
danielk197784ac9d02004-05-18 09:58:06 +0000630 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhac82fcf2002-09-08 17:23:41 +0000631 break;
632 }
drhc926afb2002-06-20 03:38:26 +0000633 default: {
drhf46f9052002-06-22 02:33:38 +0000634 /* Do nothing */
drhc926afb2002-06-20 03:38:26 +0000635 break;
636 }
637 }
danielk19774adee202004-05-08 08:23:19 +0000638 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
639 sqlite3VdbeResolveLabel(v, end2);
640 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
641 sqlite3VdbeResolveLabel(v, end1);
642 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000643}
644
645/*
drhfcb78a42003-01-18 20:11:05 +0000646** Generate code that will tell the VDBE the datatypes of
647** columns in the result set.
drhe78e8282003-01-19 03:59:45 +0000648**
649** This routine only generates code if the "PRAGMA show_datatypes=on"
650** has been executed. The datatypes are reported out in the azCol
651** parameter to the callback function. The first N azCol[] entries
652** are the names of the columns, and the second N entries are the
653** datatypes for the columns.
654**
655** The "datatype" for a result that is a column of a type is the
656** datatype definition extracted from the CREATE TABLE statement.
657** The datatype for an expression is either TEXT or NUMERIC. The
658** datatype for a ROWID field is INTEGER.
drhfcb78a42003-01-18 20:11:05 +0000659*/
660static void generateColumnTypes(
661 Parse *pParse, /* Parser context */
drhfcb78a42003-01-18 20:11:05 +0000662 SrcList *pTabList, /* List of tables */
663 ExprList *pEList /* Expressions defining the result set */
664){
665 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000666 int i, j;
drhfcb78a42003-01-18 20:11:05 +0000667 for(i=0; i<pEList->nExpr; i++){
668 Expr *p = pEList->a[i].pExpr;
669 char *zType = 0;
670 if( p==0 ) continue;
671 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000672 Table *pTab;
drhfcb78a42003-01-18 20:11:05 +0000673 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000674 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
675 assert( j<pTabList->nSrc );
676 pTab = pTabList->a[j].pTab;
drhfcb78a42003-01-18 20:11:05 +0000677 if( iCol<0 ) iCol = pTab->iPKey;
678 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
679 if( iCol<0 ){
680 zType = "INTEGER";
681 }else{
682 zType = pTab->aCol[iCol].zType;
683 }
684 }else{
danielk19774adee202004-05-08 08:23:19 +0000685 if( sqlite3ExprType(p)==SQLITE_SO_TEXT ){
drhfcb78a42003-01-18 20:11:05 +0000686 zType = "TEXT";
687 }else{
688 zType = "NUMERIC";
689 }
690 }
danielk19774adee202004-05-08 08:23:19 +0000691 sqlite3VdbeOp3(v, OP_ColumnName, i + pEList->nExpr, 0, zType, 0);
drhfcb78a42003-01-18 20:11:05 +0000692 }
693}
694
695/*
696** Generate code that will tell the VDBE the names of columns
697** in the result set. This information is used to provide the
drhfcabd462004-02-20 14:50:58 +0000698** azCol[] values in the callback.
drh82c3d632000-06-06 21:56:07 +0000699*/
drh832508b2002-03-02 17:04:07 +0000700static void generateColumnNames(
701 Parse *pParse, /* Parser context */
drhad3cab52002-05-24 02:04:32 +0000702 SrcList *pTabList, /* List of tables */
drh832508b2002-03-02 17:04:07 +0000703 ExprList *pEList /* Expressions defining the result set */
704){
drhd8bc7082000-06-07 23:51:50 +0000705 Vdbe *v = pParse->pVdbe;
drh6a3ea0e2003-05-02 14:32:12 +0000706 int i, j;
drhfcabd462004-02-20 14:50:58 +0000707 sqlite *db = pParse->db;
708 int fullNames, shortNames;
709
drhd6502752004-02-16 03:44:01 +0000710 assert( v!=0 );
danielk19776f8a5032004-05-10 10:34:51 +0000711 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000712 pParse->colNamesSet = 1;
drhfcabd462004-02-20 14:50:58 +0000713 fullNames = (db->flags & SQLITE_FullColNames)!=0;
714 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
drh82c3d632000-06-06 21:56:07 +0000715 for(i=0; i<pEList->nExpr; i++){
716 Expr *p;
drhd6502752004-02-16 03:44:01 +0000717 int p2 = i==pEList->nExpr-1;
drh5a387052003-01-11 14:19:51 +0000718 p = pEList->a[i].pExpr;
719 if( p==0 ) continue;
drh82c3d632000-06-06 21:56:07 +0000720 if( pEList->a[i].zName ){
721 char *zName = pEList->a[i].zName;
danielk19774adee202004-05-08 08:23:19 +0000722 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000723 continue;
724 }
drhfa173a72002-07-10 21:26:00 +0000725 if( p->op==TK_COLUMN && pTabList ){
drh6a3ea0e2003-05-02 14:32:12 +0000726 Table *pTab;
drh97665872002-02-13 23:22:53 +0000727 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000728 int iCol = p->iColumn;
drh6a3ea0e2003-05-02 14:32:12 +0000729 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
730 assert( j<pTabList->nSrc );
731 pTab = pTabList->a[j].pTab;
drh8aff1012001-12-22 14:49:24 +0000732 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000733 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
drhb1363202002-06-26 02:45:03 +0000734 if( iCol<0 ){
735 zCol = "_ROWID_";
drhb1363202002-06-26 02:45:03 +0000736 }else{
737 zCol = pTab->aCol[iCol].zName;
drhb1363202002-06-26 02:45:03 +0000738 }
drhfcabd462004-02-20 14:50:58 +0000739 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000740 int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
741 sqlite3VdbeCompressSpace(v, addr);
drhfcabd462004-02-20 14:50:58 +0000742 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
drh82c3d632000-06-06 21:56:07 +0000743 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000744 char *zTab;
745
drh6a3ea0e2003-05-02 14:32:12 +0000746 zTab = pTabList->a[j].zAlias;
drhfcabd462004-02-20 14:50:58 +0000747 if( fullNames || zTab==0 ) zTab = pTab->zName;
danielk19774adee202004-05-08 08:23:19 +0000748 sqlite3SetString(&zName, zTab, ".", zCol, 0);
749 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, P3_DYNAMIC);
drh82c3d632000-06-06 21:56:07 +0000750 }else{
danielk19774adee202004-05-08 08:23:19 +0000751 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000752 }
drh6977fea2002-10-22 23:38:04 +0000753 }else if( p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000754 int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
755 sqlite3VdbeCompressSpace(v, addr);
drh1bee3d72001-10-15 00:44:35 +0000756 }else{
757 char zName[30];
758 assert( p->op!=TK_COLUMN || pTabList==0 );
759 sprintf(zName, "column%d", i+1);
danielk19774adee202004-05-08 08:23:19 +0000760 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000761 }
762 }
763}
764
765/*
drhd8bc7082000-06-07 23:51:50 +0000766** Name of the connection operator, used for error messages.
767*/
768static const char *selectOpName(int id){
769 char *z;
770 switch( id ){
771 case TK_ALL: z = "UNION ALL"; break;
772 case TK_INTERSECT: z = "INTERSECT"; break;
773 case TK_EXCEPT: z = "EXCEPT"; break;
774 default: z = "UNION"; break;
775 }
776 return z;
777}
778
779/*
drh315555c2002-10-20 15:53:03 +0000780** Forward declaration
781*/
782static int fillInColumnList(Parse*, Select*);
783
784/*
drh22f70c32002-02-18 01:17:00 +0000785** Given a SELECT statement, generate a Table structure that describes
786** the result set of that SELECT.
787*/
danielk19774adee202004-05-08 08:23:19 +0000788Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
drh22f70c32002-02-18 01:17:00 +0000789 Table *pTab;
drhb733d032004-01-24 20:18:12 +0000790 int i, j;
drh22f70c32002-02-18 01:17:00 +0000791 ExprList *pEList;
drhb733d032004-01-24 20:18:12 +0000792 Column *aCol;
drh22f70c32002-02-18 01:17:00 +0000793
794 if( fillInColumnList(pParse, pSelect) ){
795 return 0;
796 }
797 pTab = sqliteMalloc( sizeof(Table) );
798 if( pTab==0 ){
799 return 0;
800 }
801 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
802 pEList = pSelect->pEList;
803 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000804 assert( pTab->nCol>0 );
drhb733d032004-01-24 20:18:12 +0000805 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
drh22f70c32002-02-18 01:17:00 +0000806 for(i=0; i<pTab->nCol; i++){
drhb733d032004-01-24 20:18:12 +0000807 Expr *p, *pR;
drh22f70c32002-02-18 01:17:00 +0000808 if( pEList->a[i].zName ){
drhb733d032004-01-24 20:18:12 +0000809 aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
810 }else if( (p=pEList->a[i].pExpr)->op==TK_DOT
811 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
812 int cnt;
danielk19774adee202004-05-08 08:23:19 +0000813 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
drhb733d032004-01-24 20:18:12 +0000814 for(j=cnt=0; j<i; j++){
danielk19774adee202004-05-08 08:23:19 +0000815 if( sqlite3StrICmp(aCol[j].zName, aCol[i].zName)==0 ){
drhb733d032004-01-24 20:18:12 +0000816 int n;
817 char zBuf[30];
818 sprintf(zBuf,"_%d",++cnt);
819 n = strlen(zBuf);
danielk1977e014a832004-05-17 10:48:57 +0000820 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf,n,0);
drhb733d032004-01-24 20:18:12 +0000821 j = -1;
822 }
823 }
824 }else if( p->span.z && p->span.z[0] ){
danielk19774adee202004-05-08 08:23:19 +0000825 sqlite3SetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drh22f70c32002-02-18 01:17:00 +0000826 }else{
827 char zBuf[30];
828 sprintf(zBuf, "column%d", i+1);
829 pTab->aCol[i].zName = sqliteStrDup(zBuf);
830 }
danielk1977e014a832004-05-17 10:48:57 +0000831
832 /* Affinity is always NONE, as there is no type name. */
833 pTab->aCol[i].affinity = SQLITE_AFF_NONE;
drh22f70c32002-02-18 01:17:00 +0000834 }
835 pTab->iPKey = -1;
836 return pTab;
837}
838
839/*
drhad2d8302002-05-24 20:31:36 +0000840** For the given SELECT statement, do three things.
drhd8bc7082000-06-07 23:51:50 +0000841**
drhad3cab52002-05-24 02:04:32 +0000842** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
drh63eb5f22003-04-29 16:20:44 +0000843** defines the set of tables that should be scanned. For views,
844** fill pTabList->a[].pSelect with a copy of the SELECT statement
845** that implements the view. A copy is made of the view's SELECT
846** statement so that we can freely modify or delete that statement
847** without worrying about messing up the presistent representation
848** of the view.
drhd8bc7082000-06-07 23:51:50 +0000849**
drhad2d8302002-05-24 20:31:36 +0000850** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
851** on joins and the ON and USING clause of joins.
852**
853** (3) Scan the list of columns in the result set (pEList) looking
drh54473222002-04-04 02:10:55 +0000854** for instances of the "*" operator or the TABLE.* operator.
855** If found, expand each "*" to be every column in every table
856** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000857**
858** Return 0 on success. If there are problems, leave an error message
859** in pParse and return non-zero.
860*/
861static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000862 int i, j, k, rc;
drhad3cab52002-05-24 02:04:32 +0000863 SrcList *pTabList;
drhdaffd0e2001-04-11 14:28:42 +0000864 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000865 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000866
867 if( p==0 || p->pSrc==0 ) return 1;
868 pTabList = p->pSrc;
869 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000870
871 /* Look up every table in the table list.
872 */
drhad3cab52002-05-24 02:04:32 +0000873 for(i=0; i<pTabList->nSrc; i++){
drhd8bc7082000-06-07 23:51:50 +0000874 if( pTabList->a[i].pTab ){
875 /* This routine has run before! No need to continue */
876 return 0;
877 }
drhdaffd0e2001-04-11 14:28:42 +0000878 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000879 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000880 assert( pTabList->a[i].pSelect!=0 );
drhad2d8302002-05-24 20:31:36 +0000881 if( pTabList->a[i].zAlias==0 ){
882 char zFakeName[60];
883 sprintf(zFakeName, "sqlite_subquery_%p_",
884 (void*)pTabList->a[i].pSelect);
danielk19774adee202004-05-08 08:23:19 +0000885 sqlite3SetString(&pTabList->a[i].zAlias, zFakeName, 0);
drhad2d8302002-05-24 20:31:36 +0000886 }
drh22f70c32002-02-18 01:17:00 +0000887 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000888 sqlite3ResultSetOfSelect(pParse, pTabList->a[i].zAlias,
drh22f70c32002-02-18 01:17:00 +0000889 pTabList->a[i].pSelect);
890 if( pTab==0 ){
891 return 1;
892 }
drh5cf590c2003-04-24 01:45:04 +0000893 /* The isTransient flag indicates that the Table structure has been
894 ** dynamically allocated and may be freed at any time. In other words,
895 ** pTab is not pointing to a persistent table structure that defines
896 ** part of the schema. */
drh22f70c32002-02-18 01:17:00 +0000897 pTab->isTransient = 1;
898 }else{
drha76b5df2002-02-23 02:32:10 +0000899 /* An ordinary table or view name in the FROM clause */
900 pTabList->a[i].pTab = pTab =
danielk19774adee202004-05-08 08:23:19 +0000901 sqlite3LocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
drha76b5df2002-02-23 02:32:10 +0000902 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000903 return 1;
904 }
drha76b5df2002-02-23 02:32:10 +0000905 if( pTab->pSelect ){
drh63eb5f22003-04-29 16:20:44 +0000906 /* We reach here if the named table is a really a view */
danielk19774adee202004-05-08 08:23:19 +0000907 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh417be792002-03-03 18:59:40 +0000908 return 1;
909 }
drh63eb5f22003-04-29 16:20:44 +0000910 /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
911 ** view within a view. The SELECT structure has already been
912 ** copied by the outer view so we can skip the copy step here
913 ** in the inner view.
914 */
915 if( pTabList->a[i].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +0000916 pTabList->a[i].pSelect = sqlite3SelectDup(pTab->pSelect);
drh63eb5f22003-04-29 16:20:44 +0000917 }
drha76b5df2002-02-23 02:32:10 +0000918 }
drhd8bc7082000-06-07 23:51:50 +0000919 }
920 }
921
drhad2d8302002-05-24 20:31:36 +0000922 /* Process NATURAL keywords, and ON and USING clauses of joins.
923 */
924 if( sqliteProcessJoin(pParse, p) ) return 1;
925
drh7c917d12001-12-16 20:05:05 +0000926 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000927 ** all columns in all tables. And for every TABLE.* insert the names
928 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000929 ** with the TK_ALL operator for each "*" that it found in the column list.
930 ** The following code just has to locate the TK_ALL expressions and expand
931 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000932 **
933 ** The first loop just checks to see if there are any "*" operators
934 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000935 */
drh7c917d12001-12-16 20:05:05 +0000936 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000937 Expr *pE = pEList->a[k].pExpr;
938 if( pE->op==TK_ALL ) break;
939 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
940 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000941 }
drh54473222002-04-04 02:10:55 +0000942 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000943 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000944 /*
945 ** If we get here it means the result set contains one or more "*"
946 ** operators that need to be expanded. Loop through each expression
947 ** in the result set and expand them one by one.
948 */
drh7c917d12001-12-16 20:05:05 +0000949 struct ExprList_item *a = pEList->a;
950 ExprList *pNew = 0;
951 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000952 Expr *pE = a[k].pExpr;
953 if( pE->op!=TK_ALL &&
954 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
955 /* This particular expression does not need to be expanded.
956 */
danielk19774adee202004-05-08 08:23:19 +0000957 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
drh7c917d12001-12-16 20:05:05 +0000958 pNew->a[pNew->nExpr-1].zName = a[k].zName;
959 a[k].pExpr = 0;
960 a[k].zName = 0;
961 }else{
drh54473222002-04-04 02:10:55 +0000962 /* This expression is a "*" or a "TABLE.*" and needs to be
963 ** expanded. */
964 int tableSeen = 0; /* Set to 1 when TABLE matches */
965 Token *pName; /* text of name of TABLE */
966 if( pE->op==TK_DOT && pE->pLeft ){
967 pName = &pE->pLeft->token;
968 }else{
969 pName = 0;
970 }
drhad3cab52002-05-24 02:04:32 +0000971 for(i=0; i<pTabList->nSrc; i++){
drh7c917d12001-12-16 20:05:05 +0000972 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000973 char *zTabName = pTabList->a[i].zAlias;
974 if( zTabName==0 || zTabName[0]==0 ){
975 zTabName = pTab->zName;
976 }
drhc754fa52002-05-27 03:25:51 +0000977 if( pName && (zTabName==0 || zTabName[0]==0 ||
danielk19774adee202004-05-08 08:23:19 +0000978 sqlite3StrNICmp(pName->z, zTabName, pName->n)!=0 ||
drhc754fa52002-05-27 03:25:51 +0000979 zTabName[pName->n]!=0) ){
drh54473222002-04-04 02:10:55 +0000980 continue;
981 }
982 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +0000983 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000984 Expr *pExpr, *pLeft, *pRight;
drhad2d8302002-05-24 20:31:36 +0000985 char *zName = pTab->aCol[j].zName;
986
987 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
988 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
989 /* In a NATURAL join, omit the join columns from the
990 ** table on the right */
991 continue;
992 }
danielk19774adee202004-05-08 08:23:19 +0000993 if( i>0 && sqlite3IdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
drhad2d8302002-05-24 20:31:36 +0000994 /* In a join with a USING clause, omit columns in the
995 ** using clause from the table on the right. */
996 continue;
997 }
danielk19774adee202004-05-08 08:23:19 +0000998 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
drh22f70c32002-02-18 01:17:00 +0000999 if( pRight==0 ) break;
drhad2d8302002-05-24 20:31:36 +00001000 pRight->token.z = zName;
1001 pRight->token.n = strlen(zName);
drh4b59ab52002-08-24 18:24:51 +00001002 pRight->token.dyn = 0;
drh4b59ab52002-08-24 18:24:51 +00001003 if( zTabName && pTabList->nSrc>1 ){
danielk19774adee202004-05-08 08:23:19 +00001004 pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
1005 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
drh22f70c32002-02-18 01:17:00 +00001006 if( pExpr==0 ) break;
drh4b59ab52002-08-24 18:24:51 +00001007 pLeft->token.z = zTabName;
1008 pLeft->token.n = strlen(zTabName);
1009 pLeft->token.dyn = 0;
danielk19774adee202004-05-08 08:23:19 +00001010 sqlite3SetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
drh6977fea2002-10-22 23:38:04 +00001011 pExpr->span.n = strlen(pExpr->span.z);
1012 pExpr->span.dyn = 1;
1013 pExpr->token.z = 0;
1014 pExpr->token.n = 0;
1015 pExpr->token.dyn = 0;
drh7c917d12001-12-16 20:05:05 +00001016 }else{
drh22f70c32002-02-18 01:17:00 +00001017 pExpr = pRight;
drh6977fea2002-10-22 23:38:04 +00001018 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +00001019 }
danielk19774adee202004-05-08 08:23:19 +00001020 pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
drh7c917d12001-12-16 20:05:05 +00001021 }
drh17e24df2001-11-06 14:10:41 +00001022 }
drh54473222002-04-04 02:10:55 +00001023 if( !tableSeen ){
drhf5db2d32002-06-06 23:42:27 +00001024 if( pName ){
danielk19774adee202004-05-08 08:23:19 +00001025 sqlite3ErrorMsg(pParse, "no such table: %T", pName);
drhf5db2d32002-06-06 23:42:27 +00001026 }else{
danielk19774adee202004-05-08 08:23:19 +00001027 sqlite3ErrorMsg(pParse, "no tables specified");
drhf5db2d32002-06-06 23:42:27 +00001028 }
drh54473222002-04-04 02:10:55 +00001029 rc = 1;
1030 }
drhd8bc7082000-06-07 23:51:50 +00001031 }
1032 }
danielk19774adee202004-05-08 08:23:19 +00001033 sqlite3ExprListDelete(pEList);
drh7c917d12001-12-16 20:05:05 +00001034 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +00001035 }
drh54473222002-04-04 02:10:55 +00001036 return rc;
drhd8bc7082000-06-07 23:51:50 +00001037}
1038
1039/*
drhff78bd22002-02-27 01:47:11 +00001040** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1041** in a select structure. It just sets the pointers to NULL. This
1042** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1043** pointer is not NULL, this routine is called recursively on that pointer.
1044**
1045** This routine is called on the Select structure that defines a
1046** VIEW in order to undo any bindings to tables. This is necessary
1047** because those tables might be DROPed by a subsequent SQL command.
drh5cf590c2003-04-24 01:45:04 +00001048** If the bindings are not removed, then the Select.pSrc->a[].pTab field
1049** will be left pointing to a deallocated Table structure after the
1050** DROP and a coredump will occur the next time the VIEW is used.
drhff78bd22002-02-27 01:47:11 +00001051*/
danielk19774adee202004-05-08 08:23:19 +00001052void sqlite3SelectUnbind(Select *p){
drhff78bd22002-02-27 01:47:11 +00001053 int i;
drhad3cab52002-05-24 02:04:32 +00001054 SrcList *pSrc = p->pSrc;
drhff78bd22002-02-27 01:47:11 +00001055 Table *pTab;
1056 if( p==0 ) return;
drhad3cab52002-05-24 02:04:32 +00001057 for(i=0; i<pSrc->nSrc; i++){
drhff78bd22002-02-27 01:47:11 +00001058 if( (pTab = pSrc->a[i].pTab)!=0 ){
1059 if( pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001060 sqlite3DeleteTable(0, pTab);
drhff78bd22002-02-27 01:47:11 +00001061 }
1062 pSrc->a[i].pTab = 0;
1063 if( pSrc->a[i].pSelect ){
danielk19774adee202004-05-08 08:23:19 +00001064 sqlite3SelectUnbind(pSrc->a[i].pSelect);
drhff78bd22002-02-27 01:47:11 +00001065 }
1066 }
1067 }
1068}
1069
1070/*
drhd8bc7082000-06-07 23:51:50 +00001071** This routine associates entries in an ORDER BY expression list with
1072** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +00001073** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +00001074** the top-level node is filled in with column number and the iTable
1075** value of the top-level node is filled with iTable parameter.
1076**
1077** If there are prior SELECT clauses, they are processed first. A match
1078** in an earlier SELECT takes precedence over a later SELECT.
1079**
1080** Any entry that does not match is flagged as an error. The number
1081** of errors is returned.
drhfcb78a42003-01-18 20:11:05 +00001082**
1083** This routine does NOT correctly initialize the Expr.dataType field
1084** of the ORDER BY expressions. The multiSelectSortOrder() routine
1085** must be called to do that after the individual select statements
1086** have all been analyzed. This routine is unable to compute Expr.dataType
1087** because it must be called before the individual select statements
1088** have been analyzed.
drhd8bc7082000-06-07 23:51:50 +00001089*/
1090static int matchOrderbyToColumn(
1091 Parse *pParse, /* A place to leave error messages */
1092 Select *pSelect, /* Match to result columns of this SELECT */
1093 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
drhe4de1fe2002-06-02 16:09:01 +00001094 int iTable, /* Insert this value in iTable */
drhd8bc7082000-06-07 23:51:50 +00001095 int mustComplete /* If TRUE all ORDER BYs must match */
1096){
1097 int nErr = 0;
1098 int i, j;
1099 ExprList *pEList;
1100
drhdaffd0e2001-04-11 14:28:42 +00001101 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +00001102 if( mustComplete ){
1103 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1104 }
1105 if( fillInColumnList(pParse, pSelect) ){
1106 return 1;
1107 }
1108 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +00001109 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
1110 return 1;
1111 }
drhd8bc7082000-06-07 23:51:50 +00001112 }
1113 pEList = pSelect->pEList;
1114 for(i=0; i<pOrderBy->nExpr; i++){
1115 Expr *pE = pOrderBy->a[i].pExpr;
drhe4de1fe2002-06-02 16:09:01 +00001116 int iCol = -1;
drhd8bc7082000-06-07 23:51:50 +00001117 if( pOrderBy->a[i].done ) continue;
danielk19774adee202004-05-08 08:23:19 +00001118 if( sqlite3ExprIsInteger(pE, &iCol) ){
drhe4de1fe2002-06-02 16:09:01 +00001119 if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001120 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001121 "ORDER BY position %d should be between 1 and %d",
1122 iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00001123 nErr++;
1124 break;
1125 }
drhfcb78a42003-01-18 20:11:05 +00001126 if( !mustComplete ) continue;
drhe4de1fe2002-06-02 16:09:01 +00001127 iCol--;
1128 }
1129 for(j=0; iCol<0 && j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +00001130 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +00001131 char *zName, *zLabel;
1132 zName = pEList->a[j].zName;
1133 assert( pE->token.z );
1134 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
danielk19774adee202004-05-08 08:23:19 +00001135 sqlite3Dequote(zLabel);
1136 if( sqlite3StrICmp(zName, zLabel)==0 ){
drhe4de1fe2002-06-02 16:09:01 +00001137 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001138 }
drh6e142f52000-06-08 13:36:40 +00001139 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +00001140 }
danielk19774adee202004-05-08 08:23:19 +00001141 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
drhe4de1fe2002-06-02 16:09:01 +00001142 iCol = j;
drhd8bc7082000-06-07 23:51:50 +00001143 }
1144 }
drhe4de1fe2002-06-02 16:09:01 +00001145 if( iCol>=0 ){
1146 pE->op = TK_COLUMN;
1147 pE->iColumn = iCol;
1148 pE->iTable = iTable;
1149 pOrderBy->a[i].done = 1;
1150 }
1151 if( iCol<0 && mustComplete ){
danielk19774adee202004-05-08 08:23:19 +00001152 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001153 "ORDER BY term number %d does not match any result column", i+1);
drhd8bc7082000-06-07 23:51:50 +00001154 nErr++;
1155 break;
1156 }
1157 }
1158 return nErr;
1159}
1160
1161/*
1162** Get a VDBE for the given parser context. Create a new one if necessary.
1163** If an error occurs, return NULL and leave a message in pParse.
1164*/
danielk19774adee202004-05-08 08:23:19 +00001165Vdbe *sqlite3GetVdbe(Parse *pParse){
drhd8bc7082000-06-07 23:51:50 +00001166 Vdbe *v = pParse->pVdbe;
1167 if( v==0 ){
danielk19774adee202004-05-08 08:23:19 +00001168 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +00001169 }
drhd8bc7082000-06-07 23:51:50 +00001170 return v;
1171}
drhfcb78a42003-01-18 20:11:05 +00001172
1173/*
1174** This routine sets the Expr.dataType field on all elements of
1175** the pOrderBy expression list. The pOrderBy list will have been
1176** set up by matchOrderbyToColumn(). Hence each expression has
1177** a TK_COLUMN as its root node. The Expr.iColumn refers to a
1178** column in the result set. The datatype is set to SQLITE_SO_TEXT
1179** if the corresponding column in p and every SELECT to the left of
1180** p has a datatype of SQLITE_SO_TEXT. If the cooressponding column
1181** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
1182** of the order-by expression is set to SQLITE_SO_NUM.
1183**
1184** Examples:
1185**
drhe78e8282003-01-19 03:59:45 +00001186** CREATE TABLE one(a INTEGER, b TEXT);
1187** CREATE TABLE two(c VARCHAR(5), d FLOAT);
1188**
1189** SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
1190**
1191** The primary sort key will use SQLITE_SO_NUM because the "d" in
1192** the second SELECT is numeric. The 1st column of the first SELECT
1193** is text but that does not matter because a numeric always overrides
1194** a text.
1195**
1196** The secondary key will use the SQLITE_SO_TEXT sort order because
1197** both the (second) "b" in the first SELECT and the "c" in the second
1198** SELECT have a datatype of text.
drhfcb78a42003-01-18 20:11:05 +00001199*/
1200static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
1201 int i;
1202 ExprList *pEList;
1203 if( pOrderBy==0 ) return;
1204 if( p==0 ){
1205 for(i=0; i<pOrderBy->nExpr; i++){
1206 pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
1207 }
1208 return;
1209 }
1210 multiSelectSortOrder(p->pPrior, pOrderBy);
1211 pEList = p->pEList;
1212 for(i=0; i<pOrderBy->nExpr; i++){
1213 Expr *pE = pOrderBy->a[i].pExpr;
1214 if( pE->dataType==SQLITE_SO_NUM ) continue;
1215 assert( pE->iColumn>=0 );
1216 if( pEList->nExpr>pE->iColumn ){
danielk19774adee202004-05-08 08:23:19 +00001217 pE->dataType = sqlite3ExprType(pEList->a[pE->iColumn].pExpr);
drhfcb78a42003-01-18 20:11:05 +00001218 }
1219 }
1220}
drhd8bc7082000-06-07 23:51:50 +00001221
danielk197784ac9d02004-05-18 09:58:06 +00001222static void multiSelectAffinity(Select *p, char *zAff){
1223 int i;
1224
1225 if( !p ) return;
1226 multiSelectAffinity(p->pPrior, zAff);
1227
1228 for(i=0; i<p->pEList->nExpr; i++){
1229 if( zAff[i]=='\0' ){
1230 zAff[i] = sqlite3ExprAffinity(p->pEList->a[i].pExpr);
1231 }
1232 }
1233}
1234
drhd8bc7082000-06-07 23:51:50 +00001235/*
drh7b58dae2003-07-20 01:16:46 +00001236** Compute the iLimit and iOffset fields of the SELECT based on the
1237** nLimit and nOffset fields. nLimit and nOffset hold the integers
1238** that appear in the original SQL statement after the LIMIT and OFFSET
1239** keywords. Or that hold -1 and 0 if those keywords are omitted.
1240** iLimit and iOffset are the integer memory register numbers for
1241** counters used to compute the limit and offset. If there is no
1242** limit and/or offset, then iLimit and iOffset are negative.
1243**
1244** This routine changes the values if iLimit and iOffset only if
1245** a limit or offset is defined by nLimit and nOffset. iLimit and
1246** iOffset should have been preset to appropriate default values
1247** (usually but not always -1) prior to calling this routine.
1248** Only if nLimit>=0 or nOffset>0 do the limit registers get
1249** redefined. The UNION ALL operator uses this property to force
1250** the reuse of the same limit and offset registers across multiple
1251** SELECT statements.
1252*/
1253static void computeLimitRegisters(Parse *pParse, Select *p){
1254 /*
1255 ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
1256 ** all rows. It is the same as no limit. If the comparision is
1257 ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
1258 ** "LIMIT -1" always shows all rows. There is some
1259 ** contraversy about what the correct behavior should be.
1260 ** The current implementation interprets "LIMIT 0" to mean
1261 ** no rows.
1262 */
1263 if( p->nLimit>=0 ){
1264 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001265 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001266 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001267 sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
1268 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001269 p->iLimit = iMem;
1270 }
1271 if( p->nOffset>0 ){
1272 int iMem = pParse->nMem++;
danielk19774adee202004-05-08 08:23:19 +00001273 Vdbe *v = sqlite3GetVdbe(pParse);
drh7b58dae2003-07-20 01:16:46 +00001274 if( v==0 ) return;
danielk19774adee202004-05-08 08:23:19 +00001275 sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
1276 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
drh7b58dae2003-07-20 01:16:46 +00001277 p->iOffset = iMem;
1278 }
1279}
1280
1281/*
drh82c3d632000-06-06 21:56:07 +00001282** This routine is called to process a query that is really the union
1283** or intersection of two or more separate queries.
drhc926afb2002-06-20 03:38:26 +00001284**
drhe78e8282003-01-19 03:59:45 +00001285** "p" points to the right-most of the two queries. the query on the
1286** left is p->pPrior. The left query could also be a compound query
1287** in which case this routine will be called recursively.
1288**
1289** The results of the total query are to be written into a destination
1290** of type eDest with parameter iParm.
1291**
1292** Example 1: Consider a three-way compound SQL statement.
1293**
1294** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1295**
1296** This statement is parsed up as follows:
1297**
1298** SELECT c FROM t3
1299** |
1300** `-----> SELECT b FROM t2
1301** |
jplyon4b11c6d2004-01-19 04:57:53 +00001302** `------> SELECT a FROM t1
drhe78e8282003-01-19 03:59:45 +00001303**
1304** The arrows in the diagram above represent the Select.pPrior pointer.
1305** So if this routine is called with p equal to the t3 query, then
1306** pPrior will be the t2 query. p->op will be TK_UNION in this case.
1307**
1308** Notice that because of the way SQLite parses compound SELECTs, the
1309** individual selects always group from left to right.
drh82c3d632000-06-06 21:56:07 +00001310*/
danielk197784ac9d02004-05-18 09:58:06 +00001311static int multiSelect(
1312 Parse *pParse,
1313 Select *p,
1314 int eDest,
1315 int iParm,
1316 char *aff /* If eDest is SRT_Union, the affinity string */
1317){
1318 int rc = SQLITE_OK; /* Success code from a subroutine */
drh10e5e3c2000-06-08 00:19:02 +00001319 Select *pPrior; /* Another SELECT immediately to our left */
1320 Vdbe *v; /* Generate code to this VDBE */
danielk197784ac9d02004-05-18 09:58:06 +00001321 char *affStr = 0;
1322
1323 if( !aff ){
1324 int len;
1325 rc = fillInColumnList(pParse, p);
1326 if( rc!=SQLITE_OK ){
1327 goto multi_select_end;
1328 }
1329 len = p->pEList->nExpr+1;
1330 affStr = (char *)sqliteMalloc(p->pEList->nExpr+1);
1331 if( !affStr ){
1332 rc = SQLITE_NOMEM;
1333 goto multi_select_end;
1334 }
1335 memset(affStr, (int)SQLITE_AFF_NUMERIC, len-1);
1336 aff = affStr;
1337 }
drh82c3d632000-06-06 21:56:07 +00001338
drh7b58dae2003-07-20 01:16:46 +00001339 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
1340 ** the last SELECT in the series may have an ORDER BY or LIMIT.
drh82c3d632000-06-06 21:56:07 +00001341 */
danielk197784ac9d02004-05-18 09:58:06 +00001342 if( p==0 || p->pPrior==0 ){
1343 rc = 1;
1344 goto multi_select_end;
1345 }
drhd8bc7082000-06-07 23:51:50 +00001346 pPrior = p->pPrior;
1347 if( pPrior->pOrderBy ){
danielk19774adee202004-05-08 08:23:19 +00001348 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
drhda93d232003-03-31 02:12:46 +00001349 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001350 rc = 1;
1351 goto multi_select_end;
drh82c3d632000-06-06 21:56:07 +00001352 }
drh7b58dae2003-07-20 01:16:46 +00001353 if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
danielk19774adee202004-05-08 08:23:19 +00001354 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
drh7b58dae2003-07-20 01:16:46 +00001355 selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001356 rc = 1;
1357 goto multi_select_end;
drh7b58dae2003-07-20 01:16:46 +00001358 }
drh82c3d632000-06-06 21:56:07 +00001359
drhd8bc7082000-06-07 23:51:50 +00001360 /* Make sure we have a valid query engine. If not, create a new one.
1361 */
danielk19774adee202004-05-08 08:23:19 +00001362 v = sqlite3GetVdbe(pParse);
danielk197784ac9d02004-05-18 09:58:06 +00001363 if( v==0 ){
1364 rc = 1;
1365 goto multi_select_end;
1366 }
drhd8bc7082000-06-07 23:51:50 +00001367
drh1cc3d752002-03-23 00:31:29 +00001368 /* Create the destination temporary table if necessary
1369 */
1370 if( eDest==SRT_TempTable ){
danielk1977b4964b72004-05-18 01:23:38 +00001371 assert( p->pEList );
danielk19774adee202004-05-08 08:23:19 +00001372 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00001373 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, p->pEList->nExpr);
drh1cc3d752002-03-23 00:31:29 +00001374 eDest = SRT_Table;
1375 }
1376
drhf46f9052002-06-22 02:33:38 +00001377 /* Generate code for the left and right SELECT statements.
drhd8bc7082000-06-07 23:51:50 +00001378 */
drh82c3d632000-06-06 21:56:07 +00001379 switch( p->op ){
drhf46f9052002-06-22 02:33:38 +00001380 case TK_ALL: {
1381 if( p->pOrderBy==0 ){
drh7b58dae2003-07-20 01:16:46 +00001382 pPrior->nLimit = p->nLimit;
1383 pPrior->nOffset = p->nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001384 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
1385 if( rc ){
1386 goto multi_select_end;
1387 }
drhf46f9052002-06-22 02:33:38 +00001388 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001389 p->iLimit = pPrior->iLimit;
1390 p->iOffset = pPrior->iOffset;
1391 p->nLimit = -1;
1392 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001393 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
drhf46f9052002-06-22 02:33:38 +00001394 p->pPrior = pPrior;
danielk197784ac9d02004-05-18 09:58:06 +00001395 if( rc ){
1396 goto multi_select_end;
1397 }
drhf46f9052002-06-22 02:33:38 +00001398 break;
1399 }
1400 /* For UNION ALL ... ORDER BY fall through to the next case */
1401 }
drh82c3d632000-06-06 21:56:07 +00001402 case TK_EXCEPT:
1403 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +00001404 int unionTab; /* Cursor number of the temporary table holding result */
1405 int op; /* One of the SRT_ operations to apply to self */
1406 int priorOp; /* The SRT_ operation to apply to prior selects */
drh7b58dae2003-07-20 01:16:46 +00001407 int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
drhc926afb2002-06-20 03:38:26 +00001408 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
drh82c3d632000-06-06 21:56:07 +00001409
drhd8bc7082000-06-07 23:51:50 +00001410 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
drh7b58dae2003-07-20 01:16:46 +00001411 if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
drhd8bc7082000-06-07 23:51:50 +00001412 /* We can reuse a temporary table generated by a SELECT to our
drhc926afb2002-06-20 03:38:26 +00001413 ** right.
drhd8bc7082000-06-07 23:51:50 +00001414 */
drh82c3d632000-06-06 21:56:07 +00001415 unionTab = iParm;
1416 }else{
drhd8bc7082000-06-07 23:51:50 +00001417 /* We will need to create our own temporary table to hold the
1418 ** intermediate results.
1419 */
1420 unionTab = pParse->nTab++;
1421 if( p->pOrderBy
1422 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001423 rc = 1;
1424 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001425 }
drhd8bc7082000-06-07 23:51:50 +00001426 if( p->op!=TK_ALL ){
danielk19774adee202004-05-08 08:23:19 +00001427 sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 1);
1428 sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drh345fda32001-01-15 22:51:08 +00001429 }else{
danielk19774adee202004-05-08 08:23:19 +00001430 sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001431 }
danielk197784ac9d02004-05-18 09:58:06 +00001432 assert( p->pEList );
drh82c3d632000-06-06 21:56:07 +00001433 }
drhd8bc7082000-06-07 23:51:50 +00001434
1435 /* Code the SELECT statements to our left
1436 */
danielk197784ac9d02004-05-18 09:58:06 +00001437 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
1438 if( rc ){
1439 goto multi_select_end;
1440 }
1441 if( p->op==TK_ALL ){
1442 sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, pPrior->pEList->nExpr);
1443 }
drhd8bc7082000-06-07 23:51:50 +00001444
1445 /* Code the current SELECT statement
1446 */
1447 switch( p->op ){
1448 case TK_EXCEPT: op = SRT_Except; break;
1449 case TK_UNION: op = SRT_Union; break;
1450 case TK_ALL: op = SRT_Table; break;
1451 }
drh82c3d632000-06-06 21:56:07 +00001452 p->pPrior = 0;
drhc926afb2002-06-20 03:38:26 +00001453 pOrderBy = p->pOrderBy;
1454 p->pOrderBy = 0;
drh7b58dae2003-07-20 01:16:46 +00001455 nLimit = p->nLimit;
1456 p->nLimit = -1;
1457 nOffset = p->nOffset;
1458 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001459 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001460 p->pPrior = pPrior;
drhc926afb2002-06-20 03:38:26 +00001461 p->pOrderBy = pOrderBy;
drh7b58dae2003-07-20 01:16:46 +00001462 p->nLimit = nLimit;
1463 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001464 if( rc ){
1465 goto multi_select_end;
1466 }
1467
drhd8bc7082000-06-07 23:51:50 +00001468
1469 /* Convert the data in the temporary table into whatever form
1470 ** it is that we currently need.
1471 */
drhc926afb2002-06-20 03:38:26 +00001472 if( eDest!=priorOp || unionTab!=iParm ){
drh6b563442001-11-07 16:48:26 +00001473 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +00001474 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001475 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001476 generateColumnNames(pParse, 0, p->pEList);
1477 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001478 }
danielk19774adee202004-05-08 08:23:19 +00001479 iBreak = sqlite3VdbeMakeLabel(v);
1480 iCont = sqlite3VdbeMakeLabel(v);
1481 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001482 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001483 iStart = sqlite3VdbeCurrentAddr(v);
drhfcb78a42003-01-18 20:11:05 +00001484 multiSelectSortOrder(p, p->pOrderBy);
drh38640e12002-07-05 21:42:36 +00001485 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001486 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001487 iCont, iBreak, 0);
1488 if( rc ){
1489 rc = 1;
1490 goto multi_select_end;
1491 }
danielk19774adee202004-05-08 08:23:19 +00001492 sqlite3VdbeResolveLabel(v, iCont);
1493 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
1494 sqlite3VdbeResolveLabel(v, iBreak);
1495 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +00001496 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001497 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001498 }
drh82c3d632000-06-06 21:56:07 +00001499 }
1500 break;
1501 }
1502 case TK_INTERSECT: {
1503 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +00001504 int iCont, iBreak, iStart;
drh7b58dae2003-07-20 01:16:46 +00001505 int nLimit, nOffset;
drh82c3d632000-06-06 21:56:07 +00001506
drhd8bc7082000-06-07 23:51:50 +00001507 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +00001508 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +00001509 ** by allocating the tables we will need.
1510 */
drh82c3d632000-06-06 21:56:07 +00001511 tab1 = pParse->nTab++;
1512 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +00001513 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
danielk197784ac9d02004-05-18 09:58:06 +00001514 rc = 1;
1515 goto multi_select_end;
drhd8bc7082000-06-07 23:51:50 +00001516 }
danielk19774adee202004-05-08 08:23:19 +00001517 sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 1);
1518 sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
danielk197784ac9d02004-05-18 09:58:06 +00001519 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +00001520
1521 /* Code the SELECTs to our left into temporary table "tab1".
1522 */
danielk197784ac9d02004-05-18 09:58:06 +00001523 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
1524 if( rc ){
1525 goto multi_select_end;
1526 }
drhd8bc7082000-06-07 23:51:50 +00001527
1528 /* Code the current SELECT into temporary table "tab2"
1529 */
danielk19774adee202004-05-08 08:23:19 +00001530 sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 1);
1531 sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh82c3d632000-06-06 21:56:07 +00001532 p->pPrior = 0;
drh7b58dae2003-07-20 01:16:46 +00001533 nLimit = p->nLimit;
1534 p->nLimit = -1;
1535 nOffset = p->nOffset;
1536 p->nOffset = 0;
danielk197784ac9d02004-05-18 09:58:06 +00001537 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
drh82c3d632000-06-06 21:56:07 +00001538 p->pPrior = pPrior;
drh7b58dae2003-07-20 01:16:46 +00001539 p->nLimit = nLimit;
1540 p->nOffset = nOffset;
danielk197784ac9d02004-05-18 09:58:06 +00001541 if( rc ){
1542 goto multi_select_end;
1543 }
drhd8bc7082000-06-07 23:51:50 +00001544
1545 /* Generate code to take the intersection of the two temporary
1546 ** tables.
1547 */
drh82c3d632000-06-06 21:56:07 +00001548 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +00001549 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001550 generateColumnNames(pParse, 0, p->pEList);
1551 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh41202cc2002-04-23 17:10:18 +00001552 }
danielk19774adee202004-05-08 08:23:19 +00001553 iBreak = sqlite3VdbeMakeLabel(v);
1554 iCont = sqlite3VdbeMakeLabel(v);
1555 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
drh7b58dae2003-07-20 01:16:46 +00001556 computeLimitRegisters(pParse, p);
danielk19774adee202004-05-08 08:23:19 +00001557 iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
1558 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
drhfcb78a42003-01-18 20:11:05 +00001559 multiSelectSortOrder(p, p->pOrderBy);
drh38640e12002-07-05 21:42:36 +00001560 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +00001561 p->pOrderBy, -1, eDest, iParm,
danielk197784ac9d02004-05-18 09:58:06 +00001562 iCont, iBreak, 0);
1563 if( rc ){
1564 rc = 1;
1565 goto multi_select_end;
1566 }
danielk19774adee202004-05-08 08:23:19 +00001567 sqlite3VdbeResolveLabel(v, iCont);
1568 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
1569 sqlite3VdbeResolveLabel(v, iBreak);
1570 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
1571 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
drhd8bc7082000-06-07 23:51:50 +00001572 if( p->pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00001573 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
drhd8bc7082000-06-07 23:51:50 +00001574 }
drh82c3d632000-06-06 21:56:07 +00001575 break;
1576 }
1577 }
1578 assert( p->pEList && pPrior->pEList );
1579 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001580 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
drhda93d232003-03-31 02:12:46 +00001581 " do not have the same number of result columns", selectOpName(p->op));
danielk197784ac9d02004-05-18 09:58:06 +00001582 rc = 1;
1583 goto multi_select_end;
drh22827922000-06-06 17:27:05 +00001584 }
danielk197784ac9d02004-05-18 09:58:06 +00001585
1586multi_select_end:
1587 if( affStr ){
1588 if( rc!=SQLITE_OK ){
1589 sqliteFree(affStr);
1590 }else{
1591 multiSelectAffinity(p, affStr);
1592 sqlite3VdbeOp3(v, OP_Noop, 0, 0, affStr, P3_DYNAMIC);
1593 }
1594 }
1595 return rc;
drh22827922000-06-06 17:27:05 +00001596}
1597
1598/*
drh832508b2002-03-02 17:04:07 +00001599** Scan through the expression pExpr. Replace every reference to
drh6a3ea0e2003-05-02 14:32:12 +00001600** a column in table number iTable with a copy of the iColumn-th
drh84e59202002-03-14 14:33:31 +00001601** entry in pEList. (But leave references to the ROWID column
drh6a3ea0e2003-05-02 14:32:12 +00001602** unchanged.)
drh832508b2002-03-02 17:04:07 +00001603**
1604** This routine is part of the flattening procedure. A subquery
1605** whose result set is defined by pEList appears as entry in the
1606** FROM clause of a SELECT such that the VDBE cursor assigned to that
1607** FORM clause entry is iTable. This routine make the necessary
1608** changes to pExpr so that it refers directly to the source table
1609** of the subquery rather the result set of the subquery.
1610*/
drh6a3ea0e2003-05-02 14:32:12 +00001611static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
1612static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001613 if( pExpr==0 ) return;
drh50350a12004-02-13 16:22:22 +00001614 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1615 if( pExpr->iColumn<0 ){
1616 pExpr->op = TK_NULL;
1617 }else{
1618 Expr *pNew;
1619 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1620 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1621 pNew = pEList->a[pExpr->iColumn].pExpr;
1622 assert( pNew!=0 );
1623 pExpr->op = pNew->op;
1624 pExpr->dataType = pNew->dataType;
1625 assert( pExpr->pLeft==0 );
danielk19774adee202004-05-08 08:23:19 +00001626 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
drh50350a12004-02-13 16:22:22 +00001627 assert( pExpr->pRight==0 );
danielk19774adee202004-05-08 08:23:19 +00001628 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
drh50350a12004-02-13 16:22:22 +00001629 assert( pExpr->pList==0 );
danielk19774adee202004-05-08 08:23:19 +00001630 pExpr->pList = sqlite3ExprListDup(pNew->pList);
drh50350a12004-02-13 16:22:22 +00001631 pExpr->iTable = pNew->iTable;
1632 pExpr->iColumn = pNew->iColumn;
1633 pExpr->iAgg = pNew->iAgg;
danielk19774adee202004-05-08 08:23:19 +00001634 sqlite3TokenCopy(&pExpr->token, &pNew->token);
1635 sqlite3TokenCopy(&pExpr->span, &pNew->span);
drh50350a12004-02-13 16:22:22 +00001636 }
drh832508b2002-03-02 17:04:07 +00001637 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001638 substExpr(pExpr->pLeft, iTable, pEList);
1639 substExpr(pExpr->pRight, iTable, pEList);
1640 substExprList(pExpr->pList, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001641 }
1642}
1643static void
drh6a3ea0e2003-05-02 14:32:12 +00001644substExprList(ExprList *pList, int iTable, ExprList *pEList){
drh832508b2002-03-02 17:04:07 +00001645 int i;
1646 if( pList==0 ) return;
1647 for(i=0; i<pList->nExpr; i++){
drh6a3ea0e2003-05-02 14:32:12 +00001648 substExpr(pList->a[i].pExpr, iTable, pEList);
drh832508b2002-03-02 17:04:07 +00001649 }
1650}
1651
1652/*
drh1350b032002-02-27 19:00:20 +00001653** This routine attempts to flatten subqueries in order to speed
1654** execution. It returns 1 if it makes changes and 0 if no flattening
1655** occurs.
1656**
1657** To understand the concept of flattening, consider the following
1658** query:
1659**
1660** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1661**
1662** The default way of implementing this query is to execute the
1663** subquery first and store the results in a temporary table, then
1664** run the outer query on that temporary table. This requires two
1665** passes over the data. Furthermore, because the temporary table
1666** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +00001667** optimized.
drh1350b032002-02-27 19:00:20 +00001668**
drh832508b2002-03-02 17:04:07 +00001669** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +00001670** a single flat select, like this:
1671**
1672** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1673**
1674** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +00001675** but only has to scan the data once. And because indices might
1676** exist on the table t1, a complete scan of the data might be
1677** avoided.
drh1350b032002-02-27 19:00:20 +00001678**
drh832508b2002-03-02 17:04:07 +00001679** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +00001680**
drh832508b2002-03-02 17:04:07 +00001681** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +00001682**
drh832508b2002-03-02 17:04:07 +00001683** (2) The subquery is not an aggregate or the outer query is not a join.
1684**
drh8af4d3a2003-05-06 20:35:16 +00001685** (3) The subquery is not the right operand of a left outer join, or
1686** the subquery is not itself a join. (Ticket #306)
drh832508b2002-03-02 17:04:07 +00001687**
1688** (4) The subquery is not DISTINCT or the outer query is not a join.
1689**
1690** (5) The subquery is not DISTINCT or the outer query does not use
1691** aggregates.
1692**
1693** (6) The subquery does not use aggregates or the outer query is not
1694** DISTINCT.
1695**
drh08192d52002-04-30 19:20:28 +00001696** (7) The subquery has a FROM clause.
1697**
drhdf199a22002-06-14 22:38:41 +00001698** (8) The subquery does not use LIMIT or the outer query is not a join.
1699**
1700** (9) The subquery does not use LIMIT or the outer query does not use
1701** aggregates.
1702**
1703** (10) The subquery does not use aggregates or the outer query does not
1704** use LIMIT.
1705**
drh174b6192002-12-03 02:22:52 +00001706** (11) The subquery and the outer query do not both have ORDER BY clauses.
1707**
drh3fc673e2003-06-16 00:40:34 +00001708** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
1709** subquery has no WHERE clause. (added by ticket #350)
1710**
drh832508b2002-03-02 17:04:07 +00001711** In this routine, the "p" parameter is a pointer to the outer query.
1712** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
1713** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1714**
drh665de472003-03-31 13:36:09 +00001715** If flattening is not attempted, this routine is a no-op and returns 0.
drh832508b2002-03-02 17:04:07 +00001716** If flattening is attempted this routine returns 1.
1717**
1718** All of the expression analysis must occur on both the outer query and
1719** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +00001720*/
drh8c74a8c2002-08-25 19:20:40 +00001721static int flattenSubquery(
1722 Parse *pParse, /* The parsing context */
1723 Select *p, /* The parent or outer SELECT statement */
1724 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
1725 int isAgg, /* True if outer SELECT uses aggregate functions */
1726 int subqueryIsAgg /* True if the subquery uses aggregate functions */
1727){
drh0bb28102002-05-08 11:54:14 +00001728 Select *pSub; /* The inner query or "subquery" */
drhad3cab52002-05-24 02:04:32 +00001729 SrcList *pSrc; /* The FROM clause of the outer query */
1730 SrcList *pSubSrc; /* The FROM clause of the subquery */
drh0bb28102002-05-08 11:54:14 +00001731 ExprList *pList; /* The result set of the outer query */
drh6a3ea0e2003-05-02 14:32:12 +00001732 int iParent; /* VDBE cursor number of the pSub result set temp table */
drh832508b2002-03-02 17:04:07 +00001733 int i;
drh832508b2002-03-02 17:04:07 +00001734 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +00001735
drh832508b2002-03-02 17:04:07 +00001736 /* Check to see if flattening is permitted. Return 0 if not.
1737 */
1738 if( p==0 ) return 0;
1739 pSrc = p->pSrc;
drhad3cab52002-05-24 02:04:32 +00001740 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
drh832508b2002-03-02 17:04:07 +00001741 pSub = pSrc->a[iFrom].pSelect;
1742 assert( pSub!=0 );
1743 if( isAgg && subqueryIsAgg ) return 0;
drhad3cab52002-05-24 02:04:32 +00001744 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
drh832508b2002-03-02 17:04:07 +00001745 pSubSrc = pSub->pSrc;
1746 assert( pSubSrc );
drhc31c2eb2003-05-02 16:04:17 +00001747 if( pSubSrc->nSrc==0 ) return 0;
drhdf199a22002-06-14 22:38:41 +00001748 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
1749 return 0;
1750 }
drhd11d3822002-06-21 23:01:49 +00001751 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
drh174b6192002-12-03 02:22:52 +00001752 if( p->pOrderBy && pSub->pOrderBy ) return 0;
drh832508b2002-03-02 17:04:07 +00001753
drh8af4d3a2003-05-06 20:35:16 +00001754 /* Restriction 3: If the subquery is a join, make sure the subquery is
1755 ** not used as the right operand of an outer join. Examples of why this
1756 ** is not allowed:
1757 **
1758 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
1759 **
1760 ** If we flatten the above, we would get
1761 **
1762 ** (t1 LEFT OUTER JOIN t2) JOIN t3
1763 **
1764 ** which is not at all the same thing.
1765 */
1766 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
1767 return 0;
1768 }
1769
drh3fc673e2003-06-16 00:40:34 +00001770 /* Restriction 12: If the subquery is the right operand of a left outer
1771 ** join, make sure the subquery has no WHERE clause.
1772 ** An examples of why this is not allowed:
1773 **
1774 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1775 **
1776 ** If we flatten the above, we would get
1777 **
1778 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1779 **
1780 ** But the t2.x>0 test will always fail on a NULL row of t2, which
1781 ** effectively converts the OUTER JOIN into an INNER JOIN.
1782 */
1783 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
1784 && pSub->pWhere!=0 ){
1785 return 0;
1786 }
1787
drh0bb28102002-05-08 11:54:14 +00001788 /* If we reach this point, it means flattening is permitted for the
drh63eb5f22003-04-29 16:20:44 +00001789 ** iFrom-th entry of the FROM clause in the outer query.
drh832508b2002-03-02 17:04:07 +00001790 */
drhc31c2eb2003-05-02 16:04:17 +00001791
1792 /* Move all of the FROM elements of the subquery into the
1793 ** the FROM clause of the outer query. Before doing this, remember
1794 ** the cursor number for the original outer query FROM element in
1795 ** iParent. The iParent cursor will never be used. Subsequent code
1796 ** will scan expressions looking for iParent references and replace
1797 ** those references with expressions that resolve to the subquery FROM
1798 ** elements we are now copying in.
1799 */
drh6a3ea0e2003-05-02 14:32:12 +00001800 iParent = pSrc->a[iFrom].iCursor;
drhc31c2eb2003-05-02 16:04:17 +00001801 {
1802 int nSubSrc = pSubSrc->nSrc;
drh8af4d3a2003-05-06 20:35:16 +00001803 int jointype = pSrc->a[iFrom].jointype;
drhc31c2eb2003-05-02 16:04:17 +00001804
1805 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
danielk19774adee202004-05-08 08:23:19 +00001806 sqlite3DeleteTable(0, pSrc->a[iFrom].pTab);
drhc31c2eb2003-05-02 16:04:17 +00001807 }
drhf26e09c2003-05-31 16:21:12 +00001808 sqliteFree(pSrc->a[iFrom].zDatabase);
drhc31c2eb2003-05-02 16:04:17 +00001809 sqliteFree(pSrc->a[iFrom].zName);
1810 sqliteFree(pSrc->a[iFrom].zAlias);
1811 if( nSubSrc>1 ){
1812 int extra = nSubSrc - 1;
1813 for(i=1; i<nSubSrc; i++){
danielk19774adee202004-05-08 08:23:19 +00001814 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
drhc31c2eb2003-05-02 16:04:17 +00001815 }
1816 p->pSrc = pSrc;
1817 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1818 pSrc->a[i] = pSrc->a[i-extra];
1819 }
1820 }
1821 for(i=0; i<nSubSrc; i++){
1822 pSrc->a[i+iFrom] = pSubSrc->a[i];
1823 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1824 }
drh8af4d3a2003-05-06 20:35:16 +00001825 pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
drhc31c2eb2003-05-02 16:04:17 +00001826 }
1827
1828 /* Now begin substituting subquery result set expressions for
1829 ** references to the iParent in the outer query.
1830 **
1831 ** Example:
1832 **
1833 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1834 ** \ \_____________ subquery __________/ /
1835 ** \_____________________ outer query ______________________________/
1836 **
1837 ** We look at every expression in the outer query and every place we see
1838 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1839 */
drh6a3ea0e2003-05-02 14:32:12 +00001840 substExprList(p->pEList, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001841 pList = p->pEList;
1842 for(i=0; i<pList->nExpr; i++){
drh6977fea2002-10-22 23:38:04 +00001843 Expr *pExpr;
1844 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
1845 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
drh832508b2002-03-02 17:04:07 +00001846 }
1847 }
drh1b2e0322002-03-03 02:49:51 +00001848 if( isAgg ){
drh6a3ea0e2003-05-02 14:32:12 +00001849 substExprList(p->pGroupBy, iParent, pSub->pEList);
1850 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001851 }
drh174b6192002-12-03 02:22:52 +00001852 if( pSub->pOrderBy ){
1853 assert( p->pOrderBy==0 );
1854 p->pOrderBy = pSub->pOrderBy;
1855 pSub->pOrderBy = 0;
drh174b6192002-12-03 02:22:52 +00001856 }else if( p->pOrderBy ){
drh6a3ea0e2003-05-02 14:32:12 +00001857 substExprList(p->pOrderBy, iParent, pSub->pEList);
drh174b6192002-12-03 02:22:52 +00001858 }
drh832508b2002-03-02 17:04:07 +00001859 if( pSub->pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001860 pWhere = sqlite3ExprDup(pSub->pWhere);
drh832508b2002-03-02 17:04:07 +00001861 }else{
1862 pWhere = 0;
1863 }
1864 if( subqueryIsAgg ){
1865 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +00001866 p->pHaving = p->pWhere;
1867 p->pWhere = pWhere;
drh6a3ea0e2003-05-02 14:32:12 +00001868 substExpr(p->pHaving, iParent, pSub->pEList);
drh1b2e0322002-03-03 02:49:51 +00001869 if( pSub->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001870 Expr *pHaving = sqlite3ExprDup(pSub->pHaving);
drh1b2e0322002-03-03 02:49:51 +00001871 if( p->pHaving ){
danielk19774adee202004-05-08 08:23:19 +00001872 p->pHaving = sqlite3Expr(TK_AND, p->pHaving, pHaving, 0);
drh1b2e0322002-03-03 02:49:51 +00001873 }else{
1874 p->pHaving = pHaving;
1875 }
1876 }
1877 assert( p->pGroupBy==0 );
danielk19774adee202004-05-08 08:23:19 +00001878 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
drh832508b2002-03-02 17:04:07 +00001879 }else if( p->pWhere==0 ){
1880 p->pWhere = pWhere;
1881 }else{
drh6a3ea0e2003-05-02 14:32:12 +00001882 substExpr(p->pWhere, iParent, pSub->pEList);
drh832508b2002-03-02 17:04:07 +00001883 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00001884 p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pWhere, 0);
drh832508b2002-03-02 17:04:07 +00001885 }
1886 }
drhc31c2eb2003-05-02 16:04:17 +00001887
1888 /* The flattened query is distinct if either the inner or the
1889 ** outer query is distinct.
1890 */
drh832508b2002-03-02 17:04:07 +00001891 p->isDistinct = p->isDistinct || pSub->isDistinct;
drh8c74a8c2002-08-25 19:20:40 +00001892
drhc31c2eb2003-05-02 16:04:17 +00001893 /* Transfer the limit expression from the subquery to the outer
1894 ** query.
1895 */
drhdf199a22002-06-14 22:38:41 +00001896 if( pSub->nLimit>=0 ){
1897 if( p->nLimit<0 ){
1898 p->nLimit = pSub->nLimit;
1899 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
1900 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
1901 }
1902 }
1903 p->nOffset += pSub->nOffset;
drh8c74a8c2002-08-25 19:20:40 +00001904
drhc31c2eb2003-05-02 16:04:17 +00001905 /* Finially, delete what is left of the subquery and return
1906 ** success.
1907 */
danielk19774adee202004-05-08 08:23:19 +00001908 sqlite3SelectDelete(pSub);
drh832508b2002-03-02 17:04:07 +00001909 return 1;
1910}
drh1350b032002-02-27 19:00:20 +00001911
1912/*
drh9562b552002-02-19 15:00:07 +00001913** Analyze the SELECT statement passed in as an argument to see if it
1914** is a simple min() or max() query. If it is and this query can be
1915** satisfied using a single seek to the beginning or end of an index,
drhe78e8282003-01-19 03:59:45 +00001916** then generate the code for this SELECT and return 1. If this is not a
drh9562b552002-02-19 15:00:07 +00001917** simple min() or max() query, then return 0;
1918**
1919** A simply min() or max() query looks like this:
1920**
1921** SELECT min(a) FROM table;
1922** SELECT max(a) FROM table;
1923**
1924** The query may have only a single table in its FROM argument. There
1925** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1926** be the min() or max() of a single column of the table. The column
1927** in the min() or max() function must be indexed.
1928**
danielk19774adee202004-05-08 08:23:19 +00001929** The parameters to this routine are the same as for sqlite3Select().
drh9562b552002-02-19 15:00:07 +00001930** See the header comment on that routine for additional information.
1931*/
1932static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1933 Expr *pExpr;
1934 int iCol;
1935 Table *pTab;
1936 Index *pIdx;
1937 int base;
1938 Vdbe *v;
drh9562b552002-02-19 15:00:07 +00001939 int seekOp;
1940 int cont;
drh6e175292004-03-13 14:00:36 +00001941 ExprList *pEList, *pList, eList;
drh9562b552002-02-19 15:00:07 +00001942 struct ExprList_item eListItem;
drh6e175292004-03-13 14:00:36 +00001943 SrcList *pSrc;
1944
drh9562b552002-02-19 15:00:07 +00001945
1946 /* Check to see if this query is a simple min() or max() query. Return
1947 ** zero if it is not.
1948 */
1949 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
drh6e175292004-03-13 14:00:36 +00001950 pSrc = p->pSrc;
1951 if( pSrc->nSrc!=1 ) return 0;
1952 pEList = p->pEList;
1953 if( pEList->nExpr!=1 ) return 0;
1954 pExpr = pEList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00001955 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
drh6e175292004-03-13 14:00:36 +00001956 pList = pExpr->pList;
1957 if( pList==0 || pList->nExpr!=1 ) return 0;
drh6977fea2002-10-22 23:38:04 +00001958 if( pExpr->token.n!=3 ) return 0;
danielk19774adee202004-05-08 08:23:19 +00001959 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00001960 seekOp = OP_Rewind;
danielk19774adee202004-05-08 08:23:19 +00001961 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
drh0bce8352002-02-28 00:41:10 +00001962 seekOp = OP_Last;
1963 }else{
1964 return 0;
1965 }
drh6e175292004-03-13 14:00:36 +00001966 pExpr = pList->a[0].pExpr;
drh9562b552002-02-19 15:00:07 +00001967 if( pExpr->op!=TK_COLUMN ) return 0;
1968 iCol = pExpr->iColumn;
drh6e175292004-03-13 14:00:36 +00001969 pTab = pSrc->a[0].pTab;
drh9562b552002-02-19 15:00:07 +00001970
1971 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00001972 ** Check to make sure we have an index and make pIdx point to the
1973 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
1974 ** key column, no index is necessary so set pIdx to NULL. If no
1975 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00001976 */
1977 if( iCol<0 ){
1978 pIdx = 0;
1979 }else{
1980 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1981 assert( pIdx->nColumn>=1 );
1982 if( pIdx->aiColumn[0]==iCol ) break;
1983 }
1984 if( pIdx==0 ) return 0;
1985 }
1986
drhe5f50722003-07-19 00:44:14 +00001987 /* Identify column types if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00001988 ** step is skipped if the output is going to a table or a memory cell.
drhe5f50722003-07-19 00:44:14 +00001989 ** The column names have already been generated in the calling function.
drh9562b552002-02-19 15:00:07 +00001990 */
danielk19774adee202004-05-08 08:23:19 +00001991 v = sqlite3GetVdbe(pParse);
drh9562b552002-02-19 15:00:07 +00001992 if( v==0 ) return 0;
1993 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00001994 generateColumnTypes(pParse, p->pSrc, p->pEList);
drh9562b552002-02-19 15:00:07 +00001995 }
1996
drh0c37e632004-01-30 02:01:03 +00001997 /* If the output is destined for a temporary table, open that table.
1998 */
1999 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002000 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002001 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
drh0c37e632004-01-30 02:01:03 +00002002 }
2003
drh17f71932002-02-21 12:01:27 +00002004 /* Generating code to find the min or the max. Basically all we have
2005 ** to do is find the first or the last entry in the chosen index. If
2006 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
2007 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00002008 */
danielk19774adee202004-05-08 08:23:19 +00002009 sqlite3CodeVerifySchema(pParse, pTab->iDb);
drh6e175292004-03-13 14:00:36 +00002010 base = pSrc->a[0].iCursor;
drh7b58dae2003-07-20 01:16:46 +00002011 computeLimitRegisters(pParse, p);
drh6e175292004-03-13 14:00:36 +00002012 if( pSrc->a[0].pSelect==0 ){
danielk19774adee202004-05-08 08:23:19 +00002013 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
2014 sqlite3VdbeOp3(v, OP_OpenRead, base, pTab->tnum, pTab->zName, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002015 sqlite3VdbeAddOp(v, OP_SetNumColumns, base, pTab->nCol);
drh6e175292004-03-13 14:00:36 +00002016 }
danielk19774adee202004-05-08 08:23:19 +00002017 cont = sqlite3VdbeMakeLabel(v);
drh9562b552002-02-19 15:00:07 +00002018 if( pIdx==0 ){
danielk19774adee202004-05-08 08:23:19 +00002019 sqlite3VdbeAddOp(v, seekOp, base, 0);
drh9562b552002-02-19 15:00:07 +00002020 }else{
danielk19774adee202004-05-08 08:23:19 +00002021 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
2022 sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum, pIdx->zName, P3_STATIC);
2023 sqlite3VdbeAddOp(v, seekOp, base+1, 0);
2024 sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
2025 sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
2026 sqlite3VdbeAddOp(v, OP_MoveTo, base, 0);
drh9562b552002-02-19 15:00:07 +00002027 }
drh5cf8e8c2002-02-19 22:42:05 +00002028 eList.nExpr = 1;
2029 memset(&eListItem, 0, sizeof(eListItem));
2030 eList.a = &eListItem;
2031 eList.a[0].pExpr = pExpr;
danielk197784ac9d02004-05-18 09:58:06 +00002032 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
danielk19774adee202004-05-08 08:23:19 +00002033 sqlite3VdbeResolveLabel(v, cont);
2034 sqlite3VdbeAddOp(v, OP_Close, base, 0);
drh6e175292004-03-13 14:00:36 +00002035
drh9562b552002-02-19 15:00:07 +00002036 return 1;
2037}
2038
2039/*
drh9bb61fe2000-06-05 16:01:39 +00002040** Generate code for the given SELECT statement.
2041**
drhfef52082000-06-06 01:50:43 +00002042** The results are distributed in various ways depending on the
2043** value of eDest and iParm.
2044**
2045** eDest Value Result
2046** ------------ -------------------------------------------
2047** SRT_Callback Invoke the callback for each row of the result.
2048**
2049** SRT_Mem Store first result in memory cell iParm
2050**
danielk1977e014a832004-05-17 10:48:57 +00002051** SRT_Set Store results as keys of table iParm.
drhfef52082000-06-06 01:50:43 +00002052**
drh82c3d632000-06-06 21:56:07 +00002053** SRT_Union Store results as a key in a temporary table iParm
2054**
jplyon4b11c6d2004-01-19 04:57:53 +00002055** SRT_Except Remove results from the temporary table iParm.
drhc4a3c772001-04-04 11:48:57 +00002056**
2057** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00002058**
drhe78e8282003-01-19 03:59:45 +00002059** The table above is incomplete. Additional eDist value have be added
2060** since this comment was written. See the selectInnerLoop() function for
2061** a complete listing of the allowed values of eDest and their meanings.
2062**
drh9bb61fe2000-06-05 16:01:39 +00002063** This routine returns the number of errors. If any errors are
2064** encountered, then an appropriate error message is left in
2065** pParse->zErrMsg.
2066**
2067** This routine does NOT free the Select structure passed in. The
2068** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00002069**
2070** The pParent, parentTab, and *pParentAgg fields are filled in if this
2071** SELECT is a subquery. This routine may try to combine this SELECT
2072** with its parent to form a single flat query. In so doing, it might
2073** change the parent query from a non-aggregate to an aggregate query.
2074** For that reason, the pParentAgg flag is passed as a pointer, so it
2075** can be changed.
drhe78e8282003-01-19 03:59:45 +00002076**
2077** Example 1: The meaning of the pParent parameter.
2078**
2079** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2080** \ \_______ subquery _______/ /
2081** \ /
2082** \____________________ outer query ___________________/
2083**
2084** This routine is called for the outer query first. For that call,
2085** pParent will be NULL. During the processing of the outer query, this
2086** routine is called recursively to handle the subquery. For the recursive
2087** call, pParent will point to the outer query. Because the subquery is
2088** the second element in a three-way join, the parentTab parameter will
2089** be 1 (the 2nd value of a 0-indexed array.)
drh9bb61fe2000-06-05 16:01:39 +00002090*/
danielk19774adee202004-05-08 08:23:19 +00002091int sqlite3Select(
drhcce7d172000-05-31 15:34:51 +00002092 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00002093 Select *p, /* The SELECT statement being coded. */
drhe78e8282003-01-19 03:59:45 +00002094 int eDest, /* How to dispose of the results */
2095 int iParm, /* A parameter used by the eDest disposal method */
drh832508b2002-03-02 17:04:07 +00002096 Select *pParent, /* Another SELECT for which this is a sub-query */
2097 int parentTab, /* Index in pParent->pSrc of this query */
danielk197784ac9d02004-05-18 09:58:06 +00002098 int *pParentAgg, /* True if pParent uses aggregate functions */
2099 char *aff /* If eDest is SRT_Union, the affinity string */
drhcce7d172000-05-31 15:34:51 +00002100){
drhd8bc7082000-06-07 23:51:50 +00002101 int i;
drhcce7d172000-05-31 15:34:51 +00002102 WhereInfo *pWInfo;
2103 Vdbe *v;
2104 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00002105 ExprList *pEList; /* List of columns to extract. */
drhad3cab52002-05-24 02:04:32 +00002106 SrcList *pTabList; /* List of tables to select from */
drh9bb61fe2000-06-05 16:01:39 +00002107 Expr *pWhere; /* The WHERE clause. May be NULL */
2108 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00002109 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
2110 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00002111 int isDistinct; /* True if the DISTINCT keyword is present */
2112 int distinct; /* Table to use for the distinct set */
drh1d83f052002-02-17 00:30:36 +00002113 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00002114
danielk19776f8a5032004-05-10 10:34:51 +00002115 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
danielk19774adee202004-05-08 08:23:19 +00002116 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
drhdaffd0e2001-04-11 14:28:42 +00002117
drh82c3d632000-06-06 21:56:07 +00002118 /* If there is are a sequence of queries, do the earlier ones first.
2119 */
2120 if( p->pPrior ){
danielk197784ac9d02004-05-18 09:58:06 +00002121 return multiSelect(pParse, p, eDest, iParm, aff);
drh82c3d632000-06-06 21:56:07 +00002122 }
2123
2124 /* Make local copies of the parameters for this query.
2125 */
drh9bb61fe2000-06-05 16:01:39 +00002126 pTabList = p->pSrc;
2127 pWhere = p->pWhere;
2128 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00002129 pGroupBy = p->pGroupBy;
2130 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00002131 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00002132
drh6a3ea0e2003-05-02 14:32:12 +00002133 /* Allocate VDBE cursors for each table in the FROM clause
drh10e5e3c2000-06-08 00:19:02 +00002134 */
danielk19774adee202004-05-08 08:23:19 +00002135 sqlite3SrcListAssignCursors(pParse, pTabList);
drh10e5e3c2000-06-08 00:19:02 +00002136
drh9bb61fe2000-06-05 16:01:39 +00002137 /*
2138 ** Do not even attempt to generate any code if we have already seen
2139 ** errors before this routine starts.
2140 */
drh1d83f052002-02-17 00:30:36 +00002141 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002142
drhe78e8282003-01-19 03:59:45 +00002143 /* Expand any "*" terms in the result set. (For example the "*" in
2144 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
2145 ** other housekeeping - see the header comment for details.
drhcce7d172000-05-31 15:34:51 +00002146 */
drhd8bc7082000-06-07 23:51:50 +00002147 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00002148 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002149 }
drhad2d8302002-05-24 20:31:36 +00002150 pWhere = p->pWhere;
drhd8bc7082000-06-07 23:51:50 +00002151 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00002152 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002153
drh22827922000-06-06 17:27:05 +00002154 /* If writing to memory or generating a set
2155 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00002156 */
drhfef52082000-06-06 01:50:43 +00002157 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
danielk19774adee202004-05-08 08:23:19 +00002158 sqlite3ErrorMsg(pParse, "only a single result allowed for "
drhda93d232003-03-31 02:12:46 +00002159 "a SELECT that is part of an expression");
drh1d83f052002-02-17 00:30:36 +00002160 goto select_end;
drh19a775c2000-06-05 18:54:46 +00002161 }
2162
drhc926afb2002-06-20 03:38:26 +00002163 /* ORDER BY is ignored for some destinations.
drh22827922000-06-06 17:27:05 +00002164 */
drhc926afb2002-06-20 03:38:26 +00002165 switch( eDest ){
2166 case SRT_Union:
2167 case SRT_Except:
2168 case SRT_Discard:
2169 pOrderBy = 0;
2170 break;
2171 default:
2172 break;
drh22827922000-06-06 17:27:05 +00002173 }
2174
drh10e5e3c2000-06-08 00:19:02 +00002175 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00002176 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00002177 **
drh967e8b72000-06-21 13:59:10 +00002178 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00002179 */
drh4794b982000-06-06 13:54:14 +00002180 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002181 if( sqlite3ExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002182 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002183 }
danielk19774adee202004-05-08 08:23:19 +00002184 if( sqlite3ExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00002185 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002186 }
2187 }
drhcce7d172000-05-31 15:34:51 +00002188 if( pWhere ){
danielk19774adee202004-05-08 08:23:19 +00002189 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00002190 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002191 }
danielk19774adee202004-05-08 08:23:19 +00002192 if( sqlite3ExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00002193 goto select_end;
drhcce7d172000-05-31 15:34:51 +00002194 }
2195 }
drhc66c5a22002-12-03 02:34:49 +00002196 if( pHaving ){
2197 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002198 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
drhc66c5a22002-12-03 02:34:49 +00002199 goto select_end;
2200 }
danielk19774adee202004-05-08 08:23:19 +00002201 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pHaving) ){
drhc66c5a22002-12-03 02:34:49 +00002202 goto select_end;
2203 }
danielk19774adee202004-05-08 08:23:19 +00002204 if( sqlite3ExprCheck(pParse, pHaving, 1, &isAgg) ){
drhc66c5a22002-12-03 02:34:49 +00002205 goto select_end;
2206 }
2207 }
drhcce7d172000-05-31 15:34:51 +00002208 if( pOrderBy ){
2209 for(i=0; i<pOrderBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002210 int iCol;
drh22827922000-06-06 17:27:05 +00002211 Expr *pE = pOrderBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002212 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2213 sqlite3ExprDelete(pE);
2214 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh88eee382003-01-31 17:16:36 +00002215 }
danielk19774adee202004-05-08 08:23:19 +00002216 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh88eee382003-01-31 17:16:36 +00002217 goto select_end;
2218 }
danielk19774adee202004-05-08 08:23:19 +00002219 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh88eee382003-01-31 17:16:36 +00002220 goto select_end;
2221 }
danielk19774adee202004-05-08 08:23:19 +00002222 if( sqlite3ExprIsConstant(pE) ){
2223 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2224 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002225 "ORDER BY terms must not be non-integer constants");
drhe4de1fe2002-06-02 16:09:01 +00002226 goto select_end;
2227 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002228 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002229 "ORDER BY column number %d out of range - should be "
drhe4de1fe2002-06-02 16:09:01 +00002230 "between 1 and %d", iCol, pEList->nExpr);
drhe4de1fe2002-06-02 16:09:01 +00002231 goto select_end;
2232 }
drhcce7d172000-05-31 15:34:51 +00002233 }
2234 }
2235 }
drh22827922000-06-06 17:27:05 +00002236 if( pGroupBy ){
2237 for(i=0; i<pGroupBy->nExpr; i++){
drh88eee382003-01-31 17:16:36 +00002238 int iCol;
drh22827922000-06-06 17:27:05 +00002239 Expr *pE = pGroupBy->a[i].pExpr;
danielk19774adee202004-05-08 08:23:19 +00002240 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2241 sqlite3ExprDelete(pE);
2242 pE = pGroupBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
drh92086432002-01-22 14:11:29 +00002243 }
danielk19774adee202004-05-08 08:23:19 +00002244 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00002245 goto select_end;
drh22827922000-06-06 17:27:05 +00002246 }
danielk19774adee202004-05-08 08:23:19 +00002247 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00002248 goto select_end;
drh22827922000-06-06 17:27:05 +00002249 }
danielk19774adee202004-05-08 08:23:19 +00002250 if( sqlite3ExprIsConstant(pE) ){
2251 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2252 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002253 "GROUP BY terms must not be non-integer constants");
drh88eee382003-01-31 17:16:36 +00002254 goto select_end;
2255 }else if( iCol<=0 || iCol>pEList->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002256 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002257 "GROUP BY column number %d out of range - should be "
drh88eee382003-01-31 17:16:36 +00002258 "between 1 and %d", iCol, pEList->nExpr);
drh88eee382003-01-31 17:16:36 +00002259 goto select_end;
2260 }
2261 }
drh22827922000-06-06 17:27:05 +00002262 }
2263 }
drhcce7d172000-05-31 15:34:51 +00002264
drhd820cb12002-02-18 03:21:45 +00002265 /* Begin generating code.
2266 */
danielk19774adee202004-05-08 08:23:19 +00002267 v = sqlite3GetVdbe(pParse);
drhd820cb12002-02-18 03:21:45 +00002268 if( v==0 ) goto select_end;
2269
drhe78e8282003-01-19 03:59:45 +00002270 /* Identify column names if we will be using them in a callback. This
2271 ** step is skipped if the output is going to some other destination.
drh0bb28102002-05-08 11:54:14 +00002272 */
2273 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002274 generateColumnNames(pParse, pTabList, pEList);
drh0bb28102002-05-08 11:54:14 +00002275 }
2276
danielk197784ac9d02004-05-18 09:58:06 +00002277 /* If the destination is SRT_Union, then set the number of columns in
2278 ** the records that will be inserted into the temporary table. The caller
2279 ** couldn't do this, in case the select statement is of the form
2280 ** "SELECT * FROM ....".
2281 **
2282 ** We need to do this before we start inserting records into the
2283 ** temporary table (which has had OP_KeyAsData executed on it), because
2284 ** it is required by the key comparison function. So do it now, even
2285 ** though this means that OP_SetNumColumns may be executed on the same
2286 ** cursor more than once.
2287 */
2288 if( eDest==SRT_Union ){
2289 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
2290 }
2291
drhd820cb12002-02-18 03:21:45 +00002292 /* Generate code for all sub-queries in the FROM clause
2293 */
drhad3cab52002-05-24 02:04:32 +00002294 for(i=0; i<pTabList->nSrc; i++){
drh5cf590c2003-04-24 01:45:04 +00002295 const char *zSavedAuthContext;
drhc31c2eb2003-05-02 16:04:17 +00002296 int needRestoreContext;
2297
drha76b5df2002-02-23 02:32:10 +00002298 if( pTabList->a[i].pSelect==0 ) continue;
drh5cf590c2003-04-24 01:45:04 +00002299 if( pTabList->a[i].zName!=0 ){
2300 zSavedAuthContext = pParse->zAuthContext;
2301 pParse->zAuthContext = pTabList->a[i].zName;
drhc31c2eb2003-05-02 16:04:17 +00002302 needRestoreContext = 1;
2303 }else{
2304 needRestoreContext = 0;
drh5cf590c2003-04-24 01:45:04 +00002305 }
danielk19774adee202004-05-08 08:23:19 +00002306 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
danielk197784ac9d02004-05-18 09:58:06 +00002307 pTabList->a[i].iCursor, p, i, &isAgg, 0);
drhc31c2eb2003-05-02 16:04:17 +00002308 if( needRestoreContext ){
drh5cf590c2003-04-24 01:45:04 +00002309 pParse->zAuthContext = zSavedAuthContext;
2310 }
drh1b2e0322002-03-03 02:49:51 +00002311 pTabList = p->pSrc;
2312 pWhere = p->pWhere;
drhc31c2eb2003-05-02 16:04:17 +00002313 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
drhacd4c692002-03-07 02:02:51 +00002314 pOrderBy = p->pOrderBy;
2315 }
drh1b2e0322002-03-03 02:49:51 +00002316 pGroupBy = p->pGroupBy;
2317 pHaving = p->pHaving;
2318 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00002319 }
2320
drh6e175292004-03-13 14:00:36 +00002321 /* Check for the special case of a min() or max() function by itself
2322 ** in the result set.
2323 */
2324 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
2325 rc = 0;
2326 goto select_end;
2327 }
2328
drh832508b2002-03-02 17:04:07 +00002329 /* Check to see if this is a subquery that can be "flattened" into its parent.
2330 ** If flattening is a possiblity, do so and return immediately.
2331 */
drh1b2e0322002-03-03 02:49:51 +00002332 if( pParent && pParentAgg &&
drh8c74a8c2002-08-25 19:20:40 +00002333 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
drh1b2e0322002-03-03 02:49:51 +00002334 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00002335 return rc;
2336 }
drh832508b2002-03-02 17:04:07 +00002337
drh7b58dae2003-07-20 01:16:46 +00002338 /* Set the limiter.
2339 */
2340 computeLimitRegisters(pParse, p);
2341
drhe78e8282003-01-19 03:59:45 +00002342 /* Identify column types if we will be using a callback. This
2343 ** step is skipped if the output is going to a destination other
2344 ** than a callback.
drhe5f50722003-07-19 00:44:14 +00002345 **
2346 ** We have to do this separately from the creation of column names
2347 ** above because if the pTabList contains views then they will not
2348 ** have been resolved and we will not know the column types until
2349 ** now.
drhfcb78a42003-01-18 20:11:05 +00002350 */
2351 if( eDest==SRT_Callback ){
drh6a3ea0e2003-05-02 14:32:12 +00002352 generateColumnTypes(pParse, pTabList, pEList);
drhfcb78a42003-01-18 20:11:05 +00002353 }
2354
drh2d0794e2002-03-03 03:03:52 +00002355 /* If the output is destined for a temporary table, open that table.
2356 */
2357 if( eDest==SRT_TempTable ){
danielk19774adee202004-05-08 08:23:19 +00002358 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
danielk1977b4964b72004-05-18 01:23:38 +00002359 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
drh2d0794e2002-03-03 03:03:52 +00002360 }
2361
drh22827922000-06-06 17:27:05 +00002362 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00002363 */
drhd820cb12002-02-18 03:21:45 +00002364 sqliteAggregateInfoReset(pParse);
drhbb999ef2003-02-02 12:41:25 +00002365 if( isAgg || pGroupBy ){
drh0bce8352002-02-28 00:41:10 +00002366 assert( pParse->nAgg==0 );
drhbb999ef2003-02-02 12:41:25 +00002367 isAgg = 1;
drh22827922000-06-06 17:27:05 +00002368 for(i=0; i<pEList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002369 if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002370 goto select_end;
drh22827922000-06-06 17:27:05 +00002371 }
2372 }
2373 if( pGroupBy ){
2374 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002375 if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002376 goto select_end;
drh22827922000-06-06 17:27:05 +00002377 }
2378 }
2379 }
danielk19774adee202004-05-08 08:23:19 +00002380 if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00002381 goto select_end;
drh22827922000-06-06 17:27:05 +00002382 }
drh191b6902000-06-08 11:13:01 +00002383 if( pOrderBy ){
2384 for(i=0; i<pOrderBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002385 if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00002386 goto select_end;
drh191b6902000-06-08 11:13:01 +00002387 }
2388 }
2389 }
drhefb72512000-05-31 20:00:52 +00002390 }
2391
drh22827922000-06-06 17:27:05 +00002392 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00002393 */
2394 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002395 sqlite3VdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00002396 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00002397 FuncDef *pFunc;
2398 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002399 sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_POINTER);
drhe5095352002-02-24 03:25:14 +00002400 }
2401 }
drh1bee3d72001-10-15 00:44:35 +00002402 if( pGroupBy==0 ){
danielk19774adee202004-05-08 08:23:19 +00002403 sqlite3VdbeAddOp(v, OP_String, 0, 0);
2404 sqlite3VdbeAddOp(v, OP_AggFocus, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00002405 }
drhcce7d172000-05-31 15:34:51 +00002406 }
2407
drh19a775c2000-06-05 18:54:46 +00002408 /* Initialize the memory cell to NULL
2409 */
drhfef52082000-06-06 01:50:43 +00002410 if( eDest==SRT_Mem ){
danielk19774adee202004-05-08 08:23:19 +00002411 sqlite3VdbeAddOp(v, OP_String, 0, 0);
2412 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00002413 }
2414
drh832508b2002-03-02 17:04:07 +00002415 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00002416 */
drh19a775c2000-06-05 18:54:46 +00002417 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00002418 distinct = pParse->nTab++;
danielk19774adee202004-05-08 08:23:19 +00002419 sqlite3VdbeAddOp(v, OP_OpenTemp, distinct, 1);
drh832508b2002-03-02 17:04:07 +00002420 }else{
2421 distinct = -1;
drhefb72512000-05-31 20:00:52 +00002422 }
drh832508b2002-03-02 17:04:07 +00002423
2424 /* Begin the database scan
2425 */
danielk19774adee202004-05-08 08:23:19 +00002426 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
drh68d2e592002-08-04 00:52:38 +00002427 pGroupBy ? 0 : &pOrderBy);
drh1d83f052002-02-17 00:30:36 +00002428 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00002429
drh22827922000-06-06 17:27:05 +00002430 /* Use the standard inner loop if we are not dealing with
2431 ** aggregates
drhcce7d172000-05-31 15:34:51 +00002432 */
drhda9d6c42000-05-31 18:20:14 +00002433 if( !isAgg ){
drhdf199a22002-06-14 22:38:41 +00002434 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002435 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
drh1d83f052002-02-17 00:30:36 +00002436 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00002437 }
drhcce7d172000-05-31 15:34:51 +00002438 }
drhefb72512000-05-31 20:00:52 +00002439
drhe3184742002-06-19 14:27:05 +00002440 /* If we are dealing with aggregates, then do the special aggregate
drh22827922000-06-06 17:27:05 +00002441 ** processing.
drhefb72512000-05-31 20:00:52 +00002442 */
drh22827922000-06-06 17:27:05 +00002443 else{
drh268380c2004-02-25 13:47:31 +00002444 AggExpr *pAgg;
drh22827922000-06-06 17:27:05 +00002445 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00002446 int lbl1;
drh22827922000-06-06 17:27:05 +00002447 for(i=0; i<pGroupBy->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002448 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
drh22827922000-06-06 17:27:05 +00002449 }
danielk19774adee202004-05-08 08:23:19 +00002450 sqlite3VdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
danielk197736a3c702004-05-11 06:55:14 +00002451 sqlite3AddKeyType(v, pGroupBy);
danielk19774adee202004-05-08 08:23:19 +00002452 lbl1 = sqlite3VdbeMakeLabel(v);
2453 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh268380c2004-02-25 13:47:31 +00002454 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2455 if( pAgg->isAgg ) continue;
danielk19774adee202004-05-08 08:23:19 +00002456 sqlite3ExprCode(pParse, pAgg->pExpr);
2457 sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00002458 }
danielk19774adee202004-05-08 08:23:19 +00002459 sqlite3VdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00002460 }
drh268380c2004-02-25 13:47:31 +00002461 for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
drh22827922000-06-06 17:27:05 +00002462 Expr *pE;
drh268380c2004-02-25 13:47:31 +00002463 int nExpr;
2464 FuncDef *pDef;
2465 if( !pAgg->isAgg ) continue;
2466 assert( pAgg->pFunc!=0 );
2467 assert( pAgg->pFunc->xStep!=0 );
2468 pDef = pAgg->pFunc;
2469 pE = pAgg->pExpr;
2470 assert( pE!=0 );
drh22827922000-06-06 17:27:05 +00002471 assert( pE->op==TK_AGG_FUNCTION );
danielk19774adee202004-05-08 08:23:19 +00002472 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList, pDef->includeTypes);
2473 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
2474 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
drh22827922000-06-06 17:27:05 +00002475 }
drhcce7d172000-05-31 15:34:51 +00002476 }
2477
2478 /* End the database scan loop.
2479 */
danielk19774adee202004-05-08 08:23:19 +00002480 sqlite3WhereEnd(pWInfo);
drhcce7d172000-05-31 15:34:51 +00002481
drh22827922000-06-06 17:27:05 +00002482 /* If we are processing aggregates, we need to set up a second loop
2483 ** over all of the aggregate values and process them.
2484 */
2485 if( isAgg ){
danielk19774adee202004-05-08 08:23:19 +00002486 int endagg = sqlite3VdbeMakeLabel(v);
drh22827922000-06-06 17:27:05 +00002487 int startagg;
danielk19774adee202004-05-08 08:23:19 +00002488 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00002489 pParse->useAgg = 1;
2490 if( pHaving ){
danielk19774adee202004-05-08 08:23:19 +00002491 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
drh22827922000-06-06 17:27:05 +00002492 }
drhdf199a22002-06-14 22:38:41 +00002493 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
danielk197784ac9d02004-05-18 09:58:06 +00002494 iParm, startagg, endagg, aff) ){
drh1d83f052002-02-17 00:30:36 +00002495 goto select_end;
drh22827922000-06-06 17:27:05 +00002496 }
danielk19774adee202004-05-08 08:23:19 +00002497 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
2498 sqlite3VdbeResolveLabel(v, endagg);
2499 sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00002500 pParse->useAgg = 0;
2501 }
2502
drhcce7d172000-05-31 15:34:51 +00002503 /* If there is an ORDER BY clause, then we need to sort the results
2504 ** and send them to the callback one by one.
2505 */
2506 if( pOrderBy ){
drhc926afb2002-06-20 03:38:26 +00002507 generateSortTail(p, v, pEList->nExpr, eDest, iParm);
drhcce7d172000-05-31 15:34:51 +00002508 }
drh6a535342001-10-19 16:44:56 +00002509
drhf620b4e2004-02-09 14:37:50 +00002510 /* If this was a subquery, we have now converted the subquery into a
2511 ** temporary table. So delete the subquery structure from the parent
2512 ** to prevent this subquery from being evaluated again and to force the
2513 ** the use of the temporary table.
2514 */
2515 if( pParent ){
2516 assert( pParent->pSrc->nSrc>parentTab );
2517 assert( pParent->pSrc->a[parentTab].pSelect==p );
danielk19774adee202004-05-08 08:23:19 +00002518 sqlite3SelectDelete(p);
drhf620b4e2004-02-09 14:37:50 +00002519 pParent->pSrc->a[parentTab].pSelect = 0;
2520 }
2521
drh1d83f052002-02-17 00:30:36 +00002522 /* The SELECT was successfully coded. Set the return code to 0
2523 ** to indicate no errors.
2524 */
2525 rc = 0;
2526
2527 /* Control jumps to here if an error is encountered above, or upon
2528 ** successful coding of the SELECT.
2529 */
2530select_end:
2531 sqliteAggregateInfoReset(pParse);
2532 return rc;
drhcce7d172000-05-31 15:34:51 +00002533}