Skip to content

Commit ea68c93

Browse files
authored
feat(cloud_sql/postgres): update to V2 sample (GoogleCloudPlatform#1633)
1 parent 39ad5b0 commit ea68c93

File tree

8 files changed

+265
-252
lines changed

8 files changed

+265
-252
lines changed

cloud_sql/postgres/pdo/README.md

Lines changed: 21 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ Instructions are provided below for using the proxy with a TCP connection or a
2828
Unix domain socket. On Linux or macOS, you can use either option, but the
2929
Windows proxy requires a TCP connection.
3030

31-
### Unix Socket mode
31+
### Launch proxy with Unix Domain Socket
3232

3333
NOTE: this option is currently only supported on Linux and macOS. Windows users
3434
should use the TCP option.
@@ -37,22 +37,16 @@ To use a Unix socket, you'll need to create a directory and give access to the
3737
user running the proxy:
3838

3939
```bash
40-
sudo mkdir /path/to/the/new/directory
41-
sudo chown -R $USER /path/to/the/new/directory
40+
sudo mkdir /cloudsql
41+
sudo chown -R $USER /cloudsql
4242
```
4343

44-
You'll also need to initialize an environment variable pointing to the directory
45-
you just created:
46-
47-
```bash
48-
export DB_SOCKET_DIR=/path/to/the/new/directory
49-
```
50-
51-
Use these terminal commands to initialize other environment variables as well:
44+
Use these terminal commands to initialize environment variables:
5245

5346
```bash
5447
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account/key.json
55-
export INSTANCE_CONNECTION_NAME='<MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>'
48+
export INSTANCE_CONNECTION_NAME='<PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE-NAME>'
49+
export INSTANCE_UNIX_SOCKET='/cloudsql/<PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE-NAME>'
5650
export DB_USER='<DB_USER_NAME>'
5751
export DB_PASS='<DB_PASSWORD>'
5852
export DB_NAME='<DB_NAME>'
@@ -66,22 +60,22 @@ safe.
6660
Then use the following command to launch the proxy in the background:
6761

6862
```bash
69-
./cloud_sql_proxy -dir=$DB_SOCKET_DIR --instances=$INSTANCE_CONNECTION_NAME --credential_file=$GOOGLE_APPLICATION_CREDENTIALS &
63+
./cloud_sql_proxy -dir=/cloudsql --instances=$INSTANCE_CONNECTION_NAME --credential_file=$GOOGLE_APPLICATION_CREDENTIALS &
7064
```
7165

72-
### TCP mode
66+
### Launch proxy with TCP
7367

7468
To run the sample locally with a TCP connection, set environment variables and
7569
launch the proxy as shown below.
7670

77-
#### Linux / macOS
71+
#### Linux / Mac OS
7872

7973
Use these terminal commands to initialize environment variables:
8074

8175
```bash
8276
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account/key.json
83-
export INSTANCE_CONNECTION_NAME='<MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>'
84-
export DB_HOST='127.0.0.1'
77+
export INSTANCE_CONNECTION_NAME='<PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE-NAME>'
78+
export INSTANCE_HOST='127.0.0.1'
8579
export DB_USER='<DB_USER_NAME>'
8680
export DB_PASS='<DB_PASSWORD>'
8781
export DB_NAME='<DB_NAME>'
@@ -104,7 +98,7 @@ Use these PowerShell commands to initialize environment variables:
10498

10599
```bash
106100
$env:GOOGLE_APPLICATION_CREDENTIALS="<CREDENTIALS_JSON_FILE>"
107-
$env:DB_HOST="127.0.0.1"
101+
$env:INSTANCE_HOST="127.0.0.1"
108102
$env:DB_USER="<DB_USER_NAME>"
109103
$env:DB_PASS="<DB_PASSWORD>"
110104
$env:DB_NAME="<DB_NAME>
@@ -141,7 +135,7 @@ To run on App Engine Standard, create an App Engine project by following the
141135
setup for these
142136
[instructions](https://cloud.google.com/appengine/docs/standard/php7/quickstart#before-you-begin).
143137
144-
First, update `app.standard.yaml` with the correct values to pass the
138+
First, update [app.standard.yaml](app.standard.yaml) with the correct values to pass the
145139
environment variables into the runtime.
146140
147141
Next, the following command will deploy the application to your Google Cloud
@@ -156,17 +150,21 @@ To run on App Engine Flex, create an App Engine project by following the setup
156150
for these
157151
[instructions](https://cloud.google.com/appengine/docs/standard/php7/quickstart#before-you-begin).
158152
159-
First, update `app.flex.yaml` with the correct values to pass the environment
153+
First, update [app.flex.yaml](app.flex.yaml) with the correct values to pass the environment
160154
variables into the runtime.
161155
162156
To use a TCP connection instead of a Unix socket to connect your sample to your
163-
Cloud SQL instance on App Engine, make sure to uncomment the `DB_HOST`
157+
Cloud SQL instance on App Engine, make sure to uncomment the `INSTANCE_HOST`
164158
field under `env_variables`. Also make sure to remove the uncommented
165159
`beta_settings` and `cloud_sql_instances` fields and replace them with the
166160
commented `beta_settings` and `cloud_sql_instances` fields.
167161
168-
Then, make sure that the service account
169-
`service-{PROJECT_NUMBER}>@gae-api-prod.google.com.iam.gserviceaccount.com` has
162+
Then, make sure that the App Engine default service account
163+
`<PROJECT-ID>@appspot.gserviceaccount.com` has
164+
the IAM role `Cloud SQL Client`.
165+
166+
Also, make sure that the Cloud Build service account
167+
`cloudbuild@<PROJECT-ID>.iam.gserviceaccount.com` has
170168
the IAM role `Cloud SQL Client`.
171169
172170
Next, the following command will deploy the application to your Google Cloud

cloud_sql/postgres/pdo/app.flex.yaml

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,23 +19,23 @@ env: flex
1919
# something like https://cloud.google.com/secret-manager/ to help keep secrets
2020
# secret.
2121
env_variables:
22-
INSTANCE_CONNECTION_NAME: "<MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>"
23-
DB_USER: my-db-user
24-
DB_PASS: my-db-pass
25-
DB_NAME: my-db
22+
INSTANCE_UNIX_SOCKET: /cloudsql/<PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE-NAME>
23+
DB_USER: <YOUR_DB_USER_NAME>
24+
DB_PASS: <YOUR_DB_PASSWORD>
25+
DB_NAME: <YOUR_DB_NAME>
2626

2727
# TCP domain socket setup; uncomment if using a TCP domain socket
28-
# DB_HOST: 172.17.0.1
28+
# INSTANCE_HOST: 172.17.0.1
2929

3030
# Choose to enable either a TCP or Unix domain socket for your database
3131
# connection:
3232
# Enable a Unix domain socket:
3333
beta_settings:
34-
cloud_sql_instances: "<MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>"
34+
cloud_sql_instances: "<PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE-NAME>"
3535

3636
# Enable a TCP domain socket:
3737
# beta_settings:
38-
# cloud_sql_instances: <MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>=tcp:5432
38+
# cloud_sql_instances: <PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE-NAME>=tcp:5432
3939

4040
runtime_config:
4141
document_root: .

cloud_sql/postgres/pdo/app.standard.yaml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@ runtime: php74
1717
# Remember - storing secrets in plaintext is potentially unsafe. Consider using
1818
# something like https://cloud.google.com/secret-manager/ to help keep secrets secret.
1919
env_variables:
20-
INSTANCE_CONNECTION_NAME: <MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>
21-
DB_USER: my-db-user
22-
DB_PASS: my-db-pass
23-
DB_NAME: my-db
20+
INSTANCE_UNIX_SOCKET: /cloudsql/<PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE-NAME>
21+
DB_USER: <YOUR_DB_USER_NAME>
22+
DB_PASS: <YOUR_DB_PASSWORD>
23+
DB_NAME: <YOUR_DB_NAME>
2424

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

cloud_sql/postgres/pdo/src/DBInitializer.php

Lines changed: 0 additions & 151 deletions
This file was deleted.
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
<?php
2+
/*
3+
* Copyright 2022 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_postgres_pdo_connect_tcp]
21+
namespace Google\Cloud\Samples\CloudSQL\Postgres;
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('pgsql:dbname=%s;host=%s', $dbName, $instanceHost);
44+
45+
// Connect to the database
46+
$conn = new PDO(
47+
$dsn,
48+
$username,
49+
$password,
50+
# [START_EXCLUDE]
51+
# [START cloud_sql_postgres_pdo_timeout]
52+
// Here we set the connection timeout to five seconds and ask PDO to
53+
// throw an exception if any errors occur.
54+
[
55+
PDO::ATTR_TIMEOUT => 5,
56+
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
57+
]
58+
# [END cloud_sql_postgres_pdo_timeout]
59+
# [END_EXCLUDE]
60+
);
61+
} catch (TypeError $e) {
62+
throw new RuntimeException(
63+
sprintf(
64+
'Invalid or missing configuration! Make sure you have set ' .
65+
'$username, $password, $dbName, and $instanceHost (for TCP mode). ' .
66+
'The PHP error was %s',
67+
$e->getMessage()
68+
),
69+
$e->getCode(),
70+
$e
71+
);
72+
} catch (PDOException $e) {
73+
throw new RuntimeException(
74+
sprintf(
75+
'Could not connect to the Cloud SQL Database. Check that ' .
76+
'your username and password are correct, that the Cloud SQL ' .
77+
'proxy is running, and that the database exists and is ready ' .
78+
'for use. For more assistance, refer to %s. The PDO error was %s',
79+
'https://cloud.google.com/sql/docs/postgres/connect-external-app',
80+
$e->getMessage()
81+
),
82+
$e->getCode(),
83+
$e
84+
);
85+
}
86+
87+
return $conn;
88+
}
89+
}
90+
# [END cloud_sql_postgres_pdo_connect_tcp]

0 commit comments

Comments
 (0)