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
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ Before you can run or deploy the sample, you will need to do the following:

$ mysql -h 127.0.0.1 -u root -p -e "CREATE DATABASE <YOUR_DATABASE_NAME>;"


## Deploy to App Engine

**Prerequisites**
Expand Down Expand Up @@ -70,19 +69,19 @@ in your browser.
installed and running.

1. Set the following environment variables with the configuration values for
`USER`, `PASSWORD`, and `DATABASE` you used during setup:
`USER`, `PASSWORD`, `DATABASE`, and `CONNECTION_NAME` you used during setup:

```sh
# set local mysql connection parameters
export MYSQL_DSN="mysql:host=127.0.0.1;port=3306;dbname=DATABASE"
export MYSQL_USERNAME=USER
export MYSQL_USER=USER
export MYSQL_PASSWORD=PASSWORD
```

1. Run the application

```sh
cd php-docs-samples/appengine/standard/cloudsql
cd php-docs-samples/appengine/flexible/cloudsql
php -S localhost:8080
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,19 @@
// create the Silex application
$app = new Application();

$app['pdo'] = function ($app) {
$pdo = new PDO(
$app['mysql.dsn'],
$app['mysql.user'],
$app['mysql.password']
);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->query('CREATE TABLE IF NOT EXISTS visits ' .
'(time_stamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, user_ip CHAR(64))');
return $pdo;
};
// Create the PDO object for CloudSQL MySQL.
$dsn = getenv('MYSQL_DSN');
$user = getenv('MYSQL_USER');
$password = getenv('MYSQL_PASSWORD');
$pdo = new PDO($dsn, $user, $password);

// Create the database if it doesn't exist
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->query('CREATE TABLE IF NOT EXISTS visits ' .
'(time_stamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, user_ip CHAR(64))');

// Add the PDO object to our Silex application.
$app['pdo'] = $pdo;

$app->get('/', function (Application $app, Request $request) {
$ip = $request->GetClientIp();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ env: flex
env_variables:
# Replace USER, PASSWORD, DATABASE, and CONNECTION_NAME with the
# values obtained when configuring your Cloud SQL instance.
MYSQL_DSN: mysql:dbname=DATABASE;unix_socket=/cloudsql/CONNECTION_NAME
MYSQL_USER: USER
MYSQL_PASSWORD: PASSWORD
MYSQL_DSN: mysql:dbname=DATABASE;unix_socket=/cloudsql/CONNECTION_NAME
#[END env]

#[START cloudsql_settings]
# Use the connection name obtained when configuring your Cloud SQL instance.
beta_settings:
cloud_sql_instances: "CONNECTION_NAME"
#[END cloudsql_settings]
#[END cloudsql_settings]
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,4 @@
// Run the app!
// use "gcloud app deploy"
$app['debug'] = true;
$app['mysql.dsn'] = getenv('MYSQL_DSN');
$app['mysql.user'] = getenv('MYSQL_USER');
$app['mysql.password'] = getenv('MYSQL_PASSWORD');
$app->run();
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,26 @@ public function testIndex()
$this->assertContains("Last 10 visits:", (string) $resp->getBody());
}

public function beforeDeploy()
public static function beforeDeploy()
{
$tmpDir = FileUtil::cloneDirectoryIntoTmp(__DIR__ . '/..');
self::$gcloudWrapper->setDir($tmpDir);
chdir($tmpDir);

$connectionName = getenv('CLOUDSQL_CONNECTION_NAME');
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't actually run the DeployTest on travis, these are run from Jenkins. But that being said, we still want to rename these. nice job!

$connectionName = getenv('CLOUDSQL_CONNECTION_NAME_MYSQL');
$user = getenv('MYSQL_USER');
$database = getenv('MYSQL_DATABASE');
$password = getenv('MYSQL_PASSWORD');

$appYaml = Yaml::parse(file_get_contents('app.yaml'));
$appYamlContents = file_get_contents('app.yaml');

$appYaml = Yaml::parse($appYamlContents);
$appYaml['env_variables']['MYSQL_USER'] = $user;
$appYaml['env_variables']['MYSQL_PASSWORD'] = $password;
$appYaml['beta_settings']['cloud_sql_instances'] = $connectionName;
$appYaml['env_variables']['MYSQL_DSN'] = str_replace(
['DATABASE', 'CONNECTION_NAME'],
['cloud_samples_tests_php', $connectionName],
[$database, $connectionName],
$appYaml['env_variables']['MYSQL_DSN']
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,9 @@ public function setUp()
public function createApplication()
{
$app = require __DIR__ . '/../app.php';
$app['mysql.dsn'] = getenv('MYSQL_DSN');
$app['mysql.user'] = getenv('MYSQL_USER');
$app['mysql.password'] = getenv('MYSQL_PASSWORD');
if ($app['mysql.dsn'] === false ||
$app['mysql.user'] === false ||
$app['mysql.password'] === false) {
if (getenv('MYSQL_DSN') === false ||
getenv('MYSQL_USER') === false ||
getenv('MYSQL_PASSWORD') === false) {
$this->markTestSkipped('set the MYSQL_DSN, MYSQL_USER and MYSQL_PASSWORD environment variables');
}
return $app;
Expand Down
89 changes: 89 additions & 0 deletions appengine/flexible/cloudsql-postgres/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Cloud SQL & Google App Engine Flexible Environment

This sample application demonstrates how to use [Cloud SQL with Google App Engine Flexible Environment](https://cloud.google.com/appengine/docs/flexible/php/using-cloud-sql).

## Setup

Before running this sample:

## Prerequisites

- Install [`composer`](https://getcomposer.org)
- Install dependencies by running:

```sh
composer install
```

## Setup

Before you can run or deploy the sample, you will need to do the following:

1. Create a [Second Generation Cloud SQL](https://cloud.google.com/sql/docs/create-instance) instance. You can do this from the [Cloud Console](https://console.developers.google.com) or via the [Cloud SDK](https://cloud.google.com/sdk). To create it via the SDK use the following command:

$ gcloud beta sql instances create YOUR_INSTANCE_NAME --tier=db-f1-micro --activation-policy=ALWAYS

> Note: the `--tier` option is required to create a `Second Generation` instance. See the
full list of available tiers by running `gcloud sql tiers list`

2. Set the root password on your Cloud SQL instance:

$ gcloud sql instances set-root-password YOUR_INSTANCE_NAME --password YOUR_INSTANCE_ROOT_PASSWORD

3. Install and run the [CloudSQL Proxy](https://cloud.google.com/sql/docs/mysql-connect-proxy)

4. Create a database for this example

$ mysql -h 127.0.0.1 -u root -p -e "CREATE DATABASE <YOUR_DATABASE_NAME>;"

## Deploy to App Engine

**Prerequisites**

- Install the [Google Cloud SDK](https://developers.google.com/cloud/sdk/).

**Deploy with gcloud**

1. Update `app.yaml` with the configuration values for `USER`, `PASSWORD`, and
`DATABASE` with the values you used during setup.

1. Get the CloudSQL connection name

$ gcloud beta sql instances describe YOUR_INSTANCE_NAME | grep connectionName

1. Update `app.yaml` with the configuration value for `CONNECTION_NAME` you retrieved
at the end up setup.

```
gcloud config set project YOUR_PROJECT_ID
gcloud app deploy
gcloud app browse
```

The last command will open `https://{YOUR_PROJECT_ID}.appspot.com/`
in your browser.

