Skip to content

Commit

Permalink
fix: fix sqldbtest; files tossing
Browse files Browse the repository at this point in the history
  • Loading branch information
roman-vanesyan committed Oct 21, 2024
1 parent 0be9991 commit 1707863
Show file tree
Hide file tree
Showing 29 changed files with 344 additions and 313 deletions.
7 changes: 3 additions & 4 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ services:
image: postgres:16
restart: unless-stopped
environment:
POSTGRES_PASSWORD: test
POSTGRES_USER: test
POSTGRES_DB: test
POSTGRES_PASSWORD: local
POSTGRES_USER: local
POSTGRES_DB: local
ports:
- "5432:5432"

5 changes: 0 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ require (
github.com/jackc/pgx/v5 v5.6.0
github.com/jackc/puddle/v2 v2.2.1
github.com/joho/godotenv v1.5.1
github.com/samber/lo v1.47.0
github.com/spf13/cobra v1.8.1
github.com/stretchr/testify v1.9.0
go.inout.gg/shield v0.0.0-20240827214956-d2b7a49e7e6f
golang.org/x/crypto v0.26.0
golang.org/x/sync v0.8.0
)
Expand All @@ -24,14 +21,12 @@ require (
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/kr/text v0.2.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rogpeppe/go-internal v1.12.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/net v0.27.0 // indirect
golang.org/x/sys v0.23.0 // indirect
golang.org/x/text v0.17.0 // indirect
Expand Down
12 changes: 0 additions & 12 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ github.com/a-h/templ v0.2.747 h1:D0dQ2lxC3W7Dxl6fxQ/1zZHBQslSkTSvl5FxP/CfdKg=
github.com/a-h/templ v0.2.747/go.mod h1:69ObQIbrcuwPCU32ohNaWce3Cb7qM5GMiqN1K+2yop4=
github.com/caarlos0/env/v11 v11.1.0 h1:a5qZqieE9ZfzdvbbdhTalRrHT5vu/4V1/ad1Ka6frhI=
github.com/caarlos0/env/v11 v11.1.0/go.mod h1:LwgkYk1kDvfGpHthrWWLof3Ny7PezzFwS4QrsJdHTMo=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
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=
Expand All @@ -24,8 +23,6 @@ github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
Expand All @@ -46,20 +43,11 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/samber/lo v1.47.0 h1:z7RynLwP5nbyRscyvcD043DWYoOcYRv3mV8lBeqOCLc=
github.com/samber/lo v1.47.0/go.mod h1:RmDH9Ct32Qy3gduHQuKJ3gW1fMHAnE/fAzQuf6He5cU=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.inout.gg/shield v0.0.0-20240827214956-d2b7a49e7e6f h1:ZmMipAuTb7XaFoHZXG4DNZWoqwd7UY4/omqSzTY84hY=
go.inout.gg/shield v0.0.0-20240827214956-d2b7a49e7e6f/go.mod h1:Pr1OahlV0l4aEF7X5MpmXdzyV2s0fz747kn8wfPWkhA=
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys=
Expand Down
60 changes: 60 additions & 0 deletions pointer/pointer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package pointer

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestToValue(t *testing.T) {
t.Run("non-nil pointer", func(t *testing.T) {
value := 42
ptr := &value
defaultValue := 0

result := ToValue(ptr, defaultValue)

assert.Equal(t, value, result, "ToValue should return the pointed-to value for non-nil pointers")
})

t.Run("nil pointer", func(t *testing.T) {
var ptr *int
defaultValue := 10

result := ToValue(ptr, defaultValue)

assert.Equal(t, defaultValue, result, "ToValue should return the default value for nil pointers")
})
}

func TestFromValue(t *testing.T) {
t.Run("integer value", func(t *testing.T) {
value := 42

result := FromValue(value)

assert.NotNil(t, result, "FromValue should return a non-nil pointer")
assert.Equal(t, value, *result, "FromValue should return a pointer to the correct value")
})

t.Run("string value", func(t *testing.T) {
value := "hello"

result := FromValue(value)

assert.NotNil(t, result, "FromValue should return a non-nil pointer")
assert.Equal(t, value, *result, "FromValue should return a pointer to the correct value")
})

t.Run("struct value", func(t *testing.T) {
type TestStruct struct {
Field string
}
value := TestStruct{Field: "test"}

result := FromValue(value)

assert.NotNil(t, result, "FromValue should return a non-nil pointer")
assert.Equal(t, value, *result, "FromValue should return a pointer to the correct value")
})
}
28 changes: 0 additions & 28 deletions random/hex.go

This file was deleted.

30 changes: 0 additions & 30 deletions sql/db/context.go

This file was deleted.

Empty file removed sql/db/middleware.go
Empty file.
15 changes: 0 additions & 15 deletions sql/db/option.go

This file was deleted.

9 changes: 5 additions & 4 deletions sql/db/dbutil/util.go → sqldb/error.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package dbutil
package sqldb

import (
"errors"
Expand All @@ -14,11 +14,12 @@ const (

// IsUniqueViolationError returns true if the error is a unique violation error.
func IsUniqueViolationError(err error) bool {
if pgxErr, ok := err.(*pgconn.PgError); !ok || pgxErr.Code != ErrCodeUniqueViolation {
return false
pgxErr := &pgconn.PgError{}
if errors.As(err, &pgxErr) {
return pgxErr.Code == ErrCodeUniqueViolation
}

return true
return false
}

// IsNotFoundError returns true if the error is a pgx no rows error.
Expand Down
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ import (

"github.com/google/uuid"
"github.com/stretchr/testify/require"
"go.inout.gg/foundations/sql/db/dbtest"
"go.inout.gg/foundations/sqldb/sqldbtest"
)

func TestCodecDecodeValue(t *testing.T) {
ctx := context.Background()
db := dbtest.Must(ctx, t)
db := sqldbtest.Must(ctx, t)

pool := db.Pool()
original, err := uuid.NewV7()
Expand Down Expand Up @@ -50,7 +50,7 @@ func TestCodecDecodeValue(t *testing.T) {

func TestArray(t *testing.T) {
ctx := context.Background()
db := dbtest.Must(ctx, t)
db := sqldbtest.Must(ctx, t)
p := db.Pool()

inputSlice := []uuid.UUID{}
Expand Down
44 changes: 44 additions & 0 deletions sqldb/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package sqldb

import (
"context"
"errors"
"net/http"

"github.com/jackc/pgx/v5/pgxpool"
"go.inout.gg/foundations/http/httpmiddleware"
)

type ctxKey struct{}

var kCtxKey = ctxKey{}

var ErrDBPoolNotFound = errors.New("foundations/sqldb: failed to retrieve db pool from context.")

// WithContext returns a new context with the given pool.
func WithContext(ctx context.Context, pool *pgxpool.Pool) context.Context {
return context.WithValue(ctx, kCtxKey, pool)
}

// FromContext returns the pool associated with the given context.
func FromContext(ctx context.Context) (*pgxpool.Pool, error) {
if pool, ok := ctx.Value(kCtxKey).(*pgxpool.Pool); ok {
return pool, nil
}

return nil, ErrDBPoolNotFound
}

// FromRequest returns the pool associated with the given http request.
func FromRequest(req *http.Request) (*pgxpool.Pool, error) {
return FromContext(req.Context())
}

// Middleware returns a middleware that injects the given pool into the request context.
func Middleware(db *pgxpool.Pool) httpmiddleware.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
next.ServeHTTP(w, req.WithContext(WithContext(req.Context(), db)))
})
}
}
66 changes: 66 additions & 0 deletions sqldb/pool.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package sqldb

import (
"context"
"fmt"

"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"go.inout.gg/foundations/must"
"go.inout.gg/foundations/sqldb/internal/pgxuuid"
)

// WithTracer sets the query tracer for the database pool.
func WithTracer(t pgx.QueryTracer) func(c *pgxpool.Config) {

Check failure on line 14 in sqldb/pool.go

View workflow job for this annotation

GitHub Actions / lint

undefined: pgx (typecheck)
return func(c *pgxpool.Config) { c.ConnConfig.Tracer = t }
}

// WithUUID adds native support for converting between Postgres UUID and google/uuid.
func WithUUID() func(c *pgxpool.Config) {
return func(c *pgxpool.Config) {
origAfterConnect := c.AfterConnect
c.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {

Check failure on line 22 in sqldb/pool.go

View workflow job for this annotation

GitHub Actions / lint

undefined: pgx (typecheck)
pgxuuid.Register(conn.TypeMap())
if origAfterConnect != nil {
return origAfterConnect(ctx, conn)
}
return nil
}
}
}

// MustPool creates a new connection pool and panics on error.
func MustPool(ctx context.Context, connString string, cfgs ...func(*pgxpool.Config)) *pgxpool.Pool {
return must.Must(NewPool(ctx, connString, cfgs...))
}

// NewPool creates a new connection pool using the provided connection string.
//
// Optional cfgs like WithUUID or WithTracer can be provided.
func NewPool(ctx context.Context, connString string, cfgs ...func(*pgxpool.Config)) (pool *pgxpool.Pool, err error) {
config, err := pgxpool.ParseConfig(connString)
if err != nil {
return nil, fmt.Errorf("foundations/sqldb: failed to parse database connection string: %w", err)
}
for _, f := range cfgs {
f(config)
}

pool, err = pgxpool.NewWithConfig(ctx, config)
if err != nil {
return nil, fmt.Errorf("foundations/sqldb: failed to create a new database pool: %w", err)
}
defer func() {
if err != nil {
if pool != nil {
pool.Close()
}
}
}()

if err = pool.Ping(ctx); err != nil {
return nil, fmt.Errorf("foundations/sqldb: failed to connect to the database at %s: %w", connString, err)
}

return pool, nil
}
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit 1707863

Please sign in to comment.