mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
61 lines
1.6 KiB
Go
61 lines
1.6 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
"os"
|
|
)
|
|
|
|
const (
|
|
productPresaleMigrationFile = "008_product_presale_delivery_purchase_limit.sql"
|
|
productPresaleMigrationLockID = 904_120_008
|
|
)
|
|
|
|
// ApplyProductPresaleMigration executes the release SQL before the product
|
|
// service begins serving traffic. The migration itself is idempotent; the
|
|
// advisory lock only serializes concurrent replicas during deployment.
|
|
func ApplyProductPresaleMigration(ctx context.Context, db *sql.DB) error {
|
|
if db == nil {
|
|
return fmt.Errorf("database is required")
|
|
}
|
|
|
|
ddl, err := readProductPresaleMigration()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
conn, err := db.Conn(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("acquire product presale migration connection: %w", err)
|
|
}
|
|
defer conn.Close()
|
|
if _, err := conn.ExecContext(ctx, "SELECT pg_advisory_lock($1)", productPresaleMigrationLockID); err != nil {
|
|
return fmt.Errorf("lock product presale migration: %w", err)
|
|
}
|
|
defer func() {
|
|
_, _ = conn.ExecContext(context.Background(), "SELECT pg_advisory_unlock($1)", productPresaleMigrationLockID)
|
|
}()
|
|
|
|
if _, err := conn.ExecContext(ctx, string(ddl)); err != nil {
|
|
return fmt.Errorf("apply product presale migration: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func readProductPresaleMigration() ([]byte, error) {
|
|
paths := []string{
|
|
"scripts/sql/" + productPresaleMigrationFile,
|
|
"/app/migrations/" + productPresaleMigrationFile,
|
|
}
|
|
var lastErr error
|
|
for _, path := range paths {
|
|
contents, err := os.ReadFile(path)
|
|
if err == nil {
|
|
return contents, nil
|
|
}
|
|
lastErr = err
|
|
}
|
|
return nil, fmt.Errorf("read product presale migration: %w", lastErr)
|
|
}
|