github.com/Elate-DevOps/migrate/v4@v4.0.12/database/postgres/postgres.go (about)

     1  //go:build go1.9
     2  // +build go1.9
     3  
     4  package postgres
     5  
     6  import (
     7  	"context"
     8  	"database/sql"
     9  	"fmt"
    10  	"io"
    11  	nurl "net/url"
    12  	"regexp"
    13  	"strconv"
    14  	"strings"
    15  	"time"
    16  
    17  	"go.uber.org/atomic"
    18  
    19  	"github.com/Elate-DevOps/migrate/v4"
    20  	"github.com/Elate-DevOps/migrate/v4/database"
    21  	"github.com/Elate-DevOps/migrate/v4/database/multistmt"
    22  	"github.com/hashicorp/go-multierror"
    23  	"github.com/lib/pq"
    24  )
    25  
    26  func init() {
    27  	db := Postgres{}
    28  	database.Register("postgres", &db)
    29  	database.Register("postgresql", &db)
    30  }
    31  
    32  var (
    33  	multiStmtDelimiter = []byte(";")
    34  
    35  	DefaultMigrationsTable       = "schema_migrations"
    36  	DefaultMultiStatementMaxSize = 10 * 1 << 20 // 10 MB
    37  )
    38  
    39  var (
    40  	ErrNilConfig      = fmt.Errorf("no config")
    41  	ErrNoDatabaseName = fmt.Errorf("no database name")
    42  	ErrNoSchema       = fmt.Errorf("no schema")
    43  	ErrDatabaseDirty  = fmt.Errorf("database is dirty")
    44  )
    45  
    46  type Config struct {
    47  	MigrationsTable       string
    48  	MigrationsTableQuoted bool
    49  	MultiStatementEnabled bool
    50  	DatabaseName          string
    51  	SchemaName            string
    52  	migrationsSchemaName  string
    53  	migrationsTableName   string
    54  	StatementTimeout      time.Duration
    55  	MultiStatementMaxSize int
    56  }
    57  
    58  type Postgres struct {
    59  	// Locking and unlocking need to use the same connection
    60  	conn     *sql.Conn
    61  	db       *sql.DB
    62  	isLocked atomic.Bool
    63  
    64  	// Open and WithInstance need to guarantee that config is never nil
    65  	config *Config
    66  }
    67  
    68  func WithConnection(ctx context.Context, conn *sql.Conn, config *Config) (*Postgres, error) {
    69  	if config == nil {
    70  		return nil, ErrNilConfig
    71  	}
    72  
    73  	if err := conn.PingContext(ctx); err != nil {
    74  		return nil, err
    75  	}
    76  
    77  	if config.DatabaseName == "" {
    78  		query := `SELECT CURRENT_DATABASE()`
    79  		var databaseName string
    80  		if err := conn.QueryRowContext(ctx, query).Scan(&databaseName); err != nil {
    81  			return nil, &database.Error{OrigErr: err, Query: []byte(query)}
    82  		}
    83  
    84  		if len(databaseName) == 0 {
    85  			return nil, ErrNoDatabaseName
    86  		}
    87  
    88  		config.DatabaseName = databaseName
    89  	}
    90  
    91  	if len(config.MigrationsTable) == 0 {
    92  		config.MigrationsTable = DefaultMigrationsTable
    93  	}
    94  
    95  	config.migrationsTableName = config.MigrationsTable
    96  	if config.MigrationsTableQuoted {
    97  		re := regexp.MustCompile(`"(.*?)"`)
    98  		result := re.FindAllStringSubmatch(config.MigrationsTable, -1)
    99  		config.migrationsTableName = result[len(result)-1][1]
   100  		if len(result) > 1 {
   101  			return nil, fmt.Errorf("\"%s\" MigrationsTable contains too many dot characters", config.MigrationsTable)
   102  		}
   103  	}
   104  
   105  	px := &Postgres{
   106  		conn:   conn,
   107  		config: config,
   108  	}
   109  
   110  	if err := px.ensureVersionTable(); err != nil {
   111  		return nil, err
   112  	}
   113  
   114  	return px, nil
   115  }
   116  
   117  func WithInstance(instance *sql.DB, config *Config) (database.Driver, error) {
   118  	ctx := context.Background()
   119  
   120  	if err := instance.Ping(); err != nil {
   121  		return nil, err
   122  	}
   123  
   124  	conn, err := instance.Conn(ctx)
   125  	if err != nil {
   126  		return nil, err
   127  	}
   128  
   129  	px, err := WithConnection(ctx, conn, config)
   130  	if err != nil {
   131  		return nil, err
   132  	}
   133  	px.db = instance
   134  	return px, nil
   135  }
   136  
   137  func (p *Postgres) Open(url string) (database.Driver, error) {
   138  	purl, err := nurl.Parse(url)
   139  	if err != nil {
   140  		return nil, err
   141  	}
   142  
   143  	db, err := sql.Open("postgres", migrate.FilterCustomQuery(purl).String())
   144  	if err != nil {
   145  		return nil, err
   146  	}
   147  
   148  	migrationsTable := purl.Query().Get("x-migrations-table")
   149  	migrationsTableQuoted := false
   150  	if s := purl.Query().Get("x-migrations-table-quoted"); len(s) > 0 {
   151  		migrationsTableQuoted, err = strconv.ParseBool(s)
   152  		if err != nil {
   153  			return nil, fmt.Errorf("Unable to parse option x-migrations-table-quoted: %w", err)
   154  		}
   155  	}
   156  	if (len(migrationsTable) > 0) && (migrationsTableQuoted) && ((migrationsTable[0] != '"') || (migrationsTable[len(migrationsTable)-1] != '"')) {
   157  		return nil, fmt.Errorf("x-migrations-table must be quoted (for instance '\"migrate\".\"schema_migrations\"') when x-migrations-table-quoted is enabled, current value is: %s", migrationsTable)
   158  	}
   159  
   160  	statementTimeoutString := purl.Query().Get("x-statement-timeout")
   161  	statementTimeout := 0
   162  	if statementTimeoutString != "" {
   163  		statementTimeout, err = strconv.Atoi(statementTimeoutString)
   164  		if err != nil {
   165  			return nil, err
   166  		}
   167  	}
   168  
   169  	multiStatementMaxSize := DefaultMultiStatementMaxSize
   170  	if s := purl.Query().Get("x-multi-statement-max-size"); len(s) > 0 {
   171  		multiStatementMaxSize, err = strconv.Atoi(s)
   172  		if err != nil {
   173  			return nil, err
   174  		}
   175  		if multiStatementMaxSize <= 0 {
   176  			multiStatementMaxSize = DefaultMultiStatementMaxSize
   177  		}
   178  	}
   179  
   180  	multiStatementEnabled := false
   181  	if s := purl.Query().Get("x-multi-statement"); len(s) > 0 {
   182  		multiStatementEnabled, err = strconv.ParseBool(s)
   183  		if err != nil {
   184  			return nil, fmt.Errorf("Unable to parse option x-multi-statement: %w", err)
   185  		}
   186  	}
   187  
   188  	px, err := WithInstance(db, &Config{
   189  		DatabaseName:          purl.Path,
   190  		MigrationsTable:       migrationsTable,
   191  		MigrationsTableQuoted: migrationsTableQuoted,
   192  		StatementTimeout:      time.Duration(statementTimeout) * time.Millisecond,
   193  		MultiStatementEnabled: multiStatementEnabled,
   194  		MultiStatementMaxSize: multiStatementMaxSize,
   195  	})
   196  	if err != nil {
   197  		return nil, err
   198  	}
   199  
   200  	return px, nil
   201  }
   202  
   203  func (p *Postgres) Close() error {
   204  	connErr := p.conn.Close()
   205  	var dbErr error
   206  	if p.db != nil {
   207  		dbErr = p.db.Close()
   208  	}
   209  
   210  	if connErr != nil || dbErr != nil {
   211  		return fmt.Errorf("conn: %v, db: %v", connErr, dbErr)
   212  	}
   213  	return nil
   214  }
   215  
   216  // https://www.postgresql.org/docs/9.6/static/explicit-locking.html#ADVISORY-LOCKS
   217  func (p *Postgres) Lock() error {
   218  	// return database.CasRestoreOnErr(&p.isLocked, false, true, database.ErrLocked, func() error {
   219  	// 	aid, err := database.GenerateAdvisoryLockId(p.config.DatabaseName, p.config.migrationsSchemaName, p.config.migrationsTableName)
   220  	// 	if err != nil {
   221  	// 		return err
   222  	// 	}
   223  
   224  	// 	// This will wait indefinitely until the lock can be acquired.
   225  	// 	query := `SELECT pg_advisory_lock($1)`
   226  	// 	if _, err := p.conn.ExecContext(context.Background(), query, aid); err != nil {
   227  	// 		return &database.Error{OrigErr: err, Err: "try lock failed", Query: []byte(query)}
   228  	// 	}
   229  
   230  	// 	return nil
   231  	// })
   232  	return nil
   233  }
   234  
   235  func (p *Postgres) Unlock() error {
   236  	// return database.CasRestoreOnErr(&p.isLocked, true, false, database.ErrNotLocked, func() error {
   237  	// 	aid, err := database.GenerateAdvisoryLockId(p.config.DatabaseName, p.config.migrationsSchemaName, p.config.migrationsTableName)
   238  	// 	if err != nil {
   239  	// 		return err
   240  	// 	}
   241  
   242  	// 	query := `SELECT pg_advisory_unlock($1)`
   243  	// 	if _, err := p.conn.ExecContext(context.Background(), query, aid); err != nil {
   244  	// 		return &database.Error{OrigErr: err, Query: []byte(query)}
   245  	// 	}
   246  	// 	return nil
   247  	// })
   248  	return nil
   249  }
   250  
   251  func (p *Postgres) Run(migration io.Reader) error {
   252  	if p.config.MultiStatementEnabled {
   253  		var err error
   254  		if e := multistmt.Parse(migration, multiStmtDelimiter, p.config.MultiStatementMaxSize, func(m []byte) bool {
   255  			if err = p.runStatement(m); err != nil {
   256  				return false
   257  			}
   258  			return true
   259  		}); e != nil {
   260  			return e
   261  		}
   262  		return err
   263  	}
   264  	migr, err := io.ReadAll(migration)
   265  	if err != nil {
   266  		return err
   267  	}
   268  	return p.runStatement(migr)
   269  }
   270  
   271  func (p *Postgres) runStatement(statement []byte) error {
   272  	ctx := context.Background()
   273  	if p.config.StatementTimeout != 0 {
   274  		var cancel context.CancelFunc
   275  		ctx, cancel = context.WithTimeout(ctx, p.config.StatementTimeout)
   276  		defer cancel()
   277  	}
   278  	query := string(statement)
   279  	if strings.TrimSpace(query) == "" {
   280  		return nil
   281  	}
   282  	if _, err := p.conn.ExecContext(ctx, query); err != nil {
   283  		if pgErr, ok := err.(*pq.Error); ok {
   284  			var line uint
   285  			var col uint
   286  			var lineColOK bool
   287  			if pgErr.Position != "" {
   288  				if pos, err := strconv.ParseUint(pgErr.Position, 10, 64); err == nil {
   289  					line, col, lineColOK = computeLineFromPos(query, int(pos))
   290  				}
   291  			}
   292  			message := fmt.Sprintf("migration failed: %s", pgErr.Message)
   293  			if lineColOK {
   294  				message = fmt.Sprintf("%s (column %d)", message, col)
   295  			}
   296  			if pgErr.Detail != "" {
   297  				message = fmt.Sprintf("%s, %s", message, pgErr.Detail)
   298  			}
   299  			return database.Error{OrigErr: err, Err: message, Query: statement, Line: line}
   300  		}
   301  		return database.Error{OrigErr: err, Err: "migration failed", Query: statement}
   302  	}
   303  	return nil
   304  }
   305  
   306  func computeLineFromPos(s string, pos int) (line uint, col uint, ok bool) {
   307  	// replace crlf with lf
   308  	s = strings.Replace(s, "\r\n", "\n", -1)
   309  	// pg docs: pos uses index 1 for the first character, and positions are measured in characters not bytes
   310  	runes := []rune(s)
   311  	if pos > len(runes) {
   312  		return 0, 0, false
   313  	}
   314  	sel := runes[:pos]
   315  	line = uint(runesCount(sel, newLine) + 1)
   316  	col = uint(pos - 1 - runesLastIndex(sel, newLine))
   317  	return line, col, true
   318  }
   319  
   320  const newLine = '\n'
   321  
   322  func runesCount(input []rune, target rune) int {
   323  	var count int
   324  	for _, r := range input {
   325  		if r == target {
   326  			count++
   327  		}
   328  	}
   329  	return count
   330  }
   331  
   332  func runesLastIndex(input []rune, target rune) int {
   333  	for i := len(input) - 1; i >= 0; i-- {
   334  		if input[i] == target {
   335  			return i
   336  		}
   337  	}
   338  	return -1
   339  }
   340  
   341  func (p *Postgres) SetVersion(version int, dirty bool) error {
   342  	tx, err := p.conn.BeginTx(context.Background(), &sql.TxOptions{})
   343  	if err != nil {
   344  		return &database.Error{OrigErr: err, Err: "transaction start failed"}
   345  	}
   346  
   347  	query := `TRUNCATE ` + pq.QuoteIdentifier(p.config.migrationsTableName)
   348  	if _, err := tx.Exec(query); err != nil {
   349  		if errRollback := tx.Rollback(); errRollback != nil {
   350  			err = multierror.Append(err, errRollback)
   351  		}
   352  		return &database.Error{OrigErr: err, Query: []byte(query)}
   353  	}
   354  
   355  	// Also re-write the schema version for nil dirty versions to prevent
   356  	// empty schema version for failed down migration on the first migration
   357  	// See: https://github.com/golang-migrate/migrate/issues/330
   358  	if version >= 0 || (version == database.NilVersion && dirty) {
   359  		query = `INSERT INTO ` + pq.QuoteIdentifier(p.config.migrationsTableName) + ` (version, dirty) VALUES ($1, $2)`
   360  		if _, err := tx.Exec(query, version, dirty); err != nil {
   361  			if errRollback := tx.Rollback(); errRollback != nil {
   362  				err = multierror.Append(err, errRollback)
   363  			}
   364  			return &database.Error{OrigErr: err, Query: []byte(query)}
   365  		}
   366  	}
   367  
   368  	if err := tx.Commit(); err != nil {
   369  		return &database.Error{OrigErr: err, Err: "transaction commit failed"}
   370  	}
   371  
   372  	return nil
   373  }
   374  
   375  func (p *Postgres) Version() (version int, dirty bool, err error) {
   376  	query := `SELECT version, dirty FROM ` + pq.QuoteIdentifier(p.config.migrationsTableName) + ` LIMIT 1`
   377  	err = p.conn.QueryRowContext(context.Background(), query).Scan(&version, &dirty)
   378  	switch {
   379  	case err == sql.ErrNoRows:
   380  		return database.NilVersion, false, nil
   381  
   382  	case err != nil:
   383  		if e, ok := err.(*pq.Error); ok {
   384  			if e.Code.Name() == "undefined_table" {
   385  				return database.NilVersion, false, nil
   386  			}
   387  		}
   388  		return 0, false, &database.Error{OrigErr: err, Query: []byte(query)}
   389  
   390  	default:
   391  		return version, dirty, nil
   392  	}
   393  }
   394  
   395  func (p *Postgres) Drop() (err error) {
   396  	// select all tables in current schema
   397  	query := `SELECT table_name FROM information_schema.tables WHERE table_type='BASE TABLE'`
   398  	tables, err := p.conn.QueryContext(context.Background(), query)
   399  	if err != nil {
   400  		return &database.Error{OrigErr: err, Query: []byte(query)}
   401  	}
   402  	defer func() {
   403  		if errClose := tables.Close(); errClose != nil {
   404  			err = multierror.Append(err, errClose)
   405  		}
   406  	}()
   407  
   408  	// delete one table after another
   409  	tableNames := make([]string, 0)
   410  	for tables.Next() {
   411  		var tableName string
   412  		if err := tables.Scan(&tableName); err != nil {
   413  			return err
   414  		}
   415  		if len(tableName) > 0 {
   416  			tableNames = append(tableNames, tableName)
   417  		}
   418  	}
   419  	if err := tables.Err(); err != nil {
   420  		return &database.Error{OrigErr: err, Query: []byte(query)}
   421  	}
   422  
   423  	if len(tableNames) > 0 {
   424  		// delete one by one ...
   425  		for _, t := range tableNames {
   426  			query = `DROP TABLE ` + pq.QuoteIdentifier(t) + ` CASCADE`
   427  			if _, err := p.conn.ExecContext(context.Background(), query); err != nil {
   428  				return &database.Error{OrigErr: err, Query: []byte(query)}
   429  			}
   430  		}
   431  	}
   432  
   433  	return nil
   434  }
   435  
   436  // ensureVersionTable checks if versions table exists and, if not, creates it.
   437  // Note that this function locks the database, which deviates from the usual
   438  // convention of "caller locks" in the Postgres type.
   439  func (p *Postgres) ensureVersionTable() (err error) {
   440  	// if err = p.Lock(); err != nil {
   441  	// 	return err
   442  	// }
   443  
   444  	// defer func() {
   445  	// 	if e := p.Unlock(); e != nil {
   446  	// 		if err == nil {
   447  	// 			err = e
   448  	// 		} else {
   449  	// 			err = multierror.Append(err, e)
   450  	// 		}
   451  	// 	}
   452  	// }()
   453  
   454  	// This block checks whether the `MigrationsTable` already exists. This is useful because it allows read only postgres
   455  	// users to also check the current version of the schema. Previously, even if `MigrationsTable` existed, the
   456  	// `CREATE TABLE IF NOT EXISTS...` query would fail because the user does not have the CREATE permission.
   457  	// Taken from https://github.com/mattes/migrate/blob/master/database/postgres/postgres.go#L258
   458  	query := `SELECT COUNT(1) FROM information_schema.tables WHERE table_name = $1 LIMIT 1`
   459  	row := p.conn.QueryRowContext(context.Background(), query, p.config.migrationsTableName)
   460  
   461  	var count int
   462  	err = row.Scan(&count)
   463  	if err != nil {
   464  		return &database.Error{OrigErr: err, Query: []byte(query)}
   465  	}
   466  
   467  	if count == 1 {
   468  		return nil
   469  	}
   470  
   471  	query = `CREATE TABLE IF NOT EXISTS ` + pq.QuoteIdentifier(p.config.migrationsTableName) + ` (version bigint not null primary key, dirty boolean not null)`
   472  	if _, err = p.conn.ExecContext(context.Background(), query); err != nil {
   473  		return &database.Error{OrigErr: err, Query: []byte(query)}
   474  	}
   475  
   476  	return nil
   477  }