Browse Source

Merge pull request #167 from dalinaum/cloudsql

Add Google Cloud SQL support for App Engine.
Julien Schmidt 12 years ago
parent
commit
c418c1bc35
3 changed files with 40 additions and 2 deletions
  1. 5 0
      README.md
  2. 25 0
      appengine.go
  3. 10 2
      driver.go

+ 5 - 0
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

+ 25 - 0
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)
+	}
+}

+ 10 - 2
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
 	}