atlascmd

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2022 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Overview

Package atlascmd holds the atlas commands used to build an atlas distribution.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Root represents the root command when called without any subcommands.
	Root = &cobra.Command{
		Use:          "atlas",
		Short:        "A database toolkit.",
		SilenceUsage: true,
	}

	// GlobalFlags contains flags common to many Atlas sub-commands.
	GlobalFlags struct {
		// SelectedEnv contains the environment selected from the active
		// project via the --env flag.
		SelectedEnv string
		// Vars contains the input variables passed from the CLI to
		// Atlas DDL or project files.
		Vars map[string]string
	}

	// EnvCmd represents the subcommand 'atlas env'.
	EnvCmd = &cobra.Command{
		Use:   "env",
		Short: "Print atlas environment variables.",
		Long: `'atlas env' prints atlas environment information.

Every set environment param will be printed in the form of NAME=VALUE.

List of supported environment parameters:
* ATLAS_NO_UPDATE_NOTIFIER: On any command, the CLI will check for new releases using the GitHub API.
  This check will happen at most once every 24 hours. To cancel this behavior, set the environment 
  variable "ATLAS_NO_UPDATE_NOTIFIER".`,
		Run: func(cmd *cobra.Command, args []string) {
			keys := []string{update.AtlasNoUpdateNotifier}
			for _, k := range keys {
				if v, ok := os.LookupEnv(k); ok {
					cmd.Println(fmt.Sprintf("%s=%s", k, v))
				}
			}
		},
	}
)
View Source
var (
	// MigrateFlags are the flags used in MigrateCmd (and sub-commands).
	MigrateFlags struct {
		DirURL         string
		DevURL         string
		ToURL          string
		Schemas        []string
		Format         string
		LogFormat      string
		RevisionSchema string
		Force          bool
		Verbose        bool
	}
	// MigrateCmd represents the migrate command. It wraps several other sub-commands.
	MigrateCmd = &cobra.Command{
		Use:   "migrate",
		Short: "Manage versioned migration files",
		Long:  "'atlas migrate' wraps several sub-commands for migration management.",
		PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
			if err := migrateFlagsFromEnv(cmd, nil); err != nil {
				return err
			}

			if !MigrateFlags.Force {
				dir, err := dir()
				if err != nil {
					return err
				}
				if err := migrate.Validate(dir); err != nil {
					fmt.Fprintf(cmd.OutOrStderr(), `You have a checksum error in your migration directory.
This happens if you manually create or edit a migration file.
Please check your migration files and run

'atlas migrate hash --force'

to re-hash the contents and resolve the error

`)
					cmd.SilenceUsage = true
					return err
				}
			}
			return nil
		},
	}
	// MigrateApplyCmd represents the 'atlas migrate apply' subcommand.
	MigrateApplyCmd = &cobra.Command{
		Use:   "apply",
		Short: "Applies pending migration files on the connected database.",
		Long: `'atlas migrate apply' reads the migration state of the connected database and computes what migrations are pending.
It then attempts to apply the pending migration files in the correct order onto the database. 
The first argument denotes the maximum number of migration files to apply.
As a safety measure 'atlas migrate apply' will abort with an error, if:
  - the migration directory is not in sync with the 'atlas.sum' file
  - the migration and database history do not match each other`,
		Example: `  atlas migrate apply --to mysql://user:pass@localhost:3306/dbname
  atlas migrate apply 1 --dir file:///path/to/migration/directory --to mysql://user:pass@localhost:3306/dbname`,
		Args: cobra.MaximumNArgs(1),
		RunE: CmdMigrateApplyRun,
	}
	// MigrateDiffCmd represents the 'atlas migrate diff' subcommand.
	MigrateDiffCmd = &cobra.Command{
		Use:   "diff",
		Short: "Compute the diff between the migration directory and a connected database and create a new migration file.",
		Long: `'atlas migrate diff' uses the dev-database to re-run all migration files in the migration
directory and compares it to a given desired state and create a new migration file containing SQL statements to migrate 
the migration directory state to the desired schema. The desired state can be another connected database or an HCL file.`,
		Example: `  atlas migrate diff --dev-url mysql://user:pass@localhost:3306/dev --to mysql://user:pass@localhost:3306/dbname
  atlas migrate diff --dev-url mysql://user:pass@localhost:3306/dev --to file://atlas.hcl`,
		Args:    cobra.MaximumNArgs(1),
		PreRunE: migrateFlagsFromEnv,
		RunE:    CmdMigrateDiffRun,
	}
	// MigrateHashCmd represents the migrate hash command.
	MigrateHashCmd = &cobra.Command{
		Use:   "hash",
		Short: "Hash (re-)creates an integrity hash file for the migration directory.",
		Long: `'atlas migrate hash' computes the integrity hash sum of the migration directory and stores it in the atlas.sum file.
This command should be used whenever a manual change in the migration directory was made.`,
		Example: `  atlas migrate hash --force`,
		PreRunE: migrateFlagsFromEnv,
		RunE:    CmdMigrateHashRun,
	}
	// MigrateNewCmd represents the migrate new command.
	MigrateNewCmd = &cobra.Command{
		Use:     "new",
		Short:   "Creates a new empty migration file in the migration directory.",
		Long:    `'atlas migrate new' creates a new migration according to the configured formatter without any statements in it.`,
		Example: `  atlas migrate new my-new-migration`,
		Args:    cobra.MaximumNArgs(1),
		PreRunE: migrateFlagsFromEnv,
		RunE:    CmdMigrateNewRun,
	}
	// MigrateValidateCmd represents the migrate validate command.
	MigrateValidateCmd = &cobra.Command{
		Use:   "validate",
		Short: "Validates the migration directories checksum and SQL statements.",
		Long: `'atlas migrate validate' computes the integrity hash sum of the migration directory and compares it to 
the atlas.sum file. If there is a mismatch it will be reported. If the --dev-url flag is given, the migration files are 
executed on the connected database in order to validate SQL semantics.`,
		Example: `  atlas migrate validate
  atlas migrate validate --dir file:///path/to/migration/directory
  atlas migrate validate --dir file:///path/to/migration/directory --dev-url mysql://user:pass@localhost:3306/dev`,
		PreRunE: migrateFlagsFromEnv,
		RunE:    CmdMigrateValidateRun,
	}
)
View Source
var (

	// SchemaFlags are common flags used by schema commands.
	SchemaFlags struct {
		URL     string
		Schemas []string

		// Deprecated: DSN is an alias for URL.
		DSN string
	}

	// ApplyFlags are the flags used in SchemaApply command.
	ApplyFlags struct {
		DevURL      string
		File        string
		Web         bool
		Addr        string
		DryRun      bool
		AutoApprove bool
		Verbose     bool
	}
	// SchemaApply represents the 'atlas schema apply' subcommand command.
	SchemaApply = &cobra.Command{
		Use:   "apply",
		Short: "Apply an atlas schema to a target database.",

		Long: `'atlas schema apply' plans and executes a database migration to bring a given
database to the state described in the Atlas schema file. Before running the
migration, Atlas will print the migration plan and prompt the user for approval.

If run with the "--dry-run" flag, atlas will exit after printing out the planned
migration.`,
		PreRunE: schemaFlagsFromEnv,
		RunE:    CmdApplyRun,
		Example: `  atlas schema apply -u "mysql://user:pass@localhost/dbname" -f atlas.hcl
  atlas schema apply -u "mysql://localhost" -f atlas.hcl --schema prod --schema staging
  atlas schema apply -u "mysql://user:pass@localhost:3306/dbname" -f atlas.hcl --dry-run
  atlas schema apply -u "mariadb://user:pass@localhost:3306/dbname" -f atlas.hcl
  atlas schema apply --url "postgres://user:pass@host:port/dbname?sslmode=disable" -f atlas.hcl
  atlas schema apply -u "sqlite://file:ex1.db?_fk=1" -f atlas.hcl`,
	}

	// InspectFlags are the flags used in SchemaInspect command.
	InspectFlags struct {
		Web  bool
		Addr string
	}
	// SchemaInspect represents the 'atlas schema inspect' subcommand.
	SchemaInspect = &cobra.Command{
		Use:   "inspect",
		Short: "Inspect a database's and print its schema in Atlas DDL syntax.",
		Long: `'atlas schema inspect' connects to the given database and inspects its schema.
It then prints to the screen the schema of that database in Atlas DDL syntax. This output can be
saved to a file, commonly by redirecting the output to a file named with a ".hcl" suffix:

  atlas schema inspect -u "mysql://user:pass@localhost:3306/dbname" > atlas.hcl

This file can then be edited and used with the` + " `atlas schema apply` " + `command to plan
and execute schema migrations against the given database. In cases where users wish to inspect
all multiple schemas in a given database (for instance a MySQL server may contain multiple named
databases), omit the relevant part from the url, e.g. "mysql://user:pass@localhost:3306/".
To select specific schemas from the databases, users may use the "--schema" (or "-s" shorthand)
flag.
	`,
		PreRunE: schemaFlagsFromEnv,
		RunE:    CmdInspectRun,
		Example: `  atlas schema inspect -u "mysql://user:pass@localhost:3306/dbname"
  atlas schema inspect -u "mariadb://user:pass@localhost:3306/" --schema=schemaA,schemaB -s schemaC
  atlas schema inspect --url "postgres://user:pass@host:port/dbname?sslmode=disable"
  atlas schema inspect -u "sqlite://file:ex1.db?_fk=1"`,
	}

	// SchemaFmt represents the 'atlas schema fmt' subcommand.
	SchemaFmt = &cobra.Command{
		Use:   "fmt [path ...]",
		Short: "Formats Atlas HCL files",
		Long: `'atlas schema fmt' formats all ".hcl" files under the given path using
canonical HCL layout style as defined by the github.com/hashicorp/hcl/v2/hclwrite package.
Unless stated otherwise, the fmt command will use the current directory.

After running, the command will print the names of the files it has formatted. If all
files in the directory are formatted, no input will be printed out.
`,
		Run: CmdFmtRun,
	}
)

