atlasexec

package
v0.5.11 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2024 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrLint is returned when the 'migrate lint' finds a diagnostic that is configured to
	// be reported as an error, such as destructive changes by default.
	ErrLint = errors.New("lint error")
	// Deprecated: Use ErrLint instead.
	LintErr = ErrLint
)

Functions

func TempFile

func TempFile(content, ext string) (string, func() error, error)

TempFile creates a temporary file with the given content and extension.

Types

type AppliedFile

type AppliedFile struct {
	File
	Start   time.Time
	End     time.Time
	Skipped int           // Amount of skipped SQL statements in a partially applied file.
	Applied []string      // SQL statements applied with success
	Checks  []*FileChecks // Assertion checks
	Error   *struct {
		Stmt string // SQL statement that failed.
		Text string //	 Error returned by the database.
	}
}

AppliedFile is part of a MigrateApply containing information about an applied file in a migration attempt.

type Changes

type Changes struct {
	Applied []string   `json:"Applied,omitempty"` // SQL changes applied with success
	Pending []string   `json:"Pending,omitempty"` // SQL changes that were not applied
	Error   *StmtError `json:"Error,omitempty"`   // Error that occurred during applying
}

Changes represents a list of changes that are pending or applied.

type Check

type Check struct {
	Stmt  string  `json:"Stmt,omitempty"`  // Assertion statement.
	Error *string `json:"Error,omitempty"` // Assertion error, if any.
}

Check represents an assertion and its status.

type Client

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

Client is a client for the Atlas CLI.

func NewClient

func NewClient(workingDir, execPath string) (_ *Client, err error)

NewClient returns a new Atlas client with the given atlas-cli path.

func (*Client) Login

func (c *Client) Login(ctx context.Context, params *LoginParams) error

Login runs the 'login' command.

func (*Client) Logout

func (c *Client) Logout(ctx context.Context) error

Logout runs the 'logout' command.

func (*Client) MigrateApply

func (c *Client) MigrateApply(ctx context.Context, params *MigrateApplyParams) (*MigrateApply, error)

MigrateApply runs the 'migrate apply' command.

func (*Client) MigrateApplySlice

func (c *Client) MigrateApplySlice(ctx context.Context, params *MigrateApplyParams) ([]*MigrateApply, error)

MigrateApplySlice runs the 'migrate apply' command for multiple targets.

func (*Client) MigrateDown

func (c *Client) MigrateDown(ctx context.Context, params *MigrateDownParams) (*MigrateDown, error)

MigrateDown runs the 'migrate down' command.

func (*Client) MigrateLint

func (c *Client) MigrateLint(ctx context.Context, params *MigrateLintParams) (*SummaryReport, error)

MigrateLint runs the 'migrate lint' command.

func (*Client) MigrateLintError

func (c *Client) MigrateLintError(ctx context.Context, params *MigrateLintParams) error

MigrateLintError runs the 'migrate lint' command, the output is written to params.Writer and reports if an error occurred. If the error is a setup error, a Error is returned. If the error is a lint error, LintErr is returned.

func (*Client) MigratePush

func (c *Client) MigratePush(ctx context.Context, params *MigratePushParams) (string, error)

MigratePush runs the 'migrate push' command.

func (*Client) MigrateStatus

func (c *Client) MigrateStatus(ctx context.Context, params *MigrateStatusParams) (*MigrateStatus, error)

MigrateStatus runs the 'migrate status' command.

func (*Client) MigrateTest

func (c *Client) MigrateTest(ctx context.Context, params *MigrateTestParams) (string, error)

MigrateTest runs the 'migrate test' command.

func (*Client) SchemaApply

func (c *Client) SchemaApply(ctx context.Context, params *SchemaApplyParams) (*SchemaApply, error)

SchemaApply runs the 'schema apply' command.

func (*Client) SchemaApplySlice

func (c *Client) SchemaApplySlice(ctx context.Context, params *SchemaApplyParams) ([]*SchemaApply, error)

SchemaApplySlice runs the 'schema apply' command for multiple targets.

func (*Client) SchemaInspect

func (c *Client) SchemaInspect(ctx context.Context, params *SchemaInspectParams) (string, error)

SchemaInspect runs the 'schema inspect' command.

func (*Client) SchemaTest

func (c *Client) SchemaTest(ctx context.Context, params *SchemaTestParams) (string, error)

SchemaTest runs the 'schema test' command.

func (*Client) SetEnv

