ds@1952: /* ds@1952: ** 2001 September 15 ds@1952: ** ds@1952: ** The author disclaims copyright to this source code. In place of ds@1952: ** a legal notice, here is a blessing: ds@1952: ** ds@1952: ** May you do good and not evil. ds@1952: ** May you find forgiveness for yourself and forgive others. ds@1952: ** May you share freely, never taking more than you give. ds@1952: ** ds@1952: ************************************************************************* ds@1952: ** This file contains C code routines that are called by the parser ds@1952: ** to handle SELECT statements in SQLite. ds@1952: ** ds@1952: ** $Id$ ds@1952: */ ds@1952: #include "sqliteInt.h" ds@1952: ds@1952: ds@1952: /* ds@1952: ** Delete all the content of a Select structure but do not deallocate ds@1952: ** the select structure itself. ds@1952: */ ds@1952: static void clearSelect(Select *p){ ds@1952: sqlite3ExprListDelete(p->pEList); ds@1952: sqlite3SrcListDelete(p->pSrc); ds@1952: sqlite3ExprDelete(p->pWhere); ds@1952: sqlite3ExprListDelete(p->pGroupBy); ds@1952: sqlite3ExprDelete(p->pHaving); ds@1952: sqlite3ExprListDelete(p->pOrderBy); ds@1952: sqlite3SelectDelete(p->pPrior); ds@1952: sqlite3ExprDelete(p->pLimit); ds@1952: sqlite3ExprDelete(p->pOffset); ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Allocate a new Select structure and return a pointer to that ds@1952: ** structure. ds@1952: */ ds@1952: Select *sqlite3SelectNew( ds@1952: Parse *pParse, /* Parsing context */ ds@1952: ExprList *pEList, /* which columns to include in the result */ ds@1952: SrcList *pSrc, /* the FROM clause -- which tables to scan */ ds@1952: Expr *pWhere, /* the WHERE clause */ ds@1952: ExprList *pGroupBy, /* the GROUP BY clause */ ds@1952: Expr *pHaving, /* the HAVING clause */ ds@1952: ExprList *pOrderBy, /* the ORDER BY clause */ ds@1952: int isDistinct, /* true if the DISTINCT keyword is present */ ds@1952: Expr *pLimit, /* LIMIT value. NULL means not used */ ds@1952: Expr *pOffset /* OFFSET value. NULL means no offset */ ds@1952: ){ ds@1952: Select *pNew; ds@1952: Select standin; ds@1952: sqlite3 *db = pParse->db; ds@1952: pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); ds@1952: assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */ ds@1952: if( pNew==0 ){ ds@1952: pNew = &standin; ds@1952: memset(pNew, 0, sizeof(*pNew)); ds@1952: } ds@1952: if( pEList==0 ){ ds@1952: pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0); ds@1952: } ds@1952: pNew->pEList = pEList; ds@1952: pNew->pSrc = pSrc; ds@1952: pNew->pWhere = pWhere; ds@1952: pNew->pGroupBy = pGroupBy; ds@1952: pNew->pHaving = pHaving; ds@1952: pNew->pOrderBy = pOrderBy; ds@1952: pNew->isDistinct = isDistinct; ds@1952: pNew->op = TK_SELECT; ds@1952: assert( pOffset==0 || pLimit!=0 ); ds@1952: pNew->pLimit = pLimit; ds@1952: pNew->pOffset = pOffset; ds@1952: pNew->iLimit = -1; ds@1952: pNew->iOffset = -1; ds@1952: pNew->addrOpenEphm[0] = -1; ds@1952: pNew->addrOpenEphm[1] = -1; ds@1952: pNew->addrOpenEphm[2] = -1; ds@1952: if( pNew==&standin) { ds@1952: clearSelect(pNew); ds@1952: pNew = 0; ds@1952: } ds@1952: return pNew; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Delete the given Select structure and all of its substructures. ds@1952: */ ds@1952: void sqlite3SelectDelete(Select *p){ ds@1952: if( p ){ ds@1952: clearSelect(p); ds@1952: sqlite3_free(p); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the ds@1952: ** type of join. Return an integer constant that expresses that type ds@1952: ** in terms of the following bit values: ds@1952: ** ds@1952: ** JT_INNER ds@1952: ** JT_CROSS ds@1952: ** JT_OUTER ds@1952: ** JT_NATURAL ds@1952: ** JT_LEFT ds@1952: ** JT_RIGHT ds@1952: ** ds@1952: ** A full outer join is the combination of JT_LEFT and JT_RIGHT. ds@1952: ** ds@1952: ** If an illegal or unsupported join type is seen, then still return ds@1952: ** a join type, but put an error in the pParse structure. ds@1952: */ ds@1952: int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ ds@1952: int jointype = 0; ds@1952: Token *apAll[3]; ds@1952: Token *p; ds@1952: static const struct { ds@1952: const char zKeyword[8]; ds@1952: u8 nChar; ds@1952: u8 code; ds@1952: } keywords[] = { ds@1952: { "natural", 7, JT_NATURAL }, ds@1952: { "left", 4, JT_LEFT|JT_OUTER }, ds@1952: { "right", 5, JT_RIGHT|JT_OUTER }, ds@1952: { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER }, ds@1952: { "outer", 5, JT_OUTER }, ds@1952: { "inner", 5, JT_INNER }, ds@1952: { "cross", 5, JT_INNER|JT_CROSS }, ds@1952: }; ds@1952: int i, j; ds@1952: apAll[0] = pA; ds@1952: apAll[1] = pB; ds@1952: apAll[2] = pC; ds@1952: for(i=0; i<3 && apAll[i]; i++){ ds@1952: p = apAll[i]; ds@1952: for(j=0; jn==keywords[j].nChar ds@1952: && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){ ds@1952: jointype |= keywords[j].code; ds@1952: break; ds@1952: } ds@1952: } ds@1952: if( j>=sizeof(keywords)/sizeof(keywords[0]) ){ ds@1952: jointype |= JT_ERROR; ds@1952: break; ds@1952: } ds@1952: } ds@1952: if( ds@1952: (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || ds@1952: (jointype & JT_ERROR)!=0 ds@1952: ){ ds@1952: const char *zSp1 = " "; ds@1952: const char *zSp2 = " "; ds@1952: if( pB==0 ){ zSp1++; } ds@1952: if( pC==0 ){ zSp2++; } ds@1952: sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " ds@1952: "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC); ds@1952: jointype = JT_INNER; ds@1952: }else if( jointype & JT_RIGHT ){ ds@1952: sqlite3ErrorMsg(pParse, ds@1952: "RIGHT and FULL OUTER JOINs are not currently supported"); ds@1952: jointype = JT_INNER; ds@1952: } ds@1952: return jointype; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return the index of a column in a table. Return -1 if the column ds@1952: ** is not contained in the table. ds@1952: */ ds@1952: static int columnIndex(Table *pTab, const char *zCol){ ds@1952: int i; ds@1952: for(i=0; inCol; i++){ ds@1952: if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; ds@1952: } ds@1952: return -1; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Set the value of a token to a '\000'-terminated string. ds@1952: */ ds@1952: static void setToken(Token *p, const char *z){ ds@1952: p->z = (u8*)z; ds@1952: p->n = z ? strlen(z) : 0; ds@1952: p->dyn = 0; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Set the token to the double-quoted and escaped version of the string pointed ds@1952: ** to by z. For example; ds@1952: ** ds@1952: ** {a"bc} -> {"a""bc"} ds@1952: */ ds@1952: static void setQuotedToken(Parse *pParse, Token *p, const char *z){ ds@1952: p->z = (u8 *)sqlite3MPrintf(0, "\"%w\"", z); ds@1952: p->dyn = 1; ds@1952: if( p->z ){ ds@1952: p->n = strlen((char *)p->z); ds@1952: }else{ ds@1952: pParse->db->mallocFailed = 1; ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Create an expression node for an identifier with the name of zName ds@1952: */ ds@1952: Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){ ds@1952: Token dummy; ds@1952: setToken(&dummy, zName); ds@1952: return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy); ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Add a term to the WHERE expression in *ppExpr that requires the ds@1952: ** zCol column to be equal in the two tables pTab1 and pTab2. ds@1952: */ ds@1952: static void addWhereTerm( ds@1952: Parse *pParse, /* Parsing context */ ds@1952: const char *zCol, /* Name of the column */ ds@1952: const Table *pTab1, /* First table */ ds@1952: const char *zAlias1, /* Alias for first table. May be NULL */ ds@1952: const Table *pTab2, /* Second table */ ds@1952: const char *zAlias2, /* Alias for second table. May be NULL */ ds@1952: int iRightJoinTable, /* VDBE cursor for the right table */ ds@1952: Expr **ppExpr /* Add the equality term to this expression */ ds@1952: ){ ds@1952: Expr *pE1a, *pE1b, *pE1c; ds@1952: Expr *pE2a, *pE2b, *pE2c; ds@1952: Expr *pE; ds@1952: ds@1952: pE1a = sqlite3CreateIdExpr(pParse, zCol); ds@1952: pE2a = sqlite3CreateIdExpr(pParse, zCol); ds@1952: if( zAlias1==0 ){ ds@1952: zAlias1 = pTab1->zName; ds@1952: } ds@1952: pE1b = sqlite3CreateIdExpr(pParse, zAlias1); ds@1952: if( zAlias2==0 ){ ds@1952: zAlias2 = pTab2->zName; ds@1952: } ds@1952: pE2b = sqlite3CreateIdExpr(pParse, zAlias2); ds@1952: pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0); ds@1952: pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0); ds@1952: pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0); ds@1952: if( pE ){ ds@1952: ExprSetProperty(pE, EP_FromJoin); ds@1952: pE->iRightJoinTable = iRightJoinTable; ds@1952: } ds@1952: pE = sqlite3ExprAnd(pParse->db,*ppExpr, pE); ds@1952: if( pE ){ ds@1952: *ppExpr = pE; ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Set the EP_FromJoin property on all terms of the given expression. ds@1952: ** And set the Expr.iRightJoinTable to iTable for every term in the ds@1952: ** expression. ds@1952: ** ds@1952: ** The EP_FromJoin property is used on terms of an expression to tell ds@1952: ** the LEFT OUTER JOIN processing logic that this term is part of the ds@1952: ** join restriction specified in the ON or USING clause and not a part ds@1952: ** of the more general WHERE clause. These terms are moved over to the ds@1952: ** WHERE clause during join processing but we need to remember that they ds@1952: ** originated in the ON or USING clause. ds@1952: ** ds@1952: ** The Expr.iRightJoinTable tells the WHERE clause processing that the ds@1952: ** expression depends on table iRightJoinTable even if that table is not ds@1952: ** explicitly mentioned in the expression. That information is needed ds@1952: ** for cases like this: ds@1952: ** ds@1952: ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 ds@1952: ** ds@1952: ** The where clause needs to defer the handling of the t1.x=5 ds@1952: ** term until after the t2 loop of the join. In that way, a ds@1952: ** NULL t2 row will be inserted whenever t1.x!=5. If we do not ds@1952: ** defer the handling of t1.x=5, it will be processed immediately ds@1952: ** after the t1 loop and rows with t1.x!=5 will never appear in ds@1952: ** the output, which is incorrect. ds@1952: */ ds@1952: static void setJoinExpr(Expr *p, int iTable){ ds@1952: while( p ){ ds@1952: ExprSetProperty(p, EP_FromJoin); ds@1952: p->iRightJoinTable = iTable; ds@1952: setJoinExpr(p->pLeft, iTable); ds@1952: p = p->pRight; ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine processes the join information for a SELECT statement. ds@1952: ** ON and USING clauses are converted into extra terms of the WHERE clause. ds@1952: ** NATURAL joins also create extra WHERE clause terms. ds@1952: ** ds@1952: ** The terms of a FROM clause are contained in the Select.pSrc structure. ds@1952: ** The left most table is the first entry in Select.pSrc. The right-most ds@1952: ** table is the last entry. The join operator is held in the entry to ds@1952: ** the left. Thus entry 0 contains the join operator for the join between ds@1952: ** entries 0 and 1. Any ON or USING clauses associated with the join are ds@1952: ** also attached to the left entry. ds@1952: ** ds@1952: ** This routine returns the number of errors encountered. ds@1952: */ ds@1952: static int sqliteProcessJoin(Parse *pParse, Select *p){ ds@1952: SrcList *pSrc; /* All tables in the FROM clause */ ds@1952: int i, j; /* Loop counters */ ds@1952: struct SrcList_item *pLeft; /* Left table being joined */ ds@1952: struct SrcList_item *pRight; /* Right table being joined */ ds@1952: ds@1952: pSrc = p->pSrc; ds@1952: pLeft = &pSrc->a[0]; ds@1952: pRight = &pLeft[1]; ds@1952: for(i=0; inSrc-1; i++, pRight++, pLeft++){ ds@1952: Table *pLeftTab = pLeft->pTab; ds@1952: Table *pRightTab = pRight->pTab; ds@1952: ds@1952: if( pLeftTab==0 || pRightTab==0 ) continue; ds@1952: ds@1952: /* When the NATURAL keyword is present, add WHERE clause terms for ds@1952: ** every column that the two tables have in common. ds@1952: */ ds@1952: if( pRight->jointype & JT_NATURAL ){ ds@1952: if( pRight->pOn || pRight->pUsing ){ ds@1952: sqlite3ErrorMsg(pParse, "a NATURAL join may not have " ds@1952: "an ON or USING clause", 0); ds@1952: return 1; ds@1952: } ds@1952: for(j=0; jnCol; j++){ ds@1952: char *zName = pLeftTab->aCol[j].zName; ds@1952: if( columnIndex(pRightTab, zName)>=0 ){ ds@1952: addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, ds@1952: pRightTab, pRight->zAlias, ds@1952: pRight->iCursor, &p->pWhere); ds@1952: ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: /* Disallow both ON and USING clauses in the same join ds@1952: */ ds@1952: if( pRight->pOn && pRight->pUsing ){ ds@1952: sqlite3ErrorMsg(pParse, "cannot have both ON and USING " ds@1952: "clauses in the same join"); ds@1952: return 1; ds@1952: } ds@1952: ds@1952: /* Add the ON clause to the end of the WHERE clause, connected by ds@1952: ** an AND operator. ds@1952: */ ds@1952: if( pRight->pOn ){ ds@1952: setJoinExpr(pRight->pOn, pRight->iCursor); ds@1952: p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); ds@1952: pRight->pOn = 0; ds@1952: } ds@1952: ds@1952: /* Create extra terms on the WHERE clause for each column named ds@1952: ** in the USING clause. Example: If the two tables to be joined are ds@1952: ** A and B and the USING clause names X, Y, and Z, then add this ds@1952: ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z ds@1952: ** Report an error if any column mentioned in the USING clause is ds@1952: ** not contained in both tables to be joined. ds@1952: */ ds@1952: if( pRight->pUsing ){ ds@1952: IdList *pList = pRight->pUsing; ds@1952: for(j=0; jnId; j++){ ds@1952: char *zName = pList->a[j].zName; ds@1952: if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){ ds@1952: sqlite3ErrorMsg(pParse, "cannot join using column %s - column " ds@1952: "not present in both tables", zName); ds@1952: return 1; ds@1952: } ds@1952: addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, ds@1952: pRightTab, pRight->zAlias, ds@1952: pRight->iCursor, &p->pWhere); ds@1952: } ds@1952: } ds@1952: } ds@1952: return 0; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Insert code into "v" that will push the record on the top of the ds@1952: ** stack into the sorter. ds@1952: */ ds@1952: static void pushOntoSorter( ds@1952: Parse *pParse, /* Parser context */ ds@1952: ExprList *pOrderBy, /* The ORDER BY clause */ ds@1952: Select *pSelect /* The whole SELECT statement */ ds@1952: ){ ds@1952: Vdbe *v = pParse->pVdbe; ds@1952: sqlite3ExprCodeExprList(pParse, pOrderBy); ds@1952: sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0); ds@1952: sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0); ds@1952: sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0); ds@1952: if( pSelect->iLimit>=0 ){ ds@1952: int addr1, addr2; ds@1952: addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0); ds@1952: sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1); ds@1952: addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); ds@1952: sqlite3VdbeJumpHere(v, addr1); ds@1952: sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Delete, pOrderBy->iECursor, 0); ds@1952: sqlite3VdbeJumpHere(v, addr2); ds@1952: pSelect->iLimit = -1; ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Add code to implement the OFFSET ds@1952: */ ds@1952: static void codeOffset( ds@1952: Vdbe *v, /* Generate code into this VM */ ds@1952: Select *p, /* The SELECT statement being coded */ ds@1952: int iContinue, /* Jump here to skip the current record */ ds@1952: int nPop /* Number of times to pop stack when jumping */ ds@1952: ){ ds@1952: if( p->iOffset>=0 && iContinue!=0 ){ ds@1952: int addr; ds@1952: sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iOffset); ds@1952: addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, 0); ds@1952: if( nPop>0 ){ ds@1952: sqlite3VdbeAddOp(v, OP_Pop, nPop, 0); ds@1952: } ds@1952: sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue); ds@1952: VdbeComment((v, "# skip OFFSET records")); ds@1952: sqlite3VdbeJumpHere(v, addr); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Add code that will check to make sure the top N elements of the ds@1952: ** stack are distinct. iTab is a sorting index that holds previously ds@1952: ** seen combinations of the N values. A new entry is made in iTab ds@1952: ** if the current N values are new. ds@1952: ** ds@1952: ** A jump to addrRepeat is made and the N+1 values are popped from the ds@1952: ** stack if the top N elements are not distinct. ds@1952: */ ds@1952: static void codeDistinct( ds@1952: Vdbe *v, /* Generate code into this VM */ ds@1952: int iTab, /* A sorting index used to test for distinctness */ ds@1952: int addrRepeat, /* Jump to here if not distinct */ ds@1952: int N /* The top N elements of the stack must be distinct */ ds@1952: ){ ds@1952: sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3); ds@1952: sqlite3VdbeAddOp(v, OP_Pop, N+1, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat); ds@1952: VdbeComment((v, "# skip indistinct records")); ds@1952: sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Generate an error message when a SELECT is used within a subexpression ds@1952: ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result ds@1952: ** column. We do this in a subroutine because the error occurs in multiple ds@1952: ** places. ds@1952: */ ds@1952: static int checkForMultiColumnSelectError(Parse *pParse, int eDest, int nExpr){ ds@1952: if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){ ds@1952: sqlite3ErrorMsg(pParse, "only a single result allowed for " ds@1952: "a SELECT that is part of an expression"); ds@1952: return 1; ds@1952: }else{ ds@1952: return 0; ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine generates the code for the inside of the inner loop ds@1952: ** of a SELECT. ds@1952: ** ds@1952: ** If srcTab and nColumn are both zero, then the pEList expressions ds@1952: ** are evaluated in order to get the data for this row. If nColumn>0 ds@1952: ** then data is pulled from srcTab and pEList is used only to get the ds@1952: ** datatypes for each column. ds@1952: */ ds@1952: static int selectInnerLoop( ds@1952: Parse *pParse, /* The parser context */ ds@1952: Select *p, /* The complete select statement being coded */ ds@1952: ExprList *pEList, /* List of values being extracted */ ds@1952: int srcTab, /* Pull data from this table */ ds@1952: int nColumn, /* Number of columns in the source table */ ds@1952: ExprList *pOrderBy, /* If not NULL, sort results using this key */ ds@1952: int distinct, /* If >=0, make sure results are distinct */ ds@1952: int eDest, /* How to dispose of the results */ ds@1952: int iParm, /* An argument to the disposal method */ ds@1952: int iContinue, /* Jump here to continue with next row */ ds@1952: int iBreak, /* Jump here to break out of the inner loop */ ds@1952: char *aff /* affinity string if eDest is SRT_Union */ ds@1952: ){ ds@1952: Vdbe *v = pParse->pVdbe; ds@1952: int i; ds@1952: int hasDistinct; /* True if the DISTINCT keyword is present */ ds@1952: ds@1952: if( v==0 ) return 0; ds@1952: assert( pEList!=0 ); ds@1952: ds@1952: /* If there was a LIMIT clause on the SELECT statement, then do the check ds@1952: ** to see if this row should be output. ds@1952: */ ds@1952: hasDistinct = distinct>=0 && pEList->nExpr>0; ds@1952: if( pOrderBy==0 && !hasDistinct ){ ds@1952: codeOffset(v, p, iContinue, 0); ds@1952: } ds@1952: ds@1952: /* Pull the requested columns. ds@1952: */ ds@1952: if( nColumn>0 ){ ds@1952: for(i=0; inExpr; ds@1952: sqlite3ExprCodeExprList(pParse, pEList); ds@1952: } ds@1952: ds@1952: /* If the DISTINCT keyword was present on the SELECT statement ds@1952: ** and this row has been seen before, then do not make this row ds@1952: ** part of the result. ds@1952: */ ds@1952: if( hasDistinct ){ ds@1952: assert( pEList!=0 ); ds@1952: assert( pEList->nExpr==nColumn ); ds@1952: codeDistinct(v, distinct, iContinue, nColumn); ds@1952: if( pOrderBy==0 ){ ds@1952: codeOffset(v, p, iContinue, nColumn); ds@1952: } ds@1952: } ds@1952: ds@1952: if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){ ds@1952: return 0; ds@1952: } ds@1952: ds@1952: switch( eDest ){ ds@1952: /* In this mode, write each query result to the key of the temporary ds@1952: ** table iParm. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_COMPOUND_SELECT ds@1952: case SRT_Union: { ds@1952: sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); ds@1952: if( aff ){ ds@1952: sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); ds@1952: } ds@1952: sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0); ds@1952: break; ds@1952: } ds@1952: ds@1952: /* Construct a record from the query result, but instead of ds@1952: ** saving that record, use it as a key to delete elements from ds@1952: ** the temporary table iParm. ds@1952: */ ds@1952: case SRT_Except: { ds@1952: int addr; ds@1952: addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); ds@1952: sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); ds@1952: sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3); ds@1952: sqlite3VdbeAddOp(v, OP_Delete, iParm, 0); ds@1952: break; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Store the result as data using a unique key. ds@1952: */ ds@1952: case SRT_Table: ds@1952: case SRT_EphemTab: { ds@1952: sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); ds@1952: if( pOrderBy ){ ds@1952: pushOntoSorter(pParse, pOrderBy, p); ds@1952: }else{ ds@1952: sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Pull, 1, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND); ds@1952: } ds@1952: break; ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_SUBQUERY ds@1952: /* If we are creating a set for an "expr IN (SELECT ...)" construct, ds@1952: ** then there should be a single item on the stack. Write this ds@1952: ** item into the set table with bogus data. ds@1952: */ ds@1952: case SRT_Set: { ds@1952: int addr1 = sqlite3VdbeCurrentAddr(v); ds@1952: int addr2; ds@1952: ds@1952: assert( nColumn==1 ); ds@1952: sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3); ds@1952: sqlite3VdbeAddOp(v, OP_Pop, 1, 0); ds@1952: addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); ds@1952: p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr,(iParm>>16)&0xff); ds@1952: if( pOrderBy ){ ds@1952: /* At first glance you would think we could optimize out the ds@1952: ** ORDER BY in this case since the order of entries in the set ds@1952: ** does not matter. But there might be a LIMIT clause, in which ds@1952: ** case the order does matter */ ds@1952: pushOntoSorter(pParse, pOrderBy, p); ds@1952: }else{ ds@1952: sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1); ds@1952: sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0); ds@1952: } ds@1952: sqlite3VdbeJumpHere(v, addr2); ds@1952: break; ds@1952: } ds@1952: ds@1952: /* If any row exist in the result set, record that fact and abort. ds@1952: */ ds@1952: case SRT_Exists: { ds@1952: sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm); ds@1952: sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); ds@1952: /* The LIMIT clause will terminate the loop for us */ ds@1952: break; ds@1952: } ds@1952: ds@1952: /* If this is a scalar select that is part of an expression, then ds@1952: ** store the results in the appropriate memory cell and break out ds@1952: ** of the scan loop. ds@1952: */ ds@1952: case SRT_Mem: { ds@1952: assert( nColumn==1 ); ds@1952: if( pOrderBy ){ ds@1952: pushOntoSorter(pParse, pOrderBy, p); ds@1952: }else{ ds@1952: sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); ds@1952: /* The LIMIT clause will jump out of the loop for us */ ds@1952: } ds@1952: break; ds@1952: } ds@1952: #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ ds@1952: ds@1952: /* Send the data to the callback function or to a subroutine. In the ds@1952: ** case of a subroutine, the subroutine itself is responsible for ds@1952: ** popping the data from the stack. ds@1952: */ ds@1952: case SRT_Subroutine: ds@1952: case SRT_Callback: { ds@1952: if( pOrderBy ){ ds@1952: sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); ds@1952: pushOntoSorter(pParse, pOrderBy, p); ds@1952: }else if( eDest==SRT_Subroutine ){ ds@1952: sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); ds@1952: }else{ ds@1952: sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); ds@1952: } ds@1952: break; ds@1952: } ds@1952: ds@1952: #if !defined(SQLITE_OMIT_TRIGGER) ds@1952: /* Discard the results. This is used for SELECT statements inside ds@1952: ** the body of a TRIGGER. The purpose of such selects is to call ds@1952: ** user-defined functions that have side effects. We do not care ds@1952: ** about the actual results of the select. ds@1952: */ ds@1952: default: { ds@1952: assert( eDest==SRT_Discard ); ds@1952: sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); ds@1952: break; ds@1952: } ds@1952: #endif ds@1952: } ds@1952: ds@1952: /* Jump to the end of the loop if the LIMIT is reached. ds@1952: */ ds@1952: if( p->iLimit>=0 && pOrderBy==0 ){ ds@1952: sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit); ds@1952: sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak); ds@1952: } ds@1952: return 0; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Given an expression list, generate a KeyInfo structure that records ds@1952: ** the collating sequence for each expression in that expression list. ds@1952: ** ds@1952: ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting ds@1952: ** KeyInfo structure is appropriate for initializing a virtual index to ds@1952: ** implement that clause. If the ExprList is the result set of a SELECT ds@1952: ** then the KeyInfo structure is appropriate for initializing a virtual ds@1952: ** index to implement a DISTINCT test. ds@1952: ** ds@1952: ** Space to hold the KeyInfo structure is obtain from malloc. The calling ds@1952: ** function is responsible for seeing that this structure is eventually ds@1952: ** freed. Add the KeyInfo structure to the P3 field of an opcode using ds@1952: ** P3_KEYINFO_HANDOFF is the usual way of dealing with this. ds@1952: */ ds@1952: static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ ds@1952: sqlite3 *db = pParse->db; ds@1952: int nExpr; ds@1952: KeyInfo *pInfo; ds@1952: struct ExprList_item *pItem; ds@1952: int i; ds@1952: ds@1952: nExpr = pList->nExpr; ds@1952: pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) ); ds@1952: if( pInfo ){ ds@1952: pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr]; ds@1952: pInfo->nField = nExpr; ds@1952: pInfo->enc = ENC(db); ds@1952: for(i=0, pItem=pList->a; ipExpr); ds@1952: if( !pColl ){ ds@1952: pColl = db->pDfltColl; ds@1952: } ds@1952: pInfo->aColl[i] = pColl; ds@1952: pInfo->aSortOrder[i] = pItem->sortOrder; ds@1952: } ds@1952: } ds@1952: return pInfo; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** If the inner loop was generated using a non-null pOrderBy argument, ds@1952: ** then the results were placed in a sorter. After the loop is terminated ds@1952: ** we need to run the sorter and output the results. The following ds@1952: ** routine generates the code needed to do that. ds@1952: */ ds@1952: static void generateSortTail( ds@1952: Parse *pParse, /* Parsing context */ ds@1952: Select *p, /* The SELECT statement */ ds@1952: Vdbe *v, /* Generate code into this VDBE */ ds@1952: int nColumn, /* Number of columns of data */ ds@1952: int eDest, /* Write the sorted results here */ ds@1952: int iParm /* Optional parameter associated with eDest */ ds@1952: ){ ds@1952: int brk = sqlite3VdbeMakeLabel(v); ds@1952: int cont = sqlite3VdbeMakeLabel(v); ds@1952: int addr; ds@1952: int iTab; ds@1952: int pseudoTab = 0; ds@1952: ExprList *pOrderBy = p->pOrderBy; ds@1952: ds@1952: iTab = pOrderBy->iECursor; ds@1952: if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ ds@1952: pseudoTab = pParse->nTab++; ds@1952: sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0); ds@1952: sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn); ds@1952: } ds@1952: addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk); ds@1952: codeOffset(v, p, cont, 0); ds@1952: if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ ds@1952: sqlite3VdbeAddOp(v, OP_Integer, 1, 0); ds@1952: } ds@1952: sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1); ds@1952: switch( eDest ){ ds@1952: case SRT_Table: ds@1952: case SRT_EphemTab: { ds@1952: sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Pull, 1, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND); ds@1952: break; ds@1952: } ds@1952: #ifndef SQLITE_OMIT_SUBQUERY ds@1952: case SRT_Set: { ds@1952: assert( nColumn==1 ); ds@1952: sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3); ds@1952: sqlite3VdbeAddOp(v, OP_Pop, 1, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3); ds@1952: sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1); ds@1952: sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0); ds@1952: break; ds@1952: } ds@1952: case SRT_Mem: { ds@1952: assert( nColumn==1 ); ds@1952: sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); ds@1952: /* The LIMIT clause will terminate the loop for us */ ds@1952: break; ds@1952: } ds@1952: #endif ds@1952: case SRT_Callback: ds@1952: case SRT_Subroutine: { ds@1952: int i; ds@1952: sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0); ds@1952: for(i=0; iiLimit>=0 ){ ds@1952: sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit); ds@1952: sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk); ds@1952: } ds@1952: ds@1952: /* The bottom of the loop ds@1952: */ ds@1952: sqlite3VdbeResolveLabel(v, cont); ds@1952: sqlite3VdbeAddOp(v, OP_Next, iTab, addr); ds@1952: sqlite3VdbeResolveLabel(v, brk); ds@1952: if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ ds@1952: sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0); ds@1952: } ds@1952: ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return a pointer to a string containing the 'declaration type' of the ds@1952: ** expression pExpr. The string may be treated as static by the caller. ds@1952: ** ds@1952: ** The declaration type is the exact datatype definition extracted from the ds@1952: ** original CREATE TABLE statement if the expression is a column. The ds@1952: ** declaration type for a ROWID field is INTEGER. Exactly when an expression ds@1952: ** is considered a column can be complex in the presence of subqueries. The ds@1952: ** result-set expression in all of the following SELECT statements is ds@1952: ** considered a column by this function. ds@1952: ** ds@1952: ** SELECT col FROM tbl; ds@1952: ** SELECT (SELECT col FROM tbl; ds@1952: ** SELECT (SELECT col FROM tbl); ds@1952: ** SELECT abc FROM (SELECT col AS abc FROM tbl); ds@1952: ** ds@1952: ** The declaration type for any expression other than a column is NULL. ds@1952: */ ds@1952: static const char *columnType( ds@1952: NameContext *pNC, ds@1952: Expr *pExpr, ds@1952: const char **pzOriginDb, ds@1952: const char **pzOriginTab, ds@1952: const char **pzOriginCol ds@1952: ){ ds@1952: char const *zType = 0; ds@1952: char const *zOriginDb = 0; ds@1952: char const *zOriginTab = 0; ds@1952: char const *zOriginCol = 0; ds@1952: int j; ds@1952: if( pExpr==0 || pNC->pSrcList==0 ) return 0; ds@1952: ds@1952: switch( pExpr->op ){ ds@1952: case TK_AGG_COLUMN: ds@1952: case TK_COLUMN: { ds@1952: /* The expression is a column. Locate the table the column is being ds@1952: ** extracted from in NameContext.pSrcList. This table may be real ds@1952: ** database table or a subquery. ds@1952: */ ds@1952: Table *pTab = 0; /* Table structure column is extracted from */ ds@1952: Select *pS = 0; /* Select the column is extracted from */ ds@1952: int iCol = pExpr->iColumn; /* Index of column in pTab */ ds@1952: while( pNC && !pTab ){ ds@1952: SrcList *pTabList = pNC->pSrcList; ds@1952: for(j=0;jnSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); ds@1952: if( jnSrc ){ ds@1952: pTab = pTabList->a[j].pTab; ds@1952: pS = pTabList->a[j].pSelect; ds@1952: }else{ ds@1952: pNC = pNC->pNext; ds@1952: } ds@1952: } ds@1952: ds@1952: if( pTab==0 ){ ds@1952: /* FIX ME: ds@1952: ** This can occurs if you have something like "SELECT new.x;" inside ds@1952: ** a trigger. In other words, if you reference the special "new" ds@1952: ** table in the result set of a select. We do not have a good way ds@1952: ** to find the actual table type, so call it "TEXT". This is really ds@1952: ** something of a bug, but I do not know how to fix it. ds@1952: ** ds@1952: ** This code does not produce the correct answer - it just prevents ds@1952: ** a segfault. See ticket #1229. ds@1952: */ ds@1952: zType = "TEXT"; ds@1952: break; ds@1952: } ds@1952: ds@1952: assert( pTab ); ds@1952: if( pS ){ ds@1952: /* The "table" is actually a sub-select or a view in the FROM clause ds@1952: ** of the SELECT statement. Return the declaration type and origin ds@1952: ** data for the result-set column of the sub-select. ds@1952: */ ds@1952: if( iCol>=0 && iColpEList->nExpr ){ ds@1952: /* If iCol is less than zero, then the expression requests the ds@1952: ** rowid of the sub-select or view. This expression is legal (see ds@1952: ** test case misc2.2.2) - it always evaluates to NULL. ds@1952: */ ds@1952: NameContext sNC; ds@1952: Expr *p = pS->pEList->a[iCol].pExpr; ds@1952: sNC.pSrcList = pS->pSrc; ds@1952: sNC.pNext = 0; ds@1952: sNC.pParse = pNC->pParse; ds@1952: zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); ds@1952: } ds@1952: }else if( pTab->pSchema ){ ds@1952: /* A real table */ ds@1952: assert( !pS ); ds@1952: if( iCol<0 ) iCol = pTab->iPKey; ds@1952: assert( iCol==-1 || (iCol>=0 && iColnCol) ); ds@1952: if( iCol<0 ){ ds@1952: zType = "INTEGER"; ds@1952: zOriginCol = "rowid"; ds@1952: }else{ ds@1952: zType = pTab->aCol[iCol].zType; ds@1952: zOriginCol = pTab->aCol[iCol].zName; ds@1952: } ds@1952: zOriginTab = pTab->zName; ds@1952: if( pNC->pParse ){ ds@1952: int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); ds@1952: zOriginDb = pNC->pParse->db->aDb[iDb].zName; ds@1952: } ds@1952: } ds@1952: break; ds@1952: } ds@1952: #ifndef SQLITE_OMIT_SUBQUERY ds@1952: case TK_SELECT: { ds@1952: /* The expression is a sub-select. Return the declaration type and ds@1952: ** origin info for the single column in the result set of the SELECT ds@1952: ** statement. ds@1952: */ ds@1952: NameContext sNC; ds@1952: Select *pS = pExpr->pSelect; ds@1952: Expr *p = pS->pEList->a[0].pExpr; ds@1952: sNC.pSrcList = pS->pSrc; ds@1952: sNC.pNext = pNC; ds@1952: sNC.pParse = pNC->pParse; ds@1952: zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); ds@1952: break; ds@1952: } ds@1952: #endif ds@1952: } ds@1952: ds@1952: if( pzOriginDb ){ ds@1952: assert( pzOriginTab && pzOriginCol ); ds@1952: *pzOriginDb = zOriginDb; ds@1952: *pzOriginTab = zOriginTab; ds@1952: *pzOriginCol = zOriginCol; ds@1952: } ds@1952: return zType; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Generate code that will tell the VDBE the declaration types of columns ds@1952: ** in the result set. ds@1952: */ ds@1952: static void generateColumnTypes( ds@1952: Parse *pParse, /* Parser context */ ds@1952: SrcList *pTabList, /* List of tables */ ds@1952: ExprList *pEList /* Expressions defining the result set */ ds@1952: ){ ds@1952: Vdbe *v = pParse->pVdbe; ds@1952: int i; ds@1952: NameContext sNC; ds@1952: sNC.pSrcList = pTabList; ds@1952: sNC.pParse = pParse; ds@1952: for(i=0; inExpr; i++){ ds@1952: Expr *p = pEList->a[i].pExpr; ds@1952: const char *zOrigDb = 0; ds@1952: const char *zOrigTab = 0; ds@1952: const char *zOrigCol = 0; ds@1952: const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); ds@1952: ds@1952: /* The vdbe must make it's own copy of the column-type and other ds@1952: ** column specific strings, in case the schema is reset before this ds@1952: ** virtual machine is deleted. ds@1952: */ ds@1952: sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P3_TRANSIENT); ds@1952: sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P3_TRANSIENT); ds@1952: sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P3_TRANSIENT); ds@1952: sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P3_TRANSIENT); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Generate code that will tell the VDBE the names of columns ds@1952: ** in the result set. This information is used to provide the ds@1952: ** azCol[] values in the callback. ds@1952: */ ds@1952: static void generateColumnNames( ds@1952: Parse *pParse, /* Parser context */ ds@1952: SrcList *pTabList, /* List of tables */ ds@1952: ExprList *pEList /* Expressions defining the result set */ ds@1952: ){ ds@1952: Vdbe *v = pParse->pVdbe; ds@1952: int i, j; ds@1952: sqlite3 *db = pParse->db; ds@1952: int fullNames, shortNames; ds@1952: ds@1952: #ifndef SQLITE_OMIT_EXPLAIN ds@1952: /* If this is an EXPLAIN, skip this step */ ds@1952: if( pParse->explain ){ ds@1952: return; ds@1952: } ds@1952: #endif ds@1952: ds@1952: assert( v!=0 ); ds@1952: if( pParse->colNamesSet || v==0 || db->mallocFailed ) return; ds@1952: pParse->colNamesSet = 1; ds@1952: fullNames = (db->flags & SQLITE_FullColNames)!=0; ds@1952: shortNames = (db->flags & SQLITE_ShortColNames)!=0; ds@1952: sqlite3VdbeSetNumCols(v, pEList->nExpr); ds@1952: for(i=0; inExpr; i++){ ds@1952: Expr *p; ds@1952: p = pEList->a[i].pExpr; ds@1952: if( p==0 ) continue; ds@1952: if( pEList->a[i].zName ){ ds@1952: char *zName = pEList->a[i].zName; ds@1952: sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName)); ds@1952: continue; ds@1952: } ds@1952: if( p->op==TK_COLUMN && pTabList ){ ds@1952: Table *pTab; ds@1952: char *zCol; ds@1952: int iCol = p->iColumn; ds@1952: for(j=0; jnSrc && pTabList->a[j].iCursor!=p->iTable; j++){} ds@1952: assert( jnSrc ); ds@1952: pTab = pTabList->a[j].pTab; ds@1952: if( iCol<0 ) iCol = pTab->iPKey; ds@1952: assert( iCol==-1 || (iCol>=0 && iColnCol) ); ds@1952: if( iCol<0 ){ ds@1952: zCol = "rowid"; ds@1952: }else{ ds@1952: zCol = pTab->aCol[iCol].zName; ds@1952: } ds@1952: if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){ ds@1952: sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); ds@1952: }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){ ds@1952: char *zName = 0; ds@1952: char *zTab; ds@1952: ds@1952: zTab = pTabList->a[j].zAlias; ds@1952: if( fullNames || zTab==0 ) zTab = pTab->zName; ds@1952: sqlite3SetString(&zName, zTab, ".", zCol, (char*)0); ds@1952: sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC); ds@1952: }else{ ds@1952: sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol)); ds@1952: } ds@1952: }else if( p->span.z && p->span.z[0] ){ ds@1952: sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); ds@1952: /* sqlite3VdbeCompressSpace(v, addr); */ ds@1952: }else{ ds@1952: char zName[30]; ds@1952: assert( p->op!=TK_COLUMN || pTabList==0 ); ds@1952: sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1); ds@1952: sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0); ds@1952: } ds@1952: } ds@1952: generateColumnTypes(pParse, pTabList, pEList); ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_COMPOUND_SELECT ds@1952: /* ds@1952: ** Name of the connection operator, used for error messages. ds@1952: */ ds@1952: static const char *selectOpName(int id){ ds@1952: char *z; ds@1952: switch( id ){ ds@1952: case TK_ALL: z = "UNION ALL"; break; ds@1952: case TK_INTERSECT: z = "INTERSECT"; break; ds@1952: case TK_EXCEPT: z = "EXCEPT"; break; ds@1952: default: z = "UNION"; break; ds@1952: } ds@1952: return z; ds@1952: } ds@1952: #endif /* SQLITE_OMIT_COMPOUND_SELECT */ ds@1952: ds@1952: /* ds@1952: ** Forward declaration ds@1952: */ ds@1952: static int prepSelectStmt(Parse*, Select*); ds@1952: ds@1952: /* ds@1952: ** Given a SELECT statement, generate a Table structure that describes ds@1952: ** the result set of that SELECT. ds@1952: */ ds@1952: Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){ ds@1952: Table *pTab; ds@1952: int i, j; ds@1952: ExprList *pEList; ds@1952: Column *aCol, *pCol; ds@1952: sqlite3 *db = pParse->db; ds@1952: ds@1952: while( pSelect->pPrior ) pSelect = pSelect->pPrior; ds@1952: if( prepSelectStmt(pParse, pSelect) ){ ds@1952: return 0; ds@1952: } ds@1952: if( sqlite3SelectResolve(pParse, pSelect, 0) ){ ds@1952: return 0; ds@1952: } ds@1952: pTab = sqlite3DbMallocZero(db, sizeof(Table) ); ds@1952: if( pTab==0 ){ ds@1952: return 0; ds@1952: } ds@1952: pTab->nRef = 1; ds@1952: pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0; ds@1952: pEList = pSelect->pEList; ds@1952: pTab->nCol = pEList->nExpr; ds@1952: assert( pTab->nCol>0 ); ds@1952: pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol); ds@1952: for(i=0, pCol=aCol; inCol; i++, pCol++){ ds@1952: Expr *p, *pR; ds@1952: char *zType; ds@1952: char *zName; ds@1952: int nName; ds@1952: CollSeq *pColl; ds@1952: int cnt; ds@1952: NameContext sNC; ds@1952: ds@1952: /* Get an appropriate name for the column ds@1952: */ ds@1952: p = pEList->a[i].pExpr; ds@1952: assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 ); ds@1952: if( (zName = pEList->a[i].zName)!=0 ){ ds@1952: /* If the column contains an "AS " phrase, use as the name */ ds@1952: zName = sqlite3DbStrDup(db, zName); ds@1952: }else if( p->op==TK_DOT ds@1952: && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){ ds@1952: /* For columns of the from A.B use B as the name */ ds@1952: zName = sqlite3MPrintf(db, "%T", &pR->token); ds@1952: }else if( p->span.z && p->span.z[0] ){ ds@1952: /* Use the original text of the column expression as its name */ ds@1952: zName = sqlite3MPrintf(db, "%T", &p->span); ds@1952: }else{ ds@1952: /* If all else fails, make up a name */ ds@1952: zName = sqlite3MPrintf(db, "column%d", i+1); ds@1952: } ds@1952: if( !zName || db->mallocFailed ){ ds@1952: db->mallocFailed = 1; ds@1952: sqlite3_free(zName); ds@1952: sqlite3DeleteTable(pTab); ds@1952: return 0; ds@1952: } ds@1952: sqlite3Dequote(zName); ds@1952: ds@1952: /* Make sure the column name is unique. If the name is not unique, ds@1952: ** append a integer to the name so that it becomes unique. ds@1952: */ ds@1952: nName = strlen(zName); ds@1952: for(j=cnt=0; jzName = zName; ds@1952: ds@1952: /* Get the typename, type affinity, and collating sequence for the ds@1952: ** column. ds@1952: */ ds@1952: memset(&sNC, 0, sizeof(sNC)); ds@1952: sNC.pSrcList = pSelect->pSrc; ds@1952: zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0)); ds@1952: pCol->zType = zType; ds@1952: pCol->affinity = sqlite3ExprAffinity(p); ds@1952: pColl = sqlite3ExprCollSeq(pParse, p); ds@1952: if( pColl ){ ds@1952: pCol->zColl = sqlite3DbStrDup(db, pColl->zName); ds@1952: } ds@1952: } ds@1952: pTab->iPKey = -1; ds@1952: return pTab; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Prepare a SELECT statement for processing by doing the following ds@1952: ** things: ds@1952: ** ds@1952: ** (1) Make sure VDBE cursor numbers have been assigned to every ds@1952: ** element of the FROM clause. ds@1952: ** ds@1952: ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that ds@1952: ** defines FROM clause. When views appear in the FROM clause, ds@1952: ** fill pTabList->a[].pSelect with a copy of the SELECT statement ds@1952: ** that implements the view. A copy is made of the view's SELECT ds@1952: ** statement so that we can freely modify or delete that statement ds@1952: ** without worrying about messing up the presistent representation ds@1952: ** of the view. ds@1952: ** ds@1952: ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword ds@1952: ** on joins and the ON and USING clause of joins. ds@1952: ** ds@1952: ** (4) Scan the list of columns in the result set (pEList) looking ds@1952: ** for instances of the "*" operator or the TABLE.* operator. ds@1952: ** If found, expand each "*" to be every column in every table ds@1952: ** and TABLE.* to be every column in TABLE. ds@1952: ** ds@1952: ** Return 0 on success. If there are problems, leave an error message ds@1952: ** in pParse and return non-zero. ds@1952: */ ds@1952: static int prepSelectStmt(Parse *pParse, Select *p){ ds@1952: int i, j, k, rc; ds@1952: SrcList *pTabList; ds@1952: ExprList *pEList; ds@1952: struct SrcList_item *pFrom; ds@1952: sqlite3 *db = pParse->db; ds@1952: ds@1952: if( p==0 || p->pSrc==0 || db->mallocFailed ){ ds@1952: return 1; ds@1952: } ds@1952: pTabList = p->pSrc; ds@1952: pEList = p->pEList; ds@1952: ds@1952: /* Make sure cursor numbers have been assigned to all entries in ds@1952: ** the FROM clause of the SELECT statement. ds@1952: */ ds@1952: sqlite3SrcListAssignCursors(pParse, p->pSrc); ds@1952: ds@1952: /* Look up every table named in the FROM clause of the select. If ds@1952: ** an entry of the FROM clause is a subquery instead of a table or view, ds@1952: ** then create a transient table structure to describe the subquery. ds@1952: */ ds@1952: for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ ds@1952: Table *pTab; ds@1952: if( pFrom->pTab!=0 ){ ds@1952: /* This statement has already been prepared. There is no need ds@1952: ** to go further. */ ds@1952: assert( i==0 ); ds@1952: return 0; ds@1952: } ds@1952: if( pFrom->zName==0 ){ ds@1952: #ifndef SQLITE_OMIT_SUBQUERY ds@1952: /* A sub-query in the FROM clause of a SELECT */ ds@1952: assert( pFrom->pSelect!=0 ); ds@1952: if( pFrom->zAlias==0 ){ ds@1952: pFrom->zAlias = ds@1952: sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect); ds@1952: } ds@1952: assert( pFrom->pTab==0 ); ds@1952: pFrom->pTab = pTab = ds@1952: sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect); ds@1952: if( pTab==0 ){ ds@1952: return 1; ds@1952: } ds@1952: /* The isEphem flag indicates that the Table structure has been ds@1952: ** dynamically allocated and may be freed at any time. In other words, ds@1952: ** pTab is not pointing to a persistent table structure that defines ds@1952: ** part of the schema. */ ds@1952: pTab->isEphem = 1; ds@1952: #endif ds@1952: }else{ ds@1952: /* An ordinary table or view name in the FROM clause */ ds@1952: assert( pFrom->pTab==0 ); ds@1952: pFrom->pTab = pTab = ds@1952: sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase); ds@1952: if( pTab==0 ){ ds@1952: return 1; ds@1952: } ds@1952: pTab->nRef++; ds@1952: #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) ds@1952: if( pTab->pSelect || IsVirtual(pTab) ){ ds@1952: /* We reach here if the named table is a really a view */ ds@1952: if( sqlite3ViewGetColumnNames(pParse, pTab) ){ ds@1952: return 1; ds@1952: } ds@1952: /* If pFrom->pSelect!=0 it means we are dealing with a ds@1952: ** view within a view. The SELECT structure has already been ds@1952: ** copied by the outer view so we can skip the copy step here ds@1952: ** in the inner view. ds@1952: */ ds@1952: if( pFrom->pSelect==0 ){ ds@1952: pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect); ds@1952: } ds@1952: } ds@1952: #endif ds@1952: } ds@1952: } ds@1952: ds@1952: /* Process NATURAL keywords, and ON and USING clauses of joins. ds@1952: */ ds@1952: if( sqliteProcessJoin(pParse, p) ) return 1; ds@1952: ds@1952: /* For every "*" that occurs in the column list, insert the names of ds@1952: ** all columns in all tables. And for every TABLE.* insert the names ds@1952: ** of all columns in TABLE. The parser inserted a special expression ds@1952: ** with the TK_ALL operator for each "*" that it found in the column list. ds@1952: ** The following code just has to locate the TK_ALL expressions and expand ds@1952: ** each one to the list of all columns in all tables. ds@1952: ** ds@1952: ** The first loop just checks to see if there are any "*" operators ds@1952: ** that need expanding. ds@1952: */ ds@1952: for(k=0; knExpr; k++){ ds@1952: Expr *pE = pEList->a[k].pExpr; ds@1952: if( pE->op==TK_ALL ) break; ds@1952: if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL ds@1952: && pE->pLeft && pE->pLeft->op==TK_ID ) break; ds@1952: } ds@1952: rc = 0; ds@1952: if( knExpr ){ ds@1952: /* ds@1952: ** If we get here it means the result set contains one or more "*" ds@1952: ** operators that need to be expanded. Loop through each expression ds@1952: ** in the result set and expand them one by one. ds@1952: */ ds@1952: struct ExprList_item *a = pEList->a; ds@1952: ExprList *pNew = 0; ds@1952: int flags = pParse->db->flags; ds@1952: int longNames = (flags & SQLITE_FullColNames)!=0 && ds@1952: (flags & SQLITE_ShortColNames)==0; ds@1952: ds@1952: for(k=0; knExpr; k++){ ds@1952: Expr *pE = a[k].pExpr; ds@1952: if( pE->op!=TK_ALL && ds@1952: (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){ ds@1952: /* This particular expression does not need to be expanded. ds@1952: */ ds@1952: pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0); ds@1952: if( pNew ){ ds@1952: pNew->a[pNew->nExpr-1].zName = a[k].zName; ds@1952: }else{ ds@1952: rc = 1; ds@1952: } ds@1952: a[k].pExpr = 0; ds@1952: a[k].zName = 0; ds@1952: }else{ ds@1952: /* This expression is a "*" or a "TABLE.*" and needs to be ds@1952: ** expanded. */ ds@1952: int tableSeen = 0; /* Set to 1 when TABLE matches */ ds@1952: char *zTName; /* text of name of TABLE */ ds@1952: if( pE->op==TK_DOT && pE->pLeft ){ ds@1952: zTName = sqlite3NameFromToken(db, &pE->pLeft->token); ds@1952: }else{ ds@1952: zTName = 0; ds@1952: } ds@1952: for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ ds@1952: Table *pTab = pFrom->pTab; ds@1952: char *zTabName = pFrom->zAlias; ds@1952: if( zTabName==0 || zTabName[0]==0 ){ ds@1952: zTabName = pTab->zName; ds@1952: } ds@1952: if( zTName && (zTabName==0 || zTabName[0]==0 || ds@1952: sqlite3StrICmp(zTName, zTabName)!=0) ){ ds@1952: continue; ds@1952: } ds@1952: tableSeen = 1; ds@1952: for(j=0; jnCol; j++){ ds@1952: Expr *pExpr, *pRight; ds@1952: char *zName = pTab->aCol[j].zName; ds@1952: ds@1952: /* If a column is marked as 'hidden' (currently only possible ds@1952: ** for virtual tables), do not include it in the expanded ds@1952: ** result-set list. ds@1952: */ ds@1952: if( IsHiddenColumn(&pTab->aCol[j]) ){ ds@1952: assert(IsVirtual(pTab)); ds@1952: continue; ds@1952: } ds@1952: ds@1952: if( i>0 ){ ds@1952: struct SrcList_item *pLeft = &pTabList->a[i-1]; ds@1952: if( (pLeft[1].jointype & JT_NATURAL)!=0 && ds@1952: columnIndex(pLeft->pTab, zName)>=0 ){ ds@1952: /* In a NATURAL join, omit the join columns from the ds@1952: ** table on the right */ ds@1952: continue; ds@1952: } ds@1952: if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){ ds@1952: /* In a join with a USING clause, omit columns in the ds@1952: ** using clause from the table on the right. */ ds@1952: continue; ds@1952: } ds@1952: } ds@1952: pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0); ds@1952: if( pRight==0 ) break; ds@1952: setQuotedToken(pParse, &pRight->token, zName); ds@1952: if( zTabName && (longNames || pTabList->nSrc>1) ){ ds@1952: Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0); ds@1952: pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); ds@1952: if( pExpr==0 ) break; ds@1952: setQuotedToken(pParse, &pLeft->token, zTabName); ds@1952: setToken(&pExpr->span, ds@1952: sqlite3MPrintf(db, "%s.%s", zTabName, zName)); ds@1952: pExpr->span.dyn = 1; ds@1952: pExpr->token.z = 0; ds@1952: pExpr->token.n = 0; ds@1952: pExpr->token.dyn = 0; ds@1952: }else{ ds@1952: pExpr = pRight; ds@1952: pExpr->span = pExpr->token; ds@1952: pExpr->span.dyn = 0; ds@1952: } ds@1952: if( longNames ){ ds@1952: pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span); ds@1952: }else{ ds@1952: pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token); ds@1952: } ds@1952: } ds@1952: } ds@1952: if( !tableSeen ){ ds@1952: if( zTName ){ ds@1952: sqlite3ErrorMsg(pParse, "no such table: %s", zTName); ds@1952: }else{ ds@1952: sqlite3ErrorMsg(pParse, "no tables specified"); ds@1952: } ds@1952: rc = 1; ds@1952: } ds@1952: sqlite3_free(zTName); ds@1952: } ds@1952: } ds@1952: sqlite3ExprListDelete(pEList); ds@1952: p->pEList = pNew; ds@1952: } ds@1952: if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){ ds@1952: sqlite3ErrorMsg(pParse, "too many columns in result set"); ds@1952: rc = SQLITE_ERROR; ds@1952: } ds@1952: if( db->mallocFailed ){ ds@1952: rc = SQLITE_NOMEM; ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_COMPOUND_SELECT ds@1952: /* ds@1952: ** This routine associates entries in an ORDER BY expression list with ds@1952: ** columns in a result. For each ORDER BY expression, the opcode of ds@1952: ** the top-level node is changed to TK_COLUMN and the iColumn value of ds@1952: ** the top-level node is filled in with column number and the iTable ds@1952: ** value of the top-level node is filled with iTable parameter. ds@1952: ** ds@1952: ** If there are prior SELECT clauses, they are processed first. A match ds@1952: ** in an earlier SELECT takes precedence over a later SELECT. ds@1952: ** ds@1952: ** Any entry that does not match is flagged as an error. The number ds@1952: ** of errors is returned. ds@1952: */ ds@1952: static int matchOrderbyToColumn( ds@1952: Parse *pParse, /* A place to leave error messages */ ds@1952: Select *pSelect, /* Match to result columns of this SELECT */ ds@1952: ExprList *pOrderBy, /* The ORDER BY values to match against columns */ ds@1952: int iTable, /* Insert this value in iTable */ ds@1952: int mustComplete /* If TRUE all ORDER BYs must match */ ds@1952: ){ ds@1952: int nErr = 0; ds@1952: int i, j; ds@1952: ExprList *pEList; ds@1952: sqlite3 *db = pParse->db; ds@1952: ds@1952: if( pSelect==0 || pOrderBy==0 ) return 1; ds@1952: if( mustComplete ){ ds@1952: for(i=0; inExpr; i++){ pOrderBy->a[i].done = 0; } ds@1952: } ds@1952: if( prepSelectStmt(pParse, pSelect) ){ ds@1952: return 1; ds@1952: } ds@1952: if( pSelect->pPrior ){ ds@1952: if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){ ds@1952: return 1; ds@1952: } ds@1952: } ds@1952: pEList = pSelect->pEList; ds@1952: for(i=0; inExpr; i++){ ds@1952: struct ExprList_item *pItem; ds@1952: Expr *pE = pOrderBy->a[i].pExpr; ds@1952: int iCol = -1; ds@1952: char *zLabel; ds@1952: ds@1952: if( pOrderBy->a[i].done ) continue; ds@1952: if( sqlite3ExprIsInteger(pE, &iCol) ){ ds@1952: if( iCol<=0 || iCol>pEList->nExpr ){ ds@1952: sqlite3ErrorMsg(pParse, ds@1952: "ORDER BY position %d should be between 1 and %d", ds@1952: iCol, pEList->nExpr); ds@1952: nErr++; ds@1952: break; ds@1952: } ds@1952: if( !mustComplete ) continue; ds@1952: iCol--; ds@1952: } ds@1952: if( iCol<0 && (zLabel = sqlite3NameFromToken(db, &pE->token))!=0 ){ ds@1952: for(j=0, pItem=pEList->a; jnExpr; j++, pItem++){ ds@1952: char *zName; ds@1952: int isMatch; ds@1952: if( pItem->zName ){ ds@1952: zName = sqlite3DbStrDup(db, pItem->zName); ds@1952: }else{ ds@1952: zName = sqlite3NameFromToken(db, &pItem->pExpr->token); ds@1952: } ds@1952: isMatch = zName && sqlite3StrICmp(zName, zLabel)==0; ds@1952: sqlite3_free(zName); ds@1952: if( isMatch ){ ds@1952: iCol = j; ds@1952: break; ds@1952: } ds@1952: } ds@1952: sqlite3_free(zLabel); ds@1952: } ds@1952: if( iCol>=0 ){ ds@1952: pE->op = TK_COLUMN; ds@1952: pE->iColumn = iCol; ds@1952: pE->iTable = iTable; ds@1952: pE->iAgg = -1; ds@1952: pOrderBy->a[i].done = 1; ds@1952: }else if( mustComplete ){ ds@1952: sqlite3ErrorMsg(pParse, ds@1952: "ORDER BY term number %d does not match any result column", i+1); ds@1952: nErr++; ds@1952: break; ds@1952: } ds@1952: } ds@1952: return nErr; ds@1952: } ds@1952: #endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */ ds@1952: ds@1952: /* ds@1952: ** Get a VDBE for the given parser context. Create a new one if necessary. ds@1952: ** If an error occurs, return NULL and leave a message in pParse. ds@1952: */ ds@1952: Vdbe *sqlite3GetVdbe(Parse *pParse){ ds@1952: Vdbe *v = pParse->pVdbe; ds@1952: if( v==0 ){ ds@1952: v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); ds@1952: } ds@1952: return v; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Compute the iLimit and iOffset fields of the SELECT based on the ds@1952: ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions ds@1952: ** that appear in the original SQL statement after the LIMIT and OFFSET ds@1952: ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset ds@1952: ** are the integer memory register numbers for counters used to compute ds@1952: ** the limit and offset. If there is no limit and/or offset, then ds@1952: ** iLimit and iOffset are negative. ds@1952: ** ds@1952: ** This routine changes the values of iLimit and iOffset only if ds@1952: ** a limit or offset is defined by pLimit and pOffset. iLimit and ds@1952: ** iOffset should have been preset to appropriate default values ds@1952: ** (usually but not always -1) prior to calling this routine. ds@1952: ** Only if pLimit!=0 or pOffset!=0 do the limit registers get ds@1952: ** redefined. The UNION ALL operator uses this property to force ds@1952: ** the reuse of the same limit and offset registers across multiple ds@1952: ** SELECT statements. ds@1952: */ ds@1952: static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ ds@1952: Vdbe *v = 0; ds@1952: int iLimit = 0; ds@1952: int iOffset; ds@1952: int addr1, addr2; ds@1952: ds@1952: /* ds@1952: ** "LIMIT -1" always shows all rows. There is some ds@1952: ** contraversy about what the correct behavior should be. ds@1952: ** The current implementation interprets "LIMIT 0" to mean ds@1952: ** no rows. ds@1952: */ ds@1952: if( p->pLimit ){ ds@1952: p->iLimit = iLimit = pParse->nMem; ds@1952: pParse->nMem += 2; ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v==0 ) return; ds@1952: sqlite3ExprCode(pParse, p->pLimit); ds@1952: sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); ds@1952: sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 1); ds@1952: VdbeComment((v, "# LIMIT counter")); ds@1952: sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak); ds@1952: sqlite3VdbeAddOp(v, OP_MemLoad, iLimit, 0); ds@1952: } ds@1952: if( p->pOffset ){ ds@1952: p->iOffset = iOffset = pParse->nMem++; ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v==0 ) return; ds@1952: sqlite3ExprCode(pParse, p->pOffset); ds@1952: sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); ds@1952: sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0); ds@1952: VdbeComment((v, "# OFFSET counter")); ds@1952: addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Pop, 1, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Integer, 0, 0); ds@1952: sqlite3VdbeJumpHere(v, addr1); ds@1952: if( p->pLimit ){ ds@1952: sqlite3VdbeAddOp(v, OP_Add, 0, 0); ds@1952: } ds@1952: } ds@1952: if( p->pLimit ){ ds@1952: addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Pop, 1, 0); ds@1952: sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1); ds@1952: addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); ds@1952: sqlite3VdbeJumpHere(v, addr1); ds@1952: sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1); ds@1952: VdbeComment((v, "# LIMIT+OFFSET")); ds@1952: sqlite3VdbeJumpHere(v, addr2); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Allocate a virtual index to use for sorting. ds@1952: */ ds@1952: static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){ ds@1952: if( pOrderBy ){ ds@1952: int addr; ds@1952: assert( pOrderBy->iECursor==0 ); ds@1952: pOrderBy->iECursor = pParse->nTab++; ds@1952: addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenEphemeral, ds@1952: pOrderBy->iECursor, pOrderBy->nExpr+1); ds@1952: assert( p->addrOpenEphm[2] == -1 ); ds@1952: p->addrOpenEphm[2] = addr; ds@1952: } ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_COMPOUND_SELECT ds@1952: /* ds@1952: ** Return the appropriate collating sequence for the iCol-th column of ds@1952: ** the result set for the compound-select statement "p". Return NULL if ds@1952: ** the column has no default collating sequence. ds@1952: ** ds@1952: ** The collating sequence for the compound select is taken from the ds@1952: ** left-most term of the select that has a collating sequence. ds@1952: */ ds@1952: static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ ds@1952: CollSeq *pRet; ds@1952: if( p->pPrior ){ ds@1952: pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); ds@1952: }else{ ds@1952: pRet = 0; ds@1952: } ds@1952: if( pRet==0 ){ ds@1952: pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); ds@1952: } ds@1952: return pRet; ds@1952: } ds@1952: #endif /* SQLITE_OMIT_COMPOUND_SELECT */ ds@1952: ds@1952: #ifndef SQLITE_OMIT_COMPOUND_SELECT ds@1952: /* ds@1952: ** This routine is called to process a query that is really the union ds@1952: ** or intersection of two or more separate queries. ds@1952: ** ds@1952: ** "p" points to the right-most of the two queries. the query on the ds@1952: ** left is p->pPrior. The left query could also be a compound query ds@1952: ** in which case this routine will be called recursively. ds@1952: ** ds@1952: ** The results of the total query are to be written into a destination ds@1952: ** of type eDest with parameter iParm. ds@1952: ** ds@1952: ** Example 1: Consider a three-way compound SQL statement. ds@1952: ** ds@1952: ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 ds@1952: ** ds@1952: ** This statement is parsed up as follows: ds@1952: ** ds@1952: ** SELECT c FROM t3 ds@1952: ** | ds@1952: ** `-----> SELECT b FROM t2 ds@1952: ** | ds@1952: ** `------> SELECT a FROM t1 ds@1952: ** ds@1952: ** The arrows in the diagram above represent the Select.pPrior pointer. ds@1952: ** So if this routine is called with p equal to the t3 query, then ds@1952: ** pPrior will be the t2 query. p->op will be TK_UNION in this case. ds@1952: ** ds@1952: ** Notice that because of the way SQLite parses compound SELECTs, the ds@1952: ** individual selects always group from left to right. ds@1952: */ ds@1952: static int multiSelect( ds@1952: Parse *pParse, /* Parsing context */ ds@1952: Select *p, /* The right-most of SELECTs to be coded */ ds@1952: int eDest, /* \___ Store query results as specified */ ds@1952: int iParm, /* / by these two parameters. */ ds@1952: char *aff /* If eDest is SRT_Union, the affinity string */ ds@1952: ){ ds@1952: int rc = SQLITE_OK; /* Success code from a subroutine */ ds@1952: Select *pPrior; /* Another SELECT immediately to our left */ ds@1952: Vdbe *v; /* Generate code to this VDBE */ ds@1952: int nCol; /* Number of columns in the result set */ ds@1952: ExprList *pOrderBy; /* The ORDER BY clause on p */ ds@1952: int aSetP2[2]; /* Set P2 value of these op to number of columns */ ds@1952: int nSetP2 = 0; /* Number of slots in aSetP2[] used */ ds@1952: ds@1952: /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only ds@1952: ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. ds@1952: */ ds@1952: if( p==0 || p->pPrior==0 ){ ds@1952: rc = 1; ds@1952: goto multi_select_end; ds@1952: } ds@1952: pPrior = p->pPrior; ds@1952: assert( pPrior->pRightmost!=pPrior ); ds@1952: assert( pPrior->pRightmost==p->pRightmost ); ds@1952: if( pPrior->pOrderBy ){ ds@1952: sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", ds@1952: selectOpName(p->op)); ds@1952: rc = 1; ds@1952: goto multi_select_end; ds@1952: } ds@1952: if( pPrior->pLimit ){ ds@1952: sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", ds@1952: selectOpName(p->op)); ds@1952: rc = 1; ds@1952: goto multi_select_end; ds@1952: } ds@1952: ds@1952: /* Make sure we have a valid query engine. If not, create a new one. ds@1952: */ ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v==0 ){ ds@1952: rc = 1; ds@1952: goto multi_select_end; ds@1952: } ds@1952: ds@1952: /* Create the destination temporary table if necessary ds@1952: */ ds@1952: if( eDest==SRT_EphemTab ){ ds@1952: assert( p->pEList ); ds@1952: assert( nSetP2pOrderBy; ds@1952: switch( p->op ){ ds@1952: case TK_ALL: { ds@1952: if( pOrderBy==0 ){ ds@1952: int addr = 0; ds@1952: assert( !pPrior->pLimit ); ds@1952: pPrior->pLimit = p->pLimit; ds@1952: pPrior->pOffset = p->pOffset; ds@1952: rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff); ds@1952: p->pLimit = 0; ds@1952: p->pOffset = 0; ds@1952: if( rc ){ ds@1952: goto multi_select_end; ds@1952: } ds@1952: p->pPrior = 0; ds@1952: p->iLimit = pPrior->iLimit; ds@1952: p->iOffset = pPrior->iOffset; ds@1952: if( p->iLimit>=0 ){ ds@1952: addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0); ds@1952: VdbeComment((v, "# Jump ahead if LIMIT reached")); ds@1952: } ds@1952: rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff); ds@1952: p->pPrior = pPrior; ds@1952: if( rc ){ ds@1952: goto multi_select_end; ds@1952: } ds@1952: if( addr ){ ds@1952: sqlite3VdbeJumpHere(v, addr); ds@1952: } ds@1952: break; ds@1952: } ds@1952: /* For UNION ALL ... ORDER BY fall through to the next case */ ds@1952: } ds@1952: case TK_EXCEPT: ds@1952: case TK_UNION: { ds@1952: int unionTab; /* Cursor number of the temporary table holding result */ ds@1952: int op = 0; /* One of the SRT_ operations to apply to self */ ds@1952: int priorOp; /* The SRT_ operation to apply to prior selects */ ds@1952: Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ ds@1952: int addr; ds@1952: ds@1952: priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union; ds@1952: if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){ ds@1952: /* We can reuse a temporary table generated by a SELECT to our ds@1952: ** right. ds@1952: */ ds@1952: unionTab = iParm; ds@1952: }else{ ds@1952: /* We will need to create our own temporary table to hold the ds@1952: ** intermediate results. ds@1952: */ ds@1952: unionTab = pParse->nTab++; ds@1952: if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){ ds@1952: rc = 1; ds@1952: goto multi_select_end; ds@1952: } ds@1952: addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0); ds@1952: if( priorOp==SRT_Table ){ ds@1952: assert( nSetP2addrOpenEphm[0] == -1 ); ds@1952: p->addrOpenEphm[0] = addr; ds@1952: p->pRightmost->usesEphm = 1; ds@1952: } ds@1952: createSortingIndex(pParse, p, pOrderBy); ds@1952: assert( p->pEList ); ds@1952: } ds@1952: ds@1952: /* Code the SELECT statements to our left ds@1952: */ ds@1952: assert( !pPrior->pOrderBy ); ds@1952: rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff); ds@1952: if( rc ){ ds@1952: goto multi_select_end; ds@1952: } ds@1952: ds@1952: /* Code the current SELECT statement ds@1952: */ ds@1952: switch( p->op ){ ds@1952: case TK_EXCEPT: op = SRT_Except; break; ds@1952: case TK_UNION: op = SRT_Union; break; ds@1952: case TK_ALL: op = SRT_Table; break; ds@1952: } ds@1952: p->pPrior = 0; ds@1952: p->pOrderBy = 0; ds@1952: p->disallowOrderBy = pOrderBy!=0; ds@1952: pLimit = p->pLimit; ds@1952: p->pLimit = 0; ds@1952: pOffset = p->pOffset; ds@1952: p->pOffset = 0; ds@1952: rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff); ds@1952: /* Query flattening in sqlite3Select() might refill p->pOrderBy. ds@1952: ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ ds@1952: sqlite3ExprListDelete(p->pOrderBy); ds@1952: p->pPrior = pPrior; ds@1952: p->pOrderBy = pOrderBy; ds@1952: sqlite3ExprDelete(p->pLimit); ds@1952: p->pLimit = pLimit; ds@1952: p->pOffset = pOffset; ds@1952: p->iLimit = -1; ds@1952: p->iOffset = -1; ds@1952: if( rc ){ ds@1952: goto multi_select_end; ds@1952: } ds@1952: ds@1952: ds@1952: /* Convert the data in the temporary table into whatever form ds@1952: ** it is that we currently need. ds@1952: */ ds@1952: if( eDest!=priorOp || unionTab!=iParm ){ ds@1952: int iCont, iBreak, iStart; ds@1952: assert( p->pEList ); ds@1952: if( eDest==SRT_Callback ){ ds@1952: Select *pFirst = p; ds@1952: while( pFirst->pPrior ) pFirst = pFirst->pPrior; ds@1952: generateColumnNames(pParse, 0, pFirst->pEList); ds@1952: } ds@1952: iBreak = sqlite3VdbeMakeLabel(v); ds@1952: iCont = sqlite3VdbeMakeLabel(v); ds@1952: computeLimitRegisters(pParse, p, iBreak); ds@1952: sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak); ds@1952: iStart = sqlite3VdbeCurrentAddr(v); ds@1952: rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, ds@1952: pOrderBy, -1, eDest, iParm, ds@1952: iCont, iBreak, 0); ds@1952: if( rc ){ ds@1952: rc = 1; ds@1952: goto multi_select_end; ds@1952: } ds@1952: sqlite3VdbeResolveLabel(v, iCont); ds@1952: sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart); ds@1952: sqlite3VdbeResolveLabel(v, iBreak); ds@1952: sqlite3VdbeAddOp(v, OP_Close, unionTab, 0); ds@1952: } ds@1952: break; ds@1952: } ds@1952: case TK_INTERSECT: { ds@1952: int tab1, tab2; ds@1952: int iCont, iBreak, iStart; ds@1952: Expr *pLimit, *pOffset; ds@1952: int addr; ds@1952: ds@1952: /* INTERSECT is different from the others since it requires ds@1952: ** two temporary tables. Hence it has its own case. Begin ds@1952: ** by allocating the tables we will need. ds@1952: */ ds@1952: tab1 = pParse->nTab++; ds@1952: tab2 = pParse->nTab++; ds@1952: if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){ ds@1952: rc = 1; ds@1952: goto multi_select_end; ds@1952: } ds@1952: createSortingIndex(pParse, p, pOrderBy); ds@1952: ds@1952: addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 0); ds@1952: assert( p->addrOpenEphm[0] == -1 ); ds@1952: p->addrOpenEphm[0] = addr; ds@1952: p->pRightmost->usesEphm = 1; ds@1952: assert( p->pEList ); ds@1952: ds@1952: /* Code the SELECTs to our left into temporary table "tab1". ds@1952: */ ds@1952: rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff); ds@1952: if( rc ){ ds@1952: goto multi_select_end; ds@1952: } ds@1952: ds@1952: /* Code the current SELECT into temporary table "tab2" ds@1952: */ ds@1952: addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab2, 0); ds@1952: assert( p->addrOpenEphm[1] == -1 ); ds@1952: p->addrOpenEphm[1] = addr; ds@1952: p->pPrior = 0; ds@1952: pLimit = p->pLimit; ds@1952: p->pLimit = 0; ds@1952: pOffset = p->pOffset; ds@1952: p->pOffset = 0; ds@1952: rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff); ds@1952: p->pPrior = pPrior; ds@1952: sqlite3ExprDelete(p->pLimit); ds@1952: p->pLimit = pLimit; ds@1952: p->pOffset = pOffset; ds@1952: if( rc ){ ds@1952: goto multi_select_end; ds@1952: } ds@1952: ds@1952: /* Generate code to take the intersection of the two temporary ds@1952: ** tables. ds@1952: */ ds@1952: assert( p->pEList ); ds@1952: if( eDest==SRT_Callback ){ ds@1952: Select *pFirst = p; ds@1952: while( pFirst->pPrior ) pFirst = pFirst->pPrior; ds@1952: generateColumnNames(pParse, 0, pFirst->pEList); ds@1952: } ds@1952: iBreak = sqlite3VdbeMakeLabel(v); ds@1952: iCont = sqlite3VdbeMakeLabel(v); ds@1952: computeLimitRegisters(pParse, p, iBreak); ds@1952: sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak); ds@1952: iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0); ds@1952: sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont); ds@1952: rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, ds@1952: pOrderBy, -1, eDest, iParm, ds@1952: iCont, iBreak, 0); ds@1952: if( rc ){ ds@1952: rc = 1; ds@1952: goto multi_select_end; ds@1952: } ds@1952: sqlite3VdbeResolveLabel(v, iCont); ds@1952: sqlite3VdbeAddOp(v, OP_Next, tab1, iStart); ds@1952: sqlite3VdbeResolveLabel(v, iBreak); ds@1952: sqlite3VdbeAddOp(v, OP_Close, tab2, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Close, tab1, 0); ds@1952: break; ds@1952: } ds@1952: } ds@1952: ds@1952: /* Make sure all SELECTs in the statement have the same number of elements ds@1952: ** in their result sets. ds@1952: */ ds@1952: assert( p->pEList && pPrior->pEList ); ds@1952: if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ ds@1952: sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" ds@1952: " do not have the same number of result columns", selectOpName(p->op)); ds@1952: rc = 1; ds@1952: goto multi_select_end; ds@1952: } ds@1952: ds@1952: /* Set the number of columns in temporary tables ds@1952: */ ds@1952: nCol = p->pEList->nExpr; ds@1952: while( nSetP2 ){ ds@1952: sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol); ds@1952: } ds@1952: ds@1952: /* Compute collating sequences used by either the ORDER BY clause or ds@1952: ** by any temporary tables needed to implement the compound select. ds@1952: ** Attach the KeyInfo structure to all temporary tables. Invoke the ds@1952: ** ORDER BY processing if there is an ORDER BY clause. ds@1952: ** ds@1952: ** This section is run by the right-most SELECT statement only. ds@1952: ** SELECT statements to the left always skip this part. The right-most ds@1952: ** SELECT might also skip this part if it has no ORDER BY clause and ds@1952: ** no temp tables are required. ds@1952: */ ds@1952: if( pOrderBy || p->usesEphm ){ ds@1952: int i; /* Loop counter */ ds@1952: KeyInfo *pKeyInfo; /* Collating sequence for the result set */ ds@1952: Select *pLoop; /* For looping through SELECT statements */ ds@1952: int nKeyCol; /* Number of entries in pKeyInfo->aCol[] */ ds@1952: CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ ds@1952: CollSeq **aCopy; /* A copy of pKeyInfo->aColl[] */ ds@1952: ds@1952: assert( p->pRightmost==p ); ds@1952: nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0); ds@1952: pKeyInfo = sqlite3DbMallocZero(pParse->db, ds@1952: sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1)); ds@1952: if( !pKeyInfo ){ ds@1952: rc = SQLITE_NOMEM; ds@1952: goto multi_select_end; ds@1952: } ds@1952: ds@1952: pKeyInfo->enc = ENC(pParse->db); ds@1952: pKeyInfo->nField = nCol; ds@1952: ds@1952: for(i=0, apColl=pKeyInfo->aColl; idb->pDfltColl; ds@1952: } ds@1952: } ds@1952: ds@1952: for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ ds@1952: for(i=0; i<2; i++){ ds@1952: int addr = pLoop->addrOpenEphm[i]; ds@1952: if( addr<0 ){ ds@1952: /* If [0] is unused then [1] is also unused. So we can ds@1952: ** always safely abort as soon as the first unused slot is found */ ds@1952: assert( pLoop->addrOpenEphm[1]<0 ); ds@1952: break; ds@1952: } ds@1952: sqlite3VdbeChangeP2(v, addr, nCol); ds@1952: sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO); ds@1952: pLoop->addrOpenEphm[i] = -1; ds@1952: } ds@1952: } ds@1952: ds@1952: if( pOrderBy ){ ds@1952: struct ExprList_item *pOTerm = pOrderBy->a; ds@1952: int nOrderByExpr = pOrderBy->nExpr; ds@1952: int addr; ds@1952: u8 *pSortOrder; ds@1952: ds@1952: /* Reuse the same pKeyInfo for the ORDER BY as was used above for ds@1952: ** the compound select statements. Except we have to change out the ds@1952: ** pKeyInfo->aColl[] values. Some of the aColl[] values will be ds@1952: ** reused when constructing the pKeyInfo for the ORDER BY, so make ds@1952: ** a copy. Sufficient space to hold both the nCol entries for ds@1952: ** the compound select and the nOrderbyExpr entries for the ORDER BY ds@1952: ** was allocated above. But we need to move the compound select ds@1952: ** entries out of the way before constructing the ORDER BY entries. ds@1952: ** Move the compound select entries into aCopy[] where they can be ds@1952: ** accessed and reused when constructing the ORDER BY entries. ds@1952: ** Because nCol might be greater than or less than nOrderByExpr ds@1952: ** we have to use memmove() when doing the copy. ds@1952: */ ds@1952: aCopy = &pKeyInfo->aColl[nOrderByExpr]; ds@1952: pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol]; ds@1952: memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*)); ds@1952: ds@1952: apColl = pKeyInfo->aColl; ds@1952: for(i=0; ipExpr; ds@1952: if( (pExpr->flags & EP_ExpCollate) ){ ds@1952: assert( pExpr->pColl!=0 ); ds@1952: *apColl = pExpr->pColl; ds@1952: }else{ ds@1952: *apColl = aCopy[pExpr->iColumn]; ds@1952: } ds@1952: *pSortOrder = pOTerm->sortOrder; ds@1952: } ds@1952: assert( p->pRightmost==p ); ds@1952: assert( p->addrOpenEphm[2]>=0 ); ds@1952: addr = p->addrOpenEphm[2]; ds@1952: sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2); ds@1952: pKeyInfo->nField = nOrderByExpr; ds@1952: sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF); ds@1952: pKeyInfo = 0; ds@1952: generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm); ds@1952: } ds@1952: ds@1952: sqlite3_free(pKeyInfo); ds@1952: } ds@1952: ds@1952: multi_select_end: ds@1952: return rc; ds@1952: } ds@1952: #endif /* SQLITE_OMIT_COMPOUND_SELECT */ ds@1952: ds@1952: #ifndef SQLITE_OMIT_VIEW ds@1952: /* Forward Declarations */ ds@1952: static void substExprList(sqlite3*, ExprList*, int, ExprList*); ds@1952: static void substSelect(sqlite3*, Select *, int, ExprList *); ds@1952: ds@1952: /* ds@1952: ** Scan through the expression pExpr. Replace every reference to ds@1952: ** a column in table number iTable with a copy of the iColumn-th ds@1952: ** entry in pEList. (But leave references to the ROWID column ds@1952: ** unchanged.) ds@1952: ** ds@1952: ** This routine is part of the flattening procedure. A subquery ds@1952: ** whose result set is defined by pEList appears as entry in the ds@1952: ** FROM clause of a SELECT such that the VDBE cursor assigned to that ds@1952: ** FORM clause entry is iTable. This routine make the necessary ds@1952: ** changes to pExpr so that it refers directly to the source table ds@1952: ** of the subquery rather the result set of the subquery. ds@1952: */ ds@1952: static void substExpr( ds@1952: sqlite3 *db, /* Report malloc errors to this connection */ ds@1952: Expr *pExpr, /* Expr in which substitution occurs */ ds@1952: int iTable, /* Table to be substituted */ ds@1952: ExprList *pEList /* Substitute expressions */ ds@1952: ){ ds@1952: if( pExpr==0 ) return; ds@1952: if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ ds@1952: if( pExpr->iColumn<0 ){ ds@1952: pExpr->op = TK_NULL; ds@1952: }else{ ds@1952: Expr *pNew; ds@1952: assert( pEList!=0 && pExpr->iColumnnExpr ); ds@1952: assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 ); ds@1952: pNew = pEList->a[pExpr->iColumn].pExpr; ds@1952: assert( pNew!=0 ); ds@1952: pExpr->op = pNew->op; ds@1952: assert( pExpr->pLeft==0 ); ds@1952: pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft); ds@1952: assert( pExpr->pRight==0 ); ds@1952: pExpr->pRight = sqlite3ExprDup(db, pNew->pRight); ds@1952: assert( pExpr->pList==0 ); ds@1952: pExpr->pList = sqlite3ExprListDup(db, pNew->pList); ds@1952: pExpr->iTable = pNew->iTable; ds@1952: pExpr->pTab = pNew->pTab; ds@1952: pExpr->iColumn = pNew->iColumn; ds@1952: pExpr->iAgg = pNew->iAgg; ds@1952: sqlite3TokenCopy(db, &pExpr->token, &pNew->token); ds@1952: sqlite3TokenCopy(db, &pExpr->span, &pNew->span); ds@1952: pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect); ds@1952: pExpr->flags = pNew->flags; ds@1952: } ds@1952: }else{ ds@1952: substExpr(db, pExpr->pLeft, iTable, pEList); ds@1952: substExpr(db, pExpr->pRight, iTable, pEList); ds@1952: substSelect(db, pExpr->pSelect, iTable, pEList); ds@1952: substExprList(db, pExpr->pList, iTable, pEList); ds@1952: } ds@1952: } ds@1952: static void substExprList( ds@1952: sqlite3 *db, /* Report malloc errors here */ ds@1952: ExprList *pList, /* List to scan and in which to make substitutes */ ds@1952: int iTable, /* Table to be substituted */ ds@1952: ExprList *pEList /* Substitute values */ ds@1952: ){ ds@1952: int i; ds@1952: if( pList==0 ) return; ds@1952: for(i=0; inExpr; i++){ ds@1952: substExpr(db, pList->a[i].pExpr, iTable, pEList); ds@1952: } ds@1952: } ds@1952: static void substSelect( ds@1952: sqlite3 *db, /* Report malloc errors here */ ds@1952: Select *p, /* SELECT statement in which to make substitutions */ ds@1952: int iTable, /* Table to be replaced */ ds@1952: ExprList *pEList /* Substitute values */ ds@1952: ){ ds@1952: if( !p ) return; ds@1952: substExprList(db, p->pEList, iTable, pEList); ds@1952: substExprList(db, p->pGroupBy, iTable, pEList); ds@1952: substExprList(db, p->pOrderBy, iTable, pEList); ds@1952: substExpr(db, p->pHaving, iTable, pEList); ds@1952: substExpr(db, p->pWhere, iTable, pEList); ds@1952: substSelect(db, p->pPrior, iTable, pEList); ds@1952: } ds@1952: #endif /* !defined(SQLITE_OMIT_VIEW) */ ds@1952: ds@1952: #ifndef SQLITE_OMIT_VIEW ds@1952: /* ds@1952: ** This routine attempts to flatten subqueries in order to speed ds@1952: ** execution. It returns 1 if it makes changes and 0 if no flattening ds@1952: ** occurs. ds@1952: ** ds@1952: ** To understand the concept of flattening, consider the following ds@1952: ** query: ds@1952: ** ds@1952: ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 ds@1952: ** ds@1952: ** The default way of implementing this query is to execute the ds@1952: ** subquery first and store the results in a temporary table, then ds@1952: ** run the outer query on that temporary table. This requires two ds@1952: ** passes over the data. Furthermore, because the temporary table ds@1952: ** has no indices, the WHERE clause on the outer query cannot be ds@1952: ** optimized. ds@1952: ** ds@1952: ** This routine attempts to rewrite queries such as the above into ds@1952: ** a single flat select, like this: ds@1952: ** ds@1952: ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 ds@1952: ** ds@1952: ** The code generated for this simpification gives the same result ds@1952: ** but only has to scan the data once. And because indices might ds@1952: ** exist on the table t1, a complete scan of the data might be ds@1952: ** avoided. ds@1952: ** ds@1952: ** Flattening is only attempted if all of the following are true: ds@1952: ** ds@1952: ** (1) The subquery and the outer query do not both use aggregates. ds@1952: ** ds@1952: ** (2) The subquery is not an aggregate or the outer query is not a join. ds@1952: ** ds@1952: ** (3) The subquery is not the right operand of a left outer join, or ds@1952: ** the subquery is not itself a join. (Ticket #306) ds@1952: ** ds@1952: ** (4) The subquery is not DISTINCT or the outer query is not a join. ds@1952: ** ds@1952: ** (5) The subquery is not DISTINCT or the outer query does not use ds@1952: ** aggregates. ds@1952: ** ds@1952: ** (6) The subquery does not use aggregates or the outer query is not ds@1952: ** DISTINCT. ds@1952: ** ds@1952: ** (7) The subquery has a FROM clause. ds@1952: ** ds@1952: ** (8) The subquery does not use LIMIT or the outer query is not a join. ds@1952: ** ds@1952: ** (9) The subquery does not use LIMIT or the outer query does not use ds@1952: ** aggregates. ds@1952: ** ds@1952: ** (10) The subquery does not use aggregates or the outer query does not ds@1952: ** use LIMIT. ds@1952: ** ds@1952: ** (11) The subquery and the outer query do not both have ORDER BY clauses. ds@1952: ** ds@1952: ** (12) The subquery is not the right term of a LEFT OUTER JOIN or the ds@1952: ** subquery has no WHERE clause. (added by ticket #350) ds@1952: ** ds@1952: ** (13) The subquery and outer query do not both use LIMIT ds@1952: ** ds@1952: ** (14) The subquery does not use OFFSET ds@1952: ** ds@1952: ** (15) The outer query is not part of a compound select or the ds@1952: ** subquery does not have both an ORDER BY and a LIMIT clause. ds@1952: ** (See ticket #2339) ds@1952: ** ds@1952: ** In this routine, the "p" parameter is a pointer to the outer query. ds@1952: ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query ds@1952: ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. ds@1952: ** ds@1952: ** If flattening is not attempted, this routine is a no-op and returns 0. ds@1952: ** If flattening is attempted this routine returns 1. ds@1952: ** ds@1952: ** All of the expression analysis must occur on both the outer query and ds@1952: ** the subquery before this routine runs. ds@1952: */ ds@1952: static int flattenSubquery( ds@1952: sqlite3 *db, /* Database connection */ ds@1952: Select *p, /* The parent or outer SELECT statement */ ds@1952: int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ ds@1952: int isAgg, /* True if outer SELECT uses aggregate functions */ ds@1952: int subqueryIsAgg /* True if the subquery uses aggregate functions */ ds@1952: ){ ds@1952: Select *pSub; /* The inner query or "subquery" */ ds@1952: SrcList *pSrc; /* The FROM clause of the outer query */ ds@1952: SrcList *pSubSrc; /* The FROM clause of the subquery */ ds@1952: ExprList *pList; /* The result set of the outer query */ ds@1952: int iParent; /* VDBE cursor number of the pSub result set temp table */ ds@1952: int i; /* Loop counter */ ds@1952: Expr *pWhere; /* The WHERE clause */ ds@1952: struct SrcList_item *pSubitem; /* The subquery */ ds@1952: ds@1952: /* Check to see if flattening is permitted. Return 0 if not. ds@1952: */ ds@1952: if( p==0 ) return 0; ds@1952: pSrc = p->pSrc; ds@1952: assert( pSrc && iFrom>=0 && iFromnSrc ); ds@1952: pSubitem = &pSrc->a[iFrom]; ds@1952: pSub = pSubitem->pSelect; ds@1952: assert( pSub!=0 ); ds@1952: if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ ds@1952: if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ ds@1952: pSubSrc = pSub->pSrc; ds@1952: assert( pSubSrc ); ds@1952: /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, ds@1952: ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET ds@1952: ** because they could be computed at compile-time. But when LIMIT and OFFSET ds@1952: ** became arbitrary expressions, we were forced to add restrictions (13) ds@1952: ** and (14). */ ds@1952: if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ ds@1952: if( pSub->pOffset ) return 0; /* Restriction (14) */ ds@1952: if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){ ds@1952: return 0; /* Restriction (15) */ ds@1952: } ds@1952: if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ ds@1952: if( (pSub->isDistinct || pSub->pLimit) ds@1952: && (pSrc->nSrc>1 || isAgg) ){ /* Restrictions (4)(5)(8)(9) */ ds@1952: return 0; ds@1952: } ds@1952: if( p->isDistinct && subqueryIsAgg ) return 0; /* Restriction (6) */ ds@1952: if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){ ds@1952: return 0; /* Restriction (11) */ ds@1952: } ds@1952: ds@1952: /* Restriction 3: If the subquery is a join, make sure the subquery is ds@1952: ** not used as the right operand of an outer join. Examples of why this ds@1952: ** is not allowed: ds@1952: ** ds@1952: ** t1 LEFT OUTER JOIN (t2 JOIN t3) ds@1952: ** ds@1952: ** If we flatten the above, we would get ds@1952: ** ds@1952: ** (t1 LEFT OUTER JOIN t2) JOIN t3 ds@1952: ** ds@1952: ** which is not at all the same thing. ds@1952: */ ds@1952: if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){ ds@1952: return 0; ds@1952: } ds@1952: ds@1952: /* Restriction 12: If the subquery is the right operand of a left outer ds@1952: ** join, make sure the subquery has no WHERE clause. ds@1952: ** An examples of why this is not allowed: ds@1952: ** ds@1952: ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) ds@1952: ** ds@1952: ** If we flatten the above, we would get ds@1952: ** ds@1952: ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 ds@1952: ** ds@1952: ** But the t2.x>0 test will always fail on a NULL row of t2, which ds@1952: ** effectively converts the OUTER JOIN into an INNER JOIN. ds@1952: */ ds@1952: if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){ ds@1952: return 0; ds@1952: } ds@1952: ds@1952: /* If we reach this point, it means flattening is permitted for the ds@1952: ** iFrom-th entry of the FROM clause in the outer query. ds@1952: */ ds@1952: ds@1952: /* Move all of the FROM elements of the subquery into the ds@1952: ** the FROM clause of the outer query. Before doing this, remember ds@1952: ** the cursor number for the original outer query FROM element in ds@1952: ** iParent. The iParent cursor will never be used. Subsequent code ds@1952: ** will scan expressions looking for iParent references and replace ds@1952: ** those references with expressions that resolve to the subquery FROM ds@1952: ** elements we are now copying in. ds@1952: */ ds@1952: iParent = pSubitem->iCursor; ds@1952: { ds@1952: int nSubSrc = pSubSrc->nSrc; ds@1952: int jointype = pSubitem->jointype; ds@1952: ds@1952: sqlite3DeleteTable(pSubitem->pTab); ds@1952: sqlite3_free(pSubitem->zDatabase); ds@1952: sqlite3_free(pSubitem->zName); ds@1952: sqlite3_free(pSubitem->zAlias); ds@1952: if( nSubSrc>1 ){ ds@1952: int extra = nSubSrc - 1; ds@1952: for(i=1; ipSrc = pSrc; ds@1952: for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){ ds@1952: pSrc->a[i] = pSrc->a[i-extra]; ds@1952: } ds@1952: } ds@1952: for(i=0; ia[i+iFrom] = pSubSrc->a[i]; ds@1952: memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); ds@1952: } ds@1952: pSrc->a[iFrom].jointype = jointype; ds@1952: } ds@1952: ds@1952: /* Now begin substituting subquery result set expressions for ds@1952: ** references to the iParent in the outer query. ds@1952: ** ds@1952: ** Example: ds@1952: ** ds@1952: ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; ds@1952: ** \ \_____________ subquery __________/ / ds@1952: ** \_____________________ outer query ______________________________/ ds@1952: ** ds@1952: ** We look at every expression in the outer query and every place we see ds@1952: ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". ds@1952: */ ds@1952: pList = p->pEList; ds@1952: for(i=0; inExpr; i++){ ds@1952: Expr *pExpr; ds@1952: if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){ ds@1952: pList->a[i].zName = ds@1952: sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n); ds@1952: } ds@1952: } ds@1952: substExprList(db, p->pEList, iParent, pSub->pEList); ds@1952: if( isAgg ){ ds@1952: substExprList(db, p->pGroupBy, iParent, pSub->pEList); ds@1952: substExpr(db, p->pHaving, iParent, pSub->pEList); ds@1952: } ds@1952: if( pSub->pOrderBy ){ ds@1952: assert( p->pOrderBy==0 ); ds@1952: p->pOrderBy = pSub->pOrderBy; ds@1952: pSub->pOrderBy = 0; ds@1952: }else if( p->pOrderBy ){ ds@1952: substExprList(db, p->pOrderBy, iParent, pSub->pEList); ds@1952: } ds@1952: if( pSub->pWhere ){ ds@1952: pWhere = sqlite3ExprDup(db, pSub->pWhere); ds@1952: }else{ ds@1952: pWhere = 0; ds@1952: } ds@1952: if( subqueryIsAgg ){ ds@1952: assert( p->pHaving==0 ); ds@1952: p->pHaving = p->pWhere; ds@1952: p->pWhere = pWhere; ds@1952: substExpr(db, p->pHaving, iParent, pSub->pEList); ds@1952: p->pHaving = sqlite3ExprAnd(db, p->pHaving, ds@1952: sqlite3ExprDup(db, pSub->pHaving)); ds@1952: assert( p->pGroupBy==0 ); ds@1952: p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy); ds@1952: }else{ ds@1952: substExpr(db, p->pWhere, iParent, pSub->pEList); ds@1952: p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere); ds@1952: } ds@1952: ds@1952: /* The flattened query is distinct if either the inner or the ds@1952: ** outer query is distinct. ds@1952: */ ds@1952: p->isDistinct = p->isDistinct || pSub->isDistinct; ds@1952: ds@1952: /* ds@1952: ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; ds@1952: ** ds@1952: ** One is tempted to try to add a and b to combine the limits. But this ds@1952: ** does not work if either limit is negative. ds@1952: */ ds@1952: if( pSub->pLimit ){ ds@1952: p->pLimit = pSub->pLimit; ds@1952: pSub->pLimit = 0; ds@1952: } ds@1952: ds@1952: /* Finially, delete what is left of the subquery and return ds@1952: ** success. ds@1952: */ ds@1952: sqlite3SelectDelete(pSub); ds@1952: return 1; ds@1952: } ds@1952: #endif /* SQLITE_OMIT_VIEW */ ds@1952: ds@1952: /* ds@1952: ** Analyze the SELECT statement passed in as an argument to see if it ds@1952: ** is a simple min() or max() query. If it is and this query can be ds@1952: ** satisfied using a single seek to the beginning or end of an index, ds@1952: ** then generate the code for this SELECT and return 1. If this is not a ds@1952: ** simple min() or max() query, then return 0; ds@1952: ** ds@1952: ** A simply min() or max() query looks like this: ds@1952: ** ds@1952: ** SELECT min(a) FROM table; ds@1952: ** SELECT max(a) FROM table; ds@1952: ** ds@1952: ** The query may have only a single table in its FROM argument. There ds@1952: ** can be no GROUP BY or HAVING or WHERE clauses. The result set must ds@1952: ** be the min() or max() of a single column of the table. The column ds@1952: ** in the min() or max() function must be indexed. ds@1952: ** ds@1952: ** The parameters to this routine are the same as for sqlite3Select(). ds@1952: ** See the header comment on that routine for additional information. ds@1952: */ ds@1952: static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){ ds@1952: Expr *pExpr; ds@1952: int iCol; ds@1952: Table *pTab; ds@1952: Index *pIdx; ds@1952: int base; ds@1952: Vdbe *v; ds@1952: int seekOp; ds@1952: ExprList *pEList, *pList, eList; ds@1952: struct ExprList_item eListItem; ds@1952: SrcList *pSrc; ds@1952: int brk; ds@1952: int iDb; ds@1952: ds@1952: /* Check to see if this query is a simple min() or max() query. Return ds@1952: ** zero if it is not. ds@1952: */ ds@1952: if( p->pGroupBy || p->pHaving || p->pWhere ) return 0; ds@1952: pSrc = p->pSrc; ds@1952: if( pSrc->nSrc!=1 ) return 0; ds@1952: pEList = p->pEList; ds@1952: if( pEList->nExpr!=1 ) return 0; ds@1952: pExpr = pEList->a[0].pExpr; ds@1952: if( pExpr->op!=TK_AGG_FUNCTION ) return 0; ds@1952: pList = pExpr->pList; ds@1952: if( pList==0 || pList->nExpr!=1 ) return 0; ds@1952: if( pExpr->token.n!=3 ) return 0; ds@1952: if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){ ds@1952: seekOp = OP_Rewind; ds@1952: }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){ ds@1952: seekOp = OP_Last; ds@1952: }else{ ds@1952: return 0; ds@1952: } ds@1952: pExpr = pList->a[0].pExpr; ds@1952: if( pExpr->op!=TK_COLUMN ) return 0; ds@1952: iCol = pExpr->iColumn; ds@1952: pTab = pSrc->a[0].pTab; ds@1952: ds@1952: /* This optimization cannot be used with virtual tables. */ ds@1952: if( IsVirtual(pTab) ) return 0; ds@1952: ds@1952: /* If we get to here, it means the query is of the correct form. ds@1952: ** Check to make sure we have an index and make pIdx point to the ds@1952: ** appropriate index. If the min() or max() is on an INTEGER PRIMARY ds@1952: ** key column, no index is necessary so set pIdx to NULL. If no ds@1952: ** usable index is found, return 0. ds@1952: */ ds@1952: if( iCol<0 ){ ds@1952: pIdx = 0; ds@1952: }else{ ds@1952: CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr); ds@1952: if( pColl==0 ) return 0; ds@1952: for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ ds@1952: assert( pIdx->nColumn>=1 ); ds@1952: if( pIdx->aiColumn[0]==iCol && ds@1952: 0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){ ds@1952: break; ds@1952: } ds@1952: } ds@1952: if( pIdx==0 ) return 0; ds@1952: } ds@1952: ds@1952: /* Identify column types if we will be using the callback. This ds@1952: ** step is skipped if the output is going to a table or a memory cell. ds@1952: ** The column names have already been generated in the calling function. ds@1952: */ ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v==0 ) return 0; ds@1952: ds@1952: /* If the output is destined for a temporary table, open that table. ds@1952: */ ds@1952: if( eDest==SRT_EphemTab ){ ds@1952: sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 1); ds@1952: } ds@1952: ds@1952: /* Generating code to find the min or the max. Basically all we have ds@1952: ** to do is find the first or the last entry in the chosen index. If ds@1952: ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first ds@1952: ** or last entry in the main table. ds@1952: */ ds@1952: iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); ds@1952: assert( iDb>=0 || pTab->isEphem ); ds@1952: sqlite3CodeVerifySchema(pParse, iDb); ds@1952: sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); ds@1952: base = pSrc->a[0].iCursor; ds@1952: brk = sqlite3VdbeMakeLabel(v); ds@1952: computeLimitRegisters(pParse, p, brk); ds@1952: if( pSrc->a[0].pSelect==0 ){ ds@1952: sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead); ds@1952: } ds@1952: if( pIdx==0 ){ ds@1952: sqlite3VdbeAddOp(v, seekOp, base, 0); ds@1952: }else{ ds@1952: /* Even though the cursor used to open the index here is closed ds@1952: ** as soon as a single value has been read from it, allocate it ds@1952: ** using (pParse->nTab++) to prevent the cursor id from being ds@1952: ** reused. This is important for statements of the form ds@1952: ** "INSERT INTO x SELECT max() FROM x". ds@1952: */ ds@1952: int iIdx; ds@1952: KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); ds@1952: iIdx = pParse->nTab++; ds@1952: assert( pIdx->pSchema==pTab->pSchema ); ds@1952: sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); ds@1952: sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum, ds@1952: (char*)pKey, P3_KEYINFO_HANDOFF); ds@1952: if( seekOp==OP_Rewind ){ ds@1952: sqlite3VdbeAddOp(v, OP_Null, 0, 0); ds@1952: sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0); ds@1952: seekOp = OP_MoveGt; ds@1952: } ds@1952: if( pIdx->aSortOrder[0]==SQLITE_SO_DESC ){ ds@1952: /* Ticket #2514: invert the seek operator if we are using ds@1952: ** a descending index. */ ds@1952: if( seekOp==OP_Last ){ ds@1952: seekOp = OP_Rewind; ds@1952: }else{ ds@1952: assert( seekOp==OP_MoveGt ); ds@1952: seekOp = OP_MoveLt; ds@1952: } ds@1952: } ds@1952: sqlite3VdbeAddOp(v, seekOp, iIdx, 0); ds@1952: sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0); ds@1952: sqlite3VdbeAddOp(v, OP_Close, iIdx, 0); ds@1952: sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); ds@1952: } ds@1952: eList.nExpr = 1; ds@1952: memset(&eListItem, 0, sizeof(eListItem)); ds@1952: eList.a = &eListItem; ds@1952: eList.a[0].pExpr = pExpr; ds@1952: selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0); ds@1952: sqlite3VdbeResolveLabel(v, brk); ds@1952: sqlite3VdbeAddOp(v, OP_Close, base, 0); ds@1952: ds@1952: return 1; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return ds@1952: ** the number of errors seen. ds@1952: ** ds@1952: ** An ORDER BY or GROUP BY is a list of expressions. If any expression ds@1952: ** is an integer constant, then that expression is replaced by the ds@1952: ** corresponding entry in the result set. ds@1952: */ ds@1952: static int processOrderGroupBy( ds@1952: NameContext *pNC, /* Name context of the SELECT statement. */ ds@1952: ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ ds@1952: const char *zType /* Either "ORDER" or "GROUP", as appropriate */ ds@1952: ){ ds@1952: int i; ds@1952: ExprList *pEList = pNC->pEList; /* The result set of the SELECT */ ds@1952: Parse *pParse = pNC->pParse; /* The result set of the SELECT */ ds@1952: assert( pEList ); ds@1952: ds@1952: if( pOrderBy==0 ) return 0; ds@1952: if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){ ds@1952: sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); ds@1952: return 1; ds@1952: } ds@1952: for(i=0; inExpr; i++){ ds@1952: int iCol; ds@1952: Expr *pE = pOrderBy->a[i].pExpr; ds@1952: if( sqlite3ExprIsInteger(pE, &iCol) ){ ds@1952: if( iCol>0 && iCol<=pEList->nExpr ){ ds@1952: CollSeq *pColl = pE->pColl; ds@1952: int flags = pE->flags & EP_ExpCollate; ds@1952: sqlite3ExprDelete(pE); ds@1952: pE = sqlite3ExprDup(pParse->db, pEList->a[iCol-1].pExpr); ds@1952: pOrderBy->a[i].pExpr = pE; ds@1952: if( pColl && flags ){ ds@1952: pE->pColl = pColl; ds@1952: pE->flags |= flags; ds@1952: } ds@1952: }else{ ds@1952: sqlite3ErrorMsg(pParse, ds@1952: "%s BY column number %d out of range - should be " ds@1952: "between 1 and %d", zType, iCol, pEList->nExpr); ds@1952: return 1; ds@1952: } ds@1952: } ds@1952: if( sqlite3ExprResolveNames(pNC, pE) ){ ds@1952: return 1; ds@1952: } ds@1952: } ds@1952: return 0; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine resolves any names used in the result set of the ds@1952: ** supplied SELECT statement. If the SELECT statement being resolved ds@1952: ** is a sub-select, then pOuterNC is a pointer to the NameContext ds@1952: ** of the parent SELECT. ds@1952: */ ds@1952: int sqlite3SelectResolve( ds@1952: Parse *pParse, /* The parser context */ ds@1952: Select *p, /* The SELECT statement being coded. */ ds@1952: NameContext *pOuterNC /* The outer name context. May be NULL. */ ds@1952: ){ ds@1952: ExprList *pEList; /* Result set. */ ds@1952: int i; /* For-loop variable used in multiple places */ ds@1952: NameContext sNC; /* Local name-context */ ds@1952: ExprList *pGroupBy; /* The group by clause */ ds@1952: ds@1952: /* If this routine has run before, return immediately. */ ds@1952: if( p->isResolved ){ ds@1952: assert( !pOuterNC ); ds@1952: return SQLITE_OK; ds@1952: } ds@1952: p->isResolved = 1; ds@1952: ds@1952: /* If there have already been errors, do nothing. */ ds@1952: if( pParse->nErr>0 ){ ds@1952: return SQLITE_ERROR; ds@1952: } ds@1952: ds@1952: /* Prepare the select statement. This call will allocate all cursors ds@1952: ** required to handle the tables and subqueries in the FROM clause. ds@1952: */ ds@1952: if( prepSelectStmt(pParse, p) ){ ds@1952: return SQLITE_ERROR; ds@1952: } ds@1952: ds@1952: /* Resolve the expressions in the LIMIT and OFFSET clauses. These ds@1952: ** are not allowed to refer to any names, so pass an empty NameContext. ds@1952: */ ds@1952: memset(&sNC, 0, sizeof(sNC)); ds@1952: sNC.pParse = pParse; ds@1952: if( sqlite3ExprResolveNames(&sNC, p->pLimit) || ds@1952: sqlite3ExprResolveNames(&sNC, p->pOffset) ){ ds@1952: return SQLITE_ERROR; ds@1952: } ds@1952: ds@1952: /* Set up the local name-context to pass to ExprResolveNames() to ds@1952: ** resolve the expression-list. ds@1952: */ ds@1952: sNC.allowAgg = 1; ds@1952: sNC.pSrcList = p->pSrc; ds@1952: sNC.pNext = pOuterNC; ds@1952: ds@1952: /* Resolve names in the result set. */ ds@1952: pEList = p->pEList; ds@1952: if( !pEList ) return SQLITE_ERROR; ds@1952: for(i=0; inExpr; i++){ ds@1952: Expr *pX = pEList->a[i].pExpr; ds@1952: if( sqlite3ExprResolveNames(&sNC, pX) ){ ds@1952: return SQLITE_ERROR; ds@1952: } ds@1952: } ds@1952: ds@1952: /* If there are no aggregate functions in the result-set, and no GROUP BY ds@1952: ** expression, do not allow aggregates in any of the other expressions. ds@1952: */ ds@1952: assert( !p->isAgg ); ds@1952: pGroupBy = p->pGroupBy; ds@1952: if( pGroupBy || sNC.hasAgg ){ ds@1952: p->isAgg = 1; ds@1952: }else{ ds@1952: sNC.allowAgg = 0; ds@1952: } ds@1952: ds@1952: /* If a HAVING clause is present, then there must be a GROUP BY clause. ds@1952: */ ds@1952: if( p->pHaving && !pGroupBy ){ ds@1952: sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); ds@1952: return SQLITE_ERROR; ds@1952: } ds@1952: ds@1952: /* Add the expression list to the name-context before parsing the ds@1952: ** other expressions in the SELECT statement. This is so that ds@1952: ** expressions in the WHERE clause (etc.) can refer to expressions by ds@1952: ** aliases in the result set. ds@1952: ** ds@1952: ** Minor point: If this is the case, then the expression will be ds@1952: ** re-evaluated for each reference to it. ds@1952: */ ds@1952: sNC.pEList = p->pEList; ds@1952: if( sqlite3ExprResolveNames(&sNC, p->pWhere) || ds@1952: sqlite3ExprResolveNames(&sNC, p->pHaving) ){ ds@1952: return SQLITE_ERROR; ds@1952: } ds@1952: if( p->pPrior==0 ){ ds@1952: if( processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") || ds@1952: processOrderGroupBy(&sNC, pGroupBy, "GROUP") ){ ds@1952: return SQLITE_ERROR; ds@1952: } ds@1952: } ds@1952: ds@1952: if( pParse->db->mallocFailed ){ ds@1952: return SQLITE_NOMEM; ds@1952: } ds@1952: ds@1952: /* Make sure the GROUP BY clause does not contain aggregate functions. ds@1952: */ ds@1952: if( pGroupBy ){ ds@1952: struct ExprList_item *pItem; ds@1952: ds@1952: for(i=0, pItem=pGroupBy->a; inExpr; i++, pItem++){ ds@1952: if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ ds@1952: sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " ds@1952: "the GROUP BY clause"); ds@1952: return SQLITE_ERROR; ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: /* If this is one SELECT of a compound, be sure to resolve names ds@1952: ** in the other SELECTs. ds@1952: */ ds@1952: if( p->pPrior ){ ds@1952: return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC); ds@1952: }else{ ds@1952: return SQLITE_OK; ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Reset the aggregate accumulator. ds@1952: ** ds@1952: ** The aggregate accumulator is a set of memory cells that hold ds@1952: ** intermediate results while calculating an aggregate. This ds@1952: ** routine simply stores NULLs in all of those memory cells. ds@1952: */ ds@1952: static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ ds@1952: Vdbe *v = pParse->pVdbe; ds@1952: int i; ds@1952: struct AggInfo_func *pFunc; ds@1952: if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ ds@1952: return; ds@1952: } ds@1952: for(i=0; inColumn; i++){ ds@1952: sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0); ds@1952: } ds@1952: for(pFunc=pAggInfo->aFunc, i=0; inFunc; i++, pFunc++){ ds@1952: sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0); ds@1952: if( pFunc->iDistinct>=0 ){ ds@1952: Expr *pE = pFunc->pExpr; ds@1952: if( pE->pList==0 || pE->pList->nExpr!=1 ){ ds@1952: sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed " ds@1952: "by an expression"); ds@1952: pFunc->iDistinct = -1; ds@1952: }else{ ds@1952: KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList); ds@1952: sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0, ds@1952: (char*)pKeyInfo, P3_KEYINFO_HANDOFF); ds@1952: } ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Invoke the OP_AggFinalize opcode for every aggregate function ds@1952: ** in the AggInfo structure. ds@1952: */ ds@1952: static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ ds@1952: Vdbe *v = pParse->pVdbe; ds@1952: int i; ds@1952: struct AggInfo_func *pF; ds@1952: for(i=0, pF=pAggInfo->aFunc; inFunc; i++, pF++){ ds@1952: ExprList *pList = pF->pExpr->pList; ds@1952: sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, ds@1952: (void*)pF->pFunc, P3_FUNCDEF); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Update the accumulator memory cells for an aggregate based on ds@1952: ** the current cursor position. ds@1952: */ ds@1952: static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ ds@1952: Vdbe *v = pParse->pVdbe; ds@1952: int i; ds@1952: struct AggInfo_func *pF; ds@1952: struct AggInfo_col *pC; ds@1952: ds@1952: pAggInfo->directMode = 1; ds@1952: for(i=0, pF=pAggInfo->aFunc; inFunc; i++, pF++){ ds@1952: int nArg; ds@1952: int addrNext = 0; ds@1952: ExprList *pList = pF->pExpr->pList; ds@1952: if( pList ){ ds@1952: nArg = pList->nExpr; ds@1952: sqlite3ExprCodeExprList(pParse, pList); ds@1952: }else{ ds@1952: nArg = 0; ds@1952: } ds@1952: if( pF->iDistinct>=0 ){ ds@1952: addrNext = sqlite3VdbeMakeLabel(v); ds@1952: assert( nArg==1 ); ds@1952: codeDistinct(v, pF->iDistinct, addrNext, 1); ds@1952: } ds@1952: if( pF->pFunc->needCollSeq ){ ds@1952: CollSeq *pColl = 0; ds@1952: struct ExprList_item *pItem; ds@1952: int j; ds@1952: assert( pList!=0 ); /* pList!=0 if pF->pFunc->needCollSeq is true */ ds@1952: for(j=0, pItem=pList->a; !pColl && jpExpr); ds@1952: } ds@1952: if( !pColl ){ ds@1952: pColl = pParse->db->pDfltColl; ds@1952: } ds@1952: sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ); ds@1952: } ds@1952: sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF); ds@1952: if( addrNext ){ ds@1952: sqlite3VdbeResolveLabel(v, addrNext); ds@1952: } ds@1952: } ds@1952: for(i=0, pC=pAggInfo->aCol; inAccumulator; i++, pC++){ ds@1952: sqlite3ExprCode(pParse, pC->pExpr); ds@1952: sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1); ds@1952: } ds@1952: pAggInfo->directMode = 0; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Generate code for the given SELECT statement. ds@1952: ** ds@1952: ** The results are distributed in various ways depending on the ds@1952: ** value of eDest and iParm. ds@1952: ** ds@1952: ** eDest Value Result ds@1952: ** ------------ ------------------------------------------- ds@1952: ** SRT_Callback Invoke the callback for each row of the result. ds@1952: ** ds@1952: ** SRT_Mem Store first result in memory cell iParm ds@1952: ** ds@1952: ** SRT_Set Store results as keys of table iParm. ds@1952: ** ds@1952: ** SRT_Union Store results as a key in a temporary table iParm ds@1952: ** ds@1952: ** SRT_Except Remove results from the temporary table iParm. ds@1952: ** ds@1952: ** SRT_Table Store results in temporary table iParm ds@1952: ** ds@1952: ** The table above is incomplete. Additional eDist value have be added ds@1952: ** since this comment was written. See the selectInnerLoop() function for ds@1952: ** a complete listing of the allowed values of eDest and their meanings. ds@1952: ** ds@1952: ** This routine returns the number of errors. If any errors are ds@1952: ** encountered, then an appropriate error message is left in ds@1952: ** pParse->zErrMsg. ds@1952: ** ds@1952: ** This routine does NOT free the Select structure passed in. The ds@1952: ** calling function needs to do that. ds@1952: ** ds@1952: ** The pParent, parentTab, and *pParentAgg fields are filled in if this ds@1952: ** SELECT is a subquery. This routine may try to combine this SELECT ds@1952: ** with its parent to form a single flat query. In so doing, it might ds@1952: ** change the parent query from a non-aggregate to an aggregate query. ds@1952: ** For that reason, the pParentAgg flag is passed as a pointer, so it ds@1952: ** can be changed. ds@1952: ** ds@1952: ** Example 1: The meaning of the pParent parameter. ds@1952: ** ds@1952: ** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3; ds@1952: ** \ \_______ subquery _______/ / ds@1952: ** \ / ds@1952: ** \____________________ outer query ___________________/ ds@1952: ** ds@1952: ** This routine is called for the outer query first. For that call, ds@1952: ** pParent will be NULL. During the processing of the outer query, this ds@1952: ** routine is called recursively to handle the subquery. For the recursive ds@1952: ** call, pParent will point to the outer query. Because the subquery is ds@1952: ** the second element in a three-way join, the parentTab parameter will ds@1952: ** be 1 (the 2nd value of a 0-indexed array.) ds@1952: */ ds@1952: int sqlite3Select( ds@1952: Parse *pParse, /* The parser context */ ds@1952: Select *p, /* The SELECT statement being coded. */ ds@1952: int eDest, /* How to dispose of the results */ ds@1952: int iParm, /* A parameter used by the eDest disposal method */ ds@1952: Select *pParent, /* Another SELECT for which this is a sub-query */ ds@1952: int parentTab, /* Index in pParent->pSrc of this query */ ds@1952: int *pParentAgg, /* True if pParent uses aggregate functions */ ds@1952: char *aff /* If eDest is SRT_Union, the affinity string */ ds@1952: ){ ds@1952: int i, j; /* Loop counters */ ds@1952: WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ ds@1952: Vdbe *v; /* The virtual machine under construction */ ds@1952: int isAgg; /* True for select lists like "count(*)" */ ds@1952: ExprList *pEList; /* List of columns to extract. */ ds@1952: SrcList *pTabList; /* List of tables to select from */ ds@1952: Expr *pWhere; /* The WHERE clause. May be NULL */ ds@1952: ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ ds@1952: ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ ds@1952: Expr *pHaving; /* The HAVING clause. May be NULL */ ds@1952: int isDistinct; /* True if the DISTINCT keyword is present */ ds@1952: int distinct; /* Table to use for the distinct set */ ds@1952: int rc = 1; /* Value to return from this function */ ds@1952: int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ ds@1952: AggInfo sAggInfo; /* Information used by aggregate queries */ ds@1952: int iEnd; /* Address of the end of the query */ ds@1952: sqlite3 *db; /* The database connection */ ds@1952: ds@1952: db = pParse->db; ds@1952: if( p==0 || db->mallocFailed || pParse->nErr ){ ds@1952: return 1; ds@1952: } ds@1952: if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; ds@1952: memset(&sAggInfo, 0, sizeof(sAggInfo)); ds@1952: ds@1952: #ifndef SQLITE_OMIT_COMPOUND_SELECT ds@1952: /* If there is are a sequence of queries, do the earlier ones first. ds@1952: */ ds@1952: if( p->pPrior ){ ds@1952: if( p->pRightmost==0 ){ ds@1952: Select *pLoop; ds@1952: int cnt = 0; ds@1952: for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ ds@1952: pLoop->pRightmost = p; ds@1952: } ds@1952: if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){ ds@1952: sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); ds@1952: return 1; ds@1952: } ds@1952: } ds@1952: return multiSelect(pParse, p, eDest, iParm, aff); ds@1952: } ds@1952: #endif ds@1952: ds@1952: pOrderBy = p->pOrderBy; ds@1952: if( IgnorableOrderby(eDest) ){ ds@1952: p->pOrderBy = 0; ds@1952: } ds@1952: if( sqlite3SelectResolve(pParse, p, 0) ){ ds@1952: goto select_end; ds@1952: } ds@1952: p->pOrderBy = pOrderBy; ds@1952: ds@1952: /* Make local copies of the parameters for this query. ds@1952: */ ds@1952: pTabList = p->pSrc; ds@1952: pWhere = p->pWhere; ds@1952: pGroupBy = p->pGroupBy; ds@1952: pHaving = p->pHaving; ds@1952: isAgg = p->isAgg; ds@1952: isDistinct = p->isDistinct; ds@1952: pEList = p->pEList; ds@1952: if( pEList==0 ) goto select_end; ds@1952: ds@1952: /* ds@1952: ** Do not even attempt to generate any code if we have already seen ds@1952: ** errors before this routine starts. ds@1952: */ ds@1952: if( pParse->nErr>0 ) goto select_end; ds@1952: ds@1952: /* If writing to memory or generating a set ds@1952: ** only a single column may be output. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_SUBQUERY ds@1952: if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){ ds@1952: goto select_end; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* ORDER BY is ignored for some destinations. ds@1952: */ ds@1952: if( IgnorableOrderby(eDest) ){ ds@1952: pOrderBy = 0; ds@1952: } ds@1952: ds@1952: /* Begin generating code. ds@1952: */ ds@1952: v = sqlite3GetVdbe(pParse); ds@1952: if( v==0 ) goto select_end; ds@1952: ds@1952: /* Generate code for all sub-queries in the FROM clause ds@1952: */ ds@1952: #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) ds@1952: for(i=0; inSrc; i++){ ds@1952: const char *zSavedAuthContext = 0; ds@1952: int needRestoreContext; ds@1952: struct SrcList_item *pItem = &pTabList->a[i]; ds@1952: ds@1952: if( pItem->pSelect==0 || pItem->isPopulated ) continue; ds@1952: if( pItem->zName!=0 ){ ds@1952: zSavedAuthContext = pParse->zAuthContext; ds@1952: pParse->zAuthContext = pItem->zName; ds@1952: needRestoreContext = 1; ds@1952: }else{ ds@1952: needRestoreContext = 0; ds@1952: } ds@1952: #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0 ds@1952: /* Increment Parse.nHeight by the height of the largest expression ds@1952: ** tree refered to by this, the parent select. The child select ds@1952: ** may contain expression trees of at most ds@1952: ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit ds@1952: ** more conservative than necessary, but much easier than enforcing ds@1952: ** an exact limit. ds@1952: */ ds@1952: pParse->nHeight += sqlite3SelectExprHeight(p); ds@1952: #endif ds@1952: sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab, ds@1952: pItem->iCursor, p, i, &isAgg, 0); ds@1952: #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0 ds@1952: pParse->nHeight -= sqlite3SelectExprHeight(p); ds@1952: #endif ds@1952: if( needRestoreContext ){ ds@1952: pParse->zAuthContext = zSavedAuthContext; ds@1952: } ds@1952: pTabList = p->pSrc; ds@1952: pWhere = p->pWhere; ds@1952: if( !IgnorableOrderby(eDest) ){ ds@1952: pOrderBy = p->pOrderBy; ds@1952: } ds@1952: pGroupBy = p->pGroupBy; ds@1952: pHaving = p->pHaving; ds@1952: isDistinct = p->isDistinct; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Check for the special case of a min() or max() function by itself ds@1952: ** in the result set. ds@1952: */ ds@1952: if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){ ds@1952: rc = 0; ds@1952: goto select_end; ds@1952: } ds@1952: ds@1952: /* Check to see if this is a subquery that can be "flattened" into its parent. ds@1952: ** If flattening is a possiblity, do so and return immediately. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_VIEW ds@1952: if( pParent && pParentAgg && ds@1952: flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){ ds@1952: if( isAgg ) *pParentAgg = 1; ds@1952: goto select_end; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* If there is an ORDER BY clause, then this sorting ds@1952: ** index might end up being unused if the data can be ds@1952: ** extracted in pre-sorted order. If that is the case, then the ds@1952: ** OP_OpenEphemeral instruction will be changed to an OP_Noop once ds@1952: ** we figure out that the sorting index is not needed. The addrSortIndex ds@1952: ** variable is used to facilitate that change. ds@1952: */ ds@1952: if( pOrderBy ){ ds@1952: KeyInfo *pKeyInfo; ds@1952: if( pParse->nErr ){ ds@1952: goto select_end; ds@1952: } ds@1952: pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); ds@1952: pOrderBy->iECursor = pParse->nTab++; ds@1952: p->addrOpenEphm[2] = addrSortIndex = ds@1952: sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2, (char*)pKeyInfo, P3_KEYINFO_HANDOFF); ds@1952: }else{ ds@1952: addrSortIndex = -1; ds@1952: } ds@1952: ds@1952: /* If the output is destined for a temporary table, open that table. ds@1952: */ ds@1952: if( eDest==SRT_EphemTab ){ ds@1952: sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr); ds@1952: } ds@1952: ds@1952: /* Set the limiter. ds@1952: */ ds@1952: iEnd = sqlite3VdbeMakeLabel(v); ds@1952: computeLimitRegisters(pParse, p, iEnd); ds@1952: ds@1952: /* Open a virtual index to use for the distinct set. ds@1952: */ ds@1952: if( isDistinct ){ ds@1952: KeyInfo *pKeyInfo; ds@1952: distinct = pParse->nTab++; ds@1952: pKeyInfo = keyInfoFromExprList(pParse, p->pEList); ds@1952: sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0, ds@1952: (char*)pKeyInfo, P3_KEYINFO_HANDOFF); ds@1952: }else{ ds@1952: distinct = -1; ds@1952: } ds@1952: ds@1952: /* Aggregate and non-aggregate queries are handled differently */ ds@1952: if( !isAgg && pGroupBy==0 ){ ds@1952: /* This case is for non-aggregate queries ds@1952: ** Begin the database scan ds@1952: */ ds@1952: pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy); ds@1952: if( pWInfo==0 ) goto select_end; ds@1952: ds@1952: /* If sorting index that was created by a prior OP_OpenEphemeral ds@1952: ** instruction ended up not being needed, then change the OP_OpenEphemeral ds@1952: ** into an OP_Noop. ds@1952: */ ds@1952: if( addrSortIndex>=0 && pOrderBy==0 ){ ds@1952: sqlite3VdbeChangeToNoop(v, addrSortIndex, 1); ds@1952: p->addrOpenEphm[2] = -1; ds@1952: } ds@1952: ds@1952: /* Use the standard inner loop ds@1952: */ ds@1952: if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest, ds@1952: iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){ ds@1952: goto select_end; ds@1952: } ds@1952: ds@1952: /* End the database scan loop. ds@1952: */ ds@1952: sqlite3WhereEnd(pWInfo); ds@1952: }else{ ds@1952: /* This is the processing for aggregate queries */ ds@1952: NameContext sNC; /* Name context for processing aggregate information */ ds@1952: int iAMem; /* First Mem address for storing current GROUP BY */ ds@1952: int iBMem; /* First Mem address for previous GROUP BY */ ds@1952: int iUseFlag; /* Mem address holding flag indicating that at least ds@1952: ** one row of the input to the aggregator has been ds@1952: ** processed */ ds@1952: int iAbortFlag; /* Mem address which causes query abort if positive */ ds@1952: int groupBySort; /* Rows come from source in GROUP BY order */ ds@1952: ds@1952: ds@1952: /* The following variables hold addresses or labels for parts of the ds@1952: ** virtual machine program we are putting together */ ds@1952: int addrOutputRow; /* Start of subroutine that outputs a result row */ ds@1952: int addrSetAbort; /* Set the abort flag and return */ ds@1952: int addrInitializeLoop; /* Start of code that initializes the input loop */ ds@1952: int addrTopOfLoop; /* Top of the input loop */ ds@1952: int addrGroupByChange; /* Code that runs when any GROUP BY term changes */ ds@1952: int addrProcessRow; /* Code to process a single input row */ ds@1952: int addrEnd; /* End of all processing */ ds@1952: int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ ds@1952: int addrReset; /* Subroutine for resetting the accumulator */ ds@1952: ds@1952: addrEnd = sqlite3VdbeMakeLabel(v); ds@1952: ds@1952: /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in ds@1952: ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the ds@1952: ** SELECT statement. ds@1952: */ ds@1952: memset(&sNC, 0, sizeof(sNC)); ds@1952: sNC.pParse = pParse; ds@1952: sNC.pSrcList = pTabList; ds@1952: sNC.pAggInfo = &sAggInfo; ds@1952: sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; ds@1952: sAggInfo.pGroupBy = pGroupBy; ds@1952: if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){ ds@1952: goto select_end; ds@1952: } ds@1952: if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){ ds@1952: goto select_end; ds@1952: } ds@1952: if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){ ds@1952: goto select_end; ds@1952: } ds@1952: sAggInfo.nAccumulator = sAggInfo.nColumn; ds@1952: for(i=0; ipList) ){ ds@1952: goto select_end; ds@1952: } ds@1952: } ds@1952: if( db->mallocFailed ) goto select_end; ds@1952: ds@1952: /* Processing for aggregates with GROUP BY is very different and ds@1952: ** much more complex tha aggregates without a GROUP BY. ds@1952: */ ds@1952: if( pGroupBy ){ ds@1952: KeyInfo *pKeyInfo; /* Keying information for the group by clause */ ds@1952: ds@1952: /* Create labels that we will be needing ds@1952: */ ds@1952: ds@1952: addrInitializeLoop = sqlite3VdbeMakeLabel(v); ds@1952: addrGroupByChange = sqlite3VdbeMakeLabel(v); ds@1952: addrProcessRow = sqlite3VdbeMakeLabel(v); ds@1952: ds@1952: /* If there is a GROUP BY clause we might need a sorting index to ds@1952: ** implement it. Allocate that sorting index now. If it turns out ds@1952: ** that we do not need it after all, the OpenEphemeral instruction ds@1952: ** will be converted into a Noop. ds@1952: */ ds@1952: sAggInfo.sortingIdx = pParse->nTab++; ds@1952: pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); ds@1952: addrSortingIdx = ds@1952: sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx, ds@1952: sAggInfo.nSortingColumn, ds@1952: (char*)pKeyInfo, P3_KEYINFO_HANDOFF); ds@1952: ds@1952: /* Initialize memory locations used by GROUP BY aggregate processing ds@1952: */ ds@1952: iUseFlag = pParse->nMem++; ds@1952: iAbortFlag = pParse->nMem++; ds@1952: iAMem = pParse->nMem; ds@1952: pParse->nMem += pGroupBy->nExpr; ds@1952: iBMem = pParse->nMem; ds@1952: pParse->nMem += pGroupBy->nExpr; ds@1952: sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag); ds@1952: VdbeComment((v, "# clear abort flag")); ds@1952: sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag); ds@1952: VdbeComment((v, "# indicate accumulator empty")); ds@1952: sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop); ds@1952: ds@1952: /* Generate a subroutine that outputs a single row of the result ds@1952: ** set. This subroutine first looks at the iUseFlag. If iUseFlag ds@1952: ** is less than or equal to zero, the subroutine is a no-op. If ds@1952: ** the processing calls for the query to abort, this subroutine ds@1952: ** increments the iAbortFlag memory location before returning in ds@1952: ** order to signal the caller to abort. ds@1952: */ ds@1952: addrSetAbort = sqlite3VdbeCurrentAddr(v); ds@1952: sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag); ds@1952: VdbeComment((v, "# set abort flag")); ds@1952: sqlite3VdbeAddOp(v, OP_Return, 0, 0); ds@1952: addrOutputRow = sqlite3VdbeCurrentAddr(v); ds@1952: sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2); ds@1952: VdbeComment((v, "# Groupby result generator entry point")); ds@1952: sqlite3VdbeAddOp(v, OP_Return, 0, 0); ds@1952: finalizeAggFunctions(pParse, &sAggInfo); ds@1952: if( pHaving ){ ds@1952: sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1); ds@1952: } ds@1952: rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, ds@1952: distinct, eDest, iParm, ds@1952: addrOutputRow+1, addrSetAbort, aff); ds@1952: if( rc ){ ds@1952: goto select_end; ds@1952: } ds@1952: sqlite3VdbeAddOp(v, OP_Return, 0, 0); ds@1952: VdbeComment((v, "# end groupby result generator")); ds@1952: ds@1952: /* Generate a subroutine that will reset the group-by accumulator ds@1952: */ ds@1952: addrReset = sqlite3VdbeCurrentAddr(v); ds@1952: resetAccumulator(pParse, &sAggInfo); ds@1952: sqlite3VdbeAddOp(v, OP_Return, 0, 0); ds@1952: ds@1952: /* Begin a loop that will extract all source rows in GROUP BY order. ds@1952: ** This might involve two separate loops with an OP_Sort in between, or ds@1952: ** it might be a single loop that uses an index to extract information ds@1952: ** in the right order to begin with. ds@1952: */ ds@1952: sqlite3VdbeResolveLabel(v, addrInitializeLoop); ds@1952: sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset); ds@1952: pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy); ds@1952: if( pWInfo==0 ) goto select_end; ds@1952: if( pGroupBy==0 ){ ds@1952: /* The optimizer is able to deliver rows in group by order so ds@1952: ** we do not have to sort. The OP_OpenEphemeral table will be ds@1952: ** cancelled later because we still need to use the pKeyInfo ds@1952: */ ds@1952: pGroupBy = p->pGroupBy; ds@1952: groupBySort = 0; ds@1952: }else{ ds@1952: /* Rows are coming out in undetermined order. We have to push ds@1952: ** each row into a sorting index, terminate the first loop, ds@1952: ** then loop over the sorting index in order to get the output ds@1952: ** in sorted order ds@1952: */ ds@1952: groupBySort = 1; ds@1952: sqlite3ExprCodeExprList(pParse, pGroupBy); ds@1952: sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0); ds@1952: j = pGroupBy->nExpr+1; ds@1952: for(i=0; iiSorterColumnpTab, pCol->iColumn, pCol->iTable); ds@1952: j++; ds@1952: } ds@1952: sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0); ds@1952: sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0); ds@1952: sqlite3WhereEnd(pWInfo); ds@1952: sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd); ds@1952: VdbeComment((v, "# GROUP BY sort")); ds@1952: sAggInfo.useSortingIdx = 1; ds@1952: } ds@1952: ds@1952: /* Evaluate the current GROUP BY terms and store in b0, b1, b2... ds@1952: ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) ds@1952: ** Then compare the current GROUP BY terms against the GROUP BY terms ds@1952: ** from the previous row currently stored in a0, a1, a2... ds@1952: */ ds@1952: addrTopOfLoop = sqlite3VdbeCurrentAddr(v); ds@1952: for(j=0; jnExpr; j++){ ds@1952: if( groupBySort ){ ds@1952: sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j); ds@1952: }else{ ds@1952: sAggInfo.directMode = 1; ds@1952: sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr); ds@1952: } ds@1952: sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, jnExpr-1); ds@1952: } ds@1952: for(j=pGroupBy->nExpr-1; j>=0; j--){ ds@1952: if( jnExpr-1 ){ ds@1952: sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0); ds@1952: } ds@1952: sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0); ds@1952: if( j==0 ){ ds@1952: sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow); ds@1952: }else{ ds@1952: sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange); ds@1952: } ds@1952: sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ); ds@1952: } ds@1952: ds@1952: /* Generate code that runs whenever the GROUP BY changes. ds@1952: ** Change in the GROUP BY are detected by the previous code ds@1952: ** block. If there were no changes, this block is skipped. ds@1952: ** ds@1952: ** This code copies current group by terms in b0,b1,b2,... ds@1952: ** over to a0,a1,a2. It then calls the output subroutine ds@1952: ** and resets the aggregate accumulator registers in preparation ds@1952: ** for the next GROUP BY batch. ds@1952: */ ds@1952: sqlite3VdbeResolveLabel(v, addrGroupByChange); ds@1952: for(j=0; jnExpr; j++){ ds@1952: sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j); ds@1952: } ds@1952: sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow); ds@1952: VdbeComment((v, "# output one row")); ds@1952: sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd); ds@1952: VdbeComment((v, "# check abort flag")); ds@1952: sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset); ds@1952: VdbeComment((v, "# reset accumulator")); ds@1952: ds@1952: /* Update the aggregate accumulators based on the content of ds@1952: ** the current row ds@1952: */ ds@1952: sqlite3VdbeResolveLabel(v, addrProcessRow); ds@1952: updateAccumulator(pParse, &sAggInfo); ds@1952: sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag); ds@1952: VdbeComment((v, "# indicate data in accumulator")); ds@1952: ds@1952: /* End of the loop ds@1952: */ ds@1952: if( groupBySort ){ ds@1952: sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop); ds@1952: }else{ ds@1952: sqlite3WhereEnd(pWInfo); ds@1952: sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1); ds@1952: } ds@1952: ds@1952: /* Output the final row of result ds@1952: */ ds@1952: sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow); ds@1952: VdbeComment((v, "# output final row")); ds@1952: ds@1952: } /* endif pGroupBy */ ds@1952: else { ds@1952: /* This case runs if the aggregate has no GROUP BY clause. The ds@1952: ** processing is much simpler since there is only a single row ds@1952: ** of output. ds@1952: */ ds@1952: resetAccumulator(pParse, &sAggInfo); ds@1952: pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0); ds@1952: if( pWInfo==0 ) goto select_end; ds@1952: updateAccumulator(pParse, &sAggInfo); ds@1952: sqlite3WhereEnd(pWInfo); ds@1952: finalizeAggFunctions(pParse, &sAggInfo); ds@1952: pOrderBy = 0; ds@1952: if( pHaving ){ ds@1952: sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1); ds@1952: } ds@1952: selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, ds@1952: eDest, iParm, addrEnd, addrEnd, aff); ds@1952: } ds@1952: sqlite3VdbeResolveLabel(v, addrEnd); ds@1952: ds@1952: } /* endif aggregate query */ ds@1952: ds@1952: /* If there is an ORDER BY clause, then we need to sort the results ds@1952: ** and send them to the callback one by one. ds@1952: */ ds@1952: if( pOrderBy ){ ds@1952: generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm); ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_SUBQUERY ds@1952: /* If this was a subquery, we have now converted the subquery into a ds@1952: ** temporary table. So set the SrcList_item.isPopulated flag to prevent ds@1952: ** this subquery from being evaluated again and to force the use of ds@1952: ** the temporary table. ds@1952: */ ds@1952: if( pParent ){ ds@1952: assert( pParent->pSrc->nSrc>parentTab ); ds@1952: assert( pParent->pSrc->a[parentTab].pSelect==p ); ds@1952: pParent->pSrc->a[parentTab].isPopulated = 1; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Jump here to skip this query ds@1952: */ ds@1952: sqlite3VdbeResolveLabel(v, iEnd); ds@1952: ds@1952: /* The SELECT was successfully coded. Set the return code to 0 ds@1952: ** to indicate no errors. ds@1952: */ ds@1952: rc = 0; ds@1952: ds@1952: /* Control jumps to here if an error is encountered above, or upon ds@1952: ** successful coding of the SELECT. ds@1952: */ ds@1952: select_end: ds@1952: ds@1952: /* Identify column names if we will be using them in a callback. This ds@1952: ** step is skipped if the output is going to some other destination. ds@1952: */ ds@1952: if( rc==SQLITE_OK && eDest==SRT_Callback ){ ds@1952: generateColumnNames(pParse, pTabList, pEList); ds@1952: } ds@1952: ds@1952: sqlite3_free(sAggInfo.aCol); ds@1952: sqlite3_free(sAggInfo.aFunc); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: #if defined(SQLITE_DEBUG) ds@1952: /* ds@1952: ******************************************************************************* ds@1952: ** The following code is used for testing and debugging only. The code ds@1952: ** that follows does not appear in normal builds. ds@1952: ** ds@1952: ** These routines are used to print out the content of all or part of a ds@1952: ** parse structures such as Select or Expr. Such printouts are useful ds@1952: ** for helping to understand what is happening inside the code generator ds@1952: ** during the execution of complex SELECT statements. ds@1952: ** ds@1952: ** These routine are not called anywhere from within the normal ds@1952: ** code base. Then are intended to be called from within the debugger ds@1952: ** or from temporary "printf" statements inserted for debugging. ds@1952: */ ds@1952: void sqlite3PrintExpr(Expr *p){ ds@1952: if( p->token.z && p->token.n>0 ){ ds@1952: sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z); ds@1952: }else{ ds@1952: sqlite3DebugPrintf("(%d", p->op); ds@1952: } ds@1952: if( p->pLeft ){ ds@1952: sqlite3DebugPrintf(" "); ds@1952: sqlite3PrintExpr(p->pLeft); ds@1952: } ds@1952: if( p->pRight ){ ds@1952: sqlite3DebugPrintf(" "); ds@1952: sqlite3PrintExpr(p->pRight); ds@1952: } ds@1952: sqlite3DebugPrintf(")"); ds@1952: } ds@1952: void sqlite3PrintExprList(ExprList *pList){ ds@1952: int i; ds@1952: for(i=0; inExpr; i++){ ds@1952: sqlite3PrintExpr(pList->a[i].pExpr); ds@1952: if( inExpr-1 ){ ds@1952: sqlite3DebugPrintf(", "); ds@1952: } ds@1952: } ds@1952: } ds@1952: void sqlite3PrintSelect(Select *p, int indent){ ds@1952: sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p); ds@1952: sqlite3PrintExprList(p->pEList); ds@1952: sqlite3DebugPrintf("\n"); ds@1952: if( p->pSrc ){ ds@1952: char *zPrefix; ds@1952: int i; ds@1952: zPrefix = "FROM"; ds@1952: for(i=0; ipSrc->nSrc; i++){ ds@1952: struct SrcList_item *pItem = &p->pSrc->a[i]; ds@1952: sqlite3DebugPrintf("%*s ", indent+6, zPrefix); ds@1952: zPrefix = ""; ds@1952: if( pItem->pSelect ){ ds@1952: sqlite3DebugPrintf("(\n"); ds@1952: sqlite3PrintSelect(pItem->pSelect, indent+10); ds@1952: sqlite3DebugPrintf("%*s)", indent+8, ""); ds@1952: }else if( pItem->zName ){ ds@1952: sqlite3DebugPrintf("%s", pItem->zName); ds@1952: } ds@1952: if( pItem->pTab ){ ds@1952: sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName); ds@1952: } ds@1952: if( pItem->zAlias ){ ds@1952: sqlite3DebugPrintf(" AS %s", pItem->zAlias); ds@1952: } ds@1952: if( ipSrc->nSrc-1 ){ ds@1952: sqlite3DebugPrintf(","); ds@1952: } ds@1952: sqlite3DebugPrintf("\n"); ds@1952: } ds@1952: } ds@1952: if( p->pWhere ){ ds@1952: sqlite3DebugPrintf("%*s WHERE ", indent, ""); ds@1952: sqlite3PrintExpr(p->pWhere); ds@1952: sqlite3DebugPrintf("\n"); ds@1952: } ds@1952: if( p->pGroupBy ){ ds@1952: sqlite3DebugPrintf("%*s GROUP BY ", indent, ""); ds@1952: sqlite3PrintExprList(p->pGroupBy); ds@1952: sqlite3DebugPrintf("\n"); ds@1952: } ds@1952: if( p->pHaving ){ ds@1952: sqlite3DebugPrintf("%*s HAVING ", indent, ""); ds@1952: sqlite3PrintExpr(p->pHaving); ds@1952: sqlite3DebugPrintf("\n"); ds@1952: } ds@1952: if( p->pOrderBy ){ ds@1952: sqlite3DebugPrintf("%*s ORDER BY ", indent, ""); ds@1952: sqlite3PrintExprList(p->pOrderBy); ds@1952: sqlite3DebugPrintf("\n"); ds@1952: } ds@1952: } ds@1952: /* End of the structure debug printing code ds@1952: *****************************************************************************/ ds@1952: #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */