1 /* 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 ** [email protected] 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 ** 27 ** $Id: select.c,v 1.26 2000/07/29 13:06:59 drh Exp $ 28 */ 29 #include "sqliteInt.h" 30 31 /* 32 ** Allocate a new Select structure and return a pointer to that 33 ** structure. 34 */ 35 Select *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; 54 pNew->op = TK_SELECT; 55 return pNew; 56 } 57 58 /* 59 ** Delete the given Select structure and all of its substructures. 60 */ 61 void sqliteSelectDelete(Select *p){ 62 if( p==0 ) return; 63 sqliteExprListDelete(p->pEList); 64 sqliteIdListDelete(p->pSrc); 65 sqliteExprDelete(p->pWhere); 66 sqliteExprListDelete(p->pGroupBy); 67 sqliteExprDelete(p->pHaving); 68 sqliteExprListDelete(p->pOrderBy); 69 sqliteSelectDelete(p->pPrior); 70 sqliteFree(p); 71 } 72 73 /* 74 ** Delete the aggregate information from the parse structure. 75 */ 76 void 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. 87 ** 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 nColumn 90 ** elements from the srcTab table. 91 */ 92 static int selectInnerLoop( 93 Parse *pParse, /* The parser context */ 94 ExprList *pEList, /* List of values being extracted */ 95 int srcTab, /* Pull data from this table */ 96 int nColumn, /* Number of columns in the source table */ 97 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 columns. 108 */ 109 if( pEList ){ 110 for(i=0; i<pEList->nExpr; i++){ 111 sqliteExprCode(pParse, pEList->a[i].pExpr); 112 } 113 nColumn = pEList->nExpr; 114 }else{ 115 for(i=0; i<nColumn; i++){ 116 sqliteVdbeAddOp(v, OP_Field, srcTab, i, 0, 0); 117 } 118 } 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 } 132 133 /* If there is an ORDER BY clause, then store the results 134 ** in a sorter. 135 */ 136 if( pOrderBy ){ 137 char *zSortOrder; 138 sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0, 0, 0); 139 zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 ); 140 if( zSortOrder==0 ) return 1; 141 for(i=0; i<pOrderBy->nExpr; i++){ 142 zSortOrder[i] = pOrderBy->a[i].sortOrder ? '-' : '+'; 143 sqliteExprCode(pParse, pOrderBy->a[i].pExpr); 144 } 145 zSortOrder[pOrderBy->nExpr] = 0; 146 sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0, zSortOrder, 0); 147 sqliteFree(zSortOrder); 148 sqliteVdbeAddOp(v, OP_SortPut, 0, 0, 0, 0); 149 }else 150 151 /* In this mode, write each query result to the key of the temporary 152 ** table iParm. 153 */ 154 if( eDest==SRT_Union ){ 155 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0, 0, 0); 156 sqliteVdbeAddOp(v, OP_String, iParm, 0, "", 0); 157 sqliteVdbeAddOp(v, OP_Put, iParm, 0, 0, 0); 158 }else 159 160 /* Store the result as data using a unique key. 161 */ 162 if( eDest==SRT_Table ){ 163 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0, 0, 0); 164 sqliteVdbeAddOp(v, OP_New, iParm, 0, 0, 0); 165 sqliteVdbeAddOp(v, OP_Pull, 1, 0, 0, 0); 166 sqliteVdbeAddOp(v, OP_Put, iParm, 0, 0, 0); 167 }else 168 169 /* Construct a record from the query result, but instead of 170 ** saving that record, use it as a key to delete elements from 171 ** the temporary table iParm. 172 */ 173 if( eDest==SRT_Except ){ 174 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0, 0, 0); 175 sqliteVdbeAddOp(v, OP_Delete, iParm, 0, 0, 0); 176 }else 177 178 /* If we are creating a set for an "expr IN (SELECT ...)" construct, 179 ** then there should be a single item on the stack. Write this 180 ** item into the set table with bogus data. 181 */ 182 if( eDest==SRT_Set ){ 183 assert( nColumn==1 ); 184 sqliteVdbeAddOp(v, OP_String, 0, 0, "", 0); 185 sqliteVdbeAddOp(v, OP_Put, iParm, 0, 0, 0); 186 }else 187 188 189 /* If this is a scalar select that is part of an expression, then 190 ** store the results in the appropriate memory cell and break out 191 ** of the scan loop. 192 */ 193 if( eDest==SRT_Mem ){ 194 assert( nColumn==1 ); 195 sqliteVdbeAddOp(v, OP_MemStore, iParm, 0, 0, 0); 196 sqliteVdbeAddOp(v, OP_Goto, 0, iBreak, 0, 0); 197 }else 198 199 /* If none of the above, send the data to the callback function. 200 */ 201 { 202 sqliteVdbeAddOp(v, OP_Callback, nColumn, 0, 0, 0); 203 } 204 return 0; 205 } 206 207 /* 208 ** If the inner loop was generated using a non-null pOrderBy argument, 209 ** then the results were placed in a sorter. After the loop is terminated 210 ** we need to run the sorter and output the results. The following 211 ** routine generates the code needed to do that. 212 */ 213 static void generateSortTail(Vdbe *v, int nColumn){ 214 int end = sqliteVdbeMakeLabel(v); 215 int addr; 216 sqliteVdbeAddOp(v, OP_Sort, 0, 0, 0, 0); 217 addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end, 0, 0); 218 sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0, 0, 0); 219 sqliteVdbeAddOp(v, OP_Goto, 0, addr, 0, 0); 220 sqliteVdbeAddOp(v, OP_SortClose, 0, 0, 0, end); 221 } 222 223 /* 224 ** Generate code that will tell the VDBE how many columns there 225 ** are in the result and the name for each column. This information 226 ** is used to provide "argc" and "azCol[]" values in the callback. 227 */ 228 static 229 void generateColumnNames(Parse *pParse, IdList *pTabList, ExprList *pEList){ 230 Vdbe *v = pParse->pVdbe; 231 int i; 232 if( pParse->colNamesSet ) return; 233 pParse->colNamesSet = 1; 234 sqliteVdbeAddOp(v, OP_ColumnCount, pEList->nExpr, 0, 0, 0); 235 for(i=0; i<pEList->nExpr; i++){ 236 Expr *p; 237 int addr; 238 if( pEList->a[i].zName ){ 239 char *zName = pEList->a[i].zName; 240 sqliteVdbeAddOp(v, OP_ColumnName, i, 0, zName, 0); 241 continue; 242 } 243 p = pEList->a[i].pExpr; 244 if( p->span.z && p->span.z[0] ){ 245 addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0, 0, 0); 246 sqliteVdbeChangeP3(v, addr, p->span.z, p->span.n); 247 sqliteVdbeCompressSpace(v, addr); 248 }else if( p->op!=TK_COLUMN || pTabList==0 ){ 249 char zName[30]; 250 sprintf(zName, "column%d", i+1); 251 sqliteVdbeAddOp(v, OP_ColumnName, i, 0, zName, 0); 252 }else{ 253 if( pTabList->nId>1 ){ 254 char *zName = 0; 255 Table *pTab = pTabList->a[p->iTable].pTab; 256 char *zTab; 257 258 zTab = pTabList->a[p->iTable].zAlias; 259 if( zTab==0 ) zTab = pTab->zName; 260 sqliteSetString(&zName, zTab, ".", pTab->aCol[p->iColumn].zName, 0); 261 sqliteVdbeAddOp(v, OP_ColumnName, i, 0, zName, 0); 262 sqliteFree(zName); 263 }else{ 264 Table *pTab = pTabList->a[0].pTab; 265 char *zName = pTab->aCol[p->iColumn].zName; 266 sqliteVdbeAddOp(v, OP_ColumnName, i, 0, zName, 0); 267 } 268 } 269 } 270 } 271 272 /* 273 ** Name of the connection operator, used for error messages. 274 */ 275 static const char *selectOpName(int id){ 276 char *z; 277 switch( id ){ 278 case TK_ALL: z = "UNION ALL"; break; 279 case TK_INTERSECT: z = "INTERSECT"; break; 280 case TK_EXCEPT: z = "EXCEPT"; break; 281 default: z = "UNION"; break; 282 } 283 return z; 284 } 285 286 /* 287 ** For the given SELECT statement, do two things. 288 ** 289 ** (1) Fill in the pTabList->a[].pTab fields in the IdList that 290 ** defines the set of tables that should be scanned. 291 ** 292 ** (2) If the columns to be extracted variable (pEList) is NULL 293 ** (meaning that a "*" was used in the SQL statement) then 294 ** create a fake pEList containing the names of all columns 295 ** of all tables. 296 ** 297 ** Return 0 on success. If there are problems, leave an error message 298 ** in pParse and return non-zero. 299 */ 300 static int fillInColumnList(Parse *pParse, Select *p){ 301 int i, j; 302 IdList *pTabList = p->pSrc; 303 ExprList *pEList = p->pEList; 304 305 /* Look up every table in the table list. 306 */ 307 for(i=0; i<pTabList->nId; i++){ 308 if( pTabList->a[i].pTab ){ 309 /* This routine has run before! No need to continue */ 310 return 0; 311 } 312 pTabList->a[i].pTab = sqliteFindTable(pParse->db, pTabList->a[i].zName); 313 if( pTabList->a[i].pTab==0 ){ 314 sqliteSetString(&pParse->zErrMsg, "no such table: ", 315 pTabList->a[i].zName, 0); 316 pParse->nErr++; 317 return 1; 318 } 319 } 320 321 /* If the list of columns to retrieve is "*" then replace it with 322 ** a list of all columns from all tables. 323 */ 324 if( pEList==0 ){ 325 for(i=0; i<pTabList->nId; i++){ 326 Table *pTab = pTabList->a[i].pTab; 327 for(j=0; j<pTab->nCol; j++){ 328 Expr *pExpr = sqliteExpr(TK_DOT, 0, 0, 0); 329 pExpr->pLeft = sqliteExpr(TK_ID, 0, 0, 0); 330 pExpr->pLeft->token.z = pTab->zName; 331 pExpr->pLeft->token.n = strlen(pTab->zName); 332 pExpr->pRight = sqliteExpr(TK_ID, 0, 0, 0); 333 pExpr->pRight->token.z = pTab->aCol[j].zName; 334 pExpr->pRight->token.n = strlen(pTab->aCol[j].zName); 335 pExpr->span.z = ""; 336 pExpr->span.n = 0; 337 pEList = sqliteExprListAppend(pEList, pExpr, 0); 338 } 339 } 340 p->pEList = pEList; 341 } 342 return 0; 343 } 344 345 /* 346 ** This routine associates entries in an ORDER BY expression list with 347 ** columns in a result. For each ORDER BY expression, the opcode of 348 ** the top-level node is changed to TK_COLUMN and the iColumn value of 349 ** the top-level node is filled in with column number and the iTable 350 ** value of the top-level node is filled with iTable parameter. 351 ** 352 ** If there are prior SELECT clauses, they are processed first. A match 353 ** in an earlier SELECT takes precedence over a later SELECT. 354 ** 355 ** Any entry that does not match is flagged as an error. The number 356 ** of errors is returned. 357 */ 358 static int matchOrderbyToColumn( 359 Parse *pParse, /* A place to leave error messages */ 360 Select *pSelect, /* Match to result columns of this SELECT */ 361 ExprList *pOrderBy, /* The ORDER BY values to match against columns */ 362 int iTable, /* Insert this this value in iTable */ 363 int mustComplete /* If TRUE all ORDER BYs must match */ 364 ){ 365 int nErr = 0; 366 int i, j; 367 ExprList *pEList; 368 369 assert( pSelect && pOrderBy ); 370 if( mustComplete ){ 371 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; } 372 } 373 if( fillInColumnList(pParse, pSelect) ){ 374 return 1; 375 } 376 if( pSelect->pPrior ){ 377 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){ 378 return 1; 379 } 380 } 381 pEList = pSelect->pEList; 382 for(i=0; i<pOrderBy->nExpr; i++){ 383 Expr *pE = pOrderBy->a[i].pExpr; 384 int match = 0; 385 if( pOrderBy->a[i].done ) continue; 386 for(j=0; j<pEList->nExpr; j++){ 387 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){ 388 char *zName = pEList->a[j].zName; 389 char *zLabel = sqliteStrNDup(pE->token.z, pE->token.n); 390 sqliteDequote(zLabel); 391 if( sqliteStrICmp(zName, zLabel)==0 ){ 392 match = 1; 393 } 394 sqliteFree(zLabel); 395 } 396 if( match==0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){ 397 match = 1; 398 } 399 if( match ){ 400 pE->op = TK_COLUMN; 401 pE->iColumn = j; 402 pE->iTable = iTable; 403 pOrderBy->a[i].done = 1; 404 break; 405 } 406 } 407 if( !match && mustComplete ){ 408 char zBuf[30]; 409 sprintf(zBuf,"%d",i+1); 410 sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf, 411 " does not match any result column", 0); 412 pParse->nErr++; 413 nErr++; 414 break; 415 } 416 } 417 return nErr; 418 } 419 420 /* 421 ** Get a VDBE for the given parser context. Create a new one if necessary. 422 ** If an error occurs, return NULL and leave a message in pParse. 423 */ 424 Vdbe *sqliteGetVdbe(Parse *pParse){ 425 Vdbe *v = pParse->pVdbe; 426 if( v==0 ){ 427 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db->pBe); 428 } 429 if( v==0 ){ 430 sqliteSetString(&pParse->zErrMsg, "out of memory", 0); 431 pParse->nErr++; 432 } 433 return v; 434 } 435 436 437 /* 438 ** This routine is called to process a query that is really the union 439 ** or intersection of two or more separate queries. 440 */ 441 static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){ 442 int rc; /* Success code from a subroutine */ 443 Select *pPrior; /* Another SELECT immediately to our left */ 444 Vdbe *v; /* Generate code to this VDBE */ 445 int base; /* Baseline value for pParse->nTab */ 446 447 /* Make sure there is no ORDER BY clause on prior SELECTs. Only the 448 ** last SELECT in the series may have an ORDER BY. 449 */ 450 assert( p->pPrior!=0 ); 451 pPrior = p->pPrior; 452 if( pPrior->pOrderBy ){ 453 sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ", 454 selectOpName(p->op), " not before", 0); 455 pParse->nErr++; 456 return 1; 457 } 458 459 /* Make sure we have a valid query engine. If not, create a new one. 460 */ 461 v = sqliteGetVdbe(pParse); 462 if( v==0 ) return 1; 463 464 /* Process the UNION or INTERSECTION 465 */ 466 base = pParse->nTab; 467 switch( p->op ){ 468 case TK_ALL: 469 case TK_EXCEPT: 470 case TK_UNION: { 471 int unionTab; /* Cursor number of the temporary table holding result */ 472 int op; /* One of the SRT_ operations to apply to self */ 473 int priorOp; /* The SRT_ operation to apply to prior selects */ 474 475 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union; 476 if( eDest==priorOp ){ 477 /* We can reuse a temporary table generated by a SELECT to our 478 ** right. This also means we are not the right-most select and so 479 ** we cannot have an ORDER BY clause 480 */ 481 unionTab = iParm; 482 assert( p->pOrderBy==0 ); 483 }else{ 484 /* We will need to create our own temporary table to hold the 485 ** intermediate results. 486 */ 487 unionTab = pParse->nTab++; 488 if( p->pOrderBy 489 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){ 490 return 1; 491 } 492 sqliteVdbeAddOp(v, OP_Open, unionTab, 1, 0, 0); 493 if( p->op!=TK_ALL ){ 494 sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1, 0, 0); 495 } 496 } 497 498 /* Code the SELECT statements to our left 499 */ 500 rc = sqliteSelect(pParse, pPrior, priorOp, unionTab); 501 if( rc ) return rc; 502 503 /* Code the current SELECT statement 504 */ 505 switch( p->op ){ 506 case TK_EXCEPT: op = SRT_Except; break; 507 case TK_UNION: op = SRT_Union; break; 508 case TK_ALL: op = SRT_Table; break; 509 } 510 p->pPrior = 0; 511 rc = sqliteSelect(pParse, p, op, unionTab); 512 p->pPrior = pPrior; 513 if( rc ) return rc; 514 515 /* Convert the data in the temporary table into whatever form 516 ** it is that we currently need. 517 */ 518 if( eDest!=priorOp ){ 519 int iCont, iBreak; 520 assert( p->pEList ); 521 generateColumnNames(pParse, 0, p->pEList); 522 if( p->pOrderBy ){ 523 sqliteVdbeAddOp(v, OP_SortOpen, 0, 0, 0, 0); 524 } 525 iBreak = sqliteVdbeMakeLabel(v); 526 iCont = sqliteVdbeAddOp(v, OP_Next, unionTab, iBreak, 0, 0); 527 rc = selectInnerLoop(pParse, 0, unionTab, p->pEList->nExpr, 528 p->pOrderBy, -1, eDest, iParm, 529 iCont, iBreak); 530 if( rc ) return 1; 531 sqliteVdbeAddOp(v, OP_Goto, 0, iCont, 0, 0); 532 sqliteVdbeAddOp(v, OP_Close, unionTab, 0, 0, iBreak); 533 if( p->pOrderBy ){ 534 generateSortTail(v, p->pEList->nExpr); 535 } 536 } 537 break; 538 } 539 case TK_INTERSECT: { 540 int tab1, tab2; 541 int iCont, iBreak; 542 543 /* INTERSECT is different from the others since it requires 544 ** two temporary tables. Hence it has its own case. Begin 545 ** by allocating the tables we will need. 546 */ 547 tab1 = pParse->nTab++; 548 tab2 = pParse->nTab++; 549 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){ 550 return 1; 551 } 552 sqliteVdbeAddOp(v, OP_Open, tab1, 1, 0, 0); 553 sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1, 0, 0); 554 555 /* Code the SELECTs to our left into temporary table "tab1". 556 */ 557 rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1); 558 if( rc ) return rc; 559 560 /* Code the current SELECT into temporary table "tab2" 561 */ 562 sqliteVdbeAddOp(v, OP_Open, tab2, 1, 0, 0); 563 sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1, 0, 0); 564 p->pPrior = 0; 565 rc = sqliteSelect(pParse, p, SRT_Union, tab2); 566 p->pPrior = pPrior; 567 if( rc ) return rc; 568 569 /* Generate code to take the intersection of the two temporary 570 ** tables. 571 */ 572 assert( p->pEList ); 573 generateColumnNames(pParse, 0, p->pEList); 574 if( p->pOrderBy ){ 575 sqliteVdbeAddOp(v, OP_SortOpen, 0, 0, 0, 0); 576 } 577 iBreak = sqliteVdbeMakeLabel(v); 578 iCont = sqliteVdbeAddOp(v, OP_Next, tab1, iBreak, 0, 0); 579 sqliteVdbeAddOp(v, OP_Key, tab1, 0, 0, 0); 580 sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont, 0, 0); 581 rc = selectInnerLoop(pParse, 0, tab1, p->pEList->nExpr, 582 p->pOrderBy, -1, eDest, iParm, 583 iCont, iBreak); 584 if( rc ) return 1; 585 sqliteVdbeAddOp(v, OP_Goto, 0, iCont, 0, 0); 586 sqliteVdbeAddOp(v, OP_Close, tab2, 0, 0, iBreak); 587 sqliteVdbeAddOp(v, OP_Close, tab1, 0, 0, 0); 588 if( p->pOrderBy ){ 589 generateSortTail(v, p->pEList->nExpr); 590 } 591 break; 592 } 593 } 594 assert( p->pEList && pPrior->pEList ); 595 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 596 sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ", 597 selectOpName(p->op), " do not have the same number of result columns", 0); 598 pParse->nErr++; 599 return 1; 600 } 601 pParse->nTab = base; 602 return 0; 603 } 604 605 /* 606 ** Generate code for the given SELECT statement. 607 ** 608 ** The results are distributed in various ways depending on the 609 ** value of eDest and iParm. 610 ** 611 ** eDest Value Result 612 ** ------------ ------------------------------------------- 613 ** SRT_Callback Invoke the callback for each row of the result. 614 ** 615 ** SRT_Mem Store first result in memory cell iParm 616 ** 617 ** SRT_Set Store results as keys of a table with cursor iParm 618 ** 619 ** SRT_Union Store results as a key in a temporary table iParm 620 ** 621 ** SRT_Except Remove results form the temporary talbe iParm. 622 ** 623 ** This routine returns the number of errors. If any errors are 624 ** encountered, then an appropriate error message is left in 625 ** pParse->zErrMsg. 626 ** 627 ** This routine does NOT free the Select structure passed in. The 628 ** calling function needs to do that. 629 */ 630 int sqliteSelect( 631 Parse *pParse, /* The parser context */ 632 Select *p, /* The SELECT statement being coded. */ 633 int eDest, /* One of: SRT_Callback Mem Set Union Except */ 634 int iParm /* Save result in this memory location, if >=0 */ 635 ){ 636 int i; 637 WhereInfo *pWInfo; 638 Vdbe *v; 639 int isAgg = 0; /* True for select lists like "count(*)" */ 640 ExprList *pEList; /* List of columns to extract. NULL means "*" */ 641 IdList *pTabList; /* List of tables to select from */ 642 Expr *pWhere; /* The WHERE clause. May be NULL */ 643 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 644 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 645 Expr *pHaving; /* The HAVING clause. May be NULL */ 646 int isDistinct; /* True if the DISTINCT keyword is present */ 647 int distinct; /* Table to use for the distinct set */ 648 int base; /* First cursor available for use */ 649 650 /* If there is are a sequence of queries, do the earlier ones first. 651 */ 652 if( p->pPrior ){ 653 return multiSelect(pParse, p, eDest, iParm); 654 } 655 656 /* Make local copies of the parameters for this query. 657 */ 658 pTabList = p->pSrc; 659 pWhere = p->pWhere; 660 pOrderBy = p->pOrderBy; 661 pGroupBy = p->pGroupBy; 662 pHaving = p->pHaving; 663 isDistinct = p->isDistinct; 664 665 /* Save the current value of pParse->nTab. Restore this value before 666 ** we exit. 667 */ 668 base = pParse->nTab; 669 670 /* 671 ** Do not even attempt to generate any code if we have already seen 672 ** errors before this routine starts. 673 */ 674 if( pParse->nErr>0 ) return 1; 675 sqliteParseInfoReset(pParse); 676 677 /* Look up every table in the table list and create an appropriate 678 ** columnlist in pEList if there isn't one already. (The parser leaves 679 ** a NULL in the p->pEList if the SQL said "SELECT * FROM ...") 680 */ 681 if( fillInColumnList(pParse, p) ){ 682 return 1; 683 } 684 pEList = p->pEList; 685 686 /* Allocate a temporary table to use for the DISTINCT set, if 687 ** necessary. This must be done early to allocate the cursor before 688 ** any calls to sqliteExprResolveIds(). 689 */ 690 if( isDistinct ){ 691 distinct = pParse->nTab++; 692 }else{ 693 distinct = -1; 694 } 695 696 /* If writing to memory or generating a set 697 ** only a single column may be output. 698 */ 699 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){ 700 sqliteSetString(&pParse->zErrMsg, "only a single result allowed for " 701 "a SELECT that is part of an expression", 0); 702 pParse->nErr++; 703 return 1; 704 } 705 706 /* ORDER BY is ignored if we are not sending the result to a callback. 707 */ 708 if( eDest!=SRT_Callback ){ 709 pOrderBy = 0; 710 } 711 712 /* Allocate cursors for "expr IN (SELECT ...)" constructs. 713 */ 714 for(i=0; i<pEList->nExpr; i++){ 715 sqliteExprResolveInSelect(pParse, pEList->a[i].pExpr); 716 } 717 if( pWhere ) sqliteExprResolveInSelect(pParse, pWhere); 718 if( pOrderBy ){ 719 for(i=0; i<pOrderBy->nExpr; i++){ 720 sqliteExprResolveInSelect(pParse, pOrderBy->a[i].pExpr); 721 } 722 } 723 if( pGroupBy ){ 724 for(i=0; i<pGroupBy->nExpr; i++){ 725 sqliteExprResolveInSelect(pParse, pGroupBy->a[i].pExpr); 726 } 727 } 728 if( pHaving ) sqliteExprResolveInSelect(pParse, pHaving); 729 730 /* At this point, we should have allocated all the cursors that we 731 ** need to handle subquerys and temporary tables. From here on we 732 ** are committed to keeping the same value for pParse->nTab. 733 ** 734 ** Resolve the column names and do a semantics check on all the expressions. 735 */ 736 for(i=0; i<pEList->nExpr; i++){ 737 if( sqliteExprResolveIds(pParse, pTabList, pEList->a[i].pExpr) ){ 738 return 1; 739 } 740 if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){ 741 return 1; 742 } 743 } 744 if( pWhere ){ 745 if( sqliteExprResolveIds(pParse, pTabList, pWhere) ){ 746 return 1; 747 } 748 if( sqliteExprCheck(pParse, pWhere, 0, 0) ){ 749 return 1; 750 } 751 } 752 if( pOrderBy ){ 753 for(i=0; i<pOrderBy->nExpr; i++){ 754 Expr *pE = pOrderBy->a[i].pExpr; 755 if( sqliteExprResolveIds(pParse, pTabList, pE) ){ 756 return 1; 757 } 758 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){ 759 return 1; 760 } 761 } 762 } 763 if( pGroupBy ){ 764 for(i=0; i<pGroupBy->nExpr; i++){ 765 Expr *pE = pGroupBy->a[i].pExpr; 766 if( sqliteExprResolveIds(pParse, pTabList, pE) ){ 767 return 1; 768 } 769 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){ 770 return 1; 771 } 772 } 773 } 774 if( pHaving ){ 775 if( pGroupBy==0 ){ 776 sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required " 777 "before HAVING", 0); 778 pParse->nErr++; 779 return 1; 780 } 781 if( sqliteExprResolveIds(pParse, pTabList, pHaving) ){ 782 return 1; 783 } 784 if( sqliteExprCheck(pParse, pHaving, isAgg, 0) ){ 785 return 1; 786 } 787 } 788 789 /* Do an analysis of aggregate expressions. 790 */ 791 if( isAgg ){ 792 assert( pParse->nAgg==0 && pParse->iAggCount<0 ); 793 for(i=0; i<pEList->nExpr; i++){ 794 if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){ 795 return 1; 796 } 797 } 798 if( pGroupBy ){ 799 for(i=0; i<pGroupBy->nExpr; i++){ 800 if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){ 801 return 1; 802 } 803 } 804 } 805 if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){ 806 return 1; 807 } 808 if( pOrderBy ){ 809 for(i=0; i<pOrderBy->nExpr; i++){ 810 if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){ 811 return 1; 812 } 813 } 814 } 815 } 816 817 /* Begin generating code. 818 */ 819 v = pParse->pVdbe; 820 if( v==0 ){ 821 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db->pBe); 822 } 823 if( v==0 ){ 824 sqliteSetString(&pParse->zErrMsg, "out of memory", 0); 825 pParse->nErr++; 826 return 1; 827 } 828 if( pOrderBy ){ 829 sqliteVdbeAddOp(v, OP_SortOpen, 0, 0, 0, 0); 830 } 831 832 /* Identify column names if we will be using in the callback. This 833 ** step is skipped if the output is going to a table or a memory cell. 834 */ 835 if( eDest==SRT_Callback ){ 836 generateColumnNames(pParse, pTabList, pEList); 837 } 838 839 /* Reset the aggregator 840 */ 841 if( isAgg ){ 842 sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg, 0, 0); 843 } 844 845 /* Initialize the memory cell to NULL 846 */ 847 if( eDest==SRT_Mem ){ 848 sqliteVdbeAddOp(v, OP_Null, 0, 0, 0, 0); 849 sqliteVdbeAddOp(v, OP_MemStore, iParm, 0, 0, 0); 850 } 851 852 /* Begin the database scan 853 */ 854 if( isDistinct ){ 855 sqliteVdbeAddOp(v, OP_Open, distinct, 1, 0, 0); 856 } 857 pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 0); 858 if( pWInfo==0 ) return 1; 859 860 /* Use the standard inner loop if we are not dealing with 861 ** aggregates 862 */ 863 if( !isAgg ){ 864 if( selectInnerLoop(pParse, pEList, 0, 0, pOrderBy, distinct, eDest, iParm, 865 pWInfo->iContinue, pWInfo->iBreak) ){ 866 return 1; 867 } 868 } 869 870 /* If we are dealing with aggregates, then to the special aggregate 871 ** processing. 872 */ 873 else{ 874 int doFocus; 875 if( pGroupBy ){ 876 for(i=0; i<pGroupBy->nExpr; i++){ 877 sqliteExprCode(pParse, pGroupBy->a[i].pExpr); 878 } 879 sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0, 0, 0); 880 doFocus = 1; 881 }else{ 882 doFocus = 0; 883 for(i=0; i<pParse->nAgg; i++){ 884 if( !pParse->aAgg[i].isAgg ){ 885 doFocus = 1; 886 break; 887 } 888 } 889 if( doFocus ){ 890 sqliteVdbeAddOp(v, OP_String, 0, 0, "", 0); 891 } 892 } 893 if( doFocus ){ 894 int lbl1 = sqliteVdbeMakeLabel(v); 895 sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1, 0, 0); 896 for(i=0; i<pParse->nAgg; i++){ 897 if( pParse->aAgg[i].isAgg ) continue; 898 sqliteExprCode(pParse, pParse->aAgg[i].pExpr); 899 sqliteVdbeAddOp(v, OP_AggSet, 0, i, 0, 0); 900 } 901 sqliteVdbeResolveLabel(v, lbl1); 902 } 903 for(i=0; i<pParse->nAgg; i++){ 904 Expr *pE; 905 int op; 906 if( !pParse->aAgg[i].isAgg ) continue; 907 pE = pParse->aAgg[i].pExpr; 908 if( pE==0 ){ 909 sqliteVdbeAddOp(v, OP_AggIncr, 1, i, 0, 0); 910 continue; 911 } 912 assert( pE->op==TK_AGG_FUNCTION ); 913 assert( pE->pList!=0 && pE->pList->nExpr==1 ); 914 sqliteExprCode(pParse, pE->pList->a[0].pExpr); 915 sqliteVdbeAddOp(v, OP_AggGet, 0, i, 0, 0); 916 switch( pE->iColumn ){ 917 case FN_Min: op = OP_Min; break; 918 case FN_Max: op = OP_Max; break; 919 case FN_Avg: op = OP_Add; break; 920 case FN_Sum: op = OP_Add; break; 921 } 922 sqliteVdbeAddOp(v, op, 0, 0, 0, 0); 923 sqliteVdbeAddOp(v, OP_AggSet, 0, i, 0, 0); 924 } 925 } 926 927 928 /* End the database scan loop. 929 */ 930 sqliteWhereEnd(pWInfo); 931 932 /* If we are processing aggregates, we need to set up a second loop 933 ** over all of the aggregate values and process them. 934 */ 935 if( isAgg ){ 936 int endagg = sqliteVdbeMakeLabel(v); 937 int startagg; 938 startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg, 0, 0); 939 pParse->useAgg = 1; 940 if( pHaving ){ 941 sqliteExprIfFalse(pParse, pHaving, startagg); 942 } 943 if( selectInnerLoop(pParse, pEList, 0, 0, pOrderBy, distinct, eDest, iParm, 944 startagg, endagg) ){ 945 return 1; 946 } 947 sqliteVdbeAddOp(v, OP_Goto, 0, startagg, 0, 0); 948 sqliteVdbeAddOp(v, OP_Noop, 0, 0, 0, endagg); 949 pParse->useAgg = 0; 950 } 951 952 /* If there is an ORDER BY clause, then we need to sort the results 953 ** and send them to the callback one by one. 954 */ 955 if( pOrderBy ){ 956 generateSortTail(v, pEList->nExpr); 957 } 958 pParse->nTab = base; 959 return 0; 960 } 961