Parse an "SQL2" UPDATE statement and construct a query builder
for selecting the rows and build a field => value mapping for the
update.

@param string $sql2

@return array($query, $updates)
552913
private function doParse($sql2)
    {
        $this->implicitSelectorName = null;
        $this->sql2 = $sql2;
        $source = null;
        $constraint = null;
        $updates = [];
        $applies = [];

        while ($this->scanner->lookupNextToken() !== '') {
            switch (strtoupper($this->scanner->lookupNextToken())) {
                case 'UPDATE':
                    $this->scanner->expectToken('UPDATE');
                    $source = $this->parseSource();
                    break;
                case 'SET':
                    $this->scanner->expectToken('SET');
                    $updates = $this->parseUpdates();
                    break;
                case 'APPLY':
                    $this->scanner->expectToken('APPLY');
                    $applies = $this->parseApply();
                    break;
                case 'WHERE':
                    $this->scanner->expectToken('WHERE');
                    $constraint = $this->parseConstraint();
                    break;
                default:
                    throw new InvalidQueryException('Expected end of query, got "'.$this->scanner->lookupNextToken().'" in '.$this->sql2);
            }
        }

        if (!$source instanceof SourceInterface) {
            throw new InvalidQueryException('Invalid query, source could not be determined: '.$sql2);
        }

        $query = $this->factory->createQuery($source, $constraint);

        $res = new \ArrayObject([$query, $updates, $constraint, $applies]);

        return $res;
    }
597897
public function getQuery(): Query
    {
        if (count($this->what) == 0) {
            throw new Exception('Can not build UPDATE query, SET is not defined');
        }

        if ($this->table === null) {
            throw new Exception('Can not build UPDATE query when table name is not set');
        }

        $sql = "UPDATE {$this->table}\nSET\n";

        foreach ($this->what as $field => $value) {
            $sql .= "\t{$field} = ";
            if ($value instanceof Expr) {
                $sql .= "{$value},\n";
            } else {
                //$key = $this->bind($field, $value);
	            $key = $this->getBindings()->makeAndSet($field, $value);
                $sql .= ":{$key},\n";
            }
        }

        $sql = substr($sql, 0, -2);

        if ($this->hasWhere()) {
            $sql .= "\nWHERE{$this->getWhereSql()}";
        }

        if (count($this->orderBy) > 0) {
            $sql .= "\nORDER BY";
            foreach ($this->orderBy as $r) {
                $sql .= "\n\t{$r['field']} {$r['direction']},";
            }
            $sql = substr($sql, 0, -1);
        }

        return new Query($sql, $this->getBindings(), $this->getAdapterConnection());
    }
335961
public function sql($sql, array $values = array())
    {
        $this->whereSqlConditions[] = $sql;
        $this->arguments = array_merge($this->arguments, $values);
        return $this;
    }
635443
function query($sql, $parms = array(), $alias = null)
    {
        $this->sql = $sql;
        $sth = $this->connect($alias)->prepare($sql);
        $sth->execute($parms);
        $this->rows = $sth->rowCount();
        $this->error[$sql] = $sth->errorInfo();

        if ($sth->columnCount() > 0) {
            return $this->result = $sth->fetchAll(PDO::FETCH_CLASS, __NAMESPACE__.'\Row', [$this->sql, $parms]);
        } else {
            $this->result = false;
            return $this->rows;
        }
    }
715603
private QueryBuilderKraken parseUpdate()
  {
    Token token;
    
    UpdateQueryBuilder query = new UpdateQueryBuilder(_tableManager, _sql);
    
    String tableName = parseTableName();

    query.setTableName(tableName);

    _query = query;

    if ((token = scanToken()) != Token.SET) {
      throw error(L.l("expected SET at {0}", token));
    }

    do {
      parseSetItem(query);
    } while ((token = scanToken()) == Token.COMMA);
    
    _token = token;

    //query.setUpdateBuilder(new SetUpdateBuilder(setItems));
    
    ExprKraken whereExpr = null;

    token = scanToken();
    
    if (token == Token.WHERE) {
      whereExpr = parseExpr();
    }
    else if (token != null && token != Token.EOF) {
      throw error("expected WHERE at '{0}'", token);
    }

    ParamExpr []params = _params.toArray(new ParamExpr[_params.size()]);

    query.setParams(params);
    query.setWhereExpr(whereExpr);

    return query;
  }
