202412212345_fix_types.go raw

   1  package migrations
   2  
   3  import (
   4  	"github.com/go-gormigrate/gormigrate/v2"
   5  	"gorm.io/gorm"
   6  )
   7  
   8  // This migration fixes column types for Postgres compatibility.
   9  //
  10  // First, an autoincrement sequence is created for user_configs.id (this works
  11  // in sqlite, because an integer primary key becomes "autoincrement"
  12  // automatically).
  13  //
  14  // Second, user_configs.encrypted is converted into a boolean; otherwise,
  15  // it fails to de/serialize from/to the Go model's `Encrypted bool` field.
  16  // Again, this happens to work in sqlite due to the way booleans are handled
  17  // (they're just an alias for numeric).
  18  var _202412212345_fix_types = &gormigrate.Migration{
  19  	ID: "20241221234500_fix_types",
  20  	Migrate: func(tx *gorm.DB) error {
  21  		if tx.Dialector.Name() == "postgres" {
  22  			err := tx.Exec(`
  23  CREATE SEQUENCE user_configs_id_seq;
  24  ALTER TABLE user_configs ALTER COLUMN id SET DEFAULT nextval('user_configs_id_seq');
  25  ALTER SEQUENCE user_configs_id_seq OWNED BY user_configs.id;
  26  ALTER TABLE user_configs ALTER COLUMN encrypted SET DATA TYPE BOOLEAN USING encrypted::integer::boolean; 
  27  `).Error
  28  			if err != nil {
  29  				return err
  30  			}
  31  		}
  32  		return nil
  33  	},
  34  	Rollback: func(tx *gorm.DB) error {
  35  		return nil
  36  	},
  37  }
  38