common

package
v0.22.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

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
	ExitServiceNotFound     = 6 // Service not found
	ExitUpdateAvailable     = 7 // Update available
)

Exit codes as defined in the CLI specification

View Source
const (
	AddonNone       = "none" // Special value for no add-ons
	AddonTimeSeries = "time-series"
	AddonAI         = "ai"
)

Addon constants - these match the ServiceCreateAddons from the API

Variables

View Source
var (
	// ErrPaused is returned for a paused (or pausing) service.
	ErrPaused = errors.New("service is paused")

	// ErrNotReady is returned for a service that isn't accepting connections
	// (provisioning, resuming, upgrading, deleting, etc.).
	ErrNotReady = errors.New("service is not ready")
)
View Source
var ErrReadOnly = errors.New("this operation is not allowed in read-only mode")

ErrReadOnly is returned when a destructive operation is attempted while read-only mode is enabled in the user's config.

View Source
var (
	// GetStoredCredentials loads the stored credentials (PAT or OAuth) from the
	// keyring or fallback file. It's a package var so tests can override it to
	// inject credentials of either shape.
	GetStoredCredentials = func(cfg *config.Config) (*config.Credentials, error) {
		return cfg.GetStoredCredentials()
	}
)

Functions

func CheckReadOnly

func CheckReadOnly(cfg *config.Config) error

CheckReadOnly returns ErrReadOnly if read-only mode is enabled. Callers should invoke this before any destructive API call.

func CheckServiceReady

func CheckServiceReady(service api.Service) error

CheckServiceReady returns nil only when the service is READY, ErrPaused for PAUSED/PAUSING, and ErrNotReady for every other (or unknown) status.

func ConnectTarget

func ConnectTarget(ctx context.Context, cfg *config.Config, target *ConnectionTarget, opts ConnectionDetailsOptions, mode pgx.QueryExecMode) (*pgx.Conn, error)

ConnectTarget opens a pgx connection to the target (see ConnectionTarget.Details for the pooler policy). The caller owns the returned connection and must Close it.

func EnvAPIKey

func EnvAPIKey() (publicKey, secretKey string, ok bool)

EnvAPIKey returns the API key credentials from the environment and whether any were set. Env credentials take precedence over the stored login; use this instead of reading the env vars directly.

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 FetchServiceLogs

func FetchServiceLogs(ctx context.Context, args FetchServiceLogsArgs) ([]api.ServiceLogEntry, error)

FetchServiceLogs fetches service logs with cursor-based pagination up to the specified tail limit. Returns entries in ascending order by timestamp (oldest first, newest last).

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 GenerateServiceName

func GenerateServiceName() string

Matches front-end logic for generating a random service name

func GetPassword

func GetPassword(cfg *config.Config, service api.Service, role string) (string, error)

GetPassword fetches the password for the specified service from the configured password storage mechanism. It returns an error if it fails to find the password.

func GetService

func GetService(ctx context.Context, client api.ClientWithResponsesInterface, projectID, id string) (*api.Service, error)

GetService fetches a single service by ID. The API resolves both primary service IDs and read replica set IDs here; a read replica comes back as a service whose endpoint is the replica's and whose ForkedFrom links to its parent.

func IdentifyOAuthUser

func IdentifyOAuthUser(ctx context.Context, cfg *config.Config, client api.ClientWithResponsesInterface, projectID string)

IdentifyOAuthUser sends an analytics Identify for an OAuth (PKCE) login, using the token-authenticated client built during login. It fetches the caller's identity via /auth/info. Best-effort.

func IsReadReplica

func IsReadReplica(service api.Service) bool

