common

package
v0.15.1 Latest Latest
Warning

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

Go to latest
Published: May 27, 2026 License: Apache-2.0 Imports: 34 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	ExitSuccess             = 0 // Success
	ExitGeneralError        = 1 // General error
	ExitTimeout             = 2 // Operation timeout (wait-timeout exceeded) or connection timeout
	ExitInvalidParameters   = 3 // Invalid parameters
	ExitAuthenticationError = 4 // Authentication error
	ExitPermissionDenied    = 5 // Permission denied
	ExitDatabaseNotFound    = 6 // Database not found
	ExitUpdateAvailable     = 7 // Update available
)

Exit codes as defined in the CLI specification

Variables

View Source
var (
	// ErrPaused is returned when an operation is attempted against a paused database.
	ErrPaused = errors.New("database is paused")

	// ErrNotReady is returned when an operation is attempted against a database
	// that is still being provisioned (queued or configuring).
	ErrNotReady = errors.New("database is not ready")
)
View Source
var ErrMultiSelectAborted = errors.New("multi-select aborted")

Canned errors to correspond with the MultiSelectReason values

View Source
var ErrMultiSelectCanceled = errors.New("multi-select canceled")
View Source
var ErrPasswordNotFound = errors.New("password not found")

ErrPasswordNotFound is returned when no password is available from the API and no matching entry exists in .pgpass.

View Source
var OpenBrowser = func(url string) error {
	var cmd *exec.Cmd

	switch runtime.GOOS {
	case "windows":

		cmd = exec.Command("cmd", "/c", "start", strings.ReplaceAll(url, "&", "^&"))
	case "darwin":
		cmd = exec.Command("open", url)
	default:
		cmd = exec.Command("xdg-open", url)
	}

	return cmd.Run()
}

OpenBrowser opens the given URL in the user's default browser. It blocks until the browser command completes (which is usually as soon as the browser page is successfully opened, but could technically be when the browser page is closed on certain older Linux configurations). Prefer this function over OpenBrowserAsync if you can tolerate it potentially blocking while the browser remains open, or if handling async errors returned on a channel (see OpenBrowserAsync) is just too complex. Declared as a var so tests can replace it with a no-op.

Functions

func AddToWindowsUserPath added in v0.14.0

func AddToWindowsUserPath(installDir string) error

AddToWindowsUserPath is a Windows-only writer for the persistent user Path in the registry. On other platforms it always errors — callers should branch on runtime.GOOS before calling.

func AppendCompletionsToShellRC added in v0.14.0

func AppendCompletionsToShellRC(rcPath, shell, binary string) error

AppendCompletionsToShellRC adds the completion snippet (plus a compinit block, when needed) to rcPath.

func AppendPathToShellRC added in v0.14.0

func AppendPathToShellRC(rcPath, installDir string) error

AppendPathToShellRC adds a shell snippet to rcPath that prepends installDir to $PATH. For fish, emits an equivalent `set -gx PATH` snippet.

func BuildConnectionString

func BuildConnectionString(args ConnectionStringArgs) (string, error)

BuildConnectionString builds a PostgreSQL connection string for a database.

func CheckReady

func CheckReady(database api.Database) error

CheckReady returns ErrPaused if the database is paused or pausing, or ErrNotReady if the database is queued, configuring, or resuming.

func CompletionSnippet added in v0.14.0

func CompletionSnippet(shell, binary string) string

CompletionSnippet returns the shellrc line(s) that source Ghost's completion output for the given shell.

func DetectShellRC added in v0.14.0

func DetectShellRC() string

DetectShellRC returns the path to the shell rc file that PATH and completion snippets should be appended to. Mirrors the heuristic in scripts/install.sh.

func DetectShellType added in v0.14.0

func DetectShellType() string

DetectShellType returns "bash", "zsh", "fish", or "" based on the SHELL environment variable.

func ExitWithCode

func ExitWithCode(code int, err error) error

ExitWithCode returns an error that will cause the program to exit with the specified code

func ExitWithErrorFromStatusCode

func ExitWithErrorFromStatusCode(statusCode int, err error) error

ExitWithErrorFromStatusCode maps HTTP status codes to CLI exit codes

func FetchLogs

func FetchLogs(ctx context.Context, args FetchLogsArgs) ([]string, error)

FetchLogs fetches database logs with pagination up to the specified tail limit. Returns logs in ascending chronological order (oldest first).

func FormatSchema

func FormatSchema(schema *DatabaseSchema) string

FormatSchema formats a DatabaseSchema into a human-readable string

func FormatStorageSize

func FormatStorageSize(storageMib *int) string

