graphql-engine/cli/migrate/api/migrate.go

290 lines
8.2 KiB
Go
Raw Normal View History

2018-06-24 16:40:48 +03:00
package api
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
2018-06-24 16:40:48 +03:00
"net/http"
"path/filepath"
2018-06-24 16:40:48 +03:00
"strings"
"time"
"github.com/hasura/graphql-engine/cli/internal/metadataobject"
"github.com/hasura/graphql-engine/cli/internal/hasura"
"github.com/hasura/graphql-engine/cli/internal/metadatautil"
2018-06-24 16:40:48 +03:00
"github.com/gin-gonic/gin"
"github.com/hasura/graphql-engine/cli"
2018-06-24 16:40:48 +03:00
"github.com/hasura/graphql-engine/cli/migrate"
"github.com/hasura/graphql-engine/cli/migrate/cmd"
"github.com/hasura/graphql-engine/cli/migrate/database/hasuradb"
"github.com/sirupsen/logrus"
2018-06-24 16:40:48 +03:00
)
const (
DataAPIError = "Data Error: "
MigrationMode = "migration_mode"
)
type Response struct {
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"`
Name string `json:"name,omitempty"`
StatusCode int `json:"-"`
}
type Request struct {
Name string `json:"name"`
Up []requestType `json:"up"`
Down []requestType `json:"down"`
SkipExecution bool `json:"skip_execution"`
SourceName string `json:"datasource,omitempty"`
}
type requestType struct {
Version int `json:"version,omitempty"`
Type string `json:"type"`
Database string `json:"datasource,omitempty"`
Args interface{} `json:"args"`
2018-06-24 16:40:48 +03:00
}
func MigrateAPI(c *gin.Context) {
ecPtr, ok := c.Get("ec")
2018-06-24 16:40:48 +03:00
if !ok {
return
}
// Get File url
//sourcePtr, ok := c.Get("filedir")
2018-06-24 16:40:48 +03:00
if !ok {
return
}
// Get Logger
loggerPtr, ok := c.Get("logger")
if !ok {
2018-06-24 16:40:48 +03:00
return
}
// Get version
version := c.GetInt("version")
// Convert to url.URL
ec, ok := ecPtr.(*cli.ExecutionContext)
if !ok {
c.JSON(http.StatusInternalServerError, &Response{Code: "internal_error", Message: "cannot get execution context"})
return
}
//sourceURL := sourcePtr.(*url.URL)
logger := loggerPtr.(*logrus.Logger)
mdHandler := metadataobject.NewHandlerFromEC(ec)
2018-06-24 16:40:48 +03:00
// Switch on request method
switch c.Request.Method {
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 05:21:15 +03:00
case "GET":
sourceName := c.Query("datasource")
if ec.Config.Version >= cli.V3 && sourceName == "" {
c.JSON(http.StatusInternalServerError, &Response{Code: "internal_error", Message: "datasource query parameter is required"})
return
}
sourceKind := hasura.SourceKindPG
if ec.Config.Version >= cli.V3 {
kind, err := metadatautil.GetSourceKind(ec.APIClient.V1Metadata.ExportMetadata, sourceName)
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "internal_error", Message: err.Error()})
return
}
sourceKind = *kind
}
t, err := migrate.NewMigrate(ec, false, sourceName, sourceKind)
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "internal_error", Message: err.Error()})
return
}
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 05:21:15 +03:00
// Rescan file system
err = t.ReScan()
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 05:21:15 +03:00
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "internal_error", Message: err.Error()})
return
}
status, err := t.GetStatus()
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "internal_error", Message: "Something went wrong"})
return
}
c.JSON(http.StatusOK, status)
2018-06-24 16:40:48 +03:00
case "POST":
var request Request
var err error
2018-06-24 16:40:48 +03:00
// Bind Request body to Request struct
if err = c.BindJSON(&request); err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "request_parse_error", Message: err.Error()})
2018-06-24 16:40:48 +03:00
return
}
if ec.Config.Version >= cli.V3 && request.SourceName == "" {
c.JSON(http.StatusInternalServerError, &Response{Code: "internal_error", Message: "datasource key not found in body"})
return
}
2018-06-24 16:40:48 +03:00
startTime := time.Now()
timestamp := startTime.UnixNano() / int64(time.Millisecond)
sourceName := request.SourceName
if ec.Config.Version < cli.V3 {
sourceName = ""
}
sourceKind := hasura.SourceKindPG
if ec.Config.Version >= cli.V3 {
kind, err := metadatautil.GetSourceKind(ec.APIClient.V1Metadata.ExportMetadata, sourceName)
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "internal_error", Message: err.Error()})
return
}
sourceKind = *kind
}
t, err := migrate.NewMigrate(ec, false, sourceName, sourceKind)
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "internal_error", Message: err.Error()})
return
}
createOptions := cmd.New(timestamp, request.Name, filepath.Join(ec.MigrationDir, sourceName))
if version != int(cli.V1) {
sqlUp := &bytes.Buffer{}
sqlDown := &bytes.Buffer{}
for _, arg := range request.Up {
if arg.Type == hasuradb.RunSQL {
argByt, err := json.Marshal(arg.Args)
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "request_parse_error", Message: err.Error()})
return
}
var to hasuradb.RunSQLInput
err = json.Unmarshal(argByt, &to)
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "request_parse_error", Message: err.Error()})
return
}
sqlUp.WriteString(to.SQL)
sqlUp.WriteString("\n")
}
}
for _, arg := range request.Down {
if arg.Type == hasuradb.RunSQL {
argByt, err := json.Marshal(arg.Args)
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "request_parse_error", Message: err.Error()})
return
}
var to hasuradb.RunSQLInput
err = json.Unmarshal(argByt, &to)
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "request_parse_error", Message: err.Error()})
return
}
sqlDown.WriteString(to.SQL)
sqlDown.WriteString("\n")
}
}
2018-06-24 16:40:48 +03:00
if sqlUp.String() != "" {
err = createOptions.SetSQLUp(sqlUp.String())
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "create_file_error", Message: err.Error()})
return
}
}
if sqlDown.String() != "" {
err = createOptions.SetSQLDown(sqlDown.String())
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "create_file_error", Message: err.Error()})
return
}
}
if sqlUp.String() != "" || sqlDown.String() != "" {
err = createOptions.Create()
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "create_file_error", Message: err.Error()})
return
}
} else {
timestamp = 0
}
} else {
err = createOptions.SetMetaUp(request.Up)
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "create_file_error", Message: err.Error()})
return
}
err = createOptions.SetMetaDown(request.Down)
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "create_file_error", Message: err.Error()})
return
}
err = createOptions.Create()
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "create_file_error", Message: err.Error()})
return
}
}
defer func() {
if err != nil && timestamp != 0 {
err := createOptions.Delete()
if err != nil {
logger.Debug(err)
}
}
}()
2018-06-24 16:40:48 +03:00
// Rescan file system
err = t.ReScan()
2018-06-24 16:40:48 +03:00
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "internal_error", Message: err.Error()})
return
}
upByt, err := json.Marshal(request.Up)
if err != nil {
c.JSON(http.StatusInternalServerError, &Response{Code: "internal_error", Message: err.Error()})
return
}
if err = t.QueryWithVersion(uint64(timestamp), ioutil.NopCloser(bytes.NewReader(upByt)), request.SkipExecution); err != nil {
2018-06-24 16:40:48 +03:00
if strings.HasPrefix(err.Error(), DataAPIError) {
c.JSON(http.StatusBadRequest, &Response{Code: "data_api_error", Message: strings.TrimPrefix(err.Error(), DataAPIError)})
return
}
if err == migrate.ErrNoMigrationMode {
c.JSON(http.StatusBadRequest, &Response{Code: "migration_mode_disabled", Message: err.Error()})
return
}
c.JSON(http.StatusInternalServerError, &Response{Code: "internal_error", Message: err.Error()})
return
}
defer func() {
var files map[string][]byte
files, err = mdHandler.ExportMetadata()
if err != nil {
logger.Debug(err)
return
}
err = mdHandler.WriteMetadata(files)
if err != nil {
logger.Debug(err)
return
}
}()
c.JSON(http.StatusOK, &Response{Name: fmt.Sprintf("%d_%s", timestamp, request.Name)})
2018-06-24 16:40:48 +03:00
default:
c.JSON(http.StatusMethodNotAllowed, &gin.H{"message": "Method not allowed"})
}
}