Mainflux.mainflux/users/postgres/init.go

55 lines
1.1 KiB
Go
Raw Normal View History

//
// Copyright (c) 2018
// Mainflux
//
// SPDX-License-Identifier: Apache-2.0
//
2018-05-11 05:53:25 +08:00
package postgres
import (
2018-05-11 07:00:10 +08:00
"database/sql"
2018-05-11 05:53:25 +08:00
"fmt"
2018-05-11 07:00:10 +08:00
_ "github.com/lib/pq" // required for SQL access
migrate "github.com/rubenv/sql-migrate"
2018-05-11 05:53:25 +08:00
)
2018-05-11 07:00:10 +08:00
// Connect creates a connection to the PostgreSQL instance and applies any
// unapplied database migrations. A non-nil error is returned to indicate
// failure.
func Connect(host, port, name, user, pass string) (*sql.DB, error) {
2018-05-11 05:53:25 +08:00
t := "host=%s port=%s user=%s dbname=%s password=%s sslmode=disable"
url := fmt.Sprintf(t, host, port, user, name, pass)
2018-05-11 07:00:10 +08:00
db, err := sql.Open("postgres", url)
2018-05-11 05:53:25 +08:00
if err != nil {
return nil, err
}
2018-05-11 07:00:10 +08:00
if err := migrateDB(db); err != nil {
return nil, err
}
return db, nil
}
func migrateDB(db *sql.DB) error {
migrations := &migrate.MemoryMigrationSource{
Migrations: []*migrate.Migration{
{
2018-05-11 07:00:10 +08:00
Id: "users_1",
Up: []string{
`CREATE TABLE users (
email VARCHAR(254) PRIMARY KEY,
password CHAR(60) NOT NULL
)`,
},
Down: []string{"DROP TABLE users"},
},
},
}
2018-05-11 05:53:25 +08:00
2018-05-11 07:00:10 +08:00
_, err := migrate.Exec(db, "postgres", migrations, migrate.Up)
return err
2018-05-11 05:53:25 +08:00
}