IsReadReplica reports whether the service is a standby read replica (which shares its parent primary's credentials).

func IsValidAddon

func IsValidAddon(addon string) bool

IsValidAddon checks if the given add-on is valid (case-sensitive as per API spec)

func NewAPIClient

func NewAPIClient(ctx context.Context, cfg *config.Config) (*api.ClientWithResponses, string, error)

NewAPIClient initializes a api.ClientWithResponses and returns it along with the current project ID. Credentials are pulled from the environment (if present), or loaded from storage (either the keyring or fallback file). When pulled from the environment, the credentials are first validated by hitting the /auth/info endpoint (which also allows us to fetch the project ID), and the user is identified for the sake of analytics by hitting the /analytics/identify endpoint. When credentials are pulled from storage, those operations should have already been performed via `tiger auth login`.

func ParseCPUMemory

func ParseCPUMemory(cpuMemoryStr string) (string, string, error)

ParseCPUMemory parses a CPU/memory combination string (e.g., "2 CPU/8GB") and returns millicores and GB. If "shared" is given, returns "shared" for both CPU and memory.

func ReplicaPoolerWarning

func ReplicaPoolerWarning(target *ConnectionTarget, pooled bool) string

ReplicaPoolerWarning returns the warning to show when pooling was requested for a read replica with no pooler (the connection falls back to direct), or "" otherwise — including for a non-replica target, so callers need no IsReplica guard.

func ValidAddons

func ValidAddons() []string

ValidAddons returns a slice of all valid add-on values

func ValidateAPIKey

func ValidateAPIKey(ctx context.Context, cfg *config.Config, client api.ClientWithResponsesInterface) (*api.AuthInfo, error)

ValidateAPIKey validates the API key by calling the /auth/info endpoint, and returns the caller's identity. It also identifies the user for the sake of analytics. Only PAT credentials reach this path, so the response always carries the apiKey branch.

func ValidateAddons

func ValidateAddons(addons []string) ([]string, error)

ValidateAddons validates a slice of add-ons and removes duplicate values

func WaitForService

func WaitForService(ctx context.Context, args WaitForServiceArgs) error

Types

type App

type App struct {
	// Experimental gates preview-stage commands and MCP tools. Read once from
	// TIGER_EXPERIMENTAL at startup; see CLAUDE.md's "Experimental Feature
	// Gating".
	Experimental bool
	// contains filtered or unexported fields
}

App holds shared application state: the config and the API client built from it. For CLI commands it is populated once at the start of the wrapped RunE (see wrapCommands in internal/cmd) and shared by every command handler. For MCP requests, Load is called once per request by the analytics middleware, so config changes and logins/logouts made while the session is open take effect on the next request; handlers then read the loaded state via GetAll and friends.

All state is unexported. Use Load or SetClient to populate it, and GetAll/TryGetAll/GetConfig/GetClient to read it. Concurrency is handled internally via a sync.RWMutex.

func (*App) GetAll

GetAll returns a snapshot of the config, API client, and project ID. Returns an error (and zero values) if the client is unavailable, e.g. because the user isn't logged in. Panics if the App has never been loaded (see getAll).

Callers that only read the config but do reach the API later still use GetAll (discarding the client) so that a missing credential fails fast, before any prompting or other work.

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 unavailable, e.g. because the user isn't 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 and attempts to create the API client. Returns the config, API client, and project ID. Config errors are returned; API client errors are stored and surfaced by GetClient/GetAll instead (the returned client is simply nil), so commands that don't need the client still run when the user isn't logged in.

func (*App) SetClient

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

SetClient stores an existing API client and project ID. Use it when a valid client already exists (e.g. after `tiger auth login` builds one to validate credentials) so later readers — analytics in particular — see the new credentials without re-reading them from storage.

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 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 project ID like GetAll, but tolerates an unavailable client: the returned client is simply nil. Use it for best-effort work where the API call is optional (e.g. analytics). Panics if the App has never been loaded (see getAll).

type CPUMemoryConfig

type CPUMemoryConfig struct {
	Shared    bool // Shared CPU/Memory
	CPUMillis int  // CPU in millicores
	MemoryGBs int  // Memory in GB
}

CPUMemoryConfig represents an allowed CPU/Memory configuration

func ValidateAndNormalizeCPUMemory

func ValidateAndNormalizeCPUMemory(cpuMillis, memoryGBs string) (*CPUMemoryConfig, error)

ValidateAndNormalizeCPUMemory validates CPU/Memory values and applies auto-configuration logic

func (*CPUMemoryConfig) CPUMillisString

func (c *CPUMemoryConfig) CPUMillisString() *string

func (*CPUMemoryConfig) Matches

func (c *CPUMemoryConfig) Matches(cpuMillis, memoryGBs string) bool

func (*CPUMemoryConfig) MemoryGBsString

func (c *CPUMemoryConfig) MemoryGBsString() *string

func (*CPUMemoryConfig) String

func (c *CPUMemoryConfig) String() string

type CPUMemoryConfigs

type CPUMemoryConfigs []CPUMemoryConfig

func GetAllowedCPUMemoryConfigs

func GetAllowedCPUMemoryConfigs() CPUMemoryConfigs

GetAllowedCPUMemoryConfigs returns the allowed CPU/Memory configurations from the spec

func GetAllowedResizeCPUMemoryConfigs

func GetAllowedResizeCPUMemoryConfigs() CPUMemoryConfigs

GetAllowedResizeCPUMemoryConfigs returns the allowed CPU/Memory configurations for resize operations (excludes shared)

func (CPUMemoryConfigs) String

func (c CPUMemoryConfigs) String() string

String returns a user-friendly string of allowed CPU/Memory combinations

func (CPUMemoryConfigs) Strings

func (c CPUMemoryConfigs) Strings() []string

Strings returns a slice of user-friendly strings of allowed CPU/Memory combinations

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)

