1 /* 2 ** 2001 September 15 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** 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. 10 ** 11 ************************************************************************* 12 ** This file contains C code routines that are called by the parser 13 ** to handle SELECT statements in SQLite. 14 ** 15 ** $Id: select.c,v 1.145 2003/07/20 01:16:47 drh Exp $ 16 */ 17 #include "sqliteInt.h" 18 19 20 /* 21 ** Allocate a new Select structure and return a pointer to that 22 ** structure. 23 */ 24 Select *sqliteSelectNew( 25 ExprList *pEList, /* which columns to include in the result */ 26 SrcList *pSrc, /* the FROM clause -- which tables to scan */ 27 Expr *pWhere, /* the WHERE clause */ 28 ExprList *pGroupBy, /* the GROUP BY clause */ 29 Expr *pHaving, /* the HAVING clause */ 30 ExprList *pOrderBy, /* the ORDER BY clause */ 31 int isDistinct, /* true if the DISTINCT keyword is present */ 32 int nLimit, /* LIMIT value. -1 means not used */ 33 int nOffset /* OFFSET value. 0 means no offset */ 34 ){ 35 Select *pNew; 36 pNew = sqliteMalloc( sizeof(*pNew) ); 37 if( pNew==0 ){ 38 sqliteExprListDelete(pEList); 39 sqliteSrcListDelete(pSrc); 40 sqliteExprDelete(pWhere); 41 sqliteExprListDelete(pGroupBy); 42 sqliteExprDelete(pHaving); 43 sqliteExprListDelete(pOrderBy); 44 }else{ 45 pNew->pEList = pEList; 46 pNew->pSrc = pSrc; 47 pNew->pWhere = pWhere; 48 pNew->pGroupBy = pGroupBy; 49 pNew->pHaving = pHaving; 50 pNew->pOrderBy = pOrderBy; 51 pNew->isDistinct = isDistinct; 52 pNew->op = TK_SELECT; 53 pNew->nLimit = nLimit; 54 pNew->nOffset = nOffset; 55 pNew->iLimit = -1; 56 pNew->iOffset = -1; 57 } 58 return pNew; 59 } 60 61 /* 62 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the 63 ** type of join. Return an integer constant that expresses that type 64 ** in terms of the following bit values: 65 ** 66 ** JT_INNER 67 ** JT_OUTER 68 ** JT_NATURAL 69 ** JT_LEFT 70 ** JT_RIGHT 71 ** 72 ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 73 ** 74 ** If an illegal or unsupported join type is seen, then still return 75 ** a join type, but put an error in the pParse structure. 76 */ 77 int sqliteJoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 78 int jointype = 0; 79 Token *apAll[3]; 80 Token *p; 81 static struct { 82 const char *zKeyword; 83 int nChar; 84 int code; 85 } keywords[] = { 86 { "natural", 7, JT_NATURAL }, 87 { "left", 4, JT_LEFT|JT_OUTER }, 88 { "right", 5, JT_RIGHT|JT_OUTER }, 89 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 90 { "outer", 5, JT_OUTER }, 91 { "inner", 5, JT_INNER }, 92 { "cross", 5, JT_INNER }, 93 }; 94 int i, j; 95 apAll[0] = pA; 96 apAll[1] = pB; 97 apAll[2] = pC; 98 for(i=0; i<3 && apAll[i]; i++){ 99 p = apAll[i]; 100 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){ 101 if( p->n==keywords[j].nChar 102 && sqliteStrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){ 103 jointype |= keywords[j].code; 104 break; 105 } 106 } 107 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){ 108 jointype |= JT_ERROR; 109 break; 110 } 111 } 112 if( 113 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 114 (jointype & JT_ERROR)!=0 115 ){ 116 static Token dummy = { 0, 0 }; 117 char *zSp1 = " ", *zSp2 = " "; 118 if( pB==0 ){ pB = &dummy; zSp1 = 0; } 119 if( pC==0 ){ pC = &dummy; zSp2 = 0; } 120 sqliteSetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0, 121 pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0); 122 pParse->nErr++; 123 jointype = JT_INNER; 124 }else if( jointype & JT_RIGHT ){ 125 sqliteErrorMsg(pParse, 126 "RIGHT and FULL OUTER JOINs are not currently supported"); 127 jointype = JT_INNER; 128 } 129 return jointype; 130 } 131 132 /* 133 ** Return the index of a column in a table. Return -1 if the column 134 ** is not contained in the table. 135 */ 136 static int columnIndex(Table *pTab, const char *zCol){ 137 int i; 138 for(i=0; i<pTab->nCol; i++){ 139 if( sqliteStrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 140 } 141 return -1; 142 } 143 144 /* 145 ** Add a term to the WHERE expression in *ppExpr that requires the 146 ** zCol column to be equal in the two tables pTab1 and pTab2. 147 */ 148 static void addWhereTerm( 149 const char *zCol, /* Name of the column */ 150 const Table *pTab1, /* First table */ 151 const Table *pTab2, /* Second table */ 152 Expr **ppExpr /* Add the equality term to this expression */ 153 ){ 154 Token dummy; 155 Expr *pE1a, *pE1b, *pE1c; 156 Expr *pE2a, *pE2b, *pE2c; 157 Expr *pE; 158 159 dummy.z = zCol; 160 dummy.n = strlen(zCol); 161 dummy.dyn = 0; 162 pE1a = sqliteExpr(TK_ID, 0, 0, &dummy); 163 pE2a = sqliteExpr(TK_ID, 0, 0, &dummy); 164 dummy.z = pTab1->zName; 165 dummy.n = strlen(dummy.z); 166 pE1b = sqliteExpr(TK_ID, 0, 0, &dummy); 167 dummy.z = pTab2->zName; 168 dummy.n = strlen(dummy.z); 169 pE2b = sqliteExpr(TK_ID, 0, 0, &dummy); 170 pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0); 171 pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0); 172 pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0); 173 ExprSetProperty(pE, EP_FromJoin); 174 if( *ppExpr ){ 175 *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0); 176 }else{ 177 *ppExpr = pE; 178 } 179 } 180 181 /* 182 ** Set the EP_FromJoin property on all terms of the given expression. 183 ** 184 ** The EP_FromJoin property is used on terms of an expression to tell 185 ** the LEFT OUTER JOIN processing logic that this term is part of the 186 ** join restriction specified in the ON or USING clause and not a part 187 ** of the more general WHERE clause. These terms are moved over to the 188 ** WHERE clause during join processing but we need to remember that they 189 ** originated in the ON or USING clause. 190 */ 191 static void setJoinExpr(Expr *p){ 192 while( p ){ 193 ExprSetProperty(p, EP_FromJoin); 194 setJoinExpr(p->pLeft); 195 p = p->pRight; 196 } 197 } 198 199 /* 200 ** This routine processes the join information for a SELECT statement. 201 ** ON and USING clauses are converted into extra terms of the WHERE clause. 202 ** NATURAL joins also create extra WHERE clause terms. 203 ** 204 ** This routine returns the number of errors encountered. 205 */ 206 static int sqliteProcessJoin(Parse *pParse, Select *p){ 207 SrcList *pSrc; 208 int i, j; 209 pSrc = p->pSrc; 210 for(i=0; i<pSrc->nSrc-1; i++){ 211 struct SrcList_item *pTerm = &pSrc->a[i]; 212 struct SrcList_item *pOther = &pSrc->a[i+1]; 213 214 if( pTerm->pTab==0 || pOther->pTab==0 ) continue; 215 216 /* When the NATURAL keyword is present, add WHERE clause terms for 217 ** every column that the two tables have in common. 218 */ 219 if( pTerm->jointype & JT_NATURAL ){ 220 Table *pTab; 221 if( pTerm->pOn || pTerm->pUsing ){ 222 sqliteErrorMsg(pParse, "a NATURAL join may not have " 223 "an ON or USING clause", 0); 224 return 1; 225 } 226 pTab = pTerm->pTab; 227 for(j=0; j<pTab->nCol; j++){ 228 if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){ 229 addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere); 230 } 231 } 232 } 233 234 /* Disallow both ON and USING clauses in the same join 235 */ 236 if( pTerm->pOn && pTerm->pUsing ){ 237 sqliteErrorMsg(pParse, "cannot have both ON and USING " 238 "clauses in the same join"); 239 return 1; 240 } 241 242 /* Add the ON clause to the end of the WHERE clause, connected by 243 ** and AND operator. 244 */ 245 if( pTerm->pOn ){ 246 setJoinExpr(pTerm->pOn); 247 if( p->pWhere==0 ){ 248 p->pWhere = pTerm->pOn; 249 }else{ 250 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0); 251 } 252 pTerm->pOn = 0; 253 } 254 255 /* Create extra terms on the WHERE clause for each column named 256 ** in the USING clause. Example: If the two tables to be joined are 257 ** A and B and the USING clause names X, Y, and Z, then add this 258 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 259 ** Report an error if any column mentioned in the USING clause is 260 ** not contained in both tables to be joined. 261 */ 262 if( pTerm->pUsing ){ 263 IdList *pList; 264 int j; 265 assert( i<pSrc->nSrc-1 ); 266 pList = pTerm->pUsing; 267 for(j=0; j<pList->nId; j++){ 268 if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 || 269 columnIndex(pOther->pTab, pList->a[j].zName)<0 ){ 270 sqliteErrorMsg(pParse, "cannot join using column %s - column " 271 "not present in both tables", pList->a[j].zName); 272 return 1; 273 } 274 addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere); 275 } 276 } 277 } 278 return 0; 279 } 280 281 /* 282 ** This routine implements a minimal Oracle8 join syntax immulation. 283 ** The precise oracle8 syntax is not implemented - it is easy enough 284 ** to get this routine confused. But this routine does make it possible 285 ** to write a single SQL statement that does a left outer join in both 286 ** oracle8 and in SQLite. 287 ** 288 ** This routine looks for TK_COLUMN expression nodes that are marked 289 ** with the EP_Oracle8Join property. Such nodes are generated by a 290 ** column name (either "column" or "table.column") that is followed by 291 ** the special "(+)" operator. If the table of the column marked with 292 ** the (+) operator is the second are subsequent table in a join, then 293 ** that table becomes the left table in a LEFT OUTER JOIN. The expression 294 ** that uses that table becomes part of the ON clause for the join. 295 ** 296 ** It is important to enphasize that this is not exactly how oracle8 297 ** works. But it is close enough so that one can construct queries that 298 ** will work correctly for both SQLite and Oracle8. 299 */ 300 static int sqliteOracle8JoinFixup( 301 SrcList *pSrc, /* List of tables being joined */ 302 Expr *pWhere /* The WHERE clause of the SELECT statement */ 303 ){ 304 int rc = 0; 305 if( ExprHasProperty(pWhere, EP_Oracle8Join) && pWhere->op==TK_COLUMN ){ 306 int idx; 307 for(idx=0; idx<pSrc->nSrc; idx++){ 308 if( pSrc->a[idx].iCursor==pWhere->iTable ) break; 309 } 310 assert( idx>=0 && idx<pSrc->nSrc ); 311 if( idx>0 ){ 312 pSrc->a[idx-1].jointype &= ~JT_INNER; 313 pSrc->a[idx-1].jointype |= JT_OUTER|JT_LEFT; 314 return 1; 315 } 316 } 317 if( pWhere->pRight ){ 318 rc = sqliteOracle8JoinFixup(pSrc, pWhere->pRight); 319 } 320 if( pWhere->pLeft ){ 321 rc |= sqliteOracle8JoinFixup(pSrc, pWhere->pLeft); 322 } 323 if( pWhere->pList ){ 324 int i; 325 ExprList *pList = pWhere->pList; 326 for(i=0; i<pList->nExpr && rc==0; i++){ 327 rc |= sqliteOracle8JoinFixup(pSrc, pList->a[i].pExpr); 328 } 329 } 330 if( rc==1 && (pWhere->op==TK_AND || pWhere->op==TK_EQ) ){ 331 setJoinExpr(pWhere); 332 rc = 0; 333 } 334 return rc; 335 } 336 337 /* 338 ** Delete the given Select structure and all of its substructures. 339 */ 340 void sqliteSelectDelete(Select *p){ 341 if( p==0 ) return; 342 sqliteExprListDelete(p->pEList); 343 sqliteSrcListDelete(p->pSrc); 344 sqliteExprDelete(p->pWhere); 345 sqliteExprListDelete(p->pGroupBy); 346 sqliteExprDelete(p->pHaving); 347 sqliteExprListDelete(p->pOrderBy); 348 sqliteSelectDelete(p->pPrior); 349 sqliteFree(p->zSelect); 350 sqliteFree(p); 351 } 352 353 /* 354 ** Delete the aggregate information from the parse structure. 355 */ 356 static void sqliteAggregateInfoReset(Parse *pParse){ 357 sqliteFree(pParse->aAgg); 358 pParse->aAgg = 0; 359 pParse->nAgg = 0; 360 pParse->useAgg = 0; 361 } 362 363 /* 364 ** Insert code into "v" that will push the record on the top of the 365 ** stack into the sorter. 366 */ 367 static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){ 368 char *zSortOrder; 369 int i; 370 zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 ); 371 if( zSortOrder==0 ) return; 372 for(i=0; i<pOrderBy->nExpr; i++){ 373 int order = pOrderBy->a[i].sortOrder; 374 int type; 375 int c; 376 if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){ 377 type = SQLITE_SO_TEXT; 378 }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){ 379 type = SQLITE_SO_NUM; 380 }else if( pParse->db->file_format>=4 ){ 381 type = sqliteExprType(pOrderBy->a[i].pExpr); 382 }else{ 383 type = SQLITE_SO_NUM; 384 } 385 if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){ 386 c = type==SQLITE_SO_TEXT ? 'A' : '+'; 387 }else{ 388 c = type==SQLITE_SO_TEXT ? 'D' : '-'; 389 } 390 zSortOrder[i] = c; 391 sqliteExprCode(pParse, pOrderBy->a[i].pExpr); 392 } 393 zSortOrder[pOrderBy->nExpr] = 0; 394 sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0); 395 sqliteVdbeChangeP3(v, -1, zSortOrder, strlen(zSortOrder)); 396 sqliteFree(zSortOrder); 397 sqliteVdbeAddOp(v, OP_SortPut, 0, 0); 398 } 399 400 /* 401 ** This routine adds a P3 argument to the last VDBE opcode that was 402 ** inserted. The P3 argument added is a string suitable for the 403 ** OP_MakeKey or OP_MakeIdxKey opcodes. The string consists of 404 ** characters 't' or 'n' depending on whether or not the various 405 ** fields of the key to be generated should be treated as numeric 406 ** or as text. See the OP_MakeKey and OP_MakeIdxKey opcode 407 ** documentation for additional information about the P3 string. 408 ** See also the sqliteAddIdxKeyType() routine. 409 */ 410 void sqliteAddKeyType(Vdbe *v, ExprList *pEList){ 411 int nColumn = pEList->nExpr; 412 char *zType = sqliteMalloc( nColumn+1 ); 413 int i; 414 if( zType==0 ) return; 415 for(i=0; i<nColumn; i++){ 416 zType[i] = sqliteExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't'; 417 } 418 zType[i] = 0; 419 sqliteVdbeChangeP3(v, -1, zType, nColumn); 420 sqliteFree(zType); 421 } 422 423 /* 424 ** This routine generates the code for the inside of the inner loop 425 ** of a SELECT. 426 ** 427 ** If srcTab and nColumn are both zero, then the pEList expressions 428 ** are evaluated in order to get the data for this row. If nColumn>0 429 ** then data is pulled from srcTab and pEList is used only to get the 430 ** datatypes for each column. 431 */ 432 static int selectInnerLoop( 433 Parse *pParse, /* The parser context */ 434 Select *p, /* The complete select statement being coded */ 435 ExprList *pEList, /* List of values being extracted */ 436 int srcTab, /* Pull data from this table */ 437 int nColumn, /* Number of columns in the source table */ 438 ExprList *pOrderBy, /* If not NULL, sort results using this key */ 439 int distinct, /* If >=0, make sure results are distinct */ 440 int eDest, /* How to dispose of the results */ 441 int iParm, /* An argument to the disposal method */ 442 int iContinue, /* Jump here to continue with next row */ 443 int iBreak /* Jump here to break out of the inner loop */ 444 ){ 445 Vdbe *v = pParse->pVdbe; 446 int i; 447 448 if( v==0 ) return 0; 449 assert( pEList!=0 ); 450 451 /* If there was a LIMIT clause on the SELECT statement, then do the check 452 ** to see if this row should be output. 453 */ 454 if( pOrderBy==0 ){ 455 if( p->iOffset>=0 ){ 456 int addr = sqliteVdbeCurrentAddr(v); 457 sqliteVdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2); 458 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue); 459 } 460 if( p->iLimit>=0 ){ 461 sqliteVdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak); 462 } 463 } 464 465 /* Pull the requested columns. 466 */ 467 if( nColumn>0 ){ 468 for(i=0; i<nColumn; i++){ 469 sqliteVdbeAddOp(v, OP_Column, srcTab, i); 470 } 471 }else{ 472 nColumn = pEList->nExpr; 473 for(i=0; i<pEList->nExpr; i++){ 474 sqliteExprCode(pParse, pEList->a[i].pExpr); 475 } 476 } 477 478 /* If the DISTINCT keyword was present on the SELECT statement 479 ** and this row has been seen before, then do not make this row 480 ** part of the result. 481 */ 482 if( distinct>=0 && pEList && pEList->nExpr>0 ){ 483 #if NULL_ALWAYS_DISTINCT 484 sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7); 485 #endif 486 sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1); 487 if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pEList); 488 sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3); 489 sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0); 490 sqliteVdbeAddOp(v, OP_Goto, 0, iContinue); 491 sqliteVdbeAddOp(v, OP_String, 0, 0); 492 sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0); 493 } 494 495 switch( eDest ){ 496 /* In this mode, write each query result to the key of the temporary 497 ** table iParm. 498 */ 499 case SRT_Union: { 500 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT); 501 sqliteVdbeAddOp(v, OP_String, 0, 0); 502 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0); 503 break; 504 } 505 506 /* Store the result as data using a unique key. 507 */ 508 case SRT_Table: 509 case SRT_TempTable: { 510 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0); 511 if( pOrderBy ){ 512 pushOntoSorter(pParse, v, pOrderBy); 513 }else{ 514 sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0); 515 sqliteVdbeAddOp(v, OP_Pull, 1, 0); 516 sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0); 517 } 518 break; 519 } 520 521 /* Construct a record from the query result, but instead of 522 ** saving that record, use it as a key to delete elements from 523 ** the temporary table iParm. 524 */ 525 case SRT_Except: { 526 int addr; 527 addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT); 528 sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3); 529 sqliteVdbeAddOp(v, OP_Delete, iParm, 0); 530 break; 531 } 532 533 /* If we are creating a set for an "expr IN (SELECT ...)" construct, 534 ** then there should be a single item on the stack. Write this 535 ** item into the set table with bogus data. 536 */ 537 case SRT_Set: { 538 int lbl = sqliteVdbeMakeLabel(v); 539 assert( nColumn==1 ); 540 sqliteVdbeAddOp(v, OP_IsNull, -1, lbl); 541 if( pOrderBy ){ 542 pushOntoSorter(pParse, v, pOrderBy); 543 }else{ 544 sqliteVdbeAddOp(v, OP_String, 0, 0); 545 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0); 546 } 547 sqliteVdbeResolveLabel(v, lbl); 548 break; 549 } 550 551 /* If this is a scalar select that is part of an expression, then 552 ** store the results in the appropriate memory cell and break out 553 ** of the scan loop. 554 */ 555 case SRT_Mem: { 556 assert( nColumn==1 ); 557 if( pOrderBy ){ 558 pushOntoSorter(pParse, v, pOrderBy); 559 }else{ 560 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1); 561 sqliteVdbeAddOp(v, OP_Goto, 0, iBreak); 562 } 563 break; 564 } 565 566 /* Send the data to the callback function. 567 */ 568 case SRT_Callback: 569 case SRT_Sorter: { 570 if( pOrderBy ){ 571 sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0); 572 pushOntoSorter(pParse, v, pOrderBy); 573 }else{ 574 assert( eDest==SRT_Callback ); 575 sqliteVdbeAddOp(v, OP_Callback, nColumn, 0); 576 } 577 break; 578 } 579 580 /* Invoke a subroutine to handle the results. The subroutine itself 581 ** is responsible for popping the results off of the stack. 582 */ 583 case SRT_Subroutine: { 584 if( pOrderBy ){ 585 sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0); 586 pushOntoSorter(pParse, v, pOrderBy); 587 }else{ 588 sqliteVdbeAddOp(v, OP_Gosub, 0, iParm); 589 } 590 break; 591 } 592 593 /* Discard the results. This is used for SELECT statements inside 594 ** the body of a TRIGGER. The purpose of such selects is to call 595 ** user-defined functions that have side effects. We do not care 596 ** about the actual results of the select. 597 */ 598 default: { 599 assert( eDest==SRT_Discard ); 600 sqliteVdbeAddOp(v, OP_Pop, nColumn, 0); 601 break; 602 } 603 } 604 return 0; 605 } 606 607 /* 608 ** If the inner loop was generated using a non-null pOrderBy argument, 609 ** then the results were placed in a sorter. After the loop is terminated 610 ** we need to run the sorter and output the results. The following 611 ** routine generates the code needed to do that. 612 */ 613 static void generateSortTail( 614 Select *p, /* The SELECT statement */ 615 Vdbe *v, /* Generate code into this VDBE */ 616 int nColumn, /* Number of columns of data */ 617 int eDest, /* Write the sorted results here */ 618 int iParm /* Optional parameter associated with eDest */ 619 ){ 620 int end = sqliteVdbeMakeLabel(v); 621 int addr; 622 if( eDest==SRT_Sorter ) return; 623 sqliteVdbeAddOp(v, OP_Sort, 0, 0); 624 addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end); 625 if( p->iOffset>=0 ){ 626 sqliteVdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4); 627 sqliteVdbeAddOp(v, OP_Pop, 1, 0); 628 sqliteVdbeAddOp(v, OP_Goto, 0, addr); 629 } 630 if( p->iLimit>=0 ){ 631 sqliteVdbeAddOp(v, OP_MemIncr, p->iLimit, end); 632 } 633 switch( eDest ){ 634 case SRT_Callback: { 635 sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0); 636 break; 637 } 638 case SRT_Table: 639 case SRT_TempTable: { 640 sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0); 641 sqliteVdbeAddOp(v, OP_Pull, 1, 0); 642 sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0); 643 break; 644 } 645 case SRT_Set: { 646 assert( nColumn==1 ); 647 sqliteVdbeAddOp(v, OP_IsNull, -1, sqliteVdbeCurrentAddr(v)+3); 648 sqliteVdbeAddOp(v, OP_String, 0, 0); 649 sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0); 650 break; 651 } 652 case SRT_Mem: { 653 assert( nColumn==1 ); 654 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1); 655 sqliteVdbeAddOp(v, OP_Goto, 0, end); 656 break; 657 } 658 case SRT_Subroutine: { 659 int i; 660 for(i=0; i<nColumn; i++){ 661 sqliteVdbeAddOp(v, OP_Column, -1-i, i); 662 } 663 sqliteVdbeAddOp(v, OP_Gosub, 0, iParm); 664 sqliteVdbeAddOp(v, OP_Pop, 1, 0); 665 break; 666 } 667 default: { 668 /* Do nothing */ 669 break; 670 } 671 } 672 sqliteVdbeAddOp(v, OP_Goto, 0, addr); 673 sqliteVdbeResolveLabel(v, end); 674 sqliteVdbeAddOp(v, OP_SortReset, 0, 0); 675 } 676 677 /* 678 ** Generate code that will tell the VDBE the datatypes of 679 ** columns in the result set. 680 ** 681 ** This routine only generates code if the "PRAGMA show_datatypes=on" 682 ** has been executed. The datatypes are reported out in the azCol 683 ** parameter to the callback function. The first N azCol[] entries 684 ** are the names of the columns, and the second N entries are the 685 ** datatypes for the columns. 686 ** 687 ** The "datatype" for a result that is a column of a type is the 688 ** datatype definition extracted from the CREATE TABLE statement. 689 ** The datatype for an expression is either TEXT or NUMERIC. The 690 ** datatype for a ROWID field is INTEGER. 691 */ 692 static void generateColumnTypes( 693 Parse *pParse, /* Parser context */ 694 SrcList *pTabList, /* List of tables */ 695 ExprList *pEList /* Expressions defining the result set */ 696 ){ 697 Vdbe *v = pParse->pVdbe; 698 int i, j; 699 if( pParse->useCallback && (pParse->db->flags & SQLITE_ReportTypes)==0 ){ 700 return; 701 } 702 for(i=0; i<pEList->nExpr; i++){ 703 Expr *p = pEList->a[i].pExpr; 704 char *zType = 0; 705 if( p==0 ) continue; 706 if( p->op==TK_COLUMN && pTabList ){ 707 Table *pTab; 708 int iCol = p->iColumn; 709 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){} 710 assert( j<pTabList->nSrc ); 711 pTab = pTabList->a[j].pTab; 712 if( iCol<0 ) iCol = pTab->iPKey; 713 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 714 if( iCol<0 ){ 715 zType = "INTEGER"; 716 }else{ 717 zType = pTab->aCol[iCol].zType; 718 } 719 }else{ 720 if( sqliteExprType(p)==SQLITE_SO_TEXT ){ 721 zType = "TEXT"; 722 }else{ 723 zType = "NUMERIC"; 724 } 725 } 726 sqliteVdbeAddOp(v, OP_ColumnName, i + pEList->nExpr, 0); 727 sqliteVdbeChangeP3(v, -1, zType, P3_STATIC); 728 } 729 } 730 731 /* 732 ** Generate code that will tell the VDBE the names of columns 733 ** in the result set. This information is used to provide the 734 ** azCol[] vaolues in the callback. 735 */ 736 static void generateColumnNames( 737 Parse *pParse, /* Parser context */ 738 SrcList *pTabList, /* List of tables */ 739 ExprList *pEList /* Expressions defining the result set */ 740 ){ 741 Vdbe *v = pParse->pVdbe; 742 int i, j; 743 if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return; 744 pParse->colNamesSet = 1; 745 for(i=0; i<pEList->nExpr; i++){ 746 Expr *p; 747 char *zType = 0; 748 int showFullNames; 749 p = pEList->a[i].pExpr; 750 if( p==0 ) continue; 751 if( pEList->a[i].zName ){ 752 char *zName = pEList->a[i].zName; 753 sqliteVdbeAddOp(v, OP_ColumnName, i, 0); 754 sqliteVdbeChangeP3(v, -1, zName, strlen(zName)); 755 continue; 756 } 757 showFullNames = (pParse->db->flags & SQLITE_FullColNames)!=0; 758 if( p->op==TK_COLUMN && pTabList ){ 759 Table *pTab; 760 char *zCol; 761 int iCol = p->iColumn; 762 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){} 763 assert( j<pTabList->nSrc ); 764 pTab = pTabList->a[j].pTab; 765 if( iCol<0 ) iCol = pTab->iPKey; 766 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 767 if( iCol<0 ){ 768 zCol = "_ROWID_"; 769 zType = "INTEGER"; 770 }else{ 771 zCol = pTab->aCol[iCol].zName; 772 zType = pTab->aCol[iCol].zType; 773 } 774 if( p->span.z && p->span.z[0] && !showFullNames ){ 775 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0); 776 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n); 777 sqliteVdbeCompressSpace(v, addr); 778 }else if( pTabList->nSrc>1 || showFullNames ){ 779 char *zName = 0; 780 char *zTab; 781 782 zTab = pTabList->a[j].zAlias; 783 if( showFullNames || zTab==0 ) zTab = pTab->zName; 784 sqliteSetString(&zName, zTab, ".", zCol, 0); 785 sqliteVdbeAddOp(v, OP_ColumnName, i, 0); 786 sqliteVdbeChangeP3(v, -1, zName, strlen(zName)); 787 sqliteFree(zName); 788 }else{ 789 sqliteVdbeAddOp(v, OP_ColumnName, i, 0); 790 sqliteVdbeChangeP3(v, -1, zCol, 0); 791 } 792 }else if( p->span.z && p->span.z[0] ){ 793 int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0); 794 sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n); 795 sqliteVdbeCompressSpace(v, addr); 796 }else{ 797 char zName[30]; 798 assert( p->op!=TK_COLUMN || pTabList==0 ); 799 sprintf(zName, "column%d", i+1); 800 sqliteVdbeAddOp(v, OP_ColumnName, i, 0); 801 sqliteVdbeChangeP3(v, -1, zName, strlen(zName)); 802 } 803 } 804 } 805 806 /* 807 ** Name of the connection operator, used for error messages. 808 */ 809 static const char *selectOpName(int id){ 810 char *z; 811 switch( id ){ 812 case TK_ALL: z = "UNION ALL"; break; 813 case TK_INTERSECT: z = "INTERSECT"; break; 814 case TK_EXCEPT: z = "EXCEPT"; break; 815 default: z = "UNION"; break; 816 } 817 return z; 818 } 819 820 /* 821 ** Forward declaration 822 */ 823 static int fillInColumnList(Parse*, Select*); 824 825 /* 826 ** Given a SELECT statement, generate a Table structure that describes 827 ** the result set of that SELECT. 828 */ 829 Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){ 830 Table *pTab; 831 int i; 832 ExprList *pEList; 833 834 if( fillInColumnList(pParse, pSelect) ){ 835 return 0; 836 } 837 pTab = sqliteMalloc( sizeof(Table) ); 838 if( pTab==0 ){ 839 return 0; 840 } 841 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0; 842 pEList = pSelect->pEList; 843 pTab->nCol = pEList->nExpr; 844 assert( pTab->nCol>0 ); 845 pTab->aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol ); 846 for(i=0; i<pTab->nCol; i++){ 847 Expr *p; 848 if( pEList->a[i].zName ){ 849 pTab->aCol[i].zName = sqliteStrDup(pEList->a[i].zName); 850 }else if( (p=pEList->a[i].pExpr)->span.z && p->span.z[0] ){ 851 sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0); 852 }else if( p->op==TK_DOT && p->pRight && p->pRight->token.z && 853 p->pRight->token.z[0] ){ 854 sqliteSetNString(&pTab->aCol[i].zName, 855 p->pRight->token.z, p->pRight->token.n, 0); 856 }else{ 857 char zBuf[30]; 858 sprintf(zBuf, "column%d", i+1); 859 pTab->aCol[i].zName = sqliteStrDup(zBuf); 860 } 861 } 862 pTab->iPKey = -1; 863 return pTab; 864 } 865 866 /* 867 ** For the given SELECT statement, do three things. 868 ** 869 ** (1) Fill in the pTabList->a[].pTab fields in the SrcList that 870 ** defines the set of tables that should be scanned. For views, 871 ** fill pTabList->a[].pSelect with a copy of the SELECT statement 872 ** that implements the view. A copy is made of the view's SELECT 873 ** statement so that we can freely modify or delete that statement 874 ** without worrying about messing up the presistent representation 875 ** of the view. 876 ** 877 ** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword 878 ** on joins and the ON and USING clause of joins. 879 ** 880 ** (3) Scan the list of columns in the result set (pEList) looking 881 ** for instances of the "*" operator or the TABLE.* operator. 882 ** If found, expand each "*" to be every column in every table 883 ** and TABLE.* to be every column in TABLE. 884 ** 885 ** Return 0 on success. If there are problems, leave an error message 886 ** in pParse and return non-zero. 887 */ 888 static int fillInColumnList(Parse *pParse, Select *p){ 889 int i, j, k, rc; 890 SrcList *pTabList; 891 ExprList *pEList; 892 Table *pTab; 893 894 if( p==0 || p->pSrc==0 ) return 1; 895 pTabList = p->pSrc; 896 pEList = p->pEList; 897 898 /* Look up every table in the table list. 899 */ 900 for(i=0; i<pTabList->nSrc; i++){ 901 if( pTabList->a[i].pTab ){ 902 /* This routine has run before! No need to continue */ 903 return 0; 904 } 905 if( pTabList->a[i].zName==0 ){ 906 /* A sub-query in the FROM clause of a SELECT */ 907 assert( pTabList->a[i].pSelect!=0 ); 908 if( pTabList->a[i].zAlias==0 ){ 909 char zFakeName[60]; 910 sprintf(zFakeName, "sqlite_subquery_%p_", 911 (void*)pTabList->a[i].pSelect); 912 sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0); 913 } 914 pTabList->a[i].pTab = pTab = 915 sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias, 916 pTabList->a[i].pSelect); 917 if( pTab==0 ){ 918 return 1; 919 } 920 /* The isTransient flag indicates that the Table structure has been 921 ** dynamically allocated and may be freed at any time. In other words, 922 ** pTab is not pointing to a persistent table structure that defines 923 ** part of the schema. */ 924 pTab->isTransient = 1; 925 }else{ 926 /* An ordinary table or view name in the FROM clause */ 927 pTabList->a[i].pTab = pTab = 928 sqliteLocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase); 929 if( pTab==0 ){ 930 return 1; 931 } 932 if( pTab->pSelect ){ 933 /* We reach here if the named table is a really a view */ 934 if( sqliteViewGetColumnNames(pParse, pTab) ){ 935 return 1; 936 } 937 /* If pTabList->a[i].pSelect!=0 it means we are dealing with a 938 ** view within a view. The SELECT structure has already been 939 ** copied by the outer view so we can skip the copy step here 940 ** in the inner view. 941 */ 942 if( pTabList->a[i].pSelect==0 ){ 943 pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect); 944 } 945 } 946 } 947 } 948 949 /* Process NATURAL keywords, and ON and USING clauses of joins. 950 */ 951 if( sqliteProcessJoin(pParse, p) ) return 1; 952 953 /* For every "*" that occurs in the column list, insert the names of 954 ** all columns in all tables. And for every TABLE.* insert the names 955 ** of all columns in TABLE. The parser inserted a special expression 956 ** with the TK_ALL operator for each "*" that it found in the column list. 957 ** The following code just has to locate the TK_ALL expressions and expand 958 ** each one to the list of all columns in all tables. 959 ** 960 ** The first loop just checks to see if there are any "*" operators 961 ** that need expanding. 962 */ 963 for(k=0; k<pEList->nExpr; k++){ 964 Expr *pE = pEList->a[k].pExpr; 965 if( pE->op==TK_ALL ) break; 966 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL 967 && pE->pLeft && pE->pLeft->op==TK_ID ) break; 968 } 969 rc = 0; 970 if( k<pEList->nExpr ){ 971 /* 972 ** If we get here it means the result set contains one or more "*" 973 ** operators that need to be expanded. Loop through each expression 974 ** in the result set and expand them one by one. 975 */ 976 struct ExprList_item *a = pEList->a; 977 ExprList *pNew = 0; 978 for(k=0; k<pEList->nExpr; k++){ 979 Expr *pE = a[k].pExpr; 980 if( pE->op!=TK_ALL && 981 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){ 982 /* This particular expression does not need to be expanded. 983 */ 984 pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0); 985 pNew->a[pNew->nExpr-1].zName = a[k].zName; 986 a[k].pExpr = 0; 987 a[k].zName = 0; 988 }else{ 989 /* This expression is a "*" or a "TABLE.*" and needs to be 990 ** expanded. */ 991 int tableSeen = 0; /* Set to 1 when TABLE matches */ 992 Token *pName; /* text of name of TABLE */ 993 if( pE->op==TK_DOT && pE->pLeft ){ 994 pName = &pE->pLeft->token; 995 }else{ 996 pName = 0; 997 } 998 for(i=0; i<pTabList->nSrc; i++){ 999 Table *pTab = pTabList->a[i].pTab; 1000 char *zTabName = pTabList->a[i].zAlias; 1001 if( zTabName==0 || zTabName[0]==0 ){ 1002 zTabName = pTab->zName; 1003 } 1004 if( pName && (zTabName==0 || zTabName[0]==0 || 1005 sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 || 1006 zTabName[pName->n]!=0) ){ 1007 continue; 1008 } 1009 tableSeen = 1; 1010 for(j=0; j<pTab->nCol; j++){ 1011 Expr *pExpr, *pLeft, *pRight; 1012 char *zName = pTab->aCol[j].zName; 1013 1014 if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 && 1015 columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){ 1016 /* In a NATURAL join, omit the join columns from the 1017 ** table on the right */ 1018 continue; 1019 } 1020 if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){ 1021 /* In a join with a USING clause, omit columns in the 1022 ** using clause from the table on the right. */ 1023 continue; 1024 } 1025 pRight = sqliteExpr(TK_ID, 0, 0, 0); 1026 if( pRight==0 ) break; 1027 pRight->token.z = zName; 1028 pRight->token.n = strlen(zName); 1029 pRight->token.dyn = 0; 1030 if( zTabName && pTabList->nSrc>1 ){ 1031 pLeft = sqliteExpr(TK_ID, 0, 0, 0); 1032 pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0); 1033 if( pExpr==0 ) break; 1034 pLeft->token.z = zTabName; 1035 pLeft->token.n = strlen(zTabName); 1036 pLeft->token.dyn = 0; 1037 sqliteSetString((char**)&pExpr->span.z, zTabName, ".", zName, 0); 1038 pExpr->span.n = strlen(pExpr->span.z); 1039 pExpr->span.dyn = 1; 1040 pExpr->token.z = 0; 1041 pExpr->token.n = 0; 1042 pExpr->token.dyn = 0; 1043 }else{ 1044 pExpr = pRight; 1045 pExpr->span = pExpr->token; 1046 } 1047 pNew = sqliteExprListAppend(pNew, pExpr, 0); 1048 } 1049 } 1050 if( !tableSeen ){ 1051 if( pName ){ 1052 sqliteErrorMsg(pParse, "no such table: %T", pName); 1053 }else{ 1054 sqliteErrorMsg(pParse, "no tables specified"); 1055 } 1056 rc = 1; 1057 } 1058 } 1059 } 1060 sqliteExprListDelete(pEList); 1061 p->pEList = pNew; 1062 } 1063 return rc; 1064 } 1065 1066 /* 1067 ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers 1068 ** in a select structure. It just sets the pointers to NULL. This 1069 ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect 1070 ** pointer is not NULL, this routine is called recursively on that pointer. 1071 ** 1072 ** This routine is called on the Select structure that defines a 1073 ** VIEW in order to undo any bindings to tables. This is necessary 1074 ** because those tables might be DROPed by a subsequent SQL command. 1075 ** If the bindings are not removed, then the Select.pSrc->a[].pTab field 1076 ** will be left pointing to a deallocated Table structure after the 1077 ** DROP and a coredump will occur the next time the VIEW is used. 1078 */ 1079 void sqliteSelectUnbind(Select *p){ 1080 int i; 1081 SrcList *pSrc = p->pSrc; 1082 Table *pTab; 1083 if( p==0 ) return; 1084 for(i=0; i<pSrc->nSrc; i++){ 1085 if( (pTab = pSrc->a[i].pTab)!=0 ){ 1086 if( pTab->isTransient ){ 1087 sqliteDeleteTable(0, pTab); 1088 } 1089 pSrc->a[i].pTab = 0; 1090 if( pSrc->a[i].pSelect ){ 1091 sqliteSelectUnbind(pSrc->a[i].pSelect); 1092 } 1093 } 1094 } 1095 } 1096 1097 /* 1098 ** This routine associates entries in an ORDER BY expression list with 1099 ** columns in a result. For each ORDER BY expression, the opcode of 1100 ** the top-level node is changed to TK_COLUMN and the iColumn value of 1101 ** the top-level node is filled in with column number and the iTable 1102 ** value of the top-level node is filled with iTable parameter. 1103 ** 1104 ** If there are prior SELECT clauses, they are processed first. A match 1105 ** in an earlier SELECT takes precedence over a later SELECT. 1106 ** 1107 ** Any entry that does not match is flagged as an error. The number 1108 ** of errors is returned. 1109 ** 1110 ** This routine does NOT correctly initialize the Expr.dataType field 1111 ** of the ORDER BY expressions. The multiSelectSortOrder() routine 1112 ** must be called to do that after the individual select statements 1113 ** have all been analyzed. This routine is unable to compute Expr.dataType 1114 ** because it must be called before the individual select statements 1115 ** have been analyzed. 1116 */ 1117 static int matchOrderbyToColumn( 1118 Parse *pParse, /* A place to leave error messages */ 1119 Select *pSelect, /* Match to result columns of this SELECT */ 1120 ExprList *pOrderBy, /* The ORDER BY values to match against columns */ 1121 int iTable, /* Insert this value in iTable */ 1122 int mustComplete /* If TRUE all ORDER BYs must match */ 1123 ){ 1124 int nErr = 0; 1125 int i, j; 1126 ExprList *pEList; 1127 1128 if( pSelect==0 || pOrderBy==0 ) return 1; 1129 if( mustComplete ){ 1130 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; } 1131 } 1132 if( fillInColumnList(pParse, pSelect) ){ 1133 return 1; 1134 } 1135 if( pSelect->pPrior ){ 1136 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){ 1137 return 1; 1138 } 1139 } 1140 pEList = pSelect->pEList; 1141 for(i=0; i<pOrderBy->nExpr; i++){ 1142 Expr *pE = pOrderBy->a[i].pExpr; 1143 int iCol = -1; 1144 if( pOrderBy->a[i].done ) continue; 1145 if( sqliteExprIsInteger(pE, &iCol) ){ 1146 if( iCol<=0 || iCol>pEList->nExpr ){ 1147 sqliteErrorMsg(pParse, 1148 "ORDER BY position %d should be between 1 and %d", 1149 iCol, pEList->nExpr); 1150 nErr++; 1151 break; 1152 } 1153 if( !mustComplete ) continue; 1154 iCol--; 1155 } 1156 for(j=0; iCol<0 && j<pEList->nExpr; j++){ 1157 if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){ 1158 char *zName, *zLabel; 1159 zName = pEList->a[j].zName; 1160 assert( pE->token.z ); 1161 zLabel = sqliteStrNDup(pE->token.z, pE->token.n); 1162 sqliteDequote(zLabel); 1163 if( sqliteStrICmp(zName, zLabel)==0 ){ 1164 iCol = j; 1165 } 1166 sqliteFree(zLabel); 1167 } 1168 if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){ 1169 iCol = j; 1170 } 1171 } 1172 if( iCol>=0 ){ 1173 pE->op = TK_COLUMN; 1174 pE->iColumn = iCol; 1175 pE->iTable = iTable; 1176 pOrderBy->a[i].done = 1; 1177 } 1178 if( iCol<0 && mustComplete ){ 1179 sqliteErrorMsg(pParse, 1180 "ORDER BY term number %d does not match any result column", i+1); 1181 nErr++; 1182 break; 1183 } 1184 } 1185 return nErr; 1186 } 1187 1188 /* 1189 ** Get a VDBE for the given parser context. Create a new one if necessary. 1190 ** If an error occurs, return NULL and leave a message in pParse. 1191 */ 1192 Vdbe *sqliteGetVdbe(Parse *pParse){ 1193 Vdbe *v = pParse->pVdbe; 1194 if( v==0 ){ 1195 v = pParse->pVdbe = sqliteVdbeCreate(pParse->db); 1196 } 1197 return v; 1198 } 1199 1200 /* 1201 ** This routine sets the Expr.dataType field on all elements of 1202 ** the pOrderBy expression list. The pOrderBy list will have been 1203 ** set up by matchOrderbyToColumn(). Hence each expression has 1204 ** a TK_COLUMN as its root node. The Expr.iColumn refers to a 1205 ** column in the result set. The datatype is set to SQLITE_SO_TEXT 1206 ** if the corresponding column in p and every SELECT to the left of 1207 ** p has a datatype of SQLITE_SO_TEXT. If the cooressponding column 1208 ** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype 1209 ** of the order-by expression is set to SQLITE_SO_NUM. 1210 ** 1211 ** Examples: 1212 ** 1213 ** CREATE TABLE one(a INTEGER, b TEXT); 1214 ** CREATE TABLE two(c VARCHAR(5), d FLOAT); 1215 ** 1216 ** SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2; 1217 ** 1218 ** The primary sort key will use SQLITE_SO_NUM because the "d" in 1219 ** the second SELECT is numeric. The 1st column of the first SELECT 1220 ** is text but that does not matter because a numeric always overrides 1221 ** a text. 1222 ** 1223 ** The secondary key will use the SQLITE_SO_TEXT sort order because 1224 ** both the (second) "b" in the first SELECT and the "c" in the second 1225 ** SELECT have a datatype of text. 1226 */ 1227 static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){ 1228 int i; 1229 ExprList *pEList; 1230 if( pOrderBy==0 ) return; 1231 if( p==0 ){ 1232 for(i=0; i<pOrderBy->nExpr; i++){ 1233 pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT; 1234 } 1235 return; 1236 } 1237 multiSelectSortOrder(p->pPrior, pOrderBy); 1238 pEList = p->pEList; 1239 for(i=0; i<pOrderBy->nExpr; i++){ 1240 Expr *pE = pOrderBy->a[i].pExpr; 1241 if( pE->dataType==SQLITE_SO_NUM ) continue; 1242 assert( pE->iColumn>=0 ); 1243 if( pEList->nExpr>pE->iColumn ){ 1244 pE->dataType = sqliteExprType(pEList->a[pE->iColumn].pExpr); 1245 } 1246 } 1247 } 1248 1249 /* 1250 ** Compute the iLimit and iOffset fields of the SELECT based on the 1251 ** nLimit and nOffset fields. nLimit and nOffset hold the integers 1252 ** that appear in the original SQL statement after the LIMIT and OFFSET 1253 ** keywords. Or that hold -1 and 0 if those keywords are omitted. 1254 ** iLimit and iOffset are the integer memory register numbers for 1255 ** counters used to compute the limit and offset. If there is no 1256 ** limit and/or offset, then iLimit and iOffset are negative. 1257 ** 1258 ** This routine changes the values if iLimit and iOffset only if 1259 ** a limit or offset is defined by nLimit and nOffset. iLimit and 1260 ** iOffset should have been preset to appropriate default values 1261 ** (usually but not always -1) prior to calling this routine. 1262 ** Only if nLimit>=0 or nOffset>0 do the limit registers get 1263 ** redefined. The UNION ALL operator uses this property to force 1264 ** the reuse of the same limit and offset registers across multiple 1265 ** SELECT statements. 1266 */ 1267 static void computeLimitRegisters(Parse *pParse, Select *p){ 1268 /* 1269 ** If the comparison is p->nLimit>0 then "LIMIT 0" shows 1270 ** all rows. It is the same as no limit. If the comparision is 1271 ** p->nLimit>=0 then "LIMIT 0" show no rows at all. 1272 ** "LIMIT -1" always shows all rows. There is some 1273 ** contraversy about what the correct behavior should be. 1274 ** The current implementation interprets "LIMIT 0" to mean 1275 ** no rows. 1276 */ 1277 if( p->nLimit>=0 ){ 1278 int iMem = pParse->nMem++; 1279 Vdbe *v = sqliteGetVdbe(pParse); 1280 if( v==0 ) return; 1281 sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0); 1282 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1); 1283 p->iLimit = iMem; 1284 } 1285 if( p->nOffset>0 ){ 1286 int iMem = pParse->nMem++; 1287 Vdbe *v = sqliteGetVdbe(pParse); 1288 if( v==0 ) return; 1289 sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0); 1290 sqliteVdbeAddOp(v, OP_MemStore, iMem, 1); 1291 p->iOffset = iMem; 1292 } 1293 } 1294 1295 /* 1296 ** This routine is called to process a query that is really the union 1297 ** or intersection of two or more separate queries. 1298 ** 1299 ** "p" points to the right-most of the two queries. the query on the 1300 ** left is p->pPrior. The left query could also be a compound query 1301 ** in which case this routine will be called recursively. 1302 ** 1303 ** The results of the total query are to be written into a destination 1304 ** of type eDest with parameter iParm. 1305 ** 1306 ** Example 1: Consider a three-way compound SQL statement. 1307 ** 1308 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 1309 ** 1310 ** This statement is parsed up as follows: 1311 ** 1312 ** SELECT c FROM t3 1313 ** | 1314 ** `-----> SELECT b FROM t2 1315 ** | 1316 ** `------> SELECT c FROM t1 1317 ** 1318 ** The arrows in the diagram above represent the Select.pPrior pointer. 1319 ** So if this routine is called with p equal to the t3 query, then 1320 ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 1321 ** 1322 ** Notice that because of the way SQLite parses compound SELECTs, the 1323 ** individual selects always group from left to right. 1324 */ 1325 static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){ 1326 int rc; /* Success code from a subroutine */ 1327 Select *pPrior; /* Another SELECT immediately to our left */ 1328 Vdbe *v; /* Generate code to this VDBE */ 1329 1330 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 1331 ** the last SELECT in the series may have an ORDER BY or LIMIT. 1332 */ 1333 if( p==0 || p->pPrior==0 ) return 1; 1334 pPrior = p->pPrior; 1335 if( pPrior->pOrderBy ){ 1336 sqliteErrorMsg(pParse,"ORDER BY clause should come after %s not before", 1337 selectOpName(p->op)); 1338 return 1; 1339 } 1340 if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){ 1341 sqliteErrorMsg(pParse,"LIMIT clause should come after %s not before", 1342 selectOpName(p->op)); 1343 return 1; 1344 } 1345 1346 /* Make sure we have a valid query engine. If not, create a new one. 1347 */ 1348 v = sqliteGetVdbe(pParse); 1349 if( v==0 ) return 1; 1350 1351 /* Create the destination temporary table if necessary 1352 */ 1353 if( eDest==SRT_TempTable ){ 1354 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0); 1355 eDest = SRT_Table; 1356 } 1357 1358 /* Generate code for the left and right SELECT statements. 1359 */ 1360 switch( p->op ){ 1361 case TK_ALL: { 1362 if( p->pOrderBy==0 ){ 1363 pPrior->nLimit = p->nLimit; 1364 pPrior->nOffset = p->nOffset; 1365 rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0); 1366 if( rc ) return rc; 1367 p->pPrior = 0; 1368 p->iLimit = pPrior->iLimit; 1369 p->iOffset = pPrior->iOffset; 1370 p->nLimit = -1; 1371 p->nOffset = 0; 1372 rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0); 1373 p->pPrior = pPrior; 1374 if( rc ) return rc; 1375 break; 1376 } 1377 /* For UNION ALL ... ORDER BY fall through to the next case */ 1378 } 1379 case TK_EXCEPT: 1380 case TK_UNION: { 1381 int unionTab; /* Cursor number of the temporary table holding result */ 1382 int op; /* One of the SRT_ operations to apply to self */ 1383 int priorOp; /* The SRT_ operation to apply to prior selects */ 1384 int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */ 1385 ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */ 1386 1387 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union; 1388 if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){ 1389 /* We can reuse a temporary table generated by a SELECT to our 1390 ** right. 1391 */ 1392 unionTab = iParm; 1393 }else{ 1394 /* We will need to create our own temporary table to hold the 1395 ** intermediate results. 1396 */ 1397 unionTab = pParse->nTab++; 1398 if( p->pOrderBy 1399 && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){ 1400 return 1; 1401 } 1402 if( p->op!=TK_ALL ){ 1403 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1); 1404 sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1); 1405 }else{ 1406 sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0); 1407 } 1408 } 1409 1410 /* Code the SELECT statements to our left 1411 */ 1412 rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0); 1413 if( rc ) return rc; 1414 1415 /* Code the current SELECT statement 1416 */ 1417 switch( p->op ){ 1418 case TK_EXCEPT: op = SRT_Except; break; 1419 case TK_UNION: op = SRT_Union; break; 1420 case TK_ALL: op = SRT_Table; break; 1421 } 1422 p->pPrior = 0; 1423 pOrderBy = p->pOrderBy; 1424 p->pOrderBy = 0; 1425 nLimit = p->nLimit; 1426 p->nLimit = -1; 1427 nOffset = p->nOffset; 1428 p->nOffset = 0; 1429 rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0); 1430 p->pPrior = pPrior; 1431 p->pOrderBy = pOrderBy; 1432 p->nLimit = nLimit; 1433 p->nOffset = nOffset; 1434 if( rc ) return rc; 1435 1436 /* Convert the data in the temporary table into whatever form 1437 ** it is that we currently need. 1438 */ 1439 if( eDest!=priorOp || unionTab!=iParm ){ 1440 int iCont, iBreak, iStart; 1441 assert( p->pEList ); 1442 if( eDest==SRT_Callback ){ 1443 generateColumnNames(pParse, 0, p->pEList); 1444 generateColumnTypes(pParse, p->pSrc, p->pEList); 1445 } 1446 iBreak = sqliteVdbeMakeLabel(v); 1447 iCont = sqliteVdbeMakeLabel(v); 1448 sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak); 1449 computeLimitRegisters(pParse, p); 1450 iStart = sqliteVdbeCurrentAddr(v); 1451 multiSelectSortOrder(p, p->pOrderBy); 1452 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, 1453 p->pOrderBy, -1, eDest, iParm, 1454 iCont, iBreak); 1455 if( rc ) return 1; 1456 sqliteVdbeResolveLabel(v, iCont); 1457 sqliteVdbeAddOp(v, OP_Next, unionTab, iStart); 1458 sqliteVdbeResolveLabel(v, iBreak); 1459 sqliteVdbeAddOp(v, OP_Close, unionTab, 0); 1460 if( p->pOrderBy ){ 1461 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm); 1462 } 1463 } 1464 break; 1465 } 1466 case TK_INTERSECT: { 1467 int tab1, tab2; 1468 int iCont, iBreak, iStart; 1469 int nLimit, nOffset; 1470 1471 /* INTERSECT is different from the others since it requires 1472 ** two temporary tables. Hence it has its own case. Begin 1473 ** by allocating the tables we will need. 1474 */ 1475 tab1 = pParse->nTab++; 1476 tab2 = pParse->nTab++; 1477 if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){ 1478 return 1; 1479 } 1480 sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1); 1481 sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1); 1482 1483 /* Code the SELECTs to our left into temporary table "tab1". 1484 */ 1485 rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0); 1486 if( rc ) return rc; 1487 1488 /* Code the current SELECT into temporary table "tab2" 1489 */ 1490 sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1); 1491 sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1); 1492 p->pPrior = 0; 1493 nLimit = p->nLimit; 1494 p->nLimit = -1; 1495 nOffset = p->nOffset; 1496 p->nOffset = 0; 1497 rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0); 1498 p->pPrior = pPrior; 1499 p->nLimit = nLimit; 1500 p->nOffset = nOffset; 1501 if( rc ) return rc; 1502 1503 /* Generate code to take the intersection of the two temporary 1504 ** tables. 1505 */ 1506 assert( p->pEList ); 1507 if( eDest==SRT_Callback ){ 1508 generateColumnNames(pParse, 0, p->pEList); 1509 generateColumnTypes(pParse, p->pSrc, p->pEList); 1510 } 1511 iBreak = sqliteVdbeMakeLabel(v); 1512 iCont = sqliteVdbeMakeLabel(v); 1513 sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak); 1514 computeLimitRegisters(pParse, p); 1515 iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0); 1516 sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont); 1517 multiSelectSortOrder(p, p->pOrderBy); 1518 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, 1519 p->pOrderBy, -1, eDest, iParm, 1520 iCont, iBreak); 1521 if( rc ) return 1; 1522 sqliteVdbeResolveLabel(v, iCont); 1523 sqliteVdbeAddOp(v, OP_Next, tab1, iStart); 1524 sqliteVdbeResolveLabel(v, iBreak); 1525 sqliteVdbeAddOp(v, OP_Close, tab2, 0); 1526 sqliteVdbeAddOp(v, OP_Close, tab1, 0); 1527 if( p->pOrderBy ){ 1528 generateSortTail(p, v, p->pEList->nExpr, eDest, iParm); 1529 } 1530 break; 1531 } 1532 } 1533 assert( p->pEList && pPrior->pEList ); 1534 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 1535 sqliteErrorMsg(pParse, "SELECTs to the left and right of %s" 1536 " do not have the same number of result columns", selectOpName(p->op)); 1537 return 1; 1538 } 1539 1540 /* Issue a null callback if that is what the user wants. 1541 */ 1542 if( eDest==SRT_Callback && 1543 (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0) 1544 ){ 1545 sqliteVdbeAddOp(v, OP_NullCallback, p->pEList->nExpr, 0); 1546 } 1547 return 0; 1548 } 1549 1550 /* 1551 ** Scan through the expression pExpr. Replace every reference to 1552 ** a column in table number iTable with a copy of the iColumn-th 1553 ** entry in pEList. (But leave references to the ROWID column 1554 ** unchanged.) 1555 ** 1556 ** This routine is part of the flattening procedure. A subquery 1557 ** whose result set is defined by pEList appears as entry in the 1558 ** FROM clause of a SELECT such that the VDBE cursor assigned to that 1559 ** FORM clause entry is iTable. This routine make the necessary 1560 ** changes to pExpr so that it refers directly to the source table 1561 ** of the subquery rather the result set of the subquery. 1562 */ 1563 static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */ 1564 static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){ 1565 if( pExpr==0 ) return; 1566 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){ 1567 Expr *pNew; 1568 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 1569 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 ); 1570 pNew = pEList->a[pExpr->iColumn].pExpr; 1571 assert( pNew!=0 ); 1572 pExpr->op = pNew->op; 1573 pExpr->dataType = pNew->dataType; 1574 assert( pExpr->pLeft==0 ); 1575 pExpr->pLeft = sqliteExprDup(pNew->pLeft); 1576 assert( pExpr->pRight==0 ); 1577 pExpr->pRight = sqliteExprDup(pNew->pRight); 1578 assert( pExpr->pList==0 ); 1579 pExpr->pList = sqliteExprListDup(pNew->pList); 1580 pExpr->iTable = pNew->iTable; 1581 pExpr->iColumn = pNew->iColumn; 1582 pExpr->iAgg = pNew->iAgg; 1583 sqliteTokenCopy(&pExpr->token, &pNew->token); 1584 sqliteTokenCopy(&pExpr->span, &pNew->span); 1585 }else{ 1586 substExpr(pExpr->pLeft, iTable, pEList); 1587 substExpr(pExpr->pRight, iTable, pEList); 1588 substExprList(pExpr->pList, iTable, pEList); 1589 } 1590 } 1591 static void 1592 substExprList(ExprList *pList, int iTable, ExprList *pEList){ 1593 int i; 1594 if( pList==0 ) return; 1595 for(i=0; i<pList->nExpr; i++){ 1596 substExpr(pList->a[i].pExpr, iTable, pEList); 1597 } 1598 } 1599 1600 /* 1601 ** This routine attempts to flatten subqueries in order to speed 1602 ** execution. It returns 1 if it makes changes and 0 if no flattening 1603 ** occurs. 1604 ** 1605 ** To understand the concept of flattening, consider the following 1606 ** query: 1607 ** 1608 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 1609 ** 1610 ** The default way of implementing this query is to execute the 1611 ** subquery first and store the results in a temporary table, then 1612 ** run the outer query on that temporary table. This requires two 1613 ** passes over the data. Furthermore, because the temporary table 1614 ** has no indices, the WHERE clause on the outer query cannot be 1615 ** optimized. 1616 ** 1617 ** This routine attempts to rewrite queries such as the above into 1618 ** a single flat select, like this: 1619 ** 1620 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 1621 ** 1622 ** The code generated for this simpification gives the same result 1623 ** but only has to scan the data once. And because indices might 1624 ** exist on the table t1, a complete scan of the data might be 1625 ** avoided. 1626 ** 1627 ** Flattening is only attempted if all of the following are true: 1628 ** 1629 ** (1) The subquery and the outer query do not both use aggregates. 1630 ** 1631 ** (2) The subquery is not an aggregate or the outer query is not a join. 1632 ** 1633 ** (3) The subquery is not the right operand of a left outer join, or 1634 ** the subquery is not itself a join. (Ticket #306) 1635 ** 1636 ** (4) The subquery is not DISTINCT or the outer query is not a join. 1637 ** 1638 ** (5) The subquery is not DISTINCT or the outer query does not use 1639 ** aggregates. 1640 ** 1641 ** (6) The subquery does not use aggregates or the outer query is not 1642 ** DISTINCT. 1643 ** 1644 ** (7) The subquery has a FROM clause. 1645 ** 1646 ** (8) The subquery does not use LIMIT or the outer query is not a join. 1647 ** 1648 ** (9) The subquery does not use LIMIT or the outer query does not use 1649 ** aggregates. 1650 ** 1651 ** (10) The subquery does not use aggregates or the outer query does not 1652 ** use LIMIT. 1653 ** 1654 ** (11) The subquery and the outer query do not both have ORDER BY clauses. 1655 ** 1656 ** (12) The subquery is not the right term of a LEFT OUTER JOIN or the 1657 ** subquery has no WHERE clause. (added by ticket #350) 1658 ** 1659 ** In this routine, the "p" parameter is a pointer to the outer query. 1660 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 1661 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 1662 ** 1663 ** If flattening is not attempted, this routine is a no-op and returns 0. 1664 ** If flattening is attempted this routine returns 1. 1665 ** 1666 ** All of the expression analysis must occur on both the outer query and 1667 ** the subquery before this routine runs. 1668 */ 1669 static int flattenSubquery( 1670 Parse *pParse, /* The parsing context */ 1671 Select *p, /* The parent or outer SELECT statement */ 1672 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 1673 int isAgg, /* True if outer SELECT uses aggregate functions */ 1674 int subqueryIsAgg /* True if the subquery uses aggregate functions */ 1675 ){ 1676 Select *pSub; /* The inner query or "subquery" */ 1677 SrcList *pSrc; /* The FROM clause of the outer query */ 1678 SrcList *pSubSrc; /* The FROM clause of the subquery */ 1679 ExprList *pList; /* The result set of the outer query */ 1680 int iParent; /* VDBE cursor number of the pSub result set temp table */ 1681 int i; 1682 Expr *pWhere; 1683 1684 /* Check to see if flattening is permitted. Return 0 if not. 1685 */ 1686 if( p==0 ) return 0; 1687 pSrc = p->pSrc; 1688 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 1689 pSub = pSrc->a[iFrom].pSelect; 1690 assert( pSub!=0 ); 1691 if( isAgg && subqueryIsAgg ) return 0; 1692 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; 1693 pSubSrc = pSub->pSrc; 1694 assert( pSubSrc ); 1695 if( pSubSrc->nSrc==0 ) return 0; 1696 if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){ 1697 return 0; 1698 } 1699 if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0; 1700 if( p->pOrderBy && pSub->pOrderBy ) return 0; 1701 1702 /* Restriction 3: If the subquery is a join, make sure the subquery is 1703 ** not used as the right operand of an outer join. Examples of why this 1704 ** is not allowed: 1705 ** 1706 ** t1 LEFT OUTER JOIN (t2 JOIN t3) 1707 ** 1708 ** If we flatten the above, we would get 1709 ** 1710 ** (t1 LEFT OUTER JOIN t2) JOIN t3 1711 ** 1712 ** which is not at all the same thing. 1713 */ 1714 if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){ 1715 return 0; 1716 } 1717 1718 /* Restriction 12: If the subquery is the right operand of a left outer 1719 ** join, make sure the subquery has no WHERE clause. 1720 ** An examples of why this is not allowed: 1721 ** 1722 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 1723 ** 1724 ** If we flatten the above, we would get 1725 ** 1726 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 1727 ** 1728 ** But the t2.x>0 test will always fail on a NULL row of t2, which 1729 ** effectively converts the OUTER JOIN into an INNER JOIN. 1730 */ 1731 if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 1732 && pSub->pWhere!=0 ){ 1733 return 0; 1734 } 1735 1736 /* If we reach this point, it means flattening is permitted for the 1737 ** iFrom-th entry of the FROM clause in the outer query. 1738 */ 1739 1740 /* Move all of the FROM elements of the subquery into the 1741 ** the FROM clause of the outer query. Before doing this, remember 1742 ** the cursor number for the original outer query FROM element in 1743 ** iParent. The iParent cursor will never be used. Subsequent code 1744 ** will scan expressions looking for iParent references and replace 1745 ** those references with expressions that resolve to the subquery FROM 1746 ** elements we are now copying in. 1747 */ 1748 iParent = pSrc->a[iFrom].iCursor; 1749 { 1750 int nSubSrc = pSubSrc->nSrc; 1751 int jointype = pSrc->a[iFrom].jointype; 1752 1753 if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){ 1754 sqliteDeleteTable(0, pSrc->a[iFrom].pTab); 1755 } 1756 sqliteFree(pSrc->a[iFrom].zDatabase); 1757 sqliteFree(pSrc->a[iFrom].zName); 1758 sqliteFree(pSrc->a[iFrom].zAlias); 1759 if( nSubSrc>1 ){ 1760 int extra = nSubSrc - 1; 1761 for(i=1; i<nSubSrc; i++){ 1762 pSrc = sqliteSrcListAppend(pSrc, 0, 0); 1763 } 1764 p->pSrc = pSrc; 1765 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){ 1766 pSrc->a[i] = pSrc->a[i-extra]; 1767 } 1768 } 1769 for(i=0; i<nSubSrc; i++){ 1770 pSrc->a[i+iFrom] = pSubSrc->a[i]; 1771 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 1772 } 1773 pSrc->a[iFrom+nSubSrc-1].jointype = jointype; 1774 } 1775 1776 /* Now begin substituting subquery result set expressions for 1777 ** references to the iParent in the outer query. 1778 ** 1779 ** Example: 1780 ** 1781 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 1782 ** \ \_____________ subquery __________/ / 1783 ** \_____________________ outer query ______________________________/ 1784 ** 1785 ** We look at every expression in the outer query and every place we see 1786 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 1787 */ 1788 substExprList(p->pEList, iParent, pSub->pEList); 1789 pList = p->pEList; 1790 for(i=0; i<pList->nExpr; i++){ 1791 Expr *pExpr; 1792 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){ 1793 pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n); 1794 } 1795 } 1796 if( isAgg ){ 1797 substExprList(p->pGroupBy, iParent, pSub->pEList); 1798 substExpr(p->pHaving, iParent, pSub->pEList); 1799 } 1800 if( pSub->pOrderBy ){ 1801 assert( p->pOrderBy==0 ); 1802 p->pOrderBy = pSub->pOrderBy; 1803 pSub->pOrderBy = 0; 1804 }else if( p->pOrderBy ){ 1805 substExprList(p->pOrderBy, iParent, pSub->pEList); 1806 } 1807 if( pSub->pWhere ){ 1808 pWhere = sqliteExprDup(pSub->pWhere); 1809 }else{ 1810 pWhere = 0; 1811 } 1812 if( subqueryIsAgg ){ 1813 assert( p->pHaving==0 ); 1814 p->pHaving = p->pWhere; 1815 p->pWhere = pWhere; 1816 substExpr(p->pHaving, iParent, pSub->pEList); 1817 if( pSub->pHaving ){ 1818 Expr *pHaving = sqliteExprDup(pSub->pHaving); 1819 if( p->pHaving ){ 1820 p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0); 1821 }else{ 1822 p->pHaving = pHaving; 1823 } 1824 } 1825 assert( p->pGroupBy==0 ); 1826 p->pGroupBy = sqliteExprListDup(pSub->pGroupBy); 1827 }else if( p->pWhere==0 ){ 1828 p->pWhere = pWhere; 1829 }else{ 1830 substExpr(p->pWhere, iParent, pSub->pEList); 1831 if( pWhere ){ 1832 p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0); 1833 } 1834 } 1835 1836 /* The flattened query is distinct if either the inner or the 1837 ** outer query is distinct. 1838 */ 1839 p->isDistinct = p->isDistinct || pSub->isDistinct; 1840 1841 /* Transfer the limit expression from the subquery to the outer 1842 ** query. 1843 */ 1844 if( pSub->nLimit>=0 ){ 1845 if( p->nLimit<0 ){ 1846 p->nLimit = pSub->nLimit; 1847 }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){ 1848 p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset; 1849 } 1850 } 1851 p->nOffset += pSub->nOffset; 1852 1853 /* Finially, delete what is left of the subquery and return 1854 ** success. 1855 */ 1856 sqliteSelectDelete(pSub); 1857 return 1; 1858 } 1859 1860 /* 1861 ** Analyze the SELECT statement passed in as an argument to see if it 1862 ** is a simple min() or max() query. If it is and this query can be 1863 ** satisfied using a single seek to the beginning or end of an index, 1864 ** then generate the code for this SELECT and return 1. If this is not a 1865 ** simple min() or max() query, then return 0; 1866 ** 1867 ** A simply min() or max() query looks like this: 1868 ** 1869 ** SELECT min(a) FROM table; 1870 ** SELECT max(a) FROM table; 1871 ** 1872 ** The query may have only a single table in its FROM argument. There 1873 ** can be no GROUP BY or HAVING or WHERE clauses. The result set must 1874 ** be the min() or max() of a single column of the table. The column 1875 ** in the min() or max() function must be indexed. 1876 ** 1877 ** The parameters to this routine are the same as for sqliteSelect(). 1878 ** See the header comment on that routine for additional information. 1879 */ 1880 static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){ 1881 Expr *pExpr; 1882 int iCol; 1883 Table *pTab; 1884 Index *pIdx; 1885 int base; 1886 Vdbe *v; 1887 int seekOp; 1888 int cont; 1889 ExprList eList; 1890 struct ExprList_item eListItem; 1891 1892 /* Check to see if this query is a simple min() or max() query. Return 1893 ** zero if it is not. 1894 */ 1895 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0; 1896 if( p->pSrc->nSrc!=1 ) return 0; 1897 if( p->pEList->nExpr!=1 ) return 0; 1898 pExpr = p->pEList->a[0].pExpr; 1899 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 1900 if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0; 1901 if( pExpr->token.n!=3 ) return 0; 1902 if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){ 1903 seekOp = OP_Rewind; 1904 }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){ 1905 seekOp = OP_Last; 1906 }else{ 1907 return 0; 1908 } 1909 pExpr = pExpr->pList->a[0].pExpr; 1910 if( pExpr->op!=TK_COLUMN ) return 0; 1911 iCol = pExpr->iColumn; 1912 pTab = p->pSrc->a[0].pTab; 1913 1914 /* If we get to here, it means the query is of the correct form. 1915 ** Check to make sure we have an index and make pIdx point to the 1916 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY 1917 ** key column, no index is necessary so set pIdx to NULL. If no 1918 ** usable index is found, return 0. 1919 */ 1920 if( iCol<0 ){ 1921 pIdx = 0; 1922 }else{ 1923 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 1924 assert( pIdx->nColumn>=1 ); 1925 if( pIdx->aiColumn[0]==iCol ) break; 1926 } 1927 if( pIdx==0 ) return 0; 1928 } 1929 1930 /* Identify column types if we will be using the callback. This 1931 ** step is skipped if the output is going to a table or a memory cell. 1932 ** The column names have already been generated in the calling function. 1933 */ 1934 v = sqliteGetVdbe(pParse); 1935 if( v==0 ) return 0; 1936 if( eDest==SRT_Callback ){ 1937 generateColumnTypes(pParse, p->pSrc, p->pEList); 1938 } 1939 1940 /* Generating code to find the min or the max. Basically all we have 1941 ** to do is find the first or the last entry in the chosen index. If 1942 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first 1943 ** or last entry in the main table. 1944 */ 1945 sqliteCodeVerifySchema(pParse, pTab->iDb); 1946 base = p->pSrc->a[0].iCursor; 1947 computeLimitRegisters(pParse, p); 1948 sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0); 1949 sqliteVdbeAddOp(v, OP_OpenRead, base, pTab->tnum); 1950 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC); 1951 cont = sqliteVdbeMakeLabel(v); 1952 if( pIdx==0 ){ 1953 sqliteVdbeAddOp(v, seekOp, base, 0); 1954 }else{ 1955 sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0); 1956 sqliteVdbeAddOp(v, OP_OpenRead, base+1, pIdx->tnum); 1957 sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC); 1958 sqliteVdbeAddOp(v, seekOp, base+1, 0); 1959 sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0); 1960 sqliteVdbeAddOp(v, OP_Close, base+1, 0); 1961 sqliteVdbeAddOp(v, OP_MoveTo, base, 0); 1962 } 1963 eList.nExpr = 1; 1964 memset(&eListItem, 0, sizeof(eListItem)); 1965 eList.a = &eListItem; 1966 eList.a[0].pExpr = pExpr; 1967 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont); 1968 sqliteVdbeResolveLabel(v, cont); 1969 sqliteVdbeAddOp(v, OP_Close, base, 0); 1970 return 1; 1971 } 1972 1973 /* 1974 ** Generate code for the given SELECT statement. 1975 ** 1976 ** The results are distributed in various ways depending on the 1977 ** value of eDest and iParm. 1978 ** 1979 ** eDest Value Result 1980 ** ------------ ------------------------------------------- 1981 ** SRT_Callback Invoke the callback for each row of the result. 1982 ** 1983 ** SRT_Mem Store first result in memory cell iParm 1984 ** 1985 ** SRT_Set Store results as keys of a table with cursor iParm 1986 ** 1987 ** SRT_Union Store results as a key in a temporary table iParm 1988 ** 1989 ** SRT_Except Remove results form the temporary table iParm. 1990 ** 1991 ** SRT_Table Store results in temporary table iParm 1992 ** 1993 ** The table above is incomplete. Additional eDist value have be added 1994 ** since this comment was written. See the selectInnerLoop() function for 1995 ** a complete listing of the allowed values of eDest and their meanings. 1996 ** 1997 ** This routine returns the number of errors. If any errors are 1998 ** encountered, then an appropriate error message is left in 1999 ** pParse->zErrMsg. 2000 ** 2001 ** This routine does NOT free the Select structure passed in. The 2002 ** calling function needs to do that. 2003 ** 2004 ** The pParent, parentTab, and *pParentAgg fields are filled in if this 2005 ** SELECT is a subquery. This routine may try to combine this SELECT 2006 ** with its parent to form a single flat query. In so doing, it might 2007 ** change the parent query from a non-aggregate to an aggregate query. 2008 ** For that reason, the pParentAgg flag is passed as a pointer, so it 2009 ** can be changed. 2010 ** 2011 ** Example 1: The meaning of the pParent parameter. 2012 ** 2013 ** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3; 2014 ** \ \_______ subquery _______/ / 2015 ** \ / 2016 ** \____________________ outer query ___________________/ 2017 ** 2018 ** This routine is called for the outer query first. For that call, 2019 ** pParent will be NULL. During the processing of the outer query, this 2020 ** routine is called recursively to handle the subquery. For the recursive 2021 ** call, pParent will point to the outer query. Because the subquery is 2022 ** the second element in a three-way join, the parentTab parameter will 2023 ** be 1 (the 2nd value of a 0-indexed array.) 2024 */ 2025 int sqliteSelect( 2026 Parse *pParse, /* The parser context */ 2027 Select *p, /* The SELECT statement being coded. */ 2028 int eDest, /* How to dispose of the results */ 2029 int iParm, /* A parameter used by the eDest disposal method */ 2030 Select *pParent, /* Another SELECT for which this is a sub-query */ 2031 int parentTab, /* Index in pParent->pSrc of this query */ 2032 int *pParentAgg /* True if pParent uses aggregate functions */ 2033 ){ 2034 int i; 2035 WhereInfo *pWInfo; 2036 Vdbe *v; 2037 int isAgg = 0; /* True for select lists like "count(*)" */ 2038 ExprList *pEList; /* List of columns to extract. */ 2039 SrcList *pTabList; /* List of tables to select from */ 2040 Expr *pWhere; /* The WHERE clause. May be NULL */ 2041 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 2042 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 2043 Expr *pHaving; /* The HAVING clause. May be NULL */ 2044 int isDistinct; /* True if the DISTINCT keyword is present */ 2045 int distinct; /* Table to use for the distinct set */ 2046 int rc = 1; /* Value to return from this function */ 2047 2048 if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1; 2049 if( sqliteAuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 2050 2051 /* If there is are a sequence of queries, do the earlier ones first. 2052 */ 2053 if( p->pPrior ){ 2054 return multiSelect(pParse, p, eDest, iParm); 2055 } 2056 2057 /* Make local copies of the parameters for this query. 2058 */ 2059 pTabList = p->pSrc; 2060 pWhere = p->pWhere; 2061 pOrderBy = p->pOrderBy; 2062 pGroupBy = p->pGroupBy; 2063 pHaving = p->pHaving; 2064 isDistinct = p->isDistinct; 2065 2066 /* Allocate VDBE cursors for each table in the FROM clause 2067 */ 2068 sqliteSrcListAssignCursors(pParse, pTabList); 2069 2070 /* 2071 ** Do not even attempt to generate any code if we have already seen 2072 ** errors before this routine starts. 2073 */ 2074 if( pParse->nErr>0 ) goto select_end; 2075 2076 /* Expand any "*" terms in the result set. (For example the "*" in 2077 ** "SELECT * FROM t1") The fillInColumnlist() routine also does some 2078 ** other housekeeping - see the header comment for details. 2079 */ 2080 if( fillInColumnList(pParse, p) ){ 2081 goto select_end; 2082 } 2083 pWhere = p->pWhere; 2084 pEList = p->pEList; 2085 if( pEList==0 ) goto select_end; 2086 2087 /* If writing to memory or generating a set 2088 ** only a single column may be output. 2089 */ 2090 if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){ 2091 sqliteErrorMsg(pParse, "only a single result allowed for " 2092 "a SELECT that is part of an expression"); 2093 goto select_end; 2094 } 2095 2096 /* ORDER BY is ignored for some destinations. 2097 */ 2098 switch( eDest ){ 2099 case SRT_Union: 2100 case SRT_Except: 2101 case SRT_Discard: 2102 pOrderBy = 0; 2103 break; 2104 default: 2105 break; 2106 } 2107 2108 /* At this point, we should have allocated all the cursors that we 2109 ** need to handle subquerys and temporary tables. 2110 ** 2111 ** Resolve the column names and do a semantics check on all the expressions. 2112 */ 2113 for(i=0; i<pEList->nExpr; i++){ 2114 if( sqliteExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){ 2115 goto select_end; 2116 } 2117 if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){ 2118 goto select_end; 2119 } 2120 } 2121 if( pWhere ){ 2122 if( sqliteExprResolveIds(pParse, pTabList, pEList, pWhere) ){ 2123 goto select_end; 2124 } 2125 if( sqliteExprCheck(pParse, pWhere, 0, 0) ){ 2126 goto select_end; 2127 } 2128 sqliteOracle8JoinFixup(pTabList, pWhere); 2129 } 2130 if( pHaving ){ 2131 if( pGroupBy==0 ){ 2132 sqliteErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); 2133 goto select_end; 2134 } 2135 if( sqliteExprResolveIds(pParse, pTabList, pEList, pHaving) ){ 2136 goto select_end; 2137 } 2138 if( sqliteExprCheck(pParse, pHaving, 1, &isAgg) ){ 2139 goto select_end; 2140 } 2141 } 2142 if( pOrderBy ){ 2143 for(i=0; i<pOrderBy->nExpr; i++){ 2144 int iCol; 2145 Expr *pE = pOrderBy->a[i].pExpr; 2146 if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){ 2147 sqliteExprDelete(pE); 2148 pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr); 2149 } 2150 if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){ 2151 goto select_end; 2152 } 2153 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){ 2154 goto select_end; 2155 } 2156 if( sqliteExprIsConstant(pE) ){ 2157 if( sqliteExprIsInteger(pE, &iCol)==0 ){ 2158 sqliteErrorMsg(pParse, 2159 "ORDER BY terms must not be non-integer constants"); 2160 goto select_end; 2161 }else if( iCol<=0 || iCol>pEList->nExpr ){ 2162 sqliteErrorMsg(pParse, 2163 "ORDER BY column number %d out of range - should be " 2164 "between 1 and %d", iCol, pEList->nExpr); 2165 goto select_end; 2166 } 2167 } 2168 } 2169 } 2170 if( pGroupBy ){ 2171 for(i=0; i<pGroupBy->nExpr; i++){ 2172 int iCol; 2173 Expr *pE = pGroupBy->a[i].pExpr; 2174 if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){ 2175 sqliteExprDelete(pE); 2176 pE = pGroupBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr); 2177 } 2178 if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){ 2179 goto select_end; 2180 } 2181 if( sqliteExprCheck(pParse, pE, isAgg, 0) ){ 2182 goto select_end; 2183 } 2184 if( sqliteExprIsConstant(pE) ){ 2185 if( sqliteExprIsInteger(pE, &iCol)==0 ){ 2186 sqliteErrorMsg(pParse, 2187 "GROUP BY terms must not be non-integer constants"); 2188 goto select_end; 2189 }else if( iCol<=0 || iCol>pEList->nExpr ){ 2190 sqliteErrorMsg(pParse, 2191 "GROUP BY column number %d out of range - should be " 2192 "between 1 and %d", iCol, pEList->nExpr); 2193 goto select_end; 2194 } 2195 } 2196 } 2197 } 2198 2199 /* Begin generating code. 2200 */ 2201 v = sqliteGetVdbe(pParse); 2202 if( v==0 ) goto select_end; 2203 2204 /* Identify column names if we will be using them in a callback. This 2205 ** step is skipped if the output is going to some other destination. 2206 */ 2207 if( eDest==SRT_Callback ){ 2208 generateColumnNames(pParse, pTabList, pEList); 2209 } 2210 2211 /* Check for the special case of a min() or max() function by itself 2212 ** in the result set. 2213 */ 2214 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){ 2215 rc = 0; 2216 goto select_end; 2217 } 2218 2219 /* Generate code for all sub-queries in the FROM clause 2220 */ 2221 for(i=0; i<pTabList->nSrc; i++){ 2222 const char *zSavedAuthContext; 2223 int needRestoreContext; 2224 2225 if( pTabList->a[i].pSelect==0 ) continue; 2226 if( pTabList->a[i].zName!=0 ){ 2227 zSavedAuthContext = pParse->zAuthContext; 2228 pParse->zAuthContext = pTabList->a[i].zName; 2229 needRestoreContext = 1; 2230 }else{ 2231 needRestoreContext = 0; 2232 } 2233 sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable, 2234 pTabList->a[i].iCursor, p, i, &isAgg); 2235 if( needRestoreContext ){ 2236 pParse->zAuthContext = zSavedAuthContext; 2237 } 2238 pTabList = p->pSrc; 2239 pWhere = p->pWhere; 2240 if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){ 2241 pOrderBy = p->pOrderBy; 2242 } 2243 pGroupBy = p->pGroupBy; 2244 pHaving = p->pHaving; 2245 isDistinct = p->isDistinct; 2246 } 2247 2248 /* Check to see if this is a subquery that can be "flattened" into its parent. 2249 ** If flattening is a possiblity, do so and return immediately. 2250 */ 2251 if( pParent && pParentAgg && 2252 flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){ 2253 if( isAgg ) *pParentAgg = 1; 2254 return rc; 2255 } 2256 2257 /* Set the limiter. 2258 */ 2259 computeLimitRegisters(pParse, p); 2260 2261 /* Identify column types if we will be using a callback. This 2262 ** step is skipped if the output is going to a destination other 2263 ** than a callback. 2264 ** 2265 ** We have to do this separately from the creation of column names 2266 ** above because if the pTabList contains views then they will not 2267 ** have been resolved and we will not know the column types until 2268 ** now. 2269 */ 2270 if( eDest==SRT_Callback ){ 2271 generateColumnTypes(pParse, pTabList, pEList); 2272 } 2273 2274 /* If the output is destined for a temporary table, open that table. 2275 */ 2276 if( eDest==SRT_TempTable ){ 2277 sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0); 2278 } 2279 2280 /* Do an analysis of aggregate expressions. 2281 */ 2282 sqliteAggregateInfoReset(pParse); 2283 if( isAgg || pGroupBy ){ 2284 assert( pParse->nAgg==0 ); 2285 isAgg = 1; 2286 for(i=0; i<pEList->nExpr; i++){ 2287 if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){ 2288 goto select_end; 2289 } 2290 } 2291 if( pGroupBy ){ 2292 for(i=0; i<pGroupBy->nExpr; i++){ 2293 if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){ 2294 goto select_end; 2295 } 2296 } 2297 } 2298 if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){ 2299 goto select_end; 2300 } 2301 if( pOrderBy ){ 2302 for(i=0; i<pOrderBy->nExpr; i++){ 2303 if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){ 2304 goto select_end; 2305 } 2306 } 2307 } 2308 } 2309 2310 /* Reset the aggregator 2311 */ 2312 if( isAgg ){ 2313 sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg); 2314 for(i=0; i<pParse->nAgg; i++){ 2315 FuncDef *pFunc; 2316 if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){ 2317 sqliteVdbeAddOp(v, OP_AggInit, 0, i); 2318 sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER); 2319 } 2320 } 2321 if( pGroupBy==0 ){ 2322 sqliteVdbeAddOp(v, OP_String, 0, 0); 2323 sqliteVdbeAddOp(v, OP_AggFocus, 0, 0); 2324 } 2325 } 2326 2327 /* Initialize the memory cell to NULL 2328 */ 2329 if( eDest==SRT_Mem ){ 2330 sqliteVdbeAddOp(v, OP_String, 0, 0); 2331 sqliteVdbeAddOp(v, OP_MemStore, iParm, 1); 2332 } 2333 2334 /* Open a temporary table to use for the distinct set. 2335 */ 2336 if( isDistinct ){ 2337 distinct = pParse->nTab++; 2338 sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1); 2339 }else{ 2340 distinct = -1; 2341 } 2342 2343 /* Begin the database scan 2344 */ 2345 pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 0, 2346 pGroupBy ? 0 : &pOrderBy); 2347 if( pWInfo==0 ) goto select_end; 2348 2349 /* Use the standard inner loop if we are not dealing with 2350 ** aggregates 2351 */ 2352 if( !isAgg ){ 2353 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest, 2354 iParm, pWInfo->iContinue, pWInfo->iBreak) ){ 2355 goto select_end; 2356 } 2357 } 2358 2359 /* If we are dealing with aggregates, then do the special aggregate 2360 ** processing. 2361 */ 2362 else{ 2363 if( pGroupBy ){ 2364 int lbl1; 2365 for(i=0; i<pGroupBy->nExpr; i++){ 2366 sqliteExprCode(pParse, pGroupBy->a[i].pExpr); 2367 } 2368 sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0); 2369 if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pGroupBy); 2370 lbl1 = sqliteVdbeMakeLabel(v); 2371 sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1); 2372 for(i=0; i<pParse->nAgg; i++){ 2373 if( pParse->aAgg[i].isAgg ) continue; 2374 sqliteExprCode(pParse, pParse->aAgg[i].pExpr); 2375 sqliteVdbeAddOp(v, OP_AggSet, 0, i); 2376 } 2377 sqliteVdbeResolveLabel(v, lbl1); 2378 } 2379 for(i=0; i<pParse->nAgg; i++){ 2380 Expr *pE; 2381 int j; 2382 if( !pParse->aAgg[i].isAgg ) continue; 2383 pE = pParse->aAgg[i].pExpr; 2384 assert( pE->op==TK_AGG_FUNCTION ); 2385 if( pE->pList ){ 2386 for(j=0; j<pE->pList->nExpr; j++){ 2387 sqliteExprCode(pParse, pE->pList->a[j].pExpr); 2388 } 2389 } 2390 sqliteVdbeAddOp(v, OP_Integer, i, 0); 2391 sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0); 2392 assert( pParse->aAgg[i].pFunc!=0 ); 2393 assert( pParse->aAgg[i].pFunc->xStep!=0 ); 2394 sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER); 2395 } 2396 } 2397 2398 /* End the database scan loop. 2399 */ 2400 sqliteWhereEnd(pWInfo); 2401 2402 /* If we are processing aggregates, we need to set up a second loop 2403 ** over all of the aggregate values and process them. 2404 */ 2405 if( isAgg ){ 2406 int endagg = sqliteVdbeMakeLabel(v); 2407 int startagg; 2408 startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg); 2409 pParse->useAgg = 1; 2410 if( pHaving ){ 2411 sqliteExprIfFalse(pParse, pHaving, startagg, 1); 2412 } 2413 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest, 2414 iParm, startagg, endagg) ){ 2415 goto select_end; 2416 } 2417 sqliteVdbeAddOp(v, OP_Goto, 0, startagg); 2418 sqliteVdbeResolveLabel(v, endagg); 2419 sqliteVdbeAddOp(v, OP_Noop, 0, 0); 2420 pParse->useAgg = 0; 2421 } 2422 2423 /* If there is an ORDER BY clause, then we need to sort the results 2424 ** and send them to the callback one by one. 2425 */ 2426 if( pOrderBy ){ 2427 generateSortTail(p, v, pEList->nExpr, eDest, iParm); 2428 } 2429 2430 2431 /* Issue a null callback if that is what the user wants. 2432 */ 2433 if( eDest==SRT_Callback && 2434 (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0) 2435 ){ 2436 sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0); 2437 } 2438 2439 /* The SELECT was successfully coded. Set the return code to 0 2440 ** to indicate no errors. 2441 */ 2442 rc = 0; 2443 2444 /* Control jumps to here if an error is encountered above, or upon 2445 ** successful coding of the SELECT. 2446 */ 2447 select_end: 2448 sqliteAggregateInfoReset(pParse); 2449 return rc; 2450 } 2451