mig/database/database.go

46 строки
1.0 KiB
Go

// 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/.
//
// Contributor: Julien Vehent jvehent@mozilla.com [:ulfr]
package database /* import "github.com/mozilla/mig/database" */
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
type DB struct {
c *sql.DB
}
// NewDB constructs a new DB from a SQL database connection.
func NewDB(conn *sql.DB) DB {
return DB{
c: conn,
}
}
// Connect opens a connection to the database and returns a handler
func Open(dbname, user, password, host string, port int, sslmode string) (db DB, err error) {
url := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=%s",
user, password, host, port, dbname, sslmode)
db.c, err = sql.Open("postgres", url)
if err != nil {
return
}
_, err = db.c.Query("SELECT 1")
return
}
func (db *DB) Close() {
db.c.Close()
}
func (db *DB) SetMaxOpenConns(n int) {
db.c.SetMaxOpenConns(n)
}