Add db
This commit is contained in:
29
api/internal/app/persistence/database.go
Normal file
29
api/internal/app/persistence/database.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package persistence
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"downloader/internal/app/persistence/migrations"
|
||||
"github.com/uptrace/bun"
|
||||
"github.com/uptrace/bun/dialect/pgdialect"
|
||||
"github.com/uptrace/bun/driver/pgdriver"
|
||||
"github.com/uptrace/bun/extra/bundebug"
|
||||
"github.com/uptrace/bun/migrate"
|
||||
)
|
||||
|
||||
func NewPostgresDB() *bun.DB {
|
||||
dsn := "postgres://downloader:downloadersecret@localhost:5432/downloader?sslmode=disable"
|
||||
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))
|
||||
|
||||
db := bun.NewDB(sqldb, pgdialect.New())
|
||||
db.AddQueryHook(bundebug.NewQueryHook(
|
||||
bundebug.WithVerbose(true),
|
||||
bundebug.FromEnv("BUNDEBUG")))
|
||||
|
||||
migrator := migrate.NewMigrator(db, migrations.Migrations)
|
||||
bgCtx := context.Background()
|
||||
migrator.Init(bgCtx)
|
||||
migrator.Migrate(bgCtx)
|
||||
|
||||
return db
|
||||
}
|
@@ -0,0 +1,27 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"context"
|
||||
"downloader/internal/core/ports/download_request/sql"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Migrations.MustRegister(func(ctx context.Context, db *bun.DB) error {
|
||||
_, err := db.Exec(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp";`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
db.RegisterModel((*sql.Download)(nil))
|
||||
_, err = db.NewCreateTable().
|
||||
Model((*sql.Download)(nil)).
|
||||
Exec(ctx)
|
||||
return err
|
||||
}, func(ctx context.Context, db *bun.DB) error {
|
||||
_, err := db.NewDropTable().
|
||||
Model((*sql.Download)(nil)).
|
||||
Exec(ctx)
|
||||
return err
|
||||
})
|
||||
}
|
17
api/internal/app/persistence/migrations/main.go
Normal file
17
api/internal/app/persistence/migrations/main.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"github.com/uptrace/bun/migrate"
|
||||
)
|
||||
|
||||
var Migrations = migrate.NewMigrations()
|
||||
|
||||
// go:embed *.sql
|
||||
var sqlMigrations embed.FS
|
||||
|
||||
func init() {
|
||||
if err := Migrations.Discover(sqlMigrations); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user