xref: /illumos-gate/usr/src/lib/libsqlite/src/expr.c (revision 55fea89dcaa64928bed4327112404dcb3e07b79f)
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 routines used for analyzing expressions and
13 ** for generating VDBE code that evaluates expressions in SQLite.
14 **
15 ** $Id: expr.c,v 1.114.2.3 2004/07/22 17:10:10 drh Exp $
16 */
17 #include "sqliteInt.h"
18 #include <ctype.h>
19 
20 /*
21 ** Construct a new expression node and return a pointer to it.  Memory
22 ** for this node is obtained from sqliteMalloc().  The calling function
23 ** is responsible for making sure the node eventually gets freed.
24 */
sqliteExpr(int op,Expr * pLeft,Expr * pRight,Token * pToken)25 Expr *sqliteExpr(int op, Expr *pLeft, Expr *pRight, Token *pToken){
26   Expr *pNew;
27   pNew = sqliteMalloc( sizeof(Expr) );
28   if( pNew==0 ){
29     /* When malloc fails, we leak memory from pLeft and pRight */
30     return 0;
31   }
32   pNew->op = op;
33   pNew->pLeft = pLeft;
34   pNew->pRight = pRight;
35   if( pToken ){
36     assert( pToken->dyn==0 );
37     pNew->token = *pToken;
38     pNew->span = *pToken;
39   }else{
40     assert( pNew->token.dyn==0 );
41     assert( pNew->token.z==0 );
42     assert( pNew->token.n==0 );
43     if( pLeft && pRight ){
44       sqliteExprSpan(pNew, &pLeft->span, &pRight->span);
45     }else{
46       pNew->span = pNew->token;
47     }
48   }
49   return pNew;
50 }
51 
52 /*
53 ** Set the Expr.span field of the given expression to span all
54 ** text between the two given tokens.
55 */
sqliteExprSpan(Expr * pExpr,Token * pLeft,Token * pRight)56 void sqliteExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
57   assert( pRight!=0 );
58   assert( pLeft!=0 );
59   /* Note: pExpr might be NULL due to a prior malloc failure */
60   if( pExpr && pRight->z && pLeft->z ){
61     if( pLeft->dyn==0 && pRight->dyn==0 ){
62       pExpr->span.z = pLeft->z;
63       pExpr->span.n = pRight->n + Addr(pRight->z) - Addr(pLeft->z);
64     }else{
65       pExpr->span.z = 0;
66     }
67   }
68 }
69 
70 /*
71 ** Construct a new expression node for a function with multiple
72 ** arguments.
73 */
sqliteExprFunction(ExprList * pList,Token * pToken)74 Expr *sqliteExprFunction(ExprList *pList, Token *pToken){
75   Expr *pNew;
76   pNew = sqliteMalloc( sizeof(Expr) );
77   if( pNew==0 ){
78     /* sqliteExprListDelete(pList); // Leak pList when malloc fails */
79     return 0;
80   }
81   pNew->op = TK_FUNCTION;
82   pNew->pList = pList;
83   if( pToken ){
84     assert( pToken->dyn==0 );
85     pNew->token = *pToken;
86   }else{
87     pNew->token.z = 0;
88   }
89   pNew->span = pNew->token;
90   return pNew;
91 }
92 
93 /*
94 ** Recursively delete an expression tree.
95 */
sqliteExprDelete(Expr * p)96 void sqliteExprDelete(Expr *p){
97   if( p==0 ) return;
98   if( p->span.dyn ) sqliteFree((char*)p->span.z);
99   if( p->token.dyn ) sqliteFree((char*)p->token.z);
100   sqliteExprDelete(p->pLeft);
101   sqliteExprDelete(p->pRight);
102   sqliteExprListDelete(p->pList);
103   sqliteSelectDelete(p->pSelect);
104   sqliteFree(p);
105 }
106 
107 
108 /*
109 ** The following group of routines make deep copies of expressions,
110 ** expression lists, ID lists, and select statements.  The copies can
111 ** be deleted (by being passed to their respective ...Delete() routines)
112 ** without effecting the originals.
113 **
114 ** The expression list, ID, and source lists return by sqliteExprListDup(),
115 ** sqliteIdListDup(), and sqliteSrcListDup() can not be further expanded
116 ** by subsequent calls to sqlite*ListAppend() routines.
117 **
118 ** Any tables that the SrcList might point to are not duplicated.
119 */
sqliteExprDup(Expr * p)120 Expr *sqliteExprDup(Expr *p){
121   Expr *pNew;
122   if( p==0 ) return 0;
123   pNew = sqliteMallocRaw( sizeof(*p) );
124   if( pNew==0 ) return 0;
125   memcpy(pNew, p, sizeof(*pNew));
126   if( p->token.z!=0 ){
127     pNew->token.z = sqliteStrDup(p->token.z);
128     pNew->token.dyn = 1;
129   }else{
130     assert( pNew->token.z==0 );
131   }
132   pNew->span.z = 0;
133   pNew->pLeft = sqliteExprDup(p->pLeft);
134   pNew->pRight = sqliteExprDup(p->pRight);
135   pNew->pList = sqliteExprListDup(p->pList);
136   pNew->pSelect = sqliteSelectDup(p->pSelect);
137   return pNew;
138 }
sqliteTokenCopy(Token * pTo,Token * pFrom)139 void sqliteTokenCopy(Token *pTo, Token *pFrom){
140   if( pTo->dyn ) sqliteFree((char*)pTo->z);
141   if( pFrom->z ){
142     pTo->n = pFrom->n;
143     pTo->z = sqliteStrNDup(pFrom->z, pFrom->n);
144     pTo->dyn = 1;
145   }else{
146     pTo->z = 0;
147   }
148 }
sqliteExprListDup(ExprList * p)149 ExprList *sqliteExprListDup(ExprList *p){
150   ExprList *pNew;
151   struct ExprList_item *pItem;
152   int i;
153   if( p==0 ) return 0;
154   pNew = sqliteMalloc( sizeof(*pNew) );
155   if( pNew==0 ) return 0;
156   pNew->nExpr = pNew->nAlloc = p->nExpr;
157   pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
158   if( pItem==0 ){
159     sqliteFree(pNew);
160     return 0;
161   }
162   for(i=0; i<p->nExpr; i++, pItem++){
163     Expr *pNewExpr, *pOldExpr;
164     pItem->pExpr = pNewExpr = sqliteExprDup(pOldExpr = p->a[i].pExpr);
165     if( pOldExpr->span.z!=0 && pNewExpr ){
166       /* Always make a copy of the span for top-level expressions in the
167       ** expression list.  The logic in SELECT processing that determines
168       ** the names of columns in the result set needs this information */
169       sqliteTokenCopy(&pNewExpr->span, &pOldExpr->span);
170     }
171     assert( pNewExpr==0 || pNewExpr->span.z!=0
172             || pOldExpr->span.z==0 || sqlite_malloc_failed );
173     pItem->zName = sqliteStrDup(p->a[i].zName);
174     pItem->sortOrder = p->a[i].sortOrder;
175     pItem->isAgg = p->a[i].isAgg;
176     pItem->done = 0;
177   }
178   return pNew;
179 }
sqliteSrcListDup(SrcList * p)180 SrcList *sqliteSrcListDup(SrcList *p){
181   SrcList *pNew;
182   int i;
183   int nByte;
184   if( p==0 ) return 0;
185   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
186   pNew = sqliteMallocRaw( nByte );
187   if( pNew==0 ) return 0;
188   pNew->nSrc = pNew->nAlloc = p->nSrc;
189   for(i=0; i<p->nSrc; i++){
190     struct SrcList_item *pNewItem = &pNew->a[i];
191     struct SrcList_item *pOldItem = &p->a[i];
192     pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
193     pNewItem->zName = sqliteStrDup(pOldItem->zName);
194     pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
195     pNewItem->jointype = pOldItem->jointype;
196     pNewItem->iCursor = pOldItem->iCursor;
197     pNewItem->pTab = 0;
198     pNewItem->pSelect = sqliteSelectDup(pOldItem->pSelect);
199     pNewItem->pOn = sqliteExprDup(pOldItem->pOn);
200     pNewItem->pUsing = sqliteIdListDup(pOldItem->pUsing);
201   }
202   return pNew;
203 }
sqliteIdListDup(IdList * p)204 IdList *sqliteIdListDup(IdList *p){
205   IdList *pNew;
206   int i;
207   if( p==0 ) return 0;
208   pNew = sqliteMallocRaw( sizeof(*pNew) );
209   if( pNew==0 ) return 0;
210   pNew->nId = pNew->nAlloc = p->nId;
211   pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
212   if( pNew->a==0 ) return 0;
213   for(i=0; i<p->nId; i++){
214     struct IdList_item *pNewItem = &pNew->a[i];
215     struct IdList_item *pOldItem = &p->a[i];
216     pNewItem->zName = sqliteStrDup(pOldItem->zName);
217     pNewItem->idx = pOldItem->idx;
218   }
219   return pNew;
220 }
sqliteSelectDup(Select * p)221 Select *sqliteSelectDup(Select *p){
222   Select *pNew;
223   if( p==0 ) return 0;
224   pNew = sqliteMallocRaw( sizeof(*p) );
225   if( pNew==0 ) return 0;
226   pNew->isDistinct = p->isDistinct;
227   pNew->pEList = sqliteExprListDup(p->pEList);
228   pNew->pSrc = sqliteSrcListDup(p->pSrc);
229   pNew->pWhere = sqliteExprDup(p->pWhere);
230   pNew->pGroupBy = sqliteExprListDup(p->pGroupBy);
231   pNew->pHaving = sqliteExprDup(p->pHaving);
232   pNew->pOrderBy = sqliteExprListDup(p->pOrderBy);
233   pNew->op = p->op;
234   pNew->pPrior = sqliteSelectDup(p->pPrior);
235   pNew->nLimit = p->nLimit;
236   pNew->nOffset = p->nOffset;
237   pNew->zSelect = 0;
238   pNew->iLimit = -1;
239   pNew->iOffset = -1;
240   return pNew;
241 }
242 
243 
244 /*
245 ** Add a new element to the end of an expression list.  If pList is
246 ** initially NULL, then create a new expression list.
247 */
sqliteExprListAppend(ExprList * pList,Expr * pExpr,Token * pName)248 ExprList *sqliteExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
249   if( pList==0 ){
250     pList = sqliteMalloc( sizeof(ExprList) );
251     if( pList==0 ){
252       /* sqliteExprDelete(pExpr); // Leak memory if malloc fails */
253       return 0;
254     }
255     assert( pList->nAlloc==0 );
256   }
257   if( pList->nAlloc<=pList->nExpr ){
258     pList->nAlloc = pList->nAlloc*2 + 4;
259     pList->a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]));
260     if( pList->a==0 ){
261       /* sqliteExprDelete(pExpr); // Leak memory if malloc fails */
262       pList->nExpr = pList->nAlloc = 0;
263       return pList;
264     }
265   }
266   assert( pList->a!=0 );
267   if( pExpr || pName ){
268     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
269     memset(pItem, 0, sizeof(*pItem));
270     pItem->pExpr = pExpr;
271     if( pName ){
272       sqliteSetNString(&pItem->zName, pName->z, pName->n, 0);
273       sqliteDequote(pItem->zName);
274     }
275   }
276   return pList;
277 }
278 
279 /*
280 ** Delete an entire expression list.
281 */
sqliteExprListDelete(ExprList * pList)282 void sqliteExprListDelete(ExprList *pList){
283   int i;
284   if( pList==0 ) return;
285   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
286   assert( pList->nExpr<=pList->nAlloc );
287   for(i=0; i<pList->nExpr; i++){
288     sqliteExprDelete(pList->a[i].pExpr);
289     sqliteFree(pList->a[i].zName);
290   }
291   sqliteFree(pList->a);
292   sqliteFree(pList);
293 }
294 
295 /*
296 ** Walk an expression tree.  Return 1 if the expression is constant
297 ** and 0 if it involves variables.
298 **
299 ** For the purposes of this function, a double-quoted string (ex: "abc")
300 ** is considered a variable but a single-quoted string (ex: 'abc') is
301 ** a constant.
302 */
sqliteExprIsConstant(Expr * p)303 int sqliteExprIsConstant(Expr *p){
304   switch( p->op ){
305     case TK_ID:
306     case TK_COLUMN:
307     case TK_DOT:
308     case TK_FUNCTION:
309       return 0;
310     case TK_NULL:
311     case TK_STRING:
312     case TK_INTEGER:
313     case TK_FLOAT:
314     case TK_VARIABLE:
315       return 1;
316     default: {
317       if( p->pLeft && !sqliteExprIsConstant(p->pLeft) ) return 0;
318       if( p->pRight && !sqliteExprIsConstant(p->pRight) ) return 0;
319       if( p->pList ){
320         int i;
321         for(i=0; i<p->pList->nExpr; i++){
322           if( !sqliteExprIsConstant(p->pList->a[i].pExpr) ) return 0;
323         }
324       }
325       return p->pLeft!=0 || p->pRight!=0 || (p->pList && p->pList->nExpr>0);
326     }
327   }
328   return 0;
329 }
330 
331 /*
332 ** If the given expression codes a constant integer that is small enough
333 ** to fit in a 32-bit integer, return 1 and put the value of the integer
334 ** in *pValue.  If the expression is not an integer or if it is too big
335 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
336 */
sqliteExprIsInteger(Expr * p,int * pValue)337 int sqliteExprIsInteger(Expr *p, int *pValue){
338   switch( p->op ){
339     case TK_INTEGER: {
340       if( sqliteFitsIn32Bits(p->token.z) ){
341         *pValue = atoi(p->token.z);
342         return 1;
343       }
344       break;
345     }
346     case TK_STRING: {
347       const char *z = p->token.z;
348       int n = p->token.n;
349       if( n>0 && z[0]=='-' ){ z++; n--; }
350       while( n>0 && *z && isdigit(*z) ){ z++; n--; }
351       if( n==0 && sqliteFitsIn32Bits(p->token.z) ){
352         *pValue = atoi(p->token.z);
353         return 1;
354       }
355       break;
356     }
357     case TK_UPLUS: {
358       return sqliteExprIsInteger(p->pLeft, pValue);
359     }
360     case TK_UMINUS: {
361       int v;
362       if( sqliteExprIsInteger(p->pLeft, &v) ){
363         *pValue = -v;
364         return 1;
365       }
366       break;
367     }
368     default: break;
369   }
370   return 0;
371 }
372 
373 /*
374 ** Return TRUE if the given string is a row-id column name.
375 */
sqliteIsRowid(const char * z)376 int sqliteIsRowid(const char *z){
377   if( sqliteStrICmp(z, "_ROWID_")==0 ) return 1;
378   if( sqliteStrICmp(z, "ROWID")==0 ) return 1;
379   if( sqliteStrICmp(z, "OID")==0 ) return 1;
380   return 0;
381 }
382 
383 /*
384 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
385 ** that name in the set of source tables in pSrcList and make the pExpr
386 ** expression node refer back to that source column.  The following changes
387 ** are made to pExpr:
388 **
389 **    pExpr->iDb           Set the index in db->aDb[] of the database holding
390 **                         the table.
391 **    pExpr->iTable        Set to the cursor number for the table obtained
392 **                         from pSrcList.
393 **    pExpr->iColumn       Set to the column number within the table.
394 **    pExpr->dataType      Set to the appropriate data type for the column.
395 **    pExpr->op            Set to TK_COLUMN.
396 **    pExpr->pLeft         Any expression this points to is deleted
397 **    pExpr->pRight        Any expression this points to is deleted.
398 **
399 ** The pDbToken is the name of the database (the "X").  This value may be
400 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
401 ** can be used.  The pTableToken is the name of the table (the "Y").  This
402 ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
403 ** means that the form of the name is Z and that columns from any table
404 ** can be used.
405 **
406 ** If the name cannot be resolved unambiguously, leave an error message
407 ** in pParse and return non-zero.  Return zero on success.
408 */
lookupName(Parse * pParse,Token * pDbToken,Token * pTableToken,Token * pColumnToken,SrcList * pSrcList,ExprList * pEList,Expr * pExpr)409 static int lookupName(
410   Parse *pParse,      /* The parsing context */
411   Token *pDbToken,     /* Name of the database containing table, or NULL */
412   Token *pTableToken,  /* Name of table containing column, or NULL */
413   Token *pColumnToken, /* Name of the column. */
414   SrcList *pSrcList,   /* List of tables used to resolve column names */
415   ExprList *pEList,    /* List of expressions used to resolve "AS" */
416   Expr *pExpr          /* Make this EXPR node point to the selected column */
417 ){
418   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
419   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
420   char *zCol = 0;      /* Name of the column.  The "Z" */
421   int i, j;            /* Loop counters */
422   int cnt = 0;         /* Number of matching column names */
423   int cntTab = 0;      /* Number of matching table names */
424   sqlite *db = pParse->db;  /* The database */
425 
426   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
427   if( pDbToken && pDbToken->z ){
428     zDb = sqliteStrNDup(pDbToken->z, pDbToken->n);
429     sqliteDequote(zDb);
430   }else{
431     zDb = 0;
432   }
433   if( pTableToken && pTableToken->z ){
434     zTab = sqliteStrNDup(pTableToken->z, pTableToken->n);
435     sqliteDequote(zTab);
436   }else{
437     assert( zDb==0 );
438     zTab = 0;
439   }
440   zCol = sqliteStrNDup(pColumnToken->z, pColumnToken->n);
441   sqliteDequote(zCol);
442   if( sqlite_malloc_failed ){
443     return 1;  /* Leak memory (zDb and zTab) if malloc fails */
444   }
445   assert( zTab==0 || pEList==0 );
446 
447   pExpr->iTable = -1;
448   for(i=0; i<pSrcList->nSrc; i++){
449     struct SrcList_item *pItem = &pSrcList->a[i];
450     Table *pTab = pItem->pTab;
451     Column *pCol;
452 
453     if( pTab==0 ) continue;
454     assert( pTab->nCol>0 );
455     if( zTab ){
456       if( pItem->zAlias ){
457         char *zTabName = pItem->zAlias;
458         if( sqliteStrICmp(zTabName, zTab)!=0 ) continue;
459       }else{
460         char *zTabName = pTab->zName;
461         if( zTabName==0 || sqliteStrICmp(zTabName, zTab)!=0 ) continue;
462         if( zDb!=0 && sqliteStrICmp(db->aDb[pTab->iDb].zName, zDb)!=0 ){
463           continue;
464         }
465       }
466     }
467     if( 0==(cntTab++) ){
468       pExpr->iTable = pItem->iCursor;
469       pExpr->iDb = pTab->iDb;
470     }
471     for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
472       if( sqliteStrICmp(pCol->zName, zCol)==0 ){
473         cnt++;
474         pExpr->iTable = pItem->iCursor;
475         pExpr->iDb = pTab->iDb;
476         /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
477         pExpr->iColumn = j==pTab->iPKey ? -1 : j;
478         pExpr->dataType = pCol->sortOrder & SQLITE_SO_TYPEMASK;
479         break;
480       }
481     }
482   }
483 
484   /* If we have not already resolved the name, then maybe
485   ** it is a new.* or old.* trigger argument reference
486   */
487   if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
488     TriggerStack *pTriggerStack = pParse->trigStack;
489     Table *pTab = 0;
490     if( pTriggerStack->newIdx != -1 && sqliteStrICmp("new", zTab) == 0 ){
491       pExpr->iTable = pTriggerStack->newIdx;
492       assert( pTriggerStack->pTab );
493       pTab = pTriggerStack->pTab;
494     }else if( pTriggerStack->oldIdx != -1 && sqliteStrICmp("old", zTab) == 0 ){
495       pExpr->iTable = pTriggerStack->oldIdx;
496       assert( pTriggerStack->pTab );
497       pTab = pTriggerStack->pTab;
498     }
499 
500     if( pTab ){
501       int j;
502       Column *pCol = pTab->aCol;
503 
504       pExpr->iDb = pTab->iDb;
505       cntTab++;
506       for(j=0; j < pTab->nCol; j++, pCol++) {
507         if( sqliteStrICmp(pCol->zName, zCol)==0 ){
508           cnt++;
509           pExpr->iColumn = j==pTab->iPKey ? -1 : j;
510           pExpr->dataType = pCol->sortOrder & SQLITE_SO_TYPEMASK;
511           break;
512         }
513       }
514     }
515   }
516 
517   /*
518   ** Perhaps the name is a reference to the ROWID
519   */
520   if( cnt==0 && cntTab==1 && sqliteIsRowid(zCol) ){
521     cnt = 1;
522     pExpr->iColumn = -1;
523     pExpr->dataType = SQLITE_SO_NUM;
524   }
525 
526   /*
527   ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
528   ** might refer to an result-set alias.  This happens, for example, when
529   ** we are resolving names in the WHERE clause of the following command:
530   **
531   **     SELECT a+b AS x FROM table WHERE x<10;
532   **
533   ** In cases like this, replace pExpr with a copy of the expression that
534   ** forms the result set entry ("a+b" in the example) and return immediately.
535   ** Note that the expression in the result set should have already been
536   ** resolved by the time the WHERE clause is resolved.
537   */
538   if( cnt==0 && pEList!=0 ){
539     for(j=0; j<pEList->nExpr; j++){
540       char *zAs = pEList->a[j].zName;
541       if( zAs!=0 && sqliteStrICmp(zAs, zCol)==0 ){
542         assert( pExpr->pLeft==0 && pExpr->pRight==0 );
543         pExpr->op = TK_AS;
544         pExpr->iColumn = j;
545         pExpr->pLeft = sqliteExprDup(pEList->a[j].pExpr);
546         sqliteFree(zCol);
547         assert( zTab==0 && zDb==0 );
548         return 0;
549       }
550     }
551   }
552 
553   /*
554   ** If X and Y are NULL (in other words if only the column name Z is
555   ** supplied) and the value of Z is enclosed in double-quotes, then
556   ** Z is a string literal if it doesn't match any column names.  In that
557   ** case, we need to return right away and not make any changes to
558   ** pExpr.
559   */
560   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
561     sqliteFree(zCol);
562     return 0;
563   }
564 
565   /*
566   ** cnt==0 means there was not match.  cnt>1 means there were two or
567   ** more matches.  Either way, we have an error.
568   */
569   if( cnt!=1 ){
570     char *z = 0;
571     char *zErr;
572     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
573     if( zDb ){
574       sqliteSetString(&z, zDb, ".", zTab, ".", zCol, 0);
575     }else if( zTab ){
576       sqliteSetString(&z, zTab, ".", zCol, 0);
577     }else{
578       z = sqliteStrDup(zCol);
579     }
580     sqliteErrorMsg(pParse, zErr, z);
581     sqliteFree(z);
582   }
583 
584   /* Clean up and return
585   */
586   sqliteFree(zDb);
587   sqliteFree(zTab);
588   sqliteFree(zCol);
589   sqliteExprDelete(pExpr->pLeft);
590   pExpr->pLeft = 0;
591   sqliteExprDelete(pExpr->pRight);
592   pExpr->pRight = 0;
593   pExpr->op = TK_COLUMN;
594   sqliteAuthRead(pParse, pExpr, pSrcList);
595   return cnt!=1;
596 }
597 
598 /*
599 ** This routine walks an expression tree and resolves references to
600 ** table columns.  Nodes of the form ID.ID or ID resolve into an
601 ** index to the table in the table list and a column offset.  The
602 ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
603 ** value is changed to the index of the referenced table in pTabList
604 ** plus the "base" value.  The base value will ultimately become the
605 ** VDBE cursor number for a cursor that is pointing into the referenced
606 ** table.  The Expr.iColumn value is changed to the index of the column
607 ** of the referenced table.  The Expr.iColumn value for the special
608 ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
609 ** alias for ROWID.
610 **
611 ** We also check for instances of the IN operator.  IN comes in two
612 ** forms:
613 **
614 **           expr IN (exprlist)
615 ** and
616 **           expr IN (SELECT ...)
617 **
618 ** The first form is handled by creating a set holding the list
619 ** of allowed values.  The second form causes the SELECT to generate
620 ** a temporary table.
621 **
622 ** This routine also looks for scalar SELECTs that are part of an expression.
623 ** If it finds any, it generates code to write the value of that select
624 ** into a memory cell.
625 **
626 ** Unknown columns or tables provoke an error.  The function returns
627 ** the number of errors seen and leaves an error message on pParse->zErrMsg.
628 */
sqliteExprResolveIds(Parse * pParse,SrcList * pSrcList,ExprList * pEList,Expr * pExpr)629 int sqliteExprResolveIds(
630   Parse *pParse,     /* The parser context */
631   SrcList *pSrcList, /* List of tables used to resolve column names */
632   ExprList *pEList,  /* List of expressions used to resolve "AS" */
633   Expr *pExpr        /* The expression to be analyzed. */
634 ){
635   int i;
636 
637   if( pExpr==0 || pSrcList==0 ) return 0;
638   for(i=0; i<pSrcList->nSrc; i++){
639     assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab );
640   }
641   switch( pExpr->op ){
642     /* Double-quoted strings (ex: "abc") are used as identifiers if
643     ** possible.  Otherwise they remain as strings.  Single-quoted
644     ** strings (ex: 'abc') are always string literals.
645     */
646     case TK_STRING: {
647       if( pExpr->token.z[0]=='\'' ) break;
648       /* Fall thru into the TK_ID case if this is a double-quoted string */
649     }
650     /* A lone identifier is the name of a columnd.
651     */
652     /* FALLTHROUGH */
653     case TK_ID: {
654       if( lookupName(pParse, 0, 0, &pExpr->token, pSrcList, pEList, pExpr) ){
655         return 1;
656       }
657       break;
658     }
659 
660     /* A table name and column name:     ID.ID
661     ** Or a database, table and column:  ID.ID.ID
662     */
663     case TK_DOT: {
664       Token *pColumn;
665       Token *pTable;
666       Token *pDb;
667       Expr *pRight;
668 
669       pRight = pExpr->pRight;
670       if( pRight->op==TK_ID ){
671         pDb = 0;
672         pTable = &pExpr->pLeft->token;
673         pColumn = &pRight->token;
674       }else{
675         assert( pRight->op==TK_DOT );
676         pDb = &pExpr->pLeft->token;
677         pTable = &pRight->pLeft->token;
678         pColumn = &pRight->pRight->token;
679       }
680       if( lookupName(pParse, pDb, pTable, pColumn, pSrcList, 0, pExpr) ){
681         return 1;
682       }
683       break;
684     }
685 
686     case TK_IN: {
687       Vdbe *v = sqliteGetVdbe(pParse);
688       if( v==0 ) return 1;
689       if( sqliteExprResolveIds(pParse, pSrcList, pEList, pExpr->pLeft) ){
690         return 1;
691       }
692       if( pExpr->pSelect ){
693         /* Case 1:     expr IN (SELECT ...)
694         **
695         ** Generate code to write the results of the select into a temporary
696         ** table.  The cursor number of the temporary table has already
697         ** been put in iTable by sqliteExprResolveInSelect().
698         */
699         pExpr->iTable = pParse->nTab++;
700         sqliteVdbeAddOp(v, OP_OpenTemp, pExpr->iTable, 1);
701         sqliteSelect(pParse, pExpr->pSelect, SRT_Set, pExpr->iTable, 0,0,0);
702       }else if( pExpr->pList ){
703         /* Case 2:     expr IN (exprlist)
704         **
705         ** Create a set to put the exprlist values in.  The Set id is stored
706         ** in iTable.
707         */
708         int i, iSet;
709         for(i=0; i<pExpr->pList->nExpr; i++){
710           Expr *pE2 = pExpr->pList->a[i].pExpr;
711           if( !sqliteExprIsConstant(pE2) ){
712             sqliteErrorMsg(pParse,
713               "right-hand side of IN operator must be constant");
714             return 1;
715           }
716           if( sqliteExprCheck(pParse, pE2, 0, 0) ){
717             return 1;
718           }
719         }
720         iSet = pExpr->iTable = pParse->nSet++;
721         for(i=0; i<pExpr->pList->nExpr; i++){
722           Expr *pE2 = pExpr->pList->a[i].pExpr;
723           switch( pE2->op ){
724             case TK_FLOAT:
725             case TK_INTEGER:
726             case TK_STRING: {
727               int addr;
728               assert( pE2->token.z );
729               addr = sqliteVdbeOp3(v, OP_SetInsert, iSet, 0,
730                                   pE2->token.z, pE2->token.n);
731               sqliteVdbeDequoteP3(v, addr);
732               break;
733             }
734             default: {
735               sqliteExprCode(pParse, pE2);
736               sqliteVdbeAddOp(v, OP_SetInsert, iSet, 0);
737               break;
738             }
739           }
740         }
741       }
742       break;
743     }
744 
745     case TK_SELECT: {
746       /* This has to be a scalar SELECT.  Generate code to put the
747       ** value of this select in a memory cell and record the number
748       ** of the memory cell in iColumn.
749       */
750       pExpr->iColumn = pParse->nMem++;
751       if( sqliteSelect(pParse, pExpr->pSelect, SRT_Mem, pExpr->iColumn,0,0,0) ){
752         return 1;
753       }
754       break;
755     }
756 
757     /* For all else, just recursively walk the tree */
758     default: {
759       if( pExpr->pLeft
760       && sqliteExprResolveIds(pParse, pSrcList, pEList, pExpr->pLeft) ){
761         return 1;
762       }
763       if( pExpr->pRight
764       && sqliteExprResolveIds(pParse, pSrcList, pEList, pExpr->pRight) ){
765         return 1;
766       }
767       if( pExpr->pList ){
768         int i;
769         ExprList *pList = pExpr->pList;
770         for(i=0; i<pList->nExpr; i++){
771           Expr *pArg = pList->a[i].pExpr;
772           if( sqliteExprResolveIds(pParse, pSrcList, pEList, pArg) ){
773             return 1;
774           }
775         }
776       }
777     }
778   }
779   return 0;
780 }
781 
782 /*
783 ** pExpr is a node that defines a function of some kind.  It might
784 ** be a syntactic function like "count(x)" or it might be a function
785 ** that implements an operator, like "a LIKE b".
786 **
787 ** This routine makes *pzName point to the name of the function and
788 ** *pnName hold the number of characters in the function name.
789 */
getFunctionName(Expr * pExpr,const char ** pzName,int * pnName)790 static void getFunctionName(Expr *pExpr, const char **pzName, int *pnName){
791   switch( pExpr->op ){
792     case TK_FUNCTION: {
793       *pzName = pExpr->token.z;
794       *pnName = pExpr->token.n;
795       break;
796     }
797     case TK_LIKE: {
798       *pzName = "like";
799       *pnName = 4;
800       break;
801     }
802     case TK_GLOB: {
803       *pzName = "glob";
804       *pnName = 4;
805       break;
806     }
807     default: {
808       *pzName = "can't happen";
809       *pnName = 12;
810       break;
811     }
812   }
813 }
814 
815 /*
816 ** Error check the functions in an expression.  Make sure all
817 ** function names are recognized and all functions have the correct
818 ** number of arguments.  Leave an error message in pParse->zErrMsg
819 ** if anything is amiss.  Return the number of errors.
820 **
821 ** if pIsAgg is not null and this expression is an aggregate function
822 ** (like count(*) or max(value)) then write a 1 into *pIsAgg.
823 */
sqliteExprCheck(Parse * pParse,Expr * pExpr,int allowAgg,int * pIsAgg)824 int sqliteExprCheck(Parse *pParse, Expr *pExpr, int allowAgg, int *pIsAgg){
825   int nErr = 0;
826   if( pExpr==0 ) return 0;
827   switch( pExpr->op ){
828     case TK_GLOB:
829     case TK_LIKE:
830     case TK_FUNCTION: {
831       int n = pExpr->pList ? pExpr->pList->nExpr : 0;  /* Number of arguments */
832       int no_such_func = 0;       /* True if no such function exists */
833       int wrong_num_args = 0;     /* True if wrong number of arguments */
834       int is_agg = 0;             /* True if is an aggregate function */
835       int i;
836       int nId;                    /* Number of characters in function name */
837       const char *zId;            /* The function name. */
838       FuncDef *pDef;
839 
840       getFunctionName(pExpr, &zId, &nId);
841       pDef = sqliteFindFunction(pParse->db, zId, nId, n, 0);
842       if( pDef==0 ){
843         pDef = sqliteFindFunction(pParse->db, zId, nId, -1, 0);
844         if( pDef==0 ){
845           no_such_func = 1;
846         }else{
847           wrong_num_args = 1;
848         }
849       }else{
850         is_agg = pDef->xFunc==0;
851       }
852       if( is_agg && !allowAgg ){
853         sqliteErrorMsg(pParse, "misuse of aggregate function %.*s()", nId, zId);
854         nErr++;
855         is_agg = 0;
856       }else if( no_such_func ){
857         sqliteErrorMsg(pParse, "no such function: %.*s", nId, zId);
858         nErr++;
859       }else if( wrong_num_args ){
860         sqliteErrorMsg(pParse,"wrong number of arguments to function %.*s()",
861              nId, zId);
862         nErr++;
863       }
864       if( is_agg ){
865         pExpr->op = TK_AGG_FUNCTION;
866         if( pIsAgg ) *pIsAgg = 1;
867       }
868       for(i=0; nErr==0 && i<n; i++){
869         nErr = sqliteExprCheck(pParse, pExpr->pList->a[i].pExpr,
870                                allowAgg && !is_agg, pIsAgg);
871       }
872       if( pDef==0 ){
873         /* Already reported an error */
874       }else if( pDef->dataType>=0 ){
875         if( pDef->dataType<n ){
876           pExpr->dataType =
877              sqliteExprType(pExpr->pList->a[pDef->dataType].pExpr);
878         }else{
879           pExpr->dataType = SQLITE_SO_NUM;
880         }
881       }else if( pDef->dataType==SQLITE_ARGS ){
882         pDef->dataType = SQLITE_SO_TEXT;
883         for(i=0; i<n; i++){
884           if( sqliteExprType(pExpr->pList->a[i].pExpr)==SQLITE_SO_NUM ){
885             pExpr->dataType = SQLITE_SO_NUM;
886             break;
887           }
888         }
889       }else if( pDef->dataType==SQLITE_NUMERIC ){
890         pExpr->dataType = SQLITE_SO_NUM;
891       }else{
892         pExpr->dataType = SQLITE_SO_TEXT;
893       }
894     }
895     /* FALLTHROUGH */
896     default: {
897       if( pExpr->pLeft ){
898         nErr = sqliteExprCheck(pParse, pExpr->pLeft, allowAgg, pIsAgg);
899       }
900       if( nErr==0 && pExpr->pRight ){
901         nErr = sqliteExprCheck(pParse, pExpr->pRight, allowAgg, pIsAgg);
902       }
903       if( nErr==0 && pExpr->pList ){
904         int n = pExpr->pList->nExpr;
905         int i;
906         for(i=0; nErr==0 && i<n; i++){
907           Expr *pE2 = pExpr->pList->a[i].pExpr;
908           nErr = sqliteExprCheck(pParse, pE2, allowAgg, pIsAgg);
909         }
910       }
911       break;
912     }
913   }
914   return nErr;
915 }
916 
917 /*
918 ** Return either SQLITE_SO_NUM or SQLITE_SO_TEXT to indicate whether the
919 ** given expression should sort as numeric values or as text.
920 **
921 ** The sqliteExprResolveIds() and sqliteExprCheck() routines must have
922 ** both been called on the expression before it is passed to this routine.
923 */
sqliteExprType(Expr * p)924 int sqliteExprType(Expr *p){
925   if( p==0 ) return SQLITE_SO_NUM;
926   while( p ) switch( p->op ){
927     case TK_PLUS:
928     case TK_MINUS:
929     case TK_STAR:
930     case TK_SLASH:
931     case TK_AND:
932     case TK_OR:
933     case TK_ISNULL:
934     case TK_NOTNULL:
935     case TK_NOT:
936     case TK_UMINUS:
937     case TK_UPLUS:
938     case TK_BITAND:
939     case TK_BITOR:
940     case TK_BITNOT:
941     case TK_LSHIFT:
942     case TK_RSHIFT:
943     case TK_REM:
944     case TK_INTEGER:
945     case TK_FLOAT:
946     case TK_IN:
947     case TK_BETWEEN:
948     case TK_GLOB:
949     case TK_LIKE:
950       return SQLITE_SO_NUM;
951 
952     case TK_STRING:
953     case TK_NULL:
954     case TK_CONCAT:
955     case TK_VARIABLE:
956       return SQLITE_SO_TEXT;
957 
958     case TK_LT:
959     case TK_LE:
960     case TK_GT:
961     case TK_GE:
962     case TK_NE:
963     case TK_EQ:
964       if( sqliteExprType(p->pLeft)==SQLITE_SO_NUM ){
965         return SQLITE_SO_NUM;
966       }
967       p = p->pRight;
968       break;
969 
970     case TK_AS:
971       p = p->pLeft;
972       break;
973 
974     case TK_COLUMN:
975     case TK_FUNCTION:
976     case TK_AGG_FUNCTION:
977       return p->dataType;
978 
979     case TK_SELECT:
980       assert( p->pSelect );
981       assert( p->pSelect->pEList );
982       assert( p->pSelect->pEList->nExpr>0 );
983       p = p->pSelect->pEList->a[0].pExpr;
984       break;
985 
986     case TK_CASE: {
987       if( p->pRight && sqliteExprType(p->pRight)==SQLITE_SO_NUM ){
988         return SQLITE_SO_NUM;
989       }
990       if( p->pList ){
991         int i;
992         ExprList *pList = p->pList;
993         for(i=1; i<pList->nExpr; i+=2){
994           if( sqliteExprType(pList->a[i].pExpr)==SQLITE_SO_NUM ){
995             return SQLITE_SO_NUM;
996           }
997         }
998       }
999       return SQLITE_SO_TEXT;
1000     }
1001 
1002     default:
1003       assert( p->op==TK_ABORT );  /* Can't Happen */
1004       break;
1005   }
1006   return SQLITE_SO_NUM;
1007 }
1008 
1009 /*
1010 ** Generate code into the current Vdbe to evaluate the given
1011 ** expression and leave the result on the top of stack.
1012 */
sqliteExprCode(Parse * pParse,Expr * pExpr)1013 void sqliteExprCode(Parse *pParse, Expr *pExpr){
1014   Vdbe *v = pParse->pVdbe;
1015   int op;
1016   if( v==0 || pExpr==0 ) return;
1017   switch( pExpr->op ){
1018     case TK_PLUS:     op = OP_Add;      break;
1019     case TK_MINUS:    op = OP_Subtract; break;
1020     case TK_STAR:     op = OP_Multiply; break;
1021     case TK_SLASH:    op = OP_Divide;   break;
1022     case TK_AND:      op = OP_And;      break;
1023     case TK_OR:       op = OP_Or;       break;
1024     case TK_LT:       op = OP_Lt;       break;
1025     case TK_LE:       op = OP_Le;       break;
1026     case TK_GT:       op = OP_Gt;       break;
1027     case TK_GE:       op = OP_Ge;       break;
1028     case TK_NE:       op = OP_Ne;       break;
1029     case TK_EQ:       op = OP_Eq;       break;
1030     case TK_ISNULL:   op = OP_IsNull;   break;
1031     case TK_NOTNULL:  op = OP_NotNull;  break;
1032     case TK_NOT:      op = OP_Not;      break;
1033     case TK_UMINUS:   op = OP_Negative; break;
1034     case TK_BITAND:   op = OP_BitAnd;   break;
1035     case TK_BITOR:    op = OP_BitOr;    break;
1036     case TK_BITNOT:   op = OP_BitNot;   break;
1037     case TK_LSHIFT:   op = OP_ShiftLeft;  break;
1038     case TK_RSHIFT:   op = OP_ShiftRight; break;
1039     case TK_REM:      op = OP_Remainder;  break;
1040     default: break;
1041   }
1042   switch( pExpr->op ){
1043     case TK_COLUMN: {
1044       if( pParse->useAgg ){
1045         sqliteVdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
1046       }else if( pExpr->iColumn>=0 ){
1047         sqliteVdbeAddOp(v, OP_Column, pExpr->iTable, pExpr->iColumn);
1048       }else{
1049         sqliteVdbeAddOp(v, OP_Recno, pExpr->iTable, 0);
1050       }
1051       break;
1052     }
1053     case TK_STRING:
1054     case TK_FLOAT:
1055     case TK_INTEGER: {
1056       if( pExpr->op==TK_INTEGER && sqliteFitsIn32Bits(pExpr->token.z) ){
1057         sqliteVdbeAddOp(v, OP_Integer, atoi(pExpr->token.z), 0);
1058       }else{
1059         sqliteVdbeAddOp(v, OP_String, 0, 0);
1060       }
1061       assert( pExpr->token.z );
1062       sqliteVdbeChangeP3(v, -1, pExpr->token.z, pExpr->token.n);
1063       sqliteVdbeDequoteP3(v, -1);
1064       break;
1065     }
1066     case TK_NULL: {
1067       sqliteVdbeAddOp(v, OP_String, 0, 0);
1068       break;
1069     }
1070     case TK_VARIABLE: {
1071       sqliteVdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1072       break;
1073     }
1074     case TK_LT:
1075     case TK_LE:
1076     case TK_GT:
1077     case TK_GE:
1078     case TK_NE:
1079     case TK_EQ: {
1080       if( pParse->db->file_format>=4 && sqliteExprType(pExpr)==SQLITE_SO_TEXT ){
1081         op += 6;  /* Convert numeric opcodes to text opcodes */
1082       }
1083     }
1084     /* FALLTHROUGH */
1085     case TK_AND:
1086     case TK_OR:
1087     case TK_PLUS:
1088     case TK_STAR:
1089     case TK_MINUS:
1090     case TK_REM:
1091     case TK_BITAND:
1092     case TK_BITOR:
1093     case TK_SLASH: {
1094       sqliteExprCode(pParse, pExpr->pLeft);
1095       sqliteExprCode(pParse, pExpr->pRight);
1096       sqliteVdbeAddOp(v, op, 0, 0);
1097       break;
1098     }
1099     case TK_LSHIFT:
1100     case TK_RSHIFT: {
1101       sqliteExprCode(pParse, pExpr->pRight);
1102       sqliteExprCode(pParse, pExpr->pLeft);
1103       sqliteVdbeAddOp(v, op, 0, 0);
1104       break;
1105     }
1106     case TK_CONCAT: {
1107       sqliteExprCode(pParse, pExpr->pLeft);
1108       sqliteExprCode(pParse, pExpr->pRight);
1109       sqliteVdbeAddOp(v, OP_Concat, 2, 0);
1110       break;
1111     }
1112     case TK_UMINUS: {
1113       assert( pExpr->pLeft );
1114       if( pExpr->pLeft->op==TK_FLOAT || pExpr->pLeft->op==TK_INTEGER ){
1115         Token *p = &pExpr->pLeft->token;
1116         char *z = sqliteMalloc( p->n + 2 );
1117         sprintf(z, "-%.*s", p->n, p->z);
1118         if( pExpr->pLeft->op==TK_INTEGER && sqliteFitsIn32Bits(z) ){
1119           sqliteVdbeAddOp(v, OP_Integer, atoi(z), 0);
1120         }else{
1121           sqliteVdbeAddOp(v, OP_String, 0, 0);
1122         }
1123         sqliteVdbeChangeP3(v, -1, z, p->n+1);
1124         sqliteFree(z);
1125         break;
1126       }
1127       /* Fall through into TK_NOT */
1128     }
1129     /* FALLTHROUGH */
1130     case TK_BITNOT:
1131     case TK_NOT: {
1132       sqliteExprCode(pParse, pExpr->pLeft);
1133       sqliteVdbeAddOp(v, op, 0, 0);
1134       break;
1135     }
1136     case TK_ISNULL:
1137     case TK_NOTNULL: {
1138       int dest;
1139       sqliteVdbeAddOp(v, OP_Integer, 1, 0);
1140       sqliteExprCode(pParse, pExpr->pLeft);
1141       dest = sqliteVdbeCurrentAddr(v) + 2;
1142       sqliteVdbeAddOp(v, op, 1, dest);
1143       sqliteVdbeAddOp(v, OP_AddImm, -1, 0);
1144       break;
1145     }
1146     case TK_AGG_FUNCTION: {
1147       sqliteVdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
1148       break;
1149     }
1150     case TK_GLOB:
1151     case TK_LIKE:
1152     case TK_FUNCTION: {
1153       ExprList *pList = pExpr->pList;
1154       int nExpr = pList ? pList->nExpr : 0;
1155       FuncDef *pDef;
1156       int nId;
1157       const char *zId;
1158       getFunctionName(pExpr, &zId, &nId);
1159       pDef = sqliteFindFunction(pParse->db, zId, nId, nExpr, 0);
1160       assert( pDef!=0 );
1161       nExpr = sqliteExprCodeExprList(pParse, pList, pDef->includeTypes);
1162       sqliteVdbeOp3(v, OP_Function, nExpr, 0, (char*)pDef, P3_POINTER);
1163       break;
1164     }
1165     case TK_SELECT: {
1166       sqliteVdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
1167       break;
1168     }
1169     case TK_IN: {
1170       int addr;
1171       sqliteVdbeAddOp(v, OP_Integer, 1, 0);
1172       sqliteExprCode(pParse, pExpr->pLeft);
1173       addr = sqliteVdbeCurrentAddr(v);
1174       sqliteVdbeAddOp(v, OP_NotNull, -1, addr+4);
1175       sqliteVdbeAddOp(v, OP_Pop, 2, 0);
1176       sqliteVdbeAddOp(v, OP_String, 0, 0);
1177       sqliteVdbeAddOp(v, OP_Goto, 0, addr+6);
1178       if( pExpr->pSelect ){
1179         sqliteVdbeAddOp(v, OP_Found, pExpr->iTable, addr+6);
1180       }else{
1181         sqliteVdbeAddOp(v, OP_SetFound, pExpr->iTable, addr+6);
1182       }
1183       sqliteVdbeAddOp(v, OP_AddImm, -1, 0);
1184       break;
1185     }
1186     case TK_BETWEEN: {
1187       sqliteExprCode(pParse, pExpr->pLeft);
1188       sqliteVdbeAddOp(v, OP_Dup, 0, 0);
1189       sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
1190       sqliteVdbeAddOp(v, OP_Ge, 0, 0);
1191       sqliteVdbeAddOp(v, OP_Pull, 1, 0);
1192       sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
1193       sqliteVdbeAddOp(v, OP_Le, 0, 0);
1194       sqliteVdbeAddOp(v, OP_And, 0, 0);
1195       break;
1196     }
1197     case TK_UPLUS:
1198     case TK_AS: {
1199       sqliteExprCode(pParse, pExpr->pLeft);
1200       break;
1201     }
1202     case TK_CASE: {
1203       int expr_end_label;
1204       int jumpInst;
1205       int addr;
1206       int nExpr;
1207       int i;
1208 
1209       assert(pExpr->pList);
1210       assert((pExpr->pList->nExpr % 2) == 0);
1211       assert(pExpr->pList->nExpr > 0);
1212       nExpr = pExpr->pList->nExpr;
1213       expr_end_label = sqliteVdbeMakeLabel(v);
1214       if( pExpr->pLeft ){
1215         sqliteExprCode(pParse, pExpr->pLeft);
1216       }
1217       for(i=0; i<nExpr; i=i+2){
1218         sqliteExprCode(pParse, pExpr->pList->a[i].pExpr);
1219         if( pExpr->pLeft ){
1220           sqliteVdbeAddOp(v, OP_Dup, 1, 1);
1221           jumpInst = sqliteVdbeAddOp(v, OP_Ne, 1, 0);
1222           sqliteVdbeAddOp(v, OP_Pop, 1, 0);
1223         }else{
1224           jumpInst = sqliteVdbeAddOp(v, OP_IfNot, 1, 0);
1225         }
1226         sqliteExprCode(pParse, pExpr->pList->a[i+1].pExpr);
1227         sqliteVdbeAddOp(v, OP_Goto, 0, expr_end_label);
1228         addr = sqliteVdbeCurrentAddr(v);
1229         sqliteVdbeChangeP2(v, jumpInst, addr);
1230       }
1231       if( pExpr->pLeft ){
1232         sqliteVdbeAddOp(v, OP_Pop, 1, 0);
1233       }
1234       if( pExpr->pRight ){
1235         sqliteExprCode(pParse, pExpr->pRight);
1236       }else{
1237         sqliteVdbeAddOp(v, OP_String, 0, 0);
1238       }
1239       sqliteVdbeResolveLabel(v, expr_end_label);
1240       break;
1241     }
1242     case TK_RAISE: {
1243       if( !pParse->trigStack ){
1244         sqliteErrorMsg(pParse,
1245                        "RAISE() may only be used within a trigger-program");
1246         pParse->nErr++;
1247 	return;
1248       }
1249       if( pExpr->iColumn == OE_Rollback ||
1250 	  pExpr->iColumn == OE_Abort ||
1251 	  pExpr->iColumn == OE_Fail ){
1252 	  sqliteVdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
1253                            pExpr->token.z, pExpr->token.n);
1254 	  sqliteVdbeDequoteP3(v, -1);
1255       } else {
1256 	  assert( pExpr->iColumn == OE_Ignore );
1257 	  sqliteVdbeOp3(v, OP_Goto, 0, pParse->trigStack->ignoreJump,
1258                            "(IGNORE jump)", 0);
1259       }
1260     }
1261     break;
1262   }
1263 }
1264 
1265 /*
1266 ** Generate code that pushes the value of every element of the given
1267 ** expression list onto the stack.  If the includeTypes flag is true,
1268 ** then also push a string that is the datatype of each element onto
1269 ** the stack after the value.
1270 **
1271 ** Return the number of elements pushed onto the stack.
1272 */
sqliteExprCodeExprList(Parse * pParse,ExprList * pList,int includeTypes)1273 int sqliteExprCodeExprList(
1274   Parse *pParse,     /* Parsing context */
1275   ExprList *pList,   /* The expression list to be coded */
1276   int includeTypes   /* TRUE to put datatypes on the stack too */
1277 ){
1278   struct ExprList_item *pItem;
1279   int i, n;
1280   Vdbe *v;
1281   if( pList==0 ) return 0;
1282   v = sqliteGetVdbe(pParse);
1283   n = pList->nExpr;
1284   for(pItem=pList->a, i=0; i<n; i++, pItem++){
1285     sqliteExprCode(pParse, pItem->pExpr);
1286     if( includeTypes ){
1287       sqliteVdbeOp3(v, OP_String, 0, 0,
1288          sqliteExprType(pItem->pExpr)==SQLITE_SO_NUM ? "numeric" : "text",
1289          P3_STATIC);
1290     }
1291   }
1292   return includeTypes ? n*2 : n;
1293 }
1294 
1295 /*
1296 ** Generate code for a boolean expression such that a jump is made
1297 ** to the label "dest" if the expression is true but execution
1298 ** continues straight thru if the expression is false.
1299 **
1300 ** If the expression evaluates to NULL (neither true nor false), then
1301 ** take the jump if the jumpIfNull flag is true.
1302 */
sqliteExprIfTrue(Parse * pParse,Expr * pExpr,int dest,int jumpIfNull)1303 void sqliteExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1304   Vdbe *v = pParse->pVdbe;
1305   int op = 0;
1306   if( v==0 || pExpr==0 ) return;
1307   switch( pExpr->op ){
1308     case TK_LT:       op = OP_Lt;       break;
1309     case TK_LE:       op = OP_Le;       break;
1310     case TK_GT:       op = OP_Gt;       break;
1311     case TK_GE:       op = OP_Ge;       break;
1312     case TK_NE:       op = OP_Ne;       break;
1313     case TK_EQ:       op = OP_Eq;       break;
1314     case TK_ISNULL:   op = OP_IsNull;   break;
1315     case TK_NOTNULL:  op = OP_NotNull;  break;
1316     default:  break;
1317   }
1318   switch( pExpr->op ){
1319     case TK_AND: {
1320       int d2 = sqliteVdbeMakeLabel(v);
1321       sqliteExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
1322       sqliteExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
1323       sqliteVdbeResolveLabel(v, d2);
1324       break;
1325     }
1326     case TK_OR: {
1327       sqliteExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
1328       sqliteExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
1329       break;
1330     }
1331     case TK_NOT: {
1332       sqliteExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
1333       break;
1334     }
1335     case TK_LT:
1336     case TK_LE:
1337     case TK_GT:
1338     case TK_GE:
1339     case TK_NE:
1340     case TK_EQ: {
1341       sqliteExprCode(pParse, pExpr->pLeft);
1342       sqliteExprCode(pParse, pExpr->pRight);
1343       if( pParse->db->file_format>=4 && sqliteExprType(pExpr)==SQLITE_SO_TEXT ){
1344         op += 6;  /* Convert numeric opcodes to text opcodes */
1345       }
1346       sqliteVdbeAddOp(v, op, jumpIfNull, dest);
1347       break;
1348     }
1349     case TK_ISNULL:
1350     case TK_NOTNULL: {
1351       sqliteExprCode(pParse, pExpr->pLeft);
1352       sqliteVdbeAddOp(v, op, 1, dest);
1353       break;
1354     }
1355     case TK_IN: {
1356       int addr;
1357       sqliteExprCode(pParse, pExpr->pLeft);
1358       addr = sqliteVdbeCurrentAddr(v);
1359       sqliteVdbeAddOp(v, OP_NotNull, -1, addr+3);
1360       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
1361       sqliteVdbeAddOp(v, OP_Goto, 0, jumpIfNull ? dest : addr+4);
1362       if( pExpr->pSelect ){
1363         sqliteVdbeAddOp(v, OP_Found, pExpr->iTable, dest);
1364       }else{
1365         sqliteVdbeAddOp(v, OP_SetFound, pExpr->iTable, dest);
1366       }
1367       break;
1368     }
1369     case TK_BETWEEN: {
1370       int addr;
1371       sqliteExprCode(pParse, pExpr->pLeft);
1372       sqliteVdbeAddOp(v, OP_Dup, 0, 0);
1373       sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
1374       addr = sqliteVdbeAddOp(v, OP_Lt, !jumpIfNull, 0);
1375       sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
1376       sqliteVdbeAddOp(v, OP_Le, jumpIfNull, dest);
1377       sqliteVdbeAddOp(v, OP_Integer, 0, 0);
1378       sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
1379       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
1380       break;
1381     }
1382     default: {
1383       sqliteExprCode(pParse, pExpr);
1384       sqliteVdbeAddOp(v, OP_If, jumpIfNull, dest);
1385       break;
1386     }
1387   }
1388 }
1389 
1390 /*
1391 ** Generate code for a boolean expression such that a jump is made
1392 ** to the label "dest" if the expression is false but execution
1393 ** continues straight thru if the expression is true.
1394 **
1395 ** If the expression evaluates to NULL (neither true nor false) then
1396 ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
1397 */
sqliteExprIfFalse(Parse * pParse,Expr * pExpr,int dest,int jumpIfNull)1398 void sqliteExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1399   Vdbe *v = pParse->pVdbe;
1400   int op = 0;
1401   if( v==0 || pExpr==0 ) return;
1402   switch( pExpr->op ){
1403     case TK_LT:       op = OP_Ge;       break;
1404     case TK_LE:       op = OP_Gt;       break;
1405     case TK_GT:       op = OP_Le;       break;
1406     case TK_GE:       op = OP_Lt;       break;
1407     case TK_NE:       op = OP_Eq;       break;
1408     case TK_EQ:       op = OP_Ne;       break;
1409     case TK_ISNULL:   op = OP_NotNull;  break;
1410     case TK_NOTNULL:  op = OP_IsNull;   break;
1411     default:  break;
1412   }
1413   switch( pExpr->op ){
1414     case TK_AND: {
1415       sqliteExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
1416       sqliteExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
1417       break;
1418     }
1419     case TK_OR: {
1420       int d2 = sqliteVdbeMakeLabel(v);
1421       sqliteExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
1422       sqliteExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
1423       sqliteVdbeResolveLabel(v, d2);
1424       break;
1425     }
1426     case TK_NOT: {
1427       sqliteExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
1428       break;
1429     }
1430     case TK_LT:
1431     case TK_LE:
1432     case TK_GT:
1433     case TK_GE:
1434     case TK_NE:
1435     case TK_EQ: {
1436       if( pParse->db->file_format>=4 && sqliteExprType(pExpr)==SQLITE_SO_TEXT ){
1437         /* Convert numeric comparison opcodes into text comparison opcodes.
1438         ** This step depends on the fact that the text comparision opcodes are
1439         ** always 6 greater than their corresponding numeric comparison
1440         ** opcodes.
1441         */
1442         assert( OP_Eq+6 == OP_StrEq );
1443         op += 6;
1444       }
1445       sqliteExprCode(pParse, pExpr->pLeft);
1446       sqliteExprCode(pParse, pExpr->pRight);
1447       sqliteVdbeAddOp(v, op, jumpIfNull, dest);
1448       break;
1449     }
1450     case TK_ISNULL:
1451     case TK_NOTNULL: {
1452       sqliteExprCode(pParse, pExpr->pLeft);
1453       sqliteVdbeAddOp(v, op, 1, dest);
1454       break;
1455     }
1456     case TK_IN: {
1457       int addr;
1458       sqliteExprCode(pParse, pExpr->pLeft);
1459       addr = sqliteVdbeCurrentAddr(v);
1460       sqliteVdbeAddOp(v, OP_NotNull, -1, addr+3);
1461       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
1462       sqliteVdbeAddOp(v, OP_Goto, 0, jumpIfNull ? dest : addr+4);
1463       if( pExpr->pSelect ){
1464         sqliteVdbeAddOp(v, OP_NotFound, pExpr->iTable, dest);
1465       }else{
1466         sqliteVdbeAddOp(v, OP_SetNotFound, pExpr->iTable, dest);
1467       }
1468       break;
1469     }
1470     case TK_BETWEEN: {
1471       int addr;
1472       sqliteExprCode(pParse, pExpr->pLeft);
1473       sqliteVdbeAddOp(v, OP_Dup, 0, 0);
1474       sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
1475       addr = sqliteVdbeCurrentAddr(v);
1476       sqliteVdbeAddOp(v, OP_Ge, !jumpIfNull, addr+3);
1477       sqliteVdbeAddOp(v, OP_Pop, 1, 0);
1478       sqliteVdbeAddOp(v, OP_Goto, 0, dest);
1479       sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
1480       sqliteVdbeAddOp(v, OP_Gt, jumpIfNull, dest);
1481       break;
1482     }
1483     default: {
1484       sqliteExprCode(pParse, pExpr);
1485       sqliteVdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
1486       break;
1487     }
1488   }
1489 }
1490 
1491 /*
1492 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
1493 ** if they are identical and return FALSE if they differ in any way.
1494 */
sqliteExprCompare(Expr * pA,Expr * pB)1495 int sqliteExprCompare(Expr *pA, Expr *pB){
1496   int i;
1497   if( pA==0 ){
1498     return pB==0;
1499   }else if( pB==0 ){
1500     return 0;
1501   }
1502   if( pA->op!=pB->op ) return 0;
1503   if( !sqliteExprCompare(pA->pLeft, pB->pLeft) ) return 0;
1504   if( !sqliteExprCompare(pA->pRight, pB->pRight) ) return 0;
1505   if( pA->pList ){
1506     if( pB->pList==0 ) return 0;
1507     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
1508     for(i=0; i<pA->pList->nExpr; i++){
1509       if( !sqliteExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
1510         return 0;
1511       }
1512     }
1513   }else if( pB->pList ){
1514     return 0;
1515   }
1516   if( pA->pSelect || pB->pSelect ) return 0;
1517   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
1518   if( pA->token.z ){
1519     if( pB->token.z==0 ) return 0;
1520     if( pB->token.n!=pA->token.n ) return 0;
1521     if( sqliteStrNICmp(pA->token.z, pB->token.z, pB->token.n)!=0 ) return 0;
1522   }
1523   return 1;
1524 }
1525 
1526 /*
1527 ** Add a new element to the pParse->aAgg[] array and return its index.
1528 */
appendAggInfo(Parse * pParse)1529 static int appendAggInfo(Parse *pParse){
1530   if( (pParse->nAgg & 0x7)==0 ){
1531     int amt = pParse->nAgg + 8;
1532     AggExpr *aAgg = sqliteRealloc(pParse->aAgg, amt*sizeof(pParse->aAgg[0]));
1533     if( aAgg==0 ){
1534       return -1;
1535     }
1536     pParse->aAgg = aAgg;
1537   }
1538   memset(&pParse->aAgg[pParse->nAgg], 0, sizeof(pParse->aAgg[0]));
1539   return pParse->nAgg++;
1540 }
1541 
1542 /*
1543 ** Analyze the given expression looking for aggregate functions and
1544 ** for variables that need to be added to the pParse->aAgg[] array.
1545 ** Make additional entries to the pParse->aAgg[] array as necessary.
1546 **
1547 ** This routine should only be called after the expression has been
1548 ** analyzed by sqliteExprResolveIds() and sqliteExprCheck().
1549 **
1550 ** If errors are seen, leave an error message in zErrMsg and return
1551 ** the number of errors.
1552 */
sqliteExprAnalyzeAggregates(Parse * pParse,Expr * pExpr)1553 int sqliteExprAnalyzeAggregates(Parse *pParse, Expr *pExpr){
1554   int i;
1555   AggExpr *aAgg;
1556   int nErr = 0;
1557 
1558   if( pExpr==0 ) return 0;
1559   switch( pExpr->op ){
1560     case TK_COLUMN: {
1561       aAgg = pParse->aAgg;
1562       for(i=0; i<pParse->nAgg; i++){
1563         if( aAgg[i].isAgg ) continue;
1564         if( aAgg[i].pExpr->iTable==pExpr->iTable
1565          && aAgg[i].pExpr->iColumn==pExpr->iColumn ){
1566           break;
1567         }
1568       }
1569       if( i>=pParse->nAgg ){
1570         i = appendAggInfo(pParse);
1571         if( i<0 ) return 1;
1572         pParse->aAgg[i].isAgg = 0;
1573         pParse->aAgg[i].pExpr = pExpr;
1574       }
1575       pExpr->iAgg = i;
1576       break;
1577     }
1578     case TK_AGG_FUNCTION: {
1579       aAgg = pParse->aAgg;
1580       for(i=0; i<pParse->nAgg; i++){
1581         if( !aAgg[i].isAgg ) continue;
1582         if( sqliteExprCompare(aAgg[i].pExpr, pExpr) ){
1583           break;
1584         }
1585       }
1586       if( i>=pParse->nAgg ){
1587         i = appendAggInfo(pParse);
1588         if( i<0 ) return 1;
1589         pParse->aAgg[i].isAgg = 1;
1590         pParse->aAgg[i].pExpr = pExpr;
1591         pParse->aAgg[i].pFunc = sqliteFindFunction(pParse->db,
1592              pExpr->token.z, pExpr->token.n,
1593              pExpr->pList ? pExpr->pList->nExpr : 0, 0);
1594       }
1595       pExpr->iAgg = i;
1596       break;
1597     }
1598     default: {
1599       if( pExpr->pLeft ){
1600         nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pLeft);
1601       }
1602       if( nErr==0 && pExpr->pRight ){
1603         nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pRight);
1604       }
1605       if( nErr==0 && pExpr->pList ){
1606         int n = pExpr->pList->nExpr;
1607         int i;
1608         for(i=0; nErr==0 && i<n; i++){
1609           nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pList->a[i].pExpr);
1610         }
1611       }
1612       break;
1613     }
1614   }
1615   return nErr;
1616 }
1617 
1618 /*
1619 ** Locate a user function given a name and a number of arguments.
1620 ** Return a pointer to the FuncDef structure that defines that
1621 ** function, or return NULL if the function does not exist.
1622 **
1623 ** If the createFlag argument is true, then a new (blank) FuncDef
1624 ** structure is created and liked into the "db" structure if a
1625 ** no matching function previously existed.  When createFlag is true
1626 ** and the nArg parameter is -1, then only a function that accepts
1627 ** any number of arguments will be returned.
1628 **
1629 ** If createFlag is false and nArg is -1, then the first valid
1630 ** function found is returned.  A function is valid if either xFunc
1631 ** or xStep is non-zero.
1632 */
sqliteFindFunction(sqlite * db,const char * zName,int nName,int nArg,int createFlag)1633 FuncDef *sqliteFindFunction(
1634   sqlite *db,        /* An open database */
1635   const char *zName, /* Name of the function.  Not null-terminated */
1636   int nName,         /* Number of characters in the name */
1637   int nArg,          /* Number of arguments.  -1 means any number */
1638   int createFlag     /* Create new entry if true and does not otherwise exist */
1639 ){
1640   FuncDef *pFirst, *p, *pMaybe;
1641   pFirst = p = (FuncDef*)sqliteHashFind(&db->aFunc, zName, nName);
1642   if( p && !createFlag && nArg<0 ){
1643     while( p && p->xFunc==0 && p->xStep==0 ){ p = p->pNext; }
1644     return p;
1645   }
1646   pMaybe = 0;
1647   while( p && p->nArg!=nArg ){
1648     if( p->nArg<0 && !createFlag && (p->xFunc || p->xStep) ) pMaybe = p;
1649     p = p->pNext;
1650   }
1651   if( p && !createFlag && p->xFunc==0 && p->xStep==0 ){
1652     return 0;
1653   }
1654   if( p==0 && pMaybe ){
1655     assert( createFlag==0 );
1656     return pMaybe;
1657   }
1658   if( p==0 && createFlag && (p = sqliteMalloc(sizeof(*p)))!=0 ){
1659     p->nArg = nArg;
1660     p->pNext = pFirst;
1661     p->dataType = pFirst ? pFirst->dataType : SQLITE_NUMERIC;
1662     sqliteHashInsert(&db->aFunc, zName, nName, (void*)p);
1663   }
1664   return p;
1665 }
1666