FormatStorageSize formats storage size in MiB or GiB as appropriate

func GetPassword

func GetPassword(database api.Database, role string) (string, error)

GetPassword retrieves the password for a database. It first checks the API-provided password on the Database object, then falls back to the user's ~/.pgpass file. Returns ErrPasswordNotFound if neither source has a password.

func IsInPath added in v0.14.0

func IsInPath(dir string) bool

IsInPath reports whether dir is an element of $PATH.

func IsInWindowsUserPath added in v0.14.0

func IsInWindowsUserPath(installDir string) (bool, error)

IsInWindowsUserPath is a Windows-only check against the persistent user Path in the registry. On other platforms it always errors — callers should branch on runtime.GOOS before calling.

func OpenBrowserAsync

func OpenBrowserAsync(url string) <-chan error

OpenBrowserAsync opens the given URL in the user's default browser in a goroutine and returns a channel that receives an error if the browser command fails. This is used by the login flow to avoid blocking if the browser command hangs on certain Linux configurations. Prefer this function whenever you need to open the browser, then wait for something else to happen on a channel (because in that case, it's easy to also wait for errors on the returned error chan via a select statement), or if opening the browser is "best effort" and you don't care to handle errors at all.

func ParseExpires added in v0.12.0

func ParseExpires(value string, now time.Time) (*time.Time, error)

ParseExpires parses an --expires / expires value into an absolute timestamp. Accepts either:

  • a positive Go duration (e.g. "30m", "24h") — interpreted relative to now
  • an RFC3339 timestamp (e.g. "2026-05-01T00:00:00Z")

Returns nil for an empty input (no expiry). Returns an error for malformed input or non-positive durations.

func RemovePgpassEntry

func RemovePgpassEntry(database api.Database, role string) error

RemovePgpassEntry removes the .pgpass entry for the given database and role.

func SavePassword

func SavePassword(database api.Database, password, role string) error

SavePassword saves the database password to the user's ~/.pgpass file. Returns an error if saving fails.

func ShareURL added in v0.12.0

func ShareURL(baseURL, token, name string) (string, error)

ShareURL returns the landing-page URL a recipient opens to consume a share. Uses url.JoinPath so callers don't have to care whether the configured base URL ends with a slash, and so the token is properly percent-encoded into the path. The source database name is appended as a `name=` query parameter so the landing page can show the recipient what they're about to fork; an empty name is omitted. Returns an error if the configured base URL is malformed.

func ShellRCMentions added in v0.14.0

func ShellRCMentions(rcPath, needle string) (bool, error)

ShellRCMentions reports whether the file at rcPath contains needle. A missing file is treated as "not mentioned" with no error so callers can distinguish "doesn't reference" from "couldn't read".

func ShellRCMentionsGhostCompletion added in v0.14.0

func ShellRCMentionsGhostCompletion(rcPath string) (bool, error)

ShellRCMentionsGhostCompletion reports whether the rc file appears to configure Ghost shell completions. It recognizes both the historical `ghost completion ...` form and the absolute-path form written by AppendCompletionsToShellRC. Comment lines are ignored so a commented-out snippet is not treated as configured.

func ShellRCNeedsCompinit added in v0.14.0

func ShellRCNeedsCompinit(shell, rcPath string) bool

ShellRCNeedsCompinit reports whether a zsh rc file is missing a compinit call. Returns false for non-zsh shells. Comment lines are ignored so a commented-out marker (e.g. `# compinit`) doesn't suppress the snippet.

func WaitForDatabase

func WaitForDatabase(ctx context.Context, args WaitForDatabaseArgs) error

func WaitForDatabaseWithProgress

func WaitForDatabaseWithProgress(ctx context.Context, in io.Reader, out io.Writer, args WaitForDatabaseArgs) error

WaitForDatabaseWithProgress waits for a database to be ready, showing an animated spinner if both streams are terminals, or plain text otherwise.

Types

type App

type App struct {
	Experimental bool
	// contains filtered or unexported fields
}

func (*App) GetAll

GetAll returns a snapshot of the config, API client, and project ID. The returned values remain valid even if Load is called concurrently — the pointers reference objects that are not mutated by Load (Load replaces pointers, it does not modify the objects they point to). Returns an error if the client is not available (e.g. user is not logged in).

func (*App) GetClient

func (a *App) GetClient() (api.ClientWithResponsesInterface, string, error)

GetClient returns a snapshot of the API client and project ID. Returns an error if the client is not available (e.g. user is not logged in).

func (*App) GetConfig

func (a *App) GetConfig() *config.Config

GetConfig returns a snapshot of the config.

func (*App) Load

