github.com/Redstoneguy129/cli@v0.0.0-20230211220159-15dca4e91917/internal/migration/repair/repair.go (about)

     1  package repair
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  
     8  	"github.com/Redstoneguy129/cli/internal/utils"
     9  	"github.com/jackc/pgconn"
    10  	"github.com/jackc/pgtype"
    11  	"github.com/jackc/pgx/v4"
    12  )
    13  
    14  const (
    15  	Applied  = "applied"
    16  	Reverted = "reverted"
    17  )
    18  
    19  const (
    20  	CREATE_VERSION_SCHEMA    = "CREATE SCHEMA IF NOT EXISTS supabase_migrations"
    21  	CREATE_VERSION_TABLE     = "CREATE TABLE IF NOT EXISTS supabase_migrations.schema_migrations (version text NOT NULL PRIMARY KEY)"
    22  	INSERT_MIGRATION_VERSION = "INSERT INTO supabase_migrations.schema_migrations(version) VALUES($1)"
    23  	DELETE_MIGRATION_VERSION = "DELETE FROM supabase_migrations.schema_migrations WHERE version = $1"
    24  	CREATE_MIGRATION_TABLE   = CREATE_VERSION_SCHEMA + ";" + CREATE_VERSION_TABLE
    25  )
    26  
    27  func Run(ctx context.Context, username, password, database, host, version, status string, options ...func(*pgx.ConnConfig)) error {
    28  	conn, err := utils.ConnectRemotePostgres(ctx, username, password, database, host, options...)
    29  	if err != nil {
    30  		return err
    31  	}
    32  	defer conn.Close(context.Background())
    33  	// Create history table if not exists
    34  	batch := pgconn.Batch{}
    35  	batch.ExecParams(CREATE_VERSION_SCHEMA, nil, nil, nil, nil)
    36  	batch.ExecParams(CREATE_VERSION_TABLE, nil, nil, nil, nil)
    37  	// Update migration history
    38  	switch status {
    39  	case Applied:
    40  		InsertVersionSQL(&batch, version)
    41  	case Reverted:
    42  		DeleteVersionSQL(&batch, version)
    43  	}
    44  	if _, err = conn.PgConn().ExecBatch(ctx, &batch).ReadAll(); err != nil {
    45  		return err
    46  	}
    47  	fmt.Fprintln(os.Stderr, "Repaired migration history:", version, "=>", status)
    48  	return nil
    49  }
    50  
    51  func InsertVersionSQL(batch *pgconn.Batch, version string) {
    52  	updateVersionSQL(batch, INSERT_MIGRATION_VERSION, version)
    53  }
    54  
    55  func DeleteVersionSQL(batch *pgconn.Batch, version string) {
    56  	updateVersionSQL(batch, DELETE_MIGRATION_VERSION, version)
    57  }
    58  
    59  func updateVersionSQL(batch *pgconn.Batch, sql, version string) {
    60  	batch.ExecParams(
    61  		sql,
    62  		[][]byte{[]byte(version)},
    63  		[]uint32{pgtype.TextOID},
    64  		[]int16{pgtype.TextFormatCode},
    65  		nil,
    66  	)
    67  }