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