common

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2026 License: Apache-2.0 Imports: 32 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 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 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 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 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 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 WaitForDatabase

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

func WaitForDatabaseWithProgress

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

WaitForDatabaseWithProgress waits for a database to be ready, showing an animated spinner if the writer is a terminal, 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 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 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 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 Status

type Status 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"`
}

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

func FetchStatus

func FetchStatus(ctx context.Context, client api.ClientWithResponsesInterface, projectID string) (Status, error)

FetchStatus fetches space usage and database counts from the API.

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

func (*VersionCheckResult) String

func (r *VersionCheckResult) String() string

String returns a message describing the available update, or an empty string if no update is available.

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