635283
public function buildQuery(string $table, array $set, array $where): SqlParams
    {
        if (empty($set) || empty($where)) {
            throw new \Exception('Set and where arrays cannot be empty');
        }

        $params = [];
        $sql = "UPDATE {$table} SET ";

        foreach ($set as $column => $value) {
            $sql .= $this->options->escapeIdentifier($column) . ' = ?, ';
            $params[] = $value;
        }

        $sql = substr_replace($sql, '', -2); // remove trailing comma
        $whereClause = $this->buildWhereClause($where);
        $sql .= $whereClause->getSql();

        return new SqlParams($sql, array_merge($params, $whereClause->getParams()));
    }
854553
public function query($sql, $bind = array())
    {
        $this->prepare($sql, $bind);

        return $this->db->query($sql, $bind);
    }
425135
protected function parseUpdateStmt(){
		$sql = parent::parseUpdateStmt();
		if($this->driverName === 'mysql')
			return $this->applyLimit($sql . $this->clauses[3]);
		return $sql;
	}
273015
public function update(array $values): array
	{
		$sql  = $this->query->getPrefix();
		$sql .= 'UPDATE ';
		$sql .= $this->escapeTable($this->query->getTable());
		$sql .= ' SET ';
		$sql .= $this->updateColumns($values);
		$sql .= $this->wheres($this->query->getWheres());

		return ['sql' => $sql, 'params' => $this->params];
	}
949115
public static function parseFields(string &$sql, array &$data) : array
    {
        if (preg_match_all('/\[' . static::FIELDS_LABEL . '\:not\((.+?)\)\]/i', $sql, $match)) {
            foreach ($match[0] as $key => &$value) {
                if ($value) {
                    if (isset($data[0]) && \is_array($data[0])) {
                        $new_data = $data[0];
                    } else {
                        $new_data = $data;
                    }

                    $sql = str_replace($value, static::createSelectString(
                        array_diff_key(
                            $new_data,
                            array_flip(array_map('trim', explode(',', $match[1][$key])))
                        )
                    ), $sql);
                }
            }

            unset($value);
        }

        if (stripos($sql, '[' . static::FIELDS_LABEL . ']')) {
            $sql = str_replace('[' . static::FIELDS_LABEL . ']', static::createSelectString($data), $sql);
        }

        return [$sql, $data];
    }
1122602
public function query(string $sql, array $bindings = []): IQueryBuilderHandler
    {
        $queryObject = new QueryObject($sql, $bindings, $this->getConnection());
        $this->connection->setLastQuery($queryObject);

        $this->fireEvents(EventHandler::EVENT_BEFORE_QUERY, $queryObject);

        [$response, $executionTime] = $this->statement($queryObject->getSql(), $queryObject->getBindings());

        $this->fireEvents(EventHandler::EVENT_AFTER_QUERY, $queryObject, [
            'execution_time' => $executionTime,
        ]);

        $this->pdoStatement = $response;

        return $this;
    }
736255
public function compileUpdate(Builder $query, $values)
    {
        $table = $this->wrapTable($query->from);

        // Each one of the columns in the update statements needs to be wrapped in the
        // keyword identifiers, also a place-holder needs to be created for each of
        // the values in the list of bindings so we can make the sets statements.
        $columns = collect($values)->map(function ($value, $key) {
            return $this->wrap($key).' = '.$this->parameter($value);
        })->implode(', ');

        // If the query has any "join" clauses, we will setup the joins on the builder
        // and compile them so we can attach them to this update, as update queries
        // can get join statements to attach to other tables when they're needed.
        $joins = '';

        if (isset($query->joins)) {
            $joins = ' '.$this->compileJoins($query, $query->joins);
        }

        // Of course, update queries may also be constrained by where clauses so we'll
        // need to compile the where clauses and attach it to the query so only the
        // intended records are updated by the SQL statements we generate to run.
        $wheres = $this->compileWheres($query);

        return trim("update {$table}{$joins} set $columns $wheres");
    }
