Skip to content

Commit 18fa6de

Browse files
authored
adds bigquery sql import examples (GoogleCloudPlatform#240)
1 parent 2184489 commit 18fa6de

File tree

6 files changed

+88
-10
lines changed

6 files changed

+88
-10
lines changed

bigquery/api/composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
"src/functions/export_table.php",
2121
"src/functions/import_from_file.php",
2222
"src/functions/import_from_storage.php",
23+
"src/functions/insert_sql.php",
2324
"src/functions/list_datasets.php",
2425
"src/functions/list_projects.php",
2526
"src/functions/list_tables.php",

bigquery/api/composer.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

bigquery/api/src/ImportCommand.php

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -91,28 +91,32 @@ protected function execute(InputInterface $input, OutputInterface $output)
9191
}
9292
$message = sprintf('<info>Using project %s</info>', $projectId);
9393
$output->writeln($message);
94+
$source = $input->getArgument('source');
95+
$isSqlImport = 'sql' === substr((string) $source, -3);
96+
$isDatastoreBackup = '.backup_info' === substr($source, -12);
9497
$fullTableName = $input->getArgument('dataset.table');
9598
if (1 !== substr_count($fullTableName, '.')) {
96-
throw new InvalidArgumentException('Table must in the format "dataset.table"');
99+
if (!$isSqlImport) {
100+
throw new InvalidArgumentException('Table must in the format "dataset.table"');
101+
}
102+
list($datasetId, $tableId) = [$fullTableName, ''];
103+
} else {
104+
list($datasetId, $tableId) = explode('.', $fullTableName);
97105
}
98-
list($datasetId, $tableId) = explode('.', $fullTableName);
99106
$bigQuery = new BigQueryClient([
100107
'projectId' => $projectId,
101108
]);
102109
$dataset = $bigQuery->dataset($datasetId);
103110
$table = $dataset->table($tableId);
104-
$source = $input->getArgument('source');
105-
$isDatastoreBackup = '.backup_info' === substr($source, -12);
106111
if (!$dataset->exists()) {
107112
throw new InvalidArgumentException('The supplied dataset does not exist for this project');
108113
}
109-
if (!$isDatastoreBackup) {
114+
if (!$isDatastoreBackup && !$isSqlImport) {
110115
if (!$table->exists()) {
111116
throw new InvalidArgumentException('The supplied table does not exist for this project. ' .
112117
'Create a schema in the UI or use the "schema" command');
113118
}
114119
}
115-
116120
if (empty($source)) {
117121
$info = $table->info();
118122
$data = $this->getRowData($info['schema']['fields'], $question, $input, $output);
@@ -128,7 +132,11 @@ protected function execute(InputInterface $input, OutputInterface $output)
128132
if (!(file_exists($source) && is_readable($source))) {
129133
throw new InvalidArgumentException('Source file does not exist or is not readable');
130134
}
131-
import_from_file($projectId, $datasetId, $tableId, $source);
135+
if ($isSqlImport) {
136+
insert_sql($projectId, $datasetId, $source);
137+
} else {
138+
import_from_file($projectId, $datasetId, $tableId, $source);
139+
}
132140
}
133141
}
134142

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<?php
2+
/**
3+
* Copyright 2015 Google Inc. All Rights Reserved.
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+
namespace Google\Cloud\Samples\BigQuery;
25+
26+
# [START insert_sql]
27+
use Google\Cloud\ServiceBuilder;
28+
29+
/**
30+
* @param string $projectId The Google project ID.
31+
* @param string $datasetId The BigQuery dataset ID.
32+
* @param string $source The path to the source file to import.
33+
*/
34+
function insert_sql($projectId, $datasetId, $source)
35+
{
36+
// instantiate the bigquery table service
37+
$builder = new ServiceBuilder([
38+
'projectId' => $projectId,
39+
]);
40+
$bigQuery = $builder->bigQuery();
41+
// create the import job
42+
$file = fopen($source, 'r');
43+
while ($line = fgets($file)) {
44+
if (0 !== strpos(trim($line), 'INSERT')) {
45+
continue;
46+
}
47+
$bigQuery->runQuery($line, [
48+
'useLegacySql' => false,
49+
'defaultDataset' => ['datasetId' => $datasetId],
50+
]);
51+
}
52+
print('Data imported successfully' . PHP_EOL);
53+
}
54+
# [END insert_sql]

bigquery/api/test/ImportCommandTest.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,12 @@ public function testImport($source, $createTable = true)
252252
if ($createTable) {
253253
$this->createTempTable($this->projectId, $this->datasetId, $tableId);
254254
}
255+
if ('sql' === substr($source, -3)) {
256+
$contents = file_get_contents($source);
257+
$contents = str_replace('test_table', $tableId, $contents);
258+
$source = sprintf('%s/%s.sql', sys_get_temp_dir(), $tableId);
259+
file_put_contents($source, $contents);
260+
}
255261

256262
// run the import
257263
$application = new Application();
@@ -291,6 +297,7 @@ public function provideImport()
291297
return [
292298
[__DIR__ . '/data/test_data.csv'],
293299
[__DIR__ . '/data/test_data.json'],
300+
[__DIR__ . '/data/test_data.sql'],
294301
[sprintf('gs://%s/test_data.csv', $bucket)],
295302
[sprintf('gs://%s/test_data.json', $bucket)],
296303
[sprintf('gs://%s/test_data.backup_info', $bucket), false],
@@ -300,8 +307,8 @@ public function provideImport()
300307
private function createTempTable($projectId, $datasetId, $tableId)
301308
{
302309
$schema = [
303-
['name' => 'name', 'type' => 'string', 'mode' => 'required'],
304-
['name' => 'title', 'type' => 'string', 'mode' => 'required'],
310+
['name' => 'name', 'type' => 'string', 'mode' => 'nullable'],
311+
['name' => 'title', 'type' => 'string', 'mode' => 'nullable'],
305312
];
306313
$schemaJson = tempnam(sys_get_temp_dir(), 'schema-');
307314
file_put_contents($schemaJson, json_encode($schema));
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
-- This file is used to test ../../src/functions/import_from_file.php
2+
-- These are comments.
3+
-- Each query to be executed should be on a single line.
4+
5+
/* Another ignored line. */
6+
INSERT INTO `test_table` (`name`, `title`) VALUES ('Brent Shaffer', 'PHP Developer')
7+
INSERT INTO `test_table` (`name`, `title`) VALUES ('Takashi Matsuo', 'Developer\'s Liberation Activist')
8+
INSERT INTO `test_table` (`name`, `title`) VALUES ('Jeffrey Rennie', 'The Man, The Myth, The Legend')

0 commit comments

Comments
 (0)