URL shortener and file dump for hashru.link https://hashru.link
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.1 KiB

package db
import (
const (
// EnvDatabaseDriver is the key for the 'database driver' environment variable.
// EnvDatabasePath is the key for the 'database path' environment variable.
// EnvPostgresURL is the key for the 'postgresql URL' environment variable.
// EnvFileStorePath is the key for the environment variable locating the file store.
// Database is the main rushlink database type.
// Open a database using OpenDBFromEnvironment(). Closing is not necessary.
// Only one instance of DB should exist in a program at any moment.
type Database = gorm.DB
var (
gormLogger logger.Interface = logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{
SlowThreshold: 50 * time.Millisecond,
LogLevel: logger.Error,
Colorful: true,
gormConfig = gorm.Config{Logger: gormLogger}
// OpenDBFromEnvironment tries to open an SQL database, described by
func OpenDBFromEnvironment() (*Database, error) {
const envNotSetMsg = "%v environment variable is not set"
driver, prs := os.LookupEnv(EnvDatabaseDriver)
if !prs {
return nil, errors.Errorf(envNotSetMsg, EnvDatabaseDriver)
switch driver {
case "sqlite":
path, prs := os.LookupEnv(EnvDatabasePath)
if !prs {
return nil, errors.Errorf(envNotSetMsg, EnvDatabasePath)
db, err := gorm.Open(sqlite.Open(path), &gormConfig)
if err != nil {
return nil, err
return db, nil
case "postgres":
dsn, prs := os.LookupEnv(EnvPostgresURL)
if !prs {
return nil, errors.Errorf(envNotSetMsg, EnvPostgresURL)
db, err := gorm.Open(postgres.Open(dsn), &gormConfig)
if err != nil {
return nil, err
return db, nil
return nil, errors.Errorf("RUSHLINK_DATABASE_DRIVER should be either 'sqlite' or 'postgres' (not '%v'), "+
"for more info see <https://stackoverflow.com/q/3582552/5207081>", driver)