Skip to content

Commit

Permalink
Merge pull request #25 from MateoCaicedoW/removing-sqlx
Browse files Browse the repository at this point in the history
Replacing jmoiron/sqlx by database/sql
  • Loading branch information
paganotoni authored Jun 21, 2024
2 parents 36d623c + ad85901 commit 1959fab
Show file tree
Hide file tree
Showing 10 changed files with 59 additions and 49 deletions.
11 changes: 5 additions & 6 deletions db/connection.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package db

import (
"database/sql"
"sync"

"github.com/jmoiron/sqlx"
)

var (
conn *sqlx.DB
conn *sql.DB
cmux sync.Mutex

//DriverName defaults to postgres
Expand All @@ -17,7 +16,7 @@ var (
// ConnFn is the database connection builder function that
// will be used by the application based on the driver and
// connection string.
type ConnFn func() (*sqlx.DB, error)
type ConnFn func() (*sql.DB, error)

// connectionOptions for the database
type connectionOption func()
Expand All @@ -27,7 +26,7 @@ type connectionOption func()
// connection string. It opens the connection only once
// and return the same connection on subsequent calls.
func ConnectionFn(url string, opts ...connectionOption) ConnFn {
return func() (cx *sqlx.DB, err error) {
return func() (cx *sql.DB, err error) {
cmux.Lock()
defer cmux.Unlock()

Expand All @@ -40,7 +39,7 @@ func ConnectionFn(url string, opts ...connectionOption) ConnFn {
v()
}

conn, err = sqlx.Connect(driverName, url)
conn, err = sql.Open(driverName, url)
if err != nil {
return nil, err
}
Expand Down
13 changes: 9 additions & 4 deletions db/migrations.go
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
package db

import (
"database/sql"
"embed"
"fmt"
"html/template"
"os"
"path/filepath"
"regexp"

"github.com/jmoiron/sqlx"
"github.com/leapkit/core/db/migrations"
"github.com/leapkit/core/db/postgres"
"github.com/leapkit/core/db/sqlite"
)

// migratorFor the adapter for the passed SQL connection
// based on the driver name.
func migratorFor(conn *sqlx.DB) any {
func migratorFor(conn *sql.DB) any {
// Migrator for the passed SQL connection.
switch conn.DriverName() {
drivers := sql.Drivers()
if len(drivers) != 1 {
return nil
}

switch drivers[0] {
case "postgres":
return postgres.New(conn)
case "sqlite", "sqlite3":
Expand Down Expand Up @@ -57,7 +62,7 @@ func GenerateMigration(name string, options ...migrations.Option) error {

// RunMigrations by checking in the migrations database
// table, each of the adapters take care of this.
func RunMigrations(fs embed.FS, conn *sqlx.DB) error {
func RunMigrations(fs embed.FS, conn *sql.DB) error {
dir, err := fs.ReadDir(".")
if err != nil {
return fmt.Errorf("error reading migrations directory: %w", err)
Expand Down
7 changes: 3 additions & 4 deletions db/postgres/adapter.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package postgres

import (
"database/sql"
"regexp"

"github.com/jmoiron/sqlx"
)

var (
Expand All @@ -15,11 +14,11 @@ var (
// adapter for the sqlite database it includes the connection
// to perform the framework operations.
type adapter struct {
conn *sqlx.DB
conn *sql.DB
}

// New sqlite adapter with the passed connection.
func New(conn *sqlx.DB) *adapter {
func New(conn *sql.DB) *adapter {
return &adapter{
conn: conn,
}
Expand Down
14 changes: 8 additions & 6 deletions db/postgres/manager.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package postgres

import (
"database/sql"
"fmt"

"github.com/jmoiron/sqlx"
)

type manager struct {
Expand All @@ -23,13 +22,15 @@ func (m *manager) Create() error {
return fmt.Errorf("invalid database url: %s", m.url)
}

db, err := sqlx.Connect("postgres", fmt.Sprintf("postgres://%s:%s@%s:%s/postgres?sslmode=disable", matches[1], matches[2], matches[3], matches[4]))
db, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s:%s/postgres?sslmode=disable", matches[1], matches[2], matches[3], matches[4]))
if err != nil {
return fmt.Errorf("error connecting to database: %w", err)
}

var exists int
err = db.Get(&exists, "SELECT COUNT(datname) FROM pg_database WHERE datname ilike $1", matches[5])
row := db.QueryRow("SELECT COUNT(datname) FROM pg_database WHERE datname ilike $1", matches[5])
err = row.Scan(&exists)

if err != nil {
return err
}
Expand All @@ -53,13 +54,14 @@ func (m *manager) Drop() error {
return fmt.Errorf("invalid database url: %s", m.url)
}

db, err := sqlx.Connect("postgres", fmt.Sprintf("postgres://%s:%s@%s:%s/postgres?sslmode=disable", matches[1], matches[2], matches[3], matches[4]))
db, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s:%s/postgres?sslmode=disable", matches[1], matches[2], matches[3], matches[4]))
if err != nil {
return fmt.Errorf("error connecting to database: %w", err)
}

var dbexists int
err = db.Get(&dbexists, "SELECT COUNT(datname) FROM pg_database WHERE datname ilike $1", matches[5])
row := db.QueryRow("SELECT COUNT(datname) FROM pg_database WHERE datname ilike $1", matches[5])
err = row.Scan(&dbexists)
if err != nil {
return err
}
Expand Down
3 changes: 2 additions & 1 deletion db/postgres/migrations.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ func (a *adapter) Setup() error {
// on the migrations table.
func (a *adapter) Run(timestamp, sql string) error {
var exists bool
err := a.conn.Get(&exists, "SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE timestamp = $1)", timestamp)
row := a.conn.QueryRow("SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE timestamp = $1)", timestamp)
err := row.Scan(&exists)
if err != nil {
return fmt.Errorf("error running migration: %w", err)
}
Expand Down
8 changes: 5 additions & 3 deletions db/sqlite/adapter.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
package sqlite

import "github.com/jmoiron/sqlx"
import (
"database/sql"
)

// adapter for the sqlite database it includes the connection
// to perform the framework operations.
type adapter struct {
conn *sqlx.DB
conn *sql.DB
}

// New sqlite adapter with the passed connection.
func New(conn *sqlx.DB) *adapter {
func New(conn *sql.DB) *adapter {
return &adapter{
conn: conn,
}
Expand Down
3 changes: 2 additions & 1 deletion db/sqlite/migrations.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ func (a *adapter) Setup() error {
// on the migrations table.
func (a *adapter) Run(timestamp, sql string) error {
var exists bool
err := a.conn.Get(&exists, "SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE timestamp = $1)", timestamp)
row := a.conn.QueryRow("SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE timestamp = $1)", timestamp)
err := row.Scan(&exists)
if err != nil {
return fmt.Errorf("error running migration: %w", err)
}
Expand Down
33 changes: 22 additions & 11 deletions db/sqlite/migrations_test.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
package sqlite_test

import (
"database/sql"
"path/filepath"
"testing"

"github.com/jmoiron/sqlx"
"github.com/leapkit/core/db/sqlite"
_ "github.com/mattn/go-sqlite3"
)

func TestSetup(t *testing.T) {
td := t.TempDir()
conn, err := sqlx.Connect("sqlite3", filepath.Join(td, "database.db"))
conn, err := sql.Open("sqlite3", filepath.Join(td, "database.db"))
if err != nil {
t.Fatal(err)
}
Expand All @@ -22,21 +22,30 @@ func TestSetup(t *testing.T) {
t.Fatal(err)
}

result := struct{ Name string }{}
err = conn.Get(&result, "SELECT name FROM sqlite_master WHERE type='table' AND name='schema_migrations';")
var name string
rows, err := conn.Query("SELECT name FROM sqlite_master WHERE type='table' AND name='schema_migrations';")
if err != nil {
t.Fatal("schema_migrations table not found")
}

if result.Name != "schema_migrations" {
if !rows.Next() {
t.Fatal("schema_migrations table not found")
}

err = rows.Scan(&name)
if err != nil {
t.Fatal(err)
}

if name != "schema_migrations" {
t.Fatal("schema_migrations table not found")
}
}

func TestRun(t *testing.T) {
t.Run("migration not found", func(t *testing.T) {
td := t.TempDir()
conn, err := sqlx.Connect("sqlite3", filepath.Join(td, "database.db"))
conn, err := sql.Open("sqlite3", filepath.Join(td, "database.db"))
if err != nil {
t.Fatal(err)
}
Expand All @@ -52,16 +61,17 @@ func TestRun(t *testing.T) {
t.Fatal(err)
}

result := struct{ Name string }{}
err = conn.Get(&result, "SELECT name FROM sqlite_master WHERE type='table' AND name='users';")
var name string
row := conn.QueryRow("SELECT name FROM sqlite_master WHERE type='table' AND name='users';")
err = row.Scan(&name)
if err != nil {
t.Fatal("users table not found")
}
})

t.Run("migration found", func(t *testing.T) {
td := t.TempDir()
conn, err := sqlx.Connect("sqlite3", filepath.Join(td, "database.db"))
conn, err := sql.Open("sqlite3", filepath.Join(td, "database.db"))
if err != nil {
t.Fatal(err)
}
Expand All @@ -82,8 +92,9 @@ func TestRun(t *testing.T) {
t.Fatal(err)
}

result := struct{ Name string }{}
err = conn.Get(&result, "SELECT name FROM sqlite_master WHERE type='table' AND name='users';")
var name string
row := conn.QueryRow("SELECT name FROM sqlite_master WHERE type='table' AND name='users';")
err = row.Scan(&name)
if err != nil {
t.Fatal("users table not found")
}
Expand Down
4 changes: 1 addition & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ require (
github.com/go-playground/form/v4 v4.2.1
github.com/gofrs/uuid/v5 v5.0.0
github.com/gorilla/sessions v1.2.1
github.com/jmoiron/sqlx v1.3.5
github.com/mattn/go-sqlite3 v1.14.15
github.com/mattn/go-sqlite3 v1.14.22
github.com/stretchr/testify v1.8.4
golang.org/x/sync v0.3.0
)
Expand All @@ -17,7 +16,6 @@ require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gorilla/securecookie v1.1.1 // indirect
github.com/kr/pretty v0.1.0 // indirect
github.com/lib/pq v1.10.9 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/sys v0.21.0 // indirect
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
Expand Down
12 changes: 2 additions & 10 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,19 @@ github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBY
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/form/v4 v4.2.1 h1:HjdRDKO0fftVMU5epjPW2SOREcZ6/wLUzEobqUGJuPw=
github.com/go-playground/form/v4 v4.2.1/go.mod h1:q1a2BY+AQUUzhl6xA/6hBetay6dEIhMHjgvJiGo6K7U=
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/gofrs/uuid/v5 v5.0.0 h1:p544++a97kEL+svbcFbCQVM9KFu0Yo25UoISXGNNH9M=
github.com/gofrs/uuid/v5 v5.0.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI=
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g=
github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/mattn/go-sqlite3 v1.14.15 h1:vfoHhTN1af61xCRSWzFIWzx2YskyMTwHLrExkBOjvxI=
github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
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/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
Expand Down

0 comments on commit 1959fab

Please sign in to comment.