cli: add interactive prompt to get input when --database-name flag is missing

GitOrigin-RevId: f92478d0ca6a4f6d0cfaa7aca3b4bb8a215a5cad
This commit is contained in:
Vishnu Bharathi 2021-06-09 12:42:56 +05:30 committed by hasura-bot
parent 3f19e8a3a8
commit 4b76289d03
7 changed files with 102 additions and 51 deletions

View File

@ -6,6 +6,7 @@
(Add entries below in the order of server, console, cli, docs, others) (Add entries below in the order of server, console, cli, docs, others)
- console: add foreign key CRUD functionality to ms sql server tables - console: add foreign key CRUD functionality to ms sql server tables
- console: allow tracking of custom SQL functions having composite type (rowtype) input arguments - console: allow tracking of custom SQL functions having composite type (rowtype) input arguments
- cli: add interactive prompt to get input when `--database-name` flag is missing
## v2.0.0-beta.1 ## v2.0.0-beta.1

View File

@ -331,6 +331,9 @@ type Config struct {
// Version of the config. // Version of the config.
Version ConfigVersion `yaml:"version,omitempty"` Version ConfigVersion `yaml:"version,omitempty"`
// DisableInteractive disables interactive prompt
DisableInteractive bool `yaml:"disable_interactive,omitempty"`
// ServerConfig to be used by CLI to contact server. // ServerConfig to be used by CLI to contact server.
ServerConfig `yaml:",inline"` ServerConfig `yaml:",inline"`
@ -820,7 +823,8 @@ func (ec *ExecutionContext) readConfig() error {
} }
ec.Config = &Config{ ec.Config = &Config{
Version: ConfigVersion(v.GetInt("version")), Version: ConfigVersion(v.GetInt("version")),
DisableInteractive: v.GetBool("disable_interactive"),
ServerConfig: ServerConfig{ ServerConfig: ServerConfig{
Endpoint: v.GetString("endpoint"), Endpoint: v.GetString("endpoint"),
AdminSecret: adminSecret, AdminSecret: adminSecret,

View File

@ -50,12 +50,14 @@ func NewMigrateCmd(ec *cli.ExecutionContext) *cobra.Command {
f.MarkDeprecated("access-key", "use --admin-secret instead") f.MarkDeprecated("access-key", "use --admin-secret instead")
f.Bool("insecure-skip-tls-verify", false, "skip TLS verification and disable cert checking (default: false)") f.Bool("insecure-skip-tls-verify", false, "skip TLS verification and disable cert checking (default: false)")
f.String("certificate-authority", "", "path to a cert file for the certificate authority") f.String("certificate-authority", "", "path to a cert file for the certificate authority")
f.Bool("disable-interactive", false, "disables interactive prompts (default: false)")
util.BindPFlag(v, "endpoint", f.Lookup("endpoint")) util.BindPFlag(v, "endpoint", f.Lookup("endpoint"))
util.BindPFlag(v, "admin_secret", f.Lookup("admin-secret")) util.BindPFlag(v, "admin_secret", f.Lookup("admin-secret"))
util.BindPFlag(v, "access_key", f.Lookup("access-key")) util.BindPFlag(v, "access_key", f.Lookup("access-key"))
util.BindPFlag(v, "insecure_skip_tls_verify", f.Lookup("insecure-skip-tls-verify")) util.BindPFlag(v, "insecure_skip_tls_verify", f.Lookup("insecure-skip-tls-verify"))
util.BindPFlag(v, "certificate_authority", f.Lookup("certificate-authority")) util.BindPFlag(v, "certificate_authority", f.Lookup("certificate-authority"))
util.BindPFlag(v, "disable_interactive", f.Lookup("disable-interactive"))
f.BoolVar(&ec.DisableAutoStateMigration, "disable-auto-state-migration", false, "after a config v3 update, disable automatically moving state from hdb_catalog.schema_migrations to catalog state") f.BoolVar(&ec.DisableAutoStateMigration, "disable-auto-state-migration", false, "after a config v3 update, disable automatically moving state from hdb_catalog.schema_migrations to catalog state")
f.MarkHidden("disable-auto-state-migration") f.MarkHidden("disable-auto-state-migration")
@ -107,32 +109,49 @@ func executeStatus(t *migrate.Migrate) (*migrate.Status, error) {
} }
func validateConfigV3Flags(cmd *cobra.Command, ec *cli.ExecutionContext) error { func validateConfigV3Flags(cmd *cobra.Command, ec *cli.ExecutionContext) error {
if ec.Config.Version >= cli.V3 { // for project using config older than v3, use PG source kind
if !cmd.Flags().Changed("database-name") { if ec.Config.Version < cli.V3 {
return errDatabaseNameNotSet{"--database-name flag is required"}
} else {
// if database-name flag is set
// find out the database kind by making a API call to server
// and update ec to include the database name and kind
sourceKind, err := metadatautil.GetSourceKind(ec.APIClient.V1Metadata.ExportMetadata, ec.Source.Name)
if err != nil {
return fmt.Errorf("determining database kind of %s: %w", ec.Source.Name, err)
}
if sourceKind == nil {
return fmt.Errorf("error determining database kind for %s, check if database exists on hasura", ec.Source.Name)
}
ec.Source.Kind = *sourceKind
if !migrate.IsMigrationsSupported(*sourceKind) {
return fmt.Errorf("migrations on source %s of kind %s is not supported", ec.Source.Name, *sourceKind)
}
}
} else {
// for project using config older than v3, use PG source kind
ec.Source.Kind = hasura.SourceKindPG ec.Source.Kind = hasura.SourceKindPG
if err := scripts.CheckIfUpdateToConfigV3IsRequired(ec); err != nil { if err := scripts.CheckIfUpdateToConfigV3IsRequired(ec); err != nil {
return err return err
} }
return nil
}
// if --all-databases flag is present, ignore --database-name and showing UI prompt for choosing a single database
if cmd.Flags().Changed("all-databases") {
return nil
}
// for project using config equal to or greater than v3
// database-name flag is required when running in non-terminal mode
if (!ec.IsTerminal || ec.Config.DisableInteractive) && !cmd.Flags().Changed("database-name") {
return errDatabaseNameNotSet{"--database-name flag is required"}
}
// prompt UI for choosing database if source name is not set
if ec.Source.Name == "" {
databaseName, err := metadatautil.DatabaseChooserUI(ec.APIClient.V1Metadata.ExportMetadata)
if err != nil {
return err
}
ec.Source.Name = databaseName
}
// find out the database kind by making a API call to server
// and update ec to include the database name and kind
sourceKind, err := metadatautil.GetSourceKind(ec.APIClient.V1Metadata.ExportMetadata, ec.Source.Name)
if err != nil {
return fmt.Errorf("determining database kind of %s: %w", ec.Source.Name, err)
}
if sourceKind == nil {
return fmt.Errorf("error determining database kind for %s, check if database exists on hasura", ec.Source.Name)
}
ec.Source.Kind = *sourceKind
// check if migration ops are supported for the database
if !migrate.IsMigrationsSupported(*sourceKind) {
return fmt.Errorf("migrations on source %s of kind %s is not supported", ec.Source.Name, *sourceKind)
} }
return nil return nil
} }

View File

@ -58,16 +58,7 @@ func newMigrateApplyCmd(ec *cli.ExecutionContext) *cobra.Command {
hasura migrate apply --down all`, hasura migrate apply --down all`,
SilenceUsage: true, SilenceUsage: true,
PreRunE: func(cmd *cobra.Command, args []string) error { PreRunE: func(cmd *cobra.Command, args []string) error {
err := validateConfigV3Flags(cmd, ec) return validateConfigV3Flags(cmd, ec)
// --database-name / --all-databases flag is required to be set
if _, ok := err.(errDatabaseNameNotSet); !ok {
return err
} else if ok {
if !cmd.Flags().Changed("all-databases") {
return fmt.Errorf("one of --database-name or --all-databases flag is required")
}
}
return nil
}, },
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.Source = ec.Source opts.Source = ec.Source

View File

@ -2,6 +2,7 @@ package commands
import ( import (
"fmt" "fmt"
"github.com/hasura/graphql-engine/cli/internal/scripts" "github.com/hasura/graphql-engine/cli/internal/scripts"
"github.com/hasura/graphql-engine/cli/util" "github.com/hasura/graphql-engine/cli/util"
"github.com/spf13/afero" "github.com/spf13/afero"

View File

@ -32,29 +32,44 @@ func NewSeedCmd(ec *cli.ExecutionContext) *cobra.Command {
if err := ec.Validate(); err != nil { if err := ec.Validate(); err != nil {
return err return err
} }
if ec.Config.Version >= cli.V3 { // for project using config older than v3, use PG source kind
if !cmd.Flags().Changed("database-name") { if ec.Config.Version < cli.V3 {
return errors.New("--database-name flag is required")
}
sourceKind, err := metadatautil.GetSourceKind(ec.APIClient.V1Metadata.ExportMetadata, ec.Source.Name)
if err != nil {
return err
}
if sourceKind == nil {
return fmt.Errorf("cannot determine source kind for %v", ec.Source.Name)
}
ec.Source.Kind = *sourceKind
// check if seed ops are supported for the database
if !seed.IsSeedsSupported(*sourceKind) {
return fmt.Errorf("seed operations on database %s of kind %s is not supported", ec.Source.Name, *sourceKind)
}
} else {
// for project using config older than v3, use PG source kind
ec.Source.Kind = hasura.SourceKindPG ec.Source.Kind = hasura.SourceKindPG
if err := scripts.CheckIfUpdateToConfigV3IsRequired(ec); err != nil { if err := scripts.CheckIfUpdateToConfigV3IsRequired(ec); err != nil {
return err return err
} }
return nil
} }
// for project using config equal to or greater than v3
// database-name flag is required when running in non-terminal mode
if (!ec.IsTerminal || ec.Config.DisableInteractive) && !cmd.Flags().Changed("database-name") {
return errors.New("--database-name flag is required")
}
// prompt UI for choosing database if source name is not set
if ec.Source.Name == "" {
databaseName, err := metadatautil.DatabaseChooserUI(ec.APIClient.V1Metadata.ExportMetadata)
if err != nil {
return err
}
ec.Source.Name = databaseName
}
sourceKind, err := metadatautil.GetSourceKind(ec.APIClient.V1Metadata.ExportMetadata, ec.Source.Name)
if err != nil {
return err
}
if sourceKind == nil {
return fmt.Errorf("cannot determine source kind for %v", ec.Source.Name)
}
ec.Source.Kind = *sourceKind
// check if seed ops are supported for the database
if !seed.IsSeedsSupported(*sourceKind) {
return fmt.Errorf("seed operations on database %s of kind %s is not supported", ec.Source.Name, *sourceKind)
}
return nil return nil
}, },
} }
@ -73,12 +88,14 @@ func NewSeedCmd(ec *cli.ExecutionContext) *cobra.Command {
f.MarkDeprecated("access-key", "use --admin-secret instead") f.MarkDeprecated("access-key", "use --admin-secret instead")
f.Bool("insecure-skip-tls-verify", false, "skip TLS verification and disable cert checking (default: false)") f.Bool("insecure-skip-tls-verify", false, "skip TLS verification and disable cert checking (default: false)")
f.String("certificate-authority", "", "path to a cert file for the certificate authority") f.String("certificate-authority", "", "path to a cert file for the certificate authority")
f.Bool("disable-interactive", false, "disables interactive prompts (default: false)")
util.BindPFlag(v, "endpoint", f.Lookup("endpoint")) util.BindPFlag(v, "endpoint", f.Lookup("endpoint"))
util.BindPFlag(v, "admin_secret", f.Lookup("admin-secret")) util.BindPFlag(v, "admin_secret", f.Lookup("admin-secret"))
util.BindPFlag(v, "access_key", f.Lookup("access-key")) util.BindPFlag(v, "access_key", f.Lookup("access-key"))
util.BindPFlag(v, "insecure_skip_tls_verify", f.Lookup("insecure-skip-tls-verify")) util.BindPFlag(v, "insecure_skip_tls_verify", f.Lookup("insecure-skip-tls-verify"))
util.BindPFlag(v, "certificate_authority", f.Lookup("certificate-authority")) util.BindPFlag(v, "certificate_authority", f.Lookup("certificate-authority"))
util.BindPFlag(v, "disable_interactive", f.Lookup("disable-interactive"))
return seedCmd return seedCmd
} }

View File

@ -1,6 +1,7 @@
package metadatautil package metadatautil
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -8,6 +9,7 @@ import (
"github.com/goccy/go-yaml" "github.com/goccy/go-yaml"
"github.com/goccy/go-yaml/parser" "github.com/goccy/go-yaml/parser"
"github.com/hasura/graphql-engine/cli/internal/hasura" "github.com/hasura/graphql-engine/cli/internal/hasura"
"github.com/hasura/graphql-engine/cli/util"
) )
func getMetadataAsYaml(exportMetadata func() (io.Reader, error)) ([]byte, error) { func getMetadataAsYaml(exportMetadata func() (io.Reader, error)) ([]byte, error) {
@ -107,3 +109,19 @@ func GetSourcesAndKind(exportMetadata func() (io.Reader, error)) ([]Source, erro
} }
return sources, nil return sources, nil
} }
func DatabaseChooserUI(exportMetadata func() (io.Reader, error)) (string, error) {
sources, err := GetSources(exportMetadata)
if err != nil {
return "", fmt.Errorf("unable to get available databases: %w", err)
}
if len(sources) == 0 {
return "", errors.New("no connected databases found in the server")
}
databaseName, err := util.GetSelectPrompt("Select a database to use", sources)
if err != nil {
return "", fmt.Errorf("error in selecting a database to use: %w", err)
}
return databaseName, nil
}