示例#1
0
文件: ExprTest.php 项目: titon/db
 public function testExpression()
 {
     $expr = new Expr('column', '+', 5);
     $this->assertEquals('column', $expr->getField());
     $this->assertEquals('+', $expr->getOperator());
     $this->assertEquals('5', $expr->getValue());
 }
示例#2
0
文件: Predicate.php 项目: titon/db
 /**
  * Process a parameter before adding it to the list.
  * Set the primary predicate type if it has not been set.
  *
  * @param string $field
  * @param string $op
  * @param mixed $value
  * @return $this
  */
 public function add($field, $op, $value)
 {
     $param = new Expr($field, $op, $value);
     $this->_params[] = $param;
     if ($param->useValue()) {
         $this->addBinding($field, $value);
     }
     return $this;
 }
示例#3
0
 /**
  * Format database expressions.
  *
  * @param \Titon\Db\Query\Expr $expr
  * @return string
  */
 public function formatExpression(Expr $expr)
 {
     $field = $expr->getField();
     $operator = $expr->getOperator();
     $value = $expr->getValue();
     if ($operator === Expr::AS_ALIAS) {
         return sprintf($this->getClause(self::AS_ALIAS), $this->quote($field), $this->quote($value));
         // No value to use so exit early
     } else {
         if (!$expr->useValue() && !($operator === Expr::NULL || $operator === Expr::NOT_NULL)) {
             return $this->quote($field);
         }
     }
     $isSubQuery = $value instanceof SubQuery;
     // Function as field
     if ($field instanceof Func) {
         $field = $this->formatFunction($field);
         // Raw expression as field
     } else {
         if ($field instanceof RawExpr) {
             $field = $field->getValue();
             // Regular clause
         } else {
             $field = $this->quote($field);
         }
     }
     // IN has special case
     if ($operator === Expr::IN || $operator === Expr::NOT_IN) {
         if ($isSubQuery) {
             $clause = sprintf($this->getClause($operator), $field, '?');
             $clause = str_replace(['(', ')'], '', $clause);
         } else {
             $clause = sprintf($this->getClause($operator), $field, implode(', ', array_fill(0, count($value), '?')));
         }
         // Operators with clauses
     } else {
         if ($this->hasClause($operator)) {
             $clause = sprintf($this->getClause($operator), $field);
             // Basic operator
         } else {
             $clause = sprintf($this->getClause(self::EXPRESSION), $field, $operator);
         }
     }
     // Replace ? with sub-query statement
     if ($isSubQuery) {
         /** @type \Titon\Db\Query\SubQuery $value */
         // EXISTS and NOT EXISTS doesn't have a field or operator
         if (in_array($value->getFilter(), [SubQuery::EXISTS, SubQuery::NOT_EXISTS], true)) {
             $clause = $this->formatSubQuery($value);
         } else {
             $clause = str_replace('?', $this->formatSubQuery($value), $clause);
         }
     }
     return $clause;
 }