Skip to content

Commit

Permalink
Add logging
Browse files Browse the repository at this point in the history
  • Loading branch information
KowalskiPiotr98 committed Nov 2, 2024
1 parent 4af3de6 commit 26dbc0d
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 6 deletions.
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,12 @@ var (
)
```
This will embed the contents of the `sql` directory in your output binary file, making it easy to distribute those files.
You can also use the `migrations` variable in place of the provider interface.
You can also use the `migrations` variable in place of the provider interface.

### Logging

This library logs certain errors and information into a logger.
By default, Logrus is used as a logger.
This can be overwritten by assigning custom values to variables in `logger` package.

Note that calling `LogPanic` expects the system to panic afterward, as not doing so might lead to unexpected results.
11 changes: 9 additions & 2 deletions connection_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gotabase
import (
"database/sql"
"errors"
"github.com/KowalskiPiotr98/gotabase/logger"
)

var connection *connectionHandler
Expand Down Expand Up @@ -48,16 +49,20 @@ func InitialiseConnection(connectionString string, driver string) error {
return connectionAlreadyInitialised
}

logger.LogInfo("Initialising database connection...")
database, err := sql.Open(driver, connectionString)
if err != nil {
logger.LogWarn("Failed to open database connection: %v", err)
return err
}
err = database.Ping()
if err != nil {
logger.LogWarn("Failed to ping database: %v", err)
database.Close()
return err
}

logger.LogInfo("Database connection established")
connection = &connectionHandler{
database: database,
}
Expand All @@ -66,19 +71,20 @@ func InitialiseConnection(connectionString string, driver string) error {

func GetConnection() Connector {
if connection == nil {
panic("database connection not initialised")
logger.LogPanic(connectionNotInitialisedErr.Error())
}

return connection
}

func BeginTransaction() (*Transaction, error) {
if connection == nil {
panic("database connection not initialised")
logger.LogPanic(connectionNotInitialisedErr.Error())
}

tx, err := connection.database.Begin()
if err != nil {
logger.LogWarn("Failed to begin transaction: %v", err)
return nil, err
}
return newTransaction(tx), nil
Expand All @@ -90,6 +96,7 @@ func CloseConnection() error {
}

if err := connection.database.Close(); err != nil {
logger.LogWarn("Failed to close database connection: %v", err)
return err
}
connection = nil
Expand Down
6 changes: 5 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
module github.com/KowalskiPiotr98/gotabase

go 1.21.0
go 1.21.0

require github.com/sirupsen/logrus v1.9.3

require golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
17 changes: 15 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,15 @@
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
11 changes: 11 additions & 0 deletions logger/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package logger

import (
log "github.com/sirupsen/logrus"
)

var (
LogInfo = log.Infof
LogWarn = log.Warnf
LogPanic = log.Panicf
)
4 changes: 4 additions & 0 deletions migrations/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package migrations
import (
"errors"
"fmt"
"github.com/KowalskiPiotr98/gotabase/logger"
"slices"
"strconv"
"strings"
Expand All @@ -23,6 +24,7 @@ func getLatestAvailableMigration(migrations MigrationFileProvider) (int, error)
func getMigrationSql(migrations MigrationFileProvider, i int) (string, error) {
fileBytes, err := migrations.ReadFile(fmt.Sprintf("sql/%d.sql", i))
if err != nil {
logger.LogWarn("Unable to read migration file: %v", err)
return "", migrationNotFound
}
return string(fileBytes), nil
Expand All @@ -31,6 +33,7 @@ func getMigrationSql(migrations MigrationFileProvider, i int) (string, error) {
func getAvailableMigrations(migrations MigrationFileProvider) (*[]int, error) {
dirContents, err := migrations.ReadDir("sql")
if err != nil {
logger.LogWarn("Unable to read migration directory: %v", err)
return nil, migrationNotFound
}

Expand All @@ -39,6 +42,7 @@ func getAvailableMigrations(migrations MigrationFileProvider) (*[]int, error) {
nameString := strings.TrimPrefix(strings.TrimSuffix(file.Name(), ".sql"), "sql/")
nameInt, err := strconv.Atoi(nameString)
if err != nil {
logger.LogWarn("Unable to parse migration file name: %v", err)
return nil, err
}
available = append(available, nameInt)
Expand Down
7 changes: 7 additions & 0 deletions migrations/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package migrations
import (
"fmt"
database "github.com/KowalskiPiotr98/gotabase"
"github.com/KowalskiPiotr98/gotabase/logger"
"strings"
)

Expand All @@ -25,13 +26,16 @@ func Migrate(connector database.Connector, fileProvider MigrationFileProvider) e
latestApplied, err := getLatestAppliedMigration(connector)
if err != nil {
if !IsInitialMigrationError(err) {
logger.LogWarn("Unable to get latest applied migration: %v", err)
return err
}
latestApplied = -1
}

latestAvailable, err := getLatestAvailableMigration(fileProvider)
logger.LogInfo("Latest applied migration: %d, latest available migration: %d", latestApplied, latestAvailable)
if latestApplied == latestAvailable {
logger.LogInfo("Latest migration is already applied, nothing to do.")
return nil
}

Expand All @@ -42,12 +46,15 @@ func Migrate(connector database.Connector, fileProvider MigrationFileProvider) e
return err
}

logger.LogInfo("Applying migration %d", currentMigration)
_, err = connector.Exec(MigrationCreator(migrationSql, currentMigration))
if err != nil {
logger.LogWarn("Unable to execute migration %d: %v", currentMigration, err)
return err
}
currentMigration++
}
logger.LogInfo("All pending migrations applied.")
return nil
}

Expand Down

0 comments on commit 26dbc0d

Please sign in to comment.