migrate

package
v0.0.0-...-8d6936c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 29, 2024 License: AGPL-3.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Command = &cli.Command{
	Name:  "migrate",
	Usage: "Run database migrations",
	Subcommands: []*cli.Command{
		{
			Name: "new",
			Action: func(ctx *cli.Context) error {
				folder, err := os.Open("./migrations/")
				if err != nil {
					return err
				}
				files, err := folder.Readdirnames(0)
				if err != nil {
					return err
				}
				sort.Strings(files)

				last := files[len(files)-1]
				n := strings.Index(last, "_")
				if n < 0 {
					return errors.New("no underscore found in last filename")
				}
				lastVersion, err := strconv.Atoi(last[0:n])
				if err != nil {
					return err
				}

				scanner := bufio.NewScanner(os.Stdin)
				fmt.Print("New migration name: ")
				scanner.Scan()
				name := strings.TrimSpace(scanner.Text())
				if name == "" {
					return errors.New("migration name cannot be empty")
				}
				newVersion := strconv.Itoa(lastVersion + 1)
				for i := len(newVersion); i < 4; i++ {
					newVersion = "0" + newVersion
				}
				name = newVersion + "_" + strings.ToLower(strings.ReplaceAll(name, " ", "_"))
				newFiles := []string{name + ".down.sql", name + ".up.sql"}
				for _, name := range newFiles {
					file, err := os.Create("./migrations/" + name)
					if err != nil {
						return err
					}
					if err := file.Close(); err != nil {
						return err
					}
				}
				fmt.Print("Created migration!")
				return nil
			},
		},
		{
			Name:  "run",
			Usage: "Run database migrations",
			Flags: []cli.Flag{
				&cli.Int64Flag{
					Name:  "steps",
					Usage: "Migrations steps to run (0 runs all migrations, and value can be negative)",
				},
			},
			Action: MigrateCLIWrapper,
		},
	},
}
View Source
var (
	ErrMigrationsTableNotFound = errors.New("migrations table not found")
)

Functions

func Migrate

func Migrate(c *config.Config, log bool, steps int) error

If steps is 0, all migrations are run. Otherwise, steps migrations are run up or down depending on steps > 0 or not.

func MigrateCLIWrapper

func MigrateCLIWrapper(ctx *cli.Context) error

func MysqlDSN

func MysqlDSN(addr, user, password, dbName string) string

MysqlDSN returns a DSN that could be used to connect to a MySQL database. You may want to append mysql:// to the beginning of the returned string.

func Version

func Version(db *sql.DB) (int, error)

Version returns the last migration number (the value in the schema_migrations table). If the migrations table is not found, then errMigrationsTableNotFound is returned. If the migrations table is found but empty, then sql.ErrNoRows is returned.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL