atlasexec

package
v0.37.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2025 License: Apache-2.0 Imports: 23 Imported by: 1

README

Atlas SDK for Go

Go Reference

An SDK for building ariga/atlas providers in Go.

Installation

go get -u ariga.io/atlas@master

How to use

To use the SDK, you need to create a new client with your migrations folder and the atlas binary path.

package main

import (
    ...
    "ariga.io/atlas/atlasexec"
)

func main() {
    // Create a new client
    client, err := atlasexec.NewClient("my-migration-folder", "my-atlas-cli-path")
    if err != nil {
        log.Fatalf("failed to create client: %v", err)
    }
}

APIs

For more information, refer to the documentation available at GoDoc

Documentation

Index

Examples

Constants

View Source
const (
	CopilotTypeMessage    = "message"
	CopilotTypeToolCall   = "tool_call"
	CopilotTypeToolOutput = "tool_output"
)

CopilotTypeMessage, CopilotTypeToolCall, and CopilotTypeToolOutput are the types of messages that can be emitted by the Copilot execution.

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
)
View Source
var ErrRequireLogin = errors.New("command requires 'atlas login'")

ErrRequireLogin is returned when a command requires the user to be logged in. It exists here to be shared between the different packages that require login.

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) Copilot

func (c *Client) Copilot(ctx context.Context, params *CopilotParams) (Copilot, error)

Copilot executes a one-shot Copilot session with the provided options.

func (*Client) CopilotStream

func (c *Client) CopilotStream(ctx context.Context, params *CopilotParams) (Stream[*CopilotMessage], error)

CopilotStream executes a one-shot Copilot session, streaming the result.

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.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"ariga.io/atlas/atlasexec"
)

func main() {
	// Define the execution context, supplying a migration directory
	// and potentially an `atlas.hcl` configuration file using `atlasexec.WithHCL`.
	workdir, err := atlasexec.NewWorkingDir(
		atlasexec.WithMigrations(
			os.DirFS("./migrations"),
		),
	)
	if err != nil {
		log.Fatalf("failed to load working directory: %v", err)
	}
	// atlasexec works on a temporary directory, so we need to close it
	defer workdir.Close()

	// Initialize the client.
	client, err := atlasexec.NewClient(workdir.Path(), "atlas")
	if err != nil {
		log.Fatalf("failed to initialize client: %v", err)
	}
	// Run `atlas migrate apply` on a SQLite database under /tmp.
	res, err := client.MigrateApply(context.Background(), &atlasexec.MigrateApplyParams{
		URL: "sqlite:///tmp/demo.db?_fk=1&cache=shared",
	})
	if err != nil {
		log.Fatalf("failed to apply migrations: %v", err)
	}
	fmt.Printf("Applied %d migrations\n", len(res.Applied))
}

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) MigrateDiff

func (c *Client) MigrateDiff(ctx context.Context, params *MigrateDiffParams) (*MigrateDiff, error)

MigrateDiff runs the 'migrate diff --dry-run' command and returns the generated migration files without changing the filesystem. Requires atlas CLI to be logged in to the cloud.

func (*Client) MigrateDown

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

MigrateDown runs the 'migrate down' command.

func (*Client) MigrateHash

func (c *Client) MigrateHash(ctx context.Context, params *MigrateHashParams) error

MigrateHash runs the 'migrate hash' 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) MigrateRebase

func (c *Client) MigrateRebase(ctx context.Context, params *MigrateRebaseParams) error

MigrateRebase runs the 'migrate rebase' 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) SchemaClean

func (c *Client) SchemaClean(ctx context.Context, params *SchemaCleanParams) (*SchemaClean, error)

SchemaClean runs the `schema clean` command.

func (*Client) SchemaInspect

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

SchemaInspect runs the 'schema inspect' command.

func (*Client) SchemaLint

func (c *Client) SchemaLint(ctx context.Context, params *SchemaLintParams) (*SchemaLintReport, error)

SchemaLint runs the 'schema lint' command.

func (*Client) SchemaPlan

func (c *Client) SchemaPlan(ctx context.Context, params *SchemaPlanParams) (*SchemaPlan, error)

SchemaPlan runs the `schema plan` command.

func (*Client) SchemaPlanApprove

func (c *Client) SchemaPlanApprove(ctx context.Context, params *SchemaPlanApproveParams) (*SchemaPlanApprove, error)

SchemaPlanApprove runs the `schema plan approve` command.

func (*Client) SchemaPlanLint

func (c *Client) SchemaPlanLint(ctx context.Context, params *SchemaPlanLintParams) (*SchemaPlan, error)

SchemaPlanLint runs the `schema plan lint` command.

func (*Client) SchemaPlanList

func (c *Client) SchemaPlanList(ctx context.Context, params *SchemaPlanListParams) ([]SchemaPlanFile, error)