func (c *Client) SetEnv(env map[string]string) error

SetEnv allows we override the environment variables for the atlas-cli. To append new environment variables to environment from OS, use NewOSEnviron() then add new variables.

func (*Client) Version

func (c *Client) Version(ctx context.Context) (*Version, error)

Version runs the 'version' command.

func (*Client) WithWorkDir

func (c *Client) WithWorkDir(dir string, fn func(*Client) error) error

WithWorkDir creates a new client with the given working directory. It is useful to run multiple commands in the multiple directories.

Example:

client := atlasexec.NewClient("", "atlas")
err := client.WithWorkDir("dir1", func(c *atlasexec.Client) error {
  _, err := c.MigrateApply(ctx, &atlasexec.MigrateApplyParams{
  })
  return err
})

type DeployRunContext

type DeployRunContext struct {
	TriggerType    TriggerType `json:"triggerType,omitempty"`
	TriggerVersion string      `json:"triggerVersion,omitempty"`
}

DeployRunContext is an input type for describing the context in which `migrate-apply` and `migrate down` were used. For example, a GitHub Action with version v1.2.3

type Env

type Env struct {
	Driver string         `json:"Driver,omitempty"` // Driver name.
	URL    *sqlclient.URL `json:"URL,omitempty"`    // URL to dev database.
	Dir    string         `json:"Dir,omitempty"`    // Path to migration directory.
}

Env holds the environment information.

type Environ

type Environ map[string]string

Environ is a map of environment variables.

func NewOSEnviron

func NewOSEnviron() Environ

NewOSEnviron returns the current environment variables from the OS.

func (Environ) ToSlice

func (e Environ) ToSlice() []string

ToSlice converts the environment variables to a slice.

type Error

type Error struct {
	Stdout string
	Stderr string
	// contains filtered or unexported fields
}

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) ExitCode

func (e *Error) ExitCode() int

ExitCode returns the exit code of the command.

func (*Error) Unwrap

func (e *Error) Unwrap() error

type File

type File struct {
	Name        string `json:"Name,omitempty"`
	Version     string `json:"Version,omitempty"`
	Description string `json:"Description,omitempty"`
}

File wraps migrate.File to implement json.Marshaler.

type FileChecks

type FileChecks struct {
	Name  string     `json:"Name,omitempty"`  // File/group name.
	Stmts []*Check   `json:"Stmts,omitempty"` // Checks statements executed.
	Error *StmtError `json:"Error,omitempty"` // Assertion error.
	Start time.Time  `json:"Start,omitempty"` // Start assertion time.
	End   time.Time  `json:"End,omitempty"`   // End assertion time.
}

FileChecks represents a set of checks to run before applying a file.

type FileReport

type FileReport struct {
	Name    string            `json:"Name,omitempty"`    // Name of the file.
	Text    string            `json:"Text,omitempty"`    // Contents of the file.
	Reports []sqlcheck.Report `json:"Reports,omitempty"` // List of reports.
	Error   string            `json:"Error,omitempty"`   // File specific error.
}

FileReport contains a summary of the analysis of a single file.

type LoginParams

type LoginParams struct {
	Token string
}

LoginParams are the parameters for the `login` command.

type MigrateApply

type MigrateApply struct {
	Env
	Pending []File         `json:"Pending,omitempty"` // Pending migration files
	Applied []*AppliedFile `json:"Applied,omitempty"` // Applied files
	Current string         `json:"Current,omitempty"` // Current migration version
	Target  string         `json:"Target,omitempty"`  // Target migration version
	Start   time.Time
	End     time.Time
	// Error is set even then, if it was not caused by a statement in a migration file,
	// but by Atlas, e.g. when committing or rolling back a transaction.
	Error string `json:"Error,omitempty"`
}

MigrateApply contains a summary of a migration applying attempt on a database.

func (*MigrateApply) Summary

func (a *MigrateApply) Summary(ident string) string

Summary of the migration attempt.

type MigrateApplyError

type MigrateApplyError struct {
	Result []*MigrateApply
}

MigrateApplyError is returned when an error occurred during a migration applying attempt.

func (*MigrateApplyError) Error

func (e *MigrateApplyError) Error() string

Error implements the error interface.

type MigrateApplyParams

type MigrateApplyParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	Context   *DeployRunContext
	DirURL    string

	URL             string
	RevisionsSchema string
	BaselineVersion string
	TxMode          string
	ExecOrder       MigrateExecOrder
	Amount          uint64
	AllowDirty      bool
	DryRun          bool
}

