graphql-engine/cli/commands/migrate.go
Aravind Shankar 980c65dbe2 cli(migrations): new folder structure and squash (#3072)
### Description
This PR introduces three new features:

- Support for a new migrations folder structure.
- Add `squash` command in preview.
- ~List of migrations on the Console and ability to squash them from console.~

#### New migrations folder structure

Starting with this commit, Hasura CLI supports a new directory structure for migrations folder and defaults to that for all new migrations created. 

Each migration will get a new directory with the name format `timestamp_name` and inside the directory, there will be four files:

```bash
└── migrations
    ├── 1572237730898_squashed
    │   ├── up.sql
    │   ├── up.yaml
    │   ├── down.yaml
    │   └── down.sql
```

Existing files old migration format `timestamp_name.up|down.yaml|sql` will continue to work alongside new migration files.

#### Squash command

Lots of users have expressed their interest in squashing migrations (see #2724 and #2254) and some even built [their own tools](https://github.com/domasx2/hasura-squasher) to do squash. In this PR, we take a systematic approach to squash migrations.

A new command called `migrate squash` is introduced. Note that this command is in **PREVIEW** and the correctness of squashed migration is not guaranteed (especially for down migrations). From our tests, **it works for most use cases**, but we have found some issues with squashing all the down migrations, partly because the console doesn't generate down migrations for all actions.

Hence, until we add an extensive test suite for squashing, we'll keep the command in preview. We recommend you to confirm the correctness yourself by diffing the SQL and Metadata before and after applying the squashed migrations (we're also thinking about embedding some checks into the command itself).

```bash
$ hasura migrate squash --help
(PREVIEW) Squash multiple migrations leading upto the latest one into a single migration file

Usage:
  hasura migrate squash [flags]

Examples:
  # NOTE: This command is in PREVIEW, correctness is not guaranteed and the usage may change.

  # squash all migrations from version 1572238297262 to the latest one:
  hasura migrate squash --from 1572238297262

Flags:
      --from uint             start squashing form this version
      --name string           name for the new squashed migration (default "squashed")
      --delete-source         delete the source files after squashing without any confirmation
```

### Affected components 
<!-- Remove non-affected components from the list -->

- CLI

### Related Issues
<!-- Please make sure you have an issue associated with this Pull Request -->
<!-- And then add `(close #<issue-no>)` to the pull request title -->
<!-- Add the issue number below (e.g. #234) -->
Close #2724, Close #2254, 

### Solution and Design
<!-- How is this issue solved/fixed? What is the design? -->
<!-- It's better if we elaborate -->

For the squash command, a state machine is implemented to track changes to Hasura metadata. After applying each action on the metadata state, a list of incremental changes is created.

### Steps to test and verify
1. Open console via cli and create some migrations.
2. Run `hasura migrate squash --from <version>`

### Limitations, known bugs & workarounds
<!-- Limitations of the PR, known bugs and suggested workarounds -->

<!-- Feel free to delete these comment lines -->
- The `squash` command is in preview
- Support for squashing from the console is WIP
- Support for squashing migrations that are not committed yet is planned.
- Un-tracking or dropping a table will cause inconsistent squashed down migration since console doesn't generate correct down migration.
- If cascade setting is set to `true` on any of the metadata action, generated migration may be wrong
2019-10-31 07:51:15 +05:30

133 lines
3.1 KiB
Go

package commands
import (
"fmt"
"net/url"
"runtime"
"strings"
"github.com/hasura/graphql-engine/cli"
"github.com/hasura/graphql-engine/cli/migrate"
mig "github.com/hasura/graphql-engine/cli/migrate/cmd"
"github.com/hasura/graphql-engine/cli/version"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
// Initialize migration drivers
_ "github.com/hasura/graphql-engine/cli/migrate/database/hasuradb"
_ "github.com/hasura/graphql-engine/cli/migrate/source/file"
)
// NewMigrateCmd returns the migrate command
func NewMigrateCmd(ec *cli.ExecutionContext) *cobra.Command {
migrateCmd := &cobra.Command{
Use: "migrate",
Short: "Manage migrations on the database",
SilenceUsage: true,
}
migrateCmd.AddCommand(
newMigrateApplyCmd(ec),
newMigrateStatusCmd(ec),
newMigrateCreateCmd(ec),
newMigrateSquashCmd(ec),
)
return migrateCmd
}
func newMigrate(dir string, db *url.URL, adminSecretValue string, logger *logrus.Logger, v *version.Version, isCmd bool) (*migrate.Migrate, error) {
dbURL := getDataPath(db, getAdminSecretHeaderName(v), adminSecretValue)
fileURL := getFilePath(dir)
t, err := migrate.New(fileURL.String(), dbURL.String(), isCmd, logger)
if err != nil {
return nil, errors.Wrap(err, "cannot create migrate instance")
}
return t, nil
}
// ExecuteMigration runs the actual migration
func ExecuteMigration(cmd string, t *migrate.Migrate, stepOrVersion int64) error {
var err error
switch cmd {
case "up":
err = mig.UpCmd(t, stepOrVersion)
case "down":
err = mig.DownCmd(t, stepOrVersion)
case "version":
var direction string
if stepOrVersion >= 0 {
direction = "up"
} else {
direction = "down"
stepOrVersion = -(stepOrVersion)
}
err = mig.GotoCmd(t, uint64(stepOrVersion), direction)
default:
err = fmt.Errorf("Invalid command")
}
return err
}
func executeStatus(t *migrate.Migrate) (*migrate.Status, error) {
status, err := t.GetStatus()
if err != nil {
return nil, err
}
return status, nil
}
func getDataPath(nurl *url.URL, adminSecretHeader, adminSecretValue string) *url.URL {
host := &url.URL{
Scheme: "hasuradb",
Host: nurl.Host,
Path: nurl.Path,
}
q := nurl.Query()
// Set sslmode in query
switch scheme := nurl.Scheme; scheme {
case "https":
q.Set("sslmode", "enable")
default:
q.Set("sslmode", "disable")
}
if adminSecretValue != "" {
q.Add("headers", fmt.Sprintf("%s:%s", adminSecretHeader, adminSecretValue))
}
host.RawQuery = q.Encode()
return host
}
func getFilePath(dir string) *url.URL {
host := &url.URL{
Scheme: "file",
Path: dir,
}
// Add Prefix / to path if runtime.GOOS equals to windows
if runtime.GOOS == "windows" && !strings.HasPrefix(host.Path, "/") {
host.Path = "/" + host.Path
}
return host
}
const (
XHasuraAdminSecret = "X-Hasura-Admin-Secret"
XHasuraAccessKey = "X-Hasura-Access-Key"
)
func getAdminSecretHeaderName(v *version.Version) string {
if v.ServerSemver == nil {
return XHasuraAdminSecret
}
flags, err := v.GetServerFeatureFlags()
if err != nil {
return XHasuraAdminSecret
}
if flags.HasAccessKey {
return XHasuraAccessKey
}
return XHasuraAdminSecret
}