From c069de3955da41116934884b0874c71b57bd2cf3 Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Wed, 17 Jul 2024 22:26:28 +0200 Subject: [go] refactoring --- golang/cmd/spacetraders/main.go | 4 ++-- golang/pkg/database/db.go | 19 +++++++++++++++++++ golang/pkg/database/migrations.go | 5 ----- golang/pkg/database/tokens.go | 7 ++++--- 4 files changed, 25 insertions(+), 10 deletions(-) create mode 100644 golang/pkg/database/db.go diff --git a/golang/cmd/spacetraders/main.go b/golang/cmd/spacetraders/main.go index 242dee3..84d34ea 100644 --- a/golang/cmd/spacetraders/main.go +++ b/golang/cmd/spacetraders/main.go @@ -35,8 +35,8 @@ func main() { client := api.NewClient(ctx) defer client.Close() if err := run( - db, client, + db, ); err != nil { fmt.Fprintf(os.Stderr, "%s\n", err) if err := db.Close(); err != nil { @@ -47,8 +47,8 @@ func main() { } func run( - db *database.DB, client *api.Client, + db *database.DB, ) error { // ----- Get token or register --------------------------------------------- register, err := client.Register("COSMIC", "ADYXAX-GO") diff --git a/golang/pkg/database/db.go b/golang/pkg/database/db.go new file mode 100644 index 0000000..3e07db3 --- /dev/null +++ b/golang/pkg/database/db.go @@ -0,0 +1,19 @@ +package database + +import ( + "context" + "database/sql" +) + +type DB struct { + ctx context.Context + db *sql.DB +} + +func (db *DB) Exec(query string, args ...any) (sql.Result, error) { + return db.db.ExecContext(db.ctx, query, args...) +} + +func (db *DB) QueryRow(query string, args ...any) *sql.Row { + return db.db.QueryRowContext(db.ctx, query, args...) +} diff --git a/golang/pkg/database/migrations.go b/golang/pkg/database/migrations.go index 81cebaa..b167087 100644 --- a/golang/pkg/database/migrations.go +++ b/golang/pkg/database/migrations.go @@ -9,11 +9,6 @@ import ( _ "github.com/mattn/go-sqlite3" ) -type DB struct { - ctx context.Context - db *sql.DB -} - //go:embed sql/*.sql var schemaFiles embed.FS diff --git a/golang/pkg/database/tokens.go b/golang/pkg/database/tokens.go index 0787b5c..0356cb2 100644 --- a/golang/pkg/database/tokens.go +++ b/golang/pkg/database/tokens.go @@ -1,11 +1,12 @@ package database func (db *DB) AddToken(token string) error { - _, err := db.db.ExecContext(db.ctx, `INSERT INTO tokens(data) VALUES (?);`, token) + _, err := db.Exec(`INSERT INTO tokens(data) VALUES (?);`, token) return err } -func (db *DB) GetToken() (token string, err error) { - err = db.db.QueryRowContext(db.ctx, `SELECT data FROM tokens;`).Scan(&token) +func (db *DB) GetToken() (string, error) { + var token string + err := db.QueryRow(`SELECT data FROM tokens;`).Scan(&token) return token, err } -- cgit v1.2.3