Skip to content

Commit

Permalink
fix: error handling in db conn
Browse files Browse the repository at this point in the history
  • Loading branch information
chelodoz committed May 21, 2024
1 parent a30be16 commit 44ad8f0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
7 changes: 4 additions & 3 deletions examples/golang-api-with-postgres-and-sqlc/db/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package db

import (
"context"
"fmt"
"go-postgres-sqlc/db/sqlc"
"log"

Expand All @@ -17,11 +18,11 @@ type DB struct {
}

// New initializes a new DBConfig instance
func New(dsn string) *DB {
func New(dsn string) (*DB, error) {
ctx := context.Background()
conn, err := pgx.Connect(ctx, dsn)
if err != nil {
log.Fatalf("Unable to connect to database: %v", err)
return nil, fmt.Errorf("unable to connect to database: %v", err)
}
log.Println("Connected to database")

Expand All @@ -32,5 +33,5 @@ func New(dsn string) *DB {
Context: ctx,
Conn: conn,
Queries: queries,
}
}, nil
}
19 changes: 13 additions & 6 deletions examples/golang-api-with-postgres-and-sqlc/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"fmt"
"go-postgres-sqlc/db"
"go-postgres-sqlc/handler"
"log"
Expand All @@ -13,9 +14,14 @@ import (
)

func main() {
db := db.New("postgres://postgres:postgres@db:5432/poc?sslmode=disable")
runMigrations(db)

db, err := db.New("postgres://postgres:postgres@db:5432/poc?sslmode=disable")
if err != nil {
log.Fatal(err)
}
err = runMigrations(db)
if err != nil {
log.Fatal(err)
}
userRepo := repository.NewUser(db)
userSvc := service.NewUser(userRepo)
userHandler := handler.NewUser(userSvc)
Expand All @@ -27,13 +33,13 @@ func main() {
base.HandleFunc("/user/{id:[0-9]+}", userHandler.GetUser).Methods(http.MethodGet)
base.HandleFunc("/user", userHandler.CreateUser).Methods(http.MethodPost)

err := http.ListenAndServe(":8080", base)
err = http.ListenAndServe(":8080", base)
if err != nil {
log.Fatal(err)
}
}

func runMigrations(db *db.DB) {
func runMigrations(db *db.DB) error {
query := `CREATE TABLE IF NOT EXISTS users (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
username VARCHAR(30) NOT NULL,
Expand All @@ -43,7 +49,8 @@ func runMigrations(db *db.DB) {
)`
_, err := db.Conn.Exec(db.Context, query)
if err != nil {
log.Fatalf("Failed to create users table: %v", err)
return fmt.Errorf("failed to create users table: %v", err)
}
log.Println("Users table created or already exists.")
return nil
}

0 comments on commit 44ad8f0

Please sign in to comment.