ClientFactory creates an API client from the loaded config. Tests use it to inject a client while letting Load run normally, so config resolution and flag precedence still go through the real code path.

type ConnectionDetails

type ConnectionDetails struct {
	Role     string `json:"role,omitempty"`
	Password string `json:"password,omitempty"`
	Host     string `json:"host,omitempty"`
	Port     int    `json:"port,omitempty"`
	Database string `json:"database,omitempty"`
	IsPooler bool   `json:"is_pooler,omitempty"`
	// contains filtered or unexported fields
}

func GetConnectionDetails

func GetConnectionDetails(cfg *config.Config, service api.Service, opts ConnectionDetailsOptions) (*ConnectionDetails, error)

func GetConnectionDetailsFor

func GetConnectionDetailsFor(cfg *config.Config, connService, credService api.Service, opts ConnectionDetailsOptions) (*ConnectionDetails, error)

GetConnectionDetailsFor builds connection details using connService for the endpoint/pooler and credService for the password lookup. For a primary the two are the same; for a read replica connService is the replica (its own endpoint) and credService is the parent primary whose credentials it shares.

func (*ConnectionDetails) RequirePooler

func (d *ConnectionDetails) RequirePooler(requested bool) error

RequirePooler returns an error when pooling was requested but the resolved connection isn't using the pooler endpoint. Callers that treat a missing pooler as fatal use this; the read replica path instead warns and falls back to a direct connection.

func (*ConnectionDetails) String

func (d *ConnectionDetails) String() string

String creates a PostgreSQL connection string from service details

type ConnectionDetailsOptions

type ConnectionDetailsOptions struct {
	// Pooled determines whether to use the pooler endpoint (if available)
	Pooled bool

	// Role is the database role/username to use (e.g., "tsdbadmin")
	Role string

	// WithPassword determines whether to include the password in the output
	WithPassword bool

	// InitialPassword is an optional password to use directly (e.g., from service creation response)
	// If provided and WithPassword is true, this password will be used
	// instead of fetching from password storage. This is useful when password_storage=none.
	InitialPassword string

	// ReadOnly forces the connection into Tiger Cloud's immutable read-only
	// mode by injecting the tsdb_admin.read_only_connection GUC as a startup
	// parameter. The GUC cannot be disabled with SET for the duration of the
	// session, so this is safe to use even when the LLM controls the SQL.
	ReadOnly bool
}

ConnectionDetailsOptions configures how the connection string is built

type ConnectionTarget

type ConnectionTarget struct {
	ConnectionService api.Service
	CredentialService api.Service
	IsReplica         bool
}

ConnectionTarget is the service to connect to plus the service whose credentials to use. They're the same for a primary; for a read replica the CredentialService is the parent primary, whose credentials it shares.

func NewReplicaConnectionTarget

func NewReplicaConnectionTarget(primary api.Service, replica api.ReadReplicaSet) *ConnectionTarget

NewReplicaConnectionTarget builds a ConnectionTarget for connecting to one of a service's read replica sets (as listed via the /replicaSets endpoint). The replica supplies the endpoint; the primary supplies the credentials.

func ResolveConnectionTarget

func ResolveConnectionTarget(ctx context.Context, client api.ClientWithResponsesInterface, projectID string, service api.Service) (*ConnectionTarget, error)

ResolveConnectionTarget turns a fetched service into a ConnectionTarget. When the service is a standby read replica, it connects to the replica but resolves credentials against the parent primary, which is fetched here.

func ResolveConnectionTargetByID

func ResolveConnectionTargetByID(ctx context.Context, client api.ClientWithResponsesInterface, projectID, id string) (*ConnectionTarget, error)

