Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions BigQuery/src/BigQueryClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

use function PHPUnit\Framework\isNull;

Comment on lines +37 to +38
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this was accidental

Suggested change
use function PHPUnit\Framework\isNull;

/**
* Google Cloud BigQuery allows you to create, manage, share and query data.
* Find more information at the
Expand Down Expand Up @@ -417,6 +419,45 @@ public function runQuery(JobConfigurationInterface $query, array $options = [])
], $options);
$queryResultsOptions['initialTimeoutMs'] = 10000;

// Check if we can build a query Request
$queryRequest = StatelessJobConfiguration::getQueryRequest($query);

if (!is_null($queryRequest)) {
if (isset($queryResultsOptions['formatOptions.useInt64Timestamp'])) {
$useInt64 = $this->pluck('formatOptions.useInt64Timestamp', $queryResultsOptions, false);

if (!isset($queryResultsOptions['formatOptions']) || !is_array($queryResultsOptions['formatOptions'])) {
$queryResultsOptions['formatOptions'] = [];
}

$queryResultsOptions['formatOptions']['useInt64Timestamp'] = $useInt64;
}

$statelessArgs = $queryRequest + $queryResultsOptions + [
'projectId' => $this->projectId
] + $options;

if (!isset($statelessArgs['timeoutMs'])) {
$statelessArgs['timeoutMs'] = $statelessArgs['initialTimeoutMs'];
}

$statelessResponse = $this->connection->query($statelessArgs);

$queryResults = QueryResults::fromStatelessQuery(
$this->connection,
$this->projectId,
$statelessResponse,
$this->mapper,
$queryResultsOptions + $options
);

if (!$queryResults->isComplete()) {
$queryResults->waitUntilComplete();
}

return $queryResults;
}

$queryResults = $this->startQuery(
$query,
$options
Expand Down
5 changes: 5 additions & 0 deletions BigQuery/src/Connection/Rest.php
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,11 @@ public function setTableIamPolicy(array $args = [])
return $this->send('tables', 'setIamPolicy', $args);
}

public function statelessQuery(array $args = [])
{
return $this->send('jobs', 'query', $args);
}

/**
* @param array $args
* @return array
Expand Down
10 changes: 10 additions & 0 deletions BigQuery/src/JobConfigurationTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ trait JobConfigurationTrait
*/
private $config = [];

private bool $isJobIdGenerated = false;

