~oif-team/ubuntu/natty/qt4-x11/xi2.1

« back to all changes in this revision

Viewing changes to src/3rdparty/sqlite/select.c

  • Committer: Bazaar Package Importer
  • Author(s): Adam Conrad
  • Date: 2005-08-24 04:09:09 UTC
  • Revision ID: james.westby@ubuntu.com-20050824040909-xmxe9jfr4a0w5671
Tags: upstream-4.0.0
ImportĀ upstreamĀ versionĀ 4.0.0

Show diffs side-by-side

added added

removed removed

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