Documentation
¶
Index ¶
- Constants
- Variables
- func BuildConnectionString(args ConnectionStringArgs) (string, error)
- func CheckReady(database api.Database) error
- func ExitWithCode(code int, err error) error
- func ExitWithErrorFromStatusCode(statusCode int, err error) error
- func FetchLogs(ctx context.Context, args FetchLogsArgs) ([]string, error)
- func FormatSchema(schema *DatabaseSchema) string
- func FormatStorageSize(storageMib *int) string
- func GetPassword(database api.Database, role string) (string, error)
- func OpenBrowserAsync(url string) <-chan error
- func ParseExpires(value string, now time.Time) (*time.Time, error)
- func RemovePgpassEntry(database api.Database, role string) error
- func SavePassword(database api.Database, password, role string) error
- func ShareURL(baseURL, token, name string) (string, error)
- func WaitForDatabase(ctx context.Context, args WaitForDatabaseArgs) error
- func WaitForDatabaseWithProgress(ctx context.Context, out io.Writer, args WaitForDatabaseArgs) error
- type App
- func (a *App) GetAll() (*config.Config, api.ClientWithResponsesInterface, string, error)
- func (a *App) GetClient() (api.ClientWithResponsesInterface, string, error)
- func (a *App) GetConfig() *config.Config
- func (a *App) Load(ctx context.Context) (*config.Config, api.ClientWithResponsesInterface, string, error)
- func (a *App) SetClient(client api.ClientWithResponsesInterface, projectID string)
- func (a *App) SetClientFactory(f ClientFactory)
- func (a *App) SetFlags(flags *pflag.FlagSet)
- func (a *App) TryGetAll() (*config.Config, api.ClientWithResponsesInterface, string)
- type CheckConstraint
- type ClientFactory
- type Column
- type ConnectionStringArgs
- type ConstraintType
- type DatabaseCounts
- type DatabaseSchema
- type EnumSchema
- type ExclusionConstraint
- type ExecuteQueryArgs
- type ExitCodeError
- type FetchDatabaseSchemaArgs
- type FetchLogsArgs
- type IndexSchema
- type InstallMethod
- type LoginResult
- type QueryResult
- type ResultSet
- type Status
- type TableColumnSchema
- type TableConstraint
- type TableSchema
- type VersionCheckResult
- type ViewColumnSchema
- type ViewSchema
- type WaitForDatabaseArgs
Constants ¶
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 ¶
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") )
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.
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 ¶
CheckReady returns ErrPaused if the database is paused or pausing, or ErrNotReady if the database is queued, configuring, or resuming.
func ExitWithCode ¶
ExitWithCode returns an error that will cause the program to exit with the specified code
func ExitWithErrorFromStatusCode ¶
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 ¶
FormatStorageSize formats storage size in MiB or GiB as appropriate
func GetPassword ¶
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 ¶
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
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 ¶
RemovePgpassEntry removes the .pgpass entry for the given database and role.
func SavePassword ¶
SavePassword saves the database password to the user's ~/.pgpass file. Returns an error if saving fails.
func ShareURL ¶ added in v0.12.0
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 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) Load ¶
func (a *App) Load(ctx context.Context) (*config.Config, api.ClientWithResponsesInterface, string, error)
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 ¶
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 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 ¶
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 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 ¶
LoginResult holds user information returned by a successful login.
func Login ¶
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.
type ViewColumnSchema ¶
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
}