Skip to content

Commit 15b1681

Browse files
authored
Merge pull request GoogleCloudPlatform#1057 from jdpedrie/cloudsql/mysql
feat: add mysql sample
2 parents 034c4e6 + d7df732 commit 15b1681

File tree

11 files changed

+748
-0
lines changed

11 files changed

+748
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ credentials.*
1010
.php_cs.cache
1111
.vscode/
1212
.kokoro/secrets.sh
13+
.phpunit.result.cache

cloud_sql/mysql/pdo/README.md

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# Connection to Cloud SQL - MySQL
2+
3+
## Before you begin
4+
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`.
6+
2. Create a MySQL Cloud SQL Instance by following these [instructions](https://cloud.google.com/sql/docs/mysql/create-instance). Note the connection string, database user, and database password that you create.
7+
3. Create a database for your application by following these [instructions](https://cloud.google.com/sql/docs/mysql/create-manage-databases). Note the database name.
8+
4. Create a service account with the 'Cloud SQL Client' permissions by following these [instructions](https://cloud.google.com/sql/docs/mysql/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+
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/mysql/sql-proxy#install).
13+
14+
To authenticate with Cloud SQL, set the `$GOOGLE_APPLICATION_CREDENTIALS` environment variable:
15+
16+
```bash
17+
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account/key.json
18+
```
19+
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/mysql/quickstart-proxy-test#get_the_instance_connection_name) for finding the instance connection name.
21+
22+
```bash
23+
export CLOUD_SQL_CONNECTION_NAME='::'
24+
```
25+
26+
Once the proxy is ready, use one of the following commands to start the proxy in the background.
27+
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
31+
32+
```bash
33+
$ ./cloud_sql_proxy -dir=/cloudsql \
34+
--instances=$CLOUD_SQL_CONNECTION_NAME \
35+
--credential_file=$GOOGLE_APPLICATION_CREDENTIALS
36+
```
37+
38+
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.
39+
40+
### TCP mode
41+
42+
```bash
43+
$ ./cloud_sql_proxy \
44+
--instances=$CLOUD_SQL_CONNECTION_NAME=tcp:3306 \
45+
--credential_file=$GOOGLE_APPLICATION_CREDENTIALS
46+
```
47+
48+
### Set Configuration Values
49+
Set the required environment variables for your connection to Cloud SQL. If you are using TCP mode as described above, do not set the `CLOUD_SQL_CONNECTION_NAME` variable.
50+
51+
```bash
52+
export DB_USER='my-db-user'
53+
export DB_PASS='my-db-pass'
54+
export DB_NAME='my-db-name'
55+
export DB_HOSTNAME='localhost'
56+
```
57+
58+
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.
59+
60+
Execute the following:
61+
62+
```bash
63+
$ php -S localhost:8080
64+
```
65+
66+
Navigate towards http://localhost:8080 to verify your application is running correctly.
67+
68+
## Google App Engine Flex
69+
70+
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).
71+
72+
First, update `app.yaml` with the correct values to pass the environment variables into the runtime.
73+
74+
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`.
75+
76+
Next, the following command will deploy the application to your Google Cloud project:
77+
78+
```bash
79+
$ gcloud beta app deploy
80+
```
81+
82+
## Google App Engine Standard
83+
84+
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).
85+
86+
First, update `app.yaml` with the correct values to pass the environment variables into the runtime.
87+
88+
Next, the following command will deploy the application to your Google Cloud project:
89+
90+
```bash
91+
$ gcloud app deploy app-standard.yaml
92+
```

cloud_sql/mysql/pdo/app-standard.yaml

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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: php72
16+
17+
# Remember - storing secrets in plaintext is potentially unsafe. Consider using
18+
# something like https://cloud.google.com/secret-manager/ to help keep secrets secret.
19+
env_variables:
20+
CLOUD_SQL_CONNECTION_NAME: ::
21+
DB_USER: my-db-user
22+
DB_PASS: my-db-pass
23+
DB_NAME: my-db
24+
25+
# Defaults to "serve index.php" and "serve public/index.php". Can be used to
26+
# serve a custom PHP front controller (e.g. "serve backend/index.php") or to
27+
# run a long-running PHP script as a worker process (e.g. "php worker.php").
28+
#
29+
# entrypoint: serve index.php

cloud_sql/mysql/pdo/app.yaml

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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: "::"
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: "::"
29+
30+
runtime_config:
31+
document_root: .
32+
33+
# Defaults to "serve index.php" and "serve public/index.php". Can be used to
34+
# serve a custom PHP front controller (e.g. "serve backend/index.php") or to
35+
# run a long-running PHP script as a worker process (e.g. "php worker.php").
36+
#
37+
# entrypoint: serve index.php