/**
* Sets shared job configuration properties.
*
Expand All @@ -62,6 +64,9 @@ public function jobConfigurationProperties(

if (!isset($this->config['jobReference']['jobId'])) {
$this->config['jobReference']['jobId'] = $this->generateJobId();

// Used for the Stateless query logic
$this->isJobIdGenerated = true;
}
}

Expand Down Expand Up @@ -165,6 +170,11 @@ public function location($location)
return $this;
}

public function isJobIdGenerated(): bool
{
return $this->isJobIdGenerated;
}

/**
* Returns the job config as an array.
*
Expand Down
49 changes: 49 additions & 0 deletions BigQuery/src/QueryResults.php
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,10 @@ public function info()
*/
public function reload(array $options = [])
{
if (!isset($this->info['jobReference'])) {
return $this->info;
}

return $this->info = $this->connection->getQueryResults(
$options + $this->identity
);
Expand Down Expand Up @@ -371,4 +375,49 @@ public function getIterator()
{
return $this->rows();
}

/**
* @param ConnectionInterface $connection Represents a connection to
* BigQuery. This object is created by BigQueryClient,
* and should not be instantiated outside of this client.
* @param string $projectId The project's ID.
* @param array $statelessResponse The query result's metadata.
* @param ValueMapper $mapper Maps values between PHP and BigQuery.
* @param array $queryResultsOptions Default options to be used for calls to
* get query results. See
* [documentation](https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/getQueryResults#query-parameters)
* for available options.
*/
public static function fromStatelessQuery(
ConnectionInterface $connection,
string $projectId,
array $statelessResponse,
ValueMapper $mapper,
array $queryResultsOptions = []
): QueryResults {
$jobReference = $statelessResponse['jobReference'] ?? [];
// If jobId is null, it was a stateless request that completed in one request.
$jobId = $jobReference['jobId'] ?? null;
$projectId = $jobReference['projectId'] ?? $projectId;
$location = $jobReference['location'] ?? ($statelessResponse['location'] ?? null);

$job = new Job(
$connection,
$jobId,
$projectId,
$mapper,
[],
$location
);

return new QueryResults(
$connection,
$jobId,
$projectId,
$statelessResponse,
$mapper,
$job,
$queryResultsOptions
);
}
}
111 changes: 111 additions & 0 deletions BigQuery/src/StatelessJobConfiguration.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?php
/**
* Copyright 2026 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Google\Cloud\BigQuery;

use Ramsey\Uuid\Uuid;

/**
* Represents a configuration for a stateless query.
*
* This class is used internally by {@see BigQueryClient::runQuery()} to
* determine if a query can be executed using the stateless `jobs.query`
* endpoint and to build the corresponding request.
*
* @internal
*/
class StatelessJobConfiguration implements JobConfigurationInterface
{
use JobConfigurationTrait;
const JOB_CREATION_MODE_OPTIONAL = 'JOB_CREATION_OPTIONAL';

/**
* Returns an array that represents a QueryRequest for a stateless query.
* Returns null if one of the conditions are not met for a stateless query.
*
* @return array<mixed>|null
*/
public static function getQueryRequest(JobConfigurationInterface $jobConfiguration): array|null
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fact that this returns an array when the object itself implements a toArray() method seems wrong. I would expect it to be something more like this:

if ($query->isStateless()) {
    $stateless = StatelessJobConfiguration::fromQueryConfiguration($query);
    $request = $stateless->toArray();
}

{
$config = $jobConfiguration->toArray();
$queryConfig = $config['configuration']['query'];

if (
isset($queryConfig['destinationTable']) ||
isset($queryConfig['tableDefinitions']) ||
isset($queryConfig['createDisposition']) ||
isset($queryConfig['writeDisposition']) ||
(
isset($queryConfig['priority']) &&
$queryConfig['priority'] !== 'INTERACTIVE'
) ||
(isset($queryConfig['useLegacySql']) && $queryConfig['useLegacySql']) ||
isset($queryConfig['maximumBillingTier']) ||
isset($queryConfig['timePartitioning']) ||
isset($queryConfig['rangePartitioning']) ||
isset($queryConfig['clustering']) ||
isset($queryConfig['destinationEncryptionConfiguration']) ||
isset($queryConfig['schemaUpdateOptions']) ||
isset($queryConfig['jobTimeoutMs']) ||
isset($queryConfig['jobId'])
) {
return null;
}

if (isset($config['configuration']['dryRun']) && $config['configuration']['dryRun']) {
return null;
}

// Creating a jobConfiguration from the library sets the JobId always meaning we do not have a way
// to determine if this jobId was set by the user or our library.
// We check if this was autogenerated to circumvent this issue.
if (
isset($config['jobReference']['jobId']) &&
method_exists($jobConfiguration, 'isJobIdGenerated') &&
!$jobConfiguration->isJobIdGenerated()
) {
return null;
}

return [
'query' => $queryConfig['query'],
'maxResults' => $queryConfig['maxResults'] ?? null,
'defaultDataset' => $queryConfig['defaultDataset'] ?? null,
'timeoutMs' => $queryConfig['timeoutMs'] ?? null,
'useQueryCache' => $queryConfig['useQueryCache'] ?? null,
'useLegacySql' => false,
'queryParameters' => $queryConfig['queryParameters'] ?? null,
'parameterMode' => $queryConfig['parameterMode'] ?? null,
'labels' => $config['configuration']['labels'] ?? null,
'createSession' => $queryConfig['createSession'] ?? null,
'maximumBytesBilled' => $queryConfig['maximumBytesBilled'] ?? null,
'location' => $config['jobReference']['location'] ?? null,
'requestId' => $config['jobReference']['jobId'],
'jobCreationMode' => self::JOB_CREATION_MODE_OPTIONAL
];
}

/**
* Generate a Job ID.
*
* @return string
*/
protected static function generateJobId()
{
return Uuid::uuid4()->toString();
}
}
Loading
Loading