...

Source file src/github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/postgres/hook.go

Documentation: github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/postgres

     1  // Copyright 2017 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package postgres adds a 'cloudsqlpostgres' driver to use when you want
    16  // to access a Cloud SQL Database via the go database/sql library.
    17  // It is a wrapper over the driver found at github.com/lib/pq.
    18  // To use this driver, you can look at an example in
    19  // postgres_test package in the hook_test.go file
    20  package postgres
    21  
    22  import (
    23  	"database/sql"
    24  	"database/sql/driver"
    25  	"fmt"
    26  	"net"
    27  	"regexp"
    28  	"time"
    29  
    30  	"github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/proxy"
    31  	"github.com/lib/pq"
    32  )
    33  
    34  func init() {
    35  	sql.Register("cloudsqlpostgres", &Driver{})
    36  }
    37  
    38  type Driver struct{}
    39  
    40  type dialer struct{}
    41  
    42  // instanceRegexp is used to parse the addr returned by lib/pq.
    43  // lib/pq returns the format '[project:region:instance]:port'
    44  var instanceRegexp = regexp.MustCompile(`^\[(.+)\]:[0-9]+$`)
    45  
    46  func (d dialer) Dial(ntw, addr string) (net.Conn, error) {
    47  	matches := instanceRegexp.FindStringSubmatch(addr)
    48  	if len(matches) != 2 {
    49  		return nil, fmt.Errorf("failed to parse addr: %q. It should conform to the regular expression %q", addr, instanceRegexp)
    50  	}
    51  	instance := matches[1]
    52  	return proxy.Dial(instance)
    53  }
    54  
    55  func (d dialer) DialTimeout(ntw, addr string, timeout time.Duration) (net.Conn, error) {
    56  	return nil, fmt.Errorf("timeout is not currently supported for cloudsqlpostgres dialer")
    57  }
    58  
    59  func (d *Driver) Open(name string) (driver.Conn, error) {
    60  	return pq.DialOpen(dialer{}, name)
    61  }
    62  

View as plain text