diff --git a/Gopkg.lock b/Gopkg.lock index 598968b2f9..1ade27568a 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -303,7 +303,10 @@ [[projects]] name = "github.com/ory/sqlcon" - packages = ["dockertest"] + packages = [ + ".", + "dockertest" + ] revision = "08e1c6762dd59c776a735acc134889f757574f66" version = "v0.0.2" @@ -538,6 +541,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "c0c8c5a4c4edd1c90ad7a45b25b66d7e2d3540c4715c8ba25e494d26a6e13516" + inputs-digest = "833b7210006d4fa0e660d0cfccd5335656fb8c27d1700cf4b8d1490fa8b40e02" solver-name = "gps-cdcl" solver-version = 1 diff --git a/cmd/helper_sql.go b/cmd/helper_sql.go index ae0d1f8848..0d868c0193 100644 --- a/cmd/helper_sql.go +++ b/cmd/helper_sql.go @@ -21,61 +21,45 @@ package cmd import ( - "runtime" - "time" - "net/url" "github.com/jmoiron/sqlx" "github.com/ory/oathkeeper/rule" + "github.com/ory/sqlcon" "github.com/pkg/errors" ) -func connectToSql(url string) (*sqlx.DB, error) { - db, err := sqlx.Open("postgres", url) +func connectToSql(dburl string) (*sqlx.DB, error) { + u, err := url.Parse(dburl) if err != nil { - return nil, errors.WithStack(err) + logger.Fatalf("Could not parse DATABASE_URL: %s", err) } - maxConns := maxParallelism() * 2 - maxConnLifetime := time.Duration(0) - maxIdleConns := maxParallelism() - db.SetMaxOpenConns(maxConns) - db.SetMaxIdleConns(maxIdleConns) - db.SetConnMaxLifetime(maxConnLifetime) - return db, nil -} - -func maxParallelism() int { - maxProcs := runtime.GOMAXPROCS(0) - numCPU := runtime.NumCPU() - if maxProcs < numCPU { - return maxProcs + switch u.Scheme { + case "postgres": + fallthrough + case "mysql": + connection, err := sqlcon.NewSQLConnection(dburl, logger) + if err != nil { + logger.WithError(err).Fatalf(`Unable to initialize SQL connection`) + } + return connection.GetDatabase(), nil } - return numCPU + + return nil, errors.Errorf(`Unknown DSN "%s" in DATABASE_URL: %s`, u.Scheme, dburl) } -func newRuleManager(db string) (rule.Manager, error) { - if db == "memory" { +func newRuleManager(dburl string) (rule.Manager, error) { + if dburl == "memory" { return &rule.MemoryManager{Rules: map[string]rule.Rule{}}, nil - } else if db == "" { + } else if dburl == "" { return nil, errors.New("No database URL provided") } - u, err := url.Parse(db) + db, err := connectToSql(dburl) if err != nil { return nil, errors.WithStack(err) } - switch u.Scheme { - case "postgres": - db, err := connectToSql(db) - if err != nil { - return nil, errors.WithStack(err) - } - - return rule.NewSQLManager(db), nil - } - - return nil, errors.Errorf("The provided database URL %s can not be handled", db) + return rule.NewSQLManager(db), nil }