ResolveConnectionTargetByID fetches a service (which may be a read replica) by ID and resolves its ConnectionTarget.

func (*ConnectionTarget) Details

Details builds the target's connection details. A requested-but-unavailable pooler is a hard error for a primary but silently falls back to direct for a replica.

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

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

func FetchSchemaFromConn(ctx context.Context, conn *pgx.Conn, ident SchemaIdent, opts SchemaOptions) (*DatabaseSchema, error)

FetchSchemaFromConn introspects the schema of the database reachable over conn, scoped by opts (see SchemaOptions). ident only supplies the ID/Name shown in the result; it does not affect what is queried. The caller owns conn and is responsible for any readiness check before connecting.

func FetchServiceSchema

func FetchServiceSchema(ctx context.Context, cfg *config.Config, target *ConnectionTarget, role string, pooled bool, opts SchemaOptions) (*DatabaseSchema, error)

FetchServiceSchema opens a read-only connection to the target (a primary service or one of its read replicas) and introspects its schema. It is the shared entry point for the `tiger db schema` CLI command and the db_schema MCP tool.

The connection is forced read-only: introspection only issues SELECTs, so this is always safe and guards against accidental writes.

type DeletionWaitHandler

type DeletionWaitHandler struct {
	ServiceID string
}

func (*DeletionWaitHandler) Check

func (*DeletionWaitHandler) InitialCheck

func (h *DeletionWaitHandler) InitialCheck() (bool, error)

func (*DeletionWaitHandler) Message

func (h *DeletionWaitHandler) Message() string

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

type FetchServiceLogsArgs struct {
	Client    api.ClientWithResponsesInterface
	ProjectID string
	ServiceID string
	Tail      int
	Since     *time.Time
	Until     *time.Time

	// Node selects a specific service node to fetch logs from, for services
	// with HA replicas. If nil, the backend returns logs for the primary.
	Node *int
}

type ForeignTableInfo

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

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 KeyringStorage

type KeyringStorage struct{}

KeyringStorage implements password storage using system keyring

func (*KeyringStorage) Get

func (k *KeyringStorage) Get(service api.Service, role string) (string, error)

func (*KeyringStorage) GetStorageResult

func (k *KeyringStorage) GetStorageResult(err error, password string) PasswordStorageResult

func (*KeyringStorage) Remove

func (k *KeyringStorage) Remove(service api.Service, role string) error

func (*KeyringStorage) Save

func (k *KeyringStorage) Save(service api.Service, password string, role string) error

type NamespacedSchema

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 NoStorage

type NoStorage struct{}

NoStorage implements no password storage (passwords are not saved)

func (*NoStorage) Get

func (n *NoStorage) Get(service api.Service, role string) (string, error)

func (*NoStorage) GetStorageResult

func (n *NoStorage) GetStorageResult(err error, password string) PasswordStorageResult

func (*NoStorage) Remove

func (n *NoStorage) Remove(service api.Service, role string) error

func (*NoStorage) Save

func (n *NoStorage) Save(service api.Service, password string, role string) error

type PartitionInfo

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 PasswordStorage

type PasswordStorage interface {
	Save(service api.Service, password string, role string) error
	Get(service api.Service, role string) (string, error)
	Remove(service api.Service, role string) error
	GetStorageResult(err error, password string) PasswordStorageResult
}

PasswordStorage defines the interface for password storage implementations

func GetPasswordStorage

func GetPasswordStorage(cfg *config.Config) PasswordStorage

GetPasswordStorage returns the appropriate PasswordStorage implementation based on configuration

type PasswordStorageResult

type PasswordStorageResult struct {
	Success bool   `json:"success"`
	Method  string `json:"method"`  // "keyring", "pgpass", or "none"
	Message string `json:"message"` // Human-readable message
}

PasswordStorageResult contains the result of password storage operations

func SavePasswordWithResult

func SavePasswordWithResult(cfg *config.Config, service api.Service, password string, role string) (PasswordStorageResult, error)

SavePasswordWithResult handles saving a password and returns both error and result info

type PgpassStorage

type PgpassStorage struct{}

PgpassStorage implements password storage using ~/.pgpass file

func (*PgpassStorage) Get

func (p *PgpassStorage) Get(service api.Service, role string) (string, error)

func (*PgpassStorage) GetStorageResult

func (p *PgpassStorage) GetStorageResult(err error, password string) PasswordStorageResult

