From 7c08711297284b2769974565db6991fccd61b5ef Mon Sep 17 00:00:00 2001 From: Leonardo YongUk Kim Date: Thu, 14 Nov 2013 21:36:36 +0900 Subject: [PATCH] Add Google Cloud SQL support for App Engine. It uses Cloud SQL as a database if it runs on Google App Engine with using cloudsql DSN. appengine.go includes a build constraint for Google App Engine (GAE) (http://blog.golang.org/the-app-engine-sdk-and-workspaces-gopath) to avoid an error outside App Engine and provide an exception. Using Google Cloud SQL with App Engine GO SDK is not supported yet. It is a SDK limitation. --- README.md | 5 +++++ appengine.go | 25 +++++++++++++++++++++++++ driver.go | 12 ++++++++++-- 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 appengine.go diff --git a/README.md b/README.md index be1b5dcbf..41f7d4716 100644 --- a/README.md +++ b/README.md @@ -242,6 +242,11 @@ TCP on a remote host, e.g. Amazon RDS: id:password@tcp(your-amazonaws-uri.com:3306)/dbname ``` +Google Cloud SQL on App Engine: +``` +user@cloudsql(project-id:instance-name)/dbname +``` + TCP using default port (3306) on localhost: ``` user:password@tcp/dbname&charset=utf8mb4,utf8&sys_var=esc%40ped diff --git a/appengine.go b/appengine.go new file mode 100644 index 000000000..55cd90ae3 --- /dev/null +++ b/appengine.go @@ -0,0 +1,25 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +// +build appengine + +package mysql + +import ( + "appengine/cloudsql" + "net" +) + +func init() { + if dials == nil { + dials = make(map[string]dialFunc) + } + dials["cloudsql"] = func(cfg *config) (net.Conn, error) { + return cloudsql.Dial(cfg.addr) + } +} diff --git a/driver.go b/driver.go index c5f386363..aa46ec753 100644 --- a/driver.go +++ b/driver.go @@ -26,6 +26,10 @@ import ( // In general the driver is used via the database/sql package. type MySQLDriver struct{} +type dialFunc func(*config) (net.Conn, error) + +var dials map[string]dialFunc + // Open new Connection. // See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how // the DSN string is formated @@ -43,8 +47,12 @@ func (d *MySQLDriver) Open(dsn string) (driver.Conn, error) { } // Connect to Server - nd := net.Dialer{Timeout: mc.cfg.timeout} - mc.netConn, err = nd.Dial(mc.cfg.net, mc.cfg.addr) + if dial, ok := dials[mc.cfg.net]; ok { + mc.netConn, err = dial(mc.cfg) + } else { + nd := net.Dialer{Timeout: mc.cfg.timeout} + mc.netConn, err = nd.Dial(mc.cfg.net, mc.cfg.addr) + } if err != nil { return nil, err }