Executes write queries.

@param array $queries
@param int   $concurrency

@return array
@throws \Throwable
433382
public function write(array $queries, int $concurrency = 5) : array
    {
        $result = [];
        $openedStreams = [];

        foreach ($queries as $query) {
            $requests = function(Query $query) use(&$openedStreams) {
                if (!empty($query->getFiles())) {
                    foreach ($query->getFiles() as $file) {
                        /* @var FileInterface $file */
                        $headers = $this->getHeaders();

                        $uri = $this->buildRequestUri($query->getServer(), [
                            'query' => $query->getQuery()
                        ], $query->getSettings());

                        $stream = $file->open();
                        $openedStreams[] = $stream;

                        $request = new Request('POST', $uri, $headers, $stream);

                        yield $request;
                    }
                } else {
                    $headers = $this->getHeaders();

                    $uri = $this->buildRequestUri($query->getServer(), [], $query->getSettings());

                    $request = new Request('POST', $uri, $headers, gzencode($query->getQuery()));

                    yield $request;
                }
            };

            $queryResult = [];

            $pool = new Pool(
                $this->httpClient, $requests($query), [
                    'concurrency' => $concurrency,
                    'fulfilled' => function ($response, $index) use (&$queryResult, $query) {
                        $queryResult[$index] = true;
                    },
                    'rejected' => $this->parseReason($query),
                    'options' => array_merge([
                        'expect' => false
                    ], $this->options['write'] ?? []),
                ]
            );

            $promise = $pool->promise();

            try {
                $promise->wait();
            } catch (\Throwable $exception) {
                foreach ($openedStreams as $openedStream) {
                    $openedStream->close();
                }

                throw $exception;
            }

            ksort($result);

            foreach ($openedStreams as $openedStream) {
                $openedStream->close();
            }

            $result[] = $queryResult;
        }

        return $result;
    }
701852
public function executeSql($queries)
    {
        $db = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();

        if (is_array($queries) && !empty($queries)) {
            foreach ($queries as $query) {
                $query = trim($query);
                if (!empty($query)) {
                    $db->execute($query);
                }
            }
        }
    }
95187
public function update(array $statements, array $data): array
    {
        if (\count($data) === 0) {
            throw new Exception('No data given.', 4);
        }

        $table = end($statements['tables']);

        // UPDATE
        [$updateStatement, $bindings] = $this->getUpdateStatement($data);

        // WHERE
        [$whereCriteria, $whereBindings] = $this->buildCriteriaWithType($statements, 'wheres', 'WHERE');

        $sqlArray = [
            'UPDATE',
            $this->wrapSanitizer($table),
            $this->buildQueryPart(static::QUERY_PART_JOIN, $statements),
            'SET ' . $updateStatement,
            $whereCriteria,
            $this->buildQueryPart(static::QUERY_PART_GROUPBY, $statements),
            $this->buildQueryPart(static::QUERY_PART_ORDERBY, $statements),
            $this->buildQueryPart(static::QUERY_PART_LIMIT, $statements),
            $this->buildQueryPart(static::QUERY_PART_OFFSET, $statements),
        ];

        $sql = $this->concatenateQuery($sqlArray);

        $bindings = array_merge($bindings, $whereBindings);

        return compact('sql', 'bindings');
    }
602052
private function runQuery(Query $query, $executeQueries = false)
    {
        $this->playedQueries[] = $query;
        if ($executeQueries) {
            $this->connection->executeQuery((string)$query);
        }
    }