MigrateApplyParams are the parameters for the `migrate apply` command.

type MigrateDown

type MigrateDown struct {
	Planned  []File          `json:"Planned,omitempty"`  // Planned migration files
	Reverted []*RevertedFile `json:"Reverted,omitempty"` // Reverted files
	Current  string          `json:"Current,omitempty"`  // Current migration version
	Target   string          `json:"Target,omitempty"`   // Target migration version
	Total    int             `json:"Total,omitempty"`    // Total number of migrations to revert
	Start    time.Time
	End      time.Time
	// URL and Status are set only when the migration is planned or executed in the cloud.
	URL    string `json:"URL,omitempty"`
	Status string `json:"Status,omitempty"`
	// Error is set even then, if it was not caused by a statement in a migration file,
	// but by Atlas, e.g. when committing or rolling back a transaction.
	Error string `json:"Error,omitempty"`
}

MigrateDown contains a summary of a migration down attempt on a database.

type MigrateDownParams

type MigrateDownParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	Context   *DeployRunContext
	DevURL    string

	DirURL          string
	URL             string
	RevisionsSchema string
	Amount          uint64
	ToVersion       string
	ToTag           string
}

MigrateDownParams are the parameters for the `migrate down` command.

type MigrateExecOrder

type MigrateExecOrder string

MigrateExecOrder define how Atlas computes and executes pending migration files to the database. See: https://atlasgo.io/versioned/apply#execution-order

const (
	ExecOrderLinear     MigrateExecOrder = "linear" // Default
	ExecOrderLinearSkip MigrateExecOrder = "linear-skip"
	ExecOrderNonLinear  MigrateExecOrder = "non-linear"
)

ExecutionOrder values.

type MigrateLintParams

type MigrateLintParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	Context   *RunContext
	Format    string
	DevURL    string

	DirURL  string
	Latest  uint64
	Writer  io.Writer
	Base    string
	GitBase string
	Web     bool
}

MigrateLintParams are the parameters for the `migrate lint` command.

func (*MigrateLintParams) AsArgs

func (p *MigrateLintParams) AsArgs() ([]string, error)

AsArgs returns the parameters as arguments.

type MigratePushParams

type MigratePushParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	Context   *RunContext
	DevURL    string

	Name        string
	Tag         string
	DirURL      string
	DirFormat   string
	LockTimeout string
}

MigratePushParams are the parameters for the `migrate push` command.

type MigrateStatus

type MigrateStatus struct {
	Available []File      `json:"Available,omitempty"` // Available migration files
	Pending   []File      `json:"Pending,omitempty"`   // Pending migration files
	Applied   []*Revision `json:"Applied,omitempty"`   // Applied migration files
	Current   string      `json:"Current,omitempty"`   // Current migration version
	Next      string      `json:"Next,omitempty"`      // Next migration version
	Count     int         `json:"Count,omitempty"`     // Count of applied statements of the last revision
	Total     int         `json:"Total,omitempty"`     // Total statements of the last migration
	Status    string      `json:"Status,omitempty"`    // Status of migration (OK, PENDING)
	Error     string      `json:"Error,omitempty"`     // Last Error that occurred
	SQL       string      `json:"SQL,omitempty"`       // SQL that caused the last Error
}

MigrateStatus contains a summary of the migration status of a database.

func (MigrateStatus) Amount

func (r MigrateStatus) Amount(version string) (amount uint64, ok bool)

Amount returns the number of migrations need to apply for the given version.

The second return value is true if the version is found and the database is up-to-date.

If the version is not found, it returns 0 and the second return value is false.

func (MigrateStatus) LatestVersion

func (r MigrateStatus) LatestVersion() string

LatestVersion returns the latest version of the migration directory.

type MigrateStatusParams

type MigrateStatusParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs

	DirURL          string
	URL             string
	RevisionsSchema string
}

MigrateStatusParams are the parameters for the `migrate status` command.

type MigrateTestParams

type MigrateTestParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	Context   *RunContext
	DevURL    string

	DirURL          string
	DirFormat       string
	Run             string
	RevisionsSchema string
}

MigrateTestParams are the parameters for the `migrate test` command.

type Option

type Option func(ce *WorkingDir) error

Option is a function that modifies a ContextExecer.

func WithAtlasHCL

func WithAtlasHCL(fn func(w io.Writer) error) Option

