cmdlog

package
v0.13.2-0...-194c365 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ColorCyan         = color.CyanString
	ColorGray         = color.New(color.Attribute(90))
	ColorGreen        = color.HiGreenString
	ColorRed          = color.HiRedString
	ColorRedBgWhiteFg = color.New(color.FgHiWhite, color.BgHiRed).SprintFunc()
	ColorYellow       = color.YellowString
	// ColorTemplateFuncs are globally available functions to color strings in a report template.
	ColorTemplateFuncs = template.FuncMap{
		"cyan":         ColorCyan,
		"green":        ColorGreen,
		"red":          ColorRed,
		"redBgWhiteFg": ColorRedBgWhiteFg,
		"yellow":       ColorYellow,
	}
)
View Source
var (
	// StatusTemplateFuncs are global functions available in status report templates.
	StatusTemplateFuncs = WithColorFuncs(template.FuncMap{
		"json":       jsonEncode,
		"json_merge": jsonMerge,
		"default": func(report *MigrateStatus) (string, error) {
			var buf bytes.Buffer
			t, err := template.New("report").
				Funcs(template.FuncMap{
					"add": add,
				}).
				Funcs(ColorTemplateFuncs).
				Parse(`Migration Status:
{{- if eq .Status "OK" }} {{ green .Status }}{{ end }}
{{- if eq .Status "PENDING" }} {{ yellow .Status }}{{ end }}
  {{ yellow "--" }} Current Version: {{ cyan .Current }}
{{- if gt .Total 0 }}{{ printf " (%s statements applied)" (yellow "%d" .Count) }}{{ end }}
  {{ yellow "--" }} Next Version:    {{ if .Next }}{{ cyan .Next }}{{ if .FromCheckpoint }} (checkpoint){{ end }}{{ else }}UNKNOWN{{ end }}
{{- if gt .Total 0 }}{{ printf " (%s statements left)" (yellow "%d" .Left) }}{{ end }}
  {{ yellow "--" }} Executed Files:  {{ len .Applied }}{{ if gt .Total 0 }} (last one partially){{ end }}
  {{ yellow "--" }} Pending Files:   {{ add (len .Pending) (len .OutOfOrder) }}{{ if .OutOfOrder }} ({{ if .Pending }}{{ len .OutOfOrder }} {{ end }}out of order){{ end }}
{{- if gt .Total 0 }}

Last migration attempt had errors:
  {{ yellow "--" }} SQL:   {{ .SQL }}
  {{ yellow "--" }} {{ red "ERROR:" }} {{ .Error }}
{{- else if and .OutOfOrder .Error }}

  {{ red "ERROR:" }} {{ .Error }}
{{- end }}
`)
			if err != nil {
				return "", err
			}
			err = t.Execute(&buf, report)
			return buf.String(), err
		},
	})

	// MigrateStatusTemplate holds the default template of the 'migrate status' command.
	MigrateStatusTemplate = template.Must(template.New("report").Funcs(StatusTemplateFuncs).Parse("{{ default . }}"))
)
View Source
var (
	// ApplyTemplateFuncs are global functions available in apply report templates.
	ApplyTemplateFuncs = WithColorFuncs(template.FuncMap{
		"add":        add,
		"upper":      strings.ToUpper,
		"json":       jsonEncode,
		"json_merge": jsonMerge,
		"indent_ln":  indentLn,
	})

	// MigrateApplyTemplate holds the default template of the 'migrate apply' command.
	MigrateApplyTemplate = template.Must(template.
							New("report").
							Funcs(ApplyTemplateFuncs).
							Parse(`{{- if not .Pending -}}
{{- println "No migration files to execute" }}
{{- else -}}
{{- println .Header }}
{{- range $i, $f := .Applied }}
	{{- println }}
	{{- $checkFailed := false }}
	{{- range $cf := $f.Checks }}
		{{- println " " (yellow "--") "checks before migrating version" (cyan $f.File.Version) }}
		{{- range $s := $cf.Stmts }}
			{{- if $s.Error }}
				{{- println "   " (red "->") (indent_ln $s.Stmt 7) }}
			{{- else }}
				{{- println "   " (cyan "->") (indent_ln $s.Stmt 7) }}
			{{- end }}
		{{- end }}
		{{- with $cf.Error }}
			{{- $checkFailed = true }}
			{{- println "   " (redBgWhiteFg .Text) }}
		{{- else }}
			{{- printf "  %s ok (%s)\n\n" (yellow "--") (yellow ($cf.End.Sub $cf.Start).String) }}
		{{- end }}
	{{- end }}
	{{- if $checkFailed }}
		{{- continue }} {{- /* No statements were applied. */}}
	{{- end }}
	{{- println " " (yellow "--") "migrating version" (cyan $f.File.Version) }}
	{{- range $f.Applied }}
		{{- println "   " (cyan "->") (indent_ln . 7) }}
	{{- end }}
	{{- with .Error }}
		{{- println "   " (redBgWhiteFg .Text) }}
	{{- else }}
		{{- printf "  %s ok (%s)\n" (yellow "--") (yellow (.End.Sub .Start).String) }}
	{{- end }}
{{- else }}
	{{- println }}
	{{- with .Error }}
		{{- println "   " (redBgWhiteFg .) }}
	{{- end }}
{{- end }}
{{- println }}
{{- println " " (cyan "-------------------------") }}
{{- println " " (.Summary "  ") }}
{{- end -}}
`))
)
View Source
var (
	// InspectTemplateFuncs are global functions available in inspect report templates.
	InspectTemplateFuncs = template.FuncMap{
		"base64url": base64url,
		"sql":       sqlInspect,
		"json":      jsonEncode,
		"mermaid":   mermaid,
	}

	// SchemaInspectTemplate holds the default template of the 'schema inspect' command.
	SchemaInspectTemplate = template.Must(template.New("inspect").
							Funcs(InspectTemplateFuncs).
							Parse(`{{ $.MarshalHCL }}`))
)
View Source
var (
	// SchemaDiffFuncs are global functions available in diff report templates.
	SchemaDiffFuncs = template.FuncMap{
		"sql": sqlDiff,
	}
	// SchemaDiffTemplate holds the default template of the 'schema diff' command.
	SchemaDiffTemplate = template.Must(template.
						New("schema_diff").
						Funcs(SchemaDiffFuncs).
						Parse(`{{- with .Changes -}}
{{ sql $ }}
{{- else -}}
Schemas are synced, no changes to be made.
{{ end -}}
`))
)
View Source
var MigrateSetTemplate = template.Must(template.New("set").
	Funcs(ColorTemplateFuncs).Parse(`
{{- if and (not .Current) .Revisions -}}
All revisions deleted ({{ len .Revisions }} in total):
{{ else if and .Current .Revisions -}}
Current version is {{ cyan .Current.Version }} ({{ .Summary }}):
{{ end }}
{{- if .Revisions }}
{{ range .ByVersion }}
  {{- $text := .ColoredVersion }}{{ with .Description }}{{ $text = printf "%s (%s)" $text . }}{{ end }}
  {{- printf "  %s\n" $text }}
{{- end }}
{{ end -}}
`))

