db-migrator.go
115 строк · 2.6 Кб
1/**
2* This file is part of the raoptimus/db-migrator.go library
3*
4* @copyright Copyright (c) Evgeniy Urvantsev
5* @license https://github.com/raoptimus/db-migrator.go/blob/master/LICENSE.md
6* @link https://github.com/raoptimus/db-migrator.go
7*/
8
9package action
10
11import (
12"fmt"
13
14"github.com/raoptimus/db-migrator.go/internal/args"
15"github.com/urfave/cli/v2"
16)
17
18const (
19defaultUpgradeLimit = 0
20)
21
22type Upgrade struct {
23console Console
24service MigrationService
25fileNameBuilder FileNameBuilder
26interactive bool
27}
28
29func NewUpgrade(
30console Console,
31service MigrationService,
32fileNameBuilder FileNameBuilder,
33interactive bool,
34) *Upgrade {
35return &Upgrade{
36console: console,
37service: service,
38fileNameBuilder: fileNameBuilder,
39interactive: interactive,
40}
41}
42
43func (u *Upgrade) Run(ctx *cli.Context) error {
44limit, err := args.ParseStepStringOrDefault(ctx.Args().Get(0), defaultUpgradeLimit)
45if err != nil {
46return err
47}
48
49migrations, err := u.service.NewMigrations(ctx.Context)
50if err != nil {
51return err
52}
53
54totalNewMigrations := migrations.Len()
55if totalNewMigrations == 0 {
56u.console.SuccessLn(noNewMigrationsFound)
57return nil
58}
59
60if limit > 0 && migrations.Len() > limit {
61migrations = migrations[:limit]
62}
63
64if migrations.Len() == totalNewMigrations {
65u.console.Warnf(
66"Total %d new %s to be applied: \n",
67migrations.Len(),
68u.console.NumberPlural(migrations.Len(), "migration", "migrations"),
69)
70} else {
71u.console.Warnf(
72"Total %d out of %d new %s to be applied: \n",
73migrations.Len(),
74totalNewMigrations,
75u.console.NumberPlural(totalNewMigrations, "migration", "migrations"),
76)
77}
78
79printMigrations(migrations, false)
80
81question := fmt.Sprintf("Apply the above %s?",
82u.console.NumberPlural(migrations.Len(), "migration", "migrations"),
83)
84if u.interactive && !u.console.Confirm(question) {
85return nil
86}
87
88var applied int
89for i := range migrations {
90migration := &migrations[i]
91fileName, safely := u.fileNameBuilder.Up(migration.Version, false)
92
93if err := u.service.ApplyFile(ctx.Context, migration, fileName, safely); err != nil {
94u.console.Errorf("%d from %d %s applied.\n",
95applied,
96migrations.Len(),
97u.console.NumberPlural(applied, migrationWas, migrationsWere),
98)
99u.console.Error("The rest of the migrations are canceled.\n")
100
101return err
102}
103
104applied++
105}
106
107u.console.Successf(
108"%d %s applied\n",
109migrations.Len(),
110u.console.NumberPlural(migrations.Len(), migrationWas, migrationsWere),
111)
112u.console.SuccessLn(migratedUpSuccessfully)
113
114return nil
115}
116