xref: /titanic_51/usr/src/lib/libsqlite/src/expr.c (revision c5c4113dfcabb1eed3d4bdf7609de5170027a794)
1 
2 #pragma ident	"%Z%%M%	%I%	%E% SMI"
3 
4 /*
5 ** 2001 September 15
6 **
7 ** The author disclaims copyright to this source code.  In place of
8 ** a legal notice, here is a blessing:
9 **
10 **    May you do good and not evil.
11 **    May you find forgiveness for yourself and forgive others.
12 **    May you share freely, never taking more than you give.
13 **
14 *************************************************************************
15 ** This file contains routines used for analyzing expressions and
16 ** for generating VDBE code that evaluates expressions in SQLite.
17 **
18 ** $Id: expr.c,v 1.114.2.3 2004/07/22 17:10:10 drh Exp $
19 */
20 #include "sqliteInt.h"
21 #include <ctype.h>
22 
23 /*
24 ** Construct a new expression node and return a pointer to it.  Memory
25 ** for this node is obtained from sqliteMalloc().  The calling function
26 ** is responsible for making sure the node eventually gets freed.
27 */
28 Expr *sqliteExpr(int op, Expr *pLeft, Expr *pRight, Token *pToken){
29   Expr *pNew;
30   pNew = sqliteMalloc( sizeof(Expr) );
31   if( pNew==0 ){
32     /* When malloc fails, we leak memory from pLeft and pRight */
33     return 0;
34   }
35   pNew->op = op;
36   pNew->pLeft = pLeft;
37   pNew->pRight = pRight;
38   if( pToken ){
39     assert( pToken->dyn==0 );
40     pNew->token = *pToken;
41     pNew->span = *pToken;
42   }else{
43     assert( pNew->token.dyn==0 );
44     assert( pNew->token.z==0 );
45     assert( pNew->token.n==0 );
46     if( pLeft && pRight ){
47       sqliteExprSpan(pNew, &pLeft->span, &pRight->span);
48     }else{
49       pNew->span = pNew->token;
50     }
51   }
52   return pNew;
53 }
54 
55 /*
56 ** Set the Expr.span field of the given expression to span all
57 ** text between the two given tokens.
58 */
59 void sqliteExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
60   assert( pRight!=0 );
61   assert( pLeft!=0 );
62   /* Note: pExpr might be NULL due to a prior malloc failure */
63   if( pExpr && pRight->z && pLeft->z ){
64     if( pLeft->dyn==0 && pRight->dyn==0 ){
65       pExpr->span.z = pLeft->z;
66       pExpr->span.n = pRight->n + Addr(pRight->z) - Addr(pLeft->z);
67     }else{
68       pExpr->span.z = 0;
69     }
70   }
71 }
72 
73 /*
74 ** Construct a new expression node for a function with multiple
75 ** arguments.
76 */
77 Expr *sqliteExprFunction(ExprList *pList, Token *pToken){
78   Expr *pNew;
79   pNew = sqliteMalloc( sizeof(Expr) );
80   if( pNew==0 ){
81     /* sqliteExprListDelete(pList); // Leak pList when malloc fails */
82     return 0;
83   }
84   pNew->op = TK_FUNCTION;
85   pNew->pList = pList;
86   if( pToken ){
87     assert( pToken->dyn==0 );
88     pNew->token = *pToken;
89   }else{
90     pNew->token.z = 0;
91   }
92   pNew->span = pNew->token;
93   return pNew;
94 }
95 
96 /*
97 ** Recursively delete an expression tree.
98 */
99 void sqliteExprDelete(Expr *p){
100   if( p==0 ) return;
101   if( p->span.dyn ) sqliteFree((char*)p->span.z);
102   if( p->token.dyn ) sqliteFree((char*)p->token.z);
103   sqliteExprDelete(p->pLeft);
104   sqliteExprDelete(p->pRight);
105   sqliteExprListDelete(p->pList);
106   sqliteSelectDelete(p->pSelect);
107   sqliteFree(p);
108 }
109 
110 
111 /*
112 ** The following group of routines make deep copies of expressions,
113 ** expression lists, ID lists, and select statements.  The copies can
114 ** be deleted (by being passed to their respective ...Delete() routines)
115 ** without effecting the originals.
116 **
117 ** The expression list, ID, and source lists return by sqliteExprListDup(),
118 ** sqliteIdListDup(), and sqliteSrcListDup() can not be further expanded
119 ** by subsequent calls to sqlite*ListAppend() routines.
120 **
121 ** Any tables that the SrcList might point to are not duplicated.
122 */
123 Expr *sqliteExprDup(Expr *p){
124   Expr *pNew;
125   if( p==0 ) return 0;
126   pNew = sqliteMallocRaw( sizeof(*p) );
127   if( pNew==0 ) return 0;
128   memcpy(pNew, p, sizeof(*pNew));
129   if( p->token.z!=0 ){
130     pNew->token.z = sqliteStrDup(p->token.z);
131     pNew->token.dyn = 1;
132   }else{
133     assert( pNew->token.z==0 );
134   }
135   pNew->span.z = 0;
136   pNew->pLeft = sqliteExprDup(p->pLeft);
137   pNew->pRight = sqliteExprDup(p->pRight);
138   pNew->pList = sqliteExprListDup(p->pList);
139   pNew->pSelect = sqliteSelectDup(p->pSelect);
140   return pNew;
141 }
142 void sqliteTokenCopy(Token *pTo, Token *pFrom){
143   if( pTo->dyn ) sqliteFree((char*)pTo->z);
144   if( pFrom->z ){
145     pTo->n = pFrom->n;
146     pTo->z = sqliteStrNDup(pFrom->z, pFrom->n);
147     pTo->dyn = 1;
148   }else{
149     pTo->z = 0;
150   }
151 }
152 ExprList *sqliteExprListDup(ExprList *p){
153   ExprList *pNew;
154   struct ExprList_item *pItem;
155   int i;
156   if( p==0 ) return 0;
157   pNew = sqliteMalloc( sizeof(*pNew) );
158   if( pNew==0 ) return 0;
159   pNew->nExpr = pNew->nAlloc = p->nExpr;
160   pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
161   if( pItem==0 ){
162     sqliteFree(pNew);
163     return 0;
164   }
165   for(i=0; i<p->nExpr; i++, pItem++){
166     Expr *pNewExpr, *pOldExpr;
167     pItem->pExpr = pNewExpr = sqliteExprDup(pOldExpr = p->a[i].pExpr);
168     if( pOldExpr->span.z!=0 && pNewExpr ){
169       /* Always make a copy of the span for top-level expressions in the
170       ** expression list.  The logic in SELECT processing that determines
171       ** the names of columns in the result set needs this information */
172       sqliteTokenCopy(&pNewExpr->span, &pOldExpr->span);
173     }
174     assert( pNewExpr==0 || pNewExpr->span.z!=0
175             || pOldExpr->span.z==0 || sqlite_malloc_failed );
176     pItem->zName = sqliteStrDup(p->a[i].zName);
177     pItem->sortOrder = p->a[i].sortOrder;
178     pItem->isAgg = p->a[i].isAgg;
179     pItem->done = 0;
180   }
181   return pNew;
182 }
183 SrcList *sqliteSrcListDup(SrcList *p){
184   SrcList *pNew;
185   int i;
186   int nByte;
187   if( p==0 ) return 0;
188   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
189   pNew = sqliteMallocRaw( nByte );
190   if( pNew==0 ) return 0;
191   pNew->nSrc = pNew->nAlloc = p->nSrc;
192   for(i=0; i<p->nSrc; i++){
193     struct SrcList_item *pNewItem = &pNew->a[i];
194     struct SrcList_item *pOldItem = &p->a[i];
195     pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
196     pNewItem->zName = sqliteStrDup(pOldItem->zName);
197     pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
198     pNewItem->jointype = pOldItem->jointype;
199     pNewItem->iCursor = pOldItem->iCursor;
200     pNewItem->pTab = 0;
201     pNewItem->pSelect = sqliteSelectDup(pOldItem->pSelect);
202     pNewItem->pOn = sqliteExprDup(pOldItem->pOn);
203     pNewItem->pUsing = sqliteIdListDup(pOldItem->pUsing);
204   }
205   return pNew;
206 }
207 IdList *sqliteIdListDup(IdList *p){
208   IdList *pNew;
209   int i;
210   if( p==0 ) return 0;
211   pNew = sqliteMallocRaw( sizeof(*pNew) );
212   if( pNew==0 ) return 0;
213   pNew->nId = pNew->nAlloc = p->nId;
214   pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
215   if( pNew->a==0 ) return 0;
216   for(i=0; i<p->nId; i++){
217     struct IdList_item *pNewItem = &pNew->a[i];
218     struct IdList_item *pOldItem = &p->a[i];
219     pNewItem->zName = sqliteStrDup(pOldItem->zName);
220     pNewItem->idx = pOldItem->idx;
221   }
222   return pNew;
223 }
224 Select *sqliteSelectDup(Select *p){
225   Select *pNew;
226   if( p==0 ) return 0;
227   pNew = sqliteMallocRaw( sizeof(*p) );
228   if( pNew==0 ) return 0;
229   pNew->isDistinct = p->isDistinct;
230   pNew->pEList = sqliteExprListDup(p->pEList);
231   pNew->pSrc = sqliteSrcListDup(p->pSrc);
232   pNew->pWhere = sqliteExprDup(p->pWhere);
233   pNew->pGroupBy = sqliteExprListDup(p->pGroupBy);
234   pNew->pHaving = sqliteExprDup(p->pHaving);
235   pNew->pOrderBy = sqliteExprListDup(p->pOrderBy);
236   pNew->op = p->op;
237   pNew->pPrior = sqliteSelectDup(p->pPrior);
238   pNew->nLimit = p->nLimit;
239   pNew->nOffset = p->nOffset;
240   pNew->zSelect = 0;
241   pNew->iLimit = -1;
242   pNew->iOffset = -1;
243   return pNew;
244 }
245 
246 
247 /*
248 ** Add a new element to the end of an expression list.  If pList is
249 ** initially NULL, then create a new expression list.
250 */
251 ExprList *sqliteExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
252   if( pList==0 ){
253     pList = sqliteMalloc( sizeof(ExprList) );
254     if( pList==0 ){
255       /* sqliteExprDelete(pExpr); // Leak memory if malloc fails */
256       return 0;
257     }
258     assert( pList->nAlloc==0 );
259   }
260   if( pList->nAlloc<=pList->nExpr ){
261     pList->nAlloc = pList->nAlloc*2 + 4;
262     pList->a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]));
263     if( pList->a==0 ){
264       /* sqliteExprDelete(pExpr); // Leak memory if malloc fails */
265       pList->nExpr = pList->nAlloc = 0;
266       return pList;
267     }
268   }
269   assert( pList->a!=0 );
270   if( pExpr || pName ){
271     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
272     memset(pItem, 0, sizeof(*pItem));
273     pItem->pExpr = pExpr;
274     if( pName ){
275       sqliteSetNString(&pItem->zName, pName->z, pName->n, 0);
276       sqliteDequote(pItem->zName);
277     }
278   }
279   return pList;
280 }
281 
282 /*
283 ** Delete an entire expression list.
284 */
285 void sqliteExprListDelete(ExprList *pList){
286   int i;
287   if( pList==0 ) return;
288   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
289   assert( pList->nExpr<=pList->nAlloc );
290   for(i=0; i<pList->nExpr; i++){
291     sqliteExprDelete(pList->a[i].pExpr);
292     sqliteFree(pList->a[i].zName);
293   }
294   sqliteFree(pList->a);
295   sqliteFree(pList);
296 }
297 
298 /*
299 ** Walk an expression tree.  Return 1 if the expression is constant
300 ** and 0 if it involves variables.
301 **
302 ** For the purposes of this function, a double-quoted string (ex: "abc")
303 ** is considered a variable but a single-quoted string (ex: 'abc') is
304 ** a constant.
305 */
306 int sqliteExprIsConstant(Expr *p){
307   switch( p->op ){
308     case TK_ID:
309     case TK_COLUMN:
310     case TK_DOT:
311     case TK_FUNCTION:
312       return 0;
313     case TK_NULL:
314     case TK_STRING:
315     case TK_INTEGER:
316     case TK_FLOAT:
317     case TK_VARIABLE:
318       return 1;
319     default: {
320       if( p->pLeft && !sqliteExprIsConstant(p->pLeft) ) return 0;
321       if( p->pRight && !sqliteExprIsConstant(p->pRight) ) return 0;
322       if( p->pList ){
323         int i;
324         for(i=0; i<p->pList->nExpr; i++){
325           if( !sqliteExprIsConstant(p->pList->a[i].pExpr) ) return 0;
326         }
327       }
328       return p->pLeft!=0 || p->pRight!=0 || (p->pList && p->pList->nExpr>0);
329     }
330   }
331   return 0;
332 }
333 
334 /*
335 ** If the given expression codes a constant integer that is small enough
336 ** to fit in a 32-bit integer, return 1 and put the value of the integer
337 ** in *pValue.  If the expression is not an integer or if it is too big
338 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
339 */
340 int sqliteExprIsInteger(Expr *p, int *pValue){
341   switch( p->op ){
342     case TK_INTEGER: {
343       if( sqliteFitsIn32Bits(p->token.z) ){
344         *pValue = atoi(p->token.z);
345         return 1;
346       }
347       break;
348     }
349     case TK_STRING: {
350       const char *z = p->token.z;
351       int n = p->token.n;
352       if( n>0 && z[0]=='-' ){ z++; n--; }
353       while( n>0 && *z && isdigit(*z) ){ z++; n--; }
354       if( n==0 && sqliteFitsIn32Bits(p->token.z) ){
355         *pValue = atoi(p->token.z);
356         return 1;
357       }
358       break;
359     }
360     case TK_UPLUS: {
361       return sqliteExprIsInteger(p->pLeft, pValue);
362     }
363     case TK_UMINUS: {
364       int v;
365       if( sqliteExprIsInteger(p->pLeft, &v) ){
366         *pValue = -v;
367         return 1;
368       }
369       break;
370     }
371     default: break;
372   }
373   return 0;
374 }
375 
376 /*
377 ** Return TRUE if the given string is a row-id column name.
378 */
379 int sqliteIsRowid(const char *z){
380   if( sqliteStrICmp(z, "_ROWID_")==0 ) return 1;
381   if( sqliteStrICmp(z, "ROWID")==0 ) return 1;
382   if( sqliteStrICmp(z, "OID")==0 ) return 1;
383   return 0;
384 }
385 
386 /*
387 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
388 ** that name in the set of source tables in pSrcList and make the pExpr
389 ** expression node refer back to that source column.  The following changes
390 ** are made to pExpr:
391 **
392 **    pExpr->iDb           Set the index in db->aDb[] of the database holding
393 **                         the table.
394 **    pExpr->iTable        Set to the cursor number for the table obtained
395 **                         from pSrcList.
396 **    pExpr->iColumn       Set to the column number within the table.
397 **    pExpr->dataType      Set to the appropriate data type for the column.
398 **    pExpr->op            Set to TK_COLUMN.
399 **    pExpr->pLeft         Any expression this points to is deleted
400 **    pExpr->pRight        Any expression this points to is deleted.
401 **
402 ** The pDbToken is the name of the database (the "X").  This value may be
403 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
404 ** can be used.  The pTableToken is the name of the table (the "Y").  This
405 ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
406 ** means that the form of the name is Z and that columns from any table
407 ** can be used.
408 **
409 ** If the name cannot be resolved unambiguously, leave an error message
410 ** in pParse and return non-zero.  Return zero on success.
411 */
412 static int lookupName(
413   Parse *pParse,      /* The parsing context */
414   Token *pDbToken,     /* Name of the database containing table, or NULL */
415   Token *pTableToken,  /* Name of table containing column, or NULL */
416   Token *pColumnToken, /* Name of the column. */
417   SrcList *pSrcList,   /* List of tables used to resolve column names */
418   ExprList *pEList,    /* List of expressions used to resolve "AS" */
419   Expr *pExpr          /* Make this EXPR node point to the selected column */
420 ){
421   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
422   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
423   char *zCol = 0;      /* Name of the column.  The "Z" */
424   int i, j;            /* Loop counters */
425   int cnt = 0;         /* Number of matching column names */
426   int cntTab = 0;      /* Number of matching table names */
427   sqlite *db = pParse->db;  /* The database */
428 
429   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
430   if( pDbToken && pDbToken->z ){
431     zDb = sqliteStrNDup(pDbToken->z, pDbToken->n);
432     sqliteDequote(zDb);
433   }else{
434     zDb = 0;
435   }
436   if( pTableToken && pTableToken->z ){
437     zTab = sqliteStrNDup(pTableToken->z, pTableToken->n);
438     sqliteDequote(zTab);
439   }else{
440     assert( zDb==0 );
441     zTab = 0;
442   }
443   zCol = sqliteStrNDup(pColumnToken->z, pColumnToken->n);
444   sqliteDequote(zCol);
445   if( sqlite_malloc_failed ){
446     return 1;  /* Leak memory (zDb and zTab) if malloc fails */
447   }
448   assert( zTab==0 || pEList==0 );
449 
450   pExpr->iTable = -1;
451   for(i=0; i<pSrcList->nSrc; i++){
452     struct SrcList_item *pItem = &pSrcList->a[i];
453     Table *pTab = pItem->pTab;
454     Column *pCol;
455 
456     if( pTab==0 ) continue;
457     assert( pTab->nCol>0 );
458     if( zTab ){
459       if( pItem->zAlias ){
460         char *zTabName = pItem->zAlias;
461         if( sqliteStrICmp(zTabName, zTab)!=0 ) continue;
462       }else{
463         char *zTabName = pTab->zName;
464         if( zTabName==0 || sqliteStrICmp(zTabName, zTab)!=0 ) continue;
465         if( zDb!=0 && sqliteStrICmp(db->aDb[pTab->iDb].zName, zDb)!=0 ){
466           continue;
467         }
468       }
469     }
470     if( 0==(cntTab++) ){
471       pExpr->iTable = pItem->iCursor;
472       pExpr->iDb = pTab->iDb;
473     }
474     for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
475       if( sqliteStrICmp(pCol->zName, zCol)==0 ){
476         cnt++;
477         pExpr->iTable = pItem->iCursor;
478         pExpr->iDb = pTab->iDb;
479         /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
480         pExpr->iColumn = j==pTab->iPKey ? -1 : j;
481         pExpr->dataType = pCol->sortOrder & SQLITE_SO_TYPEMASK;
482         break;
483       }
484     }
485   }
486 
487   /* If we have not already resolved the name, then maybe
488   ** it is a new.* or old.* trigger argument reference
489   */
490   if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
491     TriggerStack *pTriggerStack = pParse->trigStack;
492     Table *pTab = 0;
493     if( pTriggerStack->newIdx != -1 && sqliteStrICmp("new", zTab) == 0 ){
494       pExpr->iTable = pTriggerStack->newIdx;
495       assert( pTriggerStack->pTab );
496       pTab = pTriggerStack->pTab;
497     }else if( pTriggerStack->oldIdx != -1 && sqliteStrICmp("old", zTab) == 0 ){
498       pExpr->iTable = pTriggerStack->oldIdx;
499       assert( pTriggerStack->pTab );
500       pTab = pTriggerStack->pTab;
501     }
502 
503     if( pTab ){
504       int j;
505       Column *pCol = pTab->aCol;
506 
507       pExpr->iDb = pTab->iDb;
508       cntTab++;
509       for(j=0; j < pTab->nCol; j++, pCol++) {
510         if( sqliteStrICmp(pCol->zName, zCol)==0 ){
511           cnt++;
512           pExpr->iColumn = j==pTab->iPKey ? -1 : j;
513           pExpr->dataType = pCol->sortOrder & SQLITE_SO_TYPEMASK;
514           break;
515         }
516       }
517     }
518   }
519 
520   /*
521   ** Perhaps the name is a reference to the ROWID
522   */
523   if( cnt==0 && cntTab==1 && sqliteIsRowid(zCol) ){
524     cnt = 1;
525     pExpr->iColumn = -1;
526     pExpr->dataType = SQLITE_SO_NUM;
527   }
528 
529   /*
530   ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
531   ** might refer to an result-set alias.  This happens, for example, when
532   ** we are resolving names in the WHERE clause of the following command:
533   **
534   **     SELECT a+b AS x FROM table WHERE x<10;
535   **
536   ** In cases like this, replace pExpr with a copy of the expression that
537   ** forms the result set entry ("a+b" in the example) and return immediately.
538   ** Note that the expression in the result set should have already been
539   ** resolved by the time the WHERE clause is resolved.
540   */
541   if( cnt==0 && pEList!=0 ){
542     for(j=0; j<pEList->nExpr; j++){
543       char *zAs = pEList->a[j].zName;
544       if( zAs!=0 && sqliteStrICmp(zAs, zCol)==0 ){
545         assert( pExpr->pLeft==0 && pExpr->pRight==0 );
546         pExpr->op = TK_AS;
547         pExpr->iColumn = j;
548         pExpr->pLeft = sqliteExprDup(pEList->a[j].pExpr);
549         sqliteFree(zCol);
550         assert( zTab==0 && zDb==0 );
551         return 0;
552       }
553     }
554   }
555 
556   /*
557   ** If X and Y are NULL (in other words if only the column name Z is
558   ** supplied) and the value of Z is enclosed in double-quotes, then
559   ** Z is a string literal if it doesn't match any column names.  In that
560   ** case, we need to return right away and not make any changes to
561   ** pExpr.
562   */
563   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
564     sqliteFree(zCol);
565     return 0;
566   }
567 
568   /*
569   ** cnt==0 means there was not match.  cnt>1 means there were two or
570   ** more matches.  Either way, we have an error.
571   */
572   if( cnt!=1 ){
573     char *z = 0;
574     char *zErr;
575     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
576     if( zDb ){
577       sqliteSetString(&z, zDb, ".", zTab, ".", zCol, 0);
578     }else if( zTab ){
579       sqliteSetString(&z, zTab, ".", zCol, 0);
580     }else{
581       z = sqliteStrDup(zCol);
582     }
583     sqliteErrorMsg(pParse, zErr, z);
584     sqliteFree(z);
585   }
586 
587   /* Clean up and return
588   */
589   sqliteFree(zDb);
590   sqliteFree(zTab);
591   sqliteFree(zCol);
592   sqliteExprDelete(pExpr->pLeft);
593   pExpr->pLeft = 0;
594   sqliteExprDelete(pExpr->pRight);
595   pExpr->pRight = 0;
596   pExpr->op = TK_COLUMN;
597   sqliteAuthRead(pParse, pExpr, pSrcList);
598   return cnt!=1;
599 }
600 
601 /*
602 ** This routine walks an expression tree and resolves references to
603 ** table columns.  Nodes of the form ID.ID or ID resolve into an
604 ** index to the table in the table list and a column offset.  The
605 ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
606 ** value is changed to the index of the referenced table in pTabList
607 ** plus the "base" value.  The base value will ultimately become the
608 ** VDBE cursor number for a cursor that is pointing into the referenced
609 ** table.  The Expr.iColumn value is changed to the index of the column
610 ** of the referenced table.  The Expr.iColumn value for the special
611 ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
612 ** alias for ROWID.
613 **
614 ** We also check for instances of the IN operator.  IN comes in two
615 ** forms:
616 **
617 **           expr IN (exprlist)
618 ** and
619 **           expr IN (SELECT ...)
620 **
621 ** The first form is handled by creating a set holding the list
622 ** of allowed values.  The second form causes the SELECT to generate
623 ** a temporary table.
624 **
625 ** This routine also looks for scalar SELECTs that are part of an expression.
626 ** If it finds any, it generates code to write the value of that select
627 ** into a memory cell.
628 **
629 ** Unknown columns or tables provoke an error.  The function returns
630 ** the number of errors seen and leaves an error message on pParse->zErrMsg.
631 */
632 int sqliteExprResolveIds(
633   Parse *pParse,     /* The parser context */
634   SrcList *pSrcList, /* List of tables used to resolve column names */
635   ExprList *pEList,  /* List of expressions used to resolve "AS" */
636   Expr *pExpr        /* The expression to be analyzed. */
637 ){
638   int i;
639 
640   if( pExpr==0 || pSrcList==0 ) return 0;
641   for(i=0; i<pSrcList->nSrc; i++){
642     assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab );
643   }
644   switch( pExpr->op ){
645     /* Double-quoted strings (ex: "abc") are used as identifiers if
646     ** possible.  Otherwise they remain as strings.  Single-quoted
647     ** strings (ex: 'abc') are always string literals.
648     */
649     case TK_STRING: {
650       if( pExpr->token.z[0]=='\'' ) break;
651       /* Fall thru into the TK_ID case if this is a double-quoted string */
652     }
653     /* A lone identifier is the name of a columnd.
654     */
655     case TK_ID: {
656       if( lookupName(pParse, 0, 0, &pExpr->token, pSrcList, pEList, pExpr) ){
657         return 1;
658       }
659       break;
660     }
661 
662     /* A table name and column name:     ID.ID
663     ** Or a database, table and column:  ID.ID.ID
664     */
665     case TK_DOT: {
666       Token *pColumn;
667       Token *pTable;
668       Token *pDb;
669       Expr *pRight;
670 
671       pRight = pExpr->pRight;
672       if( pRight->op==TK_ID ){
673         pDb = 0;
674         pTable = &pExpr->pLeft->token;
675         pColumn = &pRight->token;
676       }else{
677         assert( pRight->op==TK_DOT );
678         pDb = &pExpr->pLeft->token;
679         pTable = &pRight->pLeft->token;
680         pColumn = &pRight->pRight->token;
681       }
682       if( lookupName(pParse, pDb, pTable, pColumn, pSrcList, 0, pExpr) ){
683         return 1;
684       }
685       break;
686     }
687 
688     case TK_IN: {
689       Vdbe *v = sqliteGetVdbe(pParse);
690       if( v==0 ) return 1;
691       if( sqliteExprResolveIds(pParse, pSrcList, pEList, pExpr->pLeft) ){
692         return 1;
693       }
694       if( pExpr->pSelect ){
695         /* Case 1:     expr IN (SELECT ...)
696         **
697         ** Generate code to write the results of the select into a temporary
698         ** table.  The cursor number of the temporary table has already
699         ** been put in iTable by sqliteExprResolveInSelect().
700         */
701         pExpr->iTable = pParse->nTab++;
702         sqliteVdbeAddOp(v, OP_OpenTemp, pExpr->iTable, 1);
703         sqliteSelect(pParse, pExpr->pSelect, SRT_Set, pExpr->iTable, 0,0,0);
704       }else if( pExpr->pList ){
705         /* Case 2:     expr IN (exprlist)
706         **
707         ** Create a set to put the exprlist values in.  The Set id is stored
708         ** in iTable.
709         */
710         int i, iSet;
711         for(i=0; i<pExpr->pList->nExpr; i++){
712           Expr *pE2 = pExpr->pList->a[i].pExpr;
713           if( !sqliteExprIsConstant(pE2) ){
714             sqliteErrorMsg(pParse,
715               "right-hand side of IN operator must be constant");
716             return 1;
717           }
718           if( sqliteExprCheck(pParse, pE2, 0, 0) ){
719             return 1;
720           }
721         }
722         iSet = pExpr->iTable = pParse->nSet++;
723         for(i=0; i<pExpr->pList->nExpr; i++){
724           Expr *pE2 = pExpr->pList->a[i].pExpr;
725           switch( pE2->op ){
726             case TK_FLOAT:
727             case TK_INTEGER:
728             case TK_STRING: {
729               int addr;
730               assert( pE2->token.z );
731               addr = sqliteVdbeOp3(v, OP_SetInsert, iSet, 0,
732                                   pE2->token.z, pE2->token.n);
733               sqliteVdbeDequoteP3(v, addr);
734               break;
735             }
736             default: {
737               sqliteExprCode(pParse, pE2);
738               sqliteVdbeAddOp(v, OP_SetInsert, iSet, 0);
739               break;
740             }
741           }
742         }
743       }
744       break;
745     }
746 
747     case TK_SELECT: {
748       /* This has to be a scalar SELECT.  Generate code to put the
749       ** value of this select in a memory cell and record the number
750       ** of the memory cell in iColumn.
751       */
752       pExpr->iColumn = pParse->nMem++;
753       if( sqliteSelect(pParse, pExpr->pSelect, SRT_Mem, pExpr->iColumn,0,0,0) ){
754         return 1;
755       }
756       break;
757     }
758 
759     /* For all else, just recursively walk the tree */
760     default: {
761       if( pExpr->pLeft
762       && sqliteExprResolveIds(pParse, pSrcList, pEList, pExpr->pLeft) ){
763         return 1;
764       }
765       if( pExpr->pRight
766       && sqliteExprResolveIds(pParse, pSrcList, pEList, pExpr->pRight) ){
767         return 1;
768       }
769       if( pExpr->pList ){
770         int i;
771         ExprList *pList = pExpr->pList;
772         for(i=0; i<pList->nExpr; i++){
773           Expr *pArg = pList->a[i].pExpr;
774           if( sqliteExprResolveIds(pParse, pSrcList, pEList, pArg) ){
775             return 1;
776           }
777         }
778       }
779     }
780   }
781   return 0;
782 }
783 
784 /*
785 ** pExpr is a node that defines a function of some kind.  It might
786 ** be a syntactic function like "count(x)" or it might be a function
787 ** that implements an operator, like "a LIKE b".
788 **
789 ** This routine makes *pzName point to the name of the function and
790 ** *pnName hold the number of characters in the function name.
791 */
792 static void getFunctionName(Expr *pExpr, const char **pzName, int *pnName){
793   switch( pExpr->op ){
794     case TK_FUNCTION: {
795       *pzName = pExpr->token.z;
796       *pnName = pExpr->token.n;
797       break;
798     }
799     case TK_LIKE: {
800       *pzName = "like";
801       *pnName = 4;
802       break;
803     }
804     case TK_GLOB: {
805       *pzName = "glob";
806       *pnName = 4;
807       break;
808     }
809     default: {
810       *pzName = "can't happen";
811       *pnName = 12;
812       break;
813     }
814   }
815 }
816 
817 /*
818 ** Error check the functions in an expression.  Make sure all
819 ** function names are recognized and all functions have the correct
820 ** number of arguments.  Leave an error message in pParse->zErrMsg
821 ** if anything is amiss.  Return the number of errors.
822 **
823 ** if pIsAgg is not null and this expression is an aggregate function
824 ** (like count(*) or max(value)) then write a 1 into *pIsAgg.
825 */
826 int sqliteExprCheck(Parse *pParse, Expr *pExpr, int allowAgg, int *pIsAgg){
827   int nErr = 0;
828   if( pExpr==0 ) return 0;
829   switch( pExpr->op ){
830     case TK_GLOB:
831     case TK_LIKE:
832     case TK_FUNCTION: {
833       int n = pExpr->pList ? pExpr->pList->nExpr : 0;  /* Number of arguments */
834       int no_such_func = 0;       /* True if no such function exists */
835       int wrong_num_args = 0;     /* True if wrong number of arguments */
836       int is_agg = 0;             /* True if is an aggregate function */
837       int i;
838       int nId;                    /* Number of characters in function name */
839       const char *zId;            /* The function name. */
840       FuncDef *pDef;
841 
842       getFunctionName(pExpr, &zId, &nId);
843       pDef = sqliteFindFunction(pParse->db, zId, nId, n, 0);
844       if( pDef==0 ){
845         pDef = sqliteFindFunction(pParse->db, zId, nId, -1, 0);
846         if( pDef==0 ){
847           no_such_func = 1;
848         }else{
849           wrong_num_args = 1;
850         }
851       }else{
852         is_agg = pDef->xFunc==0;
853       }
854       if( is_agg && !allowAgg ){
855         sqliteErrorMsg(pParse, "misuse of aggregate function %.*s()", nId, zId);
856         nErr++;
857         is_agg = 0;
858       }else if( no_such_func ){
859         sqliteErrorMsg(pParse, "no such function: %.*s", nId, zId);
860         nErr++;
861       }else if( wrong_num_args ){
862         sqliteErrorMsg(pParse,"wrong number of arguments to function %.*s()",
863              nId, zId);
864         nErr++;
865       }
866       if( is_agg ){
867         pExpr->op = TK_AGG_FUNCTION;
868         if( pIsAgg ) *pIsAgg = 1;
869       }
870       for(i=0; nErr==0 && i<n; i++){
871         nErr = sqliteExprCheck(pParse, pExpr->pList->a[i].pExpr,
872                                allowAgg && !is_agg, pIsAgg);
873       }
874       if( pDef==0 ){
875         /* Already reported an error */
876       }else if( pDef->dataType>=0 ){
877         if( pDef->dataType<n ){
878           pExpr->dataType =
879              sqliteExprType(pExpr->pList->a[pDef->dataType].pExpr);
880         }else{
881           pExpr->dataType = SQLITE_SO_NUM;
882         }
883       }else if( pDef->dataType==SQLITE_ARGS ){
884         pDef->dataType = SQLITE_SO_TEXT;
885         for(i=0; i<n; i++){
886           if( sqliteExprType(pExpr->pList->a[i].pExpr)==SQLITE_SO_NUM ){
887             pExpr->dataType = SQLITE_SO_NUM;
888             break;
889           }
890         }
891       }else if( pDef->dataType==SQLITE_NUMERIC ){
892         pExpr->dataType = SQLITE_SO_NUM;
893       }else{
894         pExpr->dataType = SQLITE_SO_TEXT;
895       }
896     }
897     default: {
898       if( pExpr->pLeft ){
899         nErr = sqliteExprCheck(pParse, pExpr->pLeft, allowAgg, pIsAgg);
900       }
901       if( nErr==0 && pExpr->pRight ){
902         nErr = sqliteExprCheck(pParse, pExpr->pRight, allowAgg, pIsAgg);
903       }
904       if( nErr==0 && pExpr->pList ){
905         int n = pExpr->pList->nExpr;
906         int i;
907         for(i=0; nErr==0 && i<n; i++){
908           Expr *pE2 = pExpr->pList->a[i].pExpr;
909           nErr = sqliteExprCheck(pParse, pE2, allowAgg, pIsAgg);
910         }
911       }
912       break;
913     }
914   }
915   return nErr;
916 }
917 
918 /*
919 ** Return either SQLITE_SO_NUM or SQLITE_SO_TEXT to indicate whether the
920 ** given expression should sort as numeric values or as text.
921 **
922 ** The sqliteExprResolveIds() and sqliteExprCheck() routines must have
923 ** both been called on the expression before it is passed to this routine.
924 */
925 int sqliteExprType(Expr *p){
926   if( p==0 ) return SQLITE_SO_NUM;
927   while( p ) switch( p->op ){
928     case TK_PLUS:
929     case TK_MINUS:
930     case TK_STAR:
931     case TK_SLASH:
932     case TK_AND:
933     case TK_OR:
934     case TK_ISNULL:
935     case TK_NOTNULL:
936     case TK_NOT:
937     case TK_UMINUS:
938     case TK_UPLUS:
939     case TK_BITAND:
940     case TK_BITOR:
941     case TK_BITNOT:
942     case TK_LSHIFT:
943     case TK_RSHIFT:
944     case TK_REM:
945     case TK_INTEGER:
946     case TK_FLOAT:
947     case TK_IN:
948     case TK_BETWEEN:
949     case TK_GLOB:
950     case TK_LIKE:
951       return SQLITE_SO_NUM;
952 
953     case TK_STRING:
954     case TK_NULL:
955     case TK_CONCAT:
956     case TK_VARIABLE:
957       return SQLITE_SO_TEXT;
958 
959     case TK_LT:
960     case TK_LE:
961     case TK_GT:
962     case TK_GE:
963     case TK_NE:
964     case TK_EQ:
965       if( sqliteExprType(p->pLeft)==SQLITE_SO_NUM ){
966         return SQLITE_SO_NUM;
967       }
968       p = p->pRight;
969       break;
970 
971     case TK_AS:
972       p = p->pLeft;
973       break;
974 
975     case TK_COLUMN:
976     case TK_FUNCTION:
977     case TK_AGG_FUNCTION:
978       return p->dataType;
979 
980     case TK_SELECT:
981       assert( p->pSelect );
982       assert( p->pSelect->pEList );
983       assert( p->pSelect->pEList->nExpr>0 );
984       p = p->pSelect->pEList->a[0].pExpr;
985       break;
986 
987     case TK_CASE: {
988       if( p->pRight && sqliteExprType(p->pRight)==SQLITE_SO_NUM ){
989         return SQLITE_SO_NUM;
990       }
991       if( p->pList ){
992         int i;
993         ExprList *pList = p->pList;
994         for(i=1; i<pList->nExpr; i+=2){
995           if( sqliteExprType(pList->a[i].pExpr)==SQLITE_SO_NUM ){
996             return SQLITE_SO_NUM;
997           }
998         }
999       }
1000       return SQLITE_SO_TEXT;
1001     }
1002 
1003     default:
1004       assert( p->op==TK_ABORT );  /* Can't Happen */
1005       break;
1006   }
1007   return SQLITE_SO_NUM;
1008 }
1009 
1010 /*
1011 ** Generate code into the current Vdbe to evaluate the given
1012 ** expression and leave the result on the top of stack.
1013 */
1014 void sqliteExprCode(Parse *pParse, Expr *pExpr){
1015   Vdbe *v = pParse->pVdbe;
1016   int op;
1017   if( v==0 || pExpr==0 ) return;
1018   switch( pExpr->op ){
1019     case TK_PLUS:     op = OP_Add;      break;
1020     case TK_MINUS:    op = OP_Subtract; break;
1021     case TK_STAR:     op = OP_Multiply; break;
1022     case TK_SLASH:    op = OP_Divide;   break;
1023     case TK_AND:      op = OP_And;      break;
1024     case TK_OR:       op = OP_Or;       break;
1025     case TK_LT:       op = OP_Lt;       break;
1026     case TK_LE:       op = OP_Le;       break;
1027     case TK_GT:       op = OP_Gt;       break;
1028     case TK_GE:       op = OP_Ge;       break;
1029     case TK_NE:       op = OP_Ne;       break;
1030     case TK_EQ:       op = OP_Eq;       break;
1031     case TK_ISNULL:   op = OP_IsNull;   break;
1032     case TK_NOTNULL:  op = OP_NotNull;  break;
1033     case TK_NOT:      op = OP_Not;      break;
1034     case TK_UMINUS:   op = OP_Negative; break;
1035     case TK_BITAND:   op = OP_BitAnd;   break;
1036     case TK_BITOR:    op = OP_BitOr;    break;
1037     case TK_BITNOT:   op = OP_BitNot;   break;
1038     case TK_LSHIFT:   op = OP_ShiftLeft;  break;
1039     case TK_RSHIFT:   op = OP_ShiftRight; break;
1040     case TK_REM:      op = OP_Remainder;  break;
1041     default: break;
1042   }
1043   switch( pExpr->op ){
1044     case TK_COLUMN: {
1045       if( pParse->useAgg ){
1046         sqliteVdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
1047       }else if( pExpr->iColumn>=0 ){
1048         sqliteVdbeAddOp(v, OP_Column, pExpr->iTable, pExpr->iColumn);
1049       }else{
1050         sqliteVdbeAddOp(v, OP_Recno, pExpr->iTable, 0);
1051       }
1052       break;
1053     }
1054     case TK_STRING:
1055     case TK_FLOAT:
1056     case TK_INTEGER: {
1057       if( pExpr->op==TK_INTEGER && sqliteFitsIn32Bits(pExpr->token.z) ){
1058         sqliteVdbeAddOp(v, OP_Integer, atoi(pExpr->token.z), 0);
1059       }else{
1060         sqliteVdbeAddOp(v, OP_String, 0, 0);
1061       }
1062       assert( pExpr->token.z );
1063       sqliteVdbeChangeP3(v, -1, pExpr->token.z, pExpr->token.n);
1064       sqliteVdbeDequoteP3(v, -1);
1065       break;
1066     }
1067     case TK_NULL: {
1068       sqliteVdbeAddOp(v, OP_String, 0, 0);
1069       break;
1070     }
1071     case TK_VARIABLE: {
1072       sqliteVdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1073       break;
1074     }
1075     case TK_LT:
1076     case TK_LE:
1077     case TK_GT:
1078     case TK_GE:
1079     case TK_NE:
1080     case TK_EQ: {
1081       if( pParse->db->file_format>=4 && sqliteExprType(pExpr)==SQLITE_SO_TEXT ){
1082         op += 6;  /* Convert numeric opcodes to text opcodes */
1083       }
1084       /* Fall through into the next case */
1085     }
1086     case TK_AND:
1087     case TK_OR:
1088     case TK_PLUS:
1089     case TK_STAR:
1090     case TK_MINUS:
1091     case TK_REM:
1092     case TK_BITAND:
1093     case TK_BITOR:
1094     case TK_SLASH: {
1095       sqliteExprCode(pParse, pExpr->pLeft);
1096       sqliteExprCode(pParse, pExpr->pRight);
1097       sqliteVdbeAddOp(v, op, 0, 0);
1098       break;
1099     }
1100     case TK_LSHIFT:
1101     case TK_RSHIFT: {
1102       sqliteExprCode(pParse, pExpr->pRight);
1103       sqliteExprCode(pParse, pExpr->pLeft);
1104       sqliteVdbeAddOp(v, op, 0, 0);
1105       break;
1106     }
1107     case TK_CONCAT: {
1108       sqliteExprCode(pParse, pExpr->pLeft);
1109       sqliteExprCode(pParse, pExpr->pRight);
1110       sqliteVdbeAddOp(v, OP_Concat, 2, 0);
1111       break;
1112     }
1113     case TK_UMINUS: {
1114       assert( pExpr->pLeft );
1115       if( pExpr->pLeft->op==TK_FLOAT || pExpr->pLeft->op==TK_INTEGER ){
1116         Token *p = &pExpr->pLeft->token;
1117         char *z = sqliteMalloc( p->n + 2 );
1118         sprintf(z, "-%.*s", p->n, p->z);
1119         if( pExpr->pLeft->op==TK_INTEGER && sqliteFitsIn32Bits(z) ){
1120           sqliteVdbeAddOp(v, OP_Integer, atoi(z), 0);
1121         }else{
1122           sqliteVdbeAddOp(v, OP_String, 0, 0);
1123         }
1124         sqliteVdbeChangeP3(v, -1, z, p->n+1);
1125         sqliteFree(z);
1126         break;
1127       }
1128       /* Fall through into TK_NOT */
1129     }
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 */
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 */
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 */
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 */
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 */
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 */
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 */
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