blob: 036c35ec5482ff960b5aa8ade3b5546f8442a219 [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**
drh9562b552002-02-19 15:00:07 +000015** $Id: select.c,v 1.62 2002/02/19 15:00:08 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);
drh9bb61fe2000-06-05 16:01:39 +000070 sqliteFree(p);
71}
72
73/*
drh22827922000-06-06 17:27:05 +000074** Delete the aggregate information from the parse structure.
75*/
drh1d83f052002-02-17 00:30:36 +000076static void sqliteAggregateInfoReset(Parse *pParse){
drh22827922000-06-06 17:27:05 +000077 sqliteFree(pParse->aAgg);
78 pParse->aAgg = 0;
79 pParse->nAgg = 0;
80 pParse->iAggCount = -1;
81 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 */
166 if( eDest==SRT_Table ){
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*/
drhd8bc7082000-06-07 23:51:50 +0000234static
235void generateColumnNames(Parse *pParse, IdList *pTabList, ExprList *pEList){
236 Vdbe *v = pParse->pVdbe;
drh82c3d632000-06-06 21:56:07 +0000237 int i;
drhdaffd0e2001-04-11 14:28:42 +0000238 if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
drhd8bc7082000-06-07 23:51:50 +0000239 pParse->colNamesSet = 1;
drh99fcd712001-10-13 01:06:47 +0000240 sqliteVdbeAddOp(v, OP_ColumnCount, pEList->nExpr, 0);
drh82c3d632000-06-06 21:56:07 +0000241 for(i=0; i<pEList->nExpr; i++){
242 Expr *p;
drh1bee3d72001-10-15 00:44:35 +0000243 int showFullNames;
drh82c3d632000-06-06 21:56:07 +0000244 if( pEList->a[i].zName ){
245 char *zName = pEList->a[i].zName;
drh99fcd712001-10-13 01:06:47 +0000246 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
247 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000248 continue;
249 }
250 p = pEList->a[i].pExpr;
drhdaffd0e2001-04-11 14:28:42 +0000251 if( p==0 ) continue;
drh1bee3d72001-10-15 00:44:35 +0000252 showFullNames = (pParse->db->flags & SQLITE_FullColNames)!=0;
253 if( p->span.z && p->span.z[0] && !showFullNames ){
drh99fcd712001-10-13 01:06:47 +0000254 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
255 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
drhe1b6a5b2000-07-29 13:06:59 +0000256 sqliteVdbeCompressSpace(v, addr);
drh1bee3d72001-10-15 00:44:35 +0000257 }else if( p->op==TK_COLUMN && pTabList ){
drh8aff1012001-12-22 14:49:24 +0000258 Table *pTab = pTabList->a[p->iTable - pParse->nTab].pTab;
drh97665872002-02-13 23:22:53 +0000259 char *zCol;
drh8aff1012001-12-22 14:49:24 +0000260 int iCol = p->iColumn;
261 if( iCol<0 ) iCol = pTab->iPKey;
drh97665872002-02-13 23:22:53 +0000262 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
263 zCol = iCol<0 ? "_ROWID_" : pTab->aCol[iCol].zName;
drh1bee3d72001-10-15 00:44:35 +0000264 if( pTabList->nId>1 || showFullNames ){
drh82c3d632000-06-06 21:56:07 +0000265 char *zName = 0;
drh82c3d632000-06-06 21:56:07 +0000266 char *zTab;
267
drh98808ba2001-10-18 12:34:46 +0000268 zTab = pTabList->a[p->iTable - pParse->nTab].zAlias;
drh01a34662001-10-20 12:30:10 +0000269 if( showFullNames || zTab==0 ) zTab = pTab->zName;
drh97665872002-02-13 23:22:53 +0000270 sqliteSetString(&zName, zTab, ".", zCol, 0);
drh99fcd712001-10-13 01:06:47 +0000271 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
272 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000273 sqliteFree(zName);
274 }else{
drh99fcd712001-10-13 01:06:47 +0000275 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
drh22f70c32002-02-18 01:17:00 +0000276 sqliteVdbeChangeP3(v, -1, zCol, 0);
drh82c3d632000-06-06 21:56:07 +0000277 }
drh1bee3d72001-10-15 00:44:35 +0000278 }else if( p->span.z && p->span.z[0] ){
279 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
280 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
281 sqliteVdbeCompressSpace(v, addr);
282 }else{
283 char zName[30];
284 assert( p->op!=TK_COLUMN || pTabList==0 );
285 sprintf(zName, "column%d", i+1);
286 sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
287 sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
drh82c3d632000-06-06 21:56:07 +0000288 }
289 }
290}
291
292/*
drhd8bc7082000-06-07 23:51:50 +0000293** Name of the connection operator, used for error messages.
294*/
295static const char *selectOpName(int id){
296 char *z;
297 switch( id ){
298 case TK_ALL: z = "UNION ALL"; break;
299 case TK_INTERSECT: z = "INTERSECT"; break;
300 case TK_EXCEPT: z = "EXCEPT"; break;
301 default: z = "UNION"; break;
302 }
303 return z;
304}
305
306/*
drh22f70c32002-02-18 01:17:00 +0000307** Given a SELECT statement, generate a Table structure that describes
308** the result set of that SELECT.
309*/
310Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
311 Table *pTab;
312 int i;
313 ExprList *pEList;
314 static int fillInColumnList(Parse*, Select*);
315
316 if( fillInColumnList(pParse, pSelect) ){
317 return 0;
318 }
319 pTab = sqliteMalloc( sizeof(Table) );
320 if( pTab==0 ){
321 return 0;
322 }
323 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
324 pEList = pSelect->pEList;
325 pTab->nCol = pEList->nExpr;
326 pTab->aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
327 for(i=0; i<pTab->nCol; i++){
328 Expr *p;
329 if( pEList->a[i].zName ){
330 pTab->aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
331 }else if( (p=pEList->a[i].pExpr)->span.z && p->span.z[0] ){
332 sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
drhd820cb12002-02-18 03:21:45 +0000333 }else if( p->op==TK_DOT && p->pRight && p->pRight->token.z &&
334 p->pRight->token.z[0] ){
335 sqliteSetNString(&pTab->aCol[i].zName,
336 p->pRight->token.z, p->pRight->token.n, 0);
drh22f70c32002-02-18 01:17:00 +0000337 }else{
338 char zBuf[30];
339 sprintf(zBuf, "column%d", i+1);
340 pTab->aCol[i].zName = sqliteStrDup(zBuf);
341 }
342 }
343 pTab->iPKey = -1;
344 return pTab;
345}
346
347/*
drhd8bc7082000-06-07 23:51:50 +0000348** For the given SELECT statement, do two things.
349**
drh967e8b72000-06-21 13:59:10 +0000350** (1) Fill in the pTabList->a[].pTab fields in the IdList that
drh22f70c32002-02-18 01:17:00 +0000351** defines the set of tables that should be scanned.
drhd8bc7082000-06-07 23:51:50 +0000352**
353** (2) If the columns to be extracted variable (pEList) is NULL
354** (meaning that a "*" was used in the SQL statement) then
355** create a fake pEList containing the names of all columns
356** of all tables.
357**
358** Return 0 on success. If there are problems, leave an error message
359** in pParse and return non-zero.
360*/
361static int fillInColumnList(Parse *pParse, Select *p){
drh7c917d12001-12-16 20:05:05 +0000362 int i, j, k;
drhdaffd0e2001-04-11 14:28:42 +0000363 IdList *pTabList;
364 ExprList *pEList;
365
366 if( p==0 || p->pSrc==0 ) return 1;
367 pTabList = p->pSrc;
368 pEList = p->pEList;
drhd8bc7082000-06-07 23:51:50 +0000369
370 /* Look up every table in the table list.
371 */
372 for(i=0; i<pTabList->nId; i++){
373 if( pTabList->a[i].pTab ){
374 /* This routine has run before! No need to continue */
375 return 0;
376 }
drhdaffd0e2001-04-11 14:28:42 +0000377 if( pTabList->a[i].zName==0 ){
drh22f70c32002-02-18 01:17:00 +0000378 /* A sub-query in the FROM clause of a SELECT */
379 Table *pTab;
380 assert( pTabList->a[i].pSelect!=0 );
381 pTabList->a[i].pTab = pTab =
382 sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
383 pTabList->a[i].pSelect);
384 if( pTab==0 ){
385 return 1;
386 }
387 pTab->isTransient = 1;
388 }else{
389 /* An ordinary table name in the FROM clause */
390 pTabList->a[i].pTab = sqliteFindTable(pParse->db, pTabList->a[i].zName);
391 if( pTabList->a[i].pTab==0 ){
392 sqliteSetString(&pParse->zErrMsg, "no such table: ",
393 pTabList->a[i].zName, 0);
394 pParse->nErr++;
395 return 1;
396 }
drhd8bc7082000-06-07 23:51:50 +0000397 }
398 }
399
drh7c917d12001-12-16 20:05:05 +0000400 /* For every "*" that occurs in the column list, insert the names of
401 ** all columns in all tables. The parser inserted a special expression
402 ** with the TK_ALL operator for each "*" that it found in the column list.
403 ** The following code just has to locate the TK_ALL expressions and expand
404 ** each one to the list of all columns in all tables.
drhd8bc7082000-06-07 23:51:50 +0000405 */
drh7c917d12001-12-16 20:05:05 +0000406 for(k=0; k<pEList->nExpr; k++){
407 if( pEList->a[k].pExpr->op==TK_ALL ) break;
408 }
409 if( k<pEList->nExpr ){
410 struct ExprList_item *a = pEList->a;
411 ExprList *pNew = 0;
412 for(k=0; k<pEList->nExpr; k++){
413 if( a[k].pExpr->op!=TK_ALL ){
414 pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
415 pNew->a[pNew->nExpr-1].zName = a[k].zName;
416 a[k].pExpr = 0;
417 a[k].zName = 0;
418 }else{
419 for(i=0; i<pTabList->nId; i++){
420 Table *pTab = pTabList->a[i].pTab;
421 for(j=0; j<pTab->nCol; j++){
drh22f70c32002-02-18 01:17:00 +0000422 Expr *pExpr, *pLeft, *pRight;
423 pRight = sqliteExpr(TK_ID, 0, 0, 0);
424 if( pRight==0 ) break;
425 pRight->token.z = pTab->aCol[j].zName;
426 pRight->token.n = strlen(pTab->aCol[j].zName);
427 if( pTab->zName ){
428 pLeft = sqliteExpr(TK_ID, 0, 0, 0);
429 if( pLeft==0 ) break;
430 if( pTabList->a[i].zAlias && pTabList->a[i].zAlias[0] ){
431 pLeft->token.z = pTabList->a[i].zAlias;
432 pLeft->token.n = strlen(pTabList->a[i].zAlias);
433 }else{
434 pLeft->token.z = pTab->zName;
435 pLeft->token.n = strlen(pTab->zName);
436 }
437 pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
438 if( pExpr==0 ) break;
drh7c917d12001-12-16 20:05:05 +0000439 }else{
drh22f70c32002-02-18 01:17:00 +0000440 pExpr = pRight;
441 pExpr->span = pExpr->token;
drh7c917d12001-12-16 20:05:05 +0000442 }
drh7c917d12001-12-16 20:05:05 +0000443 pNew = sqliteExprListAppend(pNew, pExpr, 0);
444 }
drh17e24df2001-11-06 14:10:41 +0000445 }
drhd8bc7082000-06-07 23:51:50 +0000446 }
447 }
drh7c917d12001-12-16 20:05:05 +0000448 sqliteExprListDelete(pEList);
449 p->pEList = pNew;
drhd8bc7082000-06-07 23:51:50 +0000450 }
451 return 0;
452}
453
454/*
455** This routine associates entries in an ORDER BY expression list with
456** columns in a result. For each ORDER BY expression, the opcode of
drh967e8b72000-06-21 13:59:10 +0000457** the top-level node is changed to TK_COLUMN and the iColumn value of
drhd8bc7082000-06-07 23:51:50 +0000458** the top-level node is filled in with column number and the iTable
459** value of the top-level node is filled with iTable parameter.
460**
461** If there are prior SELECT clauses, they are processed first. A match
462** in an earlier SELECT takes precedence over a later SELECT.
463**
464** Any entry that does not match is flagged as an error. The number
465** of errors is returned.
466*/
467static int matchOrderbyToColumn(
468 Parse *pParse, /* A place to leave error messages */
469 Select *pSelect, /* Match to result columns of this SELECT */
470 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
471 int iTable, /* Insert this this value in iTable */
472 int mustComplete /* If TRUE all ORDER BYs must match */
473){
474 int nErr = 0;
475 int i, j;
476 ExprList *pEList;
477
drhdaffd0e2001-04-11 14:28:42 +0000478 if( pSelect==0 || pOrderBy==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +0000479 if( mustComplete ){
480 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
481 }
482 if( fillInColumnList(pParse, pSelect) ){
483 return 1;
484 }
485 if( pSelect->pPrior ){
drh92cd52f2000-06-08 01:55:29 +0000486 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
487 return 1;
488 }
drhd8bc7082000-06-07 23:51:50 +0000489 }
490 pEList = pSelect->pEList;
491 for(i=0; i<pOrderBy->nExpr; i++){
492 Expr *pE = pOrderBy->a[i].pExpr;
drh92cd52f2000-06-08 01:55:29 +0000493 int match = 0;
drhd8bc7082000-06-07 23:51:50 +0000494 if( pOrderBy->a[i].done ) continue;
495 for(j=0; j<pEList->nExpr; j++){
drh4cfa7932000-06-08 15:10:46 +0000496 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
497 char *zName = pEList->a[j].zName;
drh6e142f52000-06-08 13:36:40 +0000498 char *zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
drhd8bc7082000-06-07 23:51:50 +0000499 sqliteDequote(zLabel);
500 if( sqliteStrICmp(zName, zLabel)==0 ){
501 match = 1;
502 }
drh6e142f52000-06-08 13:36:40 +0000503 sqliteFree(zLabel);
drhd8bc7082000-06-07 23:51:50 +0000504 }
drh4cfa7932000-06-08 15:10:46 +0000505 if( match==0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
drhd8bc7082000-06-07 23:51:50 +0000506 match = 1;
507 }
508 if( match ){
drh967e8b72000-06-21 13:59:10 +0000509 pE->op = TK_COLUMN;
510 pE->iColumn = j;
drhd8bc7082000-06-07 23:51:50 +0000511 pE->iTable = iTable;
512 pOrderBy->a[i].done = 1;
513 break;
514 }
515 }
drh92cd52f2000-06-08 01:55:29 +0000516 if( !match && mustComplete ){
drhd8bc7082000-06-07 23:51:50 +0000517 char zBuf[30];
518 sprintf(zBuf,"%d",i+1);
519 sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf,
520 " does not match any result column", 0);
521 pParse->nErr++;
522 nErr++;
523 break;
524 }
525 }
526 return nErr;
527}
528
529/*
530** Get a VDBE for the given parser context. Create a new one if necessary.
531** If an error occurs, return NULL and leave a message in pParse.
532*/
533Vdbe *sqliteGetVdbe(Parse *pParse){
534 Vdbe *v = pParse->pVdbe;
535 if( v==0 ){
drh4c504392000-10-16 22:06:40 +0000536 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
drhd8bc7082000-06-07 23:51:50 +0000537 }
drhd8bc7082000-06-07 23:51:50 +0000538 return v;
539}
540
541
542/*
drh82c3d632000-06-06 21:56:07 +0000543** This routine is called to process a query that is really the union
544** or intersection of two or more separate queries.
545*/
546static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
drh10e5e3c2000-06-08 00:19:02 +0000547 int rc; /* Success code from a subroutine */
548 Select *pPrior; /* Another SELECT immediately to our left */
549 Vdbe *v; /* Generate code to this VDBE */
550 int base; /* Baseline value for pParse->nTab */
drh82c3d632000-06-06 21:56:07 +0000551
drhd8bc7082000-06-07 23:51:50 +0000552 /* Make sure there is no ORDER BY clause on prior SELECTs. Only the
553 ** last SELECT in the series may have an ORDER BY.
drh82c3d632000-06-06 21:56:07 +0000554 */
drhdaffd0e2001-04-11 14:28:42 +0000555 if( p==0 || p->pPrior==0 ) return 1;
drhd8bc7082000-06-07 23:51:50 +0000556 pPrior = p->pPrior;
557 if( pPrior->pOrderBy ){
558 sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
559 selectOpName(p->op), " not before", 0);
drh82c3d632000-06-06 21:56:07 +0000560 pParse->nErr++;
561 return 1;
562 }
563
drhd8bc7082000-06-07 23:51:50 +0000564 /* Make sure we have a valid query engine. If not, create a new one.
565 */
566 v = sqliteGetVdbe(pParse);
567 if( v==0 ) return 1;
568
569 /* Process the UNION or INTERSECTION
570 */
drh10e5e3c2000-06-08 00:19:02 +0000571 base = pParse->nTab;
drh82c3d632000-06-06 21:56:07 +0000572 switch( p->op ){
drhd8bc7082000-06-07 23:51:50 +0000573 case TK_ALL:
drh82c3d632000-06-06 21:56:07 +0000574 case TK_EXCEPT:
575 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +0000576 int unionTab; /* Cursor number of the temporary table holding result */
577 int op; /* One of the SRT_ operations to apply to self */
578 int priorOp; /* The SRT_ operation to apply to prior selects */
drh82c3d632000-06-06 21:56:07 +0000579
drhd8bc7082000-06-07 23:51:50 +0000580 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
581 if( eDest==priorOp ){
582 /* We can reuse a temporary table generated by a SELECT to our
583 ** right. This also means we are not the right-most select and so
584 ** we cannot have an ORDER BY clause
585 */
drh82c3d632000-06-06 21:56:07 +0000586 unionTab = iParm;
drhd8bc7082000-06-07 23:51:50 +0000587 assert( p->pOrderBy==0 );
drh82c3d632000-06-06 21:56:07 +0000588 }else{
drhd8bc7082000-06-07 23:51:50 +0000589 /* We will need to create our own temporary table to hold the
590 ** intermediate results.
591 */
592 unionTab = pParse->nTab++;
593 if( p->pOrderBy
594 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
595 return 1;
596 }
drhd8bc7082000-06-07 23:51:50 +0000597 if( p->op!=TK_ALL ){
drhc6b52df2002-01-04 03:09:29 +0000598 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
drh99fcd712001-10-13 01:06:47 +0000599 sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
drh345fda32001-01-15 22:51:08 +0000600 }else{
drh99fcd712001-10-13 01:06:47 +0000601 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +0000602 }
drh82c3d632000-06-06 21:56:07 +0000603 }
drhd8bc7082000-06-07 23:51:50 +0000604
605 /* Code the SELECT statements to our left
606 */
607 rc = sqliteSelect(pParse, pPrior, priorOp, unionTab);
drh82c3d632000-06-06 21:56:07 +0000608 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +0000609
610 /* Code the current SELECT statement
611 */
612 switch( p->op ){
613 case TK_EXCEPT: op = SRT_Except; break;
614 case TK_UNION: op = SRT_Union; break;
615 case TK_ALL: op = SRT_Table; break;
616 }
drh82c3d632000-06-06 21:56:07 +0000617 p->pPrior = 0;
618 rc = sqliteSelect(pParse, p, op, unionTab);
619 p->pPrior = pPrior;
620 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +0000621
622 /* Convert the data in the temporary table into whatever form
623 ** it is that we currently need.
624 */
625 if( eDest!=priorOp ){
drh6b563442001-11-07 16:48:26 +0000626 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +0000627 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +0000628 generateColumnNames(pParse, 0, p->pEList);
drh82c3d632000-06-06 21:56:07 +0000629 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +0000630 iCont = sqliteVdbeMakeLabel(v);
631 sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
632 iStart = sqliteVdbeCurrentAddr(v);
drh82c3d632000-06-06 21:56:07 +0000633 rc = selectInnerLoop(pParse, 0, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +0000634 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +0000635 iCont, iBreak);
636 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +0000637 sqliteVdbeResolveLabel(v, iCont);
638 sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
drh99fcd712001-10-13 01:06:47 +0000639 sqliteVdbeResolveLabel(v, iBreak);
640 sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
drhd8bc7082000-06-07 23:51:50 +0000641 if( p->pOrderBy ){
642 generateSortTail(v, p->pEList->nExpr);
643 }
drh82c3d632000-06-06 21:56:07 +0000644 }
645 break;
646 }
647 case TK_INTERSECT: {
648 int tab1, tab2;
drh6b563442001-11-07 16:48:26 +0000649 int iCont, iBreak, iStart;
drh82c3d632000-06-06 21:56:07 +0000650
drhd8bc7082000-06-07 23:51:50 +0000651 /* INTERSECT is different from the others since it requires
drh6206d502000-06-19 19:09:08 +0000652 ** two temporary tables. Hence it has its own case. Begin
drhd8bc7082000-06-07 23:51:50 +0000653 ** by allocating the tables we will need.
654 */
drh82c3d632000-06-06 21:56:07 +0000655 tab1 = pParse->nTab++;
656 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +0000657 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
658 return 1;
659 }
drhc6b52df2002-01-04 03:09:29 +0000660 sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
drh99fcd712001-10-13 01:06:47 +0000661 sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
drhd8bc7082000-06-07 23:51:50 +0000662
663 /* Code the SELECTs to our left into temporary table "tab1".
664 */
drh82c3d632000-06-06 21:56:07 +0000665 rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1);
666 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +0000667
668 /* Code the current SELECT into temporary table "tab2"
669 */
drhc6b52df2002-01-04 03:09:29 +0000670 sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
drh99fcd712001-10-13 01:06:47 +0000671 sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
drh82c3d632000-06-06 21:56:07 +0000672 p->pPrior = 0;
673 rc = sqliteSelect(pParse, p, SRT_Union, tab2);
674 p->pPrior = pPrior;
675 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +0000676
677 /* Generate code to take the intersection of the two temporary
678 ** tables.
679 */
drh82c3d632000-06-06 21:56:07 +0000680 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +0000681 generateColumnNames(pParse, 0, p->pEList);
drh82c3d632000-06-06 21:56:07 +0000682 iBreak = sqliteVdbeMakeLabel(v);
drh6b563442001-11-07 16:48:26 +0000683 iCont = sqliteVdbeMakeLabel(v);
684 sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
685 iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
drh99fcd712001-10-13 01:06:47 +0000686 sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
drh82c3d632000-06-06 21:56:07 +0000687 rc = selectInnerLoop(pParse, 0, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +0000688 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +0000689 iCont, iBreak);
690 if( rc ) return 1;
drh6b563442001-11-07 16:48:26 +0000691 sqliteVdbeResolveLabel(v, iCont);
692 sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
drh99fcd712001-10-13 01:06:47 +0000693 sqliteVdbeResolveLabel(v, iBreak);
694 sqliteVdbeAddOp(v, OP_Close, tab2, 0);
695 sqliteVdbeAddOp(v, OP_Close, tab1, 0);
drhd8bc7082000-06-07 23:51:50 +0000696 if( p->pOrderBy ){
697 generateSortTail(v, p->pEList->nExpr);
698 }
drh82c3d632000-06-06 21:56:07 +0000699 break;
700 }
701 }
702 assert( p->pEList && pPrior->pEList );
703 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
drhd8bc7082000-06-07 23:51:50 +0000704 sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ",
705 selectOpName(p->op), " do not have the same number of result columns", 0);
drh82c3d632000-06-06 21:56:07 +0000706 pParse->nErr++;
707 return 1;
drh22827922000-06-06 17:27:05 +0000708 }
drh10e5e3c2000-06-08 00:19:02 +0000709 pParse->nTab = base;
drh22827922000-06-06 17:27:05 +0000710 return 0;
711}
712
713/*
drh9562b552002-02-19 15:00:07 +0000714** Analyze the SELECT statement passed in as an argument to see if it
715** is a simple min() or max() query. If it is and this query can be
716** satisfied using a single seek to the beginning or end of an index,
717** then generate the code for this SELECT return 1. If this is not a
718** simple min() or max() query, then return 0;
719**
720** A simply min() or max() query looks like this:
721**
722** SELECT min(a) FROM table;
723** SELECT max(a) FROM table;
724**
725** The query may have only a single table in its FROM argument. There
726** can be no GROUP BY or HAVING or WHERE clauses. The result set must
727** be the min() or max() of a single column of the table. The column
728** in the min() or max() function must be indexed.
729**
730** The parameters to this routine are the same as for sqliteSelect().
731** See the header comment on that routine for additional information.
732*/
733static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
734 Expr *pExpr;
735 int iCol;
736 Table *pTab;
737 Index *pIdx;
738 int base;
739 Vdbe *v;
740 int openOp;
741 int seekOp;
742 int cont;
743 ExprList eList;
744 struct ExprList_item eListItem;
745
746 /* Check to see if this query is a simple min() or max() query. Return
747 ** zero if it is not.
748 */
749 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
750 if( p->pSrc->nId!=1 ) return 0;
751 if( p->pEList->nExpr!=1 ) return 0;
752 pExpr = p->pEList->a[0].pExpr;
753 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
754 if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
755 if( pExpr->iColumn!=FN_Min && pExpr->iColumn!=FN_Max ) return 0;
756 seekOp = pExpr->iColumn==FN_Min ? OP_Rewind : OP_Last;
757 pExpr = pExpr->pList->a[0].pExpr;
758 if( pExpr->op!=TK_COLUMN ) return 0;
759 iCol = pExpr->iColumn;
760 pTab = p->pSrc->a[0].pTab;
761
762 /* If we get to here, it means the query is of the correct form.
763 ** Check to make sure we have an index.
764 */
765 if( iCol<0 ){
766 pIdx = 0;
767 }else{
768 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
769 assert( pIdx->nColumn>=1 );
770 if( pIdx->aiColumn[0]==iCol ) break;
771 }
772 if( pIdx==0 ) return 0;
773 }
774
775 /* Identify column names if we will be using in the callback. This
776 ** step is skipped if the output is going to a table or a memory cell.
777 */
778 v = sqliteGetVdbe(pParse);
779 if( v==0 ) return 0;
780 if( eDest==SRT_Callback ){
781 generateColumnNames(pParse, p->pSrc, p->pEList);
782 }
783
784 /* Begin generating code
785 */
786 base = pParse->nTab;
787 eList.nExpr = 1;
788 memset(&eListItem, 0, sizeof(eListItem));
789 eList.a = &eListItem;
790 eList.a[0].pExpr = pExpr;
791 openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
792 sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
793 if( pIdx==0 ){
794 sqliteVdbeAddOp(v, seekOp, base, 0);
795 }else{
796 sqliteVdbeAddOp(v, openOp, base+1, pIdx->tnum);
797 sqliteVdbeAddOp(v, seekOp, base+1, 0);
798 sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
799 sqliteVdbeAddOp(v, OP_Close, base+1, 0);
800 sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
801 }
802 cont = sqliteVdbeMakeLabel(v);
803 selectInnerLoop(pParse, &eList, base, 1, 0, -1, eDest, iParm, cont, cont);
804 sqliteVdbeResolveLabel(v, cont);
805 sqliteVdbeAddOp(v, OP_Close, base, 0);
806 return 1;
807}
808
809/*
drh9bb61fe2000-06-05 16:01:39 +0000810** Generate code for the given SELECT statement.
811**
drhfef52082000-06-06 01:50:43 +0000812** The results are distributed in various ways depending on the
813** value of eDest and iParm.
814**
815** eDest Value Result
816** ------------ -------------------------------------------
817** SRT_Callback Invoke the callback for each row of the result.
818**
819** SRT_Mem Store first result in memory cell iParm
820**
821** SRT_Set Store results as keys of a table with cursor iParm
822**
drh82c3d632000-06-06 21:56:07 +0000823** SRT_Union Store results as a key in a temporary table iParm
824**
drhc4a3c772001-04-04 11:48:57 +0000825** SRT_Except Remove results form the temporary table iParm.
826**
827** SRT_Table Store results in temporary table iParm
drh9bb61fe2000-06-05 16:01:39 +0000828**
829** This routine returns the number of errors. If any errors are
830** encountered, then an appropriate error message is left in
831** pParse->zErrMsg.
832**
833** This routine does NOT free the Select structure passed in. The
834** calling function needs to do that.
835*/
836int sqliteSelect(
drhcce7d172000-05-31 15:34:51 +0000837 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +0000838 Select *p, /* The SELECT statement being coded. */
drh82c3d632000-06-06 21:56:07 +0000839 int eDest, /* One of: SRT_Callback Mem Set Union Except */
drhfef52082000-06-06 01:50:43 +0000840 int iParm /* Save result in this memory location, if >=0 */
drhcce7d172000-05-31 15:34:51 +0000841){
drhd8bc7082000-06-07 23:51:50 +0000842 int i;
drhcce7d172000-05-31 15:34:51 +0000843 WhereInfo *pWInfo;
844 Vdbe *v;
845 int isAgg = 0; /* True for select lists like "count(*)" */
drha2e00042002-01-22 03:13:42 +0000846 ExprList *pEList; /* List of columns to extract. */
drh9bb61fe2000-06-05 16:01:39 +0000847 IdList *pTabList; /* List of tables to select from */
848 Expr *pWhere; /* The WHERE clause. May be NULL */
849 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +0000850 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
851 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +0000852 int isDistinct; /* True if the DISTINCT keyword is present */
853 int distinct; /* Table to use for the distinct set */
drh10e5e3c2000-06-08 00:19:02 +0000854 int base; /* First cursor available for use */
drh1d83f052002-02-17 00:30:36 +0000855 int rc = 1; /* Value to return from this function */
drh9bb61fe2000-06-05 16:01:39 +0000856
drhdaffd0e2001-04-11 14:28:42 +0000857 if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
858
drh82c3d632000-06-06 21:56:07 +0000859 /* If there is are a sequence of queries, do the earlier ones first.
860 */
861 if( p->pPrior ){
862 return multiSelect(pParse, p, eDest, iParm);
863 }
864
865 /* Make local copies of the parameters for this query.
866 */
drh9bb61fe2000-06-05 16:01:39 +0000867 pTabList = p->pSrc;
868 pWhere = p->pWhere;
869 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +0000870 pGroupBy = p->pGroupBy;
871 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +0000872 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +0000873
drh10e5e3c2000-06-08 00:19:02 +0000874 /* Save the current value of pParse->nTab. Restore this value before
875 ** we exit.
876 */
877 base = pParse->nTab;
878
drh9bb61fe2000-06-05 16:01:39 +0000879 /*
880 ** Do not even attempt to generate any code if we have already seen
881 ** errors before this routine starts.
882 */
drh1d83f052002-02-17 00:30:36 +0000883 if( pParse->nErr>0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +0000884
drhd8bc7082000-06-07 23:51:50 +0000885 /* Look up every table in the table list and create an appropriate
886 ** columnlist in pEList if there isn't one already. (The parser leaves
drh967e8b72000-06-21 13:59:10 +0000887 ** a NULL in the p->pEList if the SQL said "SELECT * FROM ...")
drhcce7d172000-05-31 15:34:51 +0000888 */
drhd8bc7082000-06-07 23:51:50 +0000889 if( fillInColumnList(pParse, p) ){
drh1d83f052002-02-17 00:30:36 +0000890 goto select_end;
drhcce7d172000-05-31 15:34:51 +0000891 }
drhd8bc7082000-06-07 23:51:50 +0000892 pEList = p->pEList;
drh1d83f052002-02-17 00:30:36 +0000893 if( pEList==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +0000894
drh19a775c2000-06-05 18:54:46 +0000895 /* Allocate a temporary table to use for the DISTINCT set, if
drh22827922000-06-06 17:27:05 +0000896 ** necessary. This must be done early to allocate the cursor before
897 ** any calls to sqliteExprResolveIds().
drh19a775c2000-06-05 18:54:46 +0000898 */
899 if( isDistinct ){
900 distinct = pParse->nTab++;
drh22827922000-06-06 17:27:05 +0000901 }else{
902 distinct = -1;
drh19a775c2000-06-05 18:54:46 +0000903 }
904
drh22827922000-06-06 17:27:05 +0000905 /* If writing to memory or generating a set
906 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +0000907 */
drhfef52082000-06-06 01:50:43 +0000908 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
drh19a775c2000-06-05 18:54:46 +0000909 sqliteSetString(&pParse->zErrMsg, "only a single result allowed for "
910 "a SELECT that is part of an expression", 0);
911 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +0000912 goto select_end;
drh19a775c2000-06-05 18:54:46 +0000913 }
914
drh22827922000-06-06 17:27:05 +0000915 /* ORDER BY is ignored if we are not sending the result to a callback.
916 */
917 if( eDest!=SRT_Callback ){
918 pOrderBy = 0;
919 }
920
921 /* Allocate cursors for "expr IN (SELECT ...)" constructs.
drhcce7d172000-05-31 15:34:51 +0000922 */
923 for(i=0; i<pEList->nExpr; i++){
drh4794b982000-06-06 13:54:14 +0000924 sqliteExprResolveInSelect(pParse, pEList->a[i].pExpr);
925 }
926 if( pWhere ) sqliteExprResolveInSelect(pParse, pWhere);
927 if( pOrderBy ){
928 for(i=0; i<pOrderBy->nExpr; i++){
929 sqliteExprResolveInSelect(pParse, pOrderBy->a[i].pExpr);
930 }
931 }
drh22827922000-06-06 17:27:05 +0000932 if( pGroupBy ){
933 for(i=0; i<pGroupBy->nExpr; i++){
934 sqliteExprResolveInSelect(pParse, pGroupBy->a[i].pExpr);
935 }
936 }
937 if( pHaving ) sqliteExprResolveInSelect(pParse, pHaving);
938
drh10e5e3c2000-06-08 00:19:02 +0000939 /* At this point, we should have allocated all the cursors that we
940 ** need to handle subquerys and temporary tables. From here on we
941 ** are committed to keeping the same value for pParse->nTab.
942 **
drh967e8b72000-06-21 13:59:10 +0000943 ** Resolve the column names and do a semantics check on all the expressions.
drh22827922000-06-06 17:27:05 +0000944 */
drh4794b982000-06-06 13:54:14 +0000945 for(i=0; i<pEList->nExpr; i++){
drha2e00042002-01-22 03:13:42 +0000946 if( sqliteExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +0000947 goto select_end;
drhcce7d172000-05-31 15:34:51 +0000948 }
drh22827922000-06-06 17:27:05 +0000949 if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh1d83f052002-02-17 00:30:36 +0000950 goto select_end;
drhcce7d172000-05-31 15:34:51 +0000951 }
952 }
drhcce7d172000-05-31 15:34:51 +0000953 if( pWhere ){
drha2e00042002-01-22 03:13:42 +0000954 if( sqliteExprResolveIds(pParse, pTabList, pEList, pWhere) ){
drh1d83f052002-02-17 00:30:36 +0000955 goto select_end;
drhcce7d172000-05-31 15:34:51 +0000956 }
957 if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
drh1d83f052002-02-17 00:30:36 +0000958 goto select_end;
drhcce7d172000-05-31 15:34:51 +0000959 }
960 }
961 if( pOrderBy ){
962 for(i=0; i<pOrderBy->nExpr; i++){
drh22827922000-06-06 17:27:05 +0000963 Expr *pE = pOrderBy->a[i].pExpr;
drh92086432002-01-22 14:11:29 +0000964 if( sqliteExprIsConstant(pE) ){
965 sqliteSetString(&pParse->zErrMsg,
966 "ORDER BY expressions should not be constant", 0);
967 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +0000968 goto select_end;
drh92086432002-01-22 14:11:29 +0000969 }
drha2e00042002-01-22 03:13:42 +0000970 if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +0000971 goto select_end;
drhcce7d172000-05-31 15:34:51 +0000972 }
drh22827922000-06-06 17:27:05 +0000973 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +0000974 goto select_end;
drhcce7d172000-05-31 15:34:51 +0000975 }
976 }
977 }
drh22827922000-06-06 17:27:05 +0000978 if( pGroupBy ){
979 for(i=0; i<pGroupBy->nExpr; i++){
980 Expr *pE = pGroupBy->a[i].pExpr;
drh92086432002-01-22 14:11:29 +0000981 if( sqliteExprIsConstant(pE) ){
982 sqliteSetString(&pParse->zErrMsg,
983 "GROUP BY expressions should not be constant", 0);
984 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +0000985 goto select_end;
drh92086432002-01-22 14:11:29 +0000986 }
drha2e00042002-01-22 03:13:42 +0000987 if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
drh1d83f052002-02-17 00:30:36 +0000988 goto select_end;
drh22827922000-06-06 17:27:05 +0000989 }
990 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +0000991 goto select_end;
drh22827922000-06-06 17:27:05 +0000992 }
993 }
994 }
995 if( pHaving ){
996 if( pGroupBy==0 ){
drhda932812000-06-06 18:00:15 +0000997 sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required "
998 "before HAVING", 0);
drh22827922000-06-06 17:27:05 +0000999 pParse->nErr++;
drh1d83f052002-02-17 00:30:36 +00001000 goto select_end;
drh22827922000-06-06 17:27:05 +00001001 }
drha2e00042002-01-22 03:13:42 +00001002 if( sqliteExprResolveIds(pParse, pTabList, pEList, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00001003 goto select_end;
drh22827922000-06-06 17:27:05 +00001004 }
drhda932812000-06-06 18:00:15 +00001005 if( sqliteExprCheck(pParse, pHaving, isAgg, 0) ){
drh1d83f052002-02-17 00:30:36 +00001006 goto select_end;
drh22827922000-06-06 17:27:05 +00001007 }
drhcce7d172000-05-31 15:34:51 +00001008 }
1009
drh9562b552002-02-19 15:00:07 +00001010 /* Check for the special case of a min() or max() function by itself
1011 ** in the result set.
1012 */
1013 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
1014 goto select_end;
1015 }
1016
drhd820cb12002-02-18 03:21:45 +00001017 /* Begin generating code.
1018 */
1019 v = sqliteGetVdbe(pParse);
1020 if( v==0 ) goto select_end;
1021
1022 /* Generate code for all sub-queries in the FROM clause
1023 */
1024 for(i=0; i<pTabList->nId; i++){
1025 int oldNTab;
1026 Table *pTab = pTabList->a[i].pTab;
1027 if( !pTab->isTransient ) continue;
1028 assert( pTabList->a[i].pSelect!=0 );
1029 oldNTab = pParse->nTab;
1030 pParse->nTab += i+1;
1031 sqliteVdbeAddOp(v, OP_OpenTemp, oldNTab+i, 0);
1032 sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_Table, oldNTab+i);
1033 pParse->nTab = oldNTab;
1034 }
1035
drh22827922000-06-06 17:27:05 +00001036 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +00001037 */
drhd820cb12002-02-18 03:21:45 +00001038 sqliteAggregateInfoReset(pParse);
drh22827922000-06-06 17:27:05 +00001039 if( isAgg ){
drhaaf88722000-06-08 11:25:00 +00001040 assert( pParse->nAgg==0 && pParse->iAggCount<0 );
drh22827922000-06-06 17:27:05 +00001041 for(i=0; i<pEList->nExpr; i++){
1042 if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001043 goto select_end;
drh22827922000-06-06 17:27:05 +00001044 }
1045 }
1046 if( pGroupBy ){
1047 for(i=0; i<pGroupBy->nExpr; i++){
1048 if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001049 goto select_end;
drh22827922000-06-06 17:27:05 +00001050 }
1051 }
1052 }
1053 if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
drh1d83f052002-02-17 00:30:36 +00001054 goto select_end;
drh22827922000-06-06 17:27:05 +00001055 }
drh191b6902000-06-08 11:13:01 +00001056 if( pOrderBy ){
1057 for(i=0; i<pOrderBy->nExpr; i++){
1058 if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
drh1d83f052002-02-17 00:30:36 +00001059 goto select_end;
drh191b6902000-06-08 11:13:01 +00001060 }
1061 }
1062 }
drhefb72512000-05-31 20:00:52 +00001063 }
1064
drh9bbca4c2001-11-06 04:00:18 +00001065 /* Set the limiter
1066 */
1067 if( p->nLimit<=0 ){
1068 p->nOffset = 0;
1069 }else{
1070 if( p->nOffset<0 ) p->nOffset = 0;
1071 sqliteVdbeAddOp(v, OP_Limit, p->nLimit, p->nOffset);
1072 }
1073
1074
drh22827922000-06-06 17:27:05 +00001075 /* Identify column names if we will be using in the callback. This
drh19a775c2000-06-05 18:54:46 +00001076 ** step is skipped if the output is going to a table or a memory cell.
drhcce7d172000-05-31 15:34:51 +00001077 */
drhfef52082000-06-06 01:50:43 +00001078 if( eDest==SRT_Callback ){
drhd8bc7082000-06-07 23:51:50 +00001079 generateColumnNames(pParse, pTabList, pEList);
drhcce7d172000-05-31 15:34:51 +00001080 }
1081
drh22827922000-06-06 17:27:05 +00001082 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +00001083 */
1084 if( isAgg ){
drh99fcd712001-10-13 01:06:47 +00001085 sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
drh1bee3d72001-10-15 00:44:35 +00001086 if( pGroupBy==0 ){
1087 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh1bee3d72001-10-15 00:44:35 +00001088 sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
1089 for(i=0; i<pParse->nAgg; i++){
1090 Expr *pE;
1091 if( !pParse->aAgg[i].isAgg ) continue;
1092 pE = pParse->aAgg[i].pExpr;
1093 assert( pE==0 || pE->op==TK_AGG_FUNCTION );
1094 assert( pE==0 || (pE->pList!=0 && pE->pList->nExpr==1) );
1095 if( pE==0 || pE->iColumn==FN_Sum ){
1096 sqliteVdbeAddOp(v, OP_Integer, 0, 0);
1097 sqliteVdbeAddOp(v, OP_AggSet, 0, i);
1098 continue;
1099 }
1100 }
1101 }
drhcce7d172000-05-31 15:34:51 +00001102 }
1103
drh19a775c2000-06-05 18:54:46 +00001104 /* Initialize the memory cell to NULL
1105 */
drhfef52082000-06-06 01:50:43 +00001106 if( eDest==SRT_Mem ){
drh99fcd712001-10-13 01:06:47 +00001107 sqliteVdbeAddOp(v, OP_String, 0, 0);
drh8721ce42001-11-07 14:22:00 +00001108 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
drh19a775c2000-06-05 18:54:46 +00001109 }
1110
drhcce7d172000-05-31 15:34:51 +00001111 /* Begin the database scan
drhefb72512000-05-31 20:00:52 +00001112 */
drh19a775c2000-06-05 18:54:46 +00001113 if( isDistinct ){
drhc6b52df2002-01-04 03:09:29 +00001114 sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
drhefb72512000-05-31 20:00:52 +00001115 }
drhcce7d172000-05-31 15:34:51 +00001116 pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 0);
drh1d83f052002-02-17 00:30:36 +00001117 if( pWInfo==0 ) goto select_end;
drhcce7d172000-05-31 15:34:51 +00001118
drh22827922000-06-06 17:27:05 +00001119 /* Use the standard inner loop if we are not dealing with
1120 ** aggregates
drhcce7d172000-05-31 15:34:51 +00001121 */
drhda9d6c42000-05-31 18:20:14 +00001122 if( !isAgg ){
drh82c3d632000-06-06 21:56:07 +00001123 if( selectInnerLoop(pParse, pEList, 0, 0, pOrderBy, distinct, eDest, iParm,
drh22827922000-06-06 17:27:05 +00001124 pWInfo->iContinue, pWInfo->iBreak) ){
drh1d83f052002-02-17 00:30:36 +00001125 goto select_end;
drhda9d6c42000-05-31 18:20:14 +00001126 }
drhcce7d172000-05-31 15:34:51 +00001127 }
drhefb72512000-05-31 20:00:52 +00001128
drh22827922000-06-06 17:27:05 +00001129 /* If we are dealing with aggregates, then to the special aggregate
1130 ** processing.
drhefb72512000-05-31 20:00:52 +00001131 */
drh22827922000-06-06 17:27:05 +00001132 else{
drh22827922000-06-06 17:27:05 +00001133 if( pGroupBy ){
drh1bee3d72001-10-15 00:44:35 +00001134 int lbl1;
drh22827922000-06-06 17:27:05 +00001135 for(i=0; i<pGroupBy->nExpr; i++){
1136 sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
1137 }
drh99fcd712001-10-13 01:06:47 +00001138 sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
drh1bee3d72001-10-15 00:44:35 +00001139 lbl1 = sqliteVdbeMakeLabel(v);
drh99fcd712001-10-13 01:06:47 +00001140 sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
drh22827922000-06-06 17:27:05 +00001141 for(i=0; i<pParse->nAgg; i++){
1142 if( pParse->aAgg[i].isAgg ) continue;
1143 sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
drh99fcd712001-10-13 01:06:47 +00001144 sqliteVdbeAddOp(v, OP_AggSet, 0, i);
drhcce7d172000-05-31 15:34:51 +00001145 }
drh22827922000-06-06 17:27:05 +00001146 sqliteVdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +00001147 }
drh22827922000-06-06 17:27:05 +00001148 for(i=0; i<pParse->nAgg; i++){
1149 Expr *pE;
1150 int op;
1151 if( !pParse->aAgg[i].isAgg ) continue;
1152 pE = pParse->aAgg[i].pExpr;
1153 if( pE==0 ){
drh99fcd712001-10-13 01:06:47 +00001154 sqliteVdbeAddOp(v, OP_AggIncr, 1, i);
drh22827922000-06-06 17:27:05 +00001155 continue;
1156 }
1157 assert( pE->op==TK_AGG_FUNCTION );
1158 assert( pE->pList!=0 && pE->pList->nExpr==1 );
1159 sqliteExprCode(pParse, pE->pList->a[0].pExpr);
drh99fcd712001-10-13 01:06:47 +00001160 sqliteVdbeAddOp(v, OP_AggGet, 0, i);
drh967e8b72000-06-21 13:59:10 +00001161 switch( pE->iColumn ){
drh22827922000-06-06 17:27:05 +00001162 case FN_Min: op = OP_Min; break;
1163 case FN_Max: op = OP_Max; break;
1164 case FN_Avg: op = OP_Add; break;
1165 case FN_Sum: op = OP_Add; break;
1166 }
drh99fcd712001-10-13 01:06:47 +00001167 sqliteVdbeAddOp(v, op, 0, 0);
1168 sqliteVdbeAddOp(v, OP_AggSet, 0, i);
drh22827922000-06-06 17:27:05 +00001169 }
drhcce7d172000-05-31 15:34:51 +00001170 }
1171
drh22827922000-06-06 17:27:05 +00001172
drhcce7d172000-05-31 15:34:51 +00001173 /* End the database scan loop.
1174 */
1175 sqliteWhereEnd(pWInfo);
1176
drh22827922000-06-06 17:27:05 +00001177 /* If we are processing aggregates, we need to set up a second loop
1178 ** over all of the aggregate values and process them.
1179 */
1180 if( isAgg ){
1181 int endagg = sqliteVdbeMakeLabel(v);
1182 int startagg;
drh99fcd712001-10-13 01:06:47 +00001183 startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
drh22827922000-06-06 17:27:05 +00001184 pParse->useAgg = 1;
1185 if( pHaving ){
1186 sqliteExprIfFalse(pParse, pHaving, startagg);
1187 }
drh82c3d632000-06-06 21:56:07 +00001188 if( selectInnerLoop(pParse, pEList, 0, 0, pOrderBy, distinct, eDest, iParm,
drh22827922000-06-06 17:27:05 +00001189 startagg, endagg) ){
drh1d83f052002-02-17 00:30:36 +00001190 goto select_end;
drh22827922000-06-06 17:27:05 +00001191 }
drh99fcd712001-10-13 01:06:47 +00001192 sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
1193 sqliteVdbeResolveLabel(v, endagg);
1194 sqliteVdbeAddOp(v, OP_Noop, 0, 0);
drh22827922000-06-06 17:27:05 +00001195 pParse->useAgg = 0;
1196 }
1197
drhcce7d172000-05-31 15:34:51 +00001198 /* If there is an ORDER BY clause, then we need to sort the results
1199 ** and send them to the callback one by one.
1200 */
1201 if( pOrderBy ){
drhd8bc7082000-06-07 23:51:50 +00001202 generateSortTail(v, pEList->nExpr);
drhcce7d172000-05-31 15:34:51 +00001203 }
drh10e5e3c2000-06-08 00:19:02 +00001204 pParse->nTab = base;
drh6a535342001-10-19 16:44:56 +00001205
1206
1207 /* Issue a null callback if that is what the user wants.
1208 */
1209 if( (pParse->db->flags & SQLITE_NullCallback)!=0 && eDest==SRT_Callback ){
1210 sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
1211 }
1212
drh1d83f052002-02-17 00:30:36 +00001213 /* The SELECT was successfully coded. Set the return code to 0
1214 ** to indicate no errors.
1215 */
1216 rc = 0;
1217
1218 /* Control jumps to here if an error is encountered above, or upon
1219 ** successful coding of the SELECT.
1220 */
1221select_end:
1222 sqliteAggregateInfoReset(pParse);
1223 return rc;
drhcce7d172000-05-31 15:34:51 +00001224}