common

package
v0.27.1 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: Apache-2.0 Imports: 36 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 ExecuteQuery = func(ctx context.Context, args ExecuteQueryArgs) (*QueryResult, error) {

	database, err := fetchDatabase(ctx, args.Client, args.SpaceID, args.DatabaseRef)
	if err != nil {
		return nil, err
	}

	if err := CheckReady(database); err != nil {
		return nil, err
	}

	password, err := GetPassword(database, args.Role)
	if err != nil {
		return nil, fmt.Errorf("failed to retrieve password: %w", err)
	}

	connStr, err := BuildConnectionString(ConnectionStringArgs{
		Database: database,
		Role:     args.Role,
		Password: password,
		ReadOnly: args.ReadOnly,
	})
	if err != nil {
		return nil, fmt.Errorf("failed to build connection string: %w", err)
	}

	return executeQueryWithConnection(ctx, connStr, args)
}

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.

Declared as a var so tests can replace it with a stub that doesn't require a real database connection.

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.

View Source
var WaitForDatabaseWithProgress = func(ctx context.Context, in io.Reader, out io.Writer, args WaitForDatabaseArgs) error {
	if !util.IsTerminal(in) || !util.IsTerminal(out) {
		return WaitForDatabase(ctx, args)
	}

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	model := waitModel{
		spinner: spinner.New(spinner.WithSpinner(spinner.Ellipsis)),
		ctx:     ctx,
		cancel:  cancel,
		args:    args,
	}

	p := tea.NewProgram(
		model,
		tea.WithInput(in),
		tea.WithOutput(out),
		tea.WithoutSignalHandler(),
	)

	result, err := p.Run()
	if err != nil {
		return fmt.Errorf("error rendering to terminal: %w", err)
	}

	return result.(waitModel).err
}

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

Declared as a var so tests can replace it with a stub that doesn't require polling a real database.

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 ComputeLimitExceededError added in v0.22.1

func ComputeLimitExceededError(action string) error

ComputeLimitExceededError returns a user-friendly error explaining that the space has reached its compute limit, with guidance on enabling overages. The action should complete the sentence "you can't ..." (e.g. "create a database"). It carries the invalid-parameters exit code, matching the 400 the API returns for this condition.

func DefaultAPIKeyName added in v0.27.0

func DefaultAPIKeyName(ctx context.Context, client api.ClientWithResponsesInterface) (string, error)

DefaultAPIKeyName fetches the current user's name from the API and returns a default API key name like "<user>'s API Key".

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 cursor-based pagination up to the specified tail limit. Returns logs in ascending chronological order (oldest first), formatted as `YYYY-MM-DD HH:MM:SS UTC <message>`.

func FormatSchema

func FormatSchema(schema *DatabaseSchema) string

FormatSchema formats a DatabaseSchema into a human-readable string, grouping objects under a SCHEMA: <name> header for each namespace. When includeDefinitions is false, the verbose object source bodies (view defining SELECTs and function/procedure bodies) are omitted, leaving just the structural summary (columns, constraints, indexes, signatures, etc.). When includeComments is true, object comments (COMMENT ON text) render as "-- " annotation lines under each object header and inline after columns.

func FormatStorageSize

func FormatStorageSize(storageMib *int64) 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 IsComputeLimitExceeded added in v0.22.1

func IsComputeLimitExceeded(apiErr *api.Error) bool

IsComputeLimitExceeded reports whether an API error indicates the operation was rejected because the space has used up its included compute allowance.

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 IsNoPaymentMethod added in v0.22.0

func IsNoPaymentMethod(apiErr *api.Error) bool

IsNoPaymentMethod reports whether an API error indicates that a payment method is required for the operation but none is on file.

func NewTable added in v0.19.0

func NewTable(w io.Writer, opts ...tablewriter.Option) *tablewriter.Table

NewTable returns a tablewriter.Table configured with Ghost's standard borderless, left-aligned style used for list and key/value command output.

Header auto-formatting is disabled, so headers render exactly as the literal strings passed to Header() with no camel-case splitting or title-casing. Additional options may be supplied to extend or override the defaults.

func NoPaymentMethodError added in v0.22.0

func NoPaymentMethodError(action string) error

NoPaymentMethodError returns a user-friendly error explaining that a payment method is required for the given action, with guidance on how to add one. The action should complete the sentence "a payment method is required to ..." (e.g. "create a dedicated database"). It carries the invalid-parameters exit code, matching the 400 the API returns for this condition.

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

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 space ID. Returns an error (and nil/zero values) if the client is not available (e.g. user is not logged in). Panics if the App has never been loaded (see getAll).

