Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
17 changes: 17 additions & 0 deletions cloudsql/postgresql/.gcloudignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# This file specifies files that are *not* uploaded to Google Cloud Platform
# using gcloud. It follows the same syntax as .gitignore, with the addition of
# "#!include" directives (which insert the entries of the given .gitignore-style
# file at that point).
#
# For more information, run:
# $ gcloud topic gcloudignore
#
.gcloudignore
# If you would like to upload your .git directory, .gitignore file or files
# from your .gitignore file, remove the corresponding line
# below:
.git
.gitignore

# Node.js dependencies:
node_modules/
113 changes: 113 additions & 0 deletions cloudsql/postgresql/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# Connecting to Cloud SQL - PostgreSQL

## Before you begin

1. If you haven't already, set up a Node.js Development Environment (including google-cloud-sdk, Node Version Manager (NVM) and Node Package Manager (NPM)) by following the [Node.js setup guide](https://cloud.google.com/nodejs/docs/setup).

2. Create or select a GCP project in the GCP Console and then ensure that project includes an App Engine application and billing is enabled:

[Go to APP ENGINE](https://console.cloud.google.com/projectselector/appengine/create?lang=nodejs)

3. Enable the Cloud SQL API.

[ENABLE the API](https://console.cloud.google.com/flows/enableapi?apiid=sqladmin&redirect=https://console.cloud.google.com)

4. If you haven't yet downloaded and initialized the Google Cloud SDK:

[DOWNLOAD the SDK](https://cloud.google.com/sdk/docs/)


## Configuring the Cloud SQL instance

1. Create a Cloud SQL for PostgreSQL instance by following these
[instructions](https://cloud.google.com/sql/docs/postgres/create-instance). Note the instance name that you create,
and password that you specify for the default 'postgres' user.

* If you don't want to use the default user to connect, [create a user](https://cloud.google.com/sql/docs/postgres/create-manage-users#creating).

1. Run the following gcloud command and record the connection name for the instance:

`gcloud sql instances describe [INSTANCE_NAME]`

For example the connection name should look something like:

`connectionName: project1:us-central1:instance1`

1. Create a database for your application using the following gcloud command:

`gcloud sql databases create [DATABASE_NAME] --instance=[INSTANCE_NAME]`

## Creating a Service Account

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

2. Run the following command to create an environment variable referencing
the location of the JSON key downloading in the previous step:

`export GOOGLE_APPLICATION_CREDENTIALS=$HOME/[YOUR-JSON-KEY-FILENAME]`


## Install and run the Cloud SQL proxy

1. Install the Cloud SQL proxy by following the instructions:
in the [Cloud SQL proxy quickstart](https://cloud.google.com/sql/docs/postgres/quickstart-proxy-test).


## Setting connection strings and adding a library

1. Set up the local environment to support connections for local testing.

For this sample app, you should run the following commands:

```
export SQL_USER=[YOUR_SQL_USER]
export SQL_PASSWORD=[YOUR_SQL_PASSWORD]
export SQL_DATABASE=[YOUR_SQL_DATABASE]
npm install
```
By default, when you run the app locally it tries to connect using TCP sockets. If you configured the proxy to use Unix sockets, set this additional environment variable:

`export INSTANCE_CONNECTION_NAME=[YOUR_INSTANCE_CONNECTION_NAME]`

2. To allow your app to connect to your Cloud SQL instance when the app is deployed, add the user, password, database, and instance connection name variables from Cloud SQL to the related environment variables in the `app.standard.yaml` file. The deployed application will connect via unix sockets.

```
env_variables:
SQL_USER: YOUR_SQL_USER
SQL_PASSWORD: YOUR_SQL_PASSWORD
SQL_DATABASE: YOUR_SQL_DATABASE
# e.g. my-awesome-project:us-central1:my-cloud-sql-instance
INSTANCE_CONNECTION_NAME: YOUR_INSTANCE_CONNECTION_NAME
```

## Create a table for the sample app

Run `createTable.js` to create the table you need and to ensure that the database is properly configured.
With the cloudsql proxy running, run the following command to create the sample app's table in your Cloud SQL PostgreSQL database:

1. Run createTable.js with the following command:
`node createTable.js `

## Deploying locally

To run this application locally:

1. Start the Cloud SQL proxy so that it is running locally.

2. In a separate terminal window run the following command:

`npm start`

Navigate towards `http://127.0.0.1:8080` to verify your application is running correctly.

## Deploy to Google App Engine Standard

1. After local testing, deploy your app to App Engine:

`gcloud app deploy app.standard.yaml`

2. To launch your browser and view the app at http://[YOUR_PROJECT_ID].appspot.com, run the following command:

`gcloud app browse`
32 changes: 32 additions & 0 deletions cloudsql/postgresql/app.flexible.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Copyright 2017, 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.

runtime: nodejs
env: flex

# [START gae_flex_postgres_env]
# The following env variables may contain sensitive information that grants
# anyone access to your database. Do not add this file to your source control.
env_variables:
SQL_USER: YOUR_SQL_USER
SQL_PASSWORD: YOUR_SQL_PASSWORD
SQL_DATABASE: YOUR_SQL_DATABASE
# e.g. my-awesome-project:us-central1:my-cloud-sql-instance
INSTANCE_CONNECTION_NAME: YOUR_INSTANCE_CONNECTION_NAME
# [END gae_flex_postgres_env]

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: YOUR_INSTANCE_CONNECTION_NAME
31 changes: 31 additions & 0 deletions cloudsql/postgresql/app.standard.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Copyright 2017, 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.

runtime: nodejs8

# [START gae_postgres_env]
# The following env variables may contain sensitive information that grants
# anyone access to your database. Do not add this file to your source control.
env_variables:
SQL_USER: YOUR_SQL_USER
SQL_PASSWORD: YOUR_SQL_PASSWORD
SQL_DATABASE: YOUR_SQL_DATABASE
# e.g. my-awesome-project:us-central1:my-cloud-sql-instance
INSTANCE_CONNECTION_NAME: YOUR_INSTANCE_CONNECTION_NAME
# [END gae_postgres_env]

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: YOUR_INSTANCE_CONNECTION_NAME
52 changes: 52 additions & 0 deletions cloudsql/postgresql/createTable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* Copyright 2018, 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.
*/

'use strict';

const Knex = require('knex');
const prompt = require('prompt');

const FIELDS = ['user', 'password', 'database'];

prompt.start();

// Prompt the user for connection details
prompt.get(FIELDS, (err, config) => {
if (err) {
console.error(err);
return;
}

// Connect to the database
const knex = Knex({client: 'pg', connection: config});

// Create the "votes" table
knex.schema
.createTable('votes', table => {
table.bigIncrements('vote_id').notNull();
table.timestamp('time_cast').notNull();
table.specificType('candidate', 'CHAR(6) NOT NULL');
})
.then(() => {
console.log(`Successfully created 'votes' table.`);
return knex.destroy();
})
.catch(err => {
console.error(`Failed to create 'votes' table:`, err);
if (knex) {
knex.destroy();
}
});
});
81 changes: 81 additions & 0 deletions cloudsql/postgresql/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
{
"name": "appengine-cloudsql-postgres",
"description": "Node.js PostgreSQL sample for Cloud SQL on App Engine.",
"version": "0.0.1",
"private": true,
"license": "Apache-2.0",
"author": "Google Inc.",
"repository": {
"type": "git",
"url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
},
"engines": {
"node": ">=8"
},
"scripts": {
"lint": "repo-tools lint",
"pretest": "npm run lint",
"unit-test": "ava --verbose test/*.test.js",
"start-proxy": "! pgrep cloud_sql_proxy > /dev/null && cloud_sql_proxy -instances=$INSTANCE_CONNECTION_NAME=tcp:$SQL_PORT &",
"system-test": "repo-tools test app -- server.js",
"system-test-proxy": "npm run start-proxy; npm run system-test",
"all-test": "npm run unit-test && npm run system-test",
"test": "repo-tools test run --cmd npm -- run all-test"
},
"dependencies": {
"async": "2.6.0",
"body-parser": "1.18.2",
"express": "4.16.2",
"knex": "0.14.4",
"pg": "7.4.1",
"prompt": "1.0.0",
"pug": "2.0.0-rc.4",
"@google-cloud/logging-winston": "^0.10.2",
"winston": "^3.1.0"
},
"devDependencies": {
"@google-cloud/nodejs-repo-tools": "2.2.1",
"acorn": "^6.0.4",
"acorn-jsx": "^5.0.0",
"ajv": "^6.5.5",
"ajv-keywords": "^3.2.0",
"ava": "0.25.0",
"eslint": "^5.9.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-node": "^8.0.0",
"eslint-plugin-react": "^7.11.1",
"semistandard": "^12.0.1",
"proxyquire": "^2.1.0",
"supertest": "^3.3.0",
"sinon": "^7.1.1"
},
"cloud-repo-tools": {
"requiresKeyFile": true,
"requiresProjectId": true,
"test": {
"app": {
"requiredEnvVars": [
"SQL_USER",
"SQL_PASSWORD",
"SQL_DATABASE",
"SQL_PORT",
"INSTANCE_CONNECTION_NAME"
],
"msg": "Last 10 visits:",
"substitutions": "YOUR_SQL_USER=$SQL_USER,YOUR_SQL_PASSWORD=$SQL_PASSWORD,YOUR_SQL_DATABASE=$SQL_DATABASE,YOUR_INSTANCE_CONNECTION_NAME=$INSTANCE_CONNECTION_NAME",
"args": [
"server.js"
]
},
"build": {
"requiredEnvVars": [
"SQL_USER",
"SQL_PASSWORD",
"SQL_DATABASE",
"SQL_PORT",
"INSTANCE_CONNECTION_NAME"
]
}
}
}
}
Loading