SchemaPlanList runs the `schema plan list` command.

func (*Client) SchemaPlanPull

func (c *Client) SchemaPlanPull(ctx context.Context, params *SchemaPlanPullParams) (string, error)

SchemaPlanPush runs the `schema plan pull` command.

func (*Client) SchemaPlanPush

func (c *Client) SchemaPlanPush(ctx context.Context, params *SchemaPlanPushParams) (string, error)

SchemaPlanPush runs the `schema plan push` command.

func (*Client) SchemaPlanValidate

func (c *Client) SchemaPlanValidate(ctx context.Context, params *SchemaPlanValidateParams) error

SchemaPlanValidate runs the `schema plan validate` command.

func (*Client) SchemaPush

func (c *Client) SchemaPush(ctx context.Context, params *SchemaPushParams) (*SchemaPush, error)

SchemaPush runs the 'schema push' 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) SetStderr

func (c *Client) SetStderr(w io.Writer)

SetStderr specifies a writer to stream stderr to for every command.

func (*Client) SetStdout

func (c *Client) SetStdout(w io.Writer)

SetStdout specifies a writer to stream stdout to for every command.

func (*Client) Version

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

Version runs the 'version' command.

func (*Client) WhoAmI

func (c *Client) WhoAmI(ctx context.Context, params *WhoAmIParams) (*WhoAmI, error)

WhoAmI runs the 'whoami' 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 Copilot

type Copilot []*CopilotMessage

Copilot is the result of a Copilot execution.

func (Copilot) String

func (c Copilot) String() string

type CopilotMessage

type CopilotMessage struct {
	// Session ID for the Copilot session.
	SessionID string `json:"sessionID,omitempty"`

	// Type of the message. Can be "message", "tool_call", or "tool_output".
	Type string `json:"type"`

	// Content, ToolCall and ToolOutput are mutually exclusive.
	Content    string             `json:"content,omitempty"`
	ToolCall   *ToolCallMessage   `json:"toolCall,omitempty"`
	ToolOutput *ToolOutputMessage `json:"toolOutput,omitempty"`
}

CopilotMessage is the JSON message emitted by the Copilot OneShot execution.

type CopilotParams

type CopilotParams struct {
	Prompt, Session string
	// FSWrite and FSDelete glob patterns to specify file permissions.
	FSWrite, FSDelete string
}

CopilotParams are the parameters for the Copilot execution.

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 Diagnostic

type Diagnostic struct {
	Pos  *schema.Pos `json:"Pos,omitempty"`  // Element position.
	Text string      `json:"Text"`           // Diagnostic text.
	Code string      `json:"Code,omitempty"` // Code describes the check (optional).
}

A Diagnostic is a text associated with a specific position of a definition/element in a file.

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 // Stdout of the command.
	Stderr string // Stderr of the command.
	// contains filtered or unexported fields
}

Error is an error returned by the atlasexec package, when it executes the atlas-cli command.

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. If the error is not an exec.ExitError, it returns 1.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error.

type File

