46 lines
995 B
Go
46 lines
995 B
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"embed"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
//go:embed migrations/*.sql
|
|
var migrationFS embed.FS
|
|
|
|
func Connect(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
|
pool, err := pgxpool.New(ctx, databaseURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("подключение к PostgreSQL: %w", err)
|
|
}
|
|
if err := pool.Ping(ctx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("ping PostgreSQL: %w", err)
|
|
}
|
|
return pool, nil
|
|
}
|
|
|
|
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
|
entries, err := migrationFS.ReadDir("migrations")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, e := range entries {
|
|
if e.IsDir() || !strings.HasSuffix(e.Name(), ".sql") {
|
|
continue
|
|
}
|
|
data, err := migrationFS.ReadFile("migrations/" + e.Name())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := pool.Exec(ctx, string(data)); err != nil {
|
|
return fmt.Errorf("миграция %s: %w", e.Name(), err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|