WithAtlasHCL accept a function to create the atlas.hcl file.

func WithAtlasHCLPath

func WithAtlasHCLPath(path string) Option

WithAtlasHCLPath creates the atlas.hcl file by copying the file at the given path.

func WithAtlasHCLString

func WithAtlasHCLString(s string) Option

WithAtlasHCLString creates the atlas.hcl file with the given string.

func WithMigrations

func WithMigrations(dir fs.FS) Option

WithMigrations copies all files from dir to the migrations directory. If dir is nil, no files are copied.

type RevertedFile

type RevertedFile struct {
	File
	Start   time.Time
	End     time.Time
	Skipped int      // Amount of skipped SQL statements in a partially applied file.
	Applied []string // SQL statements applied with success
	Scope   string   // Scope of the revert. e.g., statement, versions, etc.
	Error   *struct {
		Stmt string // SQL statement that failed.
		Text string //	 Error returned by the database.
	}
}

RevertedFile is part of a MigrateDown containing information about a reverted file in a downgrade attempt.

type Revision

type Revision struct {
	Version         string        `json:"Version"`             // Version of the migration.
	Description     string        `json:"Description"`         // Description of this migration.
	Type            string        `json:"Type"`                // Type of the migration.
	Applied         int           `json:"Applied"`             // Applied amount of statements in the migration.
	Total           int           `json:"Total"`               // Total amount of statements in the migration.
	ExecutedAt      time.Time     `json:"ExecutedAt"`          // ExecutedAt is the starting point of execution.
	ExecutionTime   time.Duration `json:"ExecutionTime"`       // ExecutionTime of the migration.
	Error           string        `json:"Error,omitempty"`     // Error of the migration, if any occurred.
	ErrorStmt       string        `json:"ErrorStmt,omitempty"` // ErrorStmt is the statement that raised Error.
	OperatorVersion string        `json:"OperatorVersion"`     // OperatorVersion that executed this migration.
}

A Revision denotes an applied migration in a deployment. Used to track migration executions state of a database.

type RunContext

type RunContext struct {
	Repo     string `json:"repo,omitempty"`
	Path     string `json:"path,omitempty"`
	Branch   string `json:"branch,omitempty"`
	Commit   string `json:"commit,omitempty"`
	URL      string `json:"url,omitempty"`
	Username string `json:"username,omitempty"` // The username that triggered the event that initiated the command.
	UserID   string `json:"userID,omitempty"`   // The user ID that triggered the event that initiated the command.
	SCMType  string `json:"scmType,omitempty"`  // Source control management system type.
}

RunContext is an input type for describing the context of where the command is triggered from. For example, a GitHub Action on the master branch.

type SchemaApply

type SchemaApply struct {
	Env
	Changes Changes `json:"Changes,omitempty"`
	// General error that occurred during execution.
	// e.g., when committing or rolling back a transaction.
	Error string `json:"Error,omitempty"`
}

SchemaApply contains a summary of a 'schema apply' execution on a database.

type SchemaApplyError

type SchemaApplyError struct {
	Result []*SchemaApply
}

SchemaApplyError is returned when an error occurred during a schema applying attempt.

func (*SchemaApplyError) Error

func (e *SchemaApplyError) Error() string

Error implements the error interface.

type SchemaApplyParams

type SchemaApplyParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	DevURL    string

	URL     string
	To      string
	TxMode  string
	Exclude []string
	Schema  []string
	DryRun  bool
}

SchemaApplyParams are the parameters for the `schema apply` command.

type SchemaInspectParams

type SchemaInspectParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	Format    string
	DevURL    string

	URL     string
	Exclude []string
	Schema  []string
}

SchemaInspectParams are the parameters for the `schema inspect` command.

type SchemaTestParams

type SchemaTestParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	DevURL    string

	URL string
	Run string
}

SchemaTestParams are the parameters for the `schema test` command.

type StepReport

type StepReport struct {
	Name   string      `json:"Name,omitempty"`   // Step name.
	Text   string      `json:"Text,omitempty"`   // Step description.
	Error  string      `json:"Error,omitempty"`  // Error that cause the execution to halt.
	Result *FileReport `json:"Result,omitempty"` // Result of the step. For example, a diagnostic.
}

StepReport contains a summary of the analysis of a single step.

type StmtError

type StmtError struct {
	Stmt string `json:"Stmt,omitempty"` // SQL statement that failed.
	Text string `json:"Text,omitempty"` // Error message as returned by the database.
}