845759
protected function getColumnsSql(array $sql): array
    {
        if (empty($this->columns)) {
            $sql[] = '*';

            return $sql;
        }
        $columns = [];
        foreach ($this->columns as $key => $column) {
            if ($column instanceof Closure) {
                // Sub Select
                $query = new SelectQuery($this->db);
                $column($query);
                $column = new RawExp($query->build(false));
            }
            $columns[] = $column;
        }
        $sql[] = implode(',', $this->quoter->quoteNames($columns));

        return $sql;
    }
1222586
public function select($options = [])
    {
        $sql = str_replace(
            ['%TABLE%', '%DISTINCT%', '%FIELD%', '%JOIN%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%', '%UNION%', '%LOCK%', '%COMMENT%', '%FORCE%'],
            [
                $this->parseTable($options['table'], $options),
                $this->parseDistinct($options['distinct']),
                $this->parseField($options['field'], $options),
                $this->parseJoin($options['join'], $options),
                $this->parseWhere($options['where'], $options),
                $this->parseGroup($options['group']),
                $this->parseHaving($options['having']),
                $this->parseOrder($options['order'], $options),
                $this->parseLimit($options['limit']),
                $this->parseUnion($options['union']),
                $this->parseLock($options['lock']),
                $this->parseComment($options['comment']),
                $this->parseForce($options['force']),
            ], $this->selectSql);
        return $sql;
    }
1059870
function update() {
		$args=[];
		$ctr=0;
		$pairs='';
		$filter='';
		$pkeys=[];
		foreach ($this->fields as $key=>$field)
			if ($field['pkey'])
				$pkeys[$key]=$field['previous'];
		if (isset($this->trigger['beforeupdate']) &&
			\Base::instance()->call($this->trigger['beforeupdate'],
				[$this,$pkeys])===FALSE)
			return $this;
		foreach ($this->fields as $key=>$field)
			if ($field['changed']) {
				$pairs.=($pairs?',':'').$this->db->quotekey($key).'=?';
				$args[++$ctr]=[$field['value'],$field['pdo_type']];
			}
		foreach ($this->fields as $key=>$field)
			if ($field['pkey']) {
				$filter.=($filter?' AND ':' WHERE ').
					$this->db->quotekey($key).'=?';
				$args[++$ctr]=[$field['previous'],$field['pdo_type']];
			}
		if ($pairs) {
			$sql='UPDATE '.$this->table.' SET '.$pairs.$filter;
			$this->db->exec($sql,$args);
		}
		if (isset($this->trigger['afterupdate']))
			\Base::instance()->call($this->trigger['afterupdate'],
				[$this,$pkeys]);
		// reset changed flag after calling afterupdate
		foreach ($this->fields as $key=>&$field) {
				$field['changed']=FALSE;
				$field['initial']=$field['value'];
				unset($field);
			}
		return $this;
	}
56041
protected function prepareSql($sql)
    {
        $sql = str_replace(";',", "-CODE-", $sql);
        $sql = trim($sql);
        preg_match_all('#DELIMITER (.+?)\n(.+?)DELIMITER ;#s', $sql, $m);
        foreach ($m[0] as $k => $v) {
            if ($m[1][$k] == '|') {
                throw new \RuntimeException('You can not use "|" as delimiter: '.$v);
            }
            $stored = str_replace(';', '|', $m[2][$k]);
            $stored = str_replace($m[1][$k], ";\n", $stored);
            $sql = str_replace($v, $stored, $sql);
        }
        $query = array();

        $tab = explode(";\n", $sql);
        $size = \count($tab);
        for ($i = 0; $i < $size; $i++) {
            $queryTemp = str_replace("-CODE-", ";',", $tab[$i]);
            $queryTemp = str_replace("|", ";", $queryTemp);
            $query[] = $queryTemp;
        }

        return $query;
    }
810069
public function query($sql=null, array $params=[]) {
		if($sql === null) {
			$sql = $this->buildSQL();
			$params = $this->getParameters();
		}

		$this->replaceArrayParams($sql, $params);

		return $this->query = $this->db->query($sql, $params);
	}