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
20 changes: 13 additions & 7 deletions cloud_sql/sqlserver/pdo/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ To authenticate with Cloud SQL, set the `$GOOGLE_APPLICATION_CREDENTIALS` enviro
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account/key.json
```

To run the Cloud SQL proxy, you need to set the instance connection name. See the instructions [here](https://cloud.google.com/sql/docs/sqlserver/quickstart-proxy-test#get_the_instance_connection_name) for finding the instance connection name.
To run the Cloud SQL proxy, you need to set the instance connection name. See the instructions [here](https://cloud.google.com/sql/docs/sqlserver/connect-instance-auth-proxy#get-connection-name) for finding the instance connection name.

```bash
export INSTANCE_CONNECTION_NAME='<MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME>'
export INSTANCE_CONNECTION_NAME='<PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE-NAME>'
```

Once the proxy is ready, use one of the following commands to start the proxy in the background.
Expand All @@ -39,9 +39,9 @@ $ ./cloud_sql_proxy \
Set the required environment variables for your connection to Cloud SQL.

```bash
export DB_USER='my-db-user'
export DB_PASS='my-db-pass'
export DB_NAME='my-db-name'
export DB_USER='<DB_USER_NAME>'
export DB_PASS='<DB_PASSWORD>'
export DB_NAME='<DB_NAME>'
export DB_HOST='127.0.0.1'
```

Expand All @@ -59,11 +59,17 @@ Navigate towards http://localhost:8080 to verify your application is running cor

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.yaml` with the correct values to pass the environment variables into the runtime.
First, update [app.yaml](app.yaml) with the correct values to pass the environment variables into the runtime.

