blob: d524b1a17e08dad3d935212543b0662159df1a2b [file] [log] [blame]
drhcce7d172000-05-31 15:34:51 +00001/*
2** Copyright (c) 1999, 2000 D. Richard Hipp
3**
4** This program is free software; you can redistribute it and/or
5** modify it under the terms of the GNU General Public
6** License as published by the Free Software Foundation; either
7** version 2 of the License, or (at your option) any later version.
8**
9** This program is distributed in the hope that it will be useful,
10** but WITHOUT ANY WARRANTY; without even the implied warranty of
11** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12** General Public License for more details.
13**
14** You should have received a copy of the GNU General Public
15** License along with this library; if not, write to the
16** Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17** Boston, MA 02111-1307, USA.
18**
19** Author contact information:
20** drh@hwaci.com
21** http://www.hwaci.com/drh/
22**
23*************************************************************************
24** This file contains C code routines that are called by the parser
25** to handle SELECT statements.
26**
drhd8bc7082000-06-07 23:51:50 +000027** $Id: select.c,v 1.16 2000/06/07 23:51:50 drh Exp $
drhcce7d172000-05-31 15:34:51 +000028*/
29#include "sqliteInt.h"
30
drhcce7d172000-05-31 15:34:51 +000031/*
drh9bb61fe2000-06-05 16:01:39 +000032** Allocate a new Select structure and return a pointer to that
33** structure.
drhcce7d172000-05-31 15:34:51 +000034*/
drh9bb61fe2000-06-05 16:01:39 +000035Select *sqliteSelectNew(
36 ExprList *pEList,
37 IdList *pSrc,
38 Expr *pWhere,
39 ExprList *pGroupBy,
40 Expr *pHaving,
41 ExprList *pOrderBy,
42 int isDistinct
43){
44 Select *pNew;
45 pNew = sqliteMalloc( sizeof(*pNew) );
46 if( pNew==0 ) return 0;
47 pNew->pEList = pEList;
48 pNew->pSrc = pSrc;
49 pNew->pWhere = pWhere;
50 pNew->pGroupBy = pGroupBy;
51 pNew->pHaving = pHaving;
52 pNew->pOrderBy = pOrderBy;
53 pNew->isDistinct = isDistinct;
drh82c3d632000-06-06 21:56:07 +000054 pNew->op = TK_SELECT;
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*/
76void sqliteParseInfoReset(Parse *pParse){
77 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
89** result row. Except if pEList==NULL, then we just read nField
90** 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 */
96 int nField, /* Number of fields 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;
106
107 /* Pull the requested fields.
108 */
drh82c3d632000-06-06 21:56:07 +0000109 if( pEList ){
110 for(i=0; i<pEList->nExpr; i++){
111 sqliteExprCode(pParse, pEList->a[i].pExpr);
112 }
113 nField = pEList->nExpr;
114 }else{
115 for(i=0; i<nField; i++){
116 sqliteVdbeAddOp(v, OP_Field, srcTab, i, 0, 0);
117 }
drh22827922000-06-06 17:27:05 +0000118 }
119
120 /* If the current result is not distinct, skip the rest
121 ** of the processing for the current row.
122 */
123 if( distinct>=0 ){
124 int lbl = sqliteVdbeMakeLabel(v);
125 sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1, 0, 0);
126 sqliteVdbeAddOp(v, OP_Distinct, distinct, lbl, 0, 0);
127 sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0, 0, 0);
128 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue, 0, 0);
129 sqliteVdbeAddOp(v, OP_String, 0, 0, "", lbl);
130 sqliteVdbeAddOp(v, OP_Put, distinct, 0, 0, 0);
131 }
drh82c3d632000-06-06 21:56:07 +0000132
drh22827922000-06-06 17:27:05 +0000133 /* If there is an ORDER BY clause, then store the results
134 ** in a sorter.
135 */
136 if( pOrderBy ){
137 char *zSortOrder;
drhd8bc7082000-06-07 23:51:50 +0000138 sqliteVdbeAddOp(v, OP_SortMakeRec, nField, 0, 0, 0);
drh22827922000-06-06 17:27:05 +0000139 zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
140 if( zSortOrder==0 ) return 1;
141 for(i=0; i<pOrderBy->nExpr; i++){
drhd8bc7082000-06-07 23:51:50 +0000142 zSortOrder[i] = pOrderBy->a[i].sortOrder ? '-' : '+';
drh22827922000-06-06 17:27:05 +0000143 sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
144 }
145 zSortOrder[pOrderBy->nExpr] = 0;
146 sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0, zSortOrder, 0);
147 sqliteVdbeAddOp(v, OP_SortPut, 0, 0, 0, 0);
148 }else
149
drh82c3d632000-06-06 21:56:07 +0000150 /* In this mode, write each query result to the key of the temporary
151 ** table iParm.
drh22827922000-06-06 17:27:05 +0000152 */
drh82c3d632000-06-06 21:56:07 +0000153 if( eDest==SRT_Union ){
154 sqliteVdbeAddOp(v, OP_MakeRecord, nField, 0, 0, 0);
155 sqliteVdbeAddOp(v, OP_String, iParm, 0, "", 0);
156 sqliteVdbeAddOp(v, OP_Put, iParm, 0, 0, 0);
157 }else
158
drh5974a302000-06-07 14:42:26 +0000159 /* Store the result as data using a unique key.
160 */
161 if( eDest==SRT_Table ){
162 sqliteVdbeAddOp(v, OP_MakeRecord, nField, 0, 0, 0);
163 sqliteVdbeAddOp(v, OP_New, iParm, 0, 0, 0);
164 sqliteVdbeAddOp(v, OP_Pull, 1, 0, 0, 0);
165 sqliteVdbeAddOp(v, OP_Put, iParm, 0, 0, 0);
166 }else
167
drh82c3d632000-06-06 21:56:07 +0000168 /* Construct a record from the query result, but instead of
169 ** saving that record, use it as a key to delete elements from
170 ** the temporary table iParm.
171 */
172 if( eDest==SRT_Except ){
drh1ecec3c2000-06-06 22:13:55 +0000173 sqliteVdbeAddOp(v, OP_MakeRecord, nField, 0, 0, 0);
174 sqliteVdbeAddOp(v, OP_Delete, iParm, 0, 0, 0);
drh22827922000-06-06 17:27:05 +0000175 }else
176
177 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
178 ** then there should be a single item on the stack. Write this
179 ** item into the set table with bogus data.
180 */
181 if( eDest==SRT_Set ){
drhd8bc7082000-06-07 23:51:50 +0000182 assert( nField==1 );
drh22827922000-06-06 17:27:05 +0000183 sqliteVdbeAddOp(v, OP_String, 0, 0, "", 0);
184 sqliteVdbeAddOp(v, OP_Put, iParm, 0, 0, 0);
185 }else
186
drh82c3d632000-06-06 21:56:07 +0000187
drh22827922000-06-06 17:27:05 +0000188 /* If this is a scalar select that is part of an expression, then
189 ** store the results in the appropriate memory cell and break out
190 ** of the scan loop.
191 */
192 if( eDest==SRT_Mem ){
drhd8bc7082000-06-07 23:51:50 +0000193 assert( nField==1 );
drh22827922000-06-06 17:27:05 +0000194 sqliteVdbeAddOp(v, OP_MemStore, iParm, 0, 0, 0);
195 sqliteVdbeAddOp(v, OP_Goto, 0, iBreak, 0, 0);
196 }else
197
198 /* If none of the above, send the data to the callback function.
199 */
200 {
drh82c3d632000-06-06 21:56:07 +0000201 sqliteVdbeAddOp(v, OP_Callback, nField, 0, 0, 0);
202 }
203 return 0;
204}
205
206/*
drhd8bc7082000-06-07 23:51:50 +0000207** If the inner loop was generated using a non-null pOrderBy argument,
208** then the results were placed in a sorter. After the loop is terminated
209** we need to run the sorter and output the results. The following
210** routine generates the code needed to do that.
211*/
212static void generateSortTail(Vdbe *v, int nField){
213 int end = sqliteVdbeMakeLabel(v);
214 int addr;
215 sqliteVdbeAddOp(v, OP_Sort, 0, 0, 0, 0);
216 addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end, 0, 0);
217 sqliteVdbeAddOp(v, OP_SortCallback, nField, 0, 0, 0);
218 sqliteVdbeAddOp(v, OP_Goto, 0, addr, 0, 0);
219 sqliteVdbeAddOp(v, OP_SortClose, 0, 0, 0, end);
220}
221
222/*
drh82c3d632000-06-06 21:56:07 +0000223** Generate code that will tell the VDBE how many columns there
224** are in the result and the name for each column. This information
225** is used to provide "argc" and "azCol[]" values in the callback.
226*/
drhd8bc7082000-06-07 23:51:50 +0000227static
228void generateColumnNames(Parse *pParse, IdList *pTabList, ExprList *pEList){
229 Vdbe *v = pParse->pVdbe;
drh82c3d632000-06-06 21:56:07 +0000230 int i;
drhd8bc7082000-06-07 23:51:50 +0000231 if( pParse->colNamesSet ) return;
232 pParse->colNamesSet = 1;
drh82c3d632000-06-06 21:56:07 +0000233 sqliteVdbeAddOp(v, OP_ColumnCount, pEList->nExpr, 0, 0, 0);
234 for(i=0; i<pEList->nExpr; i++){
235 Expr *p;
236 if( pEList->a[i].zName ){
237 char *zName = pEList->a[i].zName;
drhd8bc7082000-06-07 23:51:50 +0000238 sqliteVdbeAddOp(v, OP_ColumnName, i, 0, zName, 0);
drh82c3d632000-06-06 21:56:07 +0000239 continue;
240 }
241 p = pEList->a[i].pExpr;
242 if( p->op!=TK_FIELD || pTabList==0 ){
243 char zName[30];
drh5974a302000-06-07 14:42:26 +0000244 sprintf(zName, "column%d", i+1);
drh82c3d632000-06-06 21:56:07 +0000245 sqliteVdbeAddOp(v, OP_ColumnName, i, 0, zName, 0);
246 }else{
247 if( pTabList->nId>1 ){
248 char *zName = 0;
249 Table *pTab = pTabList->a[p->iTable].pTab;
250 char *zTab;
251
252 zTab = pTabList->a[p->iTable].zAlias;
253 if( zTab==0 ) zTab = pTab->zName;
254 sqliteSetString(&zName, zTab, ".", pTab->aCol[p->iField].zName, 0);
255 sqliteVdbeAddOp(v, OP_ColumnName, i, 0, zName, 0);
256 sqliteFree(zName);
257 }else{
258 Table *pTab = pTabList->a[0].pTab;
259 char *zName = pTab->aCol[p->iField].zName;
260 sqliteVdbeAddOp(v, OP_ColumnName, i, 0, zName, 0);
261 }
262 }
263 }
264}
265
266/*
drhd8bc7082000-06-07 23:51:50 +0000267** Name of the connection operator, used for error messages.
268*/
269static const char *selectOpName(int id){
270 char *z;
271 switch( id ){
272 case TK_ALL: z = "UNION ALL"; break;
273 case TK_INTERSECT: z = "INTERSECT"; break;
274 case TK_EXCEPT: z = "EXCEPT"; break;
275 default: z = "UNION"; break;
276 }
277 return z;
278}
279
280/*
281** For the given SELECT statement, do two things.
282**
283** (1) Fill in the pTab fields of the IdList that defines the set
284** of tables we are scanning.
285**
286** (2) If the columns to be extracted variable (pEList) is NULL
287** (meaning that a "*" was used in the SQL statement) then
288** create a fake pEList containing the names of all columns
289** of all tables.
290**
291** Return 0 on success. If there are problems, leave an error message
292** in pParse and return non-zero.
293*/
294static int fillInColumnList(Parse *pParse, Select *p){
295 int i, j;
296 IdList *pTabList = p->pSrc;
297 ExprList *pEList = p->pEList;
298
299 /* Look up every table in the table list.
300 */
301 for(i=0; i<pTabList->nId; i++){
302 if( pTabList->a[i].pTab ){
303 /* This routine has run before! No need to continue */
304 return 0;
305 }
306 pTabList->a[i].pTab = sqliteFindTable(pParse->db, pTabList->a[i].zName);
307 if( pTabList->a[i].pTab==0 ){
308 sqliteSetString(&pParse->zErrMsg, "no such table: ",
309 pTabList->a[i].zName, 0);
310 pParse->nErr++;
311 return 1;
312 }
313 }
314
315 /* If the list of columns to retrieve is "*" then replace it with
316 ** a list of all columns from all tables.
317 */
318 if( pEList==0 ){
319 for(i=0; i<pTabList->nId; i++){
320 Table *pTab = pTabList->a[i].pTab;
321 for(j=0; j<pTab->nCol; j++){
322 Expr *pExpr = sqliteExpr(TK_DOT, 0, 0, 0);
323 pExpr->pLeft = sqliteExpr(TK_ID, 0, 0, 0);
324 pExpr->pLeft->token.z = pTab->zName;
325 pExpr->pLeft->token.n = strlen(pTab->zName);
326 pExpr->pRight = sqliteExpr(TK_ID, 0, 0, 0);
327 pExpr->pRight->token.z = pTab->aCol[j].zName;
328 pExpr->pRight->token.n = strlen(pTab->aCol[j].zName);
329 pEList = sqliteExprListAppend(pEList, pExpr, 0);
330 }
331 }
332 p->pEList = pEList;
333 }
334 return 0;
335}
336
337/*
338** This routine associates entries in an ORDER BY expression list with
339** columns in a result. For each ORDER BY expression, the opcode of
340** the top-level node is changed to TK_FIELD and the iField value of
341** the top-level node is filled in with column number and the iTable
342** value of the top-level node is filled with iTable parameter.
343**
344** If there are prior SELECT clauses, they are processed first. A match
345** in an earlier SELECT takes precedence over a later SELECT.
346**
347** Any entry that does not match is flagged as an error. The number
348** of errors is returned.
349*/
350static int matchOrderbyToColumn(
351 Parse *pParse, /* A place to leave error messages */
352 Select *pSelect, /* Match to result columns of this SELECT */
353 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
354 int iTable, /* Insert this this value in iTable */
355 int mustComplete /* If TRUE all ORDER BYs must match */
356){
357 int nErr = 0;
358 int i, j;
359 ExprList *pEList;
360
361 assert( pSelect && pOrderBy );
362 if( mustComplete ){
363 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
364 }
365 if( fillInColumnList(pParse, pSelect) ){
366 return 1;
367 }
368 if( pSelect->pPrior ){
369 matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0);
370 }
371 pEList = pSelect->pEList;
372 for(i=0; i<pOrderBy->nExpr; i++){
373 Expr *pE = pOrderBy->a[i].pExpr;
374 if( pOrderBy->a[i].done ) continue;
375 for(j=0; j<pEList->nExpr; j++){
376 int match = 0;
377 if( pEList->a[i].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
378 char *zName = pEList->a[i].zName;
379 char *zLabel = 0;
380 sqliteSetString(&zLabel, pE->token.z, pE->token.n, 0);
381 sqliteDequote(zLabel);
382 if( sqliteStrICmp(zName, zLabel)==0 ){
383 match = 1;
384 }
385 }
386 if( match==0 && sqliteExprCompare(pE, pEList->a[i].pExpr) ){
387 match = 1;
388 }
389 if( match ){
390 pE->op = TK_FIELD;
391 pE->iField = j;
392 pE->iTable = iTable;
393 pOrderBy->a[i].done = 1;
394 break;
395 }
396 }
397 if( mustComplete ){
398 char zBuf[30];
399 sprintf(zBuf,"%d",i+1);
400 sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf,
401 " does not match any result column", 0);
402 pParse->nErr++;
403 nErr++;
404 break;
405 }
406 }
407 return nErr;
408}
409
410/*
411** Get a VDBE for the given parser context. Create a new one if necessary.
412** If an error occurs, return NULL and leave a message in pParse.
413*/
414Vdbe *sqliteGetVdbe(Parse *pParse){
415 Vdbe *v = pParse->pVdbe;
416 if( v==0 ){
417 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db->pBe);
418 }
419 if( v==0 ){
420 sqliteSetString(&pParse->zErrMsg, "out of memory", 0);
421 pParse->nErr++;
422 }
423 return v;
424}
425
426
427/*
drh82c3d632000-06-06 21:56:07 +0000428** This routine is called to process a query that is really the union
429** or intersection of two or more separate queries.
430*/
431static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
432 int rc;
433 Select *pPrior;
434 Vdbe *v;
drh82c3d632000-06-06 21:56:07 +0000435
drhd8bc7082000-06-07 23:51:50 +0000436 /* Make sure there is no ORDER BY clause on prior SELECTs. Only the
437 ** last SELECT in the series may have an ORDER BY.
drh82c3d632000-06-06 21:56:07 +0000438 */
drhd8bc7082000-06-07 23:51:50 +0000439 assert( p->pPrior!=0 );
440 pPrior = p->pPrior;
441 if( pPrior->pOrderBy ){
442 sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
443 selectOpName(p->op), " not before", 0);
drh82c3d632000-06-06 21:56:07 +0000444 pParse->nErr++;
445 return 1;
446 }
447
drhd8bc7082000-06-07 23:51:50 +0000448 /* Make sure we have a valid query engine. If not, create a new one.
449 */
450 v = sqliteGetVdbe(pParse);
451 if( v==0 ) return 1;
452
453 /* Process the UNION or INTERSECTION
454 */
drh82c3d632000-06-06 21:56:07 +0000455 switch( p->op ){
drhd8bc7082000-06-07 23:51:50 +0000456 case TK_ALL:
drh82c3d632000-06-06 21:56:07 +0000457 case TK_EXCEPT:
458 case TK_UNION: {
drhd8bc7082000-06-07 23:51:50 +0000459 int unionTab; /* Cursor number of the temporary table holding result */
460 int op; /* One of the SRT_ operations to apply to self */
461 int priorOp; /* The SRT_ operation to apply to prior selects */
drh82c3d632000-06-06 21:56:07 +0000462
drhd8bc7082000-06-07 23:51:50 +0000463 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
464 if( eDest==priorOp ){
465 /* We can reuse a temporary table generated by a SELECT to our
466 ** right. This also means we are not the right-most select and so
467 ** we cannot have an ORDER BY clause
468 */
drh82c3d632000-06-06 21:56:07 +0000469 unionTab = iParm;
drhd8bc7082000-06-07 23:51:50 +0000470 assert( p->pOrderBy==0 );
drh82c3d632000-06-06 21:56:07 +0000471 }else{
drhd8bc7082000-06-07 23:51:50 +0000472 /* We will need to create our own temporary table to hold the
473 ** intermediate results.
474 */
475 unionTab = pParse->nTab++;
476 if( p->pOrderBy
477 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
478 return 1;
479 }
drh82c3d632000-06-06 21:56:07 +0000480 sqliteVdbeAddOp(v, OP_Open, unionTab, 1, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000481 if( p->op!=TK_ALL ){
482 sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1, 0, 0);
483 }
drh82c3d632000-06-06 21:56:07 +0000484 }
drhd8bc7082000-06-07 23:51:50 +0000485
486 /* Code the SELECT statements to our left
487 */
488 rc = sqliteSelect(pParse, pPrior, priorOp, unionTab);
drh82c3d632000-06-06 21:56:07 +0000489 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +0000490
491 /* Code the current SELECT statement
492 */
493 switch( p->op ){
494 case TK_EXCEPT: op = SRT_Except; break;
495 case TK_UNION: op = SRT_Union; break;
496 case TK_ALL: op = SRT_Table; break;
497 }
drh82c3d632000-06-06 21:56:07 +0000498 p->pPrior = 0;
499 rc = sqliteSelect(pParse, p, op, unionTab);
500 p->pPrior = pPrior;
501 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +0000502
503 /* Convert the data in the temporary table into whatever form
504 ** it is that we currently need.
505 */
506 if( eDest!=priorOp ){
drh82c3d632000-06-06 21:56:07 +0000507 int iCont, iBreak;
508 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +0000509 generateColumnNames(pParse, 0, p->pEList);
drh82c3d632000-06-06 21:56:07 +0000510 iBreak = sqliteVdbeMakeLabel(v);
511 iCont = sqliteVdbeAddOp(v, OP_Next, unionTab, iBreak, 0, 0);
512 rc = selectInnerLoop(pParse, 0, unionTab, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +0000513 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +0000514 iCont, iBreak);
515 if( rc ) return 1;
516 sqliteVdbeAddOp(v, OP_Goto, 0, iCont, 0, 0);
517 sqliteVdbeAddOp(v, OP_Close, unionTab, 0, 0, iBreak);
drhd8bc7082000-06-07 23:51:50 +0000518 if( p->pOrderBy ){
519 generateSortTail(v, p->pEList->nExpr);
520 }
drh82c3d632000-06-06 21:56:07 +0000521 }
522 break;
523 }
524 case TK_INTERSECT: {
525 int tab1, tab2;
drh82c3d632000-06-06 21:56:07 +0000526 int iCont, iBreak;
527
drhd8bc7082000-06-07 23:51:50 +0000528 /* INTERSECT is different from the others since it requires
529 ** two temporary tables. Hence it has its own case. Begine
530 ** by allocating the tables we will need.
531 */
drh82c3d632000-06-06 21:56:07 +0000532 tab1 = pParse->nTab++;
533 tab2 = pParse->nTab++;
drhd8bc7082000-06-07 23:51:50 +0000534 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
535 return 1;
536 }
drh82c3d632000-06-06 21:56:07 +0000537 sqliteVdbeAddOp(v, OP_Open, tab1, 1, 0, 0);
538 sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000539
540 /* Code the SELECTs to our left into temporary table "tab1".
541 */
drh82c3d632000-06-06 21:56:07 +0000542 rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1);
543 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +0000544
545 /* Code the current SELECT into temporary table "tab2"
546 */
drh82c3d632000-06-06 21:56:07 +0000547 sqliteVdbeAddOp(v, OP_Open, tab2, 1, 0, 0);
548 sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1, 0, 0);
549 p->pPrior = 0;
550 rc = sqliteSelect(pParse, p, SRT_Union, tab2);
551 p->pPrior = pPrior;
552 if( rc ) return rc;
drhd8bc7082000-06-07 23:51:50 +0000553
554 /* Generate code to take the intersection of the two temporary
555 ** tables.
556 */
drh82c3d632000-06-06 21:56:07 +0000557 assert( p->pEList );
drhd8bc7082000-06-07 23:51:50 +0000558 generateColumnNames(pParse, 0, p->pEList);
drh82c3d632000-06-06 21:56:07 +0000559 iBreak = sqliteVdbeMakeLabel(v);
560 iCont = sqliteVdbeAddOp(v, OP_Next, tab1, iBreak, 0, 0);
561 sqliteVdbeAddOp(v, OP_Key, tab1, 0, 0, 0);
562 sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont, 0, 0);
563 rc = selectInnerLoop(pParse, 0, tab1, p->pEList->nExpr,
drhd8bc7082000-06-07 23:51:50 +0000564 p->pOrderBy, -1, eDest, iParm,
drh82c3d632000-06-06 21:56:07 +0000565 iCont, iBreak);
566 if( rc ) return 1;
567 sqliteVdbeAddOp(v, OP_Goto, 0, iCont, 0, 0);
568 sqliteVdbeAddOp(v, OP_Close, tab2, 0, 0, iBreak);
569 sqliteVdbeAddOp(v, OP_Close, tab1, 0, 0, 0);
drhd8bc7082000-06-07 23:51:50 +0000570 if( p->pOrderBy ){
571 generateSortTail(v, p->pEList->nExpr);
572 }
drh82c3d632000-06-06 21:56:07 +0000573 break;
574 }
575 }
576 assert( p->pEList && pPrior->pEList );
577 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
drhd8bc7082000-06-07 23:51:50 +0000578 sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ",
579 selectOpName(p->op), " do not have the same number of result columns", 0);
drh82c3d632000-06-06 21:56:07 +0000580 pParse->nErr++;
581 return 1;
drh22827922000-06-06 17:27:05 +0000582 }
583 return 0;
584}
585
586/*
drh9bb61fe2000-06-05 16:01:39 +0000587** Generate code for the given SELECT statement.
588**
drhfef52082000-06-06 01:50:43 +0000589** The results are distributed in various ways depending on the
590** value of eDest and iParm.
591**
592** eDest Value Result
593** ------------ -------------------------------------------
594** SRT_Callback Invoke the callback for each row of the result.
595**
596** SRT_Mem Store first result in memory cell iParm
597**
598** SRT_Set Store results as keys of a table with cursor iParm
599**
drh82c3d632000-06-06 21:56:07 +0000600** SRT_Union Store results as a key in a temporary table iParm
601**
602** SRT_Except Remove results form the temporary talbe iParm.
drh9bb61fe2000-06-05 16:01:39 +0000603**
604** This routine returns the number of errors. If any errors are
605** encountered, then an appropriate error message is left in
606** pParse->zErrMsg.
607**
608** This routine does NOT free the Select structure passed in. The
609** calling function needs to do that.
610*/
611int sqliteSelect(
drhcce7d172000-05-31 15:34:51 +0000612 Parse *pParse, /* The parser context */
drh9bb61fe2000-06-05 16:01:39 +0000613 Select *p, /* The SELECT statement being coded. */
drh82c3d632000-06-06 21:56:07 +0000614 int eDest, /* One of: SRT_Callback Mem Set Union Except */
drhfef52082000-06-06 01:50:43 +0000615 int iParm /* Save result in this memory location, if >=0 */
drhcce7d172000-05-31 15:34:51 +0000616){
drhd8bc7082000-06-07 23:51:50 +0000617 int i;
drhcce7d172000-05-31 15:34:51 +0000618 WhereInfo *pWInfo;
619 Vdbe *v;
620 int isAgg = 0; /* True for select lists like "count(*)" */
drh9bb61fe2000-06-05 16:01:39 +0000621 ExprList *pEList; /* List of fields to extract. NULL means "*" */
622 IdList *pTabList; /* List of tables to select from */
623 Expr *pWhere; /* The WHERE clause. May be NULL */
624 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
drh22827922000-06-06 17:27:05 +0000625 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
626 Expr *pHaving; /* The HAVING clause. May be NULL */
drh19a775c2000-06-05 18:54:46 +0000627 int isDistinct; /* True if the DISTINCT keyword is present */
628 int distinct; /* Table to use for the distinct set */
drh9bb61fe2000-06-05 16:01:39 +0000629
drh82c3d632000-06-06 21:56:07 +0000630 /* If there is are a sequence of queries, do the earlier ones first.
631 */
632 if( p->pPrior ){
633 return multiSelect(pParse, p, eDest, iParm);
634 }
635
636 /* Make local copies of the parameters for this query.
637 */
drh9bb61fe2000-06-05 16:01:39 +0000638 pTabList = p->pSrc;
639 pWhere = p->pWhere;
640 pOrderBy = p->pOrderBy;
drh22827922000-06-06 17:27:05 +0000641 pGroupBy = p->pGroupBy;
642 pHaving = p->pHaving;
drh19a775c2000-06-05 18:54:46 +0000643 isDistinct = p->isDistinct;
drh9bb61fe2000-06-05 16:01:39 +0000644
645 /*
646 ** Do not even attempt to generate any code if we have already seen
647 ** errors before this routine starts.
648 */
649 if( pParse->nErr>0 ) return 0;
drh22827922000-06-06 17:27:05 +0000650 sqliteParseInfoReset(pParse);
drhcce7d172000-05-31 15:34:51 +0000651
drhd8bc7082000-06-07 23:51:50 +0000652 /* Look up every table in the table list and create an appropriate
653 ** columnlist in pEList if there isn't one already. (The parser leaves
654 ** a NULL in the pEList field if the SQL said "SELECT * FROM ...")
drhcce7d172000-05-31 15:34:51 +0000655 */
drhd8bc7082000-06-07 23:51:50 +0000656 if( fillInColumnList(pParse, p) ){
657 return 1;
drhcce7d172000-05-31 15:34:51 +0000658 }
drhd8bc7082000-06-07 23:51:50 +0000659 pEList = p->pEList;
drhcce7d172000-05-31 15:34:51 +0000660
drh19a775c2000-06-05 18:54:46 +0000661 /* Allocate a temporary table to use for the DISTINCT set, if
drh22827922000-06-06 17:27:05 +0000662 ** necessary. This must be done early to allocate the cursor before
663 ** any calls to sqliteExprResolveIds().
drh19a775c2000-06-05 18:54:46 +0000664 */
665 if( isDistinct ){
666 distinct = pParse->nTab++;
drh22827922000-06-06 17:27:05 +0000667 }else{
668 distinct = -1;
drh19a775c2000-06-05 18:54:46 +0000669 }
670
drh22827922000-06-06 17:27:05 +0000671 /* If writing to memory or generating a set
672 ** only a single column may be output.
drh19a775c2000-06-05 18:54:46 +0000673 */
drhfef52082000-06-06 01:50:43 +0000674 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
drh19a775c2000-06-05 18:54:46 +0000675 sqliteSetString(&pParse->zErrMsg, "only a single result allowed for "
676 "a SELECT that is part of an expression", 0);
677 pParse->nErr++;
678 return 1;
679 }
680
drh22827922000-06-06 17:27:05 +0000681 /* ORDER BY is ignored if we are not sending the result to a callback.
682 */
683 if( eDest!=SRT_Callback ){
684 pOrderBy = 0;
685 }
686
687 /* Allocate cursors for "expr IN (SELECT ...)" constructs.
drhcce7d172000-05-31 15:34:51 +0000688 */
689 for(i=0; i<pEList->nExpr; i++){
drh4794b982000-06-06 13:54:14 +0000690 sqliteExprResolveInSelect(pParse, pEList->a[i].pExpr);
691 }
692 if( pWhere ) sqliteExprResolveInSelect(pParse, pWhere);
693 if( pOrderBy ){
694 for(i=0; i<pOrderBy->nExpr; i++){
695 sqliteExprResolveInSelect(pParse, pOrderBy->a[i].pExpr);
696 }
697 }
drh22827922000-06-06 17:27:05 +0000698 if( pGroupBy ){
699 for(i=0; i<pGroupBy->nExpr; i++){
700 sqliteExprResolveInSelect(pParse, pGroupBy->a[i].pExpr);
701 }
702 }
703 if( pHaving ) sqliteExprResolveInSelect(pParse, pHaving);
704
705 /* Resolve the field names and do a semantics check on all the expressions.
706 */
drh4794b982000-06-06 13:54:14 +0000707 for(i=0; i<pEList->nExpr; i++){
drhcce7d172000-05-31 15:34:51 +0000708 if( sqliteExprResolveIds(pParse, pTabList, pEList->a[i].pExpr) ){
drh9bb61fe2000-06-05 16:01:39 +0000709 return 1;
drhcce7d172000-05-31 15:34:51 +0000710 }
drh22827922000-06-06 17:27:05 +0000711 if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
drh9bb61fe2000-06-05 16:01:39 +0000712 return 1;
drhcce7d172000-05-31 15:34:51 +0000713 }
714 }
drhcce7d172000-05-31 15:34:51 +0000715 if( pWhere ){
716 if( sqliteExprResolveIds(pParse, pTabList, pWhere) ){
drh9bb61fe2000-06-05 16:01:39 +0000717 return 1;
drhcce7d172000-05-31 15:34:51 +0000718 }
719 if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
drh9bb61fe2000-06-05 16:01:39 +0000720 return 1;
drhcce7d172000-05-31 15:34:51 +0000721 }
722 }
723 if( pOrderBy ){
724 for(i=0; i<pOrderBy->nExpr; i++){
drh22827922000-06-06 17:27:05 +0000725 Expr *pE = pOrderBy->a[i].pExpr;
726 if( sqliteExprResolveIds(pParse, pTabList, pE) ){
drh9bb61fe2000-06-05 16:01:39 +0000727 return 1;
drhcce7d172000-05-31 15:34:51 +0000728 }
drh22827922000-06-06 17:27:05 +0000729 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
drh9bb61fe2000-06-05 16:01:39 +0000730 return 1;
drhcce7d172000-05-31 15:34:51 +0000731 }
732 }
733 }
drh22827922000-06-06 17:27:05 +0000734 if( pGroupBy ){
735 for(i=0; i<pGroupBy->nExpr; i++){
736 Expr *pE = pGroupBy->a[i].pExpr;
737 if( sqliteExprResolveIds(pParse, pTabList, pE) ){
738 return 1;
739 }
740 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
741 return 1;
742 }
743 }
744 }
745 if( pHaving ){
746 if( pGroupBy==0 ){
drhda932812000-06-06 18:00:15 +0000747 sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required "
748 "before HAVING", 0);
drh22827922000-06-06 17:27:05 +0000749 pParse->nErr++;
750 return 1;
751 }
752 if( sqliteExprResolveIds(pParse, pTabList, pHaving) ){
753 return 1;
754 }
drhda932812000-06-06 18:00:15 +0000755 if( sqliteExprCheck(pParse, pHaving, isAgg, 0) ){
drh22827922000-06-06 17:27:05 +0000756 return 1;
757 }
drhcce7d172000-05-31 15:34:51 +0000758 }
759
drh22827922000-06-06 17:27:05 +0000760 /* Do an analysis of aggregate expressions.
drhefb72512000-05-31 20:00:52 +0000761 */
drh22827922000-06-06 17:27:05 +0000762 if( isAgg ){
763 for(i=0; i<pEList->nExpr; i++){
764 if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
765 return 1;
766 }
767 }
768 if( pGroupBy ){
769 for(i=0; i<pGroupBy->nExpr; i++){
770 if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
771 return 1;
772 }
773 }
774 }
775 if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
776 return 1;
777 }
drhefb72512000-05-31 20:00:52 +0000778 }
779
drhcce7d172000-05-31 15:34:51 +0000780 /* Begin generating code.
781 */
782 v = pParse->pVdbe;
783 if( v==0 ){
784 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db->pBe);
785 }
drh9bb61fe2000-06-05 16:01:39 +0000786 if( v==0 ){
787 sqliteSetString(&pParse->zErrMsg, "out of memory", 0);
788 pParse->nErr++;
789 return 1;
790 }
drhcce7d172000-05-31 15:34:51 +0000791 if( pOrderBy ){
792 sqliteVdbeAddOp(v, OP_SortOpen, 0, 0, 0, 0);
793 }
794
drh22827922000-06-06 17:27:05 +0000795 /* Identify column names if we will be using in the callback. This
drh19a775c2000-06-05 18:54:46 +0000796 ** step is skipped if the output is going to a table or a memory cell.
drhcce7d172000-05-31 15:34:51 +0000797 */
drhfef52082000-06-06 01:50:43 +0000798 if( eDest==SRT_Callback ){
drhd8bc7082000-06-07 23:51:50 +0000799 generateColumnNames(pParse, pTabList, pEList);
drhcce7d172000-05-31 15:34:51 +0000800 }
801
drh22827922000-06-06 17:27:05 +0000802 /* Reset the aggregator
drhcce7d172000-05-31 15:34:51 +0000803 */
804 if( isAgg ){
drh22827922000-06-06 17:27:05 +0000805 sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg, 0, 0);
drhcce7d172000-05-31 15:34:51 +0000806 }
807
drh19a775c2000-06-05 18:54:46 +0000808 /* Initialize the memory cell to NULL
809 */
drhfef52082000-06-06 01:50:43 +0000810 if( eDest==SRT_Mem ){
drh19a775c2000-06-05 18:54:46 +0000811 sqliteVdbeAddOp(v, OP_Null, 0, 0, 0, 0);
drhfef52082000-06-06 01:50:43 +0000812 sqliteVdbeAddOp(v, OP_MemStore, iParm, 0, 0, 0);
drh19a775c2000-06-05 18:54:46 +0000813 }
814
drhcce7d172000-05-31 15:34:51 +0000815 /* Begin the database scan
drhefb72512000-05-31 20:00:52 +0000816 */
drh19a775c2000-06-05 18:54:46 +0000817 if( isDistinct ){
drheec553b2000-06-02 01:51:20 +0000818 sqliteVdbeAddOp(v, OP_Open, distinct, 1, 0, 0);
drhefb72512000-05-31 20:00:52 +0000819 }
drhcce7d172000-05-31 15:34:51 +0000820 pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 0);
drh9bb61fe2000-06-05 16:01:39 +0000821 if( pWInfo==0 ) return 1;
drhcce7d172000-05-31 15:34:51 +0000822
drh22827922000-06-06 17:27:05 +0000823 /* Use the standard inner loop if we are not dealing with
824 ** aggregates
drhcce7d172000-05-31 15:34:51 +0000825 */
drhda9d6c42000-05-31 18:20:14 +0000826 if( !isAgg ){
drh82c3d632000-06-06 21:56:07 +0000827 if( selectInnerLoop(pParse, pEList, 0, 0, pOrderBy, distinct, eDest, iParm,
drh22827922000-06-06 17:27:05 +0000828 pWInfo->iContinue, pWInfo->iBreak) ){
829 return 1;
drhda9d6c42000-05-31 18:20:14 +0000830 }
drhcce7d172000-05-31 15:34:51 +0000831 }
drhefb72512000-05-31 20:00:52 +0000832
drh22827922000-06-06 17:27:05 +0000833 /* If we are dealing with aggregates, then to the special aggregate
834 ** processing.
drhefb72512000-05-31 20:00:52 +0000835 */
drh22827922000-06-06 17:27:05 +0000836 else{
837 int doFocus;
838 if( pGroupBy ){
839 for(i=0; i<pGroupBy->nExpr; i++){
840 sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
841 }
842 sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0, 0, 0);
843 doFocus = 1;
844 }else{
845 doFocus = 0;
846 for(i=0; i<pParse->nAgg; i++){
847 if( !pParse->aAgg[i].isAgg ){
848 doFocus = 1;
849 break;
850 }
851 }
852 if( doFocus ){
853 sqliteVdbeAddOp(v, OP_String, 0, 0, "", 0);
854 }
drhcce7d172000-05-31 15:34:51 +0000855 }
drh22827922000-06-06 17:27:05 +0000856 if( doFocus ){
857 int lbl1 = sqliteVdbeMakeLabel(v);
858 sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1, 0, 0);
859 for(i=0; i<pParse->nAgg; i++){
860 if( pParse->aAgg[i].isAgg ) continue;
861 sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
862 sqliteVdbeAddOp(v, OP_AggSet, 0, i, 0, 0);
drhcce7d172000-05-31 15:34:51 +0000863 }
drh22827922000-06-06 17:27:05 +0000864 sqliteVdbeResolveLabel(v, lbl1);
drhcce7d172000-05-31 15:34:51 +0000865 }
drh22827922000-06-06 17:27:05 +0000866 for(i=0; i<pParse->nAgg; i++){
867 Expr *pE;
868 int op;
869 if( !pParse->aAgg[i].isAgg ) continue;
870 pE = pParse->aAgg[i].pExpr;
871 if( pE==0 ){
872 sqliteVdbeAddOp(v, OP_AggIncr, 1, i, 0, 0);
873 continue;
874 }
875 assert( pE->op==TK_AGG_FUNCTION );
876 assert( pE->pList!=0 && pE->pList->nExpr==1 );
877 sqliteExprCode(pParse, pE->pList->a[0].pExpr);
878 sqliteVdbeAddOp(v, OP_AggGet, 0, i, 0, 0);
879 switch( pE->iField ){
880 case FN_Min: op = OP_Min; break;
881 case FN_Max: op = OP_Max; break;
882 case FN_Avg: op = OP_Add; break;
883 case FN_Sum: op = OP_Add; break;
884 }
885 sqliteVdbeAddOp(v, op, 0, 0, 0, 0);
886 sqliteVdbeAddOp(v, OP_AggSet, 0, i, 0, 0);
887 }
drhcce7d172000-05-31 15:34:51 +0000888 }
889
drh22827922000-06-06 17:27:05 +0000890
drhcce7d172000-05-31 15:34:51 +0000891 /* End the database scan loop.
892 */
893 sqliteWhereEnd(pWInfo);
894
drh22827922000-06-06 17:27:05 +0000895 /* If we are processing aggregates, we need to set up a second loop
896 ** over all of the aggregate values and process them.
897 */
898 if( isAgg ){
899 int endagg = sqliteVdbeMakeLabel(v);
900 int startagg;
901 startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg, 0, 0);
902 pParse->useAgg = 1;
903 if( pHaving ){
904 sqliteExprIfFalse(pParse, pHaving, startagg);
905 }
drh82c3d632000-06-06 21:56:07 +0000906 if( selectInnerLoop(pParse, pEList, 0, 0, pOrderBy, distinct, eDest, iParm,
drh22827922000-06-06 17:27:05 +0000907 startagg, endagg) ){
908 return 1;
909 }
910 sqliteVdbeAddOp(v, OP_Goto, 0, startagg, 0, 0);
911 sqliteVdbeAddOp(v, OP_Noop, 0, 0, 0, endagg);
912 pParse->useAgg = 0;
913 }
914
drhcce7d172000-05-31 15:34:51 +0000915 /* If there is an ORDER BY clause, then we need to sort the results
916 ** and send them to the callback one by one.
917 */
918 if( pOrderBy ){
drhd8bc7082000-06-07 23:51:50 +0000919 generateSortTail(v, pEList->nExpr);
drhcce7d172000-05-31 15:34:51 +0000920 }
drh9bb61fe2000-06-05 16:01:39 +0000921 return 0;
drhcce7d172000-05-31 15:34:51 +0000922}