Skip to content

Commit 906d56f

Browse files
authored
Added integration tests for Cloud SQL (GoogleCloudPlatform#1251)
1 parent 932d488 commit 906d56f

21 files changed

+761
-319
lines changed

.kokoro/secrets.sh.enc

256 Bytes
Binary file not shown.

cloud_sql/mysql/pdo/composer.json

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,12 @@
55
"Google\\Cloud\\Samples\\CloudSQL\\MySQL\\": "src"
66
}
77
},
8-
"autoload-dev": {
9-
"psr-4": {
10-
"Google\\Cloud\\Samples\\CloudSQL\\MySQL\\Tests\\": "src"
11-
}
12-
},
138
"require": {
149
"php": ">= 7.2",
1510
"slim/slim": "^4.5",
1611
"slim/twig-view": "^3.1",
1712
"pimple/pimple": "^3.3",
1813
"guzzlehttp/psr7": "^1.6",
1914
"http-interop/http-factory-guzzle": "^1.0"
20-
},
21-
"require-dev": {
22-
"phpunit/phpunit": "^8.5"
2315
}
2416
}

cloud_sql/mysql/pdo/phpunit.xml.dist

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
xml version="1.0" encoding="UTF-8"?>
2-
<phpunit colors="true">
2+
<phpunit colors="true" bootstrap="../../../testing/bootstrap.php">
33
<testsuites>
44
<testsuite name="CloudSQLMySQLSample">
55
<directory>testsdirectory>
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
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+
class DBInitializer
27+
{
28+
29+
/**
30+
* @param $username string username of the database user
31+
* @param $password string password of the database user
32+
* @param $dbName string name of the target database
33+
* @param $dbHost string IP address or domain of the target database
34+
* @param $connConfig array driver-specific options for PDO
35+
*/
36+
public static function initTcpDatabaseConnection(
37+
string $username,
38+
string $password,
39+
string $dbName,
40+
string $dbHost,
41+
array $connConfig
42+
): PDO {
43+
try {
44+
# [START cloud_sql_mysql_pdo_create_tcp]
45+
// $username = 'your_db_user';
46+
// $password = 'yoursupersecretpassword';
47+
// $dbName = 'your_db_name';
48+
// $dbHost = "127.0.0.1";
49+
50+
// Connect using TCP
51+
$dsn = sprintf('mysql:dbname=%s;host=%s', $dbName, $dbHost);
52+
53+
// Connect to the database
54+
$conn = new PDO($dsn, $username, $password, $connConfig);
55+
# [END cloud_sql_mysql_pdo_create_tcp]
56+
} catch (TypeError $e) {
57+
throw new RuntimeException(
58+
sprintf(
59+
'Invalid or missing configuration! Make sure you have set ' .
60+
'$username, $password, $dbName, and $dbHost (for TCP mode) ' .
61+
'or $connectionName (for UNIX socket mode). ' .
62+
'The PHP error was %s',
63+
$e->getMessage()
64+
),
65+
$e->getCode(),
66+
$e
67+
);
68+
} catch (PDOException $e) {
69+
throw new RuntimeException(
70+
sprintf(
71+
'Could not connect to the Cloud SQL Database. Check that ' .
72+
'your username and password are correct, that the Cloud SQL ' .
73+
'proxy is running, and that the database exists and is ready ' .
74+
'for use. For more assistance, refer to %s. The PDO error was %s',
75+
'https://cloud.google.com/sql/docs/mysql/connect-external-app',
76+
$e->getMessage()
77+
),
78+
$e->getCode(),
79+
$e
80+
);
81+
}
82+
83+
return $conn;
84+
}
85+
86+
/**
87+
* @param $username string username of the database user
88+
* @param $password string password of the database user
89+
* @param $dbName string name of the target database
90+
* @param $connectionName string Cloud SQL instance name
91+
* @param $socketDir string Full path to unix socket
92+
* @param $conn_config array driver-specific options for PDO
93+
*/
94+
public static function initUnixDatabaseConnection(
95+
string $username,
96+
string $password,
97+
string $dbName,
98+
string $connectionName,
99+
string $socketDir,
100+
array $conn_config
101+
): PDO {
102+
try {
103+
# [START cloud_sql_mysql_pdo_create_socket]
104+
// $username = 'your_db_user';
105+
// $password = 'yoursupersecretpassword';
106+
// $dbName = 'your_db_name';
107+
// $connectionName = getenv("CLOUD_SQL_CONNECTION_NAME");
108+
// $socketDir = getenv('DB_SOCKET_DIR') ?: '/cloudsql';
109+
110+
// Connect using UNIX sockets
111+
$dsn = sprintf(
112+
'mysql:dbname=%s;unix_socket=%s/%s',
113+
$dbName,
114+
$socketDir,
115+
$connectionName
116+
);
117+
118+
// Connect to the database.
119+
$conn = new PDO($dsn, $username, $password, $conn_config);
120+
# [END cloud_sql_mysql_pdo_create_socket]
121+
} catch (TypeError $e) {
122+
throw new RuntimeException(
123+
sprintf(
124+
'Invalid or missing configuration! Make sure you have set ' .
125+
'$username, $password, $dbName, and $dbHost (for TCP mode) ' .
126+
'or $connectionName (for UNIX socket mode). ' .
127+
'The PHP error was %s',
128+
$e->getMessage()
129+
),
130+
$e->getCode(),
131+
$e
132+
);
133+
} catch (PDOException $e) {
134+
throw new RuntimeException(
135+
sprintf(
136+
'Could not connect to the Cloud SQL Database. Check that ' .
137+
'your username and password are correct, that the Cloud SQL ' .
138+
'proxy is running, and that the database exists and is ready ' .
139+
'for use. For more assistance, refer to %s. The PDO error was %s',
140+
'https://cloud.google.com/sql/docs/mysql/connect-external-app',
141+
$e->getMessage()
142+
),
143+
$e->getCode(),
144+
$e
145+
);
146+
}
147+
148+
return $conn;
149+
}
150+
}