353911
private function doInsert(array $statements, array $data, $type): array
    {
        $table = end($statements['tables']);

        $bindings = $keys = $values = [];

        foreach ($data as $key => $value) {
            $keys[] = $key;
            if ($value instanceof Raw) {
                $values[] = (string)$value;
            } else {
                $values[] = '?';
                $bindings[] = $value;
            }
        }

        $sqlArray = [
            $type . ' INTO',
            $this->wrapSanitizer($table),
            '(' . $this->arrayStr($keys) . ')',
            'VALUES',
            '(' . $this->arrayStr($values, ',', false) . ')',
        ];

        if (isset($statements['onduplicate']) === true) {

            if (\count($statements['onduplicate']) < 1) {
                throw new Exception('No data given.', 4);
            }

            [$updateStatement, $updateBindings] = $this->getUpdateStatement($statements['onduplicate']);
            $sqlArray[] = 'ON DUPLICATE KEY UPDATE ' . $updateStatement;
            $bindings = array_merge($bindings, $updateBindings);

        }

        $sql = $this->concatenateQuery($sqlArray);

        return compact('sql', 'bindings');
    }
730376
public function bulkWrite($requests, array $options = [])
    {
        if (isset($options['writeConcern'])) {
            if (!$options['writeConcern'] instanceof WriteConcern) {
                throw new InvalidArgumentException(
                    sprintf(
                        'Option "writeConcern" is expected to be "%s", "%s" given.',
                        WriteConcern::class,
                        \Tequila\MongoDB\getType($options['writeConcern'])
                    )
                );
            }

            $writeConcern = $options['writeConcern'];
            unset($options['writeConcern']);
        } else {
            $writeConcern = $this->writeConcern;
        }

        $bulkWrite = new BulkWrite($requests, $options);

        return $this->manager->executeBulkWrite($this->getNamespace(), $bulkWrite, $writeConcern);
    }
878930
public function insertBatchStream(string $tableName, array $columns = [], string $format = 'CSV')
    {
        if ($this->getCountPendingQueue() > 0) {
            throw new QueryException('Queue must be empty, before insertBatch, need executeAsync');
        }

        if (! in_array($format, self::SUPPORTED_FORMATS, true)) {
            throw new QueryException('Format not support in insertBatchFiles');
        }

        if (empty($columns)) {
            $sql = 'INSERT INTO ' . $tableName . ' FORMAT ' . $format;
        } else {
            $sql = 'INSERT INTO ' . $tableName . ' ( ' . implode(',', $columns) . ' ) FORMAT ' . $format;
        }

        return $this->transport()->writeStreamData($sql);
    }
612442
public function batchSearch(array $queries) {
        $requests = [];

        foreach ($queries as $query) {
            $requests[] = [
                'method' => 'idoit.search',
                'params' => [
                    'q' => $query
                ]
            ];
        }

        return $this->api->batchRequest($requests);
    }
1363625
protected static function unionQueriesToOne($queries)
    {
        if (count($queries) === 0) {
            throw new Exception(Module::t('app', 'Nothing to union'));
        }

        $query = array_reduce(
            $queries,
            function ($query, $item) {
                /**
                 * @var $query Query
                 */
                if ($query === null) {
                    $query = $item;
                } else {
                    $query->union($item);
                }
                return $query;
            }
        );

        return $query;
    }
770056
public function delete($statements)
    {
        if (!isset($statements['tables'])) {
            throw new Exception('No table specified', 3);
        }

        $table = end($statements['tables']);

        // Wheres
        list($whereCriteria, $whereBindings) = $this->buildCriteriaWithType($statements, 'wheres', 'WHERE');

        // Limit
        $limit = isset($statements['limit']) ? 'LIMIT ' . $statements['limit'] : '';

        $sqlArray = array('DELETE FROM', $this->wrapSanitizer($table), $whereCriteria);
        $sql = $this->concatenateQuery($sqlArray);
        $bindings = $whereBindings;

        return compact('sql', 'bindings');
    }
