Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 57 additions & 15 deletions cloud_sql/postgres/pdo/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,62 @@

## Before you begin

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/).
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`.
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.
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.
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.
5. Use the information noted in the previous steps:

## Running Locally

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).

To authenticate with Cloud SQL, set the `$GOOGLE_APPLICATION_CREDENTIALS` environment variable:

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

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.
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.

## Running Locally
```bash
export CLOUD_SQL_CONNECTION_NAME='<MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>'
```

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).
Once the proxy is ready, use one of the following commands to start the proxy in the background.

Once the proxy is ready, use the following command to start the proxy in the background:
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.

### Unix Socket mode

```bash
$ ./cloud_sql_proxy -dir=/cloudsql --instances=$CLOUD_SQL_CONNECTION_NAME --credential_file=$GOOGLE_APPLICATION_CREDENTIALS
$ ./cloud_sql_proxy -dir=/cloudsql \
--instances=$CLOUD_SQL_CONNECTION_NAME \
--credential_file=$GOOGLE_APPLICATION_CREDENTIALS
```

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.

### TCP mode

```bash
$ ./cloud_sql_proxy \
--instances=$CLOUD_SQL_CONNECTION_NAME=tcp:5432 \
--credential_file=$GOOGLE_APPLICATION_CREDENTIALS
```

### Set Configuration Values

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.

```bash
export DB_USER='my-db-user'
export DB_PASS='my-db-pass'
export DB_NAME='my-db-name'
export DB_HOSTNAME='127.0.0.1'
```

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.

Execute the following:

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

## Google App Engine Standard

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).
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).

First, update `app.standard.yaml` with the correct values to pass the environment variables into the runtime.

First, update `app.yaml` with the correct values to pass the environment variables into the runtime.
Next, the following command will deploy the application to your Google Cloud project:

```bash
$ gcloud app deploy app.standard.yaml
```

## Google App Engine Flex

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).

First, update `app.flex.yaml` with the correct values to pass the environment variables into the runtime.

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`.

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

```bash
$ gcloud app deploy
$ gcloud beta app deploy app.flex.yaml
```

32 changes: 32 additions & 0 deletions cloud_sql/postgres/pdo/app.flex.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

runtime: php
env: flex

# Remember - storing secrets in plaintext is potentially unsafe. Consider using
# something like https://cloud.google.com/secret-manager/ to help keep secrets
# secret.
env_variables:
CLOUD_SQL_CONNECTION_NAME: "<MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>"
DB_USER: my-db-user
DB_PASS: my-db-pass
DB_NAME: my-db

beta_settings:
cloud_sql_instances: "<MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>"

runtime_config:
document_root: .

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright 2018 Google LLC
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
Expand All @@ -15,12 +15,12 @@
runtime: php72

# Remember - storing secrets in plaintext is potentially unsafe. Consider using
# something like https://cloud.google.com/kms/ to help keep secrets secret.
# something like https://cloud.google.com/secret-manager/ to help keep secrets secret.
env_variables:
CLOUD_SQL_CONNECTION_NAME: <MY-PROJECT>:<INSTANCE-REGION>:<MY-DATABASE>
CLOUD_SQL_CONNECTION_NAME: <MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>
DB_USER: my-db-user
DB_PASS: my-db-pass
DB_NAME: my_db
DB_NAME: my-db

# Defaults to "serve index.php" and "serve public/index.php". Can be used to
# serve a custom PHP front controller (e.g. "serve backend/index.php") or to
Expand Down
21 changes: 21 additions & 0 deletions cloud_sql/postgres/pdo/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "google/cloud-sql-postgres-example",
"autoload": {
"psr-4": {
"Google\\Cloud\\Samples\\CloudSQL\\Postgres\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Google\\Cloud\\Samples\\CloudSQL\\Postgres\\Tests\\": "src"
}
},
"require": {
"php": ">= 7.2",
"slim/slim": "^4.5",
"slim/twig-view": "^3.1",
"slim/http": "^1.0",
"slim/psr7": "^1.0",
"pimple/pimple": "^3.3"
}
}
85 changes: 50 additions & 35 deletions cloud_sql/postgres/pdo/index.php
Original file line number Diff line number Diff line change
@@ -1,40 +1,55 @@
<?php
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

require_once 'src/DB.php';
require_once 'src/Votes.php';

use Google\Cloud\Samples\CloudSQL\Postgres\DB;
use Google\Cloud\Samples\CloudSQL\Postgres\Votes;

$votes = new Votes(DB::createPdoConnection());

if ($_SERVER['REQUEST_URI'] == '/' && $_SERVER['REQUEST_METHOD'] == 'GET') {
$list = $votes->list();

$vote_count = $votes->count_candidates();
$tab_count = $vote_count['tabs'];
$space_count = $vote_count['spaces'];

include_once("./template.php");
} elseif ($_SERVER['REQUEST_URI'] == '/' && $_SERVER['REQUEST_METHOD'] == 'POST') {
/*
* Copyright 2020 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

declare(strict_types=1);

use Slim\Psr7\Factory\StreamFactory;

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

$app = include __DIR__ . '/src/app.php';

$app->get('/', function ($request, $response) {
$this->get('votes')->createTableIfNotExists();

return $this->get('view')->render($response, 'template.twig', [
'votes' => $this->get('votes')->listVotes(),
'tabCount' => $this->get('votes')->getCountByValue('TABS'),
'spaceCount' => $this->get('votes')->getCountByValue('SPACES'),
]);
});

$app->post('/', function ($request, $response) {
$this->get('votes')->createTableIfNotExists();

$message = 'Invalid vote. Choose Between TABS and SPACES';

if (!empty($_POST['team']) && in_array($_POST['team'], ['SPACES', 'TABS'])) {
$message = $votes->save($_POST['team']);
$formData = $request->getParsedBody() + [
'voteValue' => ''
];

if (in_array($formData['voteValue'], ['SPACES', 'TABS'])) {
$message = $this->get('votes')->insertVote($formData['voteValue'])
? 'Vote cast for ' . $formData['voteValue']
: 'An error occurred';
}

echo $message;
}
$streamFactory = new StreamFactory;
return $response->withBody($streamFactory->createStream($message));
});

$app->run();
13 changes: 13 additions & 0 deletions cloud_sql/postgres/pdo/phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="../../../testing/bootstrap.php">
<testsuites>
<testsuite name="CloudSQLPostgresSample">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>
51 changes: 0 additions & 51 deletions cloud_sql/postgres/pdo/src/DB.php

This file was deleted.

Loading