StmtError groups a statement with its execution error.

type SummaryReport

type SummaryReport struct {
	URL string `json:"URL,omitempty"` // URL of the report, if exists.
	// Env holds the environment information.
	Env struct {
		Driver string         `json:"Driver,omitempty"` // Driver name.
		URL    *sqlclient.URL `json:"URL,omitempty"`    // URL to dev database.
		Dir    string         `json:"Dir,omitempty"`    // Path to migration directory.
	}
	// Schema versions found by the runner.
	Schema struct {
		Current string `json:"Current,omitempty"` // Current schema.
		Desired string `json:"Desired,omitempty"` // Desired schema.
	}
	// Steps of the analysis. Added in verbose mode.
	Steps []*StepReport `json:"Steps,omitempty"`
	// Files reports. Non-empty in case there are findings.
	Files []*FileReport `json:"Files,omitempty"`
}

A SummaryReport contains a summary of the analysis of all files. It is used as an input to templates to report the CI results.

func (*SummaryReport) DiagnosticsCount

func (r *SummaryReport) DiagnosticsCount() int

DiagnosticsCount returns the total number of diagnostics in the report.

type TriggerType

type TriggerType string

TriggerType defines the type for the "trigger_type" enum field.

const (
	TriggerTypeCLI          TriggerType = "CLI"
	TriggerTypeKubernetes   TriggerType = "KUBERNETES"
	TriggerTypeTerraform    TriggerType = "TERRAFORM"
	TriggerTypeGithubAction TriggerType = "GITHUB_ACTION"
	TriggerTypeCircleCIOrb  TriggerType = "CIRCLECI_ORB"
)

TriggerType values.

type VarArgs

type VarArgs interface {
	// AsArgs returns the variables as arguments.
	AsArgs() []string
}

VarArgs is a map of variables for the command.

type Vars deprecated

type Vars map[string]string

Vars is a map of variables for the command.

Deprecated: Use Vars2 instead.

func (Vars) AsArgs

func (v Vars) AsArgs() []string

AsArgs returns the variables as arguments.

type Vars2

type Vars2 map[string]any

Vars2 is a map of variables for the command. It supports multiple values for the same key (list).

func (Vars2) AsArgs

func (v Vars2) AsArgs() []string

AsArgs returns the variables as arguments.

type Version

type Version struct {
	Version string `json:"Version"`
	SHA     string `json:"SHA,omitempty"`
	Canary  bool   `json:"Canary,omitempty"`
}

Version contains the result of an 'atlas version' run.

func (Version) String

func (v Version) String() string

var reVersion = regexp.MustCompile(`^atlas version v(\d+\.\d+.\d+)-?([a-z0-9]*)?`)

type WorkingDir

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

WorkingDir is a temporary directory with a copy of the files from dir. It can be used to run commands in the temporary directory. The temporary directory is removed when Close is called.

func NewWorkingDir

func NewWorkingDir(opts ...Option) (*WorkingDir, error)

NewWorkingDir creates a new ContextExecer. It creates a temporary directory and copies all files from dir to the temporary directory. The atlasHCL function is called with a writer to create the atlas.hcl file. If atlasHCL is nil, no atlas.hcl file is created.

func (*WorkingDir) Close

func (ce *WorkingDir) Close() error

Close removes the temporary directory.

func (*WorkingDir) CopyFS

func (cs *WorkingDir) CopyFS(name string, src fs.FS) error

CopyFS copies all files from source FileSystem to the destination directory in the temporary directory. If source is nil, an error is returned.

func (*WorkingDir) CreateFile

func (ce *WorkingDir) CreateFile(name string, fn func(w io.Writer) error) error

CreateFile creates the file in the temporary directory.

func (*WorkingDir) DirFS

func (ce *WorkingDir) DirFS() fs.FS

DirFS returns a fs.FS for the temporary directory.

func (*WorkingDir) Path

func (ce *WorkingDir) Path(elem ...string) string

Dir returns the path to the temporary directory.

func (*WorkingDir) RunCommand

func (ce *WorkingDir) RunCommand(cmd *exec.Cmd) error

RunCommand runs the command in the temporary directory.

func (*WorkingDir) WriteFile

func (ce *WorkingDir) WriteFile(name string, data []byte) (string, error)

WriteFile writes the file to the temporary directory.

Directories

Path Synopsis
internal
e2e

Jump to

Keyboard shortcuts

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