blob: 7038809ce9bd76ee50db917fb73c7855dd7f8380 [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**
drh0bb28102002-05-08 11:54:14 +000015** $Id: select.c,v 1.81 2002/05/08 11:54:15 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
18
drhcce7d172000-05-31 15:34:51 +000019/*
drh9bb61fe2000-06-05 16:01:39 +000020** Allocate a new Select structure and return a pointer to that
21** structure.
drhcce7d172000-05-31 15:34:51 +000022*/
drh9bb61fe2000-06-05 16:01:39 +000023Select *sqliteSelectNew(
drhdaffd0e2001-04-11 14:28:42 +000024 ExprList *pEList, /* which columns to include in the result */
25 IdList *pSrc, /* the FROM clause -- which tables to scan */
26 Expr *pWhere, /* the WHERE clause */
27 ExprList *pGroupBy, /* the GROUP BY clause */
28 Expr *pHaving, /* the HAVING clause */
29 ExprList *pOrderBy, /* the ORDER BY clause */
drh9bbca4c2001-11-06 04:00:18 +000030 int isDistinct, /* true if the DISTINCT keyword is present */
31 int nLimit, /* LIMIT value. -1 means not used */
32 int nOffset /* OFFSET value. -1 means not used */
drh9bb61fe2000-06-05 16:01:39 +000033){
34 Select *pNew;
35 pNew = sqliteMalloc( sizeof(*pNew) );
drhdaffd0e2001-04-11 14:28:42 +000036 if( pNew==0 ){
37 sqliteExprListDelete(pEList);
38 sqliteIdListDelete(pSrc);
39 sqliteExprDelete(pWhere);
40 sqliteExprListDelete(pGroupBy);
41 sqliteExprDelete(pHaving);
42 sqliteExprListDelete(pOrderBy);
43 }else{
44 pNew->pEList = pEList;
45 pNew->pSrc = pSrc;
46 pNew->pWhere = pWhere;
47 pNew->pGroupBy = pGroupBy;
48 pNew->pHaving = pHaving;
49 pNew->pOrderBy = pOrderBy;
50 pNew->isDistinct = isDistinct;
51 pNew->op = TK_SELECT;
drh9bbca4c2001-11-06 04:00:18 +000052 pNew->nLimit = nLimit;
53 pNew->nOffset = nOffset;
drhdaffd0e2001-04-11 14:28:42 +000054 }
drh9bb61fe2000-06-05 16:01:39 +000055 return pNew;
56}
57
58/*
59** Delete the given Select structure and all of its substructures.
60*/
61void sqliteSelectDelete(Select *p){
drh82c3d632000-06-06 21:56:07 +000062 if( p==0 ) return;
drh9bb61fe2000-06-05 16:01:39 +000063 sqliteExprListDelete(p->pEList);
64 sqliteIdListDelete(p->pSrc);
65 sqliteExprDelete(p->pWhere);
66 sqliteExprListDelete(p->pGroupBy);
67 sqliteExprDelete(p->pHaving);
68 sqliteExprListDelete(p->pOrderBy);
drh82c3d632000-06-06 21:56:07 +000069 sqliteSelectDelete(p->pPrior);
drha76b5df2002-02-23 02:32:10 +000070 sqliteFree(p->zSelect);
drh9bb61fe2000-06-05 16:01:39 +000071 sqliteFree(p);
72}
73
74/*
drh22827922000-06-06 17:27:05 +000075** Delete the aggregate information from the parse structure.
76*/
drh1d83f052002-02-17 00:30:36 +000077static void sqliteAggregateInfoReset(Parse *pParse){
drh22827922000-06-06 17:27:05 +000078 sqliteFree(pParse->aAgg);
79 pParse->aAgg = 0;
80 pParse->nAgg = 0;
drh22827922000-06-06 17:27:05 +000081 pParse->useAgg = 0;
82}
83
84/*
85** This routine generates the code for the inside of the inner loop
86** of a SELECT.
drh82c3d632000-06-06 21:56:07 +000087**
88** The pEList is used to determine the values for each column in the
drh967e8b72000-06-21 13:59:10 +000089** result row. Except if pEList==NULL, then we just read nColumn
drh82c3d632000-06-06 21:56:07 +000090** elements from the srcTab table.
drh22827922000-06-06 17:27:05 +000091*/
92static int selectInnerLoop(
93 Parse *pParse, /* The parser context */
94 ExprList *pEList, /* List of values being extracted */
drh82c3d632000-06-06 21:56:07 +000095 int srcTab, /* Pull data from this table */
drh967e8b72000-06-21 13:59:10 +000096 int nColumn, /* Number of columns in the source table */
drh22827922000-06-06 17:27:05 +000097 ExprList *pOrderBy, /* If not NULL, sort results using this key */
98 int distinct, /* If >=0, make sure results are distinct */
99 int eDest, /* How to dispose of the results */
100 int iParm, /* An argument to the disposal method */
101 int iContinue, /* Jump here to continue with next row */
102 int iBreak /* Jump here to break out of the inner loop */
103){
104 Vdbe *v = pParse->pVdbe;
105 int i;
drhdaffd0e2001-04-11 14:28:42 +0000106 if( v==0 ) return 0;
drh22827922000-06-06 17:27:05 +0000107
drh967e8b72000-06-21 13:59:10 +0000108 /* Pull the requested columns.
drh22827922000-06-06 17:27:05 +0000109 */
drh82c3d632000-06-06 21:56:07 +0000110 if( pEList ){
111 for(i=0; i<pEList->nExpr; i++){
112 sqliteExprCode(pParse, pEList->a[i].pExpr);
113 }
drh967e8b72000-06-21 13:59:10 +0000114 nColumn = pEList->nExpr;
drh82c3d632000-06-06 21:56:07 +0000115 }else{
drh967e8b72000-06-21 13:59:10 +0000116 for(i=0; i<nColumn; i++){
drh99fcd712001-10-13 01:06:47 +0000117 sqliteVdbeAddOp(v, OP_Column, srcTab, i);
drh82c3d632000-06-06 21:56:07 +0000118 }
drh22827922000-06-06 17:27:05 +0000119 }
120
drhdaffd0e2001-04-11 14:28:42 +0000121 /* If the DISTINCT keyword was present on the SELECT statement
122 ** and this row has been seen before, then do not make this row
123 ** part of the result.
drh22827922000-06-06 17:27:05 +0000124 */
125 if( distinct>=0 ){
126 int lbl = sqliteVdbeMakeLabel(v);
drh99fcd712001-10-13 01:06:47 +0000127 sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
128 sqliteVdbeAddOp(v, OP_Distinct, distinct, lbl);
129 sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
130 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
131 sqliteVdbeResolveLabel(v, lbl);
132 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh6b125452002-01-28 15:53:03 +0000133 sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
drh22827922000-06-06 17:27:05 +0000134 }
drh82c3d632000-06-06 21:56:07 +0000135
drh22827922000-06-06 17:27:05 +0000136 /* If there is an ORDER BY clause, then store the results
137 ** in a sorter.
138 */
139 if( pOrderBy ){
140 char *zSortOrder;
drh99fcd712001-10-13 01:06:47 +0000141 sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
drh22827922000-06-06 17:27:05 +0000142 zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
143 if( zSortOrder==0 ) return 1;
144 for(i=0; i<pOrderBy->nExpr; i++){
drhd8bc7082000-06-07 23:51:50 +0000145 zSortOrder[i] = pOrderBy->a[i].sortOrder ? '-' : '+';
drh22827922000-06-06 17:27:05 +0000146 sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
147 }
148 zSortOrder[pOrderBy->nExpr] = 0;
drh99fcd712001-10-13 01:06:47 +0000149 sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0);
150 sqliteVdbeChangeP3(v, -1, zSortOrder, strlen(zSortOrder));
drh6e142f52000-06-08 13:36:40 +0000151 sqliteFree(zSortOrder);
drh99fcd712001-10-13 01:06:47 +0000152 sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
drh22827922000-06-06 17:27:05 +0000153 }else
154
drh82c3d632000-06-06 21:56:07 +0000155 /* In this mode, write each query result to the key of the temporary
156 ** table iParm.
drh22827922000-06-06 17:27:05 +0000157 */
drh82c3d632000-06-06 21:56:07 +0000158 if( eDest==SRT_Union ){
drh99fcd712001-10-13 01:06:47 +0000159 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
160 sqliteVdbeAddOp(v, OP_String, iParm, 0);
drh6b125452002-01-28 15:53:03 +0000161 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
drh82c3d632000-06-06 21:56:07 +0000162 }else
163
drh5974a302000-06-07 14:42:26 +0000164 /* Store the result as data using a unique key.
165 */
drh2d0794e2002-03-03 03:03:52 +0000166 if( eDest==SRT_Table || eDest==SRT_TempTable ){
drh99fcd712001-10-13 01:06:47 +0000167 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
168 sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
169 sqliteVdbeAddOp(v, OP_Pull, 1, 0);
drh6b125452002-01-28 15:53:03 +0000170 sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
drh5974a302000-06-07 14:42:26 +0000171 }else
172
drh82c3d632000-06-06 21:56:07 +0000173 /* Construct a record from the query result, but instead of
174 ** saving that record, use it as a key to delete elements from
175 ** the temporary table iParm.
176 */
177 if( eDest==SRT_Except ){
drh99fcd712001-10-13 01:06:47 +0000178 int addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
179 sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
180 sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
drh22827922000-06-06 17:27:05 +0000181 }else
182
183 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
184 ** then there should be a single item on the stack. Write this
185 ** item into the set table with bogus data.
186 */
187 if( eDest==SRT_Set ){
drh967e8b72000-06-21 13:59:10 +0000188 assert( nColumn==1 );
drh99fcd712001-10-13 01:06:47 +0000189 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh6b125452002-01-28 15:53:03 +0000190 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
drh22827922000-06-06 17:27:05 +0000191 }else
192
drh82c3d632000-06-06 21:56:07 +0000193
drh22827922000-06-06 17:27:05 +0000194 /* If this is a scalar select that is part of an expression, then
195 ** store the results in the appropriate memory cell and break out
196 ** of the scan loop.
197 */
198 if( eDest==SRT_Mem ){
drh967e8b72000-06-21 13:59:10 +0000199 assert( nColumn==1 );
drh8721ce42001-11-07 14:22:00 +0000200 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
drh99fcd712001-10-13 01:06:47 +0000201 sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
drh22827922000-06-06 17:27:05 +0000202 }else
203
204 /* If none of the above, send the data to the callback function.
205 */
206 {
drh9bbca4c2001-11-06 04:00:18 +0000207 sqliteVdbeAddOp(v, OP_Callback, nColumn, iBreak);
drh82c3d632000-06-06 21:56:07 +0000208 }
209 return 0;
210}
211
212/*
drhd8bc7082000-06-07 23:51:50 +0000213** If the inner loop was generated using a non-null pOrderBy argument,
214** then the results were placed in a sorter. After the loop is terminated
215** we need to run the sorter and output the results. The following
216** routine generates the code needed to do that.
217*/
drh967e8b72000-06-21 13:59:10 +0000218static void generateSortTail(Vdbe *v, int nColumn){
drhd8bc7082000-06-07 23:51:50 +0000219 int end = sqliteVdbeMakeLabel(v);
220 int addr;
drh99fcd712001-10-13 01:06:47 +0000221 sqliteVdbeAddOp(v, OP_Sort, 0, 0);
222 addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end);
drh9bbca4c2001-11-06 04:00:18 +0000223 sqliteVdbeAddOp(v, OP_SortCallback, nColumn, end);
drh99fcd712001-10-13 01:06:47 +0000224 sqliteVdbeAddOp(v, OP_Goto, 0, addr);
225 sqliteVdbeResolveLabel(v, end);
drha8b38d22001-11-01 14:41:34 +0000226 sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000227}
228
229/*
drh82c3d632000-06-06 21:56:07 +0000230** Generate code that will tell the VDBE how many columns there
231** are in the result and the name for each column. This information
232** is used to provide "argc" and "azCol[]" values in the callback.
233*/
drh832508b2002-03-02 17:04:07 +0000234static void generateColumnNames(
235 Parse *pParse, /* Parser context */
236 int base, /* VDBE cursor corresponding to first entry in pTabList */
237 IdList *pTabList, /* List of tables */
238 ExprList *pEList /* Expressions defining the result set */
239){
drhd8bc7082000-06-07 23:51:50 +0000240 Vdbe *v = pParse->pVdbe;
drh82c3d632000-06-06 21:56:07 +0000241 int i;
drhdaffd0e2001-04-11 14:28:42 +0000242 if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000243 pParse->colNamesSet = 1;
drh99fcd712001-10-13 01:06:47 +0000244 sqliteVdbeAddOp(v, OP_ColumnCount, pEList->nExpr, 0);
drh82c3d632000-06-06 21:56:07 +0000245 for(i=0; i<pEList->nExpr; i++){
246 Expr *p;
drh1bee3d72001-10-15 00:44:35 +0000247 int showFullNames;
drh82c3d632000-06-06 21:56:07 +0000248 if( pEList->a[i].zName ){
249 char *zName = pEList->a[i].zName;
drh99fcd712001-10-13 01:06:47 +0000250 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
251 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000252 continue;
253 }
254 p = pEList->a[i].pExpr;
drhdaffd0e2001-04-11 14:28:42 +0000255 if( p==0 ) continue;
drh1bee3d72001-10-15 00:44:35 +0000256 showFullNames = (pParse->db->flags & SQLITE_FullColNames)!=0;
257 if( p->span.z && p->span.z[0] && !showFullNames ){
drh99fcd712001-10-13 01:06:47 +0000258 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
259 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
drhe1b6a5b2000-07-29 13:06:59 +0000260 sqliteVdbeCompressSpace(v, addr);
drh1bee3d72001-10-15 00:44:35 +0000261 }else if( p->op==TK_COLUMN && pTabList ){
drh832508b2002-03-02 17:04:07 +0000262 Table *pTab = pTabList->a[p->iTable - base].pTab;
drh97665872002-02-13 23:22:53 +0000263 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000264 int iCol = p->iColumn;
265 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000266 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
267 zCol = iCol<0 ? "_ROWID_" : pTab->aCol[iCol].zName;
drh1bee3d72001-10-15 00:44:35 +0000268 if( pTabList->nId>1 || showFullNames ){
drh82c3d632000-06-06 21:56:07 +0000269 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000270 char *zTab;
271
drh832508b2002-03-02 17:04:07 +0000272 zTab = pTabList->a[p->iTable - base].zAlias;
drh01a34662001-10-20 12:30:10 +0000273 if( showFullNames || zTab==0 ) zTab = pTab->zName;
drh97665872002-02-13 23:22:53 +0000274 sqliteSetString(&zName, zTab, ".", zCol, 0);
drh99fcd712001-10-13 01:06:47 +0000275 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
276 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000277 sqliteFree(zName);
278 }else{
drh99fcd712001-10-13 01:06:47 +0000279 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
drh22f70c32002-02-18 01:17:00 +0000280 sqliteVdbeChangeP3(v, -1, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000281 }
drh1bee3d72001-10-15 00:44:35 +0000282 }else if( p->span.z && p->span.z[0] ){
283 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
284 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
285 sqliteVdbeCompressSpace(v, addr);
286 }else{
287 char zName[30];
288 assert( p->op!=TK_COLUMN || pTabList==0 );
289 sprintf(zName, "column%d", i+1);
290 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
291 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000292 }
293 }
294}
295
296/*
drhd8bc7082000-06-07 23:51:50 +0000297** Name of the connection operator, used for error messages.
298*/
299static const char *selectOpName(int id){
300 char *z;
301 switch( id ){
302 case TK_ALL: z = "UNION ALL"; break;
303 case TK_INTERSECT: z = "INTERSECT"; break;
304 case TK_EXCEPT: z = "EXCEPT"; break;
305 default: z = "UNION"; break;
306 }
307 return z;
308}
309
310/*
drh22f70c32002-02-18 01:17:00 +0000311** Given a SELECT statement, generate a Table structure that describes
312** the result set of that SELECT.
313*/
314Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
315 Table *pTab;
316 int i;
317 ExprList *pEList;
318 static int fillInColumnList(Parse*, Select*);
319
320 if( fillInColumnList(pParse, pSelect) ){
321 return 0;
322 }
323 pTab = sqliteMalloc( sizeof(Table) );
324 if( pTab==0 ){
325 return 0;
326 }
327 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
328 pEList = pSelect->pEList;
329 pTab->nCol = pEList->nExpr;
drh417be792002-03-03 18:59:40 +0000330 assert( pTab->nCol>0 );
drh22f70c32002-02-18 01:17:00 +0000331 pTab->aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
332 for(i=0; i<pTab->nCol; i++){
333 Expr *p;
334 if( pEList->a[i].zName ){
335 pTab->aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
336 }else if( (p=pEList->a[i].pExpr)->span.z && p->span.z[0] ){
337 sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drhd820cb12002-02-18 03:21:45 +0000338 }else if( p->op==TK_DOT && p->pRight && p->pRight->token.z &&
339 p->pRight->token.z[0] ){
340 sqliteSetNString(&pTab->aCol[i].zName,
341 p->pRight->token.z, p->pRight->token.n, 0);
drh22f70c32002-02-18 01:17:00 +0000342 }else{
343 char zBuf[30];
344 sprintf(zBuf, "column%d", i+1);
345 pTab->aCol[i].zName = sqliteStrDup(zBuf);
346 }
347 }
348 pTab->iPKey = -1;
349 return pTab;
350}
351
352/*
drhd8bc7082000-06-07 23:51:50 +0000353** For the given SELECT statement, do two things.
354**
drh967e8b72000-06-21 13:59:10 +0000355** (1) Fill in the pTabList->a[].pTab fields in the IdList that
drh22f70c32002-02-18 01:17:00 +0000356** defines the set of tables that should be scanned.
drhd8bc7082000-06-07 23:51:50 +0000357**
drh54473222002-04-04 02:10:55 +0000358** (2) Scan the list of columns in the result set (pEList) looking
359** for instances of the "*" operator or the TABLE.* operator.
360** If found, expand each "*" to be every column in every table
361** and TABLE.* to be every column in TABLE.
drhd8bc7082000-06-07 23:51:50 +0000362**
363** Return 0 on success. If there are problems, leave an error message
364** in pParse and return non-zero.
365*/
366static int fillInColumnList(Parse *pParse, Select *p){
drh54473222002-04-04 02:10:55 +0000367 int i, j, k, rc;
drhdaffd0e2001-04-11 14:28:42 +0000368 IdList *pTabList;
369 ExprList *pEList;
drha76b5df2002-02-23 02:32:10 +0000370 Table *pTab;
drhdaffd0e2001-04-11 14:28:42 +0000371
372 if( p==0 || p->pSrc==0 ) return 1;
373 pTabList = p->pSrc;
374 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000375
376 /* Look up every table in the table list.
377 */
378 for(i=0; i<pTabList->nId; i++){
379 if( pTabList->a[i].pTab ){
380 /* This routine has run before! No need to continue */
381 return 0;
382 }
drhdaffd0e2001-04-11 14:28:42 +0000383 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000384 /* A sub-query in the FROM clause of a SELECT */
drh22f70c32002-02-18 01:17:00 +0000385 assert( pTabList->a[i].pSelect!=0 );
386 pTabList->a[i].pTab = pTab =
387 sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
388 pTabList->a[i].pSelect);
389 if( pTab==0 ){
390 return 1;
391 }
392 pTab->isTransient = 1;
393 }else{
drha76b5df2002-02-23 02:32:10 +0000394 /* An ordinary table or view name in the FROM clause */
395 pTabList->a[i].pTab = pTab =
396 sqliteFindTable(pParse->db, pTabList->a[i].zName);
397 if( pTab==0 ){
drh22f70c32002-02-18 01:17:00 +0000398 sqliteSetString(&pParse->zErrMsg, "no such table: ",
399 pTabList->a[i].zName, 0);
400 pParse->nErr++;
401 return 1;
402 }
drha76b5df2002-02-23 02:32:10 +0000403 if( pTab->pSelect ){
drh417be792002-03-03 18:59:40 +0000404 if( sqliteViewGetColumnNames(pParse, pTab) ){
405 return 1;
406 }
drhff78bd22002-02-27 01:47:11 +0000407 pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
drha76b5df2002-02-23 02:32:10 +0000408 }
drhd8bc7082000-06-07 23:51:50 +0000409 }
410 }
411
drh7c917d12001-12-16 20:05:05 +0000412 /* For every "*" that occurs in the column list, insert the names of
drh54473222002-04-04 02:10:55 +0000413 ** all columns in all tables. And for every TABLE.* insert the names
414 ** of all columns in TABLE. The parser inserted a special expression
drh7c917d12001-12-16 20:05:05 +0000415 ** with the TK_ALL operator for each "*" that it found in the column list.
416 ** The following code just has to locate the TK_ALL expressions and expand
417 ** each one to the list of all columns in all tables.
drh54473222002-04-04 02:10:55 +0000418 **
419 ** The first loop just checks to see if there are any "*" operators
420 ** that need expanding.
drhd8bc7082000-06-07 23:51:50 +0000421 */
drh7c917d12001-12-16 20:05:05 +0000422 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000423 Expr *pE = pEList->a[k].pExpr;
424 if( pE->op==TK_ALL ) break;
425 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
426 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
drh7c917d12001-12-16 20:05:05 +0000427 }
drh54473222002-04-04 02:10:55 +0000428 rc = 0;
drh7c917d12001-12-16 20:05:05 +0000429 if( k<pEList->nExpr ){
drh54473222002-04-04 02:10:55 +0000430 /*
431 ** If we get here it means the result set contains one or more "*"
432 ** operators that need to be expanded. Loop through each expression
433 ** in the result set and expand them one by one.
434 */
drh7c917d12001-12-16 20:05:05 +0000435 struct ExprList_item *a = pEList->a;
436 ExprList *pNew = 0;
437 for(k=0; k<pEList->nExpr; k++){
drh54473222002-04-04 02:10:55 +0000438 Expr *pE = a[k].pExpr;
439 if( pE->op!=TK_ALL &&
440 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
441 /* This particular expression does not need to be expanded.
442 */
drh7c917d12001-12-16 20:05:05 +0000443 pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
444 pNew->a[pNew->nExpr-1].zName = a[k].zName;
445 a[k].pExpr = 0;
446 a[k].zName = 0;
447 }else{
drh54473222002-04-04 02:10:55 +0000448 /* This expression is a "*" or a "TABLE.*" and needs to be
449 ** expanded. */
450 int tableSeen = 0; /* Set to 1 when TABLE matches */
451 Token *pName; /* text of name of TABLE */
452 if( pE->op==TK_DOT && pE->pLeft ){
453 pName = &pE->pLeft->token;
454 }else{
455 pName = 0;
456 }
drh7c917d12001-12-16 20:05:05 +0000457 for(i=0; i<pTabList->nId; i++){
458 Table *pTab = pTabList->a[i].pTab;
drh54473222002-04-04 02:10:55 +0000459 char *zTabName = pTabList->a[i].zAlias;
460 if( zTabName==0 || zTabName[0]==0 ){
461 zTabName = pTab->zName;
462 }
463 if( pName && (zTabName==0 || zTabName[0]==0 ||
464 sqliteStrNICmp(pName->z, zTabName, pName->n)!=0) ){
465 continue;
466 }
467 tableSeen = 1;
drh7c917d12001-12-16 20:05:05 +0000468 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000469 Expr *pExpr, *pLeft, *pRight;
470 pRight = sqliteExpr(TK_ID, 0, 0, 0);
471 if( pRight==0 ) break;
472 pRight->token.z = pTab->aCol[j].zName;
473 pRight->token.n = strlen(pTab->aCol[j].zName);
drh54473222002-04-04 02:10:55 +0000474 if( zTabName ){
drh22f70c32002-02-18 01:17:00 +0000475 pLeft = sqliteExpr(TK_ID, 0, 0, 0);
476 if( pLeft==0 ) break;
drh54473222002-04-04 02:10:55 +0000477 pLeft->token.z = zTabName;
478 pLeft->token.n = strlen(zTabName);
drh22f70c32002-02-18 01:17:00 +0000479 pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
480 if( pExpr==0 ) break;
drh7c917d12001-12-16 20:05:05 +0000481 }else{
drh22f70c32002-02-18 01:17:00 +0000482 pExpr = pRight;
483 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +0000484 }
drh7c917d12001-12-16 20:05:05 +0000485 pNew = sqliteExprListAppend(pNew, pExpr, 0);
486 }
drh17e24df2001-11-06 14:10:41 +0000487 }
drh54473222002-04-04 02:10:55 +0000488 if( !tableSeen ){
489 assert( pName!=0 );
490 sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1,
491 pName->z, pName->n, 0);
492 rc = 1;
493 }
drhd8bc7082000-06-07 23:51:50 +0000494 }
495 }
drh7c917d12001-12-16 20:05:05 +0000496 sqliteExprListDelete(pEList);
497 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +0000498 }
drh54473222002-04-04 02:10:55 +0000499 return rc;
drhd8bc7082000-06-07 23:51:50 +0000500}
501
502/*
drhff78bd22002-02-27 01:47:11 +0000503** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
504** in a select structure. It just sets the pointers to NULL. This
505** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
506** pointer is not NULL, this routine is called recursively on that pointer.
507**
508** This routine is called on the Select structure that defines a
509** VIEW in order to undo any bindings to tables. This is necessary
510** because those tables might be DROPed by a subsequent SQL command.
511*/
512void sqliteSelectUnbind(Select *p){
513 int i;
514 IdList *pSrc = p->pSrc;
515 Table *pTab;
516 if( p==0 ) return;
517 for(i=0; i<pSrc->nId; i++){
518 if( (pTab = pSrc->a[i].pTab)!=0 ){
519 if( pTab->isTransient ){
520 sqliteDeleteTable(0, pTab);
521 sqliteSelectDelete(pSrc->a[i].pSelect);
522 pSrc->a[i].pSelect = 0;
523 }
524 pSrc->a[i].pTab = 0;
525 if( pSrc->a[i].pSelect ){
526 sqliteSelectUnbind(pSrc->a[i].pSelect);
527 }
528 }
529 }
530}
531
532/*
drhd8bc7082000-06-07 23:51:50 +0000533** This routine associates entries in an ORDER BY expression list with
534** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +0000535** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +0000536** the top-level node is filled in with column number and the iTable
537** value of the top-level node is filled with iTable parameter.
538**
539** If there are prior SELECT clauses, they are processed first. A match
540** in an earlier SELECT takes precedence over a later SELECT.
541**
542** Any entry that does not match is flagged as an error. The number
543** of errors is returned.
544*/
545static int matchOrderbyToColumn(
546 Parse *pParse, /* A place to leave error messages */
547 Select *pSelect, /* Match to result columns of this SELECT */
548 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
549 int iTable, /* Insert this this value in iTable */
550 int mustComplete /* If TRUE all ORDER BYs must match */
551){
552 int nErr = 0;
553 int i, j;
554 ExprList *pEList;
555
drhdaffd0e2001-04-11 14:28:42 +0000556 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +0000557 if( mustComplete ){
558 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
559 }
560 if( fillInColumnList(pParse, pSelect) ){
561 return 1;
562 }
563 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +0000564 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
565 return 1;
566 }
drhd8bc7082000-06-07 23:51:50 +0000567 }
568 pEList = pSelect->pEList;
569 for(i=0; i<pOrderBy->nExpr; i++){
570 Expr *pE = pOrderBy->a[i].pExpr;
drh92cd52f2000-06-08 01:55:29 +0000571 int match = 0;
drhd8bc7082000-06-07 23:51:50 +0000572 if( pOrderBy->a[i].done ) continue;
573 for(j=0; j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +0000574 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
drha76b5df2002-02-23 02:32:10 +0000575 char *zName, *zLabel;
576 zName = pEList->a[j].zName;
577 assert( pE->token.z );
578 zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
drhd8bc7082000-06-07 23:51:50 +0000579 sqliteDequote(zLabel);
580 if( sqliteStrICmp(zName, zLabel)==0 ){
581 match = 1;
582 }
drh6e142f52000-06-08 13:36:40 +0000583 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +0000584 }
drh4cfa7932000-06-08 15:10:46 +0000585 if( match==0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
drhd8bc7082000-06-07 23:51:50 +0000586 match = 1;
587 }
588 if( match ){
drh967e8b72000-06-21 13:59:10 +0000589 pE->op = TK_COLUMN;
590 pE->iColumn = j;
drhd8bc7082000-06-07 23:51:50 +0000591 pE->iTable = iTable;
592 pOrderBy->a[i].done = 1;
593 break;
594 }
595 }
drh92cd52f2000-06-08 01:55:29 +0000596 if( !match && mustComplete ){
drhd8bc7082000-06-07 23:51:50 +0000597 char zBuf[30];
598 sprintf(zBuf,"%d",i+1);
599 sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf,
600 " does not match any result column", 0);
601 pParse->nErr++;
602 nErr++;
603 break;
604 }
605 }
606 return nErr;
607}
608
609/*
610** Get a VDBE for the given parser context. Create a new one if necessary.
611** If an error occurs, return NULL and leave a message in pParse.
612*/
613Vdbe *sqliteGetVdbe(Parse *pParse){
614 Vdbe *v = pParse->pVdbe;
615 if( v==0 ){
drh4c504392000-10-16 22:06:40 +0000616 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +0000617 }
drhd8bc7082000-06-07 23:51:50 +0000618 return v;
619}
620
621
622/*
drh82c3d632000-06-06 21:56:07 +0000623** This routine is called to process a query that is really the union
624** or intersection of two or more separate queries.
625*/
626static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
drh10e5e3c2000-06-08 00:19:02 +0000627 int rc; /* Success code from a subroutine */
628 Select *pPrior; /* Another SELECT immediately to our left */
629 Vdbe *v; /* Generate code to this VDBE */
630 int base; /* Baseline value for pParse->nTab */
drh82c3d632000-06-06 21:56:07 +0000631
drhd8bc7082000-06-07 23:51:50 +0000632 /* Make sure there is no ORDER BY clause on prior SELECTs. Only the
633 ** last SELECT in the series may have an ORDER BY.
drh82c3d632000-06-06 21:56:07 +0000634 */
drhdaffd0e2001-04-11 14:28:42 +0000635 if( p==0 || p->pPrior==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +0000636 pPrior = p->pPrior;
637 if( pPrior->pOrderBy ){
638 sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
639 selectOpName(p->op), " not before", 0);
drh82c3d632000-06-06 21:56:07 +0000640 pParse->nErr++;
641 return 1;
642 }
643
drhd8bc7082000-06-07 23:51:50 +0000644 /* Make sure we have a valid query engine. If not, create a new one.
645 */
646 v = sqliteGetVdbe(pParse);
647 if( v==0 ) return 1;
648
drh1cc3d752002-03-23 00:31:29 +0000649 /* Create the destination temporary table if necessary
650 */
651 if( eDest==SRT_TempTable ){
652 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
653 eDest = SRT_Table;
654 }
655
drhd8bc7082000-06-07 23:51:50 +0000656 /* Process the UNION or INTERSECTION
657 */
drh10e5e3c2000-06-08 00:19:02 +0000658 base = pParse->nTab;
drh82c3d632000-06-06 21:56:07 +0000659 switch( p->op ){
drhd8bc7082000-06-07 23:51:50 +0000660 case TK_ALL:
drh82c3d632000-06-06 21:56:07 +0000661 case TK_EXCEPT:
662 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +0000663 int unionTab; /* Cursor number of the temporary table holding result */
664 int op; /* One of the SRT_ operations to apply to self */
665 int priorOp; /* The SRT_ operation to apply to prior selects */
drh82c3d632000-06-06 21:56:07 +0000666
drhd8bc7082000-06-07 23:51:50 +0000667 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
668 if( eDest==priorOp ){
669 /* We can reuse a temporary table generated by a SELECT to our
670 ** right. This also means we are not the right-most select and so
671 ** we cannot have an ORDER BY clause
672 */
drh82c3d632000-06-06 21:56:07 +0000673 unionTab = iParm;
drhd8bc7082000-06-07 23:51:50 +0000674 assert( p->pOrderBy==0 );
drh82c3d632000-06-06 21:56:07 +0000675 }else{
drhd8bc7082000-06-07 23:51:50 +0000676 /* We will need to create our own temporary table to hold the
677 ** intermediate results.
678 */
679 unionTab = pParse->nTab++;
680 if( p->pOrderBy
681 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
682 return 1;
683 }
drhd8bc7082000-06-07 23:51:50 +0000684 if( p->op!=TK_ALL ){
drhc6b52df2002-01-04 03:09:29 +0000685 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
drh99fcd712001-10-13 01:06:47 +0000686 sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drh345fda32001-01-15 22:51:08 +0000687 }else{
drh99fcd712001-10-13 01:06:47 +0000688 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +0000689 }
drh82c3d632000-06-06 21:56:07 +0000690 }
drhd8bc7082000-06-07 23:51:50 +0000691
692 /* Code the SELECT statements to our left
693 */
drh832508b2002-03-02 17:04:07 +0000694 rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +0000695 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +0000696
697 /* Code the current SELECT statement
698 */
699 switch( p->op ){
700 case TK_EXCEPT: op = SRT_Except; break;
701 case TK_UNION: op = SRT_Union; break;
702 case TK_ALL: op = SRT_Table; break;
703 }
drh82c3d632000-06-06 21:56:07 +0000704 p->pPrior = 0;
drh832508b2002-03-02 17:04:07 +0000705 rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +0000706 p->pPrior = pPrior;
707 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +0000708
709 /* Convert the data in the temporary table into whatever form
710 ** it is that we currently need.
711 */
712 if( eDest!=priorOp ){
drh6b563442001-11-07 16:48:26 +0000713 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +0000714 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +0000715 if( eDest==SRT_Callback ){
716 generateColumnNames(pParse, p->base, 0, p->pEList);
717 }
drh82c3d632000-06-06 21:56:07 +0000718 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +0000719 iCont = sqliteVdbeMakeLabel(v);
720 sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
721 iStart = sqliteVdbeCurrentAddr(v);
drh82c3d632000-06-06 21:56:07 +0000722 rc = selectInnerLoop(pParse, 0, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +0000723 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +0000724 iCont, iBreak);
725 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +0000726 sqliteVdbeResolveLabel(v, iCont);
727 sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
drh99fcd712001-10-13 01:06:47 +0000728 sqliteVdbeResolveLabel(v, iBreak);
729 sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +0000730 if( p->pOrderBy ){
731 generateSortTail(v, p->pEList->nExpr);
732 }
drh82c3d632000-06-06 21:56:07 +0000733 }
734 break;
735 }
736 case TK_INTERSECT: {
737 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +0000738 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +0000739
drhd8bc7082000-06-07 23:51:50 +0000740 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +0000741 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +0000742 ** by allocating the tables we will need.
743 */
drh82c3d632000-06-06 21:56:07 +0000744 tab1 = pParse->nTab++;
745 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +0000746 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
747 return 1;
748 }
drhc6b52df2002-01-04 03:09:29 +0000749 sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
drh99fcd712001-10-13 01:06:47 +0000750 sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
drhd8bc7082000-06-07 23:51:50 +0000751
752 /* Code the SELECTs to our left into temporary table "tab1".
753 */
drh832508b2002-03-02 17:04:07 +0000754 rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +0000755 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +0000756
757 /* Code the current SELECT into temporary table "tab2"
758 */
drhc6b52df2002-01-04 03:09:29 +0000759 sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
drh99fcd712001-10-13 01:06:47 +0000760 sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh82c3d632000-06-06 21:56:07 +0000761 p->pPrior = 0;
drh832508b2002-03-02 17:04:07 +0000762 rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
drh82c3d632000-06-06 21:56:07 +0000763 p->pPrior = pPrior;
764 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +0000765
766 /* Generate code to take the intersection of the two temporary
767 ** tables.
768 */
drh82c3d632000-06-06 21:56:07 +0000769 assert( p->pEList );
drh41202cc2002-04-23 17:10:18 +0000770 if( eDest==SRT_Callback ){
771 generateColumnNames(pParse, p->base, 0, p->pEList);
772 }
drh82c3d632000-06-06 21:56:07 +0000773 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +0000774 iCont = sqliteVdbeMakeLabel(v);
775 sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
776 iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
drh99fcd712001-10-13 01:06:47 +0000777 sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
drh82c3d632000-06-06 21:56:07 +0000778 rc = selectInnerLoop(pParse, 0, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +0000779 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +0000780 iCont, iBreak);
781 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +0000782 sqliteVdbeResolveLabel(v, iCont);
783 sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
drh99fcd712001-10-13 01:06:47 +0000784 sqliteVdbeResolveLabel(v, iBreak);
785 sqliteVdbeAddOp(v, OP_Close, tab2, 0);
786 sqliteVdbeAddOp(v, OP_Close, tab1, 0);
drhd8bc7082000-06-07 23:51:50 +0000787 if( p->pOrderBy ){
788 generateSortTail(v, p->pEList->nExpr);
789 }
drh82c3d632000-06-06 21:56:07 +0000790 break;
791 }
792 }
793 assert( p->pEList && pPrior->pEList );
794 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
drhd8bc7082000-06-07 23:51:50 +0000795 sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ",
796 selectOpName(p->op), " do not have the same number of result columns", 0);
drh82c3d632000-06-06 21:56:07 +0000797 pParse->nErr++;
798 return 1;
drh22827922000-06-06 17:27:05 +0000799 }
drh10e5e3c2000-06-08 00:19:02 +0000800 pParse->nTab = base;
drh22827922000-06-06 17:27:05 +0000801 return 0;
802}
803
804/*
drh832508b2002-03-02 17:04:07 +0000805** Recursively scan through an expression tree. For every reference
806** to a column in table number iFrom, change that reference to the
807** same column in table number iTo.
808*/
809static void changeTables(Expr *pExpr, int iFrom, int iTo){
810 if( pExpr==0 ) return;
811 if( pExpr->op==TK_COLUMN && pExpr->iTable==iFrom ){
812 pExpr->iTable = iTo;
813 }else{
drh1b2e0322002-03-03 02:49:51 +0000814 static void changeTablesInList(ExprList*, int, int);
drh832508b2002-03-02 17:04:07 +0000815 changeTables(pExpr->pLeft, iFrom, iTo);
816 changeTables(pExpr->pRight, iFrom, iTo);
drh1b2e0322002-03-03 02:49:51 +0000817 changeTablesInList(pExpr->pList, iFrom, iTo);
818 }
819}
820static void changeTablesInList(ExprList *pList, int iFrom, int iTo){
821 if( pList ){
822 int i;
823 for(i=0; i<pList->nExpr; i++){
824 changeTables(pList->a[i].pExpr, iFrom, iTo);
drh832508b2002-03-02 17:04:07 +0000825 }
826 }
827}
828
829/*
830** Scan through the expression pExpr. Replace every reference to
831** a column in table number iTable with a copy of the corresponding
drh84e59202002-03-14 14:33:31 +0000832** entry in pEList. (But leave references to the ROWID column
833** unchanged.) When making a copy of an expression in pEList, change
834** references to columns in table iSub into references to table iTable.
drh832508b2002-03-02 17:04:07 +0000835**
836** This routine is part of the flattening procedure. A subquery
837** whose result set is defined by pEList appears as entry in the
838** FROM clause of a SELECT such that the VDBE cursor assigned to that
839** FORM clause entry is iTable. This routine make the necessary
840** changes to pExpr so that it refers directly to the source table
841** of the subquery rather the result set of the subquery.
842*/
843static void substExpr(Expr *pExpr, int iTable, ExprList *pEList, int iSub){
844 if( pExpr==0 ) return;
drh84e59202002-03-14 14:33:31 +0000845 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){
drh832508b2002-03-02 17:04:07 +0000846 Expr *pNew;
drh84e59202002-03-14 14:33:31 +0000847 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
drh832508b2002-03-02 17:04:07 +0000848 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
849 pNew = pEList->a[pExpr->iColumn].pExpr;
850 assert( pNew!=0 );
851 pExpr->op = pNew->op;
852 pExpr->pLeft = sqliteExprDup(pNew->pLeft);
853 pExpr->pRight = sqliteExprDup(pNew->pRight);
854 pExpr->pList = sqliteExprListDup(pNew->pList);
855 pExpr->iTable = pNew->iTable;
856 pExpr->iColumn = pNew->iColumn;
857 pExpr->iAgg = pNew->iAgg;
drh1b2e0322002-03-03 02:49:51 +0000858 pExpr->token = pNew->token;
drh832508b2002-03-02 17:04:07 +0000859 if( iSub!=iTable ){
860 changeTables(pExpr, iSub, iTable);
861 }
862 }else{
863 static void substExprList(ExprList*,int,ExprList*,int);
864 substExpr(pExpr->pLeft, iTable, pEList, iSub);
865 substExpr(pExpr->pRight, iTable, pEList, iSub);
866 substExprList(pExpr->pList, iTable, pEList, iSub);
867 }
868}
869static void
870substExprList(ExprList *pList, int iTable, ExprList *pEList, int iSub){
871 int i;
872 if( pList==0 ) return;
873 for(i=0; i<pList->nExpr; i++){
874 substExpr(pList->a[i].pExpr, iTable, pEList, iSub);
875 }
876}
877
878/*
drh1350b032002-02-27 19:00:20 +0000879** This routine attempts to flatten subqueries in order to speed
880** execution. It returns 1 if it makes changes and 0 if no flattening
881** occurs.
882**
883** To understand the concept of flattening, consider the following
884** query:
885**
886** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
887**
888** The default way of implementing this query is to execute the
889** subquery first and store the results in a temporary table, then
890** run the outer query on that temporary table. This requires two
891** passes over the data. Furthermore, because the temporary table
892** has no indices, the WHERE clause on the outer query cannot be
drh832508b2002-03-02 17:04:07 +0000893** optimized.
drh1350b032002-02-27 19:00:20 +0000894**
drh832508b2002-03-02 17:04:07 +0000895** This routine attempts to rewrite queries such as the above into
drh1350b032002-02-27 19:00:20 +0000896** a single flat select, like this:
897**
898** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
899**
900** The code generated for this simpification gives the same result
drh832508b2002-03-02 17:04:07 +0000901** but only has to scan the data once. And because indices might
902** exist on the table t1, a complete scan of the data might be
903** avoided.
drh1350b032002-02-27 19:00:20 +0000904**
drh832508b2002-03-02 17:04:07 +0000905** Flattening is only attempted if all of the following are true:
drh1350b032002-02-27 19:00:20 +0000906**
drh832508b2002-03-02 17:04:07 +0000907** (1) The subquery and the outer query do not both use aggregates.
drh1350b032002-02-27 19:00:20 +0000908**
drh832508b2002-03-02 17:04:07 +0000909** (2) The subquery is not an aggregate or the outer query is not a join.
910**
911** (3) The subquery is not a join.
912**
913** (4) The subquery is not DISTINCT or the outer query is not a join.
914**
915** (5) The subquery is not DISTINCT or the outer query does not use
916** aggregates.
917**
918** (6) The subquery does not use aggregates or the outer query is not
919** DISTINCT.
920**
drh08192d52002-04-30 19:20:28 +0000921** (7) The subquery has a FROM clause.
922**
drh832508b2002-03-02 17:04:07 +0000923** In this routine, the "p" parameter is a pointer to the outer query.
924** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
925** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
926**
927** If flattening is not attempted, this routine is a no-op and return 0.
928** If flattening is attempted this routine returns 1.
929**
930** All of the expression analysis must occur on both the outer query and
931** the subquery before this routine runs.
drh1350b032002-02-27 19:00:20 +0000932*/
drh832508b2002-03-02 17:04:07 +0000933int flattenSubquery(Select *p, int iFrom, int isAgg, int subqueryIsAgg){
drh0bb28102002-05-08 11:54:14 +0000934 Select *pSub; /* The inner query or "subquery" */
935 IdList *pSrc; /* The FROM clause of the outer query */
936 IdList *pSubSrc; /* The FROM clause of the subquery */
937 ExprList *pList; /* The result set of the outer query */
drh832508b2002-03-02 17:04:07 +0000938 int i;
939 int iParent, iSub;
940 Expr *pWhere;
drh1350b032002-02-27 19:00:20 +0000941
drh832508b2002-03-02 17:04:07 +0000942 /* Check to see if flattening is permitted. Return 0 if not.
943 */
944 if( p==0 ) return 0;
945 pSrc = p->pSrc;
946 assert( pSrc && iFrom>=0 && iFrom<pSrc->nId );
947 pSub = pSrc->a[iFrom].pSelect;
948 assert( pSub!=0 );
949 if( isAgg && subqueryIsAgg ) return 0;
950 if( subqueryIsAgg && pSrc->nId>1 ) return 0;
951 pSubSrc = pSub->pSrc;
952 assert( pSubSrc );
drh08192d52002-04-30 19:20:28 +0000953 if( pSubSrc->nId!=1 ) return 0;
drh832508b2002-03-02 17:04:07 +0000954 if( pSub->isDistinct && pSrc->nId>1 ) return 0;
955 if( pSub->isDistinct && isAgg ) return 0;
956 if( p->isDistinct && subqueryIsAgg ) return 0;
957
drh0bb28102002-05-08 11:54:14 +0000958 /* If we reach this point, it means flattening is permitted for the
drh832508b2002-03-02 17:04:07 +0000959 ** i-th entry of the FROM clause in the outer query.
960 */
961 iParent = p->base + iFrom;
962 iSub = pSub->base;
963 substExprList(p->pEList, iParent, pSub->pEList, iSub);
964 pList = p->pEList;
965 for(i=0; i<pList->nExpr; i++){
966 if( pList->a[i].zName==0 ){
967 Expr *pExpr = pList->a[i].pExpr;
968 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
969 }
970 }
drh1b2e0322002-03-03 02:49:51 +0000971 if( isAgg ){
972 substExprList(p->pGroupBy, iParent, pSub->pEList, iSub);
973 substExpr(p->pHaving, iParent, pSub->pEList, iSub);
974 }
drh832508b2002-03-02 17:04:07 +0000975 substExprList(p->pOrderBy, iParent, pSub->pEList, iSub);
976 if( pSub->pWhere ){
977 pWhere = sqliteExprDup(pSub->pWhere);
978 if( iParent!=iSub ){
979 changeTables(pWhere, iSub, iParent);
980 }
981 }else{
982 pWhere = 0;
983 }
984 if( subqueryIsAgg ){
985 assert( p->pHaving==0 );
drh1b2e0322002-03-03 02:49:51 +0000986 p->pHaving = p->pWhere;
987 p->pWhere = pWhere;
drh832508b2002-03-02 17:04:07 +0000988 substExpr(p->pHaving, iParent, pSub->pEList, iSub);
drh1b2e0322002-03-03 02:49:51 +0000989 if( pSub->pHaving ){
990 Expr *pHaving = sqliteExprDup(pSub->pHaving);
991 if( iParent!=iSub ){
992 changeTables(pHaving, iSub, iParent);
993 }
994 if( p->pHaving ){
995 p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
996 }else{
997 p->pHaving = pHaving;
998 }
999 }
1000 assert( p->pGroupBy==0 );
1001 p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
1002 if( iParent!=iSub ){
1003 changeTablesInList(p->pGroupBy, iSub, iParent);
1004 }
drh832508b2002-03-02 17:04:07 +00001005 }else if( p->pWhere==0 ){
1006 p->pWhere = pWhere;
1007 }else{
1008 substExpr(p->pWhere, iParent, pSub->pEList, iSub);
1009 if( pWhere ){
1010 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
1011 }
1012 }
1013 p->isDistinct = p->isDistinct || pSub->isDistinct;
1014 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
1015 sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
1016 }
1017 pSrc->a[iFrom].pTab = pSubSrc->a[0].pTab;
1018 pSubSrc->a[0].pTab = 0;
1019 pSrc->a[iFrom].pSelect = pSubSrc->a[0].pSelect;
1020 pSubSrc->a[0].pSelect = 0;
1021 sqliteSelectDelete(pSub);
1022 return 1;
1023}
drh1350b032002-02-27 19:00:20 +00001024
1025/*
drh9562b552002-02-19 15:00:07 +00001026** Analyze the SELECT statement passed in as an argument to see if it
1027** is a simple min() or max() query. If it is and this query can be
1028** satisfied using a single seek to the beginning or end of an index,
1029** then generate the code for this SELECT return 1. If this is not a
1030** simple min() or max() query, then return 0;
1031**
1032** A simply min() or max() query looks like this:
1033**
1034** SELECT min(a) FROM table;
1035** SELECT max(a) FROM table;
1036**
1037** The query may have only a single table in its FROM argument. There
1038** can be no GROUP BY or HAVING or WHERE clauses. The result set must
1039** be the min() or max() of a single column of the table. The column
1040** in the min() or max() function must be indexed.
1041**
1042** The parameters to this routine are the same as for sqliteSelect().
1043** See the header comment on that routine for additional information.
1044*/
1045static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
1046 Expr *pExpr;
1047 int iCol;
1048 Table *pTab;
1049 Index *pIdx;
1050 int base;
1051 Vdbe *v;
1052 int openOp;
1053 int seekOp;
1054 int cont;
1055 ExprList eList;
1056 struct ExprList_item eListItem;
1057
1058 /* Check to see if this query is a simple min() or max() query. Return
1059 ** zero if it is not.
1060 */
1061 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
1062 if( p->pSrc->nId!=1 ) return 0;
1063 if( p->pEList->nExpr!=1 ) return 0;
1064 pExpr = p->pEList->a[0].pExpr;
1065 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
1066 if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
drh0bce8352002-02-28 00:41:10 +00001067 if( pExpr->token.n!=3 ) return 0;
1068 if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
1069 seekOp = OP_Rewind;
1070 }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
1071 seekOp = OP_Last;
1072 }else{
1073 return 0;
1074 }
drh9562b552002-02-19 15:00:07 +00001075 pExpr = pExpr->pList->a[0].pExpr;
1076 if( pExpr->op!=TK_COLUMN ) return 0;
1077 iCol = pExpr->iColumn;
1078 pTab = p->pSrc->a[0].pTab;
1079
1080 /* If we get to here, it means the query is of the correct form.
drh17f71932002-02-21 12:01:27 +00001081 ** Check to make sure we have an index and make pIdx point to the
1082 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
1083 ** key column, no index is necessary so set pIdx to NULL. If no
1084 ** usable index is found, return 0.
drh9562b552002-02-19 15:00:07 +00001085 */
1086 if( iCol<0 ){
1087 pIdx = 0;
1088 }else{
1089 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1090 assert( pIdx->nColumn>=1 );
1091 if( pIdx->aiColumn[0]==iCol ) break;
1092 }
1093 if( pIdx==0 ) return 0;
1094 }
1095
drh17f71932002-02-21 12:01:27 +00001096 /* Identify column names if we will be using the callback. This
drh9562b552002-02-19 15:00:07 +00001097 ** step is skipped if the output is going to a table or a memory cell.
1098 */
1099 v = sqliteGetVdbe(pParse);
1100 if( v==0 ) return 0;
1101 if( eDest==SRT_Callback ){
drh832508b2002-03-02 17:04:07 +00001102 generateColumnNames(pParse, p->base, p->pSrc, p->pEList);
drh9562b552002-02-19 15:00:07 +00001103 }
1104
drh17f71932002-02-21 12:01:27 +00001105 /* Generating code to find the min or the max. Basically all we have
1106 ** to do is find the first or the last entry in the chosen index. If
1107 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
1108 ** or last entry in the main table.
drh9562b552002-02-19 15:00:07 +00001109 */
drh5cf8e8c2002-02-19 22:42:05 +00001110 if( !pParse->schemaVerified && (pParse->db->flags & SQLITE_InTrans)==0 ){
1111 sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
1112 pParse->schemaVerified = 1;
1113 }
drh9562b552002-02-19 15:00:07 +00001114 openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
drh832508b2002-03-02 17:04:07 +00001115 base = p->base;
drh9562b552002-02-19 15:00:07 +00001116 sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001117 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
drh9562b552002-02-19 15:00:07 +00001118 if( pIdx==0 ){
1119 sqliteVdbeAddOp(v, seekOp, base, 0);
1120 }else{
1121 sqliteVdbeAddOp(v, openOp, base+1, pIdx->tnum);
drh5cf8e8c2002-02-19 22:42:05 +00001122 sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
drh9562b552002-02-19 15:00:07 +00001123 sqliteVdbeAddOp(v, seekOp, base+1, 0);
1124 sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
1125 sqliteVdbeAddOp(v, OP_Close, base+1, 0);
1126 sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
1127 }
drh5cf8e8c2002-02-19 22:42:05 +00001128 eList.nExpr = 1;
1129 memset(&eListItem, 0, sizeof(eListItem));
1130 eList.a = &eListItem;
1131 eList.a[0].pExpr = pExpr;
drh9562b552002-02-19 15:00:07 +00001132 cont = sqliteVdbeMakeLabel(v);
1133 selectInnerLoop(pParse, &eList, base, 1, 0, -1, eDest, iParm, cont, cont);
1134 sqliteVdbeResolveLabel(v, cont);
1135 sqliteVdbeAddOp(v, OP_Close, base, 0);
1136 return 1;
1137}
1138
1139/*
drh9bb61fe2000-06-05 16:01:39 +00001140** Generate code for the given SELECT statement.
1141**
drhfef52082000-06-06 01:50:43 +00001142** The results are distributed in various ways depending on the
1143** value of eDest and iParm.
1144**
1145** eDest Value Result
1146** ------------ -------------------------------------------
1147** SRT_Callback Invoke the callback for each row of the result.
1148**
1149** SRT_Mem Store first result in memory cell iParm
1150**
1151** SRT_Set Store results as keys of a table with cursor iParm
1152**
drh82c3d632000-06-06 21:56:07 +00001153** SRT_Union Store results as a key in a temporary table iParm
1154**
drhc4a3c772001-04-04 11:48:57 +00001155** SRT_Except Remove results form the temporary table iParm.
1156**
1157** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +00001158**
1159** This routine returns the number of errors. If any errors are
1160** encountered, then an appropriate error message is left in
1161** pParse->zErrMsg.
1162**
1163** This routine does NOT free the Select structure passed in. The
1164** calling function needs to do that.
drh1b2e0322002-03-03 02:49:51 +00001165**
1166** The pParent, parentTab, and *pParentAgg fields are filled in if this
1167** SELECT is a subquery. This routine may try to combine this SELECT
1168** with its parent to form a single flat query. In so doing, it might
1169** change the parent query from a non-aggregate to an aggregate query.
1170** For that reason, the pParentAgg flag is passed as a pointer, so it
1171** can be changed.
drh9bb61fe2000-06-05 16:01:39 +00001172*/
1173int sqliteSelect(
drhcce7d172000-05-31 15:34:51 +00001174 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +00001175 Select *p, /* The SELECT statement being coded. */
drh82c3d632000-06-06 21:56:07 +00001176 int eDest, /* One of: SRT_Callback Mem Set Union Except */
drh832508b2002-03-02 17:04:07 +00001177 int iParm, /* Save result in this memory location, if >=0 */
1178 Select *pParent, /* Another SELECT for which this is a sub-query */
1179 int parentTab, /* Index in pParent->pSrc of this query */
drh1b2e0322002-03-03 02:49:51 +00001180 int *pParentAgg /* True if pParent uses aggregate functions */
drhcce7d172000-05-31 15:34:51 +00001181){
drhd8bc7082000-06-07 23:51:50 +00001182 int i;
drhcce7d172000-05-31 15:34:51 +00001183 WhereInfo *pWInfo;
1184 Vdbe *v;
1185 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +00001186 ExprList *pEList; /* List of columns to extract. */
drh9bb61fe2000-06-05 16:01:39 +00001187 IdList *pTabList; /* List of tables to select from */
1188 Expr *pWhere; /* The WHERE clause. May be NULL */
1189 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +00001190 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
1191 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +00001192 int isDistinct; /* True if the DISTINCT keyword is present */
1193 int distinct; /* Table to use for the distinct set */
drh10e5e3c2000-06-08 00:19:02 +00001194 int base; /* First cursor available for use */
drh1d83f052002-02-17 00:30:36 +00001195 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +00001196
drhdaffd0e2001-04-11 14:28:42 +00001197 if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
1198
drh82c3d632000-06-06 21:56:07 +00001199 /* If there is are a sequence of queries, do the earlier ones first.
1200 */
1201 if( p->pPrior ){
1202 return multiSelect(pParse, p, eDest, iParm);
1203 }
1204
1205 /* Make local copies of the parameters for this query.
1206 */
drh9bb61fe2000-06-05 16:01:39 +00001207 pTabList = p->pSrc;
1208 pWhere = p->pWhere;
1209 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +00001210 pGroupBy = p->pGroupBy;
1211 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +00001212 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +00001213
drh832508b2002-03-02 17:04:07 +00001214 /* Allocate a block of VDBE cursors, one for each table in the FROM clause.
1215 ** The WHERE processing requires that the cursors for the tables in the
1216 ** FROM clause be consecutive.
drh10e5e3c2000-06-08 00:19:02 +00001217 */
drh832508b2002-03-02 17:04:07 +00001218 base = p->base = pParse->nTab;
1219 pParse->nTab += pTabList->nId;
drh10e5e3c2000-06-08 00:19:02 +00001220
drh9bb61fe2000-06-05 16:01:39 +00001221 /*
1222 ** Do not even attempt to generate any code if we have already seen
1223 ** errors before this routine starts.
1224 */
drh1d83f052002-02-17 00:30:36 +00001225 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001226
drhd8bc7082000-06-07 23:51:50 +00001227 /* Look up every table in the table list and create an appropriate
1228 ** columnlist in pEList if there isn't one already. (The parser leaves
drh967e8b72000-06-21 13:59:10 +00001229 ** a NULL in the p->pEList if the SQL said "SELECT * FROM ...")
drhcce7d172000-05-31 15:34:51 +00001230 */
drhd8bc7082000-06-07 23:51:50 +00001231 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +00001232 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001233 }
drhd8bc7082000-06-07 23:51:50 +00001234 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +00001235 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001236
drh22827922000-06-06 17:27:05 +00001237 /* If writing to memory or generating a set
1238 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +00001239 */
drhfef52082000-06-06 01:50:43 +00001240 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
drh19a775c2000-06-05 18:54:46 +00001241 sqliteSetString(&pParse->zErrMsg, "only a single result allowed for "
1242 "a SELECT that is part of an expression", 0);
1243 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +00001244 goto select_end;
drh19a775c2000-06-05 18:54:46 +00001245 }
1246
drh22827922000-06-06 17:27:05 +00001247 /* ORDER BY is ignored if we are not sending the result to a callback.
1248 */
1249 if( eDest!=SRT_Callback ){
drhacd4c692002-03-07 02:02:51 +00001250 pOrderBy = 0;
drh22827922000-06-06 17:27:05 +00001251 }
1252
drh10e5e3c2000-06-08 00:19:02 +00001253 /* At this point, we should have allocated all the cursors that we
drh832508b2002-03-02 17:04:07 +00001254 ** need to handle subquerys and temporary tables.
drh10e5e3c2000-06-08 00:19:02 +00001255 **
drh967e8b72000-06-21 13:59:10 +00001256 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +00001257 */
drh4794b982000-06-06 13:54:14 +00001258 for(i=0; i<pEList->nExpr; i++){
drh832508b2002-03-02 17:04:07 +00001259 if( sqliteExprResolveIds(pParse, base, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001260 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001261 }
drh22827922000-06-06 17:27:05 +00001262 if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +00001263 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001264 }
1265 }
drhcce7d172000-05-31 15:34:51 +00001266 if( pWhere ){
drh832508b2002-03-02 17:04:07 +00001267 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +00001268 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001269 }
1270 if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +00001271 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001272 }
1273 }
1274 if( pOrderBy ){
1275 for(i=0; i<pOrderBy->nExpr; i++){
drh22827922000-06-06 17:27:05 +00001276 Expr *pE = pOrderBy->a[i].pExpr;
drh92086432002-01-22 14:11:29 +00001277 if( sqliteExprIsConstant(pE) ){
1278 sqliteSetString(&pParse->zErrMsg,
1279 "ORDER BY expressions should not be constant", 0);
1280 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +00001281 goto select_end;
drh92086432002-01-22 14:11:29 +00001282 }
drh832508b2002-03-02 17:04:07 +00001283 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00001284 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001285 }
drh22827922000-06-06 17:27:05 +00001286 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00001287 goto select_end;
drhcce7d172000-05-31 15:34:51 +00001288 }
1289 }
1290 }
drh22827922000-06-06 17:27:05 +00001291 if( pGroupBy ){
1292 for(i=0; i<pGroupBy->nExpr; i++){
1293 Expr *pE = pGroupBy->a[i].pExpr;
drh92086432002-01-22 14:11:29 +00001294 if( sqliteExprIsConstant(pE) ){
1295 sqliteSetString(&pParse->zErrMsg,
1296 "GROUP BY expressions should not be constant", 0);
1297 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +00001298 goto select_end;
drh92086432002-01-22 14:11:29 +00001299 }
drh832508b2002-03-02 17:04:07 +00001300 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +00001301 goto select_end;
drh22827922000-06-06 17:27:05 +00001302 }
1303 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00001304 goto select_end;
drh22827922000-06-06 17:27:05 +00001305 }
1306 }
1307 }
1308 if( pHaving ){
1309 if( pGroupBy==0 ){
drhda932812000-06-06 18:00:15 +00001310 sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required "
1311 "before HAVING", 0);
drh22827922000-06-06 17:27:05 +00001312 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +00001313 goto select_end;
drh22827922000-06-06 17:27:05 +00001314 }
drh832508b2002-03-02 17:04:07 +00001315 if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00001316 goto select_end;
drh22827922000-06-06 17:27:05 +00001317 }
drhda932812000-06-06 18:00:15 +00001318 if( sqliteExprCheck(pParse, pHaving, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00001319 goto select_end;
drh22827922000-06-06 17:27:05 +00001320 }
drhcce7d172000-05-31 15:34:51 +00001321 }
1322
drh9562b552002-02-19 15:00:07 +00001323 /* Check for the special case of a min() or max() function by itself
1324 ** in the result set.
1325 */
1326 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
drh5cf8e8c2002-02-19 22:42:05 +00001327 rc = 0;
drh9562b552002-02-19 15:00:07 +00001328 goto select_end;
1329 }
1330
drhd820cb12002-02-18 03:21:45 +00001331 /* Begin generating code.
1332 */
1333 v = sqliteGetVdbe(pParse);
1334 if( v==0 ) goto select_end;
1335
drh0bb28102002-05-08 11:54:14 +00001336 /* Identify column names if we will be using in the callback. This
1337 ** step is skipped if the output is going to a table or a memory cell.
1338 */
1339 if( eDest==SRT_Callback ){
1340 generateColumnNames(pParse, p->base, pTabList, pEList);
1341 }
1342
1343 /* Set the limiter
1344 */
1345 if( p->nLimit<=0 ){
1346 p->nOffset = 0;
1347 }else{
1348 if( p->nOffset<0 ) p->nOffset = 0;
1349 sqliteVdbeAddOp(v, OP_Limit, p->nLimit, p->nOffset);
1350 }
1351
drhd820cb12002-02-18 03:21:45 +00001352 /* Generate code for all sub-queries in the FROM clause
1353 */
1354 for(i=0; i<pTabList->nId; i++){
drha76b5df2002-02-23 02:32:10 +00001355 if( pTabList->a[i].pSelect==0 ) continue;
drh2d0794e2002-03-03 03:03:52 +00001356 sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable, base+i,
drh1b2e0322002-03-03 02:49:51 +00001357 p, i, &isAgg);
1358 pTabList = p->pSrc;
1359 pWhere = p->pWhere;
drhacd4c692002-03-07 02:02:51 +00001360 if( eDest==SRT_Callback ){
1361 pOrderBy = p->pOrderBy;
1362 }
drh1b2e0322002-03-03 02:49:51 +00001363 pGroupBy = p->pGroupBy;
1364 pHaving = p->pHaving;
1365 isDistinct = p->isDistinct;
drhd820cb12002-02-18 03:21:45 +00001366 }
1367
drh832508b2002-03-02 17:04:07 +00001368 /* Check to see if this is a subquery that can be "flattened" into its parent.
1369 ** If flattening is a possiblity, do so and return immediately.
1370 */
drh1b2e0322002-03-03 02:49:51 +00001371 if( pParent && pParentAgg &&
1372 flattenSubquery(pParent, parentTab, *pParentAgg, isAgg) ){
1373 if( isAgg ) *pParentAgg = 1;
drh832508b2002-03-02 17:04:07 +00001374 return rc;
1375 }
drh832508b2002-03-02 17:04:07 +00001376
drh2d0794e2002-03-03 03:03:52 +00001377 /* If the output is destined for a temporary table, open that table.
1378 */
1379 if( eDest==SRT_TempTable ){
1380 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
1381 }
1382
drh22827922000-06-06 17:27:05 +00001383 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00001384 */
drhd820cb12002-02-18 03:21:45 +00001385 sqliteAggregateInfoReset(pParse);
drh22827922000-06-06 17:27:05 +00001386 if( isAgg ){
drh0bce8352002-02-28 00:41:10 +00001387 assert( pParse->nAgg==0 );
drh22827922000-06-06 17:27:05 +00001388 for(i=0; i<pEList->nExpr; i++){
1389 if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001390 goto select_end;
drh22827922000-06-06 17:27:05 +00001391 }
1392 }
1393 if( pGroupBy ){
1394 for(i=0; i<pGroupBy->nExpr; i++){
1395 if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001396 goto select_end;
drh22827922000-06-06 17:27:05 +00001397 }
1398 }
1399 }
1400 if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00001401 goto select_end;
drh22827922000-06-06 17:27:05 +00001402 }
drh191b6902000-06-08 11:13:01 +00001403 if( pOrderBy ){
1404 for(i=0; i<pOrderBy->nExpr; i++){
1405 if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001406 goto select_end;
drh191b6902000-06-08 11:13:01 +00001407 }
1408 }
1409 }
drhefb72512000-05-31 20:00:52 +00001410 }
1411
drh22827922000-06-06 17:27:05 +00001412 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00001413 */
1414 if( isAgg ){
drh99fcd712001-10-13 01:06:47 +00001415 sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drhe5095352002-02-24 03:25:14 +00001416 for(i=0; i<pParse->nAgg; i++){
drh0bce8352002-02-28 00:41:10 +00001417 FuncDef *pFunc;
1418 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
drh1350b032002-02-27 19:00:20 +00001419 sqliteVdbeAddOp(v, OP_AggInit, 0, i);
drh0bce8352002-02-28 00:41:10 +00001420 sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
drhe5095352002-02-24 03:25:14 +00001421 }
1422 }
drh1bee3d72001-10-15 00:44:35 +00001423 if( pGroupBy==0 ){
1424 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00001425 sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00001426 }
drhcce7d172000-05-31 15:34:51 +00001427 }
1428
drh19a775c2000-06-05 18:54:46 +00001429 /* Initialize the memory cell to NULL
1430 */
drhfef52082000-06-06 01:50:43 +00001431 if( eDest==SRT_Mem ){
drh99fcd712001-10-13 01:06:47 +00001432 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh8721ce42001-11-07 14:22:00 +00001433 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00001434 }
1435
drh832508b2002-03-02 17:04:07 +00001436 /* Open a temporary table to use for the distinct set.
drhefb72512000-05-31 20:00:52 +00001437 */
drh19a775c2000-06-05 18:54:46 +00001438 if( isDistinct ){
drh832508b2002-03-02 17:04:07 +00001439 distinct = pParse->nTab++;
drhc6b52df2002-01-04 03:09:29 +00001440 sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
drh832508b2002-03-02 17:04:07 +00001441 }else{
1442 distinct = -1;
drhefb72512000-05-31 20:00:52 +00001443 }
drh832508b2002-03-02 17:04:07 +00001444
1445 /* Begin the database scan
1446 */
1447 pWInfo = sqliteWhereBegin(pParse, p->base, pTabList, pWhere, 0);
drh1d83f052002-02-17 00:30:36 +00001448 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001449
drh22827922000-06-06 17:27:05 +00001450 /* Use the standard inner loop if we are not dealing with
1451 ** aggregates
drhcce7d172000-05-31 15:34:51 +00001452 */
drhda9d6c42000-05-31 18:20:14 +00001453 if( !isAgg ){
drh82c3d632000-06-06 21:56:07 +00001454 if( selectInnerLoop(pParse, pEList, 0, 0, pOrderBy, distinct, eDest, iParm,
drh22827922000-06-06 17:27:05 +00001455 pWInfo->iContinue, pWInfo->iBreak) ){
drh1d83f052002-02-17 00:30:36 +00001456 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00001457 }
drhcce7d172000-05-31 15:34:51 +00001458 }
drhefb72512000-05-31 20:00:52 +00001459
drh22827922000-06-06 17:27:05 +00001460 /* If we are dealing with aggregates, then to the special aggregate
1461 ** processing.
drhefb72512000-05-31 20:00:52 +00001462 */
drh22827922000-06-06 17:27:05 +00001463 else{
drh22827922000-06-06 17:27:05 +00001464 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00001465 int lbl1;
drh22827922000-06-06 17:27:05 +00001466 for(i=0; i<pGroupBy->nExpr; i++){
1467 sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
1468 }
drh99fcd712001-10-13 01:06:47 +00001469 sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
drh1bee3d72001-10-15 00:44:35 +00001470 lbl1 = sqliteVdbeMakeLabel(v);
drh99fcd712001-10-13 01:06:47 +00001471 sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh22827922000-06-06 17:27:05 +00001472 for(i=0; i<pParse->nAgg; i++){
1473 if( pParse->aAgg[i].isAgg ) continue;
1474 sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
drh99fcd712001-10-13 01:06:47 +00001475 sqliteVdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00001476 }
drh22827922000-06-06 17:27:05 +00001477 sqliteVdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00001478 }
drh22827922000-06-06 17:27:05 +00001479 for(i=0; i<pParse->nAgg; i++){
1480 Expr *pE;
drh0bce8352002-02-28 00:41:10 +00001481 int j;
drh22827922000-06-06 17:27:05 +00001482 if( !pParse->aAgg[i].isAgg ) continue;
1483 pE = pParse->aAgg[i].pExpr;
drh22827922000-06-06 17:27:05 +00001484 assert( pE->op==TK_AGG_FUNCTION );
drh0bce8352002-02-28 00:41:10 +00001485 if( pE->pList ){
1486 for(j=0; j<pE->pList->nExpr; j++){
1487 sqliteExprCode(pParse, pE->pList->a[j].pExpr);
1488 }
drhe5095352002-02-24 03:25:14 +00001489 }
drh0bce8352002-02-28 00:41:10 +00001490 sqliteVdbeAddOp(v, OP_Integer, i, 0);
drhf55f25f2002-02-28 01:46:11 +00001491 sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
drh0bce8352002-02-28 00:41:10 +00001492 assert( pParse->aAgg[i].pFunc!=0 );
1493 assert( pParse->aAgg[i].pFunc->xStep!=0 );
1494 sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
drh22827922000-06-06 17:27:05 +00001495 }
drhcce7d172000-05-31 15:34:51 +00001496 }
1497
1498 /* End the database scan loop.
1499 */
1500 sqliteWhereEnd(pWInfo);
1501
drh22827922000-06-06 17:27:05 +00001502 /* If we are processing aggregates, we need to set up a second loop
1503 ** over all of the aggregate values and process them.
1504 */
1505 if( isAgg ){
1506 int endagg = sqliteVdbeMakeLabel(v);
1507 int startagg;
drh99fcd712001-10-13 01:06:47 +00001508 startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00001509 pParse->useAgg = 1;
1510 if( pHaving ){
1511 sqliteExprIfFalse(pParse, pHaving, startagg);
1512 }
drh82c3d632000-06-06 21:56:07 +00001513 if( selectInnerLoop(pParse, pEList, 0, 0, pOrderBy, distinct, eDest, iParm,
drh22827922000-06-06 17:27:05 +00001514 startagg, endagg) ){
drh1d83f052002-02-17 00:30:36 +00001515 goto select_end;
drh22827922000-06-06 17:27:05 +00001516 }
drh99fcd712001-10-13 01:06:47 +00001517 sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
1518 sqliteVdbeResolveLabel(v, endagg);
1519 sqliteVdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00001520 pParse->useAgg = 0;
1521 }
1522
drhcce7d172000-05-31 15:34:51 +00001523 /* If there is an ORDER BY clause, then we need to sort the results
1524 ** and send them to the callback one by one.
1525 */
1526 if( pOrderBy ){
drhd8bc7082000-06-07 23:51:50 +00001527 generateSortTail(v, pEList->nExpr);
drhcce7d172000-05-31 15:34:51 +00001528 }
drh6a535342001-10-19 16:44:56 +00001529
1530
1531 /* Issue a null callback if that is what the user wants.
1532 */
1533 if( (pParse->db->flags & SQLITE_NullCallback)!=0 && eDest==SRT_Callback ){
1534 sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
1535 }
1536
drh1d83f052002-02-17 00:30:36 +00001537 /* The SELECT was successfully coded. Set the return code to 0
1538 ** to indicate no errors.
1539 */
1540 rc = 0;
1541
1542 /* Control jumps to here if an error is encountered above, or upon
1543 ** successful coding of the SELECT.
1544 */
1545select_end:
drh832508b2002-03-02 17:04:07 +00001546 pParse->nTab = base;
drh1d83f052002-02-17 00:30:36 +00001547 sqliteAggregateInfoReset(pParse);
1548 return rc;
drhcce7d172000-05-31 15:34:51 +00001549}