package db import ( "context" "crypto/rand" "embed" "encoding/hex" "fmt" "io/fs" "sort" "strconv" "sync/atomic" "time" "cotizador/internal/config" "github.com/jackc/pgx/v5/pgxpool" ) //go:embed migrations/*.sql var migrationsFS embed.FS var idCounter uint64 // NewID generates a URL-safe, sortable, collision-resistant CUID-like identifier // (e.g. "c" + base36 timestamp + counter + random hex, 25 chars). func NewID() string { ts := strconv.FormatInt(time.Now().UnixMilli(), 36) cnt := strconv.FormatUint(atomic.AddUint64(&idCounter, 1)%1679616, 36) var b [8]byte _, _ = rand.Read(b[:]) return "c" + ts + cnt + hex.EncodeToString(b[:])[:12] } // Connect opens a pgxpool using individual connection parameters (matching the // existing Docker/Coolify environment without SCRAM URL-encoding issues). func Connect(ctx context.Context, cfg *config.Config) (*pgxpool.Pool, error) { poolCfg, err := pgxpool.ParseConfig("") if err != nil { return nil, err } poolCfg.ConnConfig.Host = cfg.DBHost poolCfg.ConnConfig.Port = uint16(cfg.DBPort) poolCfg.ConnConfig.User = cfg.DBUser poolCfg.ConnConfig.Password = cfg.DBPassword poolCfg.ConnConfig.Database = cfg.DBName poolCfg.MaxConns = 20 poolCfg.MinConns = 2 poolCfg.MaxConnLifetime = 30 * time.Minute poolCfg.MaxConnIdleTime = 5 * time.Minute pool, err := pgxpool.NewWithConfig(ctx, poolCfg) if err != nil { return nil, fmt.Errorf("error conectando a PostgreSQL: %w", err) } if err := pool.Ping(ctx); err != nil { pool.Close() return nil, fmt.Errorf("error haciendo ping a PostgreSQL (%s:%d/%s): %w", cfg.DBHost, cfg.DBPort, cfg.DBName, err) } return pool, nil } // Migrate runs embedded idempotent SQL migrations and tracks applied files in `_go_migrations`. func Migrate(ctx context.Context, pool *pgxpool.Pool) error { _, err := pool.Exec(ctx, ` CREATE TABLE IF NOT EXISTS "_go_migrations" ( "name" TEXT PRIMARY KEY, "appliedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP ) `) if err != nil { return fmt.Errorf("error creando tabla _go_migrations: %w", err) } entries, err := fs.ReadDir(migrationsFS, "migrations") if err != nil { return fmt.Errorf("error leyendo migraciones embebidas: %w", err) } sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() }) for _, e := range entries { if e.IsDir() { continue } name := e.Name() var exists bool if err := pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM "_go_migrations" WHERE "name" = $1)`, name).Scan(&exists); err != nil { return fmt.Errorf("error verificando migracion %s: %w", name, err) } if exists { continue } sqlBytes, err := migrationsFS.ReadFile("migrations/" + name) if err != nil { return fmt.Errorf("error leyendo %s: %w", name, err) } tx, err := pool.Begin(ctx) if err != nil { return err } if _, err := tx.Exec(ctx, string(sqlBytes)); err != nil { _ = tx.Rollback(ctx) return fmt.Errorf("error ejecutando migracion %s: %w", name, err) } if _, err := tx.Exec(ctx, `INSERT INTO "_go_migrations" ("name") VALUES ($1)`, name); err != nil { _ = tx.Rollback(ctx) return fmt.Errorf("error registrando migracion %s: %w", name, err) } if err := tx.Commit(ctx); err != nil { return err } } return nil }