Skip to content

Commit 39ad5b0

Browse files
authored
feat(cloud_sql/sqlserver): update to V2 sample (GoogleCloudPlatform#1636)
1 parent de7a67b commit 39ad5b0

File tree

8 files changed

+145
-148
lines changed

8 files changed

+145
-148
lines changed

cloud_sql/sqlserver/pdo/README.md

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@ To authenticate with Cloud SQL, set the `$GOOGLE_APPLICATION_CREDENTIALS` enviro
1818
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account/key.json
1919
```
2020

21-
To run the Cloud SQL proxy, you need to set the instance connection name. See the instructions [here](https://cloud.google.com/sql/docs/sqlserver/quickstart-proxy-test#get_the_instance_connection_name) for finding the instance connection name.
21+
To run the Cloud SQL proxy, you need to set the instance connection name. See the instructions [here](https://cloud.google.com/sql/docs/sqlserver/connect-instance-auth-proxy#get-connection-name) for finding the instance connection name.
2222

2323
```bash
24-
export INSTANCE_CONNECTION_NAME='<MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>'
24+
export INSTANCE_CONNECTION_NAME='<PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE-NAME>'
2525
```
2626

2727
Once the proxy is ready, use one of the following commands to start the proxy in the background.
@@ -39,9 +39,9 @@ $ ./cloud_sql_proxy \
3939
Set the required environment variables for your connection to Cloud SQL.
4040

4141
```bash
42-
export DB_USER='my-db-user'
43-
export DB_PASS='my-db-pass'
44-
export DB_NAME='my-db-name'
42+
export DB_USER='<DB_USER_NAME>'
43+
export DB_PASS='<DB_PASSWORD>'
44+
export DB_NAME='<DB_NAME>'
4545
export DB_HOST='127.0.0.1'
4646
```
4747

@@ -59,11 +59,17 @@ Navigate towards http://localhost:8080 to verify your application is running cor
5959

6060
To run on App Engine Flex, create an App Engine project by following the setup for these [instructions](https://cloud.google.com/appengine/docs/standard/php7/quickstart#before-you-begin).
6161

62-
First, update `app.yaml` with the correct values to pass the environment variables into the runtime.
62+
First, update [app.yaml](app.yaml) with the correct values to pass the environment variables into the runtime.
6363

6464
In order to use the `sqlsrv` extension, you will need to build a [custom runtime](https://cloud.google.com/appengine/docs/flexible/custom-runtimes/quickstart). The `Dockerfile` in this sample contains a simple example of a custom PHP 7.2 runtime based off of the default App Engine Flex image with the `pdo_sqlsrv` extension installed.
6565

66-
Then, make sure that the service account `service-{PROJECT_NUMBER}>@gae-api-prod.google.com.iam.gserviceaccount.com` has the IAM role `Cloud SQL Client`.
66+
Then, make sure that the App Engine default service account
67+
`<PROJECT-ID>@appspot.gserviceaccount.com` has
68+
the IAM role `Cloud SQL Client`.
69+
70+
Also, make sure that the Cloud Build service account
71+
`cloudbuild@<PROJECT-ID>.iam.gserviceaccount.com` has
72+
the IAM role `Cloud SQL Client`.
6773

6874
Next, the following command will deploy the application to your Google Cloud project:
6975

cloud_sql/sqlserver/pdo/app.yaml

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,16 @@ env: flex
1919
# something like https://cloud.google.com/secret-manager/ to help keep secrets
2020
# secret.
2121
env_variables:
22-
DB_USER: my-db-user
23-
DB_PASS: my-db-pass
24-
DB_NAME: my-db
25-
DB_HOST: 172.17.0.1
22+
DB_USER: <YOUR_DB_USER_NAME>
23+
DB_PASS: <YOUR_DB_PASSWORD>
24+
DB_NAME: <YOUR_DB_NAME>
25+
INSTANCE_HOST: 172.17.0.1
2626

2727
beta_settings:
2828
# The connection name of your instance, available by using
2929
# 'gcloud beta sql instances describe [INSTANCE_NAME]' or from
3030
# the Instance details page in the Google Cloud Platform Console.
31-
cloud_sql_instances: <MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE_NAME>=tcp:1433
31+
cloud_sql_instances: <PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE_NAME>=tcp:1433
3232

3333
# Defaults to "serve index.php" and "serve public/index.php". Can be used to
3434
# serve a custom PHP front controller (e.g. "serve backend/index.php") or to

cloud_sql/sqlserver/pdo/composer.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@
1010
"ext-pdo_sqlsrv": "*",
1111
"slim/slim": "^4.5",
1212
"slim/twig-view": "^3.1",
13-
"pimple/pimple": "^3.3",
14-
"guzzlehttp/psr7": "^2.0",
15-
"http-interop/http-factory-guzzle": "^1.0"
13+
"slim/http": "^1.0",
14+
"slim/psr7": "^1.0",
15+
"pimple/pimple": "^3.3"
1616
}
1717
}

cloud_sql/sqlserver/pdo/index.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
declare(strict_types=1);
1919

20-
use GuzzleHttp\Psr7;
20+
use Slim\Psr7\Factory\StreamFactory;
2121

2222
include __DIR__ . '/vendor/autoload.php';
2323

@@ -48,7 +48,8 @@
4848
: 'An error occurred';
4949
}
5050

51-
return $response->withBody(Psr7\stream_for($message));
51+
$streamFactory = new StreamFactory;
52+
return $response->withBody($streamFactory->createStream($message));
5253
});
5354

5455
$app->run();

cloud_sql/sqlserver/pdo/src/DBInitializer.php

Lines changed: 0 additions & 84 deletions
This file was deleted.
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
<?php
2+
/*
3+
* Copyright 2020 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+
declare(strict_types=1);
19+
20+
# [START cloud_sql_sqlserver_pdo_connect_tcp]
21+
namespace Google\Cloud\Samples\CloudSQL\SQLServer;
22+
23+
use PDO;
24+
use PDOException;
25+
use RuntimeException;
26+
use TypeError;
27+
28+
class DatabaseTcp
29+
{
30+
public static function initTcpDatabaseConnection(): PDO
31+
{
32+
try {
33+
// Note: Saving credentials in environment variables is convenient, but not
34+
// secure - consider a more secure solution such as
35+
// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
36+
// keep secrets safe.
37+
$username = getenv('DB_USER'); // e.g. 'your_db_user'
38+
$password = getenv('DB_PASS'); // e.g. 'your_db_password'
39+
$dbName = getenv('DB_NAME'); // e.g. 'your_db_name'
40+
$instanceHost = getenv('INSTANCE_HOST'); // e.g. '127.0.0.1' ('172.17.0.1' for GAE Flex)
41+
42+
// Connect using TCP
43+
$dsn = sprintf(
44+
'sqlsrv:server=%s;Database=%s',
45+
$instanceHost,
46+
$dbName
47+
);
48+
49+
// Connect to the database
50+
$conn = new PDO(
51+
$dsn,
52+
$username,
53+
$password,
54+
# [START_EXCLUDE]
55+
# [START cloud_sql_sqlserver_pdo_timeout]
56+
// Here we set the connection timeout to five seconds and ask PDO to
57+
// throw an exception if any errors occur.
58+
[
59+
PDO::ATTR_TIMEOUT => 5,
60+
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
61+
]
62+
# [END cloud_sql_sqlserver_pdo_timeout]
63+
# [END_EXCLUDE]
64+
);
65+
} catch (TypeError $e) {
66+
throw new RuntimeException(
67+
sprintf(
68+
'Invalid or missing configuration! Make sure you have set ' .
69+
'$username, $password, $dbName, and $instanceHost (for TCP mode). ' .
70+
'The PHP error was %s',
71+
$e->getMessage()
72+
),
73+
$e->getCode(),
74+
$e
75+
);
76+
} catch (PDOException $e) {
77+
throw new RuntimeException(
78+
sprintf(
79+
'Could not connect to the Cloud SQL Database. Check that ' .
80+
'your username and password are correct, that the Cloud SQL ' .
81+
'proxy is running, and that the database exists and is ready ' .
82+
'for use. For more assistance, refer to %s. The PDO error was %s',
83+
'https://cloud.google.com/sql/docs/sqlserver/connect-external-app',
84+
$e->getMessage()
85+
),
86+
(int) $e->getCode(),
87+
$e
88+
);
89+
}
90+
91+
return $conn;
92+
}
93+
}
94+
# [END cloud_sql_sqlserver_pdo_connect_tcp]

cloud_sql/sqlserver/pdo/src/app.php

Lines changed: 13 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
declare(strict_types=1);
1919

20-
use Google\Cloud\Samples\CloudSQL\SQLServer\DBInitializer;
20+
use Google\Cloud\Samples\CloudSQL\SQLServer\DatabaseTcp;
2121
use Google\Cloud\Samples\CloudSQL\SQLServer\Votes;
2222
use Pimple\Container;
2323
use Pimple\Psr11\Container as Psr11Container;
@@ -26,7 +26,7 @@
2626
use Slim\Views\TwigMiddleware;
2727

2828
// Create and set the dependency injection container.
29-
$container = new Container;
29+
$container = new Container();
3030
AppFactory::setContainer(new Psr11Container($container));
3131

3232
// add the votes manager to the container.
@@ -36,40 +36,22 @@
3636

3737
// Setup the database connection in the container.
3838
$container['db'] = function () {
39-
# [START cloud_sql_sqlserver_pdo_timeout]
40-
// Here we set the connection timeout to five seconds and ask PDO to
41-
// throw an exception if any errors occur.
42-
$connConfig = [
43-
PDO::ATTR_TIMEOUT => 5,
44-
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
45-
];
46-
# [END cloud_sql_sqlserver_pdo_timeout]
47-
48-
$username = getenv('DB_USER');
49-
$password = getenv('DB_PASS');
50-
$dbName = getenv('DB_NAME');
51-
$dbHost = getenv('DB_HOST');
52-
53-
if (empty($username = getenv('DB_USER'))) {
54-
throw new RuntimeException('Must supply $DB_USER environment variables');
39+
if (getenv('DB_USER') === false) {
40+
throw new RuntimeException('Must supply $DB_USER environment variable');
5541
}
56-
if (empty($password = getenv('DB_PASS'))) {
57-
throw new RuntimeException('Must supply $DB_PASS environment variables');
42+
if (getenv('DB_PASS') === false) {
43+
throw new RuntimeException('Must supply $DB_PASS environment variable');
5844
}
59-
if (empty($dbName = getenv('DB_NAME'))) {
60-
throw new RuntimeException('Must supply $DB_NAME environment variables');
45+
if (getenv('DB_NAME') === false) {
46+
throw new RuntimeException('Must supply $DB_NAME environment variable');
6147
}
62-
if (empty($dbHost = getenv('DB_HOST'))) {
63-
throw new RuntimeException('Must supply $DB_HOST environment variables');
48+
if (getenv('INSTANCE_HOST') === false) {
49+
throw new RuntimeException(
50+
'Must supply $INSTANCE_HOST environment variable'
51+
);
6452
}
6553

66-
return DBInitializer::initTcpDatabaseConnection(
67-
$username,
68-
$password,
69-
$dbName,
70-
$dbHost,
71-
$connConfig
72-
);
54+
return DatabaseTcp::initTcpDatabaseConnection();
7355
};
7456

7557
// Configure the templating engine.

0 commit comments

Comments
 (0)