cloud_sql/mysql/pdo/src/Votes.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ public function createTableIfNotExists()
5555
$sql = "CREATE TABLE votes (
5656
vote_id INT NOT NULL AUTO_INCREMENT,
5757
time_cast DATETIME NOT NULL,
58-
vote_value VARCHAR(6) NOT NULL,
58+
candidate VARCHAR(6) NOT NULL,
5959
PRIMARY KEY (vote_id)
6060
);";
6161

@@ -70,7 +70,7 @@ public function createTableIfNotExists()
7070
*/
7171
public function listVotes(): array
7272
{
73-
$sql = "SELECT vote_value, time_cast FROM votes ORDER BY time_cast DESC LIMIT 5";
73+
$sql = "SELECT candidate, time_cast FROM votes ORDER BY time_cast DESC LIMIT 5";
7474
$statement = $this->connection->prepare($sql);
7575
$statement->execute();
7676
return $statement->fetchAll(PDO::FETCH_ASSOC);
@@ -84,7 +84,7 @@ public function listVotes(): array
8484
*/
8585
public function getCountByValue(string $value): int
8686
{
87-
$sql = "SELECT COUNT(vote_id) as voteCount FROM votes WHERE vote_value = ?";
87+
$sql = "SELECT COUNT(vote_id) as voteCount FROM votes WHERE candidate = ?";
8888

8989
$statement = $this->connection->prepare($sql);
9090
$statement->execute([$value]);
@@ -105,7 +105,7 @@ public function insertVote(string $value): bool
105105

106106
# [START cloud_sql_mysql_pdo_connection]
107107
// Use prepared statements to guard against SQL injection.
108-
$sql = "INSERT INTO votes (time_cast, vote_value) VALUES (NOW(), :voteValue)";
108+
$sql = "INSERT INTO votes (time_cast, candidate) VALUES (NOW(), :voteValue)";
109109

110110
try {
111111
$statement = $conn->prepare($sql);

cloud_sql/mysql/pdo/src/app.php

Lines changed: 29 additions & 112 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
declare(strict_types=1);
1919

20+
use Google\Cloud\Samples\CloudSQL\MySQL\DBInitializer;
2021
use Google\Cloud\Samples\CloudSQL\MySQL\Votes;
2122
use Pimple\Container;
2223
use Pimple\Psr11\Container as Psr11Container;
@@ -38,131 +39,47 @@
3839
# [START cloud_sql_mysql_pdo_timeout]
3940
// Here we set the connection timeout to five seconds and ask PDO to
4041
// throw an exception if any errors occur.
41-
$conn_config = [
42+
$connConfig = [
4243
PDO::ATTR_TIMEOUT => 5,
4344
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
4445
];
4546
# [END cloud_sql_mysql_pdo_timeout]
4647

47-
if (empty(getenv('DB_HOST'))) {
48-
return init_unix_database_connection($conn_config);
49-
} else {
50-
return init_tcp_database_connection($conn_config);
51-
}
52-
};
53-
54-
/**
55-
* @param $conn_config array driver-specific options for PDO
56-
*/
57-
function init_tcp_database_connection(array $conn_config): PDO
58-
{
5948
$username = getenv('DB_USER');
6049
$password = getenv('DB_PASS');
61-
$db_name = getenv('DB_NAME');
62-
$host = getenv('DB_HOST');
63-
64-
try {
65-
# [START cloud_sql_mysql_pdo_create_tcp]
66-
// // $username = 'your_db_user';
67-
// // $password = 'yoursupersecretpassword';
68-
// // $db_name = 'your_db_name';
69-
// // $host = "127.0.0.1";
50+
$dbName = getenv('DB_NAME');
7051

71-
// Connect using TCP
72-
$dsn = sprintf('mysql:dbname=%s;host=%s', $db_name, $host);
73-
74-
// Connect to the database.
75-
$conn = new PDO($dsn, $username, $password, $conn_config);
76-
# [END cloud_sql_mysql_pdo_create_tcp]
77-
} catch (TypeError $e) {
78-
throw new RuntimeException(
79-
sprintf(
80-
'Invalid or missing configuration! Make sure you have set ' .
81-
'$username, $password, $db_name, and $host (for TCP mode) ' .
82-
'or $cloud_sql_connection_name (for UNIX socket mode). ' .
83-
'The PHP error was %s',
84-
$e->getMessage()
85-
),
86-
$e->getCode(),
87-
$e
88-
);
89-
} catch (PDOException $e) {
90-
throw new RuntimeException(
91-
sprintf(
92-
'TCP Could not connect to the Cloud SQL Database. Check that ' .
93-
'your username and password are correct, that the Cloud SQL ' .
94-
'proxy is running, and that the database exists and is ready ' .
95-
'for use. For more assistance, refer to %s. The PDO error was %s',
96-
'https://cloud.google.com/sql/docs/mysql/connect-external-app',
97-
$e->getMessage()
98-
),
99-
$e->getCode(),
100-
$e
101-
);
52+
if (empty($username = getenv('DB_USER'))) {
53+
throw new RuntimeException('Must supply $DB_USER environment variables');
54+
}
55+
if (empty($password = getenv('DB_PASS'))) {
56+
throw new RuntimeException('Must supply $DB_PASS environment variables');
57+
}
58+
if (empty($dbName = getenv('DB_NAME'))) {
59+
throw new RuntimeException('Must supply $DB_NAME environment variables');
10260
}
10361

104-
return $conn;
105-
}
106-
107-
/**
108-
* @param $conn_config array driver-specific options for PDO
109-
*/
110-
function init_unix_database_connection(array $conn_config): PDO
111-
{
112-
$username = getenv('DB_USER');
113-
$password = getenv('DB_PASS');
114-
$db_name = getenv('DB_NAME');
115-
$cloud_sql_connection_name = getenv('CLOUD_SQL_CONNECTION_NAME');
116-
$socket_dir = getenv('DB_SOCKET_DIR') ?: '/cloudsql';
117-
118-
try {
119-
// # [START cloud_sql_mysql_pdo_create_socket]
120-
// // $username = 'your_db_user';
121-
// // $password = 'yoursupersecretpassword';
122-
// // $db_name = 'your_db_name';
123-
// // $cloud_sql_connection_name = getenv("CLOUD_SQL_CONNECTION_NAME");
124-
// // $socket_dir = getenv('DB_SOCKET_DIR') ?: '/cloudsql';
125-
126-
// Connect using UNIX sockets
127-
$dsn = sprintf(
128-
'mysql:dbname=%s;unix_socket=%s/%s',
129-
$db_name,
130-
$socket_dir,
131-
$cloud_sql_connection_name
132-
);
133-
134-
// Connect to the database.
135-
$conn = new PDO($dsn, $username, $password, $conn_config);
136-
# [END cloud_sql_mysql_pdo_create_socket]
137-
} catch (TypeError $e) {
138-
throw new RuntimeException(
139-
sprintf(
140-
'Invalid or missing configuration! Make sure you have set ' .
141-
'$username, $password, $db_name, and $host (for TCP mode) ' .
142-
'or $cloud_sql_connection_name (for UNIX socket mode). ' .
143-
'The PHP error was %s',
144-
$e->getMessage()
145-
),
146-
$e->getCode(),
147-
$e
62+
if ($dbHost = getenv('DB_HOST')) {
63+
return DBInitializer::initTcpDatabaseConnection(
64+
$username,
65+
$password,
66+
$dbName,
67+
$dbHost,
68+
$connConfig
14869
);
149-
} catch (PDOException $e) {
150-
throw new RuntimeException(
151-
sprintf(
152-
'Could not connect to the Cloud SQL Database. Check that ' .
153-
'your username and password are correct, that the Cloud SQL ' .
154-
'proxy is running, and that the database exists and is ready ' .
155-
'for use. For more assistance, refer to %s. The PDO error was %s',
156-
'https://cloud.google.com/sql/docs/mysql/connect-external-app',
157-
$e->getMessage()
158-
),
159-
$e->getCode(),
160-
$e
70+
} else {
71+
$connectionName = getenv('CLOUDSQL_CONNECTION_NAME');
72+
$socketDir = getenv('DB_SOCKET_DIR') ?: '/cloudsql';
73+
return DBInitializer::initUnixDatabaseConnection(
74+
$username,
75+
$password,
76+
$dbName,
77+
$connectionName,
78+
$socketDir,
79+
$connConfig
16180
);
16281
}
163-
164-
return $conn;
165-
}
82+
};
16683

16784
// Configure the templating engine.
16885
$container['view'] = function () {

0 commit comments

Comments
 (0)