In order to use the `sqlsrv` extension, you will need to build a [custom runtime](https://cloud.google.com/appengine/docs/flexible/custom-runtimes/quickstart). The `Dockerfile` in this sample contains a simple example of a custom PHP 7.2 runtime based off of the default App Engine Flex image with the `pdo_sqlsrv` extension installed.

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`.
Then, make sure that the App Engine default service account
`<PROJECT-ID>@appspot.gserviceaccount.com` has
the IAM role `Cloud SQL Client`.

Also, make sure that the Cloud Build service account
`cloudbuild@<PROJECT-ID>.iam.gserviceaccount.com` has
the IAM role `Cloud SQL Client`.

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

Expand Down
10 changes: 5 additions & 5 deletions cloud_sql/sqlserver/pdo/app.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,16 @@ env: flex
# something like https://cloud.google.com/secret-manager/ to help keep secrets
# secret.
env_variables:
DB_USER: my-db-user
DB_PASS: my-db-pass
DB_NAME: my-db
DB_HOST: 172.17.0.1
DB_USER: <YOUR_DB_USER_NAME>
DB_PASS: <YOUR_DB_PASSWORD>
DB_NAME: <YOUR_DB_NAME>
INSTANCE_HOST: 172.17.0.1

beta_settings:
# The connection name of your instance, available by using
# 'gcloud beta sql instances describe [INSTANCE_NAME]' or from
# the Instance details page in the Google Cloud Platform Console.
cloud_sql_instances: <MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE_NAME>=tcp:1433
cloud_sql_instances: <PROJECT-ID>:<INSTANCE-REGION>:<INSTANCE_NAME>=tcp:1433

# 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
6 changes: 3 additions & 3 deletions cloud_sql/sqlserver/pdo/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
"ext-pdo_sqlsrv": "*",
"slim/slim": "^4.5",
"slim/twig-view": "^3.1",
"pimple/pimple": "^3.3",
"guzzlehttp/psr7": "^2.0",
"http-interop/http-factory-guzzle": "^1.0"
"slim/http": "^1.0",
"slim/psr7": "^1.0",
"pimple/pimple": "^3.3"
}
}
5 changes: 3 additions & 2 deletions cloud_sql/sqlserver/pdo/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

declare(strict_types=1);

use GuzzleHttp\Psr7;
use Slim\Psr7\Factory\StreamFactory;

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

Expand Down Expand Up @@ -48,7 +48,8 @@
: 'An error occurred';
}

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

$app->run();
84 changes: 0 additions & 84 deletions cloud_sql/sqlserver/pdo/src/DBInitializer.php

This file was deleted.

94 changes: 94 additions & 0 deletions cloud_sql/sqlserver/pdo/src/DatabaseTcp.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php
/*
* 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);

# [START cloud_sql_sqlserver_pdo_connect_tcp]
namespace Google\Cloud\Samples\CloudSQL\SQLServer;

use PDO;
use PDOException;
use RuntimeException;
use TypeError;

class DatabaseTcp
{
public static function initTcpDatabaseConnection(): PDO
{
try {
// Note: Saving credentials in environment variables is convenient, but not
// secure - consider a more secure solution such as
// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
// keep secrets safe.
$username = getenv('DB_USER'); // e.g. 'your_db_user'
$password = getenv('DB_PASS'); // e.g. 'your_db_password'
$dbName = getenv('DB_NAME'); // e.g. 'your_db_name'
$instanceHost = getenv('INSTANCE_HOST'); // e.g. '127.0.0.1' ('172.17.0.1' for GAE Flex)

// Connect using TCP
$dsn = sprintf(
'sqlsrv:server=%s;Database=%s',
$instanceHost,
$dbName
);

// Connect to the database
$conn = new PDO(
$dsn,
$username,
$password,
# [START_EXCLUDE]
# [START cloud_sql_sqlserver_pdo_timeout]
// Here we set the connection timeout to five seconds and ask PDO to
// throw an exception if any errors occur.
[
PDO::ATTR_TIMEOUT => 5,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]
# [END cloud_sql_sqlserver_pdo_timeout]
# [END_EXCLUDE]
);
} catch (TypeError $e) {
throw new RuntimeException(
sprintf(
'Invalid or missing configuration! Make sure you have set ' .
'$username, $password, $dbName, and $instanceHost (for TCP mode). ' .
'The PHP error was %s',
$e->getMessage()
),
$e->getCode(),
$e
);
} catch (PDOException $e) {
throw new RuntimeException(
sprintf(
'Could not connect to the Cloud SQL Database. Check that ' .
'your username and password are correct, that the Cloud SQL ' .
'proxy is running, and that the database exists and is ready ' .
'for use. For more assistance, refer to %s. The PDO error was %s',
'https://cloud.google.com/sql/docs/sqlserver/connect-external-app',
$e->getMessage()
),
(int) $e->getCode(),
$e
);
}

return $conn;
}
}
# [END cloud_sql_sqlserver_pdo_connect_tcp]
44 changes: 13 additions & 31 deletions cloud_sql/sqlserver/pdo/src/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

declare(strict_types=1);

use Google\Cloud\Samples\CloudSQL\SQLServer\DBInitializer;
use Google\Cloud\Samples\CloudSQL\SQLServer\DatabaseTcp;
use Google\Cloud\Samples\CloudSQL\SQLServer\Votes;
use Pimple\Container;
use Pimple\Psr11\Container as Psr11Container;
Expand All @@ -26,7 +26,7 @@
use Slim\Views\TwigMiddleware;

// Create and set the dependency injection container.
$container = new Container;
$container = new Container();
AppFactory::setContainer(new Psr11Container($container));

// add the votes manager to the container.
Expand All @@ -36,40 +36,22 @@

// Setup the database connection in the container.
$container['db'] = function () {
# [START cloud_sql_sqlserver_pdo_timeout]
// Here we set the connection timeout to five seconds and ask PDO to
// throw an exception if any errors occur.
$connConfig = [
PDO::ATTR_TIMEOUT => 5,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
];
# [END cloud_sql_sqlserver_pdo_timeout]

$username = getenv('DB_USER');
$password = getenv('DB_PASS');
$dbName = getenv('DB_NAME');
$dbHost = getenv('DB_HOST');

if (empty($username = getenv('DB_USER'))) {
throw new RuntimeException('Must supply $DB_USER environment variables');
if (getenv('DB_USER') === false) {
throw new RuntimeException('Must supply $DB_USER environment variable');
}
if (empty($password = getenv('DB_PASS'))) {
throw new RuntimeException('Must supply $DB_PASS environment variables');
if (getenv('DB_PASS') === false) {
throw new RuntimeException('Must supply $DB_PASS environment variable');
}
if (empty($dbName = getenv('DB_NAME'))) {
throw new RuntimeException('Must supply $DB_NAME environment variables');
if (getenv('DB_NAME') === false) {
throw new RuntimeException('Must supply $DB_NAME environment variable');
}
if (empty($dbHost = getenv('DB_HOST'))) {
throw new RuntimeException('Must supply $DB_HOST environment variables');
if (getenv('INSTANCE_HOST') === false) {
throw new RuntimeException(
'Must supply $INSTANCE_HOST environment variable'
);
}

return DBInitializer::initTcpDatabaseConnection(
$username,
$password,
$dbName,
$dbHost,
$connConfig
);
return DatabaseTcp::initTcpDatabaseConnection();
};

// Configure the templating engine.
Expand Down
Loading