Functions

func CheckForUpdate

func CheckForUpdate()

CheckForUpdate exposes internal update logic to CLI.

func CmdApplyRun

func CmdApplyRun(cmd *cobra.Command, _ []string) error

CmdApplyRun is the command used when running CLI.

func CmdFmtRun

func CmdFmtRun(cmd *cobra.Command, args []string)

CmdFmtRun formats all HCL files in a given directory using canonical HCL formatting rules.

func CmdInspectRun

func CmdInspectRun(cmd *cobra.Command, _ []string) error

CmdInspectRun is the command used when running CLI.

func CmdMigrateApplyRun added in v0.4.2

func CmdMigrateApplyRun(cmd *cobra.Command, args []string) error

CmdMigrateApplyRun is the command executed when running the CLI with 'migrate apply' args.

func CmdMigrateDiffRun

func CmdMigrateDiffRun(cmd *cobra.Command, args []string) error

CmdMigrateDiffRun is the command executed when running the CLI with 'migrate diff' args.

func CmdMigrateHashRun

func CmdMigrateHashRun(_ *cobra.Command, _ []string) error

CmdMigrateHashRun is the command executed when running the CLI with 'migrate hash' args.

func CmdMigrateNewRun

func CmdMigrateNewRun(_ *cobra.Command, args []string) error

