Performs batch of select queries.

@param array $queries
@param int   $concurrency Max concurrency requests

@return array
555033
public function read(array $queries, int $concurrency = 5): array
    {
        foreach ($queries as $i => $query) {
            if (!$query instanceof Query) {
                $queries[$i] = $this->guessQuery($query);
            }
        }
        
        return $this->getTransport()->read($queries, $concurrency);
    }
1130453
public function select($query, $bindings = array())
	{
		return $this->run($query, $bindings, function($me, $query, $bindings)
		{
			if ($me->pretending()) return array();

			// For select statements, we'll simply execute the query and return an array
			// of the database result set. Each element in the array will be a single
			// row from the database table, and will either be an array or objects.
			$statement = $me->getReadPdo()->prepare($query);

			$statement->execute($me->prepareBindings($bindings));

			return $statement->fetchAll($me->getFetchMode());
		});
	}
220587
protected function filterQueries($queries)
    {
        $app = Application::getFacadeApplication();
        $config = $app->make('config');

        $textIndexDrops = [];
        foreach ($config->get('database.text_indexes') as $indexTable => $indexDefinition) {
            foreach (array_keys($indexDefinition) as $indexName) {
                $textIndexDrops[] = strtolower("DROP INDEX {$indexName} ON {$indexTable}");
            }
        }

        $returnQueries = [];
        foreach ($queries as $query) {
            $queryLowerCase = strtolower($query);
            if (!in_array($queryLowerCase, $textIndexDrops, true)) {
                $returnQueries[] = $query;
            }
        }

        return $returnQueries;
    }
75901
public function from($tables): SelectStatement
    {
        $subquery = new Subquery();
        $this->addExpression('subquery', $subquery);
        return $subquery->from($tables);
    }
612442
public function batchSearch(array $queries) {
        $requests = [];

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

        return $this->api->batchRequest($requests);
    }
319118
public static function bulkDelete(array $records, array $params = [])
    {
        if (empty($records)) {
            throw new BadRequestException('There is no record in the request.');
        }

        $response = [];
        $errors = false;
        $rollback = array_get_bool($params, ApiOptions::ROLLBACK);
        $continue = array_get_bool($params, ApiOptions::CONTINUES);

        if ($rollback) {
            //	Start a transaction
            DB::beginTransaction();
        }

        foreach ($records as $key => $record) {
            try {
                $m = new static;
                $pk = $m->getPrimaryKey();
                $id = array_get($record, $pk);
                $response[$key] = static::deleteInternal($id, $record, $params);
            } catch (\Exception $ex) {
                // track the index of the error and copy error to results
                $errors = true;
                $response[$key] = $ex;
                if ($rollback || !$continue) {
                    break;
                }
            }
        }

        if ($errors) {
            $msg = "Batch Error: Not all requested records could be deleted.";
            if ($rollback) {
                DB::rollBack();
                $msg .= " All changes rolled back.";
            }

            throw new BatchException($response, $msg);
        }

        if ($rollback) {
            DB::commit();
        }

        return $response;
    }
577778
public static function bulkEnqueue($handlers, $queue = "default", $run_at = null) {
        $sql = "INSERT INTO " . self::$jobsTable . " (handler, queue, run_at, created_at) VALUES";
        $sql .= implode(",", array_fill(0, count($handlers), "(?, ?, ?, NOW())"));

        $parameters = array();
        foreach ($handlers as $handler) {
            $parameters []= serialize($handler);
            $parameters []= (string) $queue;
            $parameters []= $run_at;
        }
        $affected = self::runUpdate($sql, $parameters);

        if ($affected < 1) {
            self::log("[JOB] failed to enqueue new jobs", self::ERROR);
            return false;
        }

        if ($affected != count($handlers))
            self::log("[JOB] failed to enqueue some new jobs", self::ERROR);

        return true;
    }
1029192
protected function multiQuery(string $queries): void
  {
    if ($this->logQueries)
    {
      $time0 = microtime(true);

      $tmp = $this->mysqli->multi_query($queries);
      if ($tmp===false)
      {
        throw new DataLayerException($this->mysqli->errno, $this->mysqli->error, $queries);
      }

      $this->queryLog[] = ['query' => $queries, 'time' => microtime(true) - $time0];
    }
    else
    {
      $tmp = $this->mysqli->multi_query($queries);
      if ($tmp===false)
      {
        throw new DataLayerException($this->mysqli->errno, $this->mysqli->error, $queries);
      }
    }
  }
742641
public function selectFromWriteConnection( $query, $bindings = [ ], $resultClass = null )
	{
		return $this->select( $query, $bindings, false, $resultClass );
	}
869923
public function union($queries, $distinct = false)
    {
        if ($this->_db === null) {
            foreach ($queries as $query) {
                if ($query instanceof self) {
                    $this->_db = $query->_db;
                    break;
                }
            }
        }
        $this->_union = ['type' => 'UNION ' . ($distinct ? 'DISTINCT' : 'ALL'), 'queries' => $queries];

        return $this;
    }
8766
public function setQueries($queries)
    {
        $this->queries = [];
        if (!is_array($queries)) {
            $queries = [$queries];
        }
        foreach ($queries as $query) {
            $this->addQuery($query);
        }

        return $this;
    }