type File struct {
	Name        string `json:"Name,omitempty"`
	Version     string `json:"Version,omitempty"`
	Description string `json:"Description,omitempty"`
	Content     string `json:"Content,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 InvalidParamsError

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

InvalidParamsError is an error type for invalid parameters.

func (*InvalidParamsError) Error

func (e *InvalidParamsError) Error() string

Error returns the error message.

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
	Stderr string
}

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
	ToVersion       string
	AllowDirty      bool
	DryRun          bool
}

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

type MigrateDiff

type MigrateDiff struct {
	Files []File `json:"Files,omitempty"` // Generated migration files
	Dir   string `json:"Dir,omitempty"`   // Path to migration directory
}

MigrateDiff contains the result of the `migrate diff` command.

type MigrateDiffParams

type MigrateDiffParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs

	Name        string
	ToURL       string
	DevURL      string
	DirURL      string
	DirFormat   string
	Schema      []string
	LockTimeout string
	Format      string
	Qualifier   string
}

MigrateDiffParams are the parameters for the `migrate diff` 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 MigrateHashParams

type MigrateHashParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs

	DirURL    string
	DirFormat string
}

MigrateHashParams are the parameters for the `migrate hash` command.

type MigrateLintParams

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

	DirURL string
	Latest uint64
	Writer io.Writer
	Base   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 MigrateRebaseParams

type MigrateRebaseParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs

	DirURL string
	Files  []string
}

MigrateRebaseParams are the parameters for the `migrate rebase` command.

type MigrateStatus

type MigrateStatus struct {
	Env       Env         `json:"Env,omitempty"`       // Environment info.
	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
	Paths           []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 Report

type Report struct {
	Text        string       `json:"Text"`                  // Report text.
	Desc        string       `json:"Desc,omitempty"`        // Optional description (secondary text).
	Error       bool         `json:"Error,omitempty"`       // Report is an error report.
	Diagnostics []Diagnostic `json:"Diagnostics,omitempty"` // Report diagnostics.
}

A Report describes a schema analysis report with an optional specific diagnostic.

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  SCMType `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 SCMType

type SCMType string

SCMType is a type for the "scm_type" enum field.

const (
	SCMTypeGithub      SCMType = "GITHUB"
	SCMTypeGitlab      SCMType = "GITLAB"
	SCMTypeBitbucket   SCMType = "BITBUCKET"
	SCMTypeAzureDevOps SCMType = "AZURE_DEVOPS"
)

SCMType values.

type SchemaApply

type SchemaApply struct {
	Env
	// Changes holds the changes applied to the database.
	// Exists for backward compatibility with the old schema
	// apply structure as old SDK versions rely on it.
	Changes Changes      `json:"Changes,omitempty"`
	Error   string       `json:"Error,omitempty"`   // Any error that occurred during execution.
	Start   time.Time    `json:"Start,omitempty"`   // When apply (including plan) started.
	End     time.Time    `json:"End,omitempty"`     // When apply ended.
	Applied *AppliedFile `json:"Applied,omitempty"` // Applied migration file (pre-planned or computed).
	// Plan information might be partially filled. For example, if lint is done
	// during plan-stage, the linting report is available in the Plan field. If
	// the migration is pre-planned migration, the File.URL is set, etc.
	Plan *SchemaPlan `json:"Plan,omitempty"`
}

SchemaApply represents the result of a 'schema apply' command.

type SchemaApplyError

type SchemaApplyError struct {
	Result []*SchemaApply
	Stderr string
}

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 // TODO: change to []string
	TxMode      string
	Exclude     []string
	Include     []string
	Schema      []string
	DryRun      bool   // If true, --dry-run is set.
	AutoApprove bool   // If true, --auto-approve is set.
	PlanURL     string // URL of the plan in Atlas format (atlas://<repo>/plans/<id>). (optional)
}

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

type SchemaClean

type SchemaClean struct {
	Env
	Start   time.Time    `json:"Start,omitempty"`   // When clean started.
	End     time.Time    `json:"End,omitempty"`     // When clean ended.
	Applied *AppliedFile `json:"Applied,omitempty"` // Applied migration file.
	Error   string       `json:"Error,omitempty"`   // Any error that occurred during execution.
}

SchemaClean represents the result of a 'schema clean' command.

type SchemaCleanParams

type SchemaCleanParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs

	URL         string // URL of the schema to clean. (required)
	DryRun      bool   // If true, --dry-run is set.
	AutoApprove bool   // If true, --auto-approve is set.
}

SchemaCleanParams are the parameters for the `schema clean` command.

type SchemaInspectParams

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

	URL     string
	Exclude []string
	Include []string
	Schema  []string
}

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

type SchemaLintParams

type SchemaLintParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs

	URL    []string // Schema URL(s) to lint
	Schema []string // If set, only the specified schemas are linted.
	Format string
	DevURL string
}

SchemaLintParams are the parameters for the `schema lint` command.

func (*SchemaLintParams) AsArgs

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

AsArgs returns the parameters as arguments.

type SchemaLintReport

type SchemaLintReport struct {
	Steps []Report `json:"Steps,omitempty"`
}

SchemaLintReport holds the results of a schema lint operation

type SchemaPlan

type SchemaPlan struct {
	Env   Env             `json:"Env,omitempty"`   // Environment info.
	Repo  string          `json:"Repo,omitempty"`  // Repository name.
	Lint  *SummaryReport  `json:"Lint,omitempty"`  // Lint report.
	File  *SchemaPlanFile `json:"File,omitempty"`  // Plan file.
	Error string          `json:"Error,omitempty"` // Any error occurred during planning.
}

SchemaPlan is the result of a 'schema plan' command.

type SchemaPlanApprove

type SchemaPlanApprove struct {
	URL    string `json:"URL,omitempty"`    // URL of the plan in Atlas format.
	Link   string `json:"Link,omitempty"`   // Link to the plan in the registry.
	Status string `json:"Status,omitempty"` // Status of the plan in the registry.
}

SchemaPlanApprove is the result of a 'schema plan approve' command.

type SchemaPlanApproveParams

type SchemaPlanApproveParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs

	URL string
}

SchemaPlanApproveParams are the parameters for the `schema plan approve` command.

type SchemaPlanFile

type SchemaPlanFile struct {
	Name      string          `json:"Name,omitempty"`      // Name of the plan.
	FromHash  string          `json:"FromHash,omitempty"`  // Hash of the 'from' realm.
	FromDesc  string          `json:"FromDesc,omitempty"`  // Optional description of the 'from' state.
	ToHash    string          `json:"ToHash,omitempty"`    // Hash of the 'to' realm.
	ToDesc    string          `json:"ToDesc,omitempty"`    // Optional description of the 'to' state.
	Migration string          `json:"Migration,omitempty"` // Migration SQL.
	Stmts     []*migrate.Stmt `json:"Stmts,omitempty"`     // Statements in the migration (available only in the JSON output).
	// registry only fields.
	URL    string `json:"URL,omitempty"`    // URL of the plan in Atlas format.
	Link   string `json:"Link,omitempty"`   // Link to the plan in the registry.
	Status string `json:"Status,omitempty"` // Status of the plan in the registry.
}

SchemaPlanFile is a JSON representation of a schema plan file.

type SchemaPlanLintParams

type SchemaPlanLintParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	Context   *RunContext
	DevURL    string
	Schema    []string
	Exclude   []string
	Include   []string

	From, To []string
	Repo     string
	File     string
}

SchemaPlanLintParams are the parameters for the `schema plan lint` command.

type SchemaPlanListParams

type SchemaPlanListParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	Context   *RunContext
	DevURL    string
	Schema    []string
	Exclude   []string
	Include   []string

	From, To []string
	Repo     string
	Pending  bool // If true, only pending plans are listed.
}

SchemaPlanListParams are the parameters for the `schema plan list` command.

type SchemaPlanParams

type SchemaPlanParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	Context   *RunContext
	DevURL    string
	Exclude   []string
	Include   []string
	Schema    []string

	From, To   []string
	Repo       string
	Name       string
	Directives []string
	// The below are mutually exclusive and can be replaced
	// with the 'schema plan' sub-commands instead.
	DryRun     bool // If false, --auto-approve is set.
	Pending    bool
	Push, Save bool
}

SchemaPlanParams are the parameters for the `schema plan` command.

type SchemaPlanPullParams

type SchemaPlanPullParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	URL       string // URL to the plan in Atlas format. (required)
}

SchemaPlanPullParams are the parameters for the `schema plan pull` command.

type SchemaPlanPushParams

type SchemaPlanPushParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	Context   *RunContext
	DevURL    string
	Schema    []string
	Exclude   []string
	Include   []string

	From, To []string
	Repo     string
	Pending  bool   // Push plan in pending state.
	File     string // File to push. (optional)
}

SchemaPlanPushParams are the parameters for the `schema plan push` command.

type SchemaPlanValidateParams

type SchemaPlanValidateParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
	Context   *RunContext
	DevURL    string
	Schema    []string
	Exclude   []string
	Include   []string

	From, To []string
	Repo     string
	Name     string
	File     string
}

SchemaPlanValidateParams are the parameters for the `schema plan validate` command.

type SchemaPush

type SchemaPush struct {
	Link string
	Slug string
	URL  string
}

SchemaPush represents the result of a 'schema push' command.

type SchemaPushParams

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

	URL         []string // Desired schema URL(s) to push
	Schema      []string // If set, only the specified schemas are pushed.
	Name        string   // Name of the schema (repo) to push to.
	Tag         string   // Tag to push the schema with
	Version     string   // Version of the schema to push. Defaults to the current timestamp.
	Description string   // Description of the schema changes.
}

SchemaPushParams are the parameters for the `schema push` command.

type SchemaTestParams

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

	URL   string
	Run   string
	Paths []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 Stream

type Stream[T any] interface {
	// Next reads the next item from the stream, making it available by calling Current.
	// It returns false if there are no more items and the stream is closed.
	Next() bool
	// Current returns the current item from the stream.
	Current() (T, error)
	// Err returns the error, if any, that occurred while reading the stream.
	Err() error
}

Stream is an interface for reading a stream of items.

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.

func (*SummaryReport) Errors

func (r *SummaryReport) Errors() []error

Errors returns the errors in the summary report, if exists.

type ToolCallMessage

type ToolCallMessage struct {
	CallID    string `json:"callID"`
	Function  string `json:"function"`
	Arguments string `json:"arguments"`
}

ToolCallMessage is the input to a tool call.

type ToolOutputMessage

type ToolOutputMessage struct {
	CallID  string `json:"callID"`
	Content string `json:"content"`
}

ToolOutputMessage is the output of a tool call.

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"
	TriggerTypeGitlab       TriggerType = "GITLAB"
	TriggerTypeBitbucket    TriggerType = "BITBUCKET"
	TriggerTypeAzureDevOps  TriggerType = "AZURE_DEVOPS"
)

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 WhoAmI

type WhoAmI struct {
	Org string `json:"Org,omitempty"`
}

WhoAmI contains the result of an 'atlas whoami' run.

type WhoAmIParams

type WhoAmIParams struct {
	ConfigURL string
	Env       string
	Vars      VarArgs
}

WhoAmIParams are the parameters for the `whoami` command

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 (ce *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