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.426 2008/04/10 13:33:18 drh Exp $ 16 */ 17 #include "sqliteInt.h" 18 19 20 /* 21 ** Delete all the content of a Select structure but do not deallocate 22 ** the select structure itself. 23 */ 24 static void clearSelect(Select *p){ 25 sqlite3ExprListDelete(p->pEList); 26 sqlite3SrcListDelete(p->pSrc); 27 sqlite3ExprDelete(p->pWhere); 28 sqlite3ExprListDelete(p->pGroupBy); 29 sqlite3ExprDelete(p->pHaving); 30 sqlite3ExprListDelete(p->pOrderBy); 31 sqlite3SelectDelete(p->pPrior); 32 sqlite3ExprDelete(p->pLimit); 33 sqlite3ExprDelete(p->pOffset); 34 } 35 36 /* 37 ** Initialize a SelectDest structure. 38 */ 39 void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ 40 pDest->eDest = eDest; 41 pDest->iParm = iParm; 42 pDest->affinity = 0; 43 pDest->iMem = 0; 44 pDest->nMem = 0; 45 } 46 47 48 /* 49 ** Allocate a new Select structure and return a pointer to that 50 ** structure. 51 */ 52 Select *sqlite3SelectNew( 53 Parse *pParse, /* Parsing context */ 54 ExprList *pEList, /* which columns to include in the result */ 55 SrcList *pSrc, /* the FROM clause -- which tables to scan */ 56 Expr *pWhere, /* the WHERE clause */ 57 ExprList *pGroupBy, /* the GROUP BY clause */ 58 Expr *pHaving, /* the HAVING clause */ 59 ExprList *pOrderBy, /* the ORDER BY clause */ 60 int isDistinct, /* true if the DISTINCT keyword is present */ 61 Expr *pLimit, /* LIMIT value. NULL means not used */ 62 Expr *pOffset /* OFFSET value. NULL means no offset */ 63 ){ 64 Select *pNew; 65 Select standin; 66 sqlite3 *db = pParse->db; 67 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 68 assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */ 69 if( pNew==0 ){ 70 pNew = &standin; 71 memset(pNew, 0, sizeof(*pNew)); 72 } 73 if( pEList==0 ){ 74 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0); 75 } 76 pNew->pEList = pEList; 77 pNew->pSrc = pSrc; 78 pNew->pWhere = pWhere; 79 pNew->pGroupBy = pGroupBy; 80 pNew->pHaving = pHaving; 81 pNew->pOrderBy = pOrderBy; 82 pNew->isDistinct = isDistinct; 83 pNew->op = TK_SELECT; 84 assert( pOffset==0 || pLimit!=0 ); 85 pNew->pLimit = pLimit; 86 pNew->pOffset = pOffset; 87 pNew->iLimit = -1; 88 pNew->iOffset = -1; 89 pNew->addrOpenEphm[0] = -1; 90 pNew->addrOpenEphm[1] = -1; 91 pNew->addrOpenEphm[2] = -1; 92 if( pNew==&standin) { 93 clearSelect(pNew); 94 pNew = 0; 95 } 96 return pNew; 97 } 98 99 /* 100 ** Delete the given Select structure and all of its substructures. 101 */ 102 void sqlite3SelectDelete(Select *p){ 103 if( p ){ 104 clearSelect(p); 105 sqlite3_free(p); 106 } 107 } 108 109 /* 110 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the 111 ** type of join. Return an integer constant that expresses that type 112 ** in terms of the following bit values: 113 ** 114 ** JT_INNER 115 ** JT_CROSS 116 ** JT_OUTER 117 ** JT_NATURAL 118 ** JT_LEFT 119 ** JT_RIGHT 120 ** 121 ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 122 ** 123 ** If an illegal or unsupported join type is seen, then still return 124 ** a join type, but put an error in the pParse structure. 125 */ 126 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 127 int jointype = 0; 128 Token *apAll[3]; 129 Token *p; 130 static const struct { 131 const char zKeyword[8]; 132 u8 nChar; 133 u8 code; 134 } keywords[] = { 135 { "natural", 7, JT_NATURAL }, 136 { "left", 4, JT_LEFT|JT_OUTER }, 137 { "right", 5, JT_RIGHT|JT_OUTER }, 138 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 139 { "outer", 5, JT_OUTER }, 140 { "inner", 5, JT_INNER }, 141 { "cross", 5, JT_INNER|JT_CROSS }, 142 }; 143 int i, j; 144 apAll[0] = pA; 145 apAll[1] = pB; 146 apAll[2] = pC; 147 for(i=0; i<3 && apAll[i]; i++){ 148 p = apAll[i]; 149 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){ 150 if( p->n==keywords[j].nChar 151 && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){ 152 jointype |= keywords[j].code; 153 break; 154 } 155 } 156 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){ 157 jointype |= JT_ERROR; 158 break; 159 } 160 } 161 if( 162 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 163 (jointype & JT_ERROR)!=0 164 ){ 165 const char *zSp1 = " "; 166 const char *zSp2 = " "; 167 if( pB==0 ){ zSp1++; } 168 if( pC==0 ){ zSp2++; } 169 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 170 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC); 171 jointype = JT_INNER; 172 }else if( jointype & JT_RIGHT ){ 173 sqlite3ErrorMsg(pParse, 174 "RIGHT and FULL OUTER JOINs are not currently supported"); 175 jointype = JT_INNER; 176 } 177 return jointype; 178 } 179 180 /* 181 ** Return the index of a column in a table. Return -1 if the column 182 ** is not contained in the table. 183 */ 184 static int columnIndex(Table *pTab, const char *zCol){ 185 int i; 186 for(i=0; i<pTab->nCol; i++){ 187 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 188 } 189 return -1; 190 } 191 192 /* 193 ** Set the value of a token to a '\000'-terminated string. 194 */ 195 static void setToken(Token *p, const char *z){ 196 p->z = (u8*)z; 197 p->n = z ? strlen(z) : 0; 198 p->dyn = 0; 199 } 200 201 /* 202 ** Set the token to the double-quoted and escaped version of the string pointed 203 ** to by z. For example; 204 ** 205 ** {a"bc} -> {"a""bc"} 206 */ 207 static void setQuotedToken(Parse *pParse, Token *p, const char *z){ 208 209 /* Check if the string contains any " characters. If it does, then 210 ** this function will malloc space to create a quoted version of 211 ** the string in. Otherwise, save a call to sqlite3MPrintf() by 212 ** just copying the pointer to the string. 213 */ 214 const char *z2 = z; 215 while( *z2 ){ 216 if( *z2=='"' ) break; 217 z2++; 218 } 219 220 if( *z2 ){ 221 /* String contains " characters - copy and quote the string. */ 222 p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z); 223 if( p->z ){ 224 p->n = strlen((char *)p->z); 225 p->dyn = 1; 226 } 227 }else{ 228 /* String contains no " characters - copy the pointer. */ 229 p->z = (u8*)z; 230 p->n = (z2 - z); 231 p->dyn = 0; 232 } 233 } 234 235 /* 236 ** Create an expression node for an identifier with the name of zName 237 */ 238 Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){ 239 Token dummy; 240 setToken(&dummy, zName); 241 return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy); 242 } 243 244 /* 245 ** Add a term to the WHERE expression in *ppExpr that requires the 246 ** zCol column to be equal in the two tables pTab1 and pTab2. 247 */ 248 static void addWhereTerm( 249 Parse *pParse, /* Parsing context */ 250 const char *zCol, /* Name of the column */ 251 const Table *pTab1, /* First table */ 252 const char *zAlias1, /* Alias for first table. May be NULL */ 253 const Table *pTab2, /* Second table */ 254 const char *zAlias2, /* Alias for second table. May be NULL */ 255 int iRightJoinTable, /* VDBE cursor for the right table */ 256 Expr **ppExpr, /* Add the equality term to this expression */ 257 int isOuterJoin /* True if dealing with an OUTER join */ 258 ){ 259 Expr *pE1a, *pE1b, *pE1c; 260 Expr *pE2a, *pE2b, *pE2c; 261 Expr *pE; 262 263 pE1a = sqlite3CreateIdExpr(pParse, zCol); 264 pE2a = sqlite3CreateIdExpr(pParse, zCol); 265 if( zAlias1==0 ){ 266 zAlias1 = pTab1->zName; 267 } 268 pE1b = sqlite3CreateIdExpr(pParse, zAlias1); 269 if( zAlias2==0 ){ 270 zAlias2 = pTab2->zName; 271 } 272 pE2b = sqlite3CreateIdExpr(pParse, zAlias2); 273 pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0); 274 pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0); 275 pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0); 276 if( pE && isOuterJoin ){ 277 ExprSetProperty(pE, EP_FromJoin); 278 pE->iRightJoinTable = iRightJoinTable; 279 } 280 *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE); 281 } 282 283 /* 284 ** Set the EP_FromJoin property on all terms of the given expression. 285 ** And set the Expr.iRightJoinTable to iTable for every term in the 286 ** expression. 287 ** 288 ** The EP_FromJoin property is used on terms of an expression to tell 289 ** the LEFT OUTER JOIN processing logic that this term is part of the 290 ** join restriction specified in the ON or USING clause and not a part 291 ** of the more general WHERE clause. These terms are moved over to the 292 ** WHERE clause during join processing but we need to remember that they 293 ** originated in the ON or USING clause. 294 ** 295 ** The Expr.iRightJoinTable tells the WHERE clause processing that the 296 ** expression depends on table iRightJoinTable even if that table is not 297 ** explicitly mentioned in the expression. That information is needed 298 ** for cases like this: 299 ** 300 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 301 ** 302 ** The where clause needs to defer the handling of the t1.x=5 303 ** term until after the t2 loop of the join. In that way, a 304 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 305 ** defer the handling of t1.x=5, it will be processed immediately 306 ** after the t1 loop and rows with t1.x!=5 will never appear in 307 ** the output, which is incorrect. 308 */ 309 static void setJoinExpr(Expr *p, int iTable){ 310 while( p ){ 311 ExprSetProperty(p, EP_FromJoin); 312 p->iRightJoinTable = iTable; 313 setJoinExpr(p->pLeft, iTable); 314 p = p->pRight; 315 } 316 } 317 318 /* 319 ** This routine processes the join information for a SELECT statement. 320 ** ON and USING clauses are converted into extra terms of the WHERE clause. 321 ** NATURAL joins also create extra WHERE clause terms. 322 ** 323 ** The terms of a FROM clause are contained in the Select.pSrc structure. 324 ** The left most table is the first entry in Select.pSrc. The right-most 325 ** table is the last entry. The join operator is held in the entry to 326 ** the left. Thus entry 0 contains the join operator for the join between 327 ** entries 0 and 1. Any ON or USING clauses associated with the join are 328 ** also attached to the left entry. 329 ** 330 ** This routine returns the number of errors encountered. 331 */ 332 static int sqliteProcessJoin(Parse *pParse, Select *p){ 333 SrcList *pSrc; /* All tables in the FROM clause */ 334 int i, j; /* Loop counters */ 335 struct SrcList_item *pLeft; /* Left table being joined */ 336 struct SrcList_item *pRight; /* Right table being joined */ 337 338 pSrc = p->pSrc; 339 pLeft = &pSrc->a[0]; 340 pRight = &pLeft[1]; 341 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 342 Table *pLeftTab = pLeft->pTab; 343 Table *pRightTab = pRight->pTab; 344 int isOuter; 345 346 if( pLeftTab==0 || pRightTab==0 ) continue; 347 isOuter = (pRight->jointype & JT_OUTER)!=0; 348 349 /* When the NATURAL keyword is present, add WHERE clause terms for 350 ** every column that the two tables have in common. 351 */ 352 if( pRight->jointype & JT_NATURAL ){ 353 if( pRight->pOn || pRight->pUsing ){ 354 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 355 "an ON or USING clause", 0); 356 return 1; 357 } 358 for(j=0; j<pLeftTab->nCol; j++){ 359 char *zName = pLeftTab->aCol[j].zName; 360 if( columnIndex(pRightTab, zName)>=0 ){ 361 addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 362 pRightTab, pRight->zAlias, 363 pRight->iCursor, &p->pWhere, isOuter); 364 365 } 366 } 367 } 368 369 /* Disallow both ON and USING clauses in the same join 370 */ 371 if( pRight->pOn && pRight->pUsing ){ 372 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 373 "clauses in the same join"); 374 return 1; 375 } 376 377 /* Add the ON clause to the end of the WHERE clause, connected by 378 ** an AND operator. 379 */ 380 if( pRight->pOn ){ 381 if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); 382 p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); 383 pRight->pOn = 0; 384 } 385 386 /* Create extra terms on the WHERE clause for each column named 387 ** in the USING clause. Example: If the two tables to be joined are 388 ** A and B and the USING clause names X, Y, and Z, then add this 389 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 390 ** Report an error if any column mentioned in the USING clause is 391 ** not contained in both tables to be joined. 392 */ 393 if( pRight->pUsing ){ 394 IdList *pList = pRight->pUsing; 395 for(j=0; j<pList->nId; j++){ 396 char *zName = pList->a[j].zName; 397 if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){ 398 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 399 "not present in both tables", zName); 400 return 1; 401 } 402 addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 403 pRightTab, pRight->zAlias, 404 pRight->iCursor, &p->pWhere, isOuter); 405 } 406 } 407 } 408 return 0; 409 } 410 411 /* 412 ** Insert code into "v" that will push the record on the top of the 413 ** stack into the sorter. 414 */ 415 static void pushOntoSorter( 416 Parse *pParse, /* Parser context */ 417 ExprList *pOrderBy, /* The ORDER BY clause */ 418 Select *pSelect, /* The whole SELECT statement */ 419 int regData /* Register holding data to be sorted */ 420 ){ 421 Vdbe *v = pParse->pVdbe; 422 int nExpr = pOrderBy->nExpr; 423 int regBase = sqlite3GetTempRange(pParse, nExpr+2); 424 int regRecord = sqlite3GetTempReg(pParse); 425 sqlite3ExprCodeExprList(pParse, pOrderBy, regBase); 426 sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr); 427 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1); 428 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord); 429 sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord); 430 sqlite3ReleaseTempReg(pParse, regRecord); 431 sqlite3ReleaseTempRange(pParse, regBase, nExpr+2); 432 if( pSelect->iLimit>=0 ){ 433 int addr1, addr2; 434 int iLimit; 435 if( pSelect->pOffset ){ 436 iLimit = pSelect->iOffset+1; 437 }else{ 438 iLimit = pSelect->iLimit; 439 } 440 addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); 441 sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1); 442 addr2 = sqlite3VdbeAddOp0(v, OP_Goto); 443 sqlite3VdbeJumpHere(v, addr1); 444 sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor); 445 sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor); 446 sqlite3VdbeJumpHere(v, addr2); 447 pSelect->iLimit = -1; 448 } 449 } 450 451 /* 452 ** Add code to implement the OFFSET 453 */ 454 static void codeOffset( 455 Vdbe *v, /* Generate code into this VM */ 456 Select *p, /* The SELECT statement being coded */ 457 int iContinue /* Jump here to skip the current record */ 458 ){ 459 if( p->iOffset>=0 && iContinue!=0 ){ 460 int addr; 461 sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1); 462 addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset); 463 sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue); 464 VdbeComment((v, "skip OFFSET records")); 465 sqlite3VdbeJumpHere(v, addr); 466 } 467 } 468 469 /* 470 ** Add code that will check to make sure the N registers starting at iMem 471 ** form a distinct entry. iTab is a sorting index that holds previously 472 ** seen combinations of the N values. A new entry is made in iTab 473 ** if the current N values are new. 474 ** 475 ** A jump to addrRepeat is made and the N+1 values are popped from the 476 ** stack if the top N elements are not distinct. 477 */ 478 static void codeDistinct( 479 Parse *pParse, /* Parsing and code generating context */ 480 int iTab, /* A sorting index used to test for distinctness */ 481 int addrRepeat, /* Jump to here if not distinct */ 482 int N, /* Number of elements */ 483 int iMem /* First element */ 484 ){ 485 Vdbe *v; 486 int r1; 487 488 v = pParse->pVdbe; 489 r1 = sqlite3GetTempReg(pParse); 490 sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); 491 sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1); 492 sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1); 493 sqlite3ReleaseTempReg(pParse, r1); 494 } 495 496 /* 497 ** Generate an error message when a SELECT is used within a subexpression 498 ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result 499 ** column. We do this in a subroutine because the error occurs in multiple 500 ** places. 501 */ 502 static int checkForMultiColumnSelectError( 503 Parse *pParse, /* Parse context. */ 504 SelectDest *pDest, /* Destination of SELECT results */ 505 int nExpr /* Number of result columns returned by SELECT */ 506 ){ 507 int eDest = pDest->eDest; 508 if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){ 509 sqlite3ErrorMsg(pParse, "only a single result allowed for " 510 "a SELECT that is part of an expression"); 511 return 1; 512 }else{ 513 return 0; 514 } 515 } 516 517 /* 518 ** This routine generates the code for the inside of the inner loop 519 ** of a SELECT. 520 ** 521 ** If srcTab and nColumn are both zero, then the pEList expressions 522 ** are evaluated in order to get the data for this row. If nColumn>0 523 ** then data is pulled from srcTab and pEList is used only to get the 524 ** datatypes for each column. 525 */ 526 static void selectInnerLoop( 527 Parse *pParse, /* The parser context */ 528 Select *p, /* The complete select statement being coded */ 529 ExprList *pEList, /* List of values being extracted */ 530 int srcTab, /* Pull data from this table */ 531 int nColumn, /* Number of columns in the source table */ 532 ExprList *pOrderBy, /* If not NULL, sort results using this key */ 533 int distinct, /* If >=0, make sure results are distinct */ 534 SelectDest *pDest, /* How to dispose of the results */ 535 int iContinue, /* Jump here to continue with next row */ 536 int iBreak, /* Jump here to break out of the inner loop */ 537 char *aff /* affinity string if eDest is SRT_Union */ 538 ){ 539 Vdbe *v = pParse->pVdbe; 540 int i; 541 int hasDistinct; /* True if the DISTINCT keyword is present */ 542 int regResult; /* Start of memory holding result set */ 543 int eDest = pDest->eDest; /* How to dispose of results */ 544 int iParm = pDest->iParm; /* First argument to disposal method */ 545 int nResultCol; /* Number of result columns */ 546 547 if( v==0 ) return; 548 assert( pEList!=0 ); 549 550 /* If there was a LIMIT clause on the SELECT statement, then do the check 551 ** to see if this row should be output. 552 */ 553 hasDistinct = distinct>=0 && pEList->nExpr>0; 554 if( pOrderBy==0 && !hasDistinct ){ 555 codeOffset(v, p, iContinue); 556 } 557 558 /* Pull the requested columns. 559 */ 560 if( nColumn>0 ){ 561 nResultCol = nColumn; 562 }else{ 563 nResultCol = pEList->nExpr; 564 } 565 if( pDest->iMem==0 ){ 566 pDest->iMem = sqlite3GetTempRange(pParse, nResultCol); 567 pDest->nMem = nResultCol; 568 }else if( pDest->nMem!=nResultCol ){ 569 /* This happens when two SELECTs of a compound SELECT have differing 570 ** numbers of result columns. The error message will be generated by 571 ** a higher-level routine. */ 572 return; 573 } 574 regResult = pDest->iMem; 575 if( nColumn>0 ){ 576 for(i=0; i<nColumn; i++){ 577 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 578 } 579 }else if( eDest!=SRT_Exists ){ 580 /* If the destination is an EXISTS(...) expression, the actual 581 ** values returned by the SELECT are not required. 582 */ 583 for(i=0; i<nResultCol; i++){ 584 sqlite3ExprCode(pParse, pEList->a[i].pExpr, regResult+i); 585 } 586 } 587 nColumn = nResultCol; 588 589 /* If the DISTINCT keyword was present on the SELECT statement 590 ** and this row has been seen before, then do not make this row 591 ** part of the result. 592 */ 593 if( hasDistinct ){ 594 assert( pEList!=0 ); 595 assert( pEList->nExpr==nColumn ); 596 codeDistinct(pParse, distinct, iContinue, nColumn, regResult); 597 if( pOrderBy==0 ){ 598 codeOffset(v, p, iContinue); 599 } 600 } 601 602 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ 603 return; 604 } 605 606 switch( eDest ){ 607 /* In this mode, write each query result to the key of the temporary 608 ** table iParm. 609 */ 610 #ifndef SQLITE_OMIT_COMPOUND_SELECT 611 case SRT_Union: { 612 int r1; 613 r1 = sqlite3GetTempReg(pParse); 614 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 615 if( aff ){ 616 sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC); 617 } 618 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 619 sqlite3ReleaseTempReg(pParse, r1); 620 break; 621 } 622 623 /* Construct a record from the query result, but instead of 624 ** saving that record, use it as a key to delete elements from 625 ** the temporary table iParm. 626 */ 627 case SRT_Except: { 628 sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn); 629 break; 630 } 631 #endif 632 633 /* Store the result as data using a unique key. 634 */ 635 case SRT_Table: 636 case SRT_EphemTab: { 637 int r1 = sqlite3GetTempReg(pParse); 638 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 639 if( pOrderBy ){ 640 pushOntoSorter(pParse, pOrderBy, p, r1); 641 }else{ 642 int r2 = sqlite3GetTempReg(pParse); 643 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 644 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 645 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 646 sqlite3ReleaseTempReg(pParse, r2); 647 } 648 sqlite3ReleaseTempReg(pParse, r1); 649 break; 650 } 651 652 #ifndef SQLITE_OMIT_SUBQUERY 653 /* If we are creating a set for an "expr IN (SELECT ...)" construct, 654 ** then there should be a single item on the stack. Write this 655 ** item into the set table with bogus data. 656 */ 657 case SRT_Set: { 658 int addr2; 659 660 assert( nColumn==1 ); 661 addr2 = sqlite3VdbeAddOp1(v, OP_IsNull, regResult); 662 p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity); 663 if( pOrderBy ){ 664 /* At first glance you would think we could optimize out the 665 ** ORDER BY in this case since the order of entries in the set 666 ** does not matter. But there might be a LIMIT clause, in which 667 ** case the order does matter */ 668 pushOntoSorter(pParse, pOrderBy, p, regResult); 669 }else{ 670 int r1 = sqlite3GetTempReg(pParse); 671 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1); 672 sqlite3ExprCacheAffinityChange(pParse, regResult, 1); 673 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 674 sqlite3ReleaseTempReg(pParse, r1); 675 } 676 sqlite3VdbeJumpHere(v, addr2); 677 break; 678 } 679 680 /* If any row exist in the result set, record that fact and abort. 681 */ 682 case SRT_Exists: { 683 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 684 /* The LIMIT clause will terminate the loop for us */ 685 break; 686 } 687 688 /* If this is a scalar select that is part of an expression, then 689 ** store the results in the appropriate memory cell and break out 690 ** of the scan loop. 691 */ 692 case SRT_Mem: { 693 assert( nColumn==1 ); 694 if( pOrderBy ){ 695 pushOntoSorter(pParse, pOrderBy, p, regResult); 696 }else{ 697 sqlite3ExprCodeMove(pParse, regResult, iParm); 698 /* The LIMIT clause will jump out of the loop for us */ 699 } 700 break; 701 } 702 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 703 704 /* Send the data to the callback function or to a subroutine. In the 705 ** case of a subroutine, the subroutine itself is responsible for 706 ** popping the data from the stack. 707 */ 708 case SRT_Subroutine: 709 case SRT_Callback: { 710 if( pOrderBy ){ 711 int r1 = sqlite3GetTempReg(pParse); 712 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 713 pushOntoSorter(pParse, pOrderBy, p, r1); 714 sqlite3ReleaseTempReg(pParse, r1); 715 }else if( eDest==SRT_Subroutine ){ 716 sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm); 717 }else{ 718 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn); 719 sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn); 720 } 721 break; 722 } 723 724 #if !defined(SQLITE_OMIT_TRIGGER) 725 /* Discard the results. This is used for SELECT statements inside 726 ** the body of a TRIGGER. The purpose of such selects is to call 727 ** user-defined functions that have side effects. We do not care 728 ** about the actual results of the select. 729 */ 730 default: { 731 assert( eDest==SRT_Discard ); 732 break; 733 } 734 #endif 735 } 736 737 /* Jump to the end of the loop if the LIMIT is reached. 738 */ 739 if( p->iLimit>=0 && pOrderBy==0 ){ 740 sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1); 741 sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak); 742 } 743 } 744 745 /* 746 ** Given an expression list, generate a KeyInfo structure that records 747 ** the collating sequence for each expression in that expression list. 748 ** 749 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 750 ** KeyInfo structure is appropriate for initializing a virtual index to 751 ** implement that clause. If the ExprList is the result set of a SELECT 752 ** then the KeyInfo structure is appropriate for initializing a virtual 753 ** index to implement a DISTINCT test. 754 ** 755 ** Space to hold the KeyInfo structure is obtain from malloc. The calling 756 ** function is responsible for seeing that this structure is eventually 757 ** freed. Add the KeyInfo structure to the P4 field of an opcode using 758 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this. 759 */ 760 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ 761 sqlite3 *db = pParse->db; 762 int nExpr; 763 KeyInfo *pInfo; 764 struct ExprList_item *pItem; 765 int i; 766 767 nExpr = pList->nExpr; 768 pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) ); 769 if( pInfo ){ 770 pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr]; 771 pInfo->nField = nExpr; 772 pInfo->enc = ENC(db); 773 for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){ 774 CollSeq *pColl; 775 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 776 if( !pColl ){ 777 pColl = db->pDfltColl; 778 } 779 pInfo->aColl[i] = pColl; 780 pInfo->aSortOrder[i] = pItem->sortOrder; 781 } 782 } 783 return pInfo; 784 } 785 786 787 /* 788 ** If the inner loop was generated using a non-null pOrderBy argument, 789 ** then the results were placed in a sorter. After the loop is terminated 790 ** we need to run the sorter and output the results. The following 791 ** routine generates the code needed to do that. 792 */ 793 static void generateSortTail( 794 Parse *pParse, /* Parsing context */ 795 Select *p, /* The SELECT statement */ 796 Vdbe *v, /* Generate code into this VDBE */ 797 int nColumn, /* Number of columns of data */ 798 SelectDest *pDest /* Write the sorted results here */ 799 ){ 800 int brk = sqlite3VdbeMakeLabel(v); 801 int cont = sqlite3VdbeMakeLabel(v); 802 int addr; 803 int iTab; 804 int pseudoTab = 0; 805 ExprList *pOrderBy = p->pOrderBy; 806 807 int eDest = pDest->eDest; 808 int iParm = pDest->iParm; 809 810 int regRow; 811 int regRowid; 812 813 iTab = pOrderBy->iECursor; 814 if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ 815 pseudoTab = pParse->nTab++; 816 sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn); 817 sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Callback); 818 } 819 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk); 820 codeOffset(v, p, cont); 821 regRow = sqlite3GetTempReg(pParse); 822 regRowid = sqlite3GetTempReg(pParse); 823 sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow); 824 switch( eDest ){ 825 case SRT_Table: 826 case SRT_EphemTab: { 827 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 828 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 829 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 830 break; 831 } 832 #ifndef SQLITE_OMIT_SUBQUERY 833 case SRT_Set: { 834 int j1; 835 assert( nColumn==1 ); 836 j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regRow); 837 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1); 838 sqlite3ExprCacheAffinityChange(pParse, regRow, 1); 839 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid); 840 sqlite3VdbeJumpHere(v, j1); 841 break; 842 } 843 case SRT_Mem: { 844 assert( nColumn==1 ); 845 sqlite3ExprCodeMove(pParse, regRow, iParm); 846 /* The LIMIT clause will terminate the loop for us */ 847 break; 848 } 849 #endif 850 case SRT_Callback: 851 case SRT_Subroutine: { 852 int i; 853 sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid); 854 sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid); 855 for(i=0; i<nColumn; i++){ 856 assert( regRow!=pDest->iMem+i ); 857 sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i); 858 } 859 if( eDest==SRT_Callback ){ 860 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn); 861 sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn); 862 }else{ 863 sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm); 864 } 865 break; 866 } 867 default: { 868 /* Do nothing */ 869 break; 870 } 871 } 872 sqlite3ReleaseTempReg(pParse, regRow); 873 sqlite3ReleaseTempReg(pParse, regRowid); 874 875 /* Jump to the end of the loop when the LIMIT is reached 876 */ 877 if( p->iLimit>=0 ){ 878 sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1); 879 sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, brk); 880 } 881 882 /* The bottom of the loop 883 */ 884 sqlite3VdbeResolveLabel(v, cont); 885 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); 886 sqlite3VdbeResolveLabel(v, brk); 887 if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ 888 sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0); 889 } 890 891 } 892 893 /* 894 ** Return a pointer to a string containing the 'declaration type' of the 895 ** expression pExpr. The string may be treated as static by the caller. 896 ** 897 ** The declaration type is the exact datatype definition extracted from the 898 ** original CREATE TABLE statement if the expression is a column. The 899 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 900 ** is considered a column can be complex in the presence of subqueries. The 901 ** result-set expression in all of the following SELECT statements is 902 ** considered a column by this function. 903 ** 904 ** SELECT col FROM tbl; 905 ** SELECT (SELECT col FROM tbl; 906 ** SELECT (SELECT col FROM tbl); 907 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 908 ** 909 ** The declaration type for any expression other than a column is NULL. 910 */ 911 static const char *columnType( 912 NameContext *pNC, 913 Expr *pExpr, 914 const char **pzOriginDb, 915 const char **pzOriginTab, 916 const char **pzOriginCol 917 ){ 918 char const *zType = 0; 919 char const *zOriginDb = 0; 920 char const *zOriginTab = 0; 921 char const *zOriginCol = 0; 922 int j; 923 if( pExpr==0 || pNC->pSrcList==0 ) return 0; 924 925 switch( pExpr->op ){ 926 case TK_AGG_COLUMN: 927 case TK_COLUMN: { 928 /* The expression is a column. Locate the table the column is being 929 ** extracted from in NameContext.pSrcList. This table may be real 930 ** database table or a subquery. 931 */ 932 Table *pTab = 0; /* Table structure column is extracted from */ 933 Select *pS = 0; /* Select the column is extracted from */ 934 int iCol = pExpr->iColumn; /* Index of column in pTab */ 935 while( pNC && !pTab ){ 936 SrcList *pTabList = pNC->pSrcList; 937 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 938 if( j<pTabList->nSrc ){ 939 pTab = pTabList->a[j].pTab; 940 pS = pTabList->a[j].pSelect; 941 }else{ 942 pNC = pNC->pNext; 943 } 944 } 945 946 if( pTab==0 ){ 947 /* FIX ME: 948 ** This can occurs if you have something like "SELECT new.x;" inside 949 ** a trigger. In other words, if you reference the special "new" 950 ** table in the result set of a select. We do not have a good way 951 ** to find the actual table type, so call it "TEXT". This is really 952 ** something of a bug, but I do not know how to fix it. 953 ** 954 ** This code does not produce the correct answer - it just prevents 955 ** a segfault. See ticket #1229. 956 */ 957 zType = "TEXT"; 958 break; 959 } 960 961 assert( pTab ); 962 if( pS ){ 963 /* The "table" is actually a sub-select or a view in the FROM clause 964 ** of the SELECT statement. Return the declaration type and origin 965 ** data for the result-set column of the sub-select. 966 */ 967 if( iCol>=0 && iCol<pS->pEList->nExpr ){ 968 /* If iCol is less than zero, then the expression requests the 969 ** rowid of the sub-select or view. This expression is legal (see 970 ** test case misc2.2.2) - it always evaluates to NULL. 971 */ 972 NameContext sNC; 973 Expr *p = pS->pEList->a[iCol].pExpr; 974 sNC.pSrcList = pS->pSrc; 975 sNC.pNext = 0; 976 sNC.pParse = pNC->pParse; 977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 978 } 979 }else if( pTab->pSchema ){ 980 /* A real table */ 981 assert( !pS ); 982 if( iCol<0 ) iCol = pTab->iPKey; 983 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 984 if( iCol<0 ){ 985 zType = "INTEGER"; 986 zOriginCol = "rowid"; 987 }else{ 988 zType = pTab->aCol[iCol].zType; 989 zOriginCol = pTab->aCol[iCol].zName; 990 } 991 zOriginTab = pTab->zName; 992 if( pNC->pParse ){ 993 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 994 zOriginDb = pNC->pParse->db->aDb[iDb].zName; 995 } 996 } 997 break; 998 } 999 #ifndef SQLITE_OMIT_SUBQUERY 1000 case TK_SELECT: { 1001 /* The expression is a sub-select. Return the declaration type and 1002 ** origin info for the single column in the result set of the SELECT 1003 ** statement. 1004 */ 1005 NameContext sNC; 1006 Select *pS = pExpr->pSelect; 1007 Expr *p = pS->pEList->a[0].pExpr; 1008 sNC.pSrcList = pS->pSrc; 1009 sNC.pNext = pNC; 1010 sNC.pParse = pNC->pParse; 1011 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 1012 break; 1013 } 1014 #endif 1015 } 1016 1017 if( pzOriginDb ){ 1018 assert( pzOriginTab && pzOriginCol ); 1019 *pzOriginDb = zOriginDb; 1020 *pzOriginTab = zOriginTab; 1021 *pzOriginCol = zOriginCol; 1022 } 1023 return zType; 1024 } 1025 1026 /* 1027 ** Generate code that will tell the VDBE the declaration types of columns 1028 ** in the result set. 1029 */ 1030 static void generateColumnTypes( 1031 Parse *pParse, /* Parser context */ 1032 SrcList *pTabList, /* List of tables */ 1033 ExprList *pEList /* Expressions defining the result set */ 1034 ){ 1035 #ifndef SQLITE_OMIT_DECLTYPE 1036 Vdbe *v = pParse->pVdbe; 1037 int i; 1038 NameContext sNC; 1039 sNC.pSrcList = pTabList; 1040 sNC.pParse = pParse; 1041 for(i=0; i<pEList->nExpr; i++){ 1042 Expr *p = pEList->a[i].pExpr; 1043 const char *zType; 1044 #ifdef SQLITE_ENABLE_COLUMN_METADATA 1045 const char *zOrigDb = 0; 1046 const char *zOrigTab = 0; 1047 const char *zOrigCol = 0; 1048 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 1049 1050 /* The vdbe must make its own copy of the column-type and other 1051 ** column specific strings, in case the schema is reset before this 1052 ** virtual machine is deleted. 1053 */ 1054 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT); 1055 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT); 1056 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT); 1057 #else 1058 zType = columnType(&sNC, p, 0, 0, 0); 1059 #endif 1060 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT); 1061 } 1062 #endif /* SQLITE_OMIT_DECLTYPE */ 1063 } 1064 1065 /* 1066 ** Generate code that will tell the VDBE the names of columns 1067 ** in the result set. This information is used to provide the 1068 ** azCol[] values in the callback. 1069 */ 1070 static void generateColumnNames( 1071 Parse *pParse, /* Parser context */ 1072 SrcList *pTabList, /* List of tables */ 1073 ExprList *pEList /* Expressions defining the result set */ 1074 ){ 1075 Vdbe *v = pParse->pVdbe; 1076 int i, j; 1077 sqlite3 *db = pParse->db; 1078 int fullNames, shortNames; 1079 1080 #ifndef SQLITE_OMIT_EXPLAIN 1081 /* If this is an EXPLAIN, skip this step */ 1082 if( pParse->explain ){ 1083 return; 1084 } 1085 #endif 1086 1087 assert( v!=0 ); 1088 if( pParse->colNamesSet || v==0 || db->mallocFailed ) return; 1089 pParse->colNamesSet = 1; 1090 fullNames = (db->flags & SQLITE_FullColNames)!=0; 1091 shortNames = (db->flags & SQLITE_ShortColNames)!=0; 1092 sqlite3VdbeSetNumCols(v, pEList->nExpr); 1093 for(i=0; i<pEList->nExpr; i++){ 1094 Expr *p; 1095 p = pEList->a[i].pExpr; 1096 if( p==0 ) continue; 1097 if( pEList->a[i].zName ){ 1098 char *zName = pEList->a[i].zName; 1099 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName)); 1100 continue; 1101 } 1102 if( p->op==TK_COLUMN && pTabList ){ 1103 Table *pTab; 1104 char *zCol; 1105 int iCol = p->iColumn; 1106 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){} 1107 assert( j<pTabList->nSrc ); 1108 pTab = pTabList->a[j].pTab; 1109 if( iCol<0 ) iCol = pTab->iPKey; 1110 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1111 if( iCol<0 ){ 1112 zCol = "rowid"; 1113 }else{ 1114 zCol = pTab->aCol[iCol].zName; 1115 } 1116 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){ 1117 sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); 1118 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){ 1119 char *zName = 0; 1120 char *zTab; 1121 1122 zTab = pTabList->a[j].zAlias; 1123 if( fullNames || zTab==0 ) zTab = pTab->zName; 1124 sqlite3SetString(&zName, zTab, ".", zCol, (char*)0); 1125 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC); 1126 }else{ 1127 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol)); 1128 } 1129 }else if( p->span.z && p->span.z[0] ){ 1130 sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); 1131 /* sqlite3VdbeCompressSpace(v, addr); */ 1132 }else{ 1133 char zName[30]; 1134 assert( p->op!=TK_COLUMN || pTabList==0 ); 1135 sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1); 1136 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0); 1137 } 1138 } 1139 generateColumnTypes(pParse, pTabList, pEList); 1140 } 1141 1142 #ifndef SQLITE_OMIT_COMPOUND_SELECT 1143 /* 1144 ** Name of the connection operator, used for error messages. 1145 */ 1146 static const char *selectOpName(int id){ 1147 char *z; 1148 switch( id ){ 1149 case TK_ALL: z = "UNION ALL"; break; 1150 case TK_INTERSECT: z = "INTERSECT"; break; 1151 case TK_EXCEPT: z = "EXCEPT"; break; 1152 default: z = "UNION"; break; 1153 } 1154 return z; 1155 } 1156 #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1157 1158 /* 1159 ** Forward declaration 1160 */ 1161 static int prepSelectStmt(Parse*, Select*); 1162 1163 /* 1164 ** Given a SELECT statement, generate a Table structure that describes 1165 ** the result set of that SELECT. 1166 */ 1167 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){ 1168 Table *pTab; 1169 int i, j; 1170 ExprList *pEList; 1171 Column *aCol, *pCol; 1172 sqlite3 *db = pParse->db; 1173 1174 while( pSelect->pPrior ) pSelect = pSelect->pPrior; 1175 if( prepSelectStmt(pParse, pSelect) ){ 1176 return 0; 1177 } 1178 if( sqlite3SelectResolve(pParse, pSelect, 0) ){ 1179 return 0; 1180 } 1181 pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 1182 if( pTab==0 ){ 1183 return 0; 1184 } 1185 pTab->nRef = 1; 1186 pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0; 1187 pEList = pSelect->pEList; 1188 pTab->nCol = pEList->nExpr; 1189 assert( pTab->nCol>0 ); 1190 pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol); 1191 for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){ 1192 Expr *p, *pR; 1193 char *zType; 1194 char *zName; 1195 int nName; 1196 CollSeq *pColl; 1197 int cnt; 1198 NameContext sNC; 1199 1200 /* Get an appropriate name for the column 1201 */ 1202 p = pEList->a[i].pExpr; 1203 assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 ); 1204 if( (zName = pEList->a[i].zName)!=0 ){ 1205 /* If the column contains an "AS <name>" phrase, use <name> as the name */ 1206 zName = sqlite3DbStrDup(db, zName); 1207 }else if( p->op==TK_DOT 1208 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){ 1209 /* For columns of the from A.B use B as the name */ 1210 zName = sqlite3MPrintf(db, "%T", &pR->token); 1211 }else if( p->span.z && p->span.z[0] ){ 1212 /* Use the original text of the column expression as its name */ 1213 zName = sqlite3MPrintf(db, "%T", &p->span); 1214 }else{ 1215 /* If all else fails, make up a name */ 1216 zName = sqlite3MPrintf(db, "column%d", i+1); 1217 } 1218 if( !zName || db->mallocFailed ){ 1219 db->mallocFailed = 1; 1220 sqlite3_free(zName); 1221 sqlite3DeleteTable(pTab); 1222 return 0; 1223 } 1224 sqlite3Dequote(zName); 1225 1226 /* Make sure the column name is unique. If the name is not unique, 1227 ** append a integer to the name so that it becomes unique. 1228 */ 1229 nName = strlen(zName); 1230 for(j=cnt=0; j<i; j++){ 1231 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 1232 zName[nName] = 0; 1233 zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt); 1234 j = -1; 1235 if( zName==0 ) break; 1236 } 1237 } 1238 pCol->zName = zName; 1239 1240 /* Get the typename, type affinity, and collating sequence for the 1241 ** column. 1242 */ 1243 memset(&sNC, 0, sizeof(sNC)); 1244 sNC.pSrcList = pSelect->pSrc; 1245 zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0)); 1246 pCol->zType = zType; 1247 pCol->affinity = sqlite3ExprAffinity(p); 1248 pColl = sqlite3ExprCollSeq(pParse, p); 1249 if( pColl ){ 1250 pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 1251 } 1252 } 1253 pTab->iPKey = -1; 1254 return pTab; 1255 } 1256 1257 /* 1258 ** Prepare a SELECT statement for processing by doing the following 1259 ** things: 1260 ** 1261 ** (1) Make sure VDBE cursor numbers have been assigned to every 1262 ** element of the FROM clause. 1263 ** 1264 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 1265 ** defines FROM clause. When views appear in the FROM clause, 1266 ** fill pTabList->a[].pSelect with a copy of the SELECT statement 1267 ** that implements the view. A copy is made of the view's SELECT 1268 ** statement so that we can freely modify or delete that statement 1269 ** without worrying about messing up the presistent representation 1270 ** of the view. 1271 ** 1272 ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword 1273 ** on joins and the ON and USING clause of joins. 1274 ** 1275 ** (4) Scan the list of columns in the result set (pEList) looking 1276 ** for instances of the "*" operator or the TABLE.* operator. 1277 ** If found, expand each "*" to be every column in every table 1278 ** and TABLE.* to be every column in TABLE. 1279 ** 1280 ** Return 0 on success. If there are problems, leave an error message 1281 ** in pParse and return non-zero. 1282 */ 1283 static int prepSelectStmt(Parse *pParse, Select *p){ 1284 int i, j, k, rc; 1285 SrcList *pTabList; 1286 ExprList *pEList; 1287 struct SrcList_item *pFrom; 1288 sqlite3 *db = pParse->db; 1289 1290 if( p==0 || p->pSrc==0 || db->mallocFailed ){ 1291 return 1; 1292 } 1293 pTabList = p->pSrc; 1294 pEList = p->pEList; 1295 1296 /* Make sure cursor numbers have been assigned to all entries in 1297 ** the FROM clause of the SELECT statement. 1298 */ 1299 sqlite3SrcListAssignCursors(pParse, p->pSrc); 1300 1301 /* Look up every table named in the FROM clause of the select. If 1302 ** an entry of the FROM clause is a subquery instead of a table or view, 1303 ** then create a transient table structure to describe the subquery. 1304 */ 1305 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 1306 Table *pTab; 1307 if( pFrom->pTab!=0 ){ 1308 /* This statement has already been prepared. There is no need 1309 ** to go further. */ 1310 assert( i==0 ); 1311 return 0; 1312 } 1313 if( pFrom->zName==0 ){ 1314 #ifndef SQLITE_OMIT_SUBQUERY 1315 /* A sub-query in the FROM clause of a SELECT */ 1316 assert( pFrom->pSelect!=0 ); 1317 if( pFrom->zAlias==0 ){ 1318 pFrom->zAlias = 1319 sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect); 1320 } 1321 assert( pFrom->pTab==0 ); 1322 pFrom->pTab = pTab = 1323 sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect); 1324 if( pTab==0 ){ 1325 return 1; 1326 } 1327 /* The isEphem flag indicates that the Table structure has been 1328 ** dynamically allocated and may be freed at any time. In other words, 1329 ** pTab is not pointing to a persistent table structure that defines 1330 ** part of the schema. */ 1331 pTab->isEphem = 1; 1332 #endif 1333 }else{ 1334 /* An ordinary table or view name in the FROM clause */ 1335 assert( pFrom->pTab==0 ); 1336 pFrom->pTab = pTab = 1337 sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase); 1338 if( pTab==0 ){ 1339 return 1; 1340 } 1341 pTab->nRef++; 1342 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 1343 if( pTab->pSelect || IsVirtual(pTab) ){ 1344 /* We reach here if the named table is a really a view */ 1345 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 1346 return 1; 1347 } 1348 /* If pFrom->pSelect!=0 it means we are dealing with a 1349 ** view within a view. The SELECT structure has already been 1350 ** copied by the outer view so we can skip the copy step here 1351 ** in the inner view. 1352 */ 1353 if( pFrom->pSelect==0 ){ 1354 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect); 1355 } 1356 } 1357 #endif 1358 } 1359 } 1360 1361 /* Process NATURAL keywords, and ON and USING clauses of joins. 1362 */ 1363 if( sqliteProcessJoin(pParse, p) ) return 1; 1364 1365 /* For every "*" that occurs in the column list, insert the names of 1366 ** all columns in all tables. And for every TABLE.* insert the names 1367 ** of all columns in TABLE. The parser inserted a special expression 1368 ** with the TK_ALL operator for each "*" that it found in the column list. 1369 ** The following code just has to locate the TK_ALL expressions and expand 1370 ** each one to the list of all columns in all tables. 1371 ** 1372 ** The first loop just checks to see if there are any "*" operators 1373 ** that need expanding. 1374 */ 1375 for(k=0; k<pEList->nExpr; k++){ 1376 Expr *pE = pEList->a[k].pExpr; 1377 if( pE->op==TK_ALL ) break; 1378 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL 1379 && pE->pLeft && pE->pLeft->op==TK_ID ) break; 1380 } 1381 rc = 0; 1382 if( k<pEList->nExpr ){ 1383 /* 1384 ** If we get here it means the result set contains one or more "*" 1385 ** operators that need to be expanded. Loop through each expression 1386 ** in the result set and expand them one by one. 1387 */ 1388 struct ExprList_item *a = pEList->a; 1389 ExprList *pNew = 0; 1390 int flags = pParse->db->flags; 1391 int longNames = (flags & SQLITE_FullColNames)!=0 && 1392 (flags & SQLITE_ShortColNames)==0; 1393 1394 for(k=0; k<pEList->nExpr; k++){ 1395 Expr *pE = a[k].pExpr; 1396 if( pE->op!=TK_ALL && 1397 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){ 1398 /* This particular expression does not need to be expanded. 1399 */ 1400 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0); 1401 if( pNew ){ 1402 pNew->a[pNew->nExpr-1].zName = a[k].zName; 1403 }else{ 1404 rc = 1; 1405 } 1406 a[k].pExpr = 0; 1407 a[k].zName = 0; 1408 }else{ 1409 /* This expression is a "*" or a "TABLE.*" and needs to be 1410 ** expanded. */ 1411 int tableSeen = 0; /* Set to 1 when TABLE matches */ 1412 char *zTName; /* text of name of TABLE */ 1413 if( pE->op==TK_DOT && pE->pLeft ){ 1414 zTName = sqlite3NameFromToken(db, &pE->pLeft->token); 1415 }else{ 1416 zTName = 0; 1417 } 1418 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 1419 Table *pTab = pFrom->pTab; 1420 char *zTabName = pFrom->zAlias; 1421 if( zTabName==0 || zTabName[0]==0 ){ 1422 zTabName = pTab->zName; 1423 } 1424 if( zTName && (zTabName==0 || zTabName[0]==0 || 1425 sqlite3StrICmp(zTName, zTabName)!=0) ){ 1426 continue; 1427 } 1428 tableSeen = 1; 1429 for(j=0; j<pTab->nCol; j++){ 1430 Expr *pExpr, *pRight; 1431 char *zName = pTab->aCol[j].zName; 1432 1433 /* If a column is marked as 'hidden' (currently only possible 1434 ** for virtual tables), do not include it in the expanded 1435 ** result-set list. 1436 */ 1437 if( IsHiddenColumn(&pTab->aCol[j]) ){ 1438 assert(IsVirtual(pTab)); 1439 continue; 1440 } 1441 1442 if( i>0 ){ 1443 struct SrcList_item *pLeft = &pTabList->a[i-1]; 1444 if( (pLeft[1].jointype & JT_NATURAL)!=0 && 1445 columnIndex(pLeft->pTab, zName)>=0 ){ 1446 /* In a NATURAL join, omit the join columns from the 1447 ** table on the right */ 1448 continue; 1449 } 1450 if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){ 1451 /* In a join with a USING clause, omit columns in the 1452 ** using clause from the table on the right. */ 1453 continue; 1454 } 1455 } 1456 pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0); 1457 if( pRight==0 ) break; 1458 setQuotedToken(pParse, &pRight->token, zName); 1459 if( zTabName && (longNames || pTabList->nSrc>1) ){ 1460 Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0); 1461 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); 1462 if( pExpr==0 ) break; 1463 setQuotedToken(pParse, &pLeft->token, zTabName); 1464 setToken(&pExpr->span, 1465 sqlite3MPrintf(db, "%s.%s", zTabName, zName)); 1466 pExpr->span.dyn = 1; 1467 pExpr->token.z = 0; 1468 pExpr->token.n = 0; 1469 pExpr->token.dyn = 0; 1470 }else{ 1471 pExpr = pRight; 1472 pExpr->span = pExpr->token; 1473 pExpr->span.dyn = 0; 1474 } 1475 if( longNames ){ 1476 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span); 1477 }else{ 1478 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token); 1479 } 1480 } 1481 } 1482 if( !tableSeen ){ 1483 if( zTName ){ 1484 sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 1485 }else{ 1486 sqlite3ErrorMsg(pParse, "no tables specified"); 1487 } 1488 rc = 1; 1489 } 1490 sqlite3_free(zTName); 1491 } 1492 } 1493 sqlite3ExprListDelete(pEList); 1494 p->pEList = pNew; 1495 } 1496 #if SQLITE_MAX_COLUMN 1497 if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 1498 sqlite3ErrorMsg(pParse, "too many columns in result set"); 1499 rc = SQLITE_ERROR; 1500 } 1501 #endif 1502 if( db->mallocFailed ){ 1503 rc = SQLITE_NOMEM; 1504 } 1505 return rc; 1506 } 1507 1508 /* 1509 ** pE is a pointer to an expression which is a single term in 1510 ** ORDER BY or GROUP BY clause. 1511 ** 1512 ** If pE evaluates to an integer constant i, then return i. 1513 ** This is an indication to the caller that it should sort 1514 ** by the i-th column of the result set. 1515 ** 1516 ** If pE is a well-formed expression and the SELECT statement 1517 ** is not compound, then return 0. This indicates to the 1518 ** caller that it should sort by the value of the ORDER BY 1519 ** expression. 1520 ** 1521 ** If the SELECT is compound, then attempt to match pE against 1522 ** result set columns in the left-most SELECT statement. Return 1523 ** the index i of the matching column, as an indication to the 1524 ** caller that it should sort by the i-th column. If there is 1525 ** no match, return -1 and leave an error message in pParse. 1526 */ 1527 static int matchOrderByTermToExprList( 1528 Parse *pParse, /* Parsing context for error messages */ 1529 Select *pSelect, /* The SELECT statement with the ORDER BY clause */ 1530 Expr *pE, /* The specific ORDER BY term */ 1531 int idx, /* When ORDER BY term is this */ 1532 int isCompound, /* True if this is a compound SELECT */ 1533 u8 *pHasAgg /* True if expression contains aggregate functions */ 1534 ){ 1535 int i; /* Loop counter */ 1536 ExprList *pEList; /* The columns of the result set */ 1537 NameContext nc; /* Name context for resolving pE */ 1538 1539 1540 /* If the term is an integer constant, return the value of that 1541 ** constant */ 1542 pEList = pSelect->pEList; 1543 if( sqlite3ExprIsInteger(pE, &i) ){ 1544 if( i<=0 ){ 1545 /* If i is too small, make it too big. That way the calling 1546 ** function still sees a value that is out of range, but does 1547 ** not confuse the column number with 0 or -1 result code. 1548 */ 1549 i = pEList->nExpr+1; 1550 } 1551 return i; 1552 } 1553 1554 /* If the term is a simple identifier that try to match that identifier 1555 ** against a column name in the result set. 1556 */ 1557 if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){ 1558 sqlite3 *db = pParse->db; 1559 char *zCol = sqlite3NameFromToken(db, &pE->token); 1560 if( zCol==0 ){ 1561 return -1; 1562 } 1563 for(i=0; i<pEList->nExpr; i++){ 1564 char *zAs = pEList->a[i].zName; 1565 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ 1566 sqlite3_free(zCol); 1567 return i+1; 1568 } 1569 } 1570 sqlite3_free(zCol); 1571 } 1572 1573 /* Resolve all names in the ORDER BY term expression 1574 */ 1575 memset(&nc, 0, sizeof(nc)); 1576 nc.pParse = pParse; 1577 nc.pSrcList = pSelect->pSrc; 1578 nc.pEList = pEList; 1579 nc.allowAgg = 1; 1580 nc.nErr = 0; 1581 if( sqlite3ExprResolveNames(&nc, pE) ){ 1582 if( isCompound ){ 1583 sqlite3ErrorClear(pParse); 1584 return 0; 1585 }else{ 1586 return -1; 1587 } 1588 } 1589 if( nc.hasAgg && pHasAgg ){ 1590 *pHasAgg = 1; 1591 } 1592 1593 /* For a compound SELECT, we need to try to match the ORDER BY 1594 ** expression against an expression in the result set 1595 */ 1596 if( isCompound ){ 1597 for(i=0; i<pEList->nExpr; i++){ 1598 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){ 1599 return i+1; 1600 } 1601 } 1602 } 1603 return 0; 1604 } 1605 1606 1607 /* 1608 ** Analyze and ORDER BY or GROUP BY clause in a simple SELECT statement. 1609 ** Return the number of errors seen. 1610 ** 1611 ** Every term of the ORDER BY or GROUP BY clause needs to be an 1612 ** expression. If any expression is an integer constant, then 1613 ** that expression is replaced by the corresponding 1614 ** expression from the result set. 1615 */ 1616 static int processOrderGroupBy( 1617 Parse *pParse, /* Parsing context. Leave error messages here */ 1618 Select *pSelect, /* The SELECT statement containing the clause */ 1619 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ 1620 int isOrder, /* 1 for ORDER BY. 0 for GROUP BY */ 1621 u8 *pHasAgg /* Set to TRUE if any term contains an aggregate */ 1622 ){ 1623 int i; 1624 sqlite3 *db = pParse->db; 1625 ExprList *pEList; 1626 1627 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0; 1628 #if SQLITE_MAX_COLUMN 1629 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 1630 const char *zType = isOrder ? "ORDER" : "GROUP"; 1631 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); 1632 return 1; 1633 } 1634 #endif 1635 pEList = pSelect->pEList; 1636 if( pEList==0 ){ 1637 return 0; 1638 } 1639 for(i=0; i<pOrderBy->nExpr; i++){ 1640 int iCol; 1641 Expr *pE = pOrderBy->a[i].pExpr; 1642 iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg); 1643 if( iCol<0 ){ 1644 return 1; 1645 } 1646 if( iCol>pEList->nExpr ){ 1647 const char *zType = isOrder ? "ORDER" : "GROUP"; 1648 sqlite3ErrorMsg(pParse, 1649 "%r %s BY term out of range - should be " 1650 "between 1 and %d", i+1, zType, pEList->nExpr); 1651 return 1; 1652 } 1653 if( iCol>0 ){ 1654 CollSeq *pColl = pE->pColl; 1655 int flags = pE->flags & EP_ExpCollate; 1656 sqlite3ExprDelete(pE); 1657 pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr); 1658 pOrderBy->a[i].pExpr = pE; 1659 if( pE && pColl && flags ){ 1660 pE->pColl = pColl; 1661 pE->flags |= flags; 1662 } 1663 } 1664 } 1665 return 0; 1666 } 1667 1668 /* 1669 ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return 1670 ** the number of errors seen. 1671 ** 1672 ** The processing depends on whether the SELECT is simple or compound. 1673 ** For a simple SELECT statement, evry term of the ORDER BY or GROUP BY 1674 ** clause needs to be an expression. If any expression is an integer 1675 ** constant, then that expression is replaced by the corresponding 1676 ** expression from the result set. 1677 ** 1678 ** For compound SELECT statements, every expression needs to be of 1679 ** type TK_COLUMN with a iTable value as given in the 4th parameter. 1680 ** If any expression is an integer, that becomes the column number. 1681 ** Otherwise, match the expression against result set columns from 1682 ** the left-most SELECT. 1683 */ 1684 static int processCompoundOrderBy( 1685 Parse *pParse, /* Parsing context. Leave error messages here */ 1686 Select *pSelect, /* The SELECT statement containing the ORDER BY */ 1687 int iTable /* Output table for compound SELECT statements */ 1688 ){ 1689 int i; 1690 ExprList *pOrderBy; 1691 ExprList *pEList; 1692 sqlite3 *db; 1693 int moreToDo = 1; 1694 1695 pOrderBy = pSelect->pOrderBy; 1696 if( pOrderBy==0 ) return 0; 1697 db = pParse->db; 1698 #if SQLITE_MAX_COLUMN 1699 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 1700 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); 1701 return 1; 1702 } 1703 #endif 1704 for(i=0; i<pOrderBy->nExpr; i++){ 1705 pOrderBy->a[i].done = 0; 1706 } 1707 while( pSelect->pPrior ){ 1708 pSelect = pSelect->pPrior; 1709 } 1710 while( pSelect && moreToDo ){ 1711 moreToDo = 0; 1712 for(i=0; i<pOrderBy->nExpr; i++){ 1713 int iCol = -1; 1714 Expr *pE, *pDup; 1715 if( pOrderBy->a[i].done ) continue; 1716 pE = pOrderBy->a[i].pExpr; 1717 pDup = sqlite3ExprDup(db, pE); 1718 if( !db->mallocFailed ){ 1719 assert(pDup); 1720 iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0); 1721 } 1722 sqlite3ExprDelete(pDup); 1723 if( iCol<0 ){ 1724 return 1; 1725 } 1726 pEList = pSelect->pEList; 1727 if( pEList==0 ){ 1728 return 1; 1729 } 1730 if( iCol>pEList->nExpr ){ 1731 sqlite3ErrorMsg(pParse, 1732 "%r ORDER BY term out of range - should be " 1733 "between 1 and %d", i+1, pEList->nExpr); 1734 return 1; 1735 } 1736 if( iCol>0 ){ 1737 pE->op = TK_COLUMN; 1738 pE->iTable = iTable; 1739 pE->iAgg = -1; 1740 pE->iColumn = iCol-1; 1741 pE->pTab = 0; 1742 pOrderBy->a[i].done = 1; 1743 }else{ 1744 moreToDo = 1; 1745 } 1746 } 1747 pSelect = pSelect->pNext; 1748 } 1749 for(i=0; i<pOrderBy->nExpr; i++){ 1750 if( pOrderBy->a[i].done==0 ){ 1751 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " 1752 "column in the result set", i+1); 1753 return 1; 1754 } 1755 } 1756 return 0; 1757 } 1758 1759 /* 1760 ** Get a VDBE for the given parser context. Create a new one if necessary. 1761 ** If an error occurs, return NULL and leave a message in pParse. 1762 */ 1763 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1764 Vdbe *v = pParse->pVdbe; 1765 if( v==0 ){ 1766 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); 1767 #ifndef SQLITE_OMIT_TRACE 1768 if( v ){ 1769 sqlite3VdbeAddOp0(v, OP_Trace); 1770 } 1771 #endif 1772 } 1773 return v; 1774 } 1775 1776 1777 /* 1778 ** Compute the iLimit and iOffset fields of the SELECT based on the 1779 ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions 1780 ** that appear in the original SQL statement after the LIMIT and OFFSET 1781 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 1782 ** are the integer memory register numbers for counters used to compute 1783 ** the limit and offset. If there is no limit and/or offset, then 1784 ** iLimit and iOffset are negative. 1785 ** 1786 ** This routine changes the values of iLimit and iOffset only if 1787 ** a limit or offset is defined by pLimit and pOffset. iLimit and 1788 ** iOffset should have been preset to appropriate default values 1789 ** (usually but not always -1) prior to calling this routine. 1790 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 1791 ** redefined. The UNION ALL operator uses this property to force 1792 ** the reuse of the same limit and offset registers across multiple 1793 ** SELECT statements. 1794 */ 1795 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 1796 Vdbe *v = 0; 1797 int iLimit = 0; 1798 int iOffset; 1799 int addr1; 1800 1801 /* 1802 ** "LIMIT -1" always shows all rows. There is some 1803 ** contraversy about what the correct behavior should be. 1804 ** The current implementation interprets "LIMIT 0" to mean 1805 ** no rows. 1806 */ 1807 if( p->pLimit ){ 1808 p->iLimit = iLimit = ++pParse->nMem; 1809 v = sqlite3GetVdbe(pParse); 1810 if( v==0 ) return; 1811 sqlite3ExprCode(pParse, p->pLimit, iLimit); 1812 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); 1813 VdbeComment((v, "LIMIT counter")); 1814 sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); 1815 } 1816 if( p->pOffset ){ 1817 p->iOffset = iOffset = ++pParse->nMem; 1818 if( p->pLimit ){ 1819 pParse->nMem++; /* Allocate an extra register for limit+offset */ 1820 } 1821 v = sqlite3GetVdbe(pParse); 1822 if( v==0 ) return; 1823 sqlite3ExprCode(pParse, p->pOffset, iOffset); 1824 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); 1825 VdbeComment((v, "OFFSET counter")); 1826 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); 1827 sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset); 1828 sqlite3VdbeJumpHere(v, addr1); 1829 if( p->pLimit ){ 1830 sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1); 1831 VdbeComment((v, "LIMIT+OFFSET")); 1832 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); 1833 sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1); 1834 sqlite3VdbeJumpHere(v, addr1); 1835 } 1836 } 1837 } 1838 1839 /* 1840 ** Allocate a virtual index to use for sorting. 1841 */ 1842 static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){ 1843 if( pOrderBy ){ 1844 int addr; 1845 assert( pOrderBy->iECursor==0 ); 1846 pOrderBy->iECursor = pParse->nTab++; 1847 addr = sqlite3VdbeAddOp2(pParse->pVdbe, OP_OpenEphemeral, 1848 pOrderBy->iECursor, pOrderBy->nExpr+1); 1849 assert( p->addrOpenEphm[2] == -1 ); 1850 p->addrOpenEphm[2] = addr; 1851 } 1852 } 1853 1854 #ifndef SQLITE_OMIT_COMPOUND_SELECT 1855 /* 1856 ** Return the appropriate collating sequence for the iCol-th column of 1857 ** the result set for the compound-select statement "p". Return NULL if 1858 ** the column has no default collating sequence. 1859 ** 1860 ** The collating sequence for the compound select is taken from the 1861 ** left-most term of the select that has a collating sequence. 1862 */ 1863 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1864 CollSeq *pRet; 1865 if( p->pPrior ){ 1866 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1867 }else{ 1868 pRet = 0; 1869 } 1870 if( pRet==0 ){ 1871 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1872 } 1873 return pRet; 1874 } 1875 #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1876 1877 #ifndef SQLITE_OMIT_COMPOUND_SELECT 1878 /* 1879 ** This routine is called to process a query that is really the union 1880 ** or intersection of two or more separate queries. 1881 ** 1882 ** "p" points to the right-most of the two queries. the query on the 1883 ** left is p->pPrior. The left query could also be a compound query 1884 ** in which case this routine will be called recursively. 1885 ** 1886 ** The results of the total query are to be written into a destination 1887 ** of type eDest with parameter iParm. 1888 ** 1889 ** Example 1: Consider a three-way compound SQL statement. 1890 ** 1891 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 1892 ** 1893 ** This statement is parsed up as follows: 1894 ** 1895 ** SELECT c FROM t3 1896 ** | 1897 ** `-----> SELECT b FROM t2 1898 ** | 1899 ** `------> SELECT a FROM t1 1900 ** 1901 ** The arrows in the diagram above represent the Select.pPrior pointer. 1902 ** So if this routine is called with p equal to the t3 query, then 1903 ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 1904 ** 1905 ** Notice that because of the way SQLite parses compound SELECTs, the 1906 ** individual selects always group from left to right. 1907 */ 1908 static int multiSelect( 1909 Parse *pParse, /* Parsing context */ 1910 Select *p, /* The right-most of SELECTs to be coded */ 1911 SelectDest *pDest, /* What to do with query results */ 1912 char *aff /* If eDest is SRT_Union, the affinity string */ 1913 ){ 1914 int rc = SQLITE_OK; /* Success code from a subroutine */ 1915 Select *pPrior; /* Another SELECT immediately to our left */ 1916 Vdbe *v; /* Generate code to this VDBE */ 1917 int nCol; /* Number of columns in the result set */ 1918 ExprList *pOrderBy; /* The ORDER BY clause on p */ 1919 int aSetP2[2]; /* Set P2 value of these op to number of columns */ 1920 int nSetP2 = 0; /* Number of slots in aSetP2[] used */ 1921 SelectDest dest; /* Alternative data destination */ 1922 1923 dest = *pDest; 1924 1925 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 1926 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 1927 */ 1928 if( p==0 || p->pPrior==0 ){ 1929 rc = 1; 1930 goto multi_select_end; 1931 } 1932 pPrior = p->pPrior; 1933 assert( pPrior->pRightmost!=pPrior ); 1934 assert( pPrior->pRightmost==p->pRightmost ); 1935 if( pPrior->pOrderBy ){ 1936 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 1937 selectOpName(p->op)); 1938 rc = 1; 1939 goto multi_select_end; 1940 } 1941 if( pPrior->pLimit ){ 1942 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 1943 selectOpName(p->op)); 1944 rc = 1; 1945 goto multi_select_end; 1946 } 1947 1948 /* Make sure we have a valid query engine. If not, create a new one. 1949 */ 1950 v = sqlite3GetVdbe(pParse); 1951 if( v==0 ){ 1952 rc = 1; 1953 goto multi_select_end; 1954 } 1955 1956 /* Create the destination temporary table if necessary 1957 */ 1958 if( dest.eDest==SRT_EphemTab ){ 1959 assert( p->pEList ); 1960 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); 1961 aSetP2[nSetP2++] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, 0); 1962 dest.eDest = SRT_Table; 1963 } 1964 1965 /* Generate code for the left and right SELECT statements. 1966 */ 1967 pOrderBy = p->pOrderBy; 1968 switch( p->op ){ 1969 case TK_ALL: { 1970 if( pOrderBy==0 ){ 1971 int addr = 0; 1972 assert( !pPrior->pLimit ); 1973 pPrior->pLimit = p->pLimit; 1974 pPrior->pOffset = p->pOffset; 1975 rc = sqlite3Select(pParse, pPrior, &dest, 0, 0, 0, aff); 1976 p->pLimit = 0; 1977 p->pOffset = 0; 1978 if( rc ){ 1979 goto multi_select_end; 1980 } 1981 p->pPrior = 0; 1982 p->iLimit = pPrior->iLimit; 1983 p->iOffset = pPrior->iOffset; 1984 if( p->iLimit>=0 ){ 1985 addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); 1986 VdbeComment((v, "Jump ahead if LIMIT reached")); 1987 } 1988 rc = sqlite3Select(pParse, p, &dest, 0, 0, 0, aff); 1989 p->pPrior = pPrior; 1990 if( rc ){ 1991 goto multi_select_end; 1992 } 1993 if( addr ){ 1994 sqlite3VdbeJumpHere(v, addr); 1995 } 1996 break; 1997 } 1998 /* For UNION ALL ... ORDER BY fall through to the next case */ 1999 } 2000 case TK_EXCEPT: 2001 case TK_UNION: { 2002 int unionTab; /* Cursor number of the temporary table holding result */ 2003 int op = 0; /* One of the SRT_ operations to apply to self */ 2004 int priorOp; /* The SRT_ operation to apply to prior selects */ 2005 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ 2006 int addr; 2007 SelectDest uniondest; 2008 2009 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union; 2010 if( dest.eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){ 2011 /* We can reuse a temporary table generated by a SELECT to our 2012 ** right. 2013 */ 2014 unionTab = dest.iParm; 2015 }else{ 2016 /* We will need to create our own temporary table to hold the 2017 ** intermediate results. 2018 */ 2019 unionTab = pParse->nTab++; 2020 if( processCompoundOrderBy(pParse, p, unionTab) ){ 2021 rc = 1; 2022 goto multi_select_end; 2023 } 2024 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 2025 if( priorOp==SRT_Table ){ 2026 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); 2027 aSetP2[nSetP2++] = addr; 2028 }else{ 2029 assert( p->addrOpenEphm[0] == -1 ); 2030 p->addrOpenEphm[0] = addr; 2031 p->pRightmost->usesEphm = 1; 2032 } 2033 createSortingIndex(pParse, p, pOrderBy); 2034 assert( p->pEList ); 2035 } 2036 2037 /* Code the SELECT statements to our left 2038 */ 2039 assert( !pPrior->pOrderBy ); 2040 sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 2041 rc = sqlite3Select(pParse, pPrior, &uniondest, 0, 0, 0, aff); 2042 if( rc ){ 2043 goto multi_select_end; 2044 } 2045 2046 /* Code the current SELECT statement 2047 */ 2048 switch( p->op ){ 2049 case TK_EXCEPT: op = SRT_Except; break; 2050 case TK_UNION: op = SRT_Union; break; 2051 case TK_ALL: op = SRT_Table; break; 2052 } 2053 p->pPrior = 0; 2054 p->pOrderBy = 0; 2055 p->disallowOrderBy = pOrderBy!=0; 2056 pLimit = p->pLimit; 2057 p->pLimit = 0; 2058 pOffset = p->pOffset; 2059 p->pOffset = 0; 2060 uniondest.eDest = op; 2061 rc = sqlite3Select(pParse, p, &uniondest, 0, 0, 0, aff); 2062 /* Query flattening in sqlite3Select() might refill p->pOrderBy. 2063 ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 2064 sqlite3ExprListDelete(p->pOrderBy); 2065 p->pPrior = pPrior; 2066 p->pOrderBy = pOrderBy; 2067 sqlite3ExprDelete(p->pLimit); 2068 p->pLimit = pLimit; 2069 p->pOffset = pOffset; 2070 p->iLimit = -1; 2071 p->iOffset = -1; 2072 if( rc ){ 2073 goto multi_select_end; 2074 } 2075 2076 2077 /* Convert the data in the temporary table into whatever form 2078 ** it is that we currently need. 2079 */ 2080 if( dest.eDest!=priorOp || unionTab!=dest.iParm ){ 2081 int iCont, iBreak, iStart; 2082 assert( p->pEList ); 2083 if( dest.eDest==SRT_Callback ){ 2084 Select *pFirst = p; 2085 while( pFirst->pPrior ) pFirst = pFirst->pPrior; 2086 generateColumnNames(pParse, 0, pFirst->pEList); 2087 } 2088 iBreak = sqlite3VdbeMakeLabel(v); 2089 iCont = sqlite3VdbeMakeLabel(v); 2090 computeLimitRegisters(pParse, p, iBreak); 2091 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); 2092 iStart = sqlite3VdbeCurrentAddr(v); 2093 selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, 2094 pOrderBy, -1, &dest, iCont, iBreak, 0); 2095 sqlite3VdbeResolveLabel(v, iCont); 2096 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); 2097 sqlite3VdbeResolveLabel(v, iBreak); 2098 sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 2099 } 2100 break; 2101 } 2102 case TK_INTERSECT: { 2103 int tab1, tab2; 2104 int iCont, iBreak, iStart; 2105 Expr *pLimit, *pOffset; 2106 int addr; 2107 SelectDest intersectdest; 2108 int r1; 2109 2110 /* INTERSECT is different from the others since it requires 2111 ** two temporary tables. Hence it has its own case. Begin 2112 ** by allocating the tables we will need. 2113 */ 2114 tab1 = pParse->nTab++; 2115 tab2 = pParse->nTab++; 2116 if( processCompoundOrderBy(pParse, p, tab1) ){ 2117 rc = 1; 2118 goto multi_select_end; 2119 } 2120 createSortingIndex(pParse, p, pOrderBy); 2121 2122 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 2123 assert( p->addrOpenEphm[0] == -1 ); 2124 p->addrOpenEphm[0] = addr; 2125 p->pRightmost->usesEphm = 1; 2126 assert( p->pEList ); 2127 2128 /* Code the SELECTs to our left into temporary table "tab1". 2129 */ 2130 sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 2131 rc = sqlite3Select(pParse, pPrior, &intersectdest, 0, 0, 0, aff); 2132 if( rc ){ 2133 goto multi_select_end; 2134 } 2135 2136 /* Code the current SELECT into temporary table "tab2" 2137 */ 2138 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 2139 assert( p->addrOpenEphm[1] == -1 ); 2140 p->addrOpenEphm[1] = addr; 2141 p->pPrior = 0; 2142 pLimit = p->pLimit; 2143 p->pLimit = 0; 2144 pOffset = p->pOffset; 2145 p->pOffset = 0; 2146 intersectdest.iParm = tab2; 2147 rc = sqlite3Select(pParse, p, &intersectdest, 0, 0, 0, aff); 2148 p->pPrior = pPrior; 2149 sqlite3ExprDelete(p->pLimit); 2150 p->pLimit = pLimit; 2151 p->pOffset = pOffset; 2152 if( rc ){ 2153 goto multi_select_end; 2154 } 2155 2156 /* Generate code to take the intersection of the two temporary 2157 ** tables. 2158 */ 2159 assert( p->pEList ); 2160 if( dest.eDest==SRT_Callback ){ 2161 Select *pFirst = p; 2162 while( pFirst->pPrior ) pFirst = pFirst->pPrior; 2163 generateColumnNames(pParse, 0, pFirst->pEList); 2164 } 2165 iBreak = sqlite3VdbeMakeLabel(v); 2166 iCont = sqlite3VdbeMakeLabel(v); 2167 computeLimitRegisters(pParse, p, iBreak); 2168 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); 2169 r1 = sqlite3GetTempReg(pParse); 2170 iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); 2171 sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1); 2172 sqlite3ReleaseTempReg(pParse, r1); 2173 selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, 2174 pOrderBy, -1, &dest, iCont, iBreak, 0); 2175 sqlite3VdbeResolveLabel(v, iCont); 2176 sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); 2177 sqlite3VdbeResolveLabel(v, iBreak); 2178 sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); 2179 sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); 2180 break; 2181 } 2182 } 2183 2184 /* Make sure all SELECTs in the statement have the same number of elements 2185 ** in their result sets. 2186 */ 2187 assert( p->pEList && pPrior->pEList ); 2188 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 2189 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 2190 " do not have the same number of result columns", selectOpName(p->op)); 2191 rc = 1; 2192 goto multi_select_end; 2193 } 2194 2195 /* Set the number of columns in temporary tables 2196 */ 2197 nCol = p->pEList->nExpr; 2198 while( nSetP2 ){ 2199 sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol); 2200 } 2201 2202 /* Compute collating sequences used by either the ORDER BY clause or 2203 ** by any temporary tables needed to implement the compound select. 2204 ** Attach the KeyInfo structure to all temporary tables. Invoke the 2205 ** ORDER BY processing if there is an ORDER BY clause. 2206 ** 2207 ** This section is run by the right-most SELECT statement only. 2208 ** SELECT statements to the left always skip this part. The right-most 2209 ** SELECT might also skip this part if it has no ORDER BY clause and 2210 ** no temp tables are required. 2211 */ 2212 if( pOrderBy || p->usesEphm ){ 2213 int i; /* Loop counter */ 2214 KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 2215 Select *pLoop; /* For looping through SELECT statements */ 2216 int nKeyCol; /* Number of entries in pKeyInfo->aCol[] */ 2217 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 2218 CollSeq **aCopy; /* A copy of pKeyInfo->aColl[] */ 2219 2220 assert( p->pRightmost==p ); 2221 nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0); 2222 pKeyInfo = sqlite3DbMallocZero(pParse->db, 2223 sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1)); 2224 if( !pKeyInfo ){ 2225 rc = SQLITE_NOMEM; 2226 goto multi_select_end; 2227 } 2228 2229 pKeyInfo->enc = ENC(pParse->db); 2230 pKeyInfo->nField = nCol; 2231 2232 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 2233 *apColl = multiSelectCollSeq(pParse, p, i); 2234 if( 0==*apColl ){ 2235 *apColl = pParse->db->pDfltColl; 2236 } 2237 } 2238 2239 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 2240 for(i=0; i<2; i++){ 2241 int addr = pLoop->addrOpenEphm[i]; 2242 if( addr<0 ){ 2243 /* If [0] is unused then [1] is also unused. So we can 2244 ** always safely abort as soon as the first unused slot is found */ 2245 assert( pLoop->addrOpenEphm[1]<0 ); 2246 break; 2247 } 2248 sqlite3VdbeChangeP2(v, addr, nCol); 2249 sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO); 2250 pLoop->addrOpenEphm[i] = -1; 2251 } 2252 } 2253 2254 if( pOrderBy ){ 2255 struct ExprList_item *pOTerm = pOrderBy->a; 2256 int nOrderByExpr = pOrderBy->nExpr; 2257 int addr; 2258 u8 *pSortOrder; 2259 2260 /* Reuse the same pKeyInfo for the ORDER BY as was used above for 2261 ** the compound select statements. Except we have to change out the 2262 ** pKeyInfo->aColl[] values. Some of the aColl[] values will be 2263 ** reused when constructing the pKeyInfo for the ORDER BY, so make 2264 ** a copy. Sufficient space to hold both the nCol entries for 2265 ** the compound select and the nOrderbyExpr entries for the ORDER BY 2266 ** was allocated above. But we need to move the compound select 2267 ** entries out of the way before constructing the ORDER BY entries. 2268 ** Move the compound select entries into aCopy[] where they can be 2269 ** accessed and reused when constructing the ORDER BY entries. 2270 ** Because nCol might be greater than or less than nOrderByExpr 2271 ** we have to use memmove() when doing the copy. 2272 */ 2273 aCopy = &pKeyInfo->aColl[nOrderByExpr]; 2274 pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol]; 2275 memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*)); 2276 2277 apColl = pKeyInfo->aColl; 2278 for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){ 2279 Expr *pExpr = pOTerm->pExpr; 2280 if( (pExpr->flags & EP_ExpCollate) ){ 2281 assert( pExpr->pColl!=0 ); 2282 *apColl = pExpr->pColl; 2283 }else{ 2284 *apColl = aCopy[pExpr->iColumn]; 2285 } 2286 *pSortOrder = pOTerm->sortOrder; 2287 } 2288 assert( p->pRightmost==p ); 2289 assert( p->addrOpenEphm[2]>=0 ); 2290 addr = p->addrOpenEphm[2]; 2291 sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2); 2292 pKeyInfo->nField = nOrderByExpr; 2293 sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 2294 pKeyInfo = 0; 2295 generateSortTail(pParse, p, v, p->pEList->nExpr, &dest); 2296 } 2297 2298 sqlite3_free(pKeyInfo); 2299 } 2300 2301 multi_select_end: 2302 pDest->iMem = dest.iMem; 2303 pDest->nMem = dest.nMem; 2304 return rc; 2305 } 2306 #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 2307 2308 #ifndef SQLITE_OMIT_VIEW 2309 /* Forward Declarations */ 2310 static void substExprList(sqlite3*, ExprList*, int, ExprList*); 2311 static void substSelect(sqlite3*, Select *, int, ExprList *); 2312 2313 /* 2314 ** Scan through the expression pExpr. Replace every reference to 2315 ** a column in table number iTable with a copy of the iColumn-th 2316 ** entry in pEList. (But leave references to the ROWID column 2317 ** unchanged.) 2318 ** 2319 ** This routine is part of the flattening procedure. A subquery 2320 ** whose result set is defined by pEList appears as entry in the 2321 ** FROM clause of a SELECT such that the VDBE cursor assigned to that 2322 ** FORM clause entry is iTable. This routine make the necessary 2323 ** changes to pExpr so that it refers directly to the source table 2324 ** of the subquery rather the result set of the subquery. 2325 */ 2326 static void substExpr( 2327 sqlite3 *db, /* Report malloc errors to this connection */ 2328 Expr *pExpr, /* Expr in which substitution occurs */ 2329 int iTable, /* Table to be substituted */ 2330 ExprList *pEList /* Substitute expressions */ 2331 ){ 2332 if( pExpr==0 ) return; 2333 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 2334 if( pExpr->iColumn<0 ){ 2335 pExpr->op = TK_NULL; 2336 }else{ 2337 Expr *pNew; 2338 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 2339 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 ); 2340 pNew = pEList->a[pExpr->iColumn].pExpr; 2341 assert( pNew!=0 ); 2342 pExpr->op = pNew->op; 2343 assert( pExpr->pLeft==0 ); 2344 pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft); 2345 assert( pExpr->pRight==0 ); 2346 pExpr->pRight = sqlite3ExprDup(db, pNew->pRight); 2347 assert( pExpr->pList==0 ); 2348 pExpr->pList = sqlite3ExprListDup(db, pNew->pList); 2349 pExpr->iTable = pNew->iTable; 2350 pExpr->pTab = pNew->pTab; 2351 pExpr->iColumn = pNew->iColumn; 2352 pExpr->iAgg = pNew->iAgg; 2353 sqlite3TokenCopy(db, &pExpr->token, &pNew->token); 2354 sqlite3TokenCopy(db, &pExpr->span, &pNew->span); 2355 pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect); 2356 pExpr->flags = pNew->flags; 2357 } 2358 }else{ 2359 substExpr(db, pExpr->pLeft, iTable, pEList); 2360 substExpr(db, pExpr->pRight, iTable, pEList); 2361 substSelect(db, pExpr->pSelect, iTable, pEList); 2362 substExprList(db, pExpr->pList, iTable, pEList); 2363 } 2364 } 2365 static void substExprList( 2366 sqlite3 *db, /* Report malloc errors here */ 2367 ExprList *pList, /* List to scan and in which to make substitutes */ 2368 int iTable, /* Table to be substituted */ 2369 ExprList *pEList /* Substitute values */ 2370 ){ 2371 int i; 2372 if( pList==0 ) return; 2373 for(i=0; i<pList->nExpr; i++){ 2374 substExpr(db, pList->a[i].pExpr, iTable, pEList); 2375 } 2376 } 2377 static void substSelect( 2378 sqlite3 *db, /* Report malloc errors here */ 2379 Select *p, /* SELECT statement in which to make substitutions */ 2380 int iTable, /* Table to be replaced */ 2381 ExprList *pEList /* Substitute values */ 2382 ){ 2383 if( !p ) return; 2384 substExprList(db, p->pEList, iTable, pEList); 2385 substExprList(db, p->pGroupBy, iTable, pEList); 2386 substExprList(db, p->pOrderBy, iTable, pEList); 2387 substExpr(db, p->pHaving, iTable, pEList); 2388 substExpr(db, p->pWhere, iTable, pEList); 2389 substSelect(db, p->pPrior, iTable, pEList); 2390 } 2391 #endif /* !defined(SQLITE_OMIT_VIEW) */ 2392 2393 #ifndef SQLITE_OMIT_VIEW 2394 /* 2395 ** This routine attempts to flatten subqueries in order to speed 2396 ** execution. It returns 1 if it makes changes and 0 if no flattening 2397 ** occurs. 2398 ** 2399 ** To understand the concept of flattening, consider the following 2400 ** query: 2401 ** 2402 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 2403 ** 2404 ** The default way of implementing this query is to execute the 2405 ** subquery first and store the results in a temporary table, then 2406 ** run the outer query on that temporary table. This requires two 2407 ** passes over the data. Furthermore, because the temporary table 2408 ** has no indices, the WHERE clause on the outer query cannot be 2409 ** optimized. 2410 ** 2411 ** This routine attempts to rewrite queries such as the above into 2412 ** a single flat select, like this: 2413 ** 2414 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 2415 ** 2416 ** The code generated for this simpification gives the same result 2417 ** but only has to scan the data once. And because indices might 2418 ** exist on the table t1, a complete scan of the data might be 2419 ** avoided. 2420 ** 2421 ** Flattening is only attempted if all of the following are true: 2422 ** 2423 ** (1) The subquery and the outer query do not both use aggregates. 2424 ** 2425 ** (2) The subquery is not an aggregate or the outer query is not a join. 2426 ** 2427 ** (3) The subquery is not the right operand of a left outer join, or 2428 ** the subquery is not itself a join. (Ticket #306) 2429 ** 2430 ** (4) The subquery is not DISTINCT or the outer query is not a join. 2431 ** 2432 ** (5) The subquery is not DISTINCT or the outer query does not use 2433 ** aggregates. 2434 ** 2435 ** (6) The subquery does not use aggregates or the outer query is not 2436 ** DISTINCT. 2437 ** 2438 ** (7) The subquery has a FROM clause. 2439 ** 2440 ** (8) The subquery does not use LIMIT or the outer query is not a join. 2441 ** 2442 ** (9) The subquery does not use LIMIT or the outer query does not use 2443 ** aggregates. 2444 ** 2445 ** (10) The subquery does not use aggregates or the outer query does not 2446 ** use LIMIT. 2447 ** 2448 ** (11) The subquery and the outer query do not both have ORDER BY clauses. 2449 ** 2450 ** (12) The subquery is not the right term of a LEFT OUTER JOIN or the 2451 ** subquery has no WHERE clause. (added by ticket #350) 2452 ** 2453 ** (13) The subquery and outer query do not both use LIMIT 2454 ** 2455 ** (14) The subquery does not use OFFSET 2456 ** 2457 ** (15) The outer query is not part of a compound select or the 2458 ** subquery does not have both an ORDER BY and a LIMIT clause. 2459 ** (See ticket #2339) 2460 ** 2461 ** (16) The outer query is not an aggregate or the subquery does 2462 ** not contain ORDER BY. (Ticket #2942) This used to not matter 2463 ** until we introduced the group_concat() function. 2464 ** 2465 ** In this routine, the "p" parameter is a pointer to the outer query. 2466 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 2467 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 2468 ** 2469 ** If flattening is not attempted, this routine is a no-op and returns 0. 2470 ** If flattening is attempted this routine returns 1. 2471 ** 2472 ** All of the expression analysis must occur on both the outer query and 2473 ** the subquery before this routine runs. 2474 */ 2475 static int flattenSubquery( 2476 sqlite3 *db, /* Database connection */ 2477 Select *p, /* The parent or outer SELECT statement */ 2478 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 2479 int isAgg, /* True if outer SELECT uses aggregate functions */ 2480 int subqueryIsAgg /* True if the subquery uses aggregate functions */ 2481 ){ 2482 Select *pSub; /* The inner query or "subquery" */ 2483 SrcList *pSrc; /* The FROM clause of the outer query */ 2484 SrcList *pSubSrc; /* The FROM clause of the subquery */ 2485 ExprList *pList; /* The result set of the outer query */ 2486 int iParent; /* VDBE cursor number of the pSub result set temp table */ 2487 int i; /* Loop counter */ 2488 Expr *pWhere; /* The WHERE clause */ 2489 struct SrcList_item *pSubitem; /* The subquery */ 2490 2491 /* Check to see if flattening is permitted. Return 0 if not. 2492 */ 2493 if( p==0 ) return 0; 2494 pSrc = p->pSrc; 2495 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 2496 pSubitem = &pSrc->a[iFrom]; 2497 pSub = pSubitem->pSelect; 2498 assert( pSub!=0 ); 2499 if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ 2500 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ 2501 pSubSrc = pSub->pSrc; 2502 assert( pSubSrc ); 2503 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 2504 ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET 2505 ** because they could be computed at compile-time. But when LIMIT and OFFSET 2506 ** became arbitrary expressions, we were forced to add restrictions (13) 2507 ** and (14). */ 2508 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 2509 if( pSub->pOffset ) return 0; /* Restriction (14) */ 2510 if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){ 2511 return 0; /* Restriction (15) */ 2512 } 2513 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 2514 if( (pSub->isDistinct || pSub->pLimit) 2515 && (pSrc->nSrc>1 || isAgg) ){ /* Restrictions (4)(5)(8)(9) */ 2516 return 0; 2517 } 2518 if( p->isDistinct && subqueryIsAgg ) return 0; /* Restriction (6) */ 2519 if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){ 2520 return 0; /* Restriction (11) */ 2521 } 2522 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 2523 2524 /* Restriction 3: If the subquery is a join, make sure the subquery is 2525 ** not used as the right operand of an outer join. Examples of why this 2526 ** is not allowed: 2527 ** 2528 ** t1 LEFT OUTER JOIN (t2 JOIN t3) 2529 ** 2530 ** If we flatten the above, we would get 2531 ** 2532 ** (t1 LEFT OUTER JOIN t2) JOIN t3 2533 ** 2534 ** which is not at all the same thing. 2535 */ 2536 if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){ 2537 return 0; 2538 } 2539 2540 /* Restriction 12: If the subquery is the right operand of a left outer 2541 ** join, make sure the subquery has no WHERE clause. 2542 ** An examples of why this is not allowed: 2543 ** 2544 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 2545 ** 2546 ** If we flatten the above, we would get 2547 ** 2548 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 2549 ** 2550 ** But the t2.x>0 test will always fail on a NULL row of t2, which 2551 ** effectively converts the OUTER JOIN into an INNER JOIN. 2552 */ 2553 if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){ 2554 return 0; 2555 } 2556 2557 /* If we reach this point, it means flattening is permitted for the 2558 ** iFrom-th entry of the FROM clause in the outer query. 2559 */ 2560 2561 /* Move all of the FROM elements of the subquery into the 2562 ** the FROM clause of the outer query. Before doing this, remember 2563 ** the cursor number for the original outer query FROM element in 2564 ** iParent. The iParent cursor will never be used. Subsequent code 2565 ** will scan expressions looking for iParent references and replace 2566 ** those references with expressions that resolve to the subquery FROM 2567 ** elements we are now copying in. 2568 */ 2569 iParent = pSubitem->iCursor; 2570 { 2571 int nSubSrc = pSubSrc->nSrc; 2572 int jointype = pSubitem->jointype; 2573 2574 sqlite3DeleteTable(pSubitem->pTab); 2575 sqlite3_free(pSubitem->zDatabase); 2576 sqlite3_free(pSubitem->zName); 2577 sqlite3_free(pSubitem->zAlias); 2578 pSubitem->pTab = 0; 2579 pSubitem->zDatabase = 0; 2580 pSubitem->zName = 0; 2581 pSubitem->zAlias = 0; 2582 if( nSubSrc>1 ){ 2583 int extra = nSubSrc - 1; 2584 for(i=1; i<nSubSrc; i++){ 2585 pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0); 2586 if( pSrc==0 ){ 2587 p->pSrc = 0; 2588 return 1; 2589 } 2590 } 2591 p->pSrc = pSrc; 2592 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){ 2593 pSrc->a[i] = pSrc->a[i-extra]; 2594 } 2595 } 2596 for(i=0; i<nSubSrc; i++){ 2597 pSrc->a[i+iFrom] = pSubSrc->a[i]; 2598 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 2599 } 2600 pSrc->a[iFrom].jointype = jointype; 2601 } 2602 2603 /* Now begin substituting subquery result set expressions for 2604 ** references to the iParent in the outer query. 2605 ** 2606 ** Example: 2607 ** 2608 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 2609 ** \ \_____________ subquery __________/ / 2610 ** \_____________________ outer query ______________________________/ 2611 ** 2612 ** We look at every expression in the outer query and every place we see 2613 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 2614 */ 2615 pList = p->pEList; 2616 for(i=0; i<pList->nExpr; i++){ 2617 Expr *pExpr; 2618 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){ 2619 pList->a[i].zName = 2620 sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n); 2621 } 2622 } 2623 substExprList(db, p->pEList, iParent, pSub->pEList); 2624 if( isAgg ){ 2625 substExprList(db, p->pGroupBy, iParent, pSub->pEList); 2626 substExpr(db, p->pHaving, iParent, pSub->pEList); 2627 } 2628 if( pSub->pOrderBy ){ 2629 assert( p->pOrderBy==0 ); 2630 p->pOrderBy = pSub->pOrderBy; 2631 pSub->pOrderBy = 0; 2632 }else if( p->pOrderBy ){ 2633 substExprList(db, p->pOrderBy, iParent, pSub->pEList); 2634 } 2635 if( pSub->pWhere ){ 2636 pWhere = sqlite3ExprDup(db, pSub->pWhere); 2637 }else{ 2638 pWhere = 0; 2639 } 2640 if( subqueryIsAgg ){ 2641 assert( p->pHaving==0 ); 2642 p->pHaving = p->pWhere; 2643 p->pWhere = pWhere; 2644 substExpr(db, p->pHaving, iParent, pSub->pEList); 2645 p->pHaving = sqlite3ExprAnd(db, p->pHaving, 2646 sqlite3ExprDup(db, pSub->pHaving)); 2647 assert( p->pGroupBy==0 ); 2648 p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy); 2649 }else{ 2650 substExpr(db, p->pWhere, iParent, pSub->pEList); 2651 p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere); 2652 } 2653 2654 /* The flattened query is distinct if either the inner or the 2655 ** outer query is distinct. 2656 */ 2657 p->isDistinct = p->isDistinct || pSub->isDistinct; 2658 2659 /* 2660 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 2661 ** 2662 ** One is tempted to try to add a and b to combine the limits. But this 2663 ** does not work if either limit is negative. 2664 */ 2665 if( pSub->pLimit ){ 2666 p->pLimit = pSub->pLimit; 2667 pSub->pLimit = 0; 2668 } 2669 2670 /* Finially, delete what is left of the subquery and return 2671 ** success. 2672 */ 2673 sqlite3SelectDelete(pSub); 2674 return 1; 2675 } 2676 #endif /* SQLITE_OMIT_VIEW */ 2677 2678 /* 2679 ** Analyze the SELECT statement passed as an argument to see if it 2680 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 2681 ** it is, or 0 otherwise. At present, a query is considered to be 2682 ** a min()/max() query if: 2683 ** 2684 ** 1. There is a single object in the FROM clause. 2685 ** 2686 ** 2. There is a single expression in the result set, and it is 2687 ** either min(x) or max(x), where x is a column reference. 2688 */ 2689 static int minMaxQuery(Parse *pParse, Select *p){ 2690 Expr *pExpr; 2691 ExprList *pEList = p->pEList; 2692 2693 if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL; 2694 pExpr = pEList->a[0].pExpr; 2695 pEList = pExpr->pList; 2696 if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0; 2697 if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL; 2698 if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL; 2699 if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){ 2700 return WHERE_ORDERBY_MIN; 2701 }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){ 2702 return WHERE_ORDERBY_MAX; 2703 } 2704 return WHERE_ORDERBY_NORMAL; 2705 } 2706 2707 /* 2708 ** This routine resolves any names used in the result set of the 2709 ** supplied SELECT statement. If the SELECT statement being resolved 2710 ** is a sub-select, then pOuterNC is a pointer to the NameContext 2711 ** of the parent SELECT. 2712 */ 2713 int sqlite3SelectResolve( 2714 Parse *pParse, /* The parser context */ 2715 Select *p, /* The SELECT statement being coded. */ 2716 NameContext *pOuterNC /* The outer name context. May be NULL. */ 2717 ){ 2718 ExprList *pEList; /* Result set. */ 2719 int i; /* For-loop variable used in multiple places */ 2720 NameContext sNC; /* Local name-context */ 2721 ExprList *pGroupBy; /* The group by clause */ 2722 2723 /* If this routine has run before, return immediately. */ 2724 if( p->isResolved ){ 2725 assert( !pOuterNC ); 2726 return SQLITE_OK; 2727 } 2728 p->isResolved = 1; 2729 2730 /* If there have already been errors, do nothing. */ 2731 if( pParse->nErr>0 ){ 2732 return SQLITE_ERROR; 2733 } 2734 2735 /* Prepare the select statement. This call will allocate all cursors 2736 ** required to handle the tables and subqueries in the FROM clause. 2737 */ 2738 if( prepSelectStmt(pParse, p) ){ 2739 return SQLITE_ERROR; 2740 } 2741 2742 /* Resolve the expressions in the LIMIT and OFFSET clauses. These 2743 ** are not allowed to refer to any names, so pass an empty NameContext. 2744 */ 2745 memset(&sNC, 0, sizeof(sNC)); 2746 sNC.pParse = pParse; 2747 if( sqlite3ExprResolveNames(&sNC, p->pLimit) || 2748 sqlite3ExprResolveNames(&sNC, p->pOffset) ){ 2749 return SQLITE_ERROR; 2750 } 2751 2752 /* Set up the local name-context to pass to ExprResolveNames() to 2753 ** resolve the expression-list. 2754 */ 2755 sNC.allowAgg = 1; 2756 sNC.pSrcList = p->pSrc; 2757 sNC.pNext = pOuterNC; 2758 2759 /* Resolve names in the result set. */ 2760 pEList = p->pEList; 2761 if( !pEList ) return SQLITE_ERROR; 2762 for(i=0; i<pEList->nExpr; i++){ 2763 Expr *pX = pEList->a[i].pExpr; 2764 if( sqlite3ExprResolveNames(&sNC, pX) ){ 2765 return SQLITE_ERROR; 2766 } 2767 } 2768 2769 /* If there are no aggregate functions in the result-set, and no GROUP BY 2770 ** expression, do not allow aggregates in any of the other expressions. 2771 */ 2772 assert( !p->isAgg ); 2773 pGroupBy = p->pGroupBy; 2774 if( pGroupBy || sNC.hasAgg ){ 2775 p->isAgg = 1; 2776 }else{ 2777 sNC.allowAgg = 0; 2778 } 2779 2780 /* If a HAVING clause is present, then there must be a GROUP BY clause. 2781 */ 2782 if( p->pHaving && !pGroupBy ){ 2783 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); 2784 return SQLITE_ERROR; 2785 } 2786 2787 /* Add the expression list to the name-context before parsing the 2788 ** other expressions in the SELECT statement. This is so that 2789 ** expressions in the WHERE clause (etc.) can refer to expressions by 2790 ** aliases in the result set. 2791 ** 2792 ** Minor point: If this is the case, then the expression will be 2793 ** re-evaluated for each reference to it. 2794 */ 2795 sNC.pEList = p->pEList; 2796 if( sqlite3ExprResolveNames(&sNC, p->pWhere) || 2797 sqlite3ExprResolveNames(&sNC, p->pHaving) ){ 2798 return SQLITE_ERROR; 2799 } 2800 if( p->pPrior==0 ){ 2801 if( processOrderGroupBy(pParse, p, p->pOrderBy, 1, &sNC.hasAgg) ){ 2802 return SQLITE_ERROR; 2803 } 2804 } 2805 if( processOrderGroupBy(pParse, p, pGroupBy, 0, &sNC.hasAgg) ){ 2806 return SQLITE_ERROR; 2807 } 2808 2809 if( pParse->db->mallocFailed ){ 2810 return SQLITE_NOMEM; 2811 } 2812 2813 /* Make sure the GROUP BY clause does not contain aggregate functions. 2814 */ 2815 if( pGroupBy ){ 2816 struct ExprList_item *pItem; 2817 2818 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){ 2819 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ 2820 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " 2821 "the GROUP BY clause"); 2822 return SQLITE_ERROR; 2823 } 2824 } 2825 } 2826 2827 /* If this is one SELECT of a compound, be sure to resolve names 2828 ** in the other SELECTs. 2829 */ 2830 if( p->pPrior ){ 2831 return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC); 2832 }else{ 2833 return SQLITE_OK; 2834 } 2835 } 2836 2837 /* 2838 ** Reset the aggregate accumulator. 2839 ** 2840 ** The aggregate accumulator is a set of memory cells that hold 2841 ** intermediate results while calculating an aggregate. This 2842 ** routine simply stores NULLs in all of those memory cells. 2843 */ 2844 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 2845 Vdbe *v = pParse->pVdbe; 2846 int i; 2847 struct AggInfo_func *pFunc; 2848 if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ 2849 return; 2850 } 2851 for(i=0; i<pAggInfo->nColumn; i++){ 2852 sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem); 2853 } 2854 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 2855 sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem); 2856 if( pFunc->iDistinct>=0 ){ 2857 Expr *pE = pFunc->pExpr; 2858 if( pE->pList==0 || pE->pList->nExpr!=1 ){ 2859 sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed " 2860 "by an expression"); 2861 pFunc->iDistinct = -1; 2862 }else{ 2863 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList); 2864 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 2865 (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 2866 } 2867 } 2868 } 2869 } 2870 2871 /* 2872 ** Invoke the OP_AggFinalize opcode for every aggregate function 2873 ** in the AggInfo structure. 2874 */ 2875 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 2876 Vdbe *v = pParse->pVdbe; 2877 int i; 2878 struct AggInfo_func *pF; 2879 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 2880 ExprList *pList = pF->pExpr->pList; 2881 sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, 2882 (void*)pF->pFunc, P4_FUNCDEF); 2883 } 2884 } 2885 2886 /* 2887 ** Update the accumulator memory cells for an aggregate based on 2888 ** the current cursor position. 2889 */ 2890 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 2891 Vdbe *v = pParse->pVdbe; 2892 int i; 2893 struct AggInfo_func *pF; 2894 struct AggInfo_col *pC; 2895 2896 pAggInfo->directMode = 1; 2897 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 2898 int nArg; 2899 int addrNext = 0; 2900 int regAgg; 2901 ExprList *pList = pF->pExpr->pList; 2902 if( pList ){ 2903 nArg = pList->nExpr; 2904 regAgg = sqlite3GetTempRange(pParse, nArg); 2905 sqlite3ExprCodeExprList(pParse, pList, regAgg); 2906 }else{ 2907 nArg = 0; 2908 regAgg = 0; 2909 } 2910 if( pF->iDistinct>=0 ){ 2911 addrNext = sqlite3VdbeMakeLabel(v); 2912 assert( nArg==1 ); 2913 codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 2914 } 2915 if( pF->pFunc->needCollSeq ){ 2916 CollSeq *pColl = 0; 2917 struct ExprList_item *pItem; 2918 int j; 2919 assert( pList!=0 ); /* pList!=0 if pF->pFunc->needCollSeq is true */ 2920 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 2921 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 2922 } 2923 if( !pColl ){ 2924 pColl = pParse->db->pDfltColl; 2925 } 2926 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); 2927 } 2928 sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem, 2929 (void*)pF->pFunc, P4_FUNCDEF); 2930 sqlite3VdbeChangeP5(v, nArg); 2931 sqlite3ReleaseTempRange(pParse, regAgg, nArg); 2932 sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); 2933 if( addrNext ){ 2934 sqlite3VdbeResolveLabel(v, addrNext); 2935 } 2936 } 2937 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 2938 sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 2939 } 2940 pAggInfo->directMode = 0; 2941 } 2942 2943 #ifndef SQLITE_OMIT_TRIGGER 2944 /* 2945 ** This function is used when a SELECT statement is used to create a 2946 ** temporary table for iterating through when running an INSTEAD OF 2947 ** UPDATE or INSTEAD OF DELETE trigger. 2948 ** 2949 ** If possible, the SELECT statement is modified so that NULL values 2950 ** are stored in the temporary table for all columns for which the 2951 ** corresponding bit in argument mask is not set. If mask takes the 2952 ** special value 0xffffffff, then all columns are populated. 2953 */ 2954 void sqlite3SelectMask(Parse *pParse, Select *p, u32 mask){ 2955 if( p && !p->pPrior && !p->isDistinct && mask!=0xffffffff ){ 2956 ExprList *pEList; 2957 int i; 2958 sqlite3SelectResolve(pParse, p, 0); 2959 pEList = p->pEList; 2960 for(i=0; pEList && i<pEList->nExpr && i<32; i++){ 2961 if( !(mask&((u32)1<<i)) ){ 2962 sqlite3ExprDelete(pEList->a[i].pExpr); 2963 pEList->a[i].pExpr = sqlite3Expr(pParse->db, TK_NULL, 0, 0, 0); 2964 } 2965 } 2966 } 2967 } 2968 #endif 2969 2970 /* 2971 ** Generate code for the given SELECT statement. 2972 ** 2973 ** The results are distributed in various ways depending on the 2974 ** contents of the SelectDest structure pointed to by argument pDest 2975 ** as follows: 2976 ** 2977 ** pDest->eDest Result 2978 ** ------------ ------------------------------------------- 2979 ** SRT_Callback Invoke the callback for each row of the result. 2980 ** 2981 ** SRT_Mem Store first result in memory cell pDest->iParm 2982 ** 2983 ** SRT_Set Store non-null results as keys of table pDest->iParm. 2984 ** Apply the affinity pDest->affinity before storing them. 2985 ** 2986 ** SRT_Union Store results as a key in a temporary table pDest->iParm. 2987 ** 2988 ** SRT_Except Remove results from the temporary table pDest->iParm. 2989 ** 2990 ** SRT_Table Store results in temporary table pDest->iParm 2991 ** 2992 ** SRT_EphemTab Create an temporary table pDest->iParm and store 2993 ** the result there. The cursor is left open after 2994 ** returning. 2995 ** 2996 ** SRT_Subroutine For each row returned, push the results onto the 2997 ** vdbe stack and call the subroutine (via OP_Gosub) 2998 ** at address pDest->iParm. 2999 ** 3000 ** SRT_Exists Store a 1 in memory cell pDest->iParm if the result 3001 ** set is not empty. 3002 ** 3003 ** SRT_Discard Throw the results away. 3004 ** 3005 ** See the selectInnerLoop() function for a canonical listing of the 3006 ** allowed values of eDest and their meanings. 3007 ** 3008 ** This routine returns the number of errors. If any errors are 3009 ** encountered, then an appropriate error message is left in 3010 ** pParse->zErrMsg. 3011 ** 3012 ** This routine does NOT free the Select structure passed in. The 3013 ** calling function needs to do that. 3014 ** 3015 ** The pParent, parentTab, and *pParentAgg fields are filled in if this 3016 ** SELECT is a subquery. This routine may try to combine this SELECT 3017 ** with its parent to form a single flat query. In so doing, it might 3018 ** change the parent query from a non-aggregate to an aggregate query. 3019 ** For that reason, the pParentAgg flag is passed as a pointer, so it 3020 ** can be changed. 3021 ** 3022 ** Example 1: The meaning of the pParent parameter. 3023 ** 3024 ** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3; 3025 ** \ \_______ subquery _______/ / 3026 ** \ / 3027 ** \____________________ outer query ___________________/ 3028 ** 3029 ** This routine is called for the outer query first. For that call, 3030 ** pParent will be NULL. During the processing of the outer query, this 3031 ** routine is called recursively to handle the subquery. For the recursive 3032 ** call, pParent will point to the outer query. Because the subquery is 3033 ** the second element in a three-way join, the parentTab parameter will 3034 ** be 1 (the 2nd value of a 0-indexed array.) 3035 */ 3036 int sqlite3Select( 3037 Parse *pParse, /* The parser context */ 3038 Select *p, /* The SELECT statement being coded. */ 3039 SelectDest *pDest, /* What to do with the query results */ 3040 Select *pParent, /* Another SELECT for which this is a sub-query */ 3041 int parentTab, /* Index in pParent->pSrc of this query */ 3042 int *pParentAgg, /* True if pParent uses aggregate functions */ 3043 char *aff /* If eDest is SRT_Union, the affinity string */ 3044 ){ 3045 int i, j; /* Loop counters */ 3046 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 3047 Vdbe *v; /* The virtual machine under construction */ 3048 int isAgg; /* True for select lists like "count(*)" */ 3049 ExprList *pEList; /* List of columns to extract. */ 3050 SrcList *pTabList; /* List of tables to select from */ 3051 Expr *pWhere; /* The WHERE clause. May be NULL */ 3052 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 3053 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 3054 Expr *pHaving; /* The HAVING clause. May be NULL */ 3055 int isDistinct; /* True if the DISTINCT keyword is present */ 3056 int distinct; /* Table to use for the distinct set */ 3057 int rc = 1; /* Value to return from this function */ 3058 int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ 3059 AggInfo sAggInfo; /* Information used by aggregate queries */ 3060 int iEnd; /* Address of the end of the query */ 3061 sqlite3 *db; /* The database connection */ 3062 3063 db = pParse->db; 3064 if( p==0 || db->mallocFailed || pParse->nErr ){ 3065 return 1; 3066 } 3067 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 3068 memset(&sAggInfo, 0, sizeof(sAggInfo)); 3069 3070 pOrderBy = p->pOrderBy; 3071 if( IgnorableOrderby(pDest) ){ 3072 p->pOrderBy = 0; 3073 3074 /* In these cases the DISTINCT operator makes no difference to the 3075 ** results, so remove it if it were specified. 3076 */ 3077 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 3078 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard); 3079 p->isDistinct = 0; 3080 } 3081 if( sqlite3SelectResolve(pParse, p, 0) ){ 3082 goto select_end; 3083 } 3084 p->pOrderBy = pOrderBy; 3085 3086 #ifndef SQLITE_OMIT_COMPOUND_SELECT 3087 /* If there is are a sequence of queries, do the earlier ones first. 3088 */ 3089 if( p->pPrior ){ 3090 if( p->pRightmost==0 ){ 3091 Select *pLoop, *pRight = 0; 3092 int cnt = 0; 3093 int mxSelect; 3094 for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ 3095 pLoop->pRightmost = p; 3096 pLoop->pNext = pRight; 3097 pRight = pLoop; 3098 } 3099 mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT]; 3100 if( mxSelect && cnt>mxSelect ){ 3101 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); 3102 return 1; 3103 } 3104 } 3105 return multiSelect(pParse, p, pDest, aff); 3106 } 3107 #endif 3108 3109 /* Make local copies of the parameters for this query. 3110 */ 3111 pTabList = p->pSrc; 3112 pWhere = p->pWhere; 3113 pGroupBy = p->pGroupBy; 3114 pHaving = p->pHaving; 3115 isAgg = p->isAgg; 3116 isDistinct = p->isDistinct; 3117 pEList = p->pEList; 3118 if( pEList==0 ) goto select_end; 3119 3120 /* 3121 ** Do not even attempt to generate any code if we have already seen 3122 ** errors before this routine starts. 3123 */ 3124 if( pParse->nErr>0 ) goto select_end; 3125 3126 /* If writing to memory or generating a set 3127 ** only a single column may be output. 3128 */ 3129 #ifndef SQLITE_OMIT_SUBQUERY 3130 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ 3131 goto select_end; 3132 } 3133 #endif 3134 3135 /* ORDER BY is ignored for some destinations. 3136 */ 3137 if( IgnorableOrderby(pDest) ){ 3138 pOrderBy = 0; 3139 } 3140 3141 /* Begin generating code. 3142 */ 3143 v = sqlite3GetVdbe(pParse); 3144 if( v==0 ) goto select_end; 3145 3146 /* Generate code for all sub-queries in the FROM clause 3147 */ 3148 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3149 for(i=0; i<pTabList->nSrc; i++){ 3150 const char *zSavedAuthContext = 0; 3151 int needRestoreContext; 3152 struct SrcList_item *pItem = &pTabList->a[i]; 3153 SelectDest dest; 3154 3155 if( pItem->pSelect==0 || pItem->isPopulated ) continue; 3156 if( pItem->zName!=0 ){ 3157 zSavedAuthContext = pParse->zAuthContext; 3158 pParse->zAuthContext = pItem->zName; 3159 needRestoreContext = 1; 3160 }else{ 3161 needRestoreContext = 0; 3162 } 3163 /* Increment Parse.nHeight by the height of the largest expression 3164 ** tree refered to by this, the parent select. The child select 3165 ** may contain expression trees of at most 3166 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 3167 ** more conservative than necessary, but much easier than enforcing 3168 ** an exact limit. 3169 */ 3170 pParse->nHeight += sqlite3SelectExprHeight(p); 3171 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 3172 sqlite3Select(pParse, pItem->pSelect, &dest, p, i, &isAgg, 0); 3173 if( db->mallocFailed ){ 3174 goto select_end; 3175 } 3176 pParse->nHeight -= sqlite3SelectExprHeight(p); 3177 if( needRestoreContext ){ 3178 pParse->zAuthContext = zSavedAuthContext; 3179 } 3180 pTabList = p->pSrc; 3181 pWhere = p->pWhere; 3182 if( !IgnorableOrderby(pDest) ){ 3183 pOrderBy = p->pOrderBy; 3184 } 3185 pGroupBy = p->pGroupBy; 3186 pHaving = p->pHaving; 3187 isDistinct = p->isDistinct; 3188 } 3189 #endif 3190 3191 /* Check to see if this is a subquery that can be "flattened" into its parent. 3192 ** If flattening is a possiblity, do so and return immediately. 3193 */ 3194 #ifndef SQLITE_OMIT_VIEW 3195 if( pParent && pParentAgg && 3196 flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){ 3197 if( isAgg ) *pParentAgg = 1; 3198 goto select_end; 3199 } 3200 #endif 3201 3202 /* If possible, rewrite the query to use GROUP BY instead of DISTINCT. 3203 ** GROUP BY may use an index, DISTINCT never does. 3204 */ 3205 if( p->isDistinct && !p->isAgg && !p->pGroupBy ){ 3206 p->pGroupBy = sqlite3ExprListDup(db, p->pEList); 3207 pGroupBy = p->pGroupBy; 3208 p->isDistinct = 0; 3209 isDistinct = 0; 3210 } 3211 3212 /* If there is an ORDER BY clause, then this sorting 3213 ** index might end up being unused if the data can be 3214 ** extracted in pre-sorted order. If that is the case, then the 3215 ** OP_OpenEphemeral instruction will be changed to an OP_Noop once 3216 ** we figure out that the sorting index is not needed. The addrSortIndex 3217 ** variable is used to facilitate that change. 3218 */ 3219 if( pOrderBy ){ 3220 KeyInfo *pKeyInfo; 3221 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); 3222 pOrderBy->iECursor = pParse->nTab++; 3223 p->addrOpenEphm[2] = addrSortIndex = 3224 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 3225 pOrderBy->iECursor, pOrderBy->nExpr+2, 0, 3226 (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 3227 }else{ 3228 addrSortIndex = -1; 3229 } 3230 3231 /* If the output is destined for a temporary table, open that table. 3232 */ 3233 if( pDest->eDest==SRT_EphemTab ){ 3234 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr); 3235 } 3236 3237 /* Set the limiter. 3238 */ 3239 iEnd = sqlite3VdbeMakeLabel(v); 3240 computeLimitRegisters(pParse, p, iEnd); 3241 3242 /* Open a virtual index to use for the distinct set. 3243 */ 3244 if( isDistinct ){ 3245 KeyInfo *pKeyInfo; 3246 assert( isAgg || pGroupBy ); 3247 distinct = pParse->nTab++; 3248 pKeyInfo = keyInfoFromExprList(pParse, p->pEList); 3249 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0, 3250 (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 3251 }else{ 3252 distinct = -1; 3253 } 3254 3255 /* Aggregate and non-aggregate queries are handled differently */ 3256 if( !isAgg && pGroupBy==0 ){ 3257 /* This case is for non-aggregate queries 3258 ** Begin the database scan 3259 */ 3260 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0); 3261 if( pWInfo==0 ) goto select_end; 3262 3263 /* If sorting index that was created by a prior OP_OpenEphemeral 3264 ** instruction ended up not being needed, then change the OP_OpenEphemeral 3265 ** into an OP_Noop. 3266 */ 3267 if( addrSortIndex>=0 && pOrderBy==0 ){ 3268 sqlite3VdbeChangeToNoop(v, addrSortIndex, 1); 3269 p->addrOpenEphm[2] = -1; 3270 } 3271 3272 /* Use the standard inner loop 3273 */ 3274 assert(!isDistinct); 3275 selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest, 3276 pWInfo->iContinue, pWInfo->iBreak, aff); 3277 3278 /* End the database scan loop. 3279 */ 3280 sqlite3WhereEnd(pWInfo); 3281 }else{ 3282 /* This is the processing for aggregate queries */ 3283 NameContext sNC; /* Name context for processing aggregate information */ 3284 int iAMem; /* First Mem address for storing current GROUP BY */ 3285 int iBMem; /* First Mem address for previous GROUP BY */ 3286 int iUseFlag; /* Mem address holding flag indicating that at least 3287 ** one row of the input to the aggregator has been 3288 ** processed */ 3289 int iAbortFlag; /* Mem address which causes query abort if positive */ 3290 int groupBySort; /* Rows come from source in GROUP BY order */ 3291 3292 3293 /* The following variables hold addresses or labels for parts of the 3294 ** virtual machine program we are putting together */ 3295 int addrOutputRow; /* Start of subroutine that outputs a result row */ 3296 int addrSetAbort; /* Set the abort flag and return */ 3297 int addrInitializeLoop; /* Start of code that initializes the input loop */ 3298 int addrTopOfLoop; /* Top of the input loop */ 3299 int addrGroupByChange; /* Code that runs when any GROUP BY term changes */ 3300 int addrProcessRow; /* Code to process a single input row */ 3301 int addrEnd; /* End of all processing */ 3302 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 3303 int addrReset; /* Subroutine for resetting the accumulator */ 3304 3305 addrEnd = sqlite3VdbeMakeLabel(v); 3306 3307 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 3308 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 3309 ** SELECT statement. 3310 */ 3311 memset(&sNC, 0, sizeof(sNC)); 3312 sNC.pParse = pParse; 3313 sNC.pSrcList = pTabList; 3314 sNC.pAggInfo = &sAggInfo; 3315 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; 3316 sAggInfo.pGroupBy = pGroupBy; 3317 sqlite3ExprAnalyzeAggList(&sNC, pEList); 3318 sqlite3ExprAnalyzeAggList(&sNC, pOrderBy); 3319 if( pHaving ){ 3320 sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 3321 } 3322 sAggInfo.nAccumulator = sAggInfo.nColumn; 3323 for(i=0; i<sAggInfo.nFunc; i++){ 3324 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList); 3325 } 3326 if( db->mallocFailed ) goto select_end; 3327 3328 /* Processing for aggregates with GROUP BY is very different and 3329 ** much more complex than aggregates without a GROUP BY. 3330 */ 3331 if( pGroupBy ){ 3332 KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 3333 3334 /* Create labels that we will be needing 3335 */ 3336 3337 addrInitializeLoop = sqlite3VdbeMakeLabel(v); 3338 addrGroupByChange = sqlite3VdbeMakeLabel(v); 3339 addrProcessRow = sqlite3VdbeMakeLabel(v); 3340 3341 /* If there is a GROUP BY clause we might need a sorting index to 3342 ** implement it. Allocate that sorting index now. If it turns out 3343 ** that we do not need it after all, the OpenEphemeral instruction 3344 ** will be converted into a Noop. 3345 */ 3346 sAggInfo.sortingIdx = pParse->nTab++; 3347 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); 3348 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 3349 sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 3350 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 3351 3352 /* Initialize memory locations used by GROUP BY aggregate processing 3353 */ 3354 iUseFlag = ++pParse->nMem; 3355 iAbortFlag = ++pParse->nMem; 3356 iAMem = pParse->nMem + 1; 3357 pParse->nMem += pGroupBy->nExpr; 3358 iBMem = pParse->nMem + 1; 3359 pParse->nMem += pGroupBy->nExpr; 3360 sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 3361 VdbeComment((v, "clear abort flag")); 3362 sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 3363 VdbeComment((v, "indicate accumulator empty")); 3364 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInitializeLoop); 3365 3366 /* Generate a subroutine that outputs a single row of the result 3367 ** set. This subroutine first looks at the iUseFlag. If iUseFlag 3368 ** is less than or equal to zero, the subroutine is a no-op. If 3369 ** the processing calls for the query to abort, this subroutine 3370 ** increments the iAbortFlag memory location before returning in 3371 ** order to signal the caller to abort. 3372 */ 3373 addrSetAbort = sqlite3VdbeCurrentAddr(v); 3374 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 3375 VdbeComment((v, "set abort flag")); 3376 sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 3377 addrOutputRow = sqlite3VdbeCurrentAddr(v); 3378 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 3379 VdbeComment((v, "Groupby result generator entry point")); 3380 sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 3381 finalizeAggFunctions(pParse, &sAggInfo); 3382 if( pHaving ){ 3383 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 3384 } 3385 selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, 3386 distinct, pDest, 3387 addrOutputRow+1, addrSetAbort, aff); 3388 sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 3389 VdbeComment((v, "end groupby result generator")); 3390 3391 /* Generate a subroutine that will reset the group-by accumulator 3392 */ 3393 addrReset = sqlite3VdbeCurrentAddr(v); 3394 resetAccumulator(pParse, &sAggInfo); 3395 sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 3396 3397 /* Begin a loop that will extract all source rows in GROUP BY order. 3398 ** This might involve two separate loops with an OP_Sort in between, or 3399 ** it might be a single loop that uses an index to extract information 3400 ** in the right order to begin with. 3401 */ 3402 sqlite3VdbeResolveLabel(v, addrInitializeLoop); 3403 sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset); 3404 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0); 3405 if( pWInfo==0 ) goto select_end; 3406 if( pGroupBy==0 ){ 3407 /* The optimizer is able to deliver rows in group by order so 3408 ** we do not have to sort. The OP_OpenEphemeral table will be 3409 ** cancelled later because we still need to use the pKeyInfo 3410 */ 3411 pGroupBy = p->pGroupBy; 3412 groupBySort = 0; 3413 }else{ 3414 /* Rows are coming out in undetermined order. We have to push 3415 ** each row into a sorting index, terminate the first loop, 3416 ** then loop over the sorting index in order to get the output 3417 ** in sorted order 3418 */ 3419 int regBase; 3420 int regRecord; 3421 int nCol; 3422 int nGroupBy; 3423 3424 groupBySort = 1; 3425 nGroupBy = pGroupBy->nExpr; 3426 nCol = nGroupBy + 1; 3427 j = nGroupBy+1; 3428 for(i=0; i<sAggInfo.nColumn; i++){ 3429 if( sAggInfo.aCol[i].iSorterColumn>=j ){ 3430 nCol++; 3431 j++; 3432 } 3433 } 3434 regBase = sqlite3GetTempRange(pParse, nCol); 3435 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase); 3436 sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy); 3437 j = nGroupBy+1; 3438 for(i=0; i<sAggInfo.nColumn; i++){ 3439 struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 3440 if( pCol->iSorterColumn>=j ){ 3441 int r1 = j + regBase; 3442 int r2 = sqlite3ExprCodeGetColumn(pParse, 3443 pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0); 3444 if( r1!=r2 ){ 3445 sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1); 3446 } 3447 j++; 3448 } 3449 } 3450 regRecord = sqlite3GetTempReg(pParse); 3451 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 3452 sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord); 3453 sqlite3ReleaseTempReg(pParse, regRecord); 3454 sqlite3ReleaseTempRange(pParse, regBase, nCol); 3455 sqlite3WhereEnd(pWInfo); 3456 sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd); 3457 VdbeComment((v, "GROUP BY sort")); 3458 sAggInfo.useSortingIdx = 1; 3459 } 3460 3461 /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 3462 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 3463 ** Then compare the current GROUP BY terms against the GROUP BY terms 3464 ** from the previous row currently stored in a0, a1, a2... 3465 */ 3466 addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 3467 for(j=0; j<pGroupBy->nExpr; j++){ 3468 if( groupBySort ){ 3469 sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j); 3470 }else{ 3471 sAggInfo.directMode = 1; 3472 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 3473 } 3474 } 3475 for(j=pGroupBy->nExpr-1; j>=0; j--){ 3476 if( j==0 ){ 3477 sqlite3VdbeAddOp3(v, OP_Eq, iAMem+j, addrProcessRow, iBMem+j); 3478 }else{ 3479 sqlite3VdbeAddOp3(v, OP_Ne, iAMem+j, addrGroupByChange, iBMem+j); 3480 } 3481 sqlite3VdbeChangeP4(v, -1, (void*)pKeyInfo->aColl[j], P4_COLLSEQ); 3482 sqlite3VdbeChangeP5(v, SQLITE_NULLEQUAL); 3483 } 3484 3485 /* Generate code that runs whenever the GROUP BY changes. 3486 ** Change in the GROUP BY are detected by the previous code 3487 ** block. If there were no changes, this block is skipped. 3488 ** 3489 ** This code copies current group by terms in b0,b1,b2,... 3490 ** over to a0,a1,a2. It then calls the output subroutine 3491 ** and resets the aggregate accumulator registers in preparation 3492 ** for the next GROUP BY batch. 3493 */ 3494 sqlite3VdbeResolveLabel(v, addrGroupByChange); 3495 for(j=0; j<pGroupBy->nExpr; j++){ 3496 sqlite3ExprCodeMove(pParse, iBMem+j, iAMem+j); 3497 } 3498 sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow); 3499 VdbeComment((v, "output one row")); 3500 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); 3501 VdbeComment((v, "check abort flag")); 3502 sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset); 3503 VdbeComment((v, "reset accumulator")); 3504 3505 /* Update the aggregate accumulators based on the content of 3506 ** the current row 3507 */ 3508 sqlite3VdbeResolveLabel(v, addrProcessRow); 3509 updateAccumulator(pParse, &sAggInfo); 3510 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 3511 VdbeComment((v, "indicate data in accumulator")); 3512 3513 /* End of the loop 3514 */ 3515 if( groupBySort ){ 3516 sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop); 3517 }else{ 3518 sqlite3WhereEnd(pWInfo); 3519 sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1); 3520 } 3521 3522 /* Output the final row of result 3523 */ 3524 sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow); 3525 VdbeComment((v, "output final row")); 3526 3527 } /* endif pGroupBy */ 3528 else { 3529 ExprList *pMinMax = 0; 3530 ExprList *pDel = 0; 3531 u8 flag; 3532 3533 /* Check if the query is of one of the following forms: 3534 ** 3535 ** SELECT min(x) FROM ... 3536 ** SELECT max(x) FROM ... 3537 ** 3538 ** If it is, then ask the code in where.c to attempt to sort results 3539 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 3540 ** If where.c is able to produce results sorted in this order, then 3541 ** add vdbe code to break out of the processing loop after the 3542 ** first iteration (since the first iteration of the loop is 3543 ** guaranteed to operate on the row with the minimum or maximum 3544 ** value of x, the only row required). 3545 ** 3546 ** A special flag must be passed to sqlite3WhereBegin() to slightly 3547 ** modify behaviour as follows: 3548 ** 3549 ** + If the query is a "SELECT min(x)", then the loop coded by 3550 ** where.c should not iterate over any values with a NULL value 3551 ** for x. 3552 ** 3553 ** + The optimizer code in where.c (the thing that decides which 3554 ** index or indices to use) should place a different priority on 3555 ** satisfying the 'ORDER BY' clause than it does in other cases. 3556 ** Refer to code and comments in where.c for details. 3557 */ 3558 flag = minMaxQuery(pParse, p); 3559 if( flag ){ 3560 pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList); 3561 if( pMinMax && !db->mallocFailed ){ 3562 pMinMax->a[0].sortOrder = ((flag==WHERE_ORDERBY_MIN)?0:1); 3563 pMinMax->a[0].pExpr->op = TK_COLUMN; 3564 } 3565 } 3566 3567 /* This case runs if the aggregate has no GROUP BY clause. The 3568 ** processing is much simpler since there is only a single row 3569 ** of output. 3570 */ 3571 resetAccumulator(pParse, &sAggInfo); 3572 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag); 3573 if( pWInfo==0 ){ 3574 sqlite3ExprListDelete(pDel); 3575 goto select_end; 3576 } 3577 updateAccumulator(pParse, &sAggInfo); 3578 if( !pMinMax && flag ){ 3579 sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak); 3580 VdbeComment((v, "%s() by index", (flag==WHERE_ORDERBY_MIN?"min":"max"))); 3581 } 3582 sqlite3WhereEnd(pWInfo); 3583 finalizeAggFunctions(pParse, &sAggInfo); 3584 pOrderBy = 0; 3585 if( pHaving ){ 3586 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 3587 } 3588 selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 3589 pDest, addrEnd, addrEnd, aff); 3590 3591 sqlite3ExprListDelete(pDel); 3592 } 3593 sqlite3VdbeResolveLabel(v, addrEnd); 3594 3595 } /* endif aggregate query */ 3596 3597 /* If there is an ORDER BY clause, then we need to sort the results 3598 ** and send them to the callback one by one. 3599 */ 3600 if( pOrderBy ){ 3601 generateSortTail(pParse, p, v, pEList->nExpr, pDest); 3602 } 3603 3604 #ifndef SQLITE_OMIT_SUBQUERY 3605 /* If this was a subquery, we have now converted the subquery into a 3606 ** temporary table. So set the SrcList_item.isPopulated flag to prevent 3607 ** this subquery from being evaluated again and to force the use of 3608 ** the temporary table. 3609 */ 3610 if( pParent ){ 3611 assert( pParent->pSrc->nSrc>parentTab ); 3612 assert( pParent->pSrc->a[parentTab].pSelect==p ); 3613 pParent->pSrc->a[parentTab].isPopulated = 1; 3614 } 3615 #endif 3616 3617 /* Jump here to skip this query 3618 */ 3619 sqlite3VdbeResolveLabel(v, iEnd); 3620 3621 /* The SELECT was successfully coded. Set the return code to 0 3622 ** to indicate no errors. 3623 */ 3624 rc = 0; 3625 3626 /* Control jumps to here if an error is encountered above, or upon 3627 ** successful coding of the SELECT. 3628 */ 3629 select_end: 3630 3631 /* Identify column names if we will be using them in a callback. This 3632 ** step is skipped if the output is going to some other destination. 3633 */ 3634 if( rc==SQLITE_OK && pDest->eDest==SRT_Callback ){ 3635 generateColumnNames(pParse, pTabList, pEList); 3636 } 3637 3638 sqlite3_free(sAggInfo.aCol); 3639 sqlite3_free(sAggInfo.aFunc); 3640 return rc; 3641 } 3642 3643 #if defined(SQLITE_DEBUG) 3644 /* 3645 ******************************************************************************* 3646 ** The following code is used for testing and debugging only. The code 3647 ** that follows does not appear in normal builds. 3648 ** 3649 ** These routines are used to print out the content of all or part of a 3650 ** parse structures such as Select or Expr. Such printouts are useful 3651 ** for helping to understand what is happening inside the code generator 3652 ** during the execution of complex SELECT statements. 3653 ** 3654 ** These routine are not called anywhere from within the normal 3655 ** code base. Then are intended to be called from within the debugger 3656 ** or from temporary "printf" statements inserted for debugging. 3657 */ 3658 static void sqlite3PrintExpr(Expr *p){ 3659 if( p->token.z && p->token.n>0 ){ 3660 sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z); 3661 }else{ 3662 sqlite3DebugPrintf("(%d", p->op); 3663 } 3664 if( p->pLeft ){ 3665 sqlite3DebugPrintf(" "); 3666 sqlite3PrintExpr(p->pLeft); 3667 } 3668 if( p->pRight ){ 3669 sqlite3DebugPrintf(" "); 3670 sqlite3PrintExpr(p->pRight); 3671 } 3672 sqlite3DebugPrintf(")"); 3673 } 3674 static void sqlite3PrintExprList(ExprList *pList){ 3675 int i; 3676 for(i=0; i<pList->nExpr; i++){ 3677 sqlite3PrintExpr(pList->a[i].pExpr); 3678 if( i<pList->nExpr-1 ){ 3679 sqlite3DebugPrintf(", "); 3680 } 3681 } 3682 } 3683 static void sqlite3PrintSelect(Select *p, int indent){ 3684 sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p); 3685 sqlite3PrintExprList(p->pEList); 3686 sqlite3DebugPrintf("\n"); 3687 if( p->pSrc ){ 3688 char *zPrefix; 3689 int i; 3690 zPrefix = "FROM"; 3691 for(i=0; i<p->pSrc->nSrc; i++){ 3692 struct SrcList_item *pItem = &p->pSrc->a[i]; 3693 sqlite3DebugPrintf("%*s ", indent+6, zPrefix); 3694 zPrefix = ""; 3695 if( pItem->pSelect ){ 3696 sqlite3DebugPrintf("(\n"); 3697 sqlite3PrintSelect(pItem->pSelect, indent+10); 3698 sqlite3DebugPrintf("%*s)", indent+8, ""); 3699 }else if( pItem->zName ){ 3700 sqlite3DebugPrintf("%s", pItem->zName); 3701 } 3702 if( pItem->pTab ){ 3703 sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName); 3704 } 3705 if( pItem->zAlias ){ 3706 sqlite3DebugPrintf(" AS %s", pItem->zAlias); 3707 } 3708 if( i<p->pSrc->nSrc-1 ){ 3709 sqlite3DebugPrintf(","); 3710 } 3711 sqlite3DebugPrintf("\n"); 3712 } 3713 } 3714 if( p->pWhere ){ 3715 sqlite3DebugPrintf("%*s WHERE ", indent, ""); 3716 sqlite3PrintExpr(p->pWhere); 3717 sqlite3DebugPrintf("\n"); 3718 } 3719 if( p->pGroupBy ){ 3720 sqlite3DebugPrintf("%*s GROUP BY ", indent, ""); 3721 sqlite3PrintExprList(p->pGroupBy); 3722 sqlite3DebugPrintf("\n"); 3723 } 3724 if( p->pHaving ){ 3725 sqlite3DebugPrintf("%*s HAVING ", indent, ""); 3726 sqlite3PrintExpr(p->pHaving); 3727 sqlite3DebugPrintf("\n"); 3728 } 3729 if( p->pOrderBy ){ 3730 sqlite3DebugPrintf("%*s ORDER BY ", indent, ""); 3731 sqlite3PrintExprList(p->pOrderBy); 3732 sqlite3DebugPrintf("\n"); 3733 } 3734 } 3735 /* End of the structure debug printing code 3736 *****************************************************************************/ 3737 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ 3738