566900
public function executeLog(string $queries): int
  {
    // Counter for the number of rows written/logged.
    $n = 0;

    $this->multiQuery($queries);
    do
    {
      $result = $this->mysqli->store_result();
      if ($this->mysqli->errno) $this->mySqlError('mysqli::store_result');
      if ($result)
      {
        $fields = $result->fetch_fields();
        while (($row = $result->fetch_row()))
        {
          $line = '';
          foreach ($row as $i => $field)
          {
            if ($i>0) $line .= ' ';
            $line .= str_pad((string)$field, $fields[$i]->max_length);
          }
          echo date('Y-m-d H:i:s'), ' ', $line, "\n";
          $n++;
        }
        $result->free();
      }

      $continue = $this->mysqli->more_results();
      if ($continue)
      {
        $tmp = $this->mysqli->next_result();
        if ($tmp===false) $this->mySqlError('mysqli::next_result');
      }
    } while ($continue);

    return $n;
  }
627906
public function select(array $statements): array
    {
        $hasDistincts = false;

        if (isset($statements['distincts']) === true && \count($statements['distincts']) > 0) {
            $hasDistincts = true;

            if (isset($statements['selects']) === true && \count($statements['selects']) > 0) {
                $statements['selects'] = array_merge($statements['distincts'], $statements['selects']);
            } else {
                $statements['selects'] = $statements['distincts'];
            }

        } else if (isset($statements['selects']) === false) {
            $statements['selects'] = ['*'];
        }

        // From
        $fromEnabled = false;
        $tables = '';

        if (isset($statements['tables']) === true) {
            $tablesFound = [];

            foreach ((array)$statements['tables'] as $table) {
                if ($table instanceof Raw) {
                    $t = $table;
                } else {
                    $prefix = $statements['aliases'][$table] ?? null;

                    if ($prefix !== null) {
                        $t = sprintf('`%s` AS `%s`', $table, strtolower($prefix));
                    } else {
                        $t = sprintf('`%s`', $table);
                    }
                }

                $tablesFound[] = $t;
            }

            $tables = implode(',', $tablesFound);
            $fromEnabled = true;
        }

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

        // HAVING
        [$havingCriteria, $havingBindings] = $this->buildCriteriaWithType($statements, 'havings', 'HAVING');

        $sql = $this->concatenateQuery([
            'SELECT' . ($hasDistincts === true ? ' DISTINCT' : ''),
            $this->arrayStr($statements['selects'], ', '),
            $fromEnabled ? 'FROM' : '',
            $tables,
            $this->buildQueryPart(static::QUERY_PART_JOIN, $statements),
            $whereCriteria,
            $this->buildQueryPart(static::QUERY_PART_GROUPBY, $statements),
            $havingCriteria,
            $this->buildQueryPart(static::QUERY_PART_ORDERBY, $statements),
            $this->buildQueryPart(static::QUERY_PART_LIMIT, $statements),
            $this->buildQueryPart(static::QUERY_PART_OFFSET, $statements),
        ]);

        $sql = $this->buildUnion($statements, $sql);

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

        return compact('sql', 'bindings');
    }
542526
private function visitQueries(array $queries)
    {
        $result = [];
        foreach ($queries as $query) {
            $result[] = $this->getInterpreter($query)->visit($query);
        }

        return $result;
    }
415093
protected function processStatements(array $statements, string $prefix = ''): void
    {
        $uses = [];

        foreach ($statements as $statement) {
            if ($statement instanceof Namespace_) {
                $this->processStatements($statement->stmts, (string)$statement->name);

                return;
            }

            if ($statement instanceof Use_) {
                foreach ($statement->uses as $use) {
                    /** @var Identifier $aliasIdentifier */
                    $aliasIdentifier = $use->alias;
                    if (empty($aliasIdentifier->name)) {
                        $parts = $use->name->parts;
                        $alias = (string)end($parts);
                    } else {
                        $alias = $aliasIdentifier->name;
                    }

                    $uses[$alias] = $use->name->toString();
                }
            }

            if ($statement instanceof Class_) {
                $this->processClassStatement($statement, $prefix, $uses);
            }
        }
    }
856797
public function queryfetch($query, $returnarray=false) {
    list($result, $numrows) = $this->query($query, true);
    
    if($result === false) {
      throw new SqlException($query, $this);
    }

    while($row = $result->fetch(PDO::FETCH_ASSOC)) {
      $rows[] = $row;
    }
    return ($returnarray) ? array($rows, $numrows, result=>$rows, numrows=>$numrows) : $rows;
  }
694263
public function lookup(array $queries = array())
    {
        try {
            $request  = $this->requestLookup($queries);
            $response = $this->getClient()->send($request);
        } catch(\Exception $ex) {
            throw new \RuntimeException('Failed to get response', 0, $ex);
        }

        // if success level, 
        if(2 == floor($response->getStatusCode()/100)) {
            $contentType = $response->getHeader('Content-Type');

            switch($contentType) {
            case 'application/json':
                return $response->json();
            case 'application/xml':
                return $response->xml();
            default:
                //throw new UnsupportedFormatException(sprintf('Content-Type "%s" is not supported.', $response->getHeader('Content-Type')));
                throw new \RuntimeException(sprintf('Content-Type "%s" is not supported.', $contentType));
            }
        }

        throw new \RuntimeException(sprintf('Failed to get the response: StatusCode [%d]', $response->getStatusCode()));
    }