MigrateSetTemplate holds the default template of the 'migrate set' command.

View Source
var SchemaPlanTemplate = template.Must(template.
	New("plan").
	Funcs(ApplyTemplateFuncs).
	Parse(`{{- with .Changes.Pending -}}
-- Planned Changes:
{{ range . -}}
{{- if .Comment -}}
{{- printf "-- %s%s\n" (slice .Comment 0 1 | upper ) (slice .Comment 1) -}}
{{- end -}}
{{- printf "%s;\n" .Cmd -}}
{{- end -}}
{{- else -}}
Schema is synced, no changes to be made
{{ end -}}
`))

SchemaPlanTemplate holds the default template of the 'schema apply --dry-run' command.

Functions

func WarnOnce

func WarnOnce(w io.Writer, text string) error

WarnOnce allow writing warning messages to the given writer, but ensures only one message will be written in process run.

func WithColorFuncs

func WithColorFuncs(f template.FuncMap) template.FuncMap

WithColorFuncs extends the given template.FuncMap with the color functions.

Types

type AppliedFile

type AppliedFile struct {
	migrate.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   *StmtError
}

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

func (*AppliedFile) MarshalJSON

func (f *AppliedFile) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

type Changes

type Changes struct {
	Applied []*migrate.Change `json:"Applied,omitempty"` // SQL changes applied with success
	Pending []*migrate.Change `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.

func (Changes) MarshalJSON

func (c Changes) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

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 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.

func NewEnv

func NewEnv(c *sqlclient.Client, dirURL *url.URL) Env

NewEnv returns an initialized Env.

type File

type File struct{ migrate.File }

File wraps migrate.File to implement json.Marshaler.

func (File) MarshalJSON

func (f File) MarshalJSON() ([]byte, error)

MarshalJSON implements 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 Files

type Files []migrate.File

Files is a slice of migrate.File. Implements json.Marshaler.

func (Files) MarshalJSON

func (f Files) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

type MigrateApply

type MigrateApply struct {
	Env
	Pending Files          `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"`
	// contains filtered or unexported fields
}

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

func NewMigrateApply

func NewMigrateApply(ctx context.Context, client *sqlclient.Client, dirURL *url.URL) *MigrateApply

NewMigrateApply returns an MigrateApply.

func (*MigrateApply) Header

func (a *MigrateApply) Header() string

Header returns a header of the migration log.

func (*MigrateApply) Log

func (a *MigrateApply) Log(e migrate.LogEntry)

Log implements migrate.Logger.

func (*MigrateApply) MarshalJSON added in v0.9.0

func (a *MigrateApply) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*MigrateApply) Summary

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

Summary returns a footer of the migration log.

type MigrateSet added in v0.9.1

type MigrateSet struct {

	// Revisions that were added, removed or updated.
	Revisions []RevisionOp `json:"Revisions,omitempty"`
	// Current version in the revisions table.
	Current *migrate.Revision `json:"Latest,omitempty"`
	// contains filtered or unexported fields
}

