Team Ai
Modelpublic

AryaWu/sqlite

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
expr.c7688 linesDownload Raw Back to src
1/*2** 2001 September 153**4** The author disclaims copyright to this source code.  In place of5** 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 and13** for generating VDBE code that evaluates expressions in SQLite.14*/15#include "sqliteInt.h"16 17/* Forward declarations */18static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);19static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);20 21/*22** Return the affinity character for a single column of a table.23*/24char sqlite3TableColumnAffinity(const Table *pTab, int iCol){25  if( iCol<0 || NEVER(iCol>=pTab->nCol) ) return SQLITE_AFF_INTEGER;26  return pTab->aCol[iCol].affinity;27}28 29/*30** Return the 'affinity' of the expression pExpr if any.31**32** If pExpr is a column, a reference to a column via an 'AS' alias,33** or a sub-select with a column as the return value, then the34** affinity of that column is returned. Otherwise, 0x00 is returned,35** indicating no affinity for the expression.36**37** i.e. the WHERE clause expressions in the following statements all38** have an affinity:39**40** CREATE TABLE t1(a);41** SELECT * FROM t1 WHERE a;42** SELECT a AS b FROM t1 WHERE b;43** SELECT * FROM t1 WHERE (select a from t1);44*/45char sqlite3ExprAffinity(const Expr *pExpr){46  int op;47  op = pExpr->op;48  while( 1 /* exit-by-break */ ){49    if( op==TK_COLUMN || (op==TK_AGG_COLUMN && pExpr->y.pTab!=0) ){50      assert( ExprUseYTab(pExpr) );51      assert( pExpr->y.pTab!=0 );52      return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);53    }54    if( op==TK_SELECT ){55      assert( ExprUseXSelect(pExpr) );56      assert( pExpr->x.pSelect!=0 );57      assert( pExpr->x.pSelect->pEList!=0 );58      assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 );59      return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);60    }61#ifndef SQLITE_OMIT_CAST62    if( op==TK_CAST ){63      assert( !ExprHasProperty(pExpr, EP_IntValue) );64      return sqlite3AffinityType(pExpr->u.zToken, 0);65    }66#endif67    if( op==TK_SELECT_COLUMN ){68      assert( pExpr->pLeft!=0 && ExprUseXSelect(pExpr->pLeft) );69      assert( pExpr->iColumn < pExpr->iTable );70      assert( pExpr->iColumn >= 0 );71      assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr );72      return sqlite3ExprAffinity(73          pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr74      );75    }76    if( op==TK_VECTOR77     || (op==TK_FUNCTION && pExpr->affExpr==SQLITE_AFF_DEFER)78    ){79      assert( ExprUseXList(pExpr) );80      return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);81    }82    if( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){83      assert( pExpr->op==TK_COLLATE84           || pExpr->op==TK_IF_NULL_ROW85           || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );86      pExpr = pExpr->pLeft;87      op = pExpr->op;88      continue;89    }90    if( op!=TK_REGISTER ) break;91    op = pExpr->op2;92    if( NEVER( op==TK_REGISTER ) ) break;93  }94  return pExpr->affExpr;95}96 97/*98** Make a guess at all the possible datatypes of the result that could99** be returned by an expression.  Return a bitmask indicating the answer:100**101**     0x01         Numeric102**     0x02         Text103**     0x04         Blob104**105** If the expression must return NULL, then 0x00 is returned.106*/107int sqlite3ExprDataType(const Expr *pExpr){108  while( pExpr ){109    switch( pExpr->op ){110      case TK_COLLATE:111      case TK_IF_NULL_ROW:112      case TK_UPLUS:  {113        pExpr = pExpr->pLeft;114        break;115      }116      case TK_NULL: {117        pExpr = 0;118        break;119      }120      case TK_STRING: {121        return 0x02;122      }123      case TK_BLOB: {124        return 0x04;125      }126      case TK_CONCAT: {127        return 0x06;128      }129      case TK_VARIABLE:130      case TK_AGG_FUNCTION:131      case TK_FUNCTION: {132        return 0x07;133      }134      case TK_COLUMN:135      case TK_AGG_COLUMN:136      case TK_SELECT:137      case TK_CAST:138      case TK_SELECT_COLUMN:139      case TK_VECTOR:  {140        int aff = sqlite3ExprAffinity(pExpr);141        if( aff>=SQLITE_AFF_NUMERIC ) return 0x05;142        if( aff==SQLITE_AFF_TEXT )    return 0x06;143        return 0x07;144      }145      case TK_CASE: {146        int res = 0;147        int ii;148        ExprList *pList = pExpr->x.pList;149        assert( ExprUseXList(pExpr) && pList!=0 );150        assert( pList->nExpr > 0);151        for(ii=1; ii<pList->nExpr; ii+=2){152          res |= sqlite3ExprDataType(pList->a[ii].pExpr);153        }154        if( pList->nExpr % 2 ){155          res |= sqlite3ExprDataType(pList->a[pList->nExpr-1].pExpr);156        }157        return res;158      }159      default: {160        return 0x01;161      }162    } /* End of switch(op) */163  } /* End of while(pExpr) */164  return 0x00;165}166 167/*168** Set the collating sequence for expression pExpr to be the collating169** sequence named by pToken.   Return a pointer to a new Expr node that170** implements the COLLATE operator.171**172** If a memory allocation error occurs, that fact is recorded in pParse->db173** and the pExpr parameter is returned unchanged.174*/175Expr *sqlite3ExprAddCollateToken(176  const Parse *pParse,     /* Parsing context */177  Expr *pExpr,             /* Add the "COLLATE" clause to this expression */178  const Token *pCollName,  /* Name of collating sequence */179  int dequote              /* True to dequote pCollName */180){181  if( pCollName->n>0 ){182    Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);183    if( pNew ){184      pNew->pLeft = pExpr;185      pNew->flags |= EP_Collate|EP_Skip;186      pExpr = pNew;187    }188  }189  return pExpr;190}191Expr *sqlite3ExprAddCollateString(192  const Parse *pParse,  /* Parsing context */193  Expr *pExpr,          /* Add the "COLLATE" clause to this expression */194  const char *zC        /* The collating sequence name */195){196  Token s;197  assert( zC!=0 );198  sqlite3TokenInit(&s, (char*)zC);199  return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);200}201 202/*203** Skip over any TK_COLLATE operators.204*/205Expr *sqlite3ExprSkipCollate(Expr *pExpr){206  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){207    assert( pExpr->op==TK_COLLATE );208    pExpr = pExpr->pLeft;209  }  210  return pExpr;211}212 213/*214** Skip over any TK_COLLATE operators and/or any unlikely()215** or likelihood() or likely() functions at the root of an216** expression.217*/218Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){219  while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){220    if( ExprHasProperty(pExpr, EP_Unlikely) ){221      assert( ExprUseXList(pExpr) );222      assert( pExpr->x.pList->nExpr>0 );223      assert( pExpr->op==TK_FUNCTION );224      pExpr = pExpr->x.pList->a[0].pExpr;225    }else if( pExpr->op==TK_COLLATE ){226      pExpr = pExpr->pLeft;227    }else{228      break;229    }230  }  231  return pExpr;232}233 234/*235** Return the collation sequence for the expression pExpr. If236** there is no defined collating sequence, return NULL.237**238** See also: sqlite3ExprNNCollSeq()239**240** The sqlite3ExprNNCollSeq() works the same exact that it returns the241** default collation if pExpr has no defined collation.242**243** The collating sequence might be determined by a COLLATE operator244** or by the presence of a column with a defined collating sequence.245** COLLATE operators take first precedence.  Left operands take246** precedence over right operands.247*/248CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){249  sqlite3 *db = pParse->db;250  CollSeq *pColl = 0;251  const Expr *p = pExpr;252  while( p ){253    int op = p->op;254    if( op==TK_REGISTER ) op = p->op2;255    if( (op==TK_AGG_COLUMN && p->y.pTab!=0)256     || op==TK_COLUMN || op==TK_TRIGGER257    ){258      int j;259      assert( ExprUseYTab(p) );260      assert( p->y.pTab!=0 );261      if( (j = p->iColumn)>=0 ){262        const char *zColl = sqlite3ColumnColl(&p->y.pTab->aCol[j]);263        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);264      }265      break;266    }267    if( op==TK_CAST || op==TK_UPLUS ){268      p = p->pLeft;269      continue;270    }271    if( op==TK_VECTOR272     || (op==TK_FUNCTION && p->affExpr==SQLITE_AFF_DEFER)273    ){274      assert( ExprUseXList(p) );275      p = p->x.pList->a[0].pExpr;276      continue;277    }278    if( op==TK_COLLATE ){279      assert( !ExprHasProperty(p, EP_IntValue) );280      pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);281      break;282    }283    if( p->flags & EP_Collate ){284      if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){285        p = p->pLeft;286      }else{287        Expr *pNext  = p->pRight;288        /* The Expr.x union is never used at the same time as Expr.pRight */289        assert( !ExprUseXList(p) || p->x.pList==0 || p->pRight==0 );290        if( ExprUseXList(p) && p->x.pList!=0 && !db->mallocFailed ){291          int i;292          for(i=0; i<p->x.pList->nExpr; i++){293            if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){294              pNext = p->x.pList->a[i].pExpr;295              break;296            }297          }298        }299        p = pNext;300      }301    }else{302      break;303    }304  }305  if( sqlite3CheckCollSeq(pParse, pColl) ){306    pColl = 0;307  }308  return pColl;309}310 311/*312** Return the collation sequence for the expression pExpr. If313** there is no defined collating sequence, return a pointer to the314** default collation sequence.315**316** See also: sqlite3ExprCollSeq()317**318** The sqlite3ExprCollSeq() routine works the same except that it319** returns NULL if there is no defined collation.320*/321CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){322  CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);323  if( p==0 ) p = pParse->db->pDfltColl;324  assert( p!=0 );325  return p;326}327 328/*329** Return TRUE if the two expressions have equivalent collating sequences.330*/331int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){332  CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);333  CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);334  return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;335}336 337/*338** pExpr is an operand of a comparison operator.  aff2 is the339** type affinity of the other operand.  This routine returns the340** type affinity that should be used for the comparison operator.341*/342char sqlite3CompareAffinity(const Expr *pExpr, char aff2){343  char aff1 = sqlite3ExprAffinity(pExpr);344  if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){345    /* Both sides of the comparison are columns. If one has numeric346    ** affinity, use that. Otherwise use no affinity.347    */348    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){349      return SQLITE_AFF_NUMERIC;350    }else{351      return SQLITE_AFF_BLOB;352    }353  }else{354    /* One side is a column, the other is not. Use the columns affinity. */355    assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );356    return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;357  }358}359 360/*361** pExpr is a comparison operator.  Return the type affinity that should362** be applied to both operands prior to doing the comparison.363*/364static char comparisonAffinity(const Expr *pExpr){365  char aff;366  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||367          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||368          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );369  assert( pExpr->pLeft );370  aff = sqlite3ExprAffinity(pExpr->pLeft);371  if( pExpr->pRight ){372    aff = sqlite3CompareAffinity(pExpr->pRight, aff);373  }else if( ExprUseXSelect(pExpr) ){374    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);375  }else if( aff==0 ){376    aff = SQLITE_AFF_BLOB;377  }378  return aff;379}380 381/*382** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.383** idx_affinity is the affinity of an indexed column. Return true384** if the index with affinity idx_affinity may be used to implement385** the comparison in pExpr.386*/387int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){388  char aff = comparisonAffinity(pExpr);389  if( aff<SQLITE_AFF_TEXT ){390    return 1;391  }392  if( aff==SQLITE_AFF_TEXT ){393    return idx_affinity==SQLITE_AFF_TEXT;394  }395  return sqlite3IsNumericAffinity(idx_affinity);396}397 398/*399** Return the P5 value that should be used for a binary comparison400** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.401*/402static u8 binaryCompareP5(403  const Expr *pExpr1,   /* Left operand */404  const Expr *pExpr2,   /* Right operand */405  int jumpIfNull        /* Extra flags added to P5 */406){407  u8 aff = (char)sqlite3ExprAffinity(pExpr2);408  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;409  return aff;410}411 412/*413** Return a pointer to the collation sequence that should be used by414** a binary comparison operator comparing pLeft and pRight.415**416** If the left hand expression has a collating sequence type, then it is417** used. Otherwise the collation sequence for the right hand expression418** is used, or the default (BINARY) if neither expression has a collating419** type.420**421** Argument pRight (but not pLeft) may be a null pointer. In this case,422** it is not considered.423*/424CollSeq *sqlite3BinaryCompareCollSeq(425  Parse *pParse,426  const Expr *pLeft,427  const Expr *pRight428){429  CollSeq *pColl;430  assert( pLeft );431  if( pLeft->flags & EP_Collate ){432    pColl = sqlite3ExprCollSeq(pParse, pLeft);433  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){434    pColl = sqlite3ExprCollSeq(pParse, pRight);435  }else{436    pColl = sqlite3ExprCollSeq(pParse, pLeft);437    if( !pColl ){438      pColl = sqlite3ExprCollSeq(pParse, pRight);439    }440  }441  return pColl;442}443 444/* Expression p is a comparison operator.  Return a collation sequence445** appropriate for the comparison operator.446**447** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().448** However, if the OP_Commuted flag is set, then the order of the operands449** is reversed in the sqlite3BinaryCompareCollSeq() call so that the450** correct collating sequence is found.451*/452CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){453  if( ExprHasProperty(p, EP_Commuted) ){454    return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);455  }else{456    return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);457  }458}459 460/*461** Generate code for a comparison operator.462*/463static int codeCompare(464  Parse *pParse,    /* The parsing (and code generating) context */465  Expr *pLeft,      /* The left operand */466  Expr *pRight,     /* The right operand */467  int opcode,       /* The comparison opcode */468  int in1, int in2, /* Register holding operands */469  int dest,         /* Jump here if true.  */470  int jumpIfNull,   /* If true, jump if either operand is NULL */471  int isCommuted    /* The comparison has been commuted */472){473  int p5;474  int addr;475  CollSeq *p4;476 477  if( pParse->nErr ) return 0;478  if( isCommuted ){479    p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);480  }else{481    p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);482  }483  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);484  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,485                           (void*)p4, P4_COLLSEQ);486  sqlite3VdbeChangeP5(pParse->pVdbe, (u16)p5);487  return addr;488}489 490/*491** Return true if expression pExpr is a vector, or false otherwise.492**493** A vector is defined as any expression that results in two or more494** columns of result.  Every TK_VECTOR node is an vector because the495** parser will not generate a TK_VECTOR with fewer than two entries.496** But a TK_SELECT might be either a vector or a scalar. It is only497** considered a vector if it has two or more result columns.498*/499int sqlite3ExprIsVector(const Expr *pExpr){500  return sqlite3ExprVectorSize(pExpr)>1;501}502 503/*504** If the expression passed as the only argument is of type TK_VECTOR505** return the number of expressions in the vector. Or, if the expression506** is a sub-select, return the number of columns in the sub-select. For507** any other type of expression, return 1.508*/509int sqlite3ExprVectorSize(const Expr *pExpr){510  u8 op = pExpr->op;511  if( op==TK_REGISTER ) op = pExpr->op2;512  if( op==TK_VECTOR ){513    assert( ExprUseXList(pExpr) );514    return pExpr->x.pList->nExpr;515  }else if( op==TK_SELECT ){516    assert( ExprUseXSelect(pExpr) );517    return pExpr->x.pSelect->pEList->nExpr;518  }else{519    return 1;520  }521}522 523/*524** Return a pointer to a subexpression of pVector that is the i-th525** column of the vector (numbered starting with 0).  The caller must526** ensure that i is within range.527**528** If pVector is really a scalar (and "scalar" here includes subqueries529** that return a single column!) then return pVector unmodified.530**531** pVector retains ownership of the returned subexpression.532**533** If the vector is a (SELECT ...) then the expression returned is534** just the expression for the i-th term of the result set, and may535** not be ready for evaluation because the table cursor has not yet536** been positioned.537*/538Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){539  assert( i<sqlite3ExprVectorSize(pVector) || pVector->op==TK_ERROR );540  if( sqlite3ExprIsVector(pVector) ){541    assert( pVector->op2==0 || pVector->op==TK_REGISTER );542    if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){543      assert( ExprUseXSelect(pVector) );544      return pVector->x.pSelect->pEList->a[i].pExpr;545    }else{546      assert( ExprUseXList(pVector) );547      return pVector->x.pList->a[i].pExpr;548    }549  }550  return pVector;551}552 553/*554** Compute and return a new Expr object which when passed to555** sqlite3ExprCode() will generate all necessary code to compute556** the iField-th column of the vector expression pVector.557**558** It is ok for pVector to be a scalar (as long as iField==0). 559** In that case, this routine works like sqlite3ExprDup().560**561** The caller owns the returned Expr object and is responsible for562** ensuring that the returned value eventually gets freed.563**564** The caller retains ownership of pVector.  If pVector is a TK_SELECT,565** then the returned object will reference pVector and so pVector must remain566** valid for the life of the returned object.  If pVector is a TK_VECTOR567** or a scalar expression, then it can be deleted as soon as this routine568** returns.569**570** A trick to cause a TK_SELECT pVector to be deleted together with571** the returned Expr object is to attach the pVector to the pRight field572** of the returned TK_SELECT_COLUMN Expr object.573*/574Expr *sqlite3ExprForVectorField(575  Parse *pParse,       /* Parsing context */576  Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */577  int iField,          /* Which column of the vector to return */578  int nField           /* Total number of columns in the vector */579){580  Expr *pRet;581  if( pVector->op==TK_SELECT ){582    assert( ExprUseXSelect(pVector) );583    /* The TK_SELECT_COLUMN Expr node:584    **585    ** pLeft:           pVector containing TK_SELECT.  Not deleted.586    ** pRight:          not used.  But recursively deleted.587    ** iColumn:         Index of a column in pVector588    ** iTable:          0 or the number of columns on the LHS of an assignment589    ** pLeft->iTable:   First in an array of register holding result, or 0590    **                  if the result is not yet computed.591    **592    ** sqlite3ExprDelete() specifically skips the recursive delete of593    ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector594    ** can be attached to pRight to cause this node to take ownership of595    ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes596    ** with the same pLeft pointer to the pVector, but only one of them597    ** will own the pVector.598    */599    pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);600    if( pRet ){601      ExprSetProperty(pRet, EP_FullSize);602      pRet->iTable = nField;603      pRet->iColumn = iField;604      pRet->pLeft = pVector;605    }606  }else{607    if( pVector->op==TK_VECTOR ){608      Expr **ppVector;609      assert( ExprUseXList(pVector) );610      ppVector = &pVector->x.pList->a[iField].pExpr;611      pVector = *ppVector;612      if( IN_RENAME_OBJECT ){613        /* This must be a vector UPDATE inside a trigger */614        *ppVector = 0;615        return pVector;616      }617    }618    pRet = sqlite3ExprDup(pParse->db, pVector, 0);619  }620  return pRet;621}622 623/*624** If expression pExpr is of type TK_SELECT, generate code to evaluate625** it. Return the register in which the result is stored (or, if the626** sub-select returns more than one column, the first in an array627** of registers in which the result is stored).628**629** If pExpr is not a TK_SELECT expression, return 0.630*/631static int exprCodeSubselect(Parse *pParse, Expr *pExpr){632  int reg = 0;633#ifndef SQLITE_OMIT_SUBQUERY634  if( pExpr->op==TK_SELECT ){635    reg = sqlite3CodeSubselect(pParse, pExpr);636  }637#endif638  return reg;639}640 641/*642** Argument pVector points to a vector expression - either a TK_VECTOR643** or TK_SELECT that returns more than one column. This function returns644** the register number of a register that contains the value of645** element iField of the vector.646**647** If pVector is a TK_SELECT expression, then code for it must have648** already been generated using the exprCodeSubselect() routine. In this649** case parameter regSelect should be the first in an array of registers650** containing the results of the sub-select.651**652** If pVector is of type TK_VECTOR, then code for the requested field653** is generated. In this case (*pRegFree) may be set to the number of654** a temporary register to be freed by the caller before returning.655**656** Before returning, output parameter (*ppExpr) is set to point to the657** Expr object corresponding to element iElem of the vector.658*/659static int exprVectorRegister(660  Parse *pParse,                  /* Parse context */661  Expr *pVector,                  /* Vector to extract element from */662  int iField,                     /* Field to extract from pVector */663  int regSelect,                  /* First in array of registers */664  Expr **ppExpr,                  /* OUT: Expression element */665  int *pRegFree                   /* OUT: Temp register to free */666){667  u8 op = pVector->op;668  assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT || op==TK_ERROR );669  if( op==TK_REGISTER ){670    *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);671    return pVector->iTable+iField;672  }673  if( op==TK_SELECT ){674    assert( ExprUseXSelect(pVector) );675    *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;676     return regSelect+iField;677  }678  if( op==TK_VECTOR ){679    assert( ExprUseXList(pVector) );680    *ppExpr = pVector->x.pList->a[iField].pExpr;681    return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);682  }683  return 0;684}685 686/*687** Expression pExpr is a comparison between two vector values. Compute688** the result of the comparison (1, 0, or NULL) and write that689** result into register dest.690**691** The caller must satisfy the following preconditions:692**693**    if pExpr->op==TK_IS:      op==TK_EQ and p5==SQLITE_NULLEQ694**    if pExpr->op==TK_ISNOT:   op==TK_NE and p5==SQLITE_NULLEQ695**    otherwise:                op==pExpr->op and p5==0696*/697static void codeVectorCompare(698  Parse *pParse,        /* Code generator context */699  Expr *pExpr,          /* The comparison operation */700  int dest,             /* Write results into this register */701  u8 op,                /* Comparison operator */702  u8 p5                 /* SQLITE_NULLEQ or zero */703){704  Vdbe *v = pParse->pVdbe;705  Expr *pLeft = pExpr->pLeft;706  Expr *pRight = pExpr->pRight;707  int nLeft = sqlite3ExprVectorSize(pLeft);708  int i;709  int regLeft = 0;710  int regRight = 0;711  u8 opx = op;712  int addrCmp = 0;713  int addrDone = sqlite3VdbeMakeLabel(pParse);714  int isCommuted = ExprHasProperty(pExpr,EP_Commuted);715 716  assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );717  if( pParse->nErr ) return;718  if( nLeft!=sqlite3ExprVectorSize(pRight) ){719    sqlite3ErrorMsg(pParse, "row value misused");720    return;721  }722  assert( pExpr->op==TK_EQ || pExpr->op==TK_NE723       || pExpr->op==TK_IS || pExpr->op==TK_ISNOT724       || pExpr->op==TK_LT || pExpr->op==TK_GT725       || pExpr->op==TK_LE || pExpr->op==TK_GE726  );727  assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)728            || (pExpr->op==TK_ISNOT && op==TK_NE) );729  assert( p5==0 || pExpr->op!=op );730  assert( p5==SQLITE_NULLEQ || pExpr->op==op );731 732  if( op==TK_LE ) opx = TK_LT;733  if( op==TK_GE ) opx = TK_GT;734  if( op==TK_NE ) opx = TK_EQ;735 736  regLeft = exprCodeSubselect(pParse, pLeft);737  regRight = exprCodeSubselect(pParse, pRight);738 739  sqlite3VdbeAddOp2(v, OP_Integer, 1, dest);740  for(i=0; 1 /*Loop exits by "break"*/; i++){741    int regFree1 = 0, regFree2 = 0;742    Expr *pL = 0, *pR = 0;743    int r1, r2;744    assert( i>=0 && i<nLeft );745    if( addrCmp ) sqlite3VdbeJumpHere(v, addrCmp);746    r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);747    r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);748    addrCmp = sqlite3VdbeCurrentAddr(v);749    codeCompare(pParse, pL, pR, opx, r1, r2, addrDone, p5, isCommuted);750    testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);751    testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);752    testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);753    testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);754    testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);755    testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);756    sqlite3ReleaseTempReg(pParse, regFree1);757    sqlite3ReleaseTempReg(pParse, regFree2);758    if( (opx==TK_LT || opx==TK_GT) && i<nLeft-1 ){759      addrCmp = sqlite3VdbeAddOp0(v, OP_ElseEq);760      testcase(opx==TK_LT); VdbeCoverageIf(v,opx==TK_LT);761      testcase(opx==TK_GT); VdbeCoverageIf(v,opx==TK_GT);762    }763    if( p5==SQLITE_NULLEQ ){764      sqlite3VdbeAddOp2(v, OP_Integer, 0, dest);765    }else{766      sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, dest, r2);767    }768    if( i==nLeft-1 ){769      break;770    }771    if( opx==TK_EQ ){772      sqlite3VdbeAddOp2(v, OP_NotNull, dest, addrDone); VdbeCoverage(v);773    }else{774      assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );775      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);776      if( i==nLeft-2 ) opx = op;777    }778  }779  sqlite3VdbeJumpHere(v, addrCmp);780  sqlite3VdbeResolveLabel(v, addrDone);781  if( op==TK_NE ){782    sqlite3VdbeAddOp2(v, OP_Not, dest, dest);783  }784}785 786#if SQLITE_MAX_EXPR_DEPTH>0787/*788** Check that argument nHeight is less than or equal to the maximum789** expression depth allowed. If it is not, leave an error message in790** pParse.791*/792int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){793  int rc = SQLITE_OK;794  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];795  if( nHeight>mxHeight ){796    sqlite3ErrorMsg(pParse,797       "Expression tree is too large (maximum depth %d)", mxHeight798    );799    rc = SQLITE_ERROR;800  }801  return rc;802}803 804/* The following three functions, heightOfExpr(), heightOfExprList()805** and heightOfSelect(), are used to determine the maximum height806** of any expression tree referenced by the structure passed as the807** first argument.808**809** If this maximum height is greater than the current value pointed810** to by pnHeight, the second parameter, then set *pnHeight to that811** value.812*/813static void heightOfExpr(const Expr *p, int *pnHeight){814  if( p ){815    if( p->nHeight>*pnHeight ){816      *pnHeight = p->nHeight;817    }818  }819}820static void heightOfExprList(const ExprList *p, int *pnHeight){821  if( p ){822    int i;823    for(i=0; i<p->nExpr; i++){824      heightOfExpr(p->a[i].pExpr, pnHeight);825    }826  }827}828static void heightOfSelect(const Select *pSelect, int *pnHeight){829  const Select *p;830  for(p=pSelect; p; p=p->pPrior){831    heightOfExpr(p->pWhere, pnHeight);832    heightOfExpr(p->pHaving, pnHeight);833    heightOfExpr(p->pLimit, pnHeight);834    heightOfExprList(p->pEList, pnHeight);835    heightOfExprList(p->pGroupBy, pnHeight);836    heightOfExprList(p->pOrderBy, pnHeight);837  }838}839 840/*841** Set the Expr.nHeight variable in the structure passed as an842** argument. An expression with no children, Expr.pList or843** Expr.pSelect member has a height of 1. Any other expression844** has a height equal to the maximum height of any other845** referenced Expr plus one.846**847** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,848** if appropriate.849*/850static void exprSetHeight(Expr *p){851  int nHeight = p->pLeft ? p->pLeft->nHeight : 0;852  if( NEVER(p->pRight) && p->pRight->nHeight>nHeight ){853    nHeight = p->pRight->nHeight;854  }855  if( ExprUseXSelect(p) ){856    heightOfSelect(p->x.pSelect, &nHeight);857  }else if( p->x.pList ){858    heightOfExprList(p->x.pList, &nHeight);859    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);860  }861  p->nHeight = nHeight + 1;862}863 864/*865** Set the Expr.nHeight variable using the exprSetHeight() function. If866** the height is greater than the maximum allowed expression depth,867** leave an error in pParse.868**869** Also propagate all EP_Propagate flags from the Expr.x.pList into870** Expr.flags.871*/872void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){873  if( pParse->nErr ) return;874  exprSetHeight(p);875  sqlite3ExprCheckHeight(pParse, p->nHeight);876}877 878/*879** Return the maximum height of any expression tree referenced880** by the select statement passed as an argument.881*/882int sqlite3SelectExprHeight(const Select *p){883  int nHeight = 0;884  heightOfSelect(p, &nHeight);885  return nHeight;886}887#else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */888/*889** Propagate all EP_Propagate flags from the Expr.x.pList into890** Expr.flags.891*/892void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){893  if( pParse->nErr ) return;894  if( p && ExprUseXList(p) && p->x.pList ){895    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);896  }897}898#define exprSetHeight(y)899#endif /* SQLITE_MAX_EXPR_DEPTH>0 */900 901/*902** Set the error offset for an Expr node, if possible.903*/904void sqlite3ExprSetErrorOffset(Expr *pExpr, int iOfst){905  if( pExpr==0 ) return;906  if( NEVER(ExprUseWJoin(pExpr)) ) return;907  pExpr->w.iOfst = iOfst;908}909 910/*911** This routine is the core allocator for Expr nodes.912**913** Construct a new expression node and return a pointer to it.  Memory914** for this node and for the pToken argument is a single allocation915** obtained from sqlite3DbMalloc().  The calling function916** is responsible for making sure the node eventually gets freed.917**918** If dequote is true, then the token (if it exists) is dequoted.919** If dequote is false, no dequoting is performed.  The deQuote920** parameter is ignored if pToken is NULL or if the token does not921** appear to be quoted.  If the quotes were of the form "..." (double-quotes)922** then the EP_DblQuoted flag is set on the expression node.923**924** Special case (tag-20240227-a):  If op==TK_INTEGER and pToken points to925** a string that can be translated into a 32-bit integer, then the token is926** not stored in u.zToken.  Instead, the integer values is written927** into u.iValue and the EP_IntValue flag is set. No extra storage928** is allocated to hold the integer text and the dequote flag is ignored.929** See also tag-20240227-b.930*/931Expr *sqlite3ExprAlloc(932  sqlite3 *db,            /* Handle for sqlite3DbMallocRawNN() */933  int op,                 /* Expression opcode */934  const Token *pToken,    /* Token argument.  Might be NULL */935  int dequote             /* True to dequote */936){937  Expr *pNew;938  int nExtra = pToken ? pToken->n+1 : 0;939 940  assert( db!=0 );941  pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);942  if( pNew ){943    memset(pNew, 0, sizeof(Expr));944    pNew->op = (u8)op;945    pNew->iAgg = -1;946    if( nExtra ){947      assert( pToken!=0 );948      pNew->u.zToken = (char*)&pNew[1];949      assert( pToken->z!=0 || pToken->n==0 );950      if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);951      pNew->u.zToken[pToken->n] = 0;952      if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){953        sqlite3DequoteExpr(pNew);954      }955    }956#if SQLITE_MAX_EXPR_DEPTH>0957    pNew->nHeight = 1;958#endif 959  }960  return pNew;961}962 963/*964** Allocate a new expression node from a zero-terminated token that has965** already been dequoted.966*/967Expr *sqlite3Expr(968  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */969  int op,                 /* Expression opcode */970  const char *zToken      /* Token argument.  Might be NULL */971){972  Token x;973  x.z = zToken;974  x.n = sqlite3Strlen30(zToken);975  return sqlite3ExprAlloc(db, op, &x, 0);976}977 978/*979** Allocate an expression for a 32-bit signed integer literal.980*/981Expr *sqlite3ExprInt32(sqlite3 *db, int iVal){982  Expr *pNew = sqlite3DbMallocRawNN(db, sizeof(Expr));983  if( pNew ){984    memset(pNew, 0, sizeof(Expr));985    pNew->op = TK_INTEGER;986    pNew->iAgg = -1;987    pNew->flags = EP_IntValue|EP_Leaf|(iVal?EP_IsTrue:EP_IsFalse);988    pNew->u.iValue = iVal;989#if SQLITE_MAX_EXPR_DEPTH>0990    pNew->nHeight = 1;991#endif 992  }993  return pNew;994}995 996/*997** Attach subtrees pLeft and pRight to the Expr node pRoot.998**999** If pRoot==NULL that means that a memory allocation error has occurred.1000** In that case, delete the subtrees pLeft and pRight.1001*/1002void sqlite3ExprAttachSubtrees(1003  sqlite3 *db,1004  Expr *pRoot,1005  Expr *pLeft,1006  Expr *pRight1007){1008  if( pRoot==0 ){1009    assert( db->mallocFailed );1010    sqlite3ExprDelete(db, pLeft);1011    sqlite3ExprDelete(db, pRight);1012  }else{1013    assert( ExprUseXList(pRoot) );1014    assert( pRoot->x.pSelect==0 );1015    if( pRight ){1016      pRoot->pRight = pRight;1017      pRoot->flags |= EP_Propagate & pRight->flags;1018#if SQLITE_MAX_EXPR_DEPTH>01019      pRoot->nHeight = pRight->nHeight+1;1020    }else{1021      pRoot->nHeight = 1;1022#endif1023    }1024    if( pLeft ){1025      pRoot->pLeft = pLeft;1026      pRoot->flags |= EP_Propagate & pLeft->flags;1027#if SQLITE_MAX_EXPR_DEPTH>01028      if( pLeft->nHeight>=pRoot->nHeight ){1029        pRoot->nHeight = pLeft->nHeight+1;1030      }1031#endif1032    }1033  }1034}1035 1036/*1037** Allocate an Expr node which joins as many as two subtrees.1038**1039** One or both of the subtrees can be NULL.  Return a pointer to the new1040** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,1041** free the subtrees and return NULL.1042*/1043Expr *sqlite3PExpr(1044  Parse *pParse,          /* Parsing context */1045  int op,                 /* Expression opcode */1046  Expr *pLeft,            /* Left operand */1047  Expr *pRight            /* Right operand */1048){1049  Expr *p;1050  p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));1051  if( p ){1052    memset(p, 0, sizeof(Expr));1053    p->op = op & 0xff;1054    p->iAgg = -1;1055    sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);1056    sqlite3ExprCheckHeight(pParse, p->nHeight);1057  }else{1058    sqlite3ExprDelete(pParse->db, pLeft);1059    sqlite3ExprDelete(pParse->db, pRight);1060  }1061  return p;1062}1063 1064/*1065** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due1066** do a memory allocation failure) then delete the pSelect object.1067*/1068void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){1069  if( pExpr ){1070    pExpr->x.pSelect = pSelect;1071    ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);1072    sqlite3ExprSetHeightAndFlags(pParse, pExpr);1073  }else{1074    assert( pParse->db->mallocFailed );1075    sqlite3SelectDelete(pParse->db, pSelect);1076  }1077}1078 1079/*1080** Expression list pEList is a list of vector values. This function1081** converts the contents of pEList to a VALUES(...) Select statement1082** returning 1 row for each element of the list. For example, the1083** expression list:1084**1085**   ( (1,2), (3,4) (5,6) )1086**1087** is translated to the equivalent of:1088**1089**   VALUES(1,2), (3,4), (5,6)1090**1091** Each of the vector values in pEList must contain exactly nElem terms.1092** If a list element that is not a vector or does not contain nElem terms,1093** an error message is left in pParse.1094**1095** This is used as part of processing IN(...) expressions with a list1096** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))".1097*/1098Select *sqlite3ExprListToValues(Parse *pParse, int nElem, ExprList *pEList){1099  int ii;1100  Select *pRet = 0;1101  assert( nElem>1 );1102  for(ii=0; ii<pEList->nExpr; ii++){1103    Select *pSel;1104    Expr *pExpr = pEList->a[ii].pExpr;1105    int nExprElem;1106    if( pExpr->op==TK_VECTOR ){1107      assert( ExprUseXList(pExpr) );1108      nExprElem = pExpr->x.pList->nExpr;1109    }else{1110      nExprElem = 1;1111    }1112    if( nExprElem!=nElem ){1113      sqlite3ErrorMsg(pParse, "IN(...) element has %d term%s - expected %d",1114          nExprElem, nExprElem>1?"s":"", nElem1115      );1116      break;1117    }1118    assert( ExprUseXList(pExpr) );1119    pSel = sqlite3SelectNew(pParse, pExpr->x.pList, 0, 0, 0, 0, 0, SF_Values,0);1120    pExpr->x.pList = 0;1121    if( pSel ){1122      if( pRet ){1123        pSel->op = TK_ALL;1124        pSel->pPrior = pRet;1125      }1126      pRet = pSel;1127    }1128  }1129 1130  if( pRet && pRet->pPrior ){1131    pRet->selFlags |= SF_MultiValue;1132  }1133  sqlite3ExprListDelete(pParse->db, pEList);1134  return pRet;1135}1136 1137/*1138** Join two expressions using an AND operator.  If either expression is1139** NULL, then just return the other expression.1140**1141** If one side or the other of the AND is known to be false, and neither side1142** is part of an ON clause, then instead of returning an AND expression,1143** just return a constant expression with a value of false.1144*/1145Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){1146  sqlite3 *db = pParse->db;1147  if( pLeft==0  ){1148    return pRight;1149  }else if( pRight==0 ){1150    return pLeft;1151  }else{1152    u32 f = pLeft->flags | pRight->flags;1153    if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse|EP_HasFunc))==EP_IsFalse1154     && !IN_RENAME_OBJECT1155    ){1156      sqlite3ExprDeferredDelete(pParse, pLeft);1157      sqlite3ExprDeferredDelete(pParse, pRight);1158      return sqlite3ExprInt32(db, 0);1159    }else{1160      return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);1161    }1162  }1163}1164 1165/*1166** Construct a new expression node for a function with multiple1167** arguments.1168*/1169Expr *sqlite3ExprFunction(1170  Parse *pParse,        /* Parsing context */1171  ExprList *pList,      /* Argument list */1172  const Token *pToken,  /* Name of the function */1173  int eDistinct         /* SF_Distinct or SF_ALL or 0 */1174){1175  Expr *pNew;1176  sqlite3 *db = pParse->db;1177  assert( pToken );1178  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);1179  if( pNew==0 ){1180    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */1181    return 0;1182  }1183  assert( !ExprHasProperty(pNew, EP_InnerON|EP_OuterON) );1184  pNew->w.iOfst = (int)(pToken->z - pParse->zTail);1185  if( pList1186   && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG]1187   && !pParse->nested1188  ){1189    sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);1190  }1191  pNew->x.pList = pList;1192  ExprSetProperty(pNew, EP_HasFunc);1193  assert( ExprUseXList(pNew) );1194  sqlite3ExprSetHeightAndFlags(pParse, pNew);1195  if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);1196  return pNew;1197}1198 1199/*1200** Report an error when attempting to use an ORDER BY clause within

Showing the first 1,200 of 7688 lines. Download the file for the rest.