1066322
public static function generate($pattern, array $queries = [])
    {
        $replace = [];

        $pattern = RouteHelper::sanitize($pattern);

        if (!isset(static::$vars[$pattern])) {
            TrieCompiler::compile($pattern);

            static::$vars[$pattern] = (array) TrieCompiler::$vars;
        }

        foreach (static::$vars[$pattern] as $key) {
            $var = isset($queries[$key]) ? $queries[$key] : 'null';

            if (is_array($var) || is_object($var)) {
                $var = implode('/', (array) $var);

                $key2 = '*' . $key;

                $replace[$key2] = $var;
            } else {
                $key2 = ':' . $key;

                $replace[$key2] = $var;
            }

            if (strpos($pattern, $key2) !== false) {
                unset($queries[$key]);
            }
        }

        $pattern = strtr($pattern, $replace);

        $queries = http_build_query($queries);

        if ($queries) {
            $pattern = rtrim($pattern, '/') . '/?' . $queries;
        }

        return $pattern;
    }
978194
public static function prepareQueryTimeline(array $queries)
    {
        if (!$queries) {
            return new NullObject();
        }

        // Prepare timeline data
        $timeline = [];

        foreach ($queries as $i => $data) {
            $time['value'] = abs($data['time']['start'] - $data['time']['end']) * 1000;
            $time['style'] = static::getStateColor($time['value'], 15);

            $memory['value'] = abs($data['memory']['start'] - $data['memory']['end']) / 1048576;
            $memory['style'] = static::getStateColor($memory['value'], 0.01);

            $timeline[$data['serial']] = [
                'time' => $time,
                'memory' => $memory,
                'data' => $data,
            ];
        }

        return $timeline;
    }
707058
protected function execute(string $query, array $bindings = [])
    {
        $query = N1qlQuery::fromString($query);
        $query->consistency($this->consistency);
        $query->crossBucket($this->crossBucket);
        $query->positionalParams($bindings);
        $result = $this->executeQuery($query);
        $this->metrics = $result->metrics ?? [];

        return $result;
    }
308149
public void executeQueries(List<String> queries, Optional<String> proxy)
      throws SQLException {
    Preconditions.checkArgument(!this.statementMap.isEmpty(), "No hive connection. Unable to execute queries");
    if (!proxy.isPresent()) {
      Preconditions.checkArgument(this.statementMap.size() == 1, "Multiple Hive connections. Please specify a user");
      proxy = Optional.fromNullable(this.statementMap.keySet().iterator().next());
    }
    Statement statement = this.statementMap.get(proxy.get());
    for (String query : queries) {
      statement.execute(query);
    }
  }
864646
public function runMultipleRawQuery($listSql, $continueOnError = false)
	{
		if (!$this->isOpen) { $this->throwError("RMRQ: It's not connected to the database",""); return false; }
		$arr = explode(';', $listSql);
		$ok = true;
		foreach ($arr as $rawSql) {
			if(trim($rawSql)!='') {
				if ($this->readonly) {
					if (stripos($rawSql, 'insert ') === 0 || stripos($rawSql, 'update ') === 0 || stripos($rawSql, 'delete ') === 0) {
						// we aren't checking SQL-DCL queries. Also, "insert into" is stopped but "  insert into" not.
						$ok = false;
						if (!$continueOnError) {
							$this->throwError("Database is in READ ONLY MODE","");
						}
					}
				}
				if ($this->logLevel >= 2) {
					$this->storeInfo($rawSql);
				}
				$r = $this->conn1->query($rawSql);
				if ($r === false) {
					$ok = false;
					if (!$continueOnError) {
						$this->throwError("Unable to run raw query",$this->lastQuery);
					}
				}
			}
		}
		return $ok;
	}
954997
public function execute($query, $bindings = [])
    {
        if (strtolower(substr($query, 0, 6)) === "select" && $this->forcePrefix) {
            $query = $this->forcePrefix . $query;
        }

        return $this->run($query, $bindings, function ($query, $bindings) {
            if ($this->pretending()) {
                return true;
            }

            $statement = $this->getPdo()->prepare($query);

            $this->bindValues($statement, $bindings);

            $statement->execute();
            return $statement;
        });
    }
626278
public function runMultiple(array $statements)
    {
        $pipeline = $this->session->createPipeline();

        foreach ($statements as $statement) {
            $pipeline->push($statement->text(), $statement->parameters(), $statement->getTag());
        }

        return $pipeline->run();
    }