cloud_sql/mysql/pdo/composer.json

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
{
2+
"name": "google/cloud-sql-mysql-example",
3+
"autoload": {
4+
"psr-4": {
5+
"Google\\Cloud\\Samples\\CloudSQL\\MySQL\\": "src"
6+
}
7+
},
8+
"autoload-dev": {
9+
"psr-4": {
10+
"Google\\Cloud\\Samples\\CloudSQL\\MySQL\\Tests\\": "src"
11+
}
12+
},
13+
"require": {
14+
"php": ">= 7.2",
15+
"slim/slim": "^4.5",
16+
"slim/twig-view": "^3.1",
17+
"pimple/pimple": "^3.3",
18+
"guzzlehttp/psr7": "^1.6",
19+
"http-interop/http-factory-guzzle": "^1.0"
20+
},
21+
"require-dev": {
22+
"phpunit/phpunit": "^8.5"
23+
}
24+
}

cloud_sql/mysql/pdo/index.php

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
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 GuzzleHttp\Psr7;
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+
39+
$message = 'Invalid vote. Choose Between TABS and SPACES';
40+
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';
49+
}
50+
51+
return $response->withBody(Psr7\stream_for($message));
52+
});
53+
54+
$app->run();

cloud_sql/mysql/pdo/phpunit.xml.dist

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">
3+
<testsuites>
4+
<testsuite name="CloudSQLMySQLSample">
5+
<directory>testsdirectory>
6+
testsuite>
7+
testsuites>
8+
<filter>
9+
<whitelist>
10+
<directory suffix=".php">srcdirectory>
11+
whitelist>
12+
filter>
13+
phpunit>

cloud_sql/mysql/pdo/src/Votes.php

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
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+
namespace Google\Cloud\Samples\CloudSQL\MySQL;
21+
22+
use PDO;
23+
use PDOException;
24+
use RuntimeException;
25+
26+
/**
27+
* Manage votes using the Cloud SQL database.
28+
*/
29+
class Votes
30+
{
31+
/**
32+
* @var PDO
33+
*/
34+
private $connection;
35+
36+
/**
37+
* @param PDO $connection A connection to the database.
38+
*/
39+
public function __construct(PDO $connection)
40+
{
41+
$this->connection = $connection;
42+
}
43+
44+
/**
45+
* Creates the table if it does not yet exist.
46+
*
47+
* @return void
48+
*/
49+
public function createTableIfNotExists()
50+
{
51+
try {
52+
$stmt = $this->connection->prepare('SELECT 1 FROM votes');
53+
$stmt->execute();
54+
} catch (PDOException $e) {
55+
$sql = "CREATE TABLE votes (
56+
vote_id INT NOT NULL AUTO_INCREMENT,
57+
time_cast DATETIME NOT NULL,
58+
vote_value VARCHAR(6) NOT NULL,
59+
PRIMARY KEY (vote_id)
60+
);";
61+
62+
$this->connection->exec($sql);
63+
}
64+
}
65+
66+
/**
67+
* Returns a list of the last five votes
68+
*
69+
* @return array
70+
*/
71+
public function listVotes() : array
72+
{
73+
$sql = "SELECT vote_value, time_cast FROM votes ORDER BY time_cast DESC LIMIT 5";
74+
$statement = $this->connection->prepare($sql);
75+
$statement->execute();
76+
return $statement->fetchAll(PDO::FETCH_ASSOC);
77+
}
78+
79+
/**
80+
* Get the number of votes cast for a given value.
81+
*
82+
* @param string $value
83+
* @param int
84+
*/
85+
public function getCountByValue(string $value) : int
86+
{
87+
$sql = "SELECT COUNT(vote_id) as voteCount FROM votes WHERE vote_value = ?";
88+
89+
$statement = $this->connection->prepare($sql);
90+
$statement->execute([$value]);
91+
92+
return (int) $statement->fetch(PDO::FETCH_COLUMN);
93+
}
94+
95+
/**
96+
* Insert a new vote into the database
97+
*
98+
* @param string $value The value to vote for.
99+
* @return boolean
100+
*/
101+
public function insertVote(string $value) : bool
102+
{
103+
$conn = $this->connection;
104+
$res = false;
105+
106+
# [START cloud_sql_mysql_pdo_connection]
107+
// Use prepared statements to guard against SQL injection.
108+
$sql = "INSERT INTO votes (time_cast, vote_value) VALUES (NOW(), :voteValue)";
109+
110+
try {
111+
$statement = $conn->prepare($sql);
112+
$statement->bindParam('voteValue', $value);
113+
114+
$res = $statement->execute();
115+
} catch (PDOException $e) {
116+
throw new RuntimeException(
117+
"Could not insert vote into database. The PDO exception was " .
118+
$e->getMessage(),
119+
$e->getCode(),
120+
$e
121+
);
122+
}
123+
# [END cloud_sql_mysql_pdo_connection]
124+
125+
return $res;
126+
}
127+
}

0 commit comments

Comments
 (0)