1. change db to sqlc, 2.use repo for db drivers

This commit is contained in:
vinchent 2024-08-01 10:04:50 +02:00
parent cec183b416
commit 459a4e5c7d
12 changed files with 67 additions and 36 deletions

View File

@ -5,11 +5,12 @@ import (
"flag" "flag"
"fmt" "fmt"
"go-udemy-web-1/internal/config" "go-udemy-web-1/internal/config"
"go-udemy-web-1/internal/driver"
"go-udemy-web-1/internal/handlers" "go-udemy-web-1/internal/handlers"
"go-udemy-web-1/internal/helpers" "go-udemy-web-1/internal/helpers"
"go-udemy-web-1/internal/models" "go-udemy-web-1/internal/models"
"go-udemy-web-1/internal/render" "go-udemy-web-1/internal/render"
"go-udemy-web-1/internal/repository"
"go-udemy-web-1/internal/repository/driverrepo"
"log" "log"
"net/http" "net/http"
"os" "os"
@ -50,7 +51,7 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
func run() (*driver.DB, error) { func run() (*repository.DB, error) {
// what am I going to put in the session // what am I going to put in the session
gob.Register(models.Reservation{}) gob.Register(models.Reservation{})
gob.Register(models.User{}) gob.Register(models.User{})
@ -103,7 +104,8 @@ func run() (*driver.DB, error) {
log.Println("Connecting to database...") log.Println("Connecting to database...")
dsn := fmt.Sprintf("host=%s port=%s dbname=%s user=%s password=%s sslmode=%s", dsn := fmt.Sprintf("host=%s port=%s dbname=%s user=%s password=%s sslmode=%s",
*dbHost, *dbPort, *dbName, *dbUser, *dbPass, *dbSSL) *dbHost, *dbPort, *dbName, *dbUser, *dbPass, *dbSSL)
db, err := driver.ConnectSQL(dsn) dbdriver := driverrepo.NewSqlRepo()
db, err := dbdriver.ConnectSQL(dsn)
if err != nil { if err != nil {
log.Fatal("Cannot connect to database! Dying...") log.Fatal("Cannot connect to database! Dying...")
} }

View File

@ -4,7 +4,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"go-udemy-web-1/internal/config" "go-udemy-web-1/internal/config"
"go-udemy-web-1/internal/driver"
"go-udemy-web-1/internal/forms" "go-udemy-web-1/internal/forms"
"go-udemy-web-1/internal/helpers" "go-udemy-web-1/internal/helpers"
"go-udemy-web-1/internal/models" "go-udemy-web-1/internal/models"
@ -30,7 +29,7 @@ type Repository struct {
} }
// NewRepo creates a new repository // NewRepo creates a new repository
func NewRepo(a *config.AppConfig, db *driver.DB) *Repository { func NewRepo(a *config.AppConfig, db *repository.DB) *Repository {
return &Repository{ return &Repository{
App: a, App: a,
DB: dbrepo.NewPostgresRepo(db.SQL, a), DB: dbrepo.NewPostgresRepo(db.SQL, a),

View File

@ -3,8 +3,8 @@ package handlers
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"go-udemy-web-1/internal/driver"
"go-udemy-web-1/internal/models" "go-udemy-web-1/internal/models"
"go-udemy-web-1/internal/repository"
"log" "log"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@ -24,7 +24,7 @@ type postData struct {
// {{{ Test NewRepo // {{{ Test NewRepo
func Test_NewRepo(t *testing.T) { func Test_NewRepo(t *testing.T) {
var db driver.DB var db repository.DB
repo := NewRepo(&app, &db) repo := NewRepo(&app, &db)
if reflect.TypeOf(repo).String() != "*handlers.Repository" { if reflect.TypeOf(repo).String() != "*handlers.Repository" {

View File

@ -4,7 +4,9 @@ import (
"database/sql" "database/sql"
"go-udemy-web-1/internal/config" "go-udemy-web-1/internal/config"
"go-udemy-web-1/internal/repository" "go-udemy-web-1/internal/repository"
"go-udemy-web-1/internal/repository/db" "go-udemy-web-1/internal/repository/sqlc"
"github.com/jackc/pgx/v5"
) )
type postgresDBRepo struct { type postgresDBRepo struct {
@ -14,7 +16,7 @@ type postgresDBRepo struct {
type pgcDBRepo struct { type pgcDBRepo struct {
App *config.AppConfig App *config.AppConfig
Q *db.Queries Q *sqlc.Queries
} }
type testDBRepo struct { type testDBRepo struct {
@ -35,7 +37,8 @@ func NewTestingRepo(a *config.AppConfig) repository.DatabaseRepo {
} }
} }
func NewPgcRepo(q *db.Queries, a *config.AppConfig) repository.DatabaseRepo { func NewPgcRepo(conn *pgx.Conn, a *config.AppConfig) repository.DatabaseRepo {
q := sqlc.New(conn)
return &pgcDBRepo{ return &pgcDBRepo{
App: a, App: a,
Q: q, Q: q,

View File

@ -4,7 +4,7 @@ import (
"context" "context"
"errors" "errors"
"go-udemy-web-1/internal/models" "go-udemy-web-1/internal/models"
"go-udemy-web-1/internal/repository/db" "go-udemy-web-1/internal/repository/sqlc"
"time" "time"
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
@ -21,7 +21,7 @@ func (m *pgcDBRepo) InsertReservation(res models.Reservation) (int, error) {
defer cancel() defer cancel()
var newId int32 var newId int32
newId, err := m.Q.InsertReservation(ctx, db.InsertReservationParams{ newId, err := m.Q.InsertReservation(ctx, sqlc.InsertReservationParams{
FirstName: res.FirstName, FirstName: res.FirstName,
LastName: res.LastName, LastName: res.LastName,
Email: res.Email, Email: res.Email,
@ -44,7 +44,7 @@ func (m *pgcDBRepo) InsertRoomRestriction(r models.RoomRestriction) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel() defer cancel()
err := m.Q.InsertRoomRestriction(ctx, db.InsertRoomRestrictionParams{ err := m.Q.InsertRoomRestriction(ctx, sqlc.InsertRoomRestrictionParams{
StartDate: pgtype.Date{Time: r.StartDate, Valid: true}, StartDate: pgtype.Date{Time: r.StartDate, Valid: true},
EndDate: pgtype.Date{Time: r.EndDate, Valid: true}, EndDate: pgtype.Date{Time: r.EndDate, Valid: true},
RoomID: int32(r.Room.ID), RoomID: int32(r.Room.ID),
@ -64,7 +64,7 @@ func (m *pgcDBRepo) SearchAvailabilityByDatesByRoomID(start, end time.Time, room
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel() defer cancel()
numRows, err := m.Q.SearchAvailabilityByDatesByRoomID(ctx, db.SearchAvailabilityByDatesByRoomIDParams{ numRows, err := m.Q.SearchAvailabilityByDatesByRoomID(ctx, sqlc.SearchAvailabilityByDatesByRoomIDParams{
RoomID: int32(roomID), RoomID: int32(roomID),
EndDate: pgtype.Date{Time: start, Valid: true}, EndDate: pgtype.Date{Time: start, Valid: true},
StartDate: pgtype.Date{Time: end, Valid: false}, StartDate: pgtype.Date{Time: end, Valid: false},
@ -87,7 +87,7 @@ func (m *pgcDBRepo) SearchAvailabilityForAllRooms(start, end time.Time) ([]model
var rooms []models.Room var rooms []models.Room
rows, err := m.Q.SearchAvailabilityForAllRooms(ctx, db.SearchAvailabilityForAllRoomsParams{ rows, err := m.Q.SearchAvailabilityForAllRooms(ctx, sqlc.SearchAvailabilityForAllRoomsParams{
EndDate: pgtype.Date{Time: start, Valid: true}, EndDate: pgtype.Date{Time: start, Valid: true},
StartDate: pgtype.Date{Time: start, Valid: true}, StartDate: pgtype.Date{Time: start, Valid: true},
}) })
@ -153,7 +153,7 @@ func (m *pgcDBRepo) UpdateUser(u models.User) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel() defer cancel()
err := m.Q.UpdateUser(ctx, db.UpdateUserParams{ err := m.Q.UpdateUser(ctx, sqlc.UpdateUserParams{
FirstName: u.FirstName, FirstName: u.FirstName,
LastName: u.LastName, LastName: u.LastName,
Email: u.Email, Email: u.Email,
@ -288,7 +288,7 @@ func (m *pgcDBRepo) UpdateReservation(r models.Reservation) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel() defer cancel()
err := m.Q.UpdateReservation(ctx, db.UpdateReservationParams{ err := m.Q.UpdateReservation(ctx, sqlc.UpdateReservationParams{
ID: int32(r.ID), ID: int32(r.ID),
FirstName: r.FirstName, FirstName: r.FirstName,
LastName: r.LastName, LastName: r.LastName,
@ -320,7 +320,7 @@ func (m *pgcDBRepo) UpdateProcessedForReservation(id, processed int) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel() defer cancel()
err := m.Q.UpdateProcessedForReservation(ctx, db.UpdateProcessedForReservationParams{ err := m.Q.UpdateProcessedForReservation(ctx, sqlc.UpdateProcessedForReservationParams{
Processed: int32(processed), Processed: int32(processed),
ID: int32(id), ID: int32(id),
}) })
@ -358,7 +358,7 @@ func (m *pgcDBRepo) GetRestrictionsForRoomByDate(roomId int, start, end time.Tim
var restrictions []models.RoomRestriction var restrictions []models.RoomRestriction
rows, err := m.Q.GetRestrictionsForRoomByDate(ctx, db.GetRestrictionsForRoomByDateParams{ rows, err := m.Q.GetRestrictionsForRoomByDate(ctx, sqlc.GetRestrictionsForRoomByDateParams{
EndDate: pgtype.Date{Time: end, Valid: true}, EndDate: pgtype.Date{Time: end, Valid: true},
StartDate: pgtype.Date{Time: start, Valid: true}, StartDate: pgtype.Date{Time: start, Valid: true},
RoomID: int32(roomId), RoomID: int32(roomId),
@ -386,7 +386,7 @@ func (m *pgcDBRepo) InsertBlockForRoom(id int, startDate time.Time) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel() defer cancel()
err := m.Q.InsertBlockForRoom(ctx, db.InsertBlockForRoomParams{ err := m.Q.InsertBlockForRoom(ctx, sqlc.InsertBlockForRoomParams{
StartDate: pgtype.Date{Time: startDate, Valid: true}, StartDate: pgtype.Date{Time: startDate, Valid: true},
EndDate: pgtype.Date{Time: startDate.AddDate(0, 0, 1)}, EndDate: pgtype.Date{Time: startDate.AddDate(0, 0, 1)},
RoomID: int32(id), RoomID: int32(id),

View File

@ -0,0 +1,18 @@
package driverrepo
import (
"go-udemy-web-1/internal/repository"
)
type (
sqlDriverRepo struct{}
sqlcDriverRepo struct{}
)
func NewSqlRepo() repository.DatabaseDriverRepo {
return &sqlDriverRepo{}
}
// func NewSqlcRepo() repository.DatabaseDriverRepo {
// return &sqlcDriverRepo{}
// }

View File

@ -1,7 +1,8 @@
package driver package driverrepo
import ( import (
"database/sql" "database/sql"
"go-udemy-web-1/internal/repository"
"time" "time"
_ "github.com/jackc/pgconn" _ "github.com/jackc/pgconn"
@ -9,12 +10,7 @@ import (
_ "github.com/jackc/pgx/v5/stdlib" _ "github.com/jackc/pgx/v5/stdlib"
) )
// DB holds the database connection pool var dbConn = &repository.DB{}
type DB struct {
SQL *sql.DB
}
var dbConn = &DB{}
const ( const (
maxOpenDbConn = 10 maxOpenDbConn = 10
@ -23,8 +19,8 @@ const (
) )
// ConnectSQL creates SQL pool for Postgres // ConnectSQL creates SQL pool for Postgres
func ConnectSQL(dsn string) (*DB, error) { func (s *sqlDriverRepo) ConnectSQL(dsn string) (*repository.DB, error) {
d, err := NewDatabase(dsn) d, err := newDatabase(dsn)
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -51,8 +47,8 @@ func testDB(d *sql.DB) error {
return nil return nil
} }
// NewDatabase creates a new datavase for the application // newDatabase creates a new database for the application
func NewDatabase(dsn string) (*sql.DB, error) { func newDatabase(dsn string) (*sql.DB, error) {
db, err := sql.Open("pgx", dsn) db, err := sql.Open("pgx", dsn)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -1,8 +1,11 @@
package repository package repository
import ( import (
"database/sql"
"go-udemy-web-1/internal/models" "go-udemy-web-1/internal/models"
"time" "time"
"github.com/jackc/pgx/v5"
) )
type DatabaseRepo interface { type DatabaseRepo interface {
@ -27,3 +30,13 @@ type DatabaseRepo interface {
InsertBlockForRoom(id int, startDate time.Time) error InsertBlockForRoom(id int, startDate time.Time) error
DeleteBlockByID(id int) error DeleteBlockByID(id int) error
} }
// DB holds the database connection pool
type DB struct {
SQL *sql.DB
PG *pgx.Conn
}
type DatabaseDriverRepo interface {
ConnectSQL(dsn string) (*DB, error)
}

View File

@ -2,7 +2,7 @@
// versions: // versions:
// sqlc v1.26.0 // sqlc v1.26.0
package db package sqlc
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// versions: // versions:
// sqlc v1.26.0 // sqlc v1.26.0
package db package sqlc
import ( import (
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"

View File

@ -3,7 +3,7 @@
// sqlc v1.26.0 // sqlc v1.26.0
// source: query.sql // source: query.sql
package db package sqlc
import ( import (
"context" "context"

View File

@ -5,6 +5,6 @@ sql:
schema: "sql/schema.sql" schema: "sql/schema.sql"
gen: gen:
go: go:
package: "db" package: "sqlc"
out: "internal/repository/db" out: "internal/repository/sqlc"
sql_package: "pgx/v5" sql_package: "pgx/v5"