MigrateSet contains a summary of the migrate set command.

func NewMigrateSet

func NewMigrateSet(ctx context.Context) *MigrateSet

NewMigrateSet returns a MigrateSet.

func (*MigrateSet) ByVersion added in v0.9.1

func (r *MigrateSet) ByVersion() []RevisionOp

ByVersion returns all revisions sorted by version.

func (*MigrateSet) Removed added in v0.9.1

func (r *MigrateSet) Removed(rev *migrate.Revision)

Removed records revision that was added.

func (*MigrateSet) Set added in v0.9.1

func (r *MigrateSet) Set(rev *migrate.Revision)

Set records revision that was added.

func (*MigrateSet) Summary added in v0.9.1

func (r *MigrateSet) Summary() string

Summary returns a summary of the set operation.

type MigrateStatus

type MigrateStatus struct {
	Env        `json:"Env"`
	Available  Files               `json:"Available,omitempty"`  // Available migration files
	OutOfOrder Files               `json:"OutOfOrder,omitempty"` // OutOfOrder migration files
	Pending    Files               `json:"Pending,omitempty"`    // Pending migration files
	Applied    []*migrate.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) FromCheckpoint

func (r *MigrateStatus) FromCheckpoint() bool

FromCheckpoint reports if we start from a checkpoint version Hence, the first file to be executed on the database is checkpoint.

func (*MigrateStatus) Left

func (r *MigrateStatus) Left() int

Left returns the amount of statements left to apply (if any).

type RevisionOp added in v0.9.1

type RevisionOp struct {
	*migrate.Revision
	Op string `json:"Op,omitempty"`
}

RevisionOp represents an operation done on a revision.

func (*RevisionOp) ColoredVersion added in v0.9.1

func (r *RevisionOp) ColoredVersion() string

ColoredVersion returns the version of the revision with a color.

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"`
	// contains filtered or unexported fields
}

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

func NewSchemaApply

func NewSchemaApply(ctx context.Context, env Env, applied, pending []*migrate.Change, err *StmtError) *SchemaApply

NewSchemaApply returns a SchemaApply.

func NewSchemaPlan

func NewSchemaPlan(ctx context.Context, env Env, pending []*migrate.Change, err *StmtError) *SchemaApply

NewSchemaPlan returns a SchemaApply only with pending changes.

type SchemaDiff added in v0.10.0

type SchemaDiff struct {
	From, To *schema.Realm
	Changes  []schema.Change
	// contains filtered or unexported fields
}

SchemaDiff contains a summary of the 'schema diff' command.

func NewSchemaDiff

func NewSchemaDiff(ctx context.Context, client *sqlclient.Client, from, to *schema.Realm, changes []schema.Change) *SchemaDiff

NewSchemaDiff returns a SchemaDiff.

func (*SchemaDiff) Client

func (s *SchemaDiff) Client() *sqlclient.Client

Client returns the client used to inspect the schema.

func (*SchemaDiff) MarshalSQL added in v0.13.0

func (s *SchemaDiff) MarshalSQL(indent ...string) (string, error)

MarshalSQL returns the default SQL representation of the schema.

type SchemaInspect added in v0.9.0

type SchemaInspect struct {
	Realm *schema.Realm `json:"Schema,omitempty"` // Inspected realm.
	// contains filtered or unexported fields
}

SchemaInspect contains a summary of the 'schema inspect' command.

func NewSchemaInspect

func NewSchemaInspect(ctx context.Context, client *sqlclient.Client, realm *schema.Realm) *SchemaInspect

NewSchemaInspect returns a SchemaInspect.

func (*SchemaInspect) Client

func (s *SchemaInspect) Client() *sqlclient.Client

Client returns the client used to inspect the schema.

func (*SchemaInspect) MarshalHCL added in v0.9.0

func (s *SchemaInspect) MarshalHCL() (string, error)

MarshalHCL returns the default HCL representation of the schema. Used by the template declared above.

func (*SchemaInspect) MarshalJSON added in v0.9.0

func (s *SchemaInspect) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*SchemaInspect) MarshalSQL added in v0.12.1

func (s *SchemaInspect) MarshalSQL(indent ...string) (string, error)

MarshalSQL returns the default SQL representation of the schema.

type StatusReporter

type StatusReporter struct {
	// Client configures the connection to the database to file a MigrateStatus for.
	Client *sqlclient.Client
	// DirURL of the migration directory.
	DirURL *url.URL
	// Dir is used for scanning and validating the migration directory.
	Dir migrate.Dir
	// Schema name the revision table resides in.
	Schema string
}

StatusReporter is used to gather information about migration status.

func (*StatusReporter) Report

func (r *StatusReporter) Report(ctx context.Context) (*MigrateStatus, error)

Report creates and writes a MigrateStatus.

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.

Source Files

  • cmdlog.go
  • cmdlog_oss.go

Jump to

Keyboard shortcuts

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