Repository navigation
Expand file tree
/
Copy pathQueryJobConfiguration.php
More file actions
691 lines (621 loc) · 21.7 KB
/
Copy pathQueryJobConfiguration.php
File metadata and controls
691 lines (621 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
<?php
/**
* Copyright 2017 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 InvalidArgumentException;
use LogicException;
/**
* Represents a configuration for a query job. For more information on the
* available settings please see the
* [Jobs configuration API documentation](https://cloud.google.com/bigquery/docs/reference/rest/v2/Job).
*
* Example:
* ```
* use Google\Cloud\BigQuery\BigQueryClient;
*
* $bigQuery = new BigQueryClient();
* $query = $bigQuery->query('SELECT commit FROM `bigquery-public-data.github_repos.commits` LIMIT 100');
* ```
*/
class QueryJobConfiguration implements JobConfigurationInterface
{
use JobConfigurationTrait;
private const JOB_CREATION_MODE_OPTIONAL = 'JOB_CREATION_OPTIONAL';
/**
* @var ValueMapper Maps values between PHP and BigQuery.
*/
private $mapper;
private bool $isJobIdGenerated = false;
/**
* @param ValueMapper $mapper Maps values between PHP and BigQuery.
* @param string $projectId The project's ID.
* @param array $config A set of configuration options for a job.
* @param string|null $location The geographic location in which the job is
* executed.
*/
public function __construct(
ValueMapper $mapper,
$projectId,
array $config,
$location
) {
$this->mapper = $mapper;
$this->jobConfigurationProperties($projectId, $config, $location);
if (!isset($config['jobReference']['jobId'])) {
// If the user did not submit a jobId to the configuration array, the library will create a JobId before
// the request is sent. This is used to keep track if it is the user who set the JobId or the library
/// for stateless queries.
$this->isJobIdGenerated = true;
}
if (!isset($this->config['configuration']['query']['useLegacySql'])) {
$this->config['configuration']['query']['useLegacySql'] = false;
}
}
/**
* Sets whether or not the query can produce arbitrarily large result
* tables at a slight cost in performance.
*
* Only applies to queries performed with legacy SQL dialect and requires a
* {@see QueryJobConfiguration::destinationTable()} to
* be set.
*
* Example:
* ```
* $query->allowLargeResults(true);
* ```
*
* @param bool $allowLargeResults Whether or not to allow large result sets.
* @return QueryJobConfiguration
*/
public function allowLargeResults($allowLargeResults)
{
$this->config['configuration']['query']['allowLargeResults'] = $allowLargeResults;
return $this;
}
/**
* Set the clustering specification for the table.
*
* Refer to BigQuery documentation for a guide to clustered tables and
* constraints imposed by the service.
*
* Example:
* ```
* $query->clustering([
* 'fields' => [
* 'col1',
* 'col2'
* ]
* ]);
* ```
*
* @see https://cloud.google.com/bigquery/docs/clustered-tables Introduction to Clustered Tables
*
* @param array $clustering Clustering specification for the table.
* @return QueryJobConfiguration
*/
public function clustering(array $clustering)
{
$this->config['configuration']['query']['clustering'] = $clustering;
return $this;
}
/**
* Sets whether the job is allowed to create new tables.
*
* Example:
* ```
* $query->createDisposition('CREATE_NEVER');
* ```
*
* @param string $createDisposition The create disposition. Acceptable
* values include `"CREATE_IF_NEEDED"`, `"CREATE_NEVER"`.
* @return QueryJobConfiguration
*/
public function createDisposition($createDisposition)
{
$this->config['configuration']['query']['createDisposition'] = $createDisposition;
return $this;
}
/**
* Sets the default dataset to use for unqualified table names in the query.
*
* Example:
* ```
* $dataset = $bigQuery->dataset('my_dataset');
* $query->defaultDataset($dataset);
* ```
*
* @param Dataset $defaultDataset The default dataset.
* @return QueryJobConfiguration
*/
public function defaultDataset(Dataset $defaultDataset)
{
$this->config['configuration']['query']['defaultDataset'] = $defaultDataset->identity();
return $this;
}
/**
* Sets the custom encryption configuration (e.g., Cloud KMS keys).
*
* Example:
* ```
* $query->destinationEncryptionConfiguration([
* 'kmsKeyName' => 'my_key'
* ]);
* ```
*
* @param array $configuration Custom encryption configuration.
* @return QueryJobConfiguration
*/
public function destinationEncryptionConfiguration(array $configuration)
{
$this->config['configuration']['query']['destinationEncryptionConfiguration'] = $configuration;
return $this;
}
/**
* Sets the table where the query results should be stored. If not set, a
* new table will be created to store the results. This property must be set
* for large results that exceed the maximum response size.
*
* Example:
* ```
* $table = $bigQuery->dataset('my_dataset')
* ->table('my_table');
* $query->destinationTable($table);
* ```
*
* @param Table $destinationTable The destination table.
* @return QueryJobConfiguration
*/
public function destinationTable(Table $destinationTable)
{
$this->config['configuration']['query']['destinationTable'] = $destinationTable->identity();
return $this;
}
/**
* Sets whether or not to flatten all nested and repeated fields in the
* query results.
*
* Only applies to queries performed with legacy SQL dialect.
* {@see QueryJobConfiguration::allowLargeResults()} must be true if this
* is set to false.
*
* Example:
* ```
* $query->useLegacySql(true)
* ->flattenResults(true);
* ```
*
* @param bool $flattenResults Whether or not to flatten results.
* @return QueryJobConfiguration
*/
public function flattenResults($flattenResults)
{
$this->config['configuration']['query']['flattenResults'] = $flattenResults;
return $this;
}
/**
* Sets the billing tier limit for this job. Queries that have resource
* usage beyond this tier will fail (without incurring a charge). If
* unspecified, this will be set to your project default.
*
* Example:
* ```
* $query->maximumBillingTier(1);
* ```
*
* @param int $maximumBillingTier The maximum billing tier.
* @return QueryJobConfiguration
*/
public function maximumBillingTier($maximumBillingTier)
{
$this->config['configuration']['query']['maximumBillingTier'] = $maximumBillingTier;
return $this;
}
/**
* Sets a bytes billed limit for this job. Queries that will have bytes
* billed beyond this limit will fail (without incurring a charge). If
* unspecified, this will be set to your project default.
*
* Example:
* ```
* $query->maximumBytesBilled(3000);
* ```
*
* @param int $maximumBytesBilled The maximum allowable bytes to bill.
* @return QueryJobConfiguration
*/
public function maximumBytesBilled($maximumBytesBilled)
{
$this->config['configuration']['query']['maximumBytesBilled'] = $maximumBytesBilled;
return $this;
}
/**
* Sets parameters to be used on the query. Only available for standard SQL
* queries.
*
* For examples of usage please see
* {@see BigQueryClient::runQuery()}.
*
* @param array $parameters Parameters to use on the query. When providing
* a non-associative array positional parameters (`?`) will be used.
* When providing an associative array named parameters will be used
* (`@name`).
* @return QueryJobConfiguration
*/
public function parameters(array $parameters)
{
$queryParams = [];
$this->config['configuration']['query']['parameterMode'] = $this->isAssoc($parameters)
? 'named'
: 'positional';
foreach ($parameters as $name => $value) {
$param = $this->mapper->toParameter($value);
if ($this->config['configuration']['query']['parameterMode'] === 'named') {
$param += ['name' => $name];
}
$queryParams[] = $param;
}
$this->config['configuration']['query']['queryParameters'] = $queryParams;
return $this;
}
/**
* Sets the parameter types for positional parameters.
* Note, that this is of high importance when an empty array can be passed as
* a positional parameter, as we have no way of guessing the data type of the
* array contents.
*
* ```
* $queryStr = 'SELECT * FROM `bigquery-public-data.github_repos.commits` ' .
* 'WHERE author.time_sec IN UNNEST (?) AND message IN UNNEST (?) AND committer.name = ? LIMIT 10';
*
* $queryJobConfig = $bigQuery->query("")
* ->parameters([[], ["abc", "def"], "John"])
* ->setParamTypes(['INT64']);
* ```
* In the above example, the first array will have a type of INT64
* while the next one will have a type of
* STRING (even though the second array type is not supplied).
*
* For named params, we can simply call:
* ```
* $queryJobConfig = $bigQuery->query("")
* ->parameters(['times' => [], 'messages' => ["abc", "def"]])
* ->setParamTypes(['times' => 'INT64']);
* ```
*
* @param array $userTypes The user supplied types for the positional parameters.
* This overrides the guessed types that the ValueMapper got from the toParameter
* method call.
*
* @return QueryJobConfiguration
*/
public function setParamTypes(array $userTypes)
{
$queryParams = $this->config['configuration']['query']['queryParameters'] ?? null;
$mode = $this->config['configuration']['query']['parameterMode'] ?? null;
if (is_null($queryParams)) {
throw new LogicException('QueryJobConfiguration::parameters must be called before setParamTypes');
}
foreach ($queryParams as $index => &$param) {
// If the user supplied named params, we use the `name` attribute of the parameter
// otherwise we just use the index to map.
$key = $mode === 'named' ? $param['name'] : $index;
$userType = $this->pluck($key, $userTypes, false);
// If the user hasn't supplied this key in the setParamTypes
// call, then we just use the $guessedType(no need to override)
if (is_null($userType)) {
continue;
}
$guessedType = $param['parameterType']['type'];
if ($guessedType === $this->mapper::TYPE_ARRAY) {
$param['parameterType']['arrayType'] = ['type' => $userType];
} else {
$param['parameterType']['type'] = $userType;
}
}
// If the $userTypes still contains a value,
// that means it had an extra key which doesn't exist
// in the parameters() call
if (count($userTypes) > 0) {
throw new InvalidArgumentException(sprintf(
'The key \'%s\' doesn\'t exist in the parameters',
key($userTypes)
));
}
$this->config['configuration']['query']['queryParameters'] = $queryParams;
return $this;
}
/**
* Sets a priority for the query.
*
* Example:
* ```
* $query->priority('BATCH');
* ```
*
* @param string $priority The priority. Acceptable values include
* `"INTERACTIVE"`, `"BATCH"`. **Defaults to** `"INTERACTIVE"`.
* @return QueryJobConfiguration
*/
public function priority($priority)
{
$this->config['configuration']['query']['priority'] = $priority;
return $this;
}
/**
* Sets the SQL query.
*
* Example:
* ```
* $query->query(
* 'SELECT commit FROM `bigquery-public-data.github_repos.commits` LIMIT 100'
* );
* ```
*
* @param string $query SQL query text to execute.
* @return QueryJobConfiguration
*/
public function query($query)
{
$this->config['configuration']['query']['query'] = $query;
return $this;
}
/**
* Sets options to allow the schema of the destination table to be updated
* as a side effect of the query job. Schema update options are supported
* in two cases: when writeDisposition is `"WRITE_APPEND"`; when
* writeDisposition is `"WRITE_TRUNCATE"` and the destination table is a
* partition of a table, specified by partition decorators. For normal
* tables, `"WRITE_TRUNCATE"` will always overwrite the schema.
*
* Example:
* ```
* $query->schemaUpdateOptions([
* 'ALLOW_FIELD_ADDITION'
* ]);
* ```
*
* @param array $schemaUpdateOptions Schema update options. Acceptable
* values include `"ALLOW_FIELD_ADDITION"` (allow adding a nullable
* field to the schema), `"ALLOW_FIELD_RELAXATION"` (allow relaxing
* a required field in the original schema to nullable).
* @return QueryJobConfiguration
*/
public function schemaUpdateOptions(array $schemaUpdateOptions)
{
$this->config['configuration']['query']['schemaUpdateOptions'] = $schemaUpdateOptions;
return $this;
}
/**
* Sets table definitions for querying an external data source outside of
* BigQuery. Describes the data format, location and other properties of the
* data source.
*
* Example:
* ```
* $query->tableDefinitions([
* 'autodetect' => true,
* 'sourceUris' => [
* 'gs://my_bucket/table.json'
* ]
* ]);
* ```
*
* @param array $tableDefinitions The table definitions.
* @return QueryJobConfiguration
*/
public function tableDefinitions(array $tableDefinitions)
{
$this->config['configuration']['query']['tableDefinitions'] = $tableDefinitions;
return $this;
}
/**
* Sets time-based partitioning for the destination table.
*
* Only one of timePartitioning and rangePartitioning should be specified.
*
* Example:
* ```
* $query->timePartitioning([
* 'type' => 'DAY'
* ]);
* ```
*
* @param array $timePartitioning Time-based partitioning configuration.
* @return QueryJobConfiguration
*/
public function timePartitioning(array $timePartitioning)
{
$this->config['configuration']['query']['timePartitioning'] = $timePartitioning;
return $this;
}
/**
* Sets range partitioning specification for the destination table.
*
* Only one of timePartitioning and rangePartitioning should be specified.
*
* Example:
* ```
* $query->rangePartitioning([
* 'field' => 'myInt',
* 'range' => [
* 'start' => '0',
* 'end' => '1000',
* 'interval' => '100'
* ]
* ]);
* ```
*
* @param array $rangePartitioning
* @return QueryJobConfiguration
*/
public function rangePartitioning(array $rangePartitioning)
{
$this->config['configuration']['query']['rangePartitioning'] = $rangePartitioning;
return $this;
}
/**
* Sets whether or not to use legacy SQL dialect. When not set, defaults to
* false in this client.
*
* Example:
* ```
* $query->useLegacySql(true);
* ```
*
* @param bool $useLegacySql Whether or not to use legacy SQL dialect.
* @return QueryJobConfiguration
*/
public function useLegacySql($useLegacySql)
{
$this->config['configuration']['query']['useLegacySql'] = $useLegacySql;
return $this;
}
/**
* Sets whether or not to use the query cache.
*
* Example:
* ```
* $query->useQueryCache(true);
* ```
*
* @see https://cloud.google.com/bigquery/docs/cached-results Using cached results
*
* @param bool $useQueryCache Whether or not to use the query cache.
* @return QueryJobConfiguration
*/
public function useQueryCache($useQueryCache)
{
$this->config['configuration']['query']['useQueryCache'] = $useQueryCache;
return $this;
}
/**
* Sets user-defined function resources used in the query.
*
* Example:
* ```
* $query->userDefinedFunctionResources([
* ['resourceUri' => 'gs://my_bucket/code_path']
* ]);
* ```
*
* @param array $userDefinedFunctionResources User-defined function
* resources used in the query. This is to be formatted as a list of
* sub-arrays containing either a key `resourceUri` or `inlineCode`.
* @return QueryJobConfiguration
*/
public function userDefinedFunctionResources(array $userDefinedFunctionResources)
{
$this->config['configuration']['query']['userDefinedFunctionResources'] = $userDefinedFunctionResources;
return $this;
}
/**
* Sets the action that occurs if the destination table already exists. Each
* action is atomic and only occurs if BigQuery is able to complete the job
* successfully. Creation, truncation and append actions occur as one atomic
* update upon job completion.
*
* Example:
* ```
* $query->writeDisposition('WRITE_TRUNCATE');
* ```
*
* @param string $writeDisposition The write disposition. Acceptable values
* include `"WRITE_TRUNCATE"`, `"WRITE_APPEND"`, `"WRITE_EMPTY"`.
* **Defaults to** `"WRITE_EMPTY"`.
* @return QueryJobConfiguration
*/
public function writeDisposition($writeDisposition)
{
$this->config['configuration']['query']['writeDisposition'] = $writeDisposition;
return $this;
}
/**
* Returns true if the current configuration is compatible with the stateless query API.
* False if not
*
* @internal
* @return bool
*/
public function isStateless(): bool
{
$config = $this->config;
$queryConfig = $config['configuration']['query'];
if (isset($queryConfig['destinationTable']) ||
isset($queryConfig['tableDefinitions']) ||
isset($queryConfig['createDisposition']) ||
isset($queryConfig['writeDisposition']) ||
($queryConfig['useLegacySql'] ?? false) ||
isset($queryConfig['maximumBillingTier']) ||
isset($queryConfig['timePartitioning']) ||
isset($queryConfig['rangePartitioning']) ||
isset($queryConfig['clustering']) ||
isset($queryConfig['destinationEncryptionConfiguration']) ||
isset($queryConfig['schemaUpdateOptions']) ||
isset($queryConfig['jobTimeoutMs'])
) {
return false;
}
if (isset($queryConfig['priority']) && $queryConfig['priority'] !== 'INTERACTIVE') {
return false;
}
if ($config['configuration']['dryRun'] ?? false) {
return false;
}
// 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']) && !$this->isJobIdGenerated()) {
return false;
}
return true;
}
/**
* Returns an array representation of a QueryRequest:
* [QueryRequest](https://docs.cloud.google.com/bigquery/docs/reference/rest/v2/jobs/query#QueryRequest)
*
* @return array
*/
public function toQueryRequest(): array
{
$config = $this->config;
$queryConfig = $config['configuration']['query'];
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
];
}
/**
* Returns if the JobId was generated by the JobConfigurationTrait
*
* @return bool
*/
private function isJobIdGenerated(): bool
{
return $this->isJobIdGenerated;
}
}