func (*App) GetClient

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

GetClient returns a snapshot of the API client and space ID. Returns an error if the client is not available (e.g. user is not logged in). Panics if the App has never been loaded (see getAll).

func (*App) GetConfig

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

GetConfig returns a snapshot of the config. Panics if the App has never been loaded (see getAll).

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 space 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, spaceID string)

SetClient stores an existing API client and space 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.

func (*App) TryGetAll

TryGetAll returns a snapshot of the config, API client, and space ID, like GetAll, but does not return an error if the client is unavailable (e.g. user is not logged in) — the returned client is simply nil. Use it for best-effort access where the API call is optional (e.g. analytics tracking). Panics if the App has never been loaded (see getAll).

type CheckConstraint

type CheckConstraint struct {
	Name       string   `json:"name"`
	Columns    []string `json:"columns,omitempty"` // columns involved in the check (from conkey)
	Expression string   `json:"expression"`        // 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 at the start of the wrapped RunE (see wrapCommands in internal/cmd) 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 Load 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 ContinuousAggregateInfo added in v0.20.0

type ContinuousAggregateInfo struct {
	CompressionEnabled bool `json:"compression_enabled"`
	// MaterializedOnly reports whether queries against the view return only
	// already-materialized data (true) or also combine the not-yet-
	// materialized recent data in real time (false).
	MaterializedOnly bool `json:"materialized_only"`
}

ContinuousAggregateInfo describes TimescaleDB continuous aggregate metadata for a view (see ViewSchema.ContinuousAggregate).

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             `json:"id"`
	Name    string             `json:"name"`
	Schemas []NamespacedSchema `json:"schemas"`
}

DatabaseSchema holds complete schema information for a database, grouped by namespace (Postgres schema).

func FetchDatabaseSchema

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

FetchDatabaseSchema fetches the complete schema information for a database. By default only user-visible schemas and objects are returned; pass IncludeInternal=true to include catalog, TimescaleDB internals, and extension-owned objects. Pass Schema to limit results to a single namespace. View/routine definitions are omitted unless IncludeDefinitions=true, and object comments are omitted unless IncludeComments=true.

type EnumSchema

type EnumSchema struct {
	Name string `json:"name"`
	// Comment is the type's COMMENT ON TYPE text. Only populated when
	// comments are requested.
	Comment string   `json:"comment,omitempty"`
	Values  []string `json:"values,omitempty"`
}

EnumSchema describes an enum type.

type ExclusionConstraint

type ExclusionConstraint struct {
	Name       string `json:"name"`
	Definition string `json:"definition"` // 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
	SpaceID     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
	SpaceID     string
	DatabaseRef string
	// Schema, if non-empty, limits the fetch to a single namespace.
	Schema string
	// IncludeInternal, when true, disables all schema/object exclusion
	// filters. Catalog (pg_*) and extension-owned objects will be included.
	IncludeInternal bool
	// IncludeDefinitions, when true, fetches full object definitions (view
	// SELECT statements and function/procedure bodies). These are omitted by
	// default because they can be large and may embed implementation details
	// or secrets; only fetch them when the caller will actually use them.
	IncludeDefinitions bool
	// IncludeComments, when true, fetches object comments (COMMENT ON text
	// from pg_description) for schemas, tables, views, materialized views,
	// columns, enums, functions, and procedures. Omitted by default to keep
	// the output concise.
	IncludeComments bool
}

FetchDatabaseSchemaArgs are the arguments to FetchDatabaseSchema.

type FetchLogsArgs

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

type ForeignTableInfo added in v0.20.0

type ForeignTableInfo struct {
	Server  string   `json:"server"`            // pg_foreign_server.srvname
	Wrapper string   `json:"wrapper"`           // pg_foreign_data_wrapper.fdwname
	Options []string `json:"options,omitempty"` // ftoptions as "key=value" strings
}

ForeignTableInfo describes the FDW binding of a foreign table. Only table-level options (pg_foreign_table.ftoptions, e.g. schema_name / table_name for postgres_fdw) are exposed; server-level options and user mappings, which can carry credentials, are never fetched.

type HypertableInfo added in v0.20.0

type HypertableInfo struct {
	CompressionEnabled bool `json:"compression_enabled"`
	NumChunks          int  `json:"num_chunks"`
}

HypertableInfo describes TimescaleDB hypertable metadata for a table.

type IndexSchema

