Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(schema): add database schema config #1129

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion cmd/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/spf13/viper"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)

type PsqlConnInfo struct {
Expand All @@ -17,6 +18,7 @@ type PsqlConnInfo struct {
DbName string
SslMode string
Password string
Schema string
}

func getPsqlConnInfo() (PsqlConnInfo, error) {
Expand Down Expand Up @@ -55,12 +57,21 @@ func getPsqlConnInfo() (PsqlConnInfo, error) {
return PsqlConnInfo{}, fmt.Errorf("%s_PGSQL_PASSWORD env var is required", envVarsPrefix)
}

var schema string
if value := viper.GetString("PGSQL_SCHEMA"); value != "" {
schema = value
} else {
schema = ""
glog.V(2).Info("No schema set.")
}
Comment on lines +61 to +66
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if value := viper.GetString("PGSQL_SCHEMA"); value != "" {
schema = value
} else {
schema = ""
glog.V(2).Info("No schema set.")
}
schema = viper.GetString("PGSQL_SCHEMA")


return PsqlConnInfo{
Host: host,
User: user,
DbName: dbName,
SslMode: sslMode,
Password: password,
Schema: schema,
}, nil
}

Expand Down Expand Up @@ -97,7 +108,18 @@ func savePgsql(jsonInfo string) {
exitWithError(err)
}

db, err := gorm.Open(postgres.Open(PsqlConnInfo.toString()), &gorm.Config{})
var db *gorm.DB

if PsqlConnInfo.Schema == "" {
serrovsky marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if PsqlConnInfo.Schema == "" {
if PsqlConnInfo.Schema == "" {
glog.V(2).Info("No schema set.")

db, err = gorm.Open(postgres.Open(PsqlConnInfo.toString()), &gorm.Config{})
} else {
db, err = gorm.Open(postgres.Open(PsqlConnInfo.toString()), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
TablePrefix: fmt.Sprintf("%s.", PsqlConnInfo.Schema), // schema name
SingularTable: false,
}})
}

if err != nil {
exitWithError(fmt.Errorf("received error connecting to database: %s", err))
}
Expand Down