From e68ded1b3c48e866df9a8fb05d6d061eaa35042a Mon Sep 17 00:00:00 2001 From: Marc Cataford Date: Thu, 11 Jul 2024 00:09:24 -0400 Subject: [PATCH] refactor: isolate db handler --- cobble.go | 11 +++-------- database.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ migrate.go | 11 ++--------- migrate_test.go | 8 ++++---- models.go | 14 +------------- 5 files changed, 55 insertions(+), 34 deletions(-) create mode 100644 database.go diff --git a/cobble.go b/cobble.go index 700054b..9991768 100644 --- a/cobble.go +++ b/cobble.go @@ -18,13 +18,8 @@ var up = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { dbPort, _ := strconv.Atoi(os.Getenv("DB_PORT")) - dbConnection, err := ConnectToDatabase(DatabaseConfiguration{ - User: os.Getenv("DB_APP_USER"), - Password: os.Getenv("DB_APP_PASSWORD"), - DatabaseName: os.Getenv("DB_NAME"), - Host: os.Getenv("DB_HOST"), - Port: dbPort, - }) + db := NewDatabase(os.Getenv("DB_HOST"), dbPort) + err := db.Connect(os.Getenv("DB_APP_USER"), os.Getenv("DB_APP_PASSWORD"), os.Getenv("DB_NAME")) if err != nil { log.Printf("Failed to connect to the database: %s", err) @@ -36,7 +31,7 @@ var up = &cobra.Command{ for _, migration := range migrationHistory { log.Printf("%s", migration.Name) - if err = migrate(dbConnection, migration.Path); err != nil { + if err = migrate(db, migration.Path); err != nil { os.Exit(1) } } diff --git a/database.go b/database.go new file mode 100644 index 0000000..9f8126b --- /dev/null +++ b/database.go @@ -0,0 +1,45 @@ +package main + +import ( + "database/sql" + "errors" + "fmt" + _ "github.com/lib/pq" +) + +type Database struct { + Host string + Port int + connection *sql.DB +} + +func NewDatabase(host string, port int) Database { + return Database{ + Host: host, + Port: port, + } +} + +func (d *Database) Connect(user string, password string, dbname string) error { + connectionString := fmt.Sprintf("postgresql://%s:%s@%s:%d?sslmode=disable", user, password, d.Host, d.Port) + + conn, err := sql.Open(dbname, connectionString) + + if err != nil { + return err + } + + d.connection = conn + + return nil +} + +func (d Database) Execute(sql string) error { + if d.connection == nil { + return errors.New("Cannot execute SQL without being connected to a database.") + } + + _, err := d.connection.Exec(sql) + + return err +} diff --git a/migrate.go b/migrate.go index c37492b..784a331 100644 --- a/migrate.go +++ b/migrate.go @@ -8,9 +8,7 @@ package main import ( "bufio" "bytes" - "database/sql" - "fmt" - _ "github.com/lib/pq" + "log" "os" "path/filepath" @@ -41,7 +39,7 @@ func migrate(db DB, migrationPath string) error { log.Printf("SQL: %s", migrationSql) - _, err = db.Exec(migrationSql) + err = db.Execute(migrationSql) if err != nil { log.Printf("Failed to run %s: %s", migrationPath, err) @@ -126,8 +124,3 @@ func getMigrations(migrationsRoot string) ([]Migration, error) { return migrationGraph.GetLinearHistory() } - -func ConnectToDatabase(config DatabaseConfiguration) (*sql.DB, error) { - connectionString := fmt.Sprintf("postgresql://%s:%s@%s:%d?sslmode=disable", config.User, config.Password, config.Host, config.Port) - return sql.Open(config.DatabaseName, connectionString) -} diff --git a/migrate_test.go b/migrate_test.go index da15370..01f68d2 100644 --- a/migrate_test.go +++ b/migrate_test.go @@ -19,18 +19,18 @@ type MockResult struct { sql.Result } -func (m *MockSqlDB) Exec(sql string, args ...any) (sql.Result, error) { +func (m *MockSqlDB) Execute(sql string) error { m.queries = append(m.queries, sql) if m.mockedError != nil { - return MockResult{}, m.mockedError + return m.mockedError } if m.mockedResult != nil { - return m.mockedResult, nil + return nil } - return MockResult{}, nil + return nil } func TestGetMigrationsGathersSqlFiles(t *testing.T) { diff --git a/models.go b/models.go index e93e9a1..16489ec 100644 --- a/models.go +++ b/models.go @@ -1,9 +1,5 @@ package main -import ( - "database/sql" -) - type MigrationHeaders struct { Requirements []string } @@ -15,14 +11,6 @@ type Migration struct { Run bool } -type DatabaseConfiguration struct { - Host string - User string - Password string - DatabaseName string - Port int -} - type MigrationGraph struct { // Reference to the root of the graph. Root *Migration @@ -33,5 +21,5 @@ type MigrationGraph struct { } type DB interface { - Exec(sql string, args ...any) (sql.Result, error) + Execute(sql string) error }