Skip to content

Commit 39a13e2

Browse files
authored
Merge pull request GoogleCloudPlatform#1099 from jdpedrie/cloudsql/postgres
feat: refactor postgres sample to use slim app
2 parents ff6140f + 0ea3794 commit 39a13e2

File tree

11 files changed

+574
-182
lines changed

11 files changed

+574
-182
lines changed

cloud_sql/postgres/pdo/README.md

Lines changed: 57 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,35 +2,62 @@
22

33
## Before you begin
44

5-
1. Before you use this code sample, you need to have [Composer](https://getcomposer.org/) installed or downloaded into this folder. Download instructions can be found [here](https://getcomposer.org/download/).
5+
1. Before you use this code sample, you need to have [Composer](https://getcomposer.org/) installed or downloaded into this folder. Download instructions can be found [here](https://getcomposer.org/download/). Once you've installed composer, use it to install required dependencies by running `composer install`.
66
2. Create a PostgreSQL Cloud SQL Instance by following these [instructions](https://cloud.google.com/sql/docs/postgres/create-instance). Note the connection string, database user, and database password that you create.
77
3. Create a database for your application by following these [instructions](https://cloud.google.com/sql/docs/postgres/create-manage-databases). Note the database name.
88
4. Create a service account with the 'Cloud SQL Client' permissions by following these [instructions](https://cloud.google.com/sql/docs/postgres/connect-external-app#4_if_required_by_your_authentication_method_create_a_service_account). Download a JSON key to use to authenticate your connection.
9-
5. Use the information noted in the previous steps:
9+
10+
## Running Locally
11+
12+
To run this application locally, download and install the `cloud_sql_proxy` by following the instructions [here](https://cloud.google.com/sql/docs/postgres/sql-proxy#install).
13+
14+
To authenticate with Cloud SQL, set the `$GOOGLE_APPLICATION_CREDENTIALS` environment variable:
1015

1116
```bash
1217
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account/key.json
13-
export CLOUD_SQL_CONNECTION_NAME='<MY-PROJECT>:<INSTANCE-REGION>:<MY-DATABASE>'
14-
export DB_USER='my-db-user'
15-
export DB_PASS='my-db-pass'
16-
export DB_NAME='my-db-name'
17-
export DB_HOSTNAME='localhost' # If connecting using TCP instead of Unix Sockets
1818
```
1919

20-
Note: Saving credentials in environment variables is convenient, but not secure - consider a more secure solution such as [Cloud KMS](https://cloud.google.com/kms/) to help keep secrets safe.
20+
To run the Cloud SQL proxy, you need to set the instance connection name. See the instructions [here](https://cloud.google.com/sql/docs/postgres/quickstart-proxy-test#get_the_instance_connection_name) for finding the instance connection name.
2121

22-
## Running Locally
22+
```bash
23+
export CLOUD_SQL_CONNECTION_NAME='<MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>'
24+
```
2325

24-
To run this application locally, download and install the `cloud_sql_proxy` by following the instructions [here](https://cloud.google.com/sql/docs/postgres/sql-proxy#install).
26+
Once the proxy is ready, use one of the following commands to start the proxy in the background.
2527

26-
Once the proxy is ready, use the following command to start the proxy in the background:
28+
You may connect to your instance via either unix sockets or TCP. To connect using a socket, you must provide the `-dir` option when starting the proxy. To connect via TCP, you must provide a port as part of the instance name. Both are demonstrated below.
29+
30+
### Unix Socket mode
2731

2832
```bash
29-
$ ./cloud_sql_proxy -dir=/cloudsql --instances=$CLOUD_SQL_CONNECTION_NAME --credential_file=$GOOGLE_APPLICATION_CREDENTIALS
33+
$ ./cloud_sql_proxy -dir=/cloudsql \
34+
--instances=$CLOUD_SQL_CONNECTION_NAME \
35+
--credential_file=$GOOGLE_APPLICATION_CREDENTIALS
3036
```
3137

3238
Note: Make sure to run the command under a user with write access in the `/cloudsql` directory. This proxy will use this folder to create a unix socket the application will use to connect to Cloud SQL.
3339

40+
### TCP mode
41+
42+
```bash
43+
$ ./cloud_sql_proxy \
44+
--instances=$CLOUD_SQL_CONNECTION_NAME=tcp:5432 \
45+
--credential_file=$GOOGLE_APPLICATION_CREDENTIALS
46+
```
47+
48+
### Set Configuration Values
49+
50+
Set the required environment variables for your connection to Cloud SQL. If you are using Unix Socket mode as described above, do not set the DB_HOSTNAME variable.
51+
52+
```bash
53+
export DB_USER='my-db-user'
54+
export DB_PASS='my-db-pass'
55+
export DB_NAME='my-db-name'
56+
export DB_HOSTNAME='127.0.0.1'
57+
```
58+
59+
Note: Saving credentials in environment variables is convenient, but not secure - consider a more secure solution such as [Secret Manager](https://cloud.google.com/secret-manager/) to help keep secrets safe.
60+
3461
Execute the following:
3562

3663
```bash
@@ -41,12 +68,27 @@ Navigate towards http://localhost:8080 to verify your application is running cor
4168

4269
## Google App Engine Standard
4370

44-
To run on GAE-Standard, create an App Engine project by following the setup for these [instructions](https://cloud.google.com/appengine/docs/standard/php7/quickstart#before-you-begin).
71+
To run on App Engine Standard, create an App Engine project by following the setup for these [instructions](https://cloud.google.com/appengine/docs/standard/php7/quickstart#before-you-begin).
72+
73+
First, update `app.standard.yaml` with the correct values to pass the environment variables into the runtime.
4574

46-
First, update `app.yaml` with the correct values to pass the environment variables into the runtime.
75+
Next, the following command will deploy the application to your Google Cloud project:
76+
77+
```bash
78+
$ gcloud app deploy app.standard.yaml
79+
```
80+
81+
## Google App Engine Flex
82+
83+
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).
84+
85+
First, update `app.flex.yaml` with the correct values to pass the environment variables into the runtime.
86+
87+
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`.
4788

4889
Next, the following command will deploy the application to your Google Cloud project:
4990

5091
```bash
51-
$ gcloud app deploy
92+
$ gcloud beta app deploy app.flex.yaml
5293
```
94+
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Copyright 2020 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
runtime: php
16+
env: flex
17+
18+
# Remember - storing secrets in plaintext is potentially unsafe. Consider using
19+
# something like https://cloud.google.com/secret-manager/ to help keep secrets
20+
# secret.
21+
env_variables:
22+
CLOUD_SQL_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
26+
27+
beta_settings:
28+
cloud_sql_instances: "<MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>"
29+
30+
runtime_config:
31+
document_root: .
32+
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2018 Google LLC
1+
# Copyright 2020 Google LLC
22
#
33
# Licensed under the Apache License, Version 2.0 (the "License");
44
# you may not use this file except in compliance with the License.
@@ -15,12 +15,12 @@
1515
runtime: php72
1616

1717
# Remember - storing secrets in plaintext is potentially unsafe. Consider using
18-
# something like https://cloud.google.com/kms/ to help keep secrets secret.
18+
# something like https://cloud.google.com/secret-manager/ to help keep secrets secret.
1919
env_variables:
20-
CLOUD_SQL_CONNECTION_NAME: <MY-PROJECT>:<INSTANCE-REGION>:<MY-DATABASE>
20+
CLOUD_SQL_CONNECTION_NAME: <MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>
2121
DB_USER: my-db-user
2222
DB_PASS: my-db-pass
23-
DB_NAME: my_db
23+
DB_NAME: my-db
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
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"name": "google/cloud-sql-postgres-example",
3+
"autoload": {
4+
"psr-4": {
5+
"Google\\Cloud\\Samples\\CloudSQL\\Postgres\\": "src"
6+
}
7+
},
8+
"autoload-dev": {
9+
"psr-4": {
10+
"Google\\Cloud\\Samples\\CloudSQL\\Postgres\\Tests\\": "src"
11+
}
12+
},
13+
"require": {
14+
"php": ">= 7.2",
15+
"slim/slim": "^4.5",
16+
"slim/twig-view": "^3.1",
17+
"slim/http": "^1.0",
18+
"slim/psr7": "^1.0",
19+
"pimple/pimple": "^3.3"
20+
}
21+
}

cloud_sql/postgres/pdo/index.php

Lines changed: 50 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,55 @@
11
<?php
2-
# Copyright 2018 Google LLC
3-
#
4-
# Licensed under the Apache License, Version 2.0 (the "License");
5-
# you may not use this file except in compliance with the License.
6-
# You may obtain a copy of the License at
7-
#
8-
# http://www.apache.org/licenses/LICENSE-2.0
9-
#
10-
# Unless required by applicable law or agreed to in writing, software
11-
# distributed under the License is distributed on an "AS IS" BASIS,
12-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-
# See the License for the specific language governing permissions and
14-
# limitations under the License.
15-
16-
require_once 'src/DB.php';
17-
require_once 'src/Votes.php';
18-
19-
use Google\Cloud\Samples\CloudSQL\Postgres\DB;
20-
use Google\Cloud\Samples\CloudSQL\Postgres\Votes;
21-
22-
$votes = new Votes(DB::createPdoConnection());
23-
24-
if ($_SERVER['REQUEST_URI'] == '/' && $_SERVER['REQUEST_METHOD'] == 'GET') {
25-
$list = $votes->list();
26-
27-
$vote_count = $votes->count_candidates();
28-
$tab_count = $vote_count['tabs'];
29-
$space_count = $vote_count['spaces'];
30-
31-
include_once("./template.php");
32-
} elseif ($_SERVER['REQUEST_URI'] == '/' && $_SERVER['REQUEST_METHOD'] == 'POST') {
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+
use Slim\Psr7\Factory\StreamFactory;
21+
22+
include __DIR__ . '/vendor/autoload.php';
23+
24+
$app = include __DIR__ . '/src/app.php';
25+
26+
$app->get('/', function ($request, $response) {
27+
$this->get('votes')->createTableIfNotExists();
28+
29+
return $this->get('view')->render($response, 'template.twig', [
30+
'votes' => $this->get('votes')->listVotes(),
31+
'tabCount' => $this->get('votes')->getCountByValue('TABS'),
32+
'spaceCount' => $this->get('votes')->getCountByValue('SPACES'),
33+
]);
34+
});
35+
36+
$app->post('/', function ($request, $response) {
37+
$this->get('votes')->createTableIfNotExists();
38+
3339
$message = 'Invalid vote. Choose Between TABS and SPACES';
3440

35-
if (!empty($_POST['team']) && in_array($_POST['team'], ['SPACES', 'TABS'])) {
36-
$message = $votes->save($_POST['team']);
41+
$formData = $request->getParsedBody() + [
42+
'voteValue' => ''
43+
];
44+
45+
if (in_array($formData['voteValue'], ['SPACES', 'TABS'])) {
46+
$message = $this->get('votes')->insertVote($formData['voteValue'])
47+
? 'Vote cast for ' . $formData['voteValue']
48+
: 'An error occurred';
3749
}
3850

39-
echo $message;
40-
}
51+
$streamFactory = new StreamFactory;
52+
return $response->withBody($streamFactory->createStream($message));
53+
});
54+
55+
$app->run();
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<phpunit colors="true" bootstrap="../../../testing/bootstrap.php">
3+
<testsuites>
4+
<testsuite name="CloudSQLPostgresSample">
5+
<directory>tests</directory>
6+
</testsuite>
7+
</testsuites>
8+
<filter>
9+
<whitelist>
10+
<directory suffix=".php">src</directory>
11+
</whitelist>
12+
</filter>
13+
</phpunit>

cloud_sql/postgres/pdo/src/DB.php

Lines changed: 0 additions & 51 deletions
This file was deleted.

0 commit comments

Comments
 (0)