type IndexSchema struct {
	Name        string `json:"name"`
	Columns     string `json:"columns"` // column expressions, e.g. "status" or "created_at DESC"
	Definition  string `json:"definition,omitempty"`
	IsUnique    bool   `json:"is_unique,omitempty"`
	WhereClause string `json:"where_clause,omitempty"` // 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 NamespacedSchema added in v0.20.0

type NamespacedSchema struct {
	Name string `json:"name"`
	// Comment is the schema's COMMENT ON SCHEMA text. Only populated when
	// comments are requested. A schema with a comment but no visible objects
	// is not surfaced just for its comment.
	Comment           string        `json:"comment,omitempty"`
	Tables            []TableSchema `json:"tables,omitempty"`
	Views             []ViewSchema  `json:"views,omitempty"`
	MaterializedViews []ViewSchema  `json:"materialized_views,omitempty"`
	Enums             []EnumSchema  `json:"enums,omitempty"`
	Functions         []Routine     `json:"functions,omitempty"`
	Procedures        []Routine     `json:"procedures,omitempty"`
}

NamespacedSchema groups the objects belonging to a single Postgres schema.

type PartitionInfo added in v0.20.0

type PartitionInfo struct {
	Name string `json:"name"`
	// Schema is the partition child's schema. It is only populated when the
	// partition lives in a different schema than its parent table (PostgreSQL
	// allows this), so that callers can schema-qualify the partition
	// correctly. When empty, the partition shares its parent's schema.
	Schema string `json:"schema,omitempty"`
	// Bound is the partition's bound expression (from pg_get_expr on
	// relpartbound), e.g. "FOR VALUES FROM ('2024-01-01') TO ('2025-01-01')".
	Bound string `json:"bound,omitempty"`
}

PartitionInfo describes a single child partition of a partitioned table.

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.

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 Routine added in v0.20.0

type Routine struct {
	Name string `json:"name"`
	// Arguments is the identity argument list (e.g. "integer, text"),
	// which distinguishes overloaded routines that share a name. Empty for
	// a routine that takes no arguments.
	Arguments string      `json:"arguments,omitempty"`
	Type      RoutineType `json:"type"`
	// Comment is the routine's COMMENT ON FUNCTION/PROCEDURE text. Only
	// populated when comments are requested.
	Comment    string `json:"comment,omitempty"`
	Definition string `json:"definition,omitempty"`
}

Routine describes a function or procedure.

type RoutineType added in v0.20.0

type RoutineType string

RoutineType is the type of a routine.

const (
	RoutineFunction  RoutineType = "FUNCTION"
	RoutineProcedure RoutineType = "PROCEDURE"
)

type SchemaNotFoundError added in v0.20.0

type SchemaNotFoundError struct {
	// Schema is the requested namespace that was not found.
	Schema string
	// Available lists the schemas the connecting user can access (i.e. holds
	// USAGE on), minus the internal namespaces a default browse hides unless
	// --internal is set. It is a best-effort suggestion list, not a guarantee
	// that each schema would produce non-empty results (a schema whose
	// contents are entirely extension-owned still renders empty on a default
	// browse). It is nil when enumeration failed (in which case ListErr is
	// set).
	Available []string
	// ListErr is non-nil when listing the available schemas failed.
	ListErr error
}

SchemaNotFoundError indicates the requested namespace does not exist. It carries a friendly message listing the available schemas when they could be enumerated. Callers can detect it with errors.As to distinguish a mistyped schema (a client input error) from an upstream/connection failure.

func (*SchemaNotFoundError) Error added in v0.20.0

func (e *SchemaNotFoundError) Error() string

Error implements the error interface.

func (*SchemaNotFoundError) Unwrap added in v0.20.0

func (e *SchemaNotFoundError) Unwrap() error

Unwrap exposes the underlying listing error (if any) for errors.Is/As.

type TableColumnSchema

type TableColumnSchema struct {
	Name string `json:"name"`
	Type string `json:"type"`
	// Comment is the column's COMMENT ON COLUMN text. Only populated when
	// comments are requested.
	Comment      string `json:"comment,omitempty"`
	NotNull      bool   `json:"not_null,omitempty"`
	Default      string `json:"default,omitempty"`       // empty if no default
	IsSerial     bool   `json:"is_serial,omitempty"`     // true if SERIAL/BIGSERIAL/SMALLSERIAL (has sequence, not identity)
	IdentityType string `json:"identity_type,omitempty"` // 'a' = ALWAYS, 'd' = BY DEFAULT, ” = not identity
}

TableColumnSchema holds schema information for a table column.

type TableConstraint

type TableConstraint struct {
	Type       ConstraintType `json:"type"`
	Name       string         `json:"name"`
	Columns    []string       `json:"columns,omitempty"`
	RefTable   string         `json:"ref_table,omitempty"`   // for FK
	RefColumns []string       `json:"ref_columns,omitempty"` // for FK
}

TableConstraint describes a constraint (single or multi-column).

type TableSchema

type TableSchema struct {
	Name string `json:"name"`
	// Comment is the table's COMMENT ON TABLE text. Only populated when
	// comments are requested.
	Comment     string                `json:"comment,omitempty"`
	Columns     []TableColumnSchema   `json:"columns,omitempty"`
	Constraints []TableConstraint     `json:"constraints,omitempty"` // PK, UK, FK constraints (single and multi-column)
	Indexes     []IndexSchema         `json:"indexes,omitempty"`
	Checks      []CheckConstraint     `json:"checks,omitempty"`
	Exclusions  []ExclusionConstraint `json:"exclusions,omitempty"`
	Triggers    []TriggerSchema       `json:"triggers,omitempty"`
	// Partitions lists the direct child partitions of a partitioned table.
	// Only populated for partitioned tables (relkind 'p'). Leaf partitions
	// are normally hidden as standalone tables, but in a multi-level hierarchy
	// an intermediate partitioned table is shown both as an entry here (under
	// its parent) and as its own table carrying its sub-partitions. When a
	// single schema is requested, a leaf whose parent lives in a different
	// schema is shown as a standalone table instead (see leafPartitionExclusion).
	Partitions []PartitionInfo `json:"partitions,omitempty"`
	Hypertable *HypertableInfo `json:"hypertable,omitempty"`
	// Foreign is the FDW binding of a foreign table (relkind 'f'). Nil for
	// regular tables. Foreign tables are modeled as tables because they
	// behave like them (columns, CHECK constraints, triggers, partition
	// membership); this field is what distinguishes them.
	Foreign *ForeignTableInfo `json:"foreign,omitempty"`
}

TableSchema holds schema information for a table.

type TriggerSchema added in v0.20.0

type TriggerSchema struct {
	Name         string `json:"name"`
	Timing       string `json:"timing"`
	Manipulation string `json:"manipulation"`
	Statement    string `json:"statement"`
}

TriggerSchema describes a single trigger on a table.

type Usage added in v0.15.1

type Usage struct {
	ComputeMinutes      int64          `json:"compute_minutes"`
	FreeComputeMinutes  int64          `json:"free_compute_minutes"`
	ComputeLimitMinutes *int64         `json:"compute_limit_minutes"`
	OveragesEnabled     bool           `json:"overages_enabled"`
	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"`
	SpaceName           string         `json:"space_name,omitempty"`
}

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, spaceID 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 `json:"name"`
	Type string `json:"type"`
	// Comment is the column's COMMENT ON COLUMN text. Only populated when
	// comments are requested.
	Comment string `json:"comment,omitempty"`
}

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