func (*PgpassStorage) Remove

func (p *PgpassStorage) Remove(service api.Service, role string) error

func (*PgpassStorage) Save

func (p *PgpassStorage) Save(service api.Service, password string, role string) error

type Routine

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

type RoutineType string

RoutineType is the type of a routine.

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

type SchemaIdent

type SchemaIdent struct {
	ID   string
	Name string
}

SchemaIdent identifies the service whose schema was fetched. Its values populate DatabaseSchema.ID and DatabaseSchema.Name for display.

type SchemaNotFoundError

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

func (e *SchemaNotFoundError) Error() string

Error implements the error interface.

func (*SchemaNotFoundError) Unwrap

func (e *SchemaNotFoundError) Unwrap() error

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

type SchemaOptions

type SchemaOptions struct {
	// Schema, if non-empty, limits the fetch to a single namespace.
	Schema string
	// IncludeInternal disables the exclusion filters, adding catalog (pg_*)
	// and extension-owned objects.
	IncludeInternal bool
	// IncludeDefinitions fetches full object definitions (view SELECTs and
	// routine bodies), omitted by default since they can be large and may
	// embed secrets.
	IncludeDefinitions bool
	// IncludeComments fetches object comments (COMMENT ON text), omitted by
	// default to keep the output concise.
	IncludeComments bool
}

SchemaOptions controls what FetchSchemaFromConn collects.

type Spinner

type Spinner interface {
	// Update changes the spinner's displayed message.
	Update(message string)

	// Stop terminates the spinner program and waits for it to finish.
	Stop()
}

func NewSpinner

func NewSpinner(args SpinnerArgs) Spinner

NewSpinner creates and returns a new Spinner for displaying animated status messages. If the output is nil or io.Discard, it returns a no-op spinner. If both streams are terminals, it uses bubbletea to dynamically update the spinner and message in place. Otherwise it prints each message on a new line without animation.

type SpinnerArgs

type SpinnerArgs struct {
	// Input is read so the animated spinner can see Ctrl+C. BubbleTea asks the
	// terminal for keyboard disambiguation, and terminals that honor it deliver
	// Ctrl+C as an escape sequence on stdin instead of as a SIGINT — so without
	// stdin attached the keypress has nowhere to go and Ctrl+C does nothing.
	Input io.Reader

	Output io.Writer

	Message string

	// Cancel is called when the user presses Ctrl+C. It lets the caller's
	// polling loop unwind through its own context rather than being torn down
	// from underneath.
	//
	// Set it whenever the animated spinner might be chosen: BubbleTea leaves
	// Ctrl+C as a key press rather than a SIGINT, so a spinner without a Cancel
	// gives the user no way at all to interrupt the wait.
	Cancel context.CancelFunc
}

type StatusWaitHandler

type StatusWaitHandler struct {
	TargetStatus string
	Service      *api.Service
}

func (*StatusWaitHandler) Check

func (h *StatusWaitHandler) Check(resp *api.GetServiceResponse) (bool, error)

func (*StatusWaitHandler) InitialCheck

func (h *StatusWaitHandler) InitialCheck() (bool, error)

func (*StatusWaitHandler) Message

func (h *StatusWaitHandler) Message() string

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

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

type WaitForServiceArgs struct {
	Client    api.ClientWithResponsesInterface
	ProjectID string
	ServiceID string
	Handler   WaitHandler

	// Input lets the spinner pick up a Ctrl+C and cancel the wait. See
	// [SpinnerArgs.Input] for why the spinner needs stdin at all.
	Input      io.Reader
	Output     io.Writer
	Timeout    time.Duration
	TimeoutMsg string
}

type WaitHandler

type WaitHandler interface {
	// Message returns the current status message that should be displayed next
	// to the spinner while waiting for a service to reach some state.
	Message() string

	// InitialCheck returns true if we don't need to begin the waiting/polling
	// process, and false if we should.  It also returns an error, which is
	// either immediately returned from WaitForService or temporarily shown
	// next to the spinner depending on the first return value.
	InitialCheck() (bool, error)

	// Check returns true if we're done waiting/polling, and false if we should
	// continue. It also returns an error, which is either immediately returned
	// from WaitForService or temporarily shown next to the spinner depending
	// on the first return value.
	Check(resp *api.GetServiceResponse) (bool, error)
}

Jump to

Keyboard shortcuts

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