|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright 2018 Google LLC. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * For instructions on how to run the full sample: |
| 20 | + * |
| 21 | + * @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/bigquery/api/README.md |
| 22 | + */ |
| 23 | + |
| 24 | +// Include Google Cloud dependendencies using Composer |
| 25 | +require_once __DIR__ . '/../vendor/autoload.php'; |
| 26 | +if (count($argv) != 3) { |
| 27 | + return printf("Usage: php %s PROJECT_ID DATASET_ID\n", __FILE__); |
| 28 | +} |
| 29 | + |
| 30 | +list($_, $projectId, $datasetId) = $argv; |
| 31 | +# [START bigquery_load_table_gcs_csv_autodetect] |
| 32 | +use Google\Cloud\BigQuery\BigQueryClient; |
| 33 | +use Google\Cloud\Core\ExponentialBackoff; |
| 34 | + |
| 35 | +/** Uncomment and populate these variables in your code */ |
| 36 | +// $projectId = 'The Google project ID'; |
| 37 | +// $datasetId = 'The BigQuery dataset ID'; |
| 38 | + |
| 39 | +// instantiate the bigquery table service |
| 40 | +$bigQuery = new BigQueryClient([ |
| 41 | + 'projectId' => $projectId, |
| 42 | +]); |
| 43 | +$dataset = $bigQuery->dataset($datasetId); |
| 44 | +$table = $dataset->table('us_states'); |
| 45 | + |
| 46 | +// create the import job |
| 47 | +$gcsUri = 'gs://cloud-samples-data/bigquery/us-states/us-states.csv'; |
| 48 | +$loadConfig = $table->loadFromStorage($gcsUri)->autodetect(true)->skipLeadingRows(1); |
| 49 | +$job = $table->runJob($loadConfig); |
| 50 | +// poll the job until it is complete |
| 51 | +$backoff = new ExponentialBackoff(10); |
| 52 | +$backoff->execute(function () use ($job) { |
| 53 | + print('Waiting for job to complete' . PHP_EOL); |
| 54 | + $job->reload(); |
| 55 | + if (!$job->isComplete()) { |
| 56 | + throw new Exception('Job has not yet completed', 500); |
| 57 | + } |
| 58 | +}); |
| 59 | +// check if the job has errors |
| 60 | +if (isset($job->info()['status']['errorResult'])) { |
| 61 | + $error = $job->info()['status']['errorResult']['message']; |
| 62 | + printf('Error running job: %s' . PHP_EOL, $error); |
| 63 | +} else { |
| 64 | + print('Data imported successfully' . PHP_EOL); |
| 65 | +} |
| 66 | +# [END bigquery_load_table_gcs_csv_autodetect] |
0 commit comments