## Run locally

1. Ensure the [CloudSQL Proxy](https://cloud.google.com/sql/docs/external#proxy) is
installed and running.

1. Set the following environment variables with the configuration values for
`USER`, `PASSWORD`, `DATABASE`, and `CONNECTION_NAME` you used during setup:

```sh
# set local mysql connection parameters
export POSTGRES_DSN="pgsql:host=127.0.0.1;port=5432;dbname=DATABASE"
export POSTGRES_USER=USER
export POSTGRES_PASSWORD=PASSWORD
```

1. Run the application

```sh
cd php-docs-samples/appengine/flexible/cloudsql
php -S localhost:8080
```

Now you can view the app running at [http://localhost:8080](http://localhost:8080)
in your browser.
76 changes: 76 additions & 0 deletions appengine/flexible/cloudsql-postgres/app.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php
/**
* Copyright 2016 Google Inc.
*
* 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.
*/

# [START example]
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

// create the Silex application
$app = new Application();

// Create the PDO object for CloudSQL Postgres.
$dsn = getenv('POSTGRES_DSN');
$user = getenv('POSTGRES_USER');
$password = getenv('POSTGRES_PASSWORD');
$pdo = new PDO($dsn, $user, $password);

// Create the database if it doesn't exist
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->query('CREATE TABLE IF NOT EXISTS visits ' .
'(time_stamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, user_ip CHAR(64))');

// Add the PDO object to our Silex application.
$app['pdo'] = $pdo;

$app->get('/', function (Application $app, Request $request) {
$ip = $request->GetClientIp();
// Keep only the first two octets of the IP address.
$octets = explode($separator = ':', $ip);
if (count($octets) < 2) { // Must be ip4 address
$octets = explode($separator = '.', $ip);
}
if (count($octets) < 2) {
$octets = ['bad', 'ip']; // IP address will be recorded as bad.ip.
}
// Replace empty chunks with zeros.
$octets = array_map(function ($x) {
return $x == '' ? '0' : $x;
}, $octets);
$user_ip = $octets[0] . $separator . $octets[1];

// Insert a visit into the database.
/** @var PDO $pdo */
$pdo = $app['pdo'];
$insert = $pdo->prepare('INSERT INTO visits (user_ip) values (:user_ip)');
$insert->execute(['user_ip' => $user_ip]);

// Look up the last 10 visits
$select = $pdo->prepare(
'SELECT * FROM visits ORDER BY time_stamp DESC LIMIT 10');
$select->execute();
$visits = ["Last 10 visits:"];
while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
array_push($visits, sprintf('Time: %s Addr: %s', $row['time_stamp'],
$row['user_ip']));
}
return new Response(implode("\n", $visits), 200,
['Content-Type' => 'text/plain']);
});
# [END example]

return $app;
17 changes: 17 additions & 0 deletions appengine/flexible/cloudsql-postgres/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
runtime: php
env: flex

#[START env]
env_variables:
# Replace USER, PASSWORD, DATABASE, and CONNECTION_NAME with the
# values obtained when configuring your Cloud SQL instance.
POSTGRES_USER: USER
POSTGRES_PASSWORD: PASSWORD
POSTGRES_DSN: pgsql:dbname=DATABASE;host=/cloudsql/CONNECTION_NAME
#[END env]

#[START cloudsql_settings]
# Use the connection name obtained when configuring your Cloud SQL instance.
beta_settings:
cloud_sql_instances: "CONNECTION_NAME"
#[END cloudsql_settings]
11 changes: 11 additions & 0 deletions appengine/flexible/cloudsql-postgres/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"require": {
"silex/silex": "^1.3",
"google/apiclient": "^2.0"
},
"require-dev": {
"google/cloud-tools": "^0.6",
"paragonie/random_compat": "^2.0",
"phpunit/phpunit": "~4"
}
}
Loading