CmdMigrateNewRun is the command executed when running the CLI with 'migrate new' args.

func CmdMigrateValidateRun

func CmdMigrateValidateRun(cmd *cobra.Command, _ []string) error

CmdMigrateValidateRun is the command executed when running the CLI with 'migrate validate' args.

Types

type Env added in v0.4.0

type Env struct {
	// Name for this environment.
	Name string `spec:"name,name"`

	// URL of the database.
	URL string `spec:"url"`

	// URL of the dev-database for this environment.
	// See: https://atlasgo.io/dev-database
	DevURL string `spec:"dev"`

	// Path to the file containing the desired schema of the environment.
	Source string `spec:"src"`

	// List of schemas in this database that are managed by Atlas.
	Schemas []string `spec:"schemas"`

	// Directory containing the migrations for the env.
	MigrationDir *MigrationDir `spec:"migration_dir"`

	schemaspec.DefaultExtension
}

Env represents an Atlas environment.

func LoadEnv added in v0.4.0

func LoadEnv(path string, name string, opts ...LoadOption) (*Env, error)

LoadEnv reads the project file in path, and loads the environment with the provided name into env.

type LoadOption added in v0.4.1

type LoadOption func(*loadConfig)

LoadOption configures the LoadEnv function.

func WithInput added in v0.4.1

func WithInput(vals map[string]string) LoadOption

WithInput is a LoadOption that sets the input values for the LoadEnv function.

type LogTTY added in v0.4.2

type LogTTY struct {
	// contains filtered or unexported fields
}

LogTTY is a migrate.Logger that pretty prints execution progress. If the connected out is not a tty, it will fall back to a non-colorful output.

func (*LogTTY) Log added in v0.4.2

func (l *LogTTY) Log(e migrate.LogEntry)

Log implements the migrate.Logger interface.

type MigrationDir added in v0.4.1

type MigrationDir struct {
	URL    string `spec:"url"`
	Format string `spec:"format"`
}

MigrationDir represents the migration directory for the Env.

Jump to

Keyboard shortcuts

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