type ViewSchema

type ViewSchema struct {
	Name string `json:"name"`
	// Comment is the view's COMMENT ON (MATERIALIZED) VIEW text. Only
	// populated when comments are requested.
	Comment string             `json:"comment,omitempty"`
	Columns []ViewColumnSchema `json:"columns,omitempty"`
	// Definition is the view's defining SELECT (from pg_get_viewdef).
	Definition string `json:"definition,omitempty"`
	// Indexes are only populated for materialized views.
	Indexes []IndexSchema `json:"indexes,omitempty"`
	// Triggers lists triggers defined on the view (e.g. INSTEAD OF
	// triggers on a regular view). Not applicable to materialized views.
	Triggers []TriggerSchema `json:"triggers,omitempty"`
	// ContinuousAggregate is TimescaleDB continuous aggregate metadata. Nil
	// for ordinary views. A continuous aggregate is a regular view (relkind
	// 'v') over an internal materialization hypertable, so it appears under
	// Views; this field is what distinguishes it. When set and definitions
	// were requested, Definition holds the user's original defining query
	// rather than the rewritten SELECT over the internal materialization
	// hypertable that pg_get_viewdef returns.
	ContinuousAggregate *ContinuousAggregateInfo `json:"continuous_aggregate,omitempty"`
}

ViewSchema holds schema information for a view or materialized view.

type WaitForDatabaseArgs

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

Jump to

Keyboard shortcuts

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