56 lines
1.1 KiB
Go
56 lines
1.1 KiB
Go
package sys
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"log"
|
|
"os"
|
|
|
|
entsql "entgo.io/ent/dialect/sql"
|
|
|
|
"entgo.io/ent/dialect"
|
|
"github.com/FrankenBotDev/FrankenAPI/ent"
|
|
"github.com/FrankenBotDev/FrankenAPI/ent/migrate"
|
|
)
|
|
|
|
type ContextKey string
|
|
|
|
const (
|
|
EntClientKey = ContextKey("ent_client")
|
|
)
|
|
|
|
const (
|
|
ContextClientKey = ContextKey("ent_context")
|
|
)
|
|
|
|
// InitDB handles postgres client creation
|
|
func InitDB() (*ent.Client, context.Context) {
|
|
client := open(os.Getenv("DATABASE")) // TODO move this to config
|
|
ctx := context.Background()
|
|
if err := client.Schema.Create(ctx); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
// Run migration.
|
|
err := client.Schema.Create(
|
|
ctx,
|
|
migrate.WithDropIndex(true),
|
|
migrate.WithDropColumn(true),
|
|
)
|
|
if err != nil {
|
|
log.Fatalf("failed creating schema resources: %v", err)
|
|
}
|
|
return client, ctx
|
|
}
|
|
|
|
// open establishes a postgres connection and returns a client
|
|
func open(databaseUrl string) *ent.Client {
|
|
db, err := sql.Open("pgx", databaseUrl)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
drv := entsql.OpenDB(dialect.Postgres, db)
|
|
return ent.NewClient(ent.Driver(drv))
|
|
}
|