Load loads (or reloads) the config from disk and attempts to create the API client. Returns the loaded config, API client, and project ID. Config loading errors are returned; API client errors are stored internally and surfaced via GetClient (the returned client will simply be nil if it couldn't be loaded).

func (*App) SetClient

func (a *App) SetClient(client api.ClientWithResponsesInterface, projectID string)

SetClient stores an existing API client and project ID on the App. Use this when a valid client already exists (e.g. after login creates one for validation) to avoid redundantly re-reading credentials from disk.

func (*App) SetClientFactory

func (a *App) SetClientFactory(f ClientFactory)

SetClientFactory sets a custom factory for API client creation. When set, Load() calls this instead of the default newAPIClient.

func (*App) SetFlags

func (a *App) SetFlags(flags *pflag.FlagSet)

SetFlags stores the command's flag set for use by config.Load. Must be called before Load (typically in PersistentPreRunE).

func (*App) TryGetAll

TryGetAll returns a snapshot of the config, API client, and project ID. The returned values remain valid even if Load is called concurrently — the pointers reference objects that are not mutated by Load (Load replaces pointers, it does not modify the objects they point to). Does not return an error if the client is not available (e.g. user is not logged in).

type CheckConstraint

type CheckConstraint struct {
	Name       string
	Columns    []string // columns involved in the check (from conkey)
	Expression string   // full constraint def from pg_get_constraintdef, e.g. "CHECK ((age > 0))"
}

CheckConstraint describes a check constraint

type ClientFactory

type ClientFactory func(ctx context.Context, cfg *config.Config) (api.ClientWithResponsesInterface, string, error)

App holds shared application state including the config and API client. For CLI commands, it is populated once in PersistentPreRunE and shared across all command handlers. For MCP tool handlers, Load is called on each tool invocation to refresh config and credentials (in case concurrent CLI commands have changed config options or logged the user in/out while the MCP session was ongoing).

All fields are unexported. Use Load or SetClient to populate state, and GetAll/GetConfig/GetClient to read it. Concurrency is handled internally via a sync.RWMutex. ClientFactory creates an API client from the loaded config. Used in tests to inject a mock client while still allowing PersistentPreRunE to run normally (loading config, etc.).

type Column

type Column struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

Column represents a column in the query result.

type ComputePriceOutput added in v0.13.0

type ComputePriceOutput struct {
	Size          string  `json:"size"`
	MilliCPU      int     `json:"milli_cpu"`
	MemoryGiB     int     `json:"memory_gib"`
	PricePerHour  float64 `json:"price_per_hour"`
	PricePerMonth float64 `json:"price_per_month"`
}

ComputePriceOutput holds the price and resource allocation for one dedicated compute size.

type ConnectionStringArgs

type ConnectionStringArgs struct {
	Database api.Database
	Role     string
	Password string // If empty, password will be omitted from the connection string.
	ReadOnly bool   // If true, includes the tsdb_admin.read_only_connection GUC as a startup parameter.
}

ConnectionStringArgs contains arguments for building a connection string.

type ConstraintType

type ConstraintType string

ConstraintType represents the type of a table constraint

const (
	ConstraintPrimaryKey ConstraintType = "PRIMARY KEY"
	ConstraintUnique     ConstraintType = "UNIQUE"
	ConstraintForeignKey ConstraintType = "FOREIGN KEY"
)

type DatabaseCounts

type DatabaseCounts struct {
	Queued      int `json:"queued,omitempty"`
	Configuring int `json:"configuring,omitempty"`
	Running     int `json:"running,omitempty"`
	Pausing     int `json:"pausing,omitempty"`
	Paused      int `json:"paused,omitempty"`
	Resuming    int `json:"resuming,omitempty"`
	Deleting    int `json:"deleting,omitempty"`
	Deleted     int `json:"deleted,omitempty"`
	Upgrading   int `json:"upgrading,omitempty"`
	Unstable    int `json:"unstable,omitempty"`
	Unknown     int `json:"unknown,omitempty"`
}

DatabaseCounts represents the number of databases in each status.

type DatabaseSchema

type DatabaseSchema struct {
	ID                string
	Name              string
	Tables            []TableSchema
	Views             []ViewSchema
	MaterializedViews []ViewSchema
	Enums             []EnumSchema
}

DatabaseSchema holds complete schema information for a database

func FetchDatabaseSchema

func FetchDatabaseSchema(ctx context.Context, args FetchDatabaseSchemaArgs) (*DatabaseSchema, error)

FetchDatabaseSchema fetches the complete schema information for a database.

type DedicatedPricingOutput added in v0.13.0

type DedicatedPricingOutput struct {
	Compute []ComputePriceOutput `json:"compute"`
	Storage StoragePriceOutput   `json:"storage"`
}

DedicatedPricingOutput holds pricing for dedicated databases.

type EnumSchema

type EnumSchema struct {
	Name   string
	Values []string
}

EnumSchema describes an enum type

type ExclusionConstraint

type ExclusionConstraint struct {
	Name       string
	Definition string // full constraint def from pg_get_constraintdef, e.g. "EXCLUDE USING gist (circle WITH &&)"
}

ExclusionConstraint describes an exclusion constraint

type ExecuteQueryArgs

type ExecuteQueryArgs struct {
	Client      api.ClientWithResponsesInterface
	ProjectID   string
	DatabaseRef string
	Query       string
	Role        string
	Parameters  []string
	ReadOnly    bool
}

ExecuteQueryArgs contains arguments for query execution.

type ExitCodeError

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

ExitCodeError creates an error that will cause the program to exit with the specified code

func (ExitCodeError) Error

func (e ExitCodeError) Error() string

func (ExitCodeError) ExitCode

func (e ExitCodeError) ExitCode() int

func (ExitCodeError) Unwrap

func (e ExitCodeError) Unwrap() error

type FetchDatabaseSchemaArgs

type FetchDatabaseSchemaArgs struct {
	Client      api.ClientWithResponsesInterface
	ProjectID   string
	DatabaseRef string
}

type FetchLogsArgs

type FetchLogsArgs struct {
	Client      api.ClientWithResponsesInterface
	ProjectID   string
	DatabaseRef string
	Tail        int
	Until       time.Time
}

type IndexSchema

type IndexSchema struct {
	Name        string
	Columns     string // column expressions, e.g. "status" or "created_at DESC"
	IsUnique    bool
	WhereClause string // for partial indexes, empty if not partial
}

IndexSchema describes an index

type InstallMethod

type InstallMethod string

InstallMethod represents how Ghost CLI was installed

const (
	InstallMethodHomebrew   InstallMethod = "homebrew"
	InstallMethodDeb        InstallMethod = "deb"
	InstallMethodRPM        InstallMethod = "rpm"
	InstallMethodInstallSh  InstallMethod = "install_sh"
	InstallMethodInstallPS1 InstallMethod = "install_ps1"
	InstallMethodUnknown    InstallMethod = "unknown"
)

type LoginResult

type LoginResult struct {
	Name    string
	Email   string
	SpaceID string
}

LoginResult holds user information returned by a successful login.

func Login

func Login(ctx context.Context, app *App, headless bool, out io.Writer) (*LoginResult, error)

Login performs the full OAuth login flow: authenticates the user via GitHub OAuth, validates the session, and stores credentials securely. If headless is true, uses the device authorization flow instead of opening a browser. Progress messages are written to out (pass nil to suppress output).

type MultiSelectItem added in v0.14.0

type MultiSelectItem struct {
	// Label is the primary text shown to the right of the checkbox.
	Label string
	// Status is dim explanatory text shown after the label (optional).
	Status string
	// Selected controls the initial checked state of the row.
	Selected bool
	// Dimmed renders the entire row (checkbox, label, status) in a dim
	// style. Used to mark rows the caller has detected as already
	// configured so the user understands why they weren't pre-selected.
	Dimmed bool
}

MultiSelectItem describes a single row of a multi-select prompt.

type MultiSelectReason added in v0.14.0

type MultiSelectReason int

MultiSelectReason describes how a multi-select prompt completed.

const (
	// MultiSelectConfirmed means the user pressed enter.
	MultiSelectConfirmed MultiSelectReason = iota
	// MultiSelectCanceled means the user pressed esc or q. Callers can
	// treat this as a soft cancel (e.g. return to a parent menu).
	MultiSelectCanceled
	// MultiSelectAborted means the user pressed ctrl+c. Callers should
	// bubble this up and stop the surrounding workflow.
	MultiSelectAborted
)

type MultiSelectResult added in v0.14.0

type MultiSelectResult struct {
	Reason  MultiSelectReason
	Indices []int // populated only when Reason == MultiSelectConfirmed
}

MultiSelectResult is the outcome of running a multi-select prompt.

func RunMultiSelect added in v0.14.0

func RunMultiSelect(ctx context.Context, in io.Reader, out io.Writer, title string, items []MultiSelectItem) (*MultiSelectResult, error)

RunMultiSelect renders an interactive multi-select prompt and returns the user's selection. ctrl+c is reported as MultiSelectAborted; esc/q as MultiSelectCanceled.

type PricingOutput added in v0.13.0

type PricingOutput struct {
	Dedicated DedicatedPricingOutput `json:"dedicated"`
}

PricingOutput is the shared output shape for pricing data, used by both the CLI command and the MCP tool. Includes the wire-format hourly figures and derived per-month figures.

func FetchPricing added in v0.13.0

FetchPricing fetches dedicated pricing from the API.

type QueryResult

type QueryResult struct {
	ResultSets    []ResultSet   `json:"result_sets"`
	ExecutionTime time.Duration `json:"execution_time"`
}

QueryResult represents the complete result of a query execution.

func ExecuteQuery

func ExecuteQuery(ctx context.Context, args ExecuteQueryArgs) (*QueryResult, error)

ExecuteQuery executes a SQL query against a database. It handles fetching the password, building the connection string, connecting to the database, and executing the query.

Multi-statement queries (semicolon-separated) are supported when no parameters are provided. When parameters are provided, only single statements are supported.

type ResultSet

type ResultSet struct {
	CommandTag   string     `json:"command_tag"`
	Columns      []Column   `json:"columns,omitempty"`
	Rows         [][]string `json:"rows,omitempty"`
	RowsAffected int64      `json:"rows_affected"`
}

ResultSet represents a single query result set.

type StoragePriceOutput added in v0.13.0

type StoragePriceOutput struct {
	PricePerGiBHour        float64 `json:"price_per_gib_hour"`
	PricePerGiBMonth       float64 `json:"price_per_gib_month"`
	IncludedGiBPerDatabase int     `json:"included_gib_per_database"`
}

StoragePriceOutput holds the dedicated storage rate and free quota.

type TableColumnSchema

type TableColumnSchema struct {
	Name         string
	Type         string
	NotNull      bool
	Default      string // empty if no default
	IsSerial     bool   // true if SERIAL/BIGSERIAL/SMALLSERIAL (has sequence, not identity)
	IdentityType string // 'a' = ALWAYS, 'd' = BY DEFAULT, ” = not identity
}

TableColumnSchema holds schema information for a table column

type TableConstraint

type TableConstraint struct {
	Type       ConstraintType
	Name       string
	Columns    []string
	RefTable   string   // for FK
	RefColumns []string // for FK
}

TableConstraint describes a constraint (single or multi-column)

type TableSchema

type TableSchema struct {
	Name        string
	Columns     []TableColumnSchema
	Constraints []TableConstraint // PK, UK, FK constraints (single and multi-column)
	Indexes     []IndexSchema
	Checks      []CheckConstraint
	Exclusions  []ExclusionConstraint
}

TableSchema holds schema information for a table

type Usage added in v0.15.1

type Usage struct {
	ComputeMinutes      int64          `json:"compute_minutes"`
	ComputeLimitMinutes int64          `json:"compute_limit_minutes"`
	StorageMib          int64          `json:"storage_mib"`
	StorageLimitMib     int64          `json:"storage_limit_mib"`
	Databases           DatabaseCounts `json:"databases"`
	CostToDate          *float64       `json:"cost_to_date,omitempty"`
	EstimatedTotalCost  *float64       `json:"estimated_total_cost,omitempty"`
	BillingPeriodStart  *time.Time     `json:"billing_period_start,omitempty"`
	BillingPeriodEnd    *time.Time     `json:"billing_period_end,omitempty"`
	SpaceID             string         `json:"space_id"`
}

Usage represents space usage including compute, storage, and database counts.

func FetchUsage added in v0.15.1

func FetchUsage(ctx context.Context, client api.ClientWithResponsesInterface, projectID string) (Usage, error)

FetchUsage fetches space usage and database counts from the API.

type VersionCheckResult

type VersionCheckResult struct {
	UpdateAvailable bool
	LatestVersion   string
	CurrentVersion  string
	InstallMethod   InstallMethod
	UpdateCommand   string
}

VersionCheckResult contains the result of a version check

func CheckVersion

func CheckVersion(ctx context.Context, releasesURL string) (*VersionCheckResult, error)

CheckVersion checks if a new version is available and returns the result.

type ViewColumnSchema

type ViewColumnSchema struct {
	Name string
	Type string
}

ViewColumnSchema holds column info for views (simpler than table columns)

type ViewSchema

type ViewSchema struct {
	Name    string
	Columns []ViewColumnSchema
	Indexes []IndexSchema // only for materialized views
}

ViewSchema holds schema information for a view or materialized view

type WaitForDatabaseArgs

type WaitForDatabaseArgs struct {
	Client      api.ClientWithResponsesInterface
	ProjectID   string
	DatabaseRef string
}

Jump to

Keyboard shortcuts

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