gcpsql

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 62 Imported by: ? 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.

README

Cloud SQL

Parity grade: B · SDK hashicorp/terraform-provider-google@v8.5.0 · last audited 2026-10-29 (c7d1c8106)

Coverage

Metric Value
PARITY entries audited 52 (38 ok, 14 partial)
Feature families 12 (9 ok, 3 partial)
Known gaps 5
Deferred items 0
Resource leaks clean
Known gaps
  • Not served: SQL Server (the only SQL Server engine in the repo is internal to services/rds and is wired to that service's own instance model; Cloud SQL would need its own engine with logins, BAK import/export and SQLSERVER_* versions, and the image is amd64-only), rescheduleMaintenance (no route; Google schedules maintenance events and the emulator never creates one, so there is nothing to reschedule), cross-project replicas (replicas.go prepareReplicaLocked: a replica must share its primary's project), the CAS-based server certificate and Entra ID certificate calls, major version upgrade, the backupdrBackup field of restoreBackup (Backup and DR vaults are not emulated), DNS connect settings, Auth Proxy and IAM database authentication.
  • Point-in-time recovery continues across a PostgreSQL failover (the archive volume belongs to the instance, not to the engine slot) but still restarts its window after a MySQL failover (the binary log lives on the data volume that pkgs/mysqlengine manages) and after a switchover, where the promoted replica is another instance with its own archive volume.
  • sslMode and requireSsl are not enforced because the engine speaks plain TCP (netfront.go forwards bytes without a TLS layer); dataDiskType, insightsConfig and maintenanceWindow are echoed only.
  • PostgreSQL ignores database charset and collation (stored only); MySQL users get GRANT ALL on .; PostgreSQL users join a cloudsqlsuperuser role the emulator creates. Backups keep object ownership, so restoring one into a different instance needs the same roles to exist.
  • flags.list is a static subset (about 60 flags) and tiers.list a fixed list; a flag outside the subset is rejected although the engine would accept it. crash_recovery: {status: ok, note: "Engine containers carry gopherstack.managed/owner/service/resource labels; after a crash a restart with the same data dir adopts the running container of a restored primary (same image, tier and dump directory, reachable with the persisted password) and removes the rest. Replicas, recoveries and fresh instances relaunch; the private replication network of a crashed run is not removed."}

More

Documentation

Index

Constants

View Source
const (
	// DefaultPort is the dedicated listener's default TCP port.
	DefaultPort = 8130
	// EngineAuto launches real database containers when a container runtime is reachable.
	EngineAuto = "auto"
	// EngineNone never starts containers: instances are state-only.
	EngineNone = "none"
	// DefaultStartupTimeout bounds how long a database container may take to accept connections.
	DefaultStartupTimeout = 5 * time.Minute
)

Variables

View Source
var ErrNilAppContext = errors.New("gcpsql: nil app context")

ErrNilAppContext is returned when Init is called with a nil AppContext.

View Source
var ErrRuntimeUnavailable = errors.New("gcpsql: container runtime unavailable")

ErrRuntimeUnavailable is returned by a Launcher when no container runtime is reachable; the instance then runs state-only.

View Source
var ErrSnapshotNull = errors.New("gcpsql: snapshot contains a null instance")

ErrSnapshotNull is returned when a snapshot holds a null instance.

Functions

func ParseBackupName

func ParseBackupName(name string) (string, string, bool)

ParseBackupName extracts the project and id of projects/{project}/backups/{id}.

Types

type APIError

type APIError struct {
	Reason  string
	Message string
	Status  int
}

APIError is a REST error with the HTTP status and reason it surfaces as.

func (*APIError) Error

func (e *APIError) Error() string

Error implements error.

type Backup

type Backup struct {
	Error                *OperationError `json:"error,omitempty"`
	BackupInterval       *Interval       `json:"backupInterval,omitempty"`
	InstanceSettings     *Instance       `json:"instanceSettings,omitempty"`
	Kind                 string          `json:"kind"`
	Name                 string          `json:"name"`
	SelfLink             string          `json:"selfLink"`
	Type                 string          `json:"type"`
	State                string          `json:"state"`
	BackupKind           string          `json:"backupKind"`
	Instance             string          `json:"instance"`
	Location             string          `json:"location"`
	DatabaseVersion      string          `json:"databaseVersion"`
	TimeZone             string          `json:"timeZone"`
	Description          string          `json:"description,omitempty"`
	ExpiryTime           string          `json:"expiryTime,omitempty"`
	InstanceDeletionTime string          `json:"instanceDeletionTime,omitempty"`
	MaxChargeableBytes   string          `json:"maxChargeableBytes,omitempty"`
}

Backup is the sql#backup resource.

type BackupInput

type BackupInput struct {
	Instance    string `json:"instance"`
	Description string `json:"description"`
	Location    string `json:"location"`
	ExpiryTime  string `json:"expiryTime"`
	TTLDays     string `json:"ttlDays"`
}

BackupInput is the writable part of sql#backup.

type BackupRun

type BackupRun struct {
	Error           *OperationError `json:"error,omitempty"`
	EndTime         string          `json:"endTime"`
	SelfLink        string          `json:"selfLink"`
	Type            string          `json:"type"`
	BackupKind      string          `json:"backupKind"`
	Description     string          `json:"description,omitempty"`
	EnqueuedTime    string          `json:"enqueuedTime"`
	Status          string          `json:"status"`
	WindowStartTime string          `json:"windowStartTime"`
	StartTime       string          `json:"startTime"`
	Instance        string          `json:"instance"`
	Kind            string          `json:"kind"`
	Location        string          `json:"location"`
	DatabaseVersion string          `json:"databaseVersion"`
	TimeZone        string          `json:"timeZone"`
	ID              string          `json:"id"`
}

BackupRun is the sql#backupRun resource.

type CertInsertResult

type CertInsertResult struct {
	Operation *Operation
	CA        *SslCert
	Cert      *SslCert
	Key       string
}

CertInsertResult is the sslCerts.insert response payload.

type CloneInput

type CloneInput struct {
	DestinationInstanceName string   `json:"destinationInstanceName"`
	DestinationProject      string   `json:"destinationProject"`
	PointInTime             string   `json:"pointInTime"`
	PitrTimestampMs         string   `json:"pitrTimestampMs"`
	DatabaseNames           []string `json:"databaseNames"`
}

CloneInput is the cloneContext of instances.clone.

type ConfigProvider

type ConfigProvider interface {
	GetGCPSQLSettings() Settings
}

ConfigProvider extracts Cloud SQL configuration from the AppContext Config.

type ConnectSettings

type ConnectSettings struct {
	Kind            string      `json:"kind"`
	ServerCaCert    *SslCert    `json:"serverCaCert,omitempty"`
	DatabaseVersion string      `json:"databaseVersion"`
	BackendType     string      `json:"backendType"`
	Region          string      `json:"region"`
	Endpoint        string      `json:"gopherstackEndpoint,omitempty"`
	IPAddresses     []IPMapping `json:"ipAddresses,omitempty"`
}

ConnectSettings is the connect.get response.

type Database

type Database struct {
	Kind      string `json:"kind"`
	Name      string `json:"name"`
	Instance  string `json:"instance"`
	Project   string `json:"project"`
	Charset   string `json:"charset,omitempty"`
	Collation string `json:"collation,omitempty"`
	Etag      string `json:"etag"`
	SelfLink  string `json:"selfLink"`
	System    bool   `json:"-"`
}

Database is the sql#database resource.

type DatabaseInput

type DatabaseInput struct {
	Name      string `json:"name"`
	Charset   string `json:"charset"`
	Collation string `json:"collation"`
}

DatabaseInput is the writable part of sql#database.

type DemoteRequest

type DemoteRequest struct {
	Source               string
	SkipReplicationSetup bool
}

DemoteRequest is the body of instances.demote and instances.demoteMaster.

type DiskUser

type DiskUser interface {
	DiskUsage(ctx context.Context) (int64, error)
	SetReadOnly(ctx context.Context, on bool) error
}

DiskUser is implemented by engines that can report their data size and stop accepting writes, which is how a full disk shows to clients.

type DumpOptions

type DumpOptions struct {
	Markers  bool
	Portable bool
}

DumpOptions tunes a dump. Markers prefixes each database with a switch line; Portable drops ownership and privileges so the file loads on an instance that lacks the original roles.

type Engine

type Engine interface {
	// Endpoint is the host and published port clients connect to.
	Endpoint() (string, int)
	CreateDatabase(ctx context.Context, name, charset, collation string) error
	DropDatabase(ctx context.Context, name string) error
	ListDatabases(ctx context.Context) ([]string, error)
	UpsertUser(ctx context.Context, u UserSpec) error
	DropUser(ctx context.Context, name, host string) error
	// Restart applies flags (persisted in the data directory) and restarts the database.
	Restart(ctx context.Context, flags []Flag) error
	Stop(ctx context.Context) error
	Start(ctx context.Context) error
	// Dump returns a logical SQL dump of dbs.
	Dump(ctx context.Context, dbs []string, opts DumpOptions) ([]byte, error)
	// Restore runs a SQL file; db is the default database when the file carries no switch lines.
	Restore(ctx context.Context, db string, data []byte) error
	Query(ctx context.Context, db, query string) ([][]string, error)
	InsertRows(ctx context.Context, db, table string, columns []string, rows [][]string) error
	Close(ctx context.Context)
}

Engine is one running database. Methods are safe for sequential use per instance.

type ExecColumn

type ExecColumn struct {
	Name string `json:"name"`
	Type string `json:"type,omitempty"`
}

ExecColumn names a result column and its database type.

type ExecMessage

type ExecMessage struct {
	Message  string `json:"message"`
	Severity string `json:"severity,omitempty"`
}

ExecMessage is a database notice or warning.

type ExecOutcome

type ExecOutcome struct {
	Failure  string
	Results  []ExecResult
	Messages []ExecMessage
}

ExecOutcome is what an engine reports for a batch; Failure is the database's own error text, in which case no result is returned.

type ExecRequest

type ExecRequest struct {
	Database string
	User     string
	Password string
	SQL      string
	RowLimit int64
	MaxBytes int
	Partial  bool
}

ExecRequest is one batch of statements an engine runs as a single database user.

type ExecResult

type ExecResult struct {
	Status        *ExecStatus  `json:"status,omitempty"`
	Message       string       `json:"message,omitempty"`
	Columns       []ExecColumn `json:"columns,omitempty"`
	Rows          []ExecRow    `json:"rows,omitempty"`
	PartialResult bool         `json:"partialResult,omitempty"`
}

ExecResult is the outcome of one statement.

type ExecRow

type ExecRow struct {
	Values []ExecValue `json:"values"`
}

ExecRow is one result row.

type ExecStatus

type ExecStatus struct {
	Message string `json:"message"`
	Code    int    `json:"code"`
}

ExecStatus is the google.rpc.Status of a failed execution.

type ExecValue

type ExecValue struct {
	Value     string `json:"value,omitempty"`
	NullValue bool   `json:"nullValue,omitempty"`
}

ExecValue is one cell; Null marks SQL NULL.

type ExecuteSQLInput

type ExecuteSQLInput struct {
	RowLimit              any    `json:"rowLimit"`
	Application           string `json:"application"`
	Database              string `json:"database"`
	PartialResultMode     string `json:"partialResultMode"`
	PasswordSecretVersion string `json:"passwordSecretVersion"`
	SQLStatement          string `json:"sqlStatement"`
	User                  string `json:"user"`
	AutoIamAuthn          bool   `json:"autoIamAuthn"`
}

ExecuteSQLInput is the request body of instances.executeSql.

type ExecuteSQLResponse

type ExecuteSQLResponse struct {
	Metadata *execMetadata `json:"metadata,omitempty"`
	Status   *ExecStatus   `json:"status,omitempty"`
	Results  []ExecResult  `json:"results,omitempty"`
	Messages []ExecMessage `json:"messages,omitempty"`
}

ExecuteSQLResponse is the response of instances.executeSql.

type ExportInput

type ExportInput struct {
	CSV       *struct{ SelectQuery string } `json:"csvExportOptions"`
	FileType  string                        `json:"fileType"`
	URI       string                        `json:"uri"`
	Databases []string                      `json:"databases"`
}

ExportInput is the exportContext of instances.export.

type Failoverable

type Failoverable interface {
	// Quiesce rejects further writes, drops client sessions and returns a position replicas can wait for.
	Quiesce(ctx context.Context) (string, error)
	// Unquiesce reverses Quiesce after a failed hand-over.
	Unquiesce(ctx context.Context) error
	// WaitCaughtUp blocks until a replica has applied everything up to pos.
	WaitCaughtUp(ctx context.Context, pos string) error
	// Seal stops a quiesced primary so that every replica holds all of its log; engines whose replicas
	// resume by transaction identity do nothing.
	Seal(ctx context.Context) error
	// Settle waits until a replica has applied all the log it received from a sealed primary.
	Settle(ctx context.Context) error
}

Failoverable is implemented by engines that can hand their role to a replica without losing committed writes.

type FinalBackupRequest

type FinalBackupRequest struct {
	Description string
	ExpiryTime  string
	TTLDays     int64
	Enabled     bool
}

FinalBackupRequest asks instances.delete for a final backup.

type Flag

type Flag struct {
	Name  string
	Value string
}

Flag is one database flag.

type FlagInfo

type FlagInfo struct {
	Name                string   `json:"name"`
	Type                string   `json:"type"`
	Kind                string   `json:"kind"`
	MinValue            string   `json:"minValue,omitempty"`
	MaxValue            string   `json:"maxValue,omitempty"`
	AppliesTo           []string `json:"appliesTo"`
	AllowedStringValues []string `json:"allowedStringValues,omitempty"`
	RequiresRestart     bool     `json:"requiresRestart"`
}

FlagInfo is one entry of flags.list.

func ListFlags

func ListFlags(databaseVersion string) []FlagInfo

ListFlags returns the flags that apply to databaseVersion (all when empty).

type FlagReloader

type FlagReloader interface {
	// ReloadFlags persists next in place of old and applies it without a restart.
	ReloadFlags(ctx context.Context, old, next []Flag) error
}

FlagReloader is implemented by engines that can apply flags needing no restart to a running server.

type Handler

type Handler struct {
	Backend *InMemoryBackend

	Port int
	// contains filtered or unexported fields
}

Handler serves the Cloud SQL Admin REST API.

func NewHandler

func NewHandler(backend *InMemoryBackend) *Handler

NewHandler creates a Handler; callers override Port from Settings.

func (*Handler) ExtractOperation

func (h *Handler) ExtractOperation(c *echo.Context) string

ExtractOperation returns the operation name for metrics.

func (*Handler) ExtractResource

func (h *Handler) ExtractResource(c *echo.Context) string

ExtractResource returns project[/instance] for metrics.

func (*Handler) GetSupportedOperations

func (h *Handler) GetSupportedOperations() []string

GetSupportedOperations lists the supported operations.

func (*Handler) Handler

func (h *Handler) Handler() echo.HandlerFunc

Handler returns the Echo handler for all Cloud SQL requests.

func (*Handler) MatchPriority

func (h *Handler) MatchPriority() int

MatchPriority is irrelevant because RouteMatcher never matches.

func (*Handler) Name

func (h *Handler) Name() string

Name returns the service name.

func (*Handler) Reset

func (h *Handler) Reset()

Reset removes every instance.

func (*Handler) Restore

func (h *Handler) Restore(ctx context.Context, data []byte) error

Restore implements persistence.Persistable by delegating to the backend.

func (*Handler) RouteMatcher

func (h *Handler) RouteMatcher() service.Matcher

RouteMatcher never matches: Cloud SQL runs on its own listener.

func (*Handler) Shutdown

func (h *Handler) Shutdown(ctx context.Context)

Shutdown stops the listener and every database container.

func (*Handler) Snapshot

func (h *Handler) Snapshot(ctx context.Context) []byte

Snapshot implements persistence.Persistable by delegating to the backend.

func (*Handler) StartWorker

func (h *Handler) StartWorker(ctx context.Context) error

StartWorker binds the dedicated listener synchronously so a port conflict is returned to the caller.

type IPMapping

type IPMapping struct {
	Type      string `json:"type"`
	IPAddress string `json:"ipAddress"`
}

IPMapping is one address of an instance.

type ImportInput

type ImportInput struct {
	CSV *struct {
		Table   string   `json:"table"`
		Columns []string `json:"columns"`
	} `json:"csvImportOptions"`
	FileType string `json:"fileType"`
	URI      string `json:"uri"`
	Database string `json:"database"`
}

ImportInput is the importContext of instances.import.

type InMemoryBackend

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

InMemoryBackend holds all Cloud SQL state under one lock.

func NewInMemoryBackend

func NewInMemoryBackend() *InMemoryBackend

NewInMemoryBackend creates an empty backend without a database launcher (state-only instances).

func (*InMemoryBackend) AddServerCa

func (b *InMemoryBackend) AddServerCa(project, instance string) (*Operation, error)

AddServerCa prepares a rotation; a CA that was added but never rotated in is replaced.

func (*InMemoryBackend) BackupCount

func (b *InMemoryBackend) BackupCount(project string) int

BackupCount is the number of project backups held for project, expired ones included until swept.

func (*InMemoryBackend) CancelOperation

func (b *InMemoryBackend) CancelOperation(project, name string) error

CancelOperation cancels an operation that has not started; running or finished operations are unchanged.

func (*InMemoryBackend) CloneInstance

func (b *InMemoryBackend) CloneInstance(project, instance string, in CloneInput) (*Operation, error)

CloneInstance creates a new instance with the settings, accounts and data of the source.

func (*InMemoryBackend) Close

func (b *InMemoryBackend) Close()

Close stops every engine and releases the runtime client.

func (*InMemoryBackend) CreateBackup

func (b *InMemoryBackend) CreateBackup(project string, in BackupInput) (*Operation, error)

CreateBackup takes an on-demand backup of an instance that outlives the instance.

func (*InMemoryBackend) DeleteBackup

func (b *InMemoryBackend) DeleteBackup(project, id string) (*Operation, error)

DeleteBackup removes a project backup.

func (*InMemoryBackend) DeleteBackupRun

func (b *InMemoryBackend) DeleteBackupRun(project, instance, id string) (*Operation, error)

DeleteBackupRun removes a backup run.

func (*InMemoryBackend) DeleteDatabase

func (b *InMemoryBackend) DeleteDatabase(project, instance, name string) (*Operation, error)

DeleteDatabase drops a database.

func (*InMemoryBackend) DeleteInstance

func (b *InMemoryBackend) DeleteInstance(project, name string, fb FinalBackupRequest) (*Operation, error)

DeleteInstance removes an instance and its engine.

func (*InMemoryBackend) DeleteSslCert

func (b *InMemoryBackend) DeleteSslCert(project, instance, fp string) (*Operation, error)

DeleteSslCert revokes a client certificate.

func (*InMemoryBackend) DeleteUser

func (b *InMemoryBackend) DeleteUser(project, instance, name, host string) (*Operation, error)

DeleteUser drops an account.

func (*InMemoryBackend) DemoteInstance

func (b *InMemoryBackend) DemoteInstance(project, name string, req DemoteRequest) (*Operation, error)

DemoteInstance turns a standalone primary into a read-only replica of an external source.

func (*InMemoryBackend) Drain

func (b *InMemoryBackend) Drain()

Drain blocks until every queued operation has finished.

func (*InMemoryBackend) EphemeralCert

func (b *InMemoryBackend) EphemeralCert(project, instance, publicKey, validDuration string) (*SslCert, error)

EphemeralCert signs a short-lived client certificate for a caller supplied public key.

func (*InMemoryBackend) ExecuteSQL

func (b *InMemoryBackend) ExecuteSQL(
	ctx context.Context, project, name string, in ExecuteSQLInput,
) (*ExecuteSQLResponse, error)

ExecuteSQL runs the statements of in on the instance engine (instances.executeSql).

func (*InMemoryBackend) ExportInstance

func (b *InMemoryBackend) ExportInstance(
	project, instance string,
	in ExportInput,
	raw map[string]any,
) (*Operation, error)

ExportInstance writes a SQL dump or CSV query result to object storage.

func (*InMemoryBackend) Failover

func (b *InMemoryBackend) Failover(project, instance string, settingsVersion string) (*Operation, error)

Failover promotes the standby of a REGIONAL instance; data committed before the call is present afterwards.

func (*InMemoryBackend) FailoverPromote

func (b *InMemoryBackend) FailoverPromote(project, name string) (*Operation, error)

FailoverPromote promotes the DR replica of a primary (promoteReplica with failover=true) and rejoins the old primary as a replica of it.

func (*InMemoryBackend) GetBackup

func (b *InMemoryBackend) GetBackup(project, id string) (*Backup, error)

GetBackup returns a project backup.

func (*InMemoryBackend) GetBackupRun

func (b *InMemoryBackend) GetBackupRun(project, instance, id string) (*BackupRun, error)

GetBackupRun returns a backup run.

func (*InMemoryBackend) GetConnectSettings

func (b *InMemoryBackend) GetConnectSettings(project, instance string) (*ConnectSettings, error)

GetConnectSettings returns what a client needs to reach the instance.

func (*InMemoryBackend) GetDatabase

func (b *InMemoryBackend) GetDatabase(project, instance, name string) (*Database, error)

GetDatabase returns a database.

func (*InMemoryBackend) GetInstance

func (b *InMemoryBackend) GetInstance(project, name string) (*Instance, error)

GetInstance returns an instance.

func (*InMemoryBackend) GetOperation

func (b *InMemoryBackend) GetOperation(project, name string) (*Operation, error)

GetOperation returns an operation.

func (*InMemoryBackend) GetSslCert

func (b *InMemoryBackend) GetSslCert(project, instance, fp string) (*SslCert, error)

GetSslCert returns a client certificate by fingerprint.

func (*InMemoryBackend) GetUser

func (b *InMemoryBackend) GetUser(project, instance, name, host string) (*User, error)

GetUser returns an account.

func (*InMemoryBackend) ImportInstance

func (b *InMemoryBackend) ImportInstance(
	project, instance string,
	in ImportInput,
	raw map[string]any,
) (*Operation, error)

ImportInstance loads a SQL file or CSV from object storage.

func (*InMemoryBackend) InsertBackupRun

func (b *InMemoryBackend) InsertBackupRun(project, instance, description string) (*Operation, error)

InsertBackupRun takes an on-demand logical backup of every user database.

func (*InMemoryBackend) InsertDatabase

func (b *InMemoryBackend) InsertDatabase(project, instance string, in DatabaseInput) (*Operation, error)

InsertDatabase creates a database.

func (*InMemoryBackend) InsertInstance

func (b *InMemoryBackend) InsertInstance(project string, in InstanceInput) (*Operation, error)

InsertInstance creates an instance, or a read replica when masterInstanceName is set, and starts its engine.

func (*InMemoryBackend) InsertSslCert

func (b *InMemoryBackend) InsertSslCert(project, instance, commonName string) (*CertInsertResult, error)

InsertSslCert issues a client certificate and private key.

func (*InMemoryBackend) InsertUser

func (b *InMemoryBackend) InsertUser(project, instance string, in UserInput) (*Operation, error)

InsertUser creates a database account.

func (*InMemoryBackend) LatestRecoveryTime

func (b *InMemoryBackend) LatestRecoveryTime(project, name string) (*RecoveryTimes, error)

LatestRecoveryTime reports the window point-in-time recovery can target.

func (*InMemoryBackend) ListBackupRuns

func (b *InMemoryBackend) ListBackupRuns(project, instance string) ([]*BackupRun, error)

ListBackupRuns lists backup runs, newest first.

func (*InMemoryBackend) ListBackups

func (b *InMemoryBackend) ListBackups(project, filter, token string, size int) (page.Page[*Backup], error)

ListBackups lists the unexpired backups of a project, newest first.

func (*InMemoryBackend) ListDatabases

func (b *InMemoryBackend) ListDatabases(project, instance string) ([]*Database, error)

ListDatabases lists the databases of an instance sorted by name.

func (*InMemoryBackend) ListInstances

func (b *InMemoryBackend) ListInstances(project, token string, limit int) page.Page[*Instance]

ListInstances lists the instances of a project sorted by name.

func (*InMemoryBackend) ListOperations

func (b *InMemoryBackend) ListOperations(project, instance, token string, limit int) page.Page[*Operation]

ListOperations lists operations of a project, newest first, optionally of one instance.

func (*InMemoryBackend) ListServerCas

func (b *InMemoryBackend) ListServerCas(project, instance string) (*ServerCas, error)

ListServerCas lists the active server CA, the CA waiting to be rotated in and the CA rotated out.

func (*InMemoryBackend) ListSslCerts

func (b *InMemoryBackend) ListSslCerts(project, instance string) ([]*SslCert, error)

ListSslCerts lists client certificates by creation time.

func (*InMemoryBackend) ListUsers

func (b *InMemoryBackend) ListUsers(project, instance string) ([]*User, error)

ListUsers lists the accounts of an instance sorted by name and host.

func (*InMemoryBackend) PromoteReplica

func (b *InMemoryBackend) PromoteReplica(project, name string) (*Operation, error)

PromoteReplica turns a read replica into a standalone primary.

func (*InMemoryBackend) ReplicaStatus

func (b *InMemoryBackend) ReplicaStatus(ctx context.Context, project, name string) (bool, float64, error)

ReplicaStatus reports a replica's replication health; it errors for non-replicas and state-only instances.

func (*InMemoryBackend) Reset

func (b *InMemoryBackend) Reset()

Reset removes every instance and stops its engine.

func (*InMemoryBackend) ResetSslConfig

func (b *InMemoryBackend) ResetSslConfig(project, instance string) (*Operation, error)

ResetSslConfig deletes every client certificate and issues a new server CA.

func (*InMemoryBackend) RestartInstance

func (b *InMemoryBackend) RestartInstance(project, name string) (*Operation, error)

RestartInstance restarts the engine, applying the configured flags.

func (*InMemoryBackend) Restore

func (b *InMemoryBackend) Restore(ctx context.Context, data []byte) error

Restore loads backend state from a snapshot and relaunches the engines of its instances.

func (*InMemoryBackend) RestoreBackup

func (b *InMemoryBackend) RestoreBackup(project, instance string, in RestoreBackupInput) (*Operation, error)

RestoreBackup replaces the databases of the target instance with a backup of the same engine family.

func (*InMemoryBackend) RestoreProjectBackup

func (b *InMemoryBackend) RestoreProjectBackup(project, instance, name string) (*Operation, error)

RestoreProjectBackup restores the databases of instance from the project backup named by name.

func (*InMemoryBackend) RotateServerCa

func (b *InMemoryBackend) RotateServerCa(project, instance, nextVersion string) (*Operation, error)

RotateServerCa makes the CA added by AddServerCa the one that signs and is reported as the server CA.

func (*InMemoryBackend) RunScheduledBackups

func (b *InMemoryBackend) RunScheduledBackups(now time.Time) int

RunScheduledBackups starts the automated backup of every running primary whose backup window for the day of now has begun and has none yet, and returns how many it started.

func (*InMemoryBackend) SetBackupLimits

func (b *InMemoryBackend) SetBackupLimits(count int, bytesLimit int64)

SetBackupLimits bounds how many backups and how many bytes of backup content one project retains; zero keeps the default.

func (*InMemoryBackend) SetClock

func (b *InMemoryBackend) SetClock(now func() time.Time)

SetClock replaces the time source for timestamps and schedules; tests pass a fake.

func (*InMemoryBackend) SetLauncher

func (b *InMemoryBackend) SetLauncher(l Launcher)

SetLauncher wires the database engine source; nil keeps instances state-only.

func (*InMemoryBackend) SetObjectStore

func (b *InMemoryBackend) SetObjectStore(o ObjectStore)

SetObjectStore wires the object store export and import read and write.

func (*InMemoryBackend) SetQuotaInterval

func (b *InMemoryBackend) SetQuotaInterval(d time.Duration)

SetQuotaInterval sets how often disk usage is compared with the provisioned size.

func (*InMemoryBackend) SetReplicaRunning

func (b *InMemoryBackend) SetReplicaRunning(project, name string, on bool) (*Operation, error)

SetReplicaRunning starts (true) or stops (false) replication on a read replica.

func (*InMemoryBackend) SetRunContext

func (b *InMemoryBackend) SetRunContext(parent context.Context)

SetRunContext derives the context engines run under; cancelling parent aborts launches in flight.

func (*InMemoryBackend) SetSecretReader

func (b *InMemoryBackend) SetSecretReader(r SecretReader)

SetSecretReader wires the Secret Manager emulator that resolves passwordSecretVersion.

func (*InMemoryBackend) SetStartupTimeout

func (b *InMemoryBackend) SetStartupTimeout(d time.Duration)

SetStartupTimeout bounds how long an engine launch may take.

func (*InMemoryBackend) Snapshot

func (b *InMemoryBackend) Snapshot(ctx context.Context) []byte

Snapshot serialises the backend state. Engine data is not part of it. Backup dumps are immutable once stored, so they are encoded after the backend lock is released.

func (*InMemoryBackend) StartBackupScheduler

func (b *InMemoryBackend) StartBackupScheduler(every time.Duration)

StartBackupScheduler runs RunScheduledBackups every interval until the backend is closed; zero uses a minute.

func (*InMemoryBackend) Switchover

func (b *InMemoryBackend) Switchover(project, instance string) (*Operation, error)

Switchover promotes the read replica and makes the old primary a replica of it.

func (*InMemoryBackend) TruncateLog

func (b *InMemoryBackend) TruncateLog(project, instance, logType string) (*Operation, error)

TruncateLog empties a MySQL general or slow log table.

func (*InMemoryBackend) UpdateBackup

func (b *InMemoryBackend) UpdateBackup(project, id string, in BackupInput, mask string) (*Operation, error)

UpdateBackup changes the description or retention of a final backup.

func (*InMemoryBackend) UpdateDatabase

func (b *InMemoryBackend) UpdateDatabase(project, instance, name string, in DatabaseInput) (*Operation, error)

UpdateDatabase accepts a patch or update that leaves the immutable charset and collation unchanged.

func (*InMemoryBackend) UpdateInstance

func (b *InMemoryBackend) UpdateInstance(project, name string, in InstanceInput, replace bool) (*Operation, error)

UpdateInstance patches (merge) or replaces (PUT) the settings of an instance.

func (*InMemoryBackend) UpdateUser

func (b *InMemoryBackend) UpdateUser(project, instance, name, host string, in UserInput) (*Operation, error)

UpdateUser changes the password and policy of an account.

type Instance

type Instance struct {
	Settings                   map[string]any      `json:"settings,omitempty"`
	ServerCaCert               *SslCert            `json:"serverCaCert,omitempty"`
	Kind                       string              `json:"kind"`
	State                      string              `json:"state"`
	DatabaseVersion            string              `json:"databaseVersion"`
	Etag                       string              `json:"etag"`
	InstanceType               string              `json:"instanceType"`
	Project                    string              `json:"project"`
	ServiceAccountEmailAddress string              `json:"serviceAccountEmailAddress,omitempty"`
	BackendType                string              `json:"backendType"`
	SelfLink                   string              `json:"selfLink"`
	ConnectionName             string              `json:"connectionName"`
	Name                       string              `json:"name"`
	Region                     string              `json:"region"`
	GceZone                    string              `json:"gceZone,omitempty"`
	SecondaryGceZone           string              `json:"secondaryGceZone,omitempty"`
	CreateTime                 string              `json:"createTime"`
	MaintenanceVersion         string              `json:"maintenanceVersion,omitempty"`
	SQLNetworkArchitecture     string              `json:"sqlNetworkArchitecture,omitempty"`
	GopherstackEndpoint        string              `json:"gopherstackEndpoint,omitempty"`
	MasterInstanceName         string              `json:"masterInstanceName,omitempty"`
	ReplicaConfiguration       map[string]any      `json:"replicaConfiguration,omitempty"`
	ReplicationCluster         *ReplicationCluster `json:"replicationCluster,omitempty"`
	IPAddresses                []IPMapping         `json:"ipAddresses,omitempty"`
	ReplicaNames               []string            `json:"replicaNames,omitempty"`
}

Instance is the sql#instance resource.

type InstanceInput

type InstanceInput struct {
	Settings           map[string]any      `json:"settings"`
	ReplicationCluster *ReplicationCluster `json:"replicationCluster"`
	Name               string              `json:"name"`
	Region             string              `json:"region"`
	DatabaseVersion    string              `json:"databaseVersion"`
	RootPassword       string              `json:"rootPassword"`
	InstanceType       string              `json:"instanceType"`
	MasterInstanceName string              `json:"masterInstanceName"`
	MaintenanceVersion string              `json:"maintenanceVersion"`
}

InstanceInput is the writable part of sql#instance.

type Interval

type Interval struct {
	StartTime string `json:"startTime,omitempty"`
	EndTime   string `json:"endTime,omitempty"`
}

Interval is the output-only time span of a backup.

type LaunchSpec

type LaunchSpec struct {
	Replica     *ReplicaSource
	Recovery    *Recovery
	ID          string
	Project     string
	Version     string
	Password    string
	Slot        string
	MemoryBytes int64
	NanoCPUs    int64
	Kind        dbKind
	ServerID    uint32
	Persist     bool
	Fresh       bool
	Standby     bool
}

LaunchSpec describes the engine of one instance.

type Launcher

type Launcher interface {
	Launch(ctx context.Context, spec LaunchSpec) (Engine, error)
}

Launcher starts engines.

type ObjectStore

type ObjectStore interface {
	ReadObject(bucket, name string) ([]byte, error)
	WriteObject(bucket, name string, data []byte, contentType string) error
}

ObjectStore is the object storage export and import files live in (the GCS emulator).

type Operation

type Operation struct {
	Error         *OperationErrors `json:"error,omitempty"`
	ExportContext map[string]any   `json:"exportContext,omitempty"`
	ImportContext map[string]any   `json:"importContext,omitempty"`
	BackupContext map[string]any   `json:"backupContext,omitempty"`
	Kind          string           `json:"kind"`
	Name          string           `json:"name"`
	OperationType string           `json:"operationType"`
	Status        string           `json:"status"`
	TargetID      string           `json:"targetId"`
	TargetLink    string           `json:"targetLink"`
	TargetProject string           `json:"targetProject"`
	SelfLink      string           `json:"selfLink"`
	User          string           `json:"user,omitempty"`
	InsertTime    string           `json:"insertTime"`
	StartTime     string           `json:"startTime,omitempty"`
	EndTime       string           `json:"endTime,omitempty"`
	// contains filtered or unexported fields
}

Operation is the sql#operation resource.

type OperationError

type OperationError struct {
	Kind    string `json:"kind"`
	Code    string `json:"code"`
	Message string `json:"message"`
}

OperationError is one error of a failed operation.

type OperationErrors

type OperationErrors struct {
	Kind   string           `json:"kind"`
	Errors []OperationError `json:"errors"`
}

OperationErrors is the error payload of a failed operation.

type Provider

type Provider struct{}

Provider implements service.Provider for Google Cloud SQL. It serves the Admin REST API on its own listener (see Handler.StartWorker) and never matches on the shared AWS router.

func (*Provider) Init

Init creates the backend and handler; the port is bound in StartWorker.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the service provider name.

type Purger

type Purger interface {
	Purge(ctx context.Context)
}

Purger is implemented by engines that own persistent storage; Purge also deletes it.

type Recoverer

type Recoverer interface {
	// EnablePITR starts archiving and returns the earliest time a recovery can target.
	EnablePITR(ctx context.Context, dbs []string) (time.Time, error)
	// DisablePITR stops archiving.
	DisablePITR(ctx context.Context) error
	// PrepareRecovery makes everything up to at recoverable and describes how a new engine starts from it.
	PrepareRecovery(ctx context.Context, at time.Time) (Recovery, error)
	// ApplyRecovery finishes a recovery on a freshly launched engine.
	ApplyRecovery(ctx context.Context, rec Recovery) error
}

Recoverer is implemented by engines that keep the logs point-in-time recovery needs.

type Recovery

type Recovery struct {
	At     time.Time
	Source *ReplicaSource
	Volume string
	// FromFile and FromPos, UntilFile and UntilPos bound the MySQL binary log range a clone replays from Source.
	FromFile  string
	UntilFile string
	Script    []byte
	FromPos   uint64
	UntilPos  uint64
}

Recovery seeds an engine from another instance's point-in-time recovery state. Volume names the source's PostgreSQL archive; for MySQL, Script is the base dump and Source the engine whose binary log is replayed.

type RecoveryTimes

type RecoveryTimes struct {
	Kind                 string `json:"kind"`
	EarliestRecoveryTime string `json:"earliestRecoveryTime"`
	LatestRecoveryTime   string `json:"latestRecoveryTime"`
}

RecoveryTimes is the sql.projects.instances.getLatestRecoveryTime response.

type ReplicaSource

type ReplicaSource struct {
	Network   string
	NetworkID string
	Host      string
	Password  string
	Port      int
}

ReplicaSource tells a replica's engine how to reach its primary.

type ReplicationCluster

type ReplicationCluster struct {
	FailoverDrReplicaName string `json:"failoverDrReplicaName,omitempty"`
	DrReplica             bool   `json:"drReplica,omitempty"`
}

ReplicationCluster designates the disaster recovery replica of a primary, or marks a replica as that DR replica.

type Replicator

type Replicator interface {
	// ReplicationSource readies the engine as a replication source and says how a replica reaches it.
	ReplicationSource(ctx context.Context) (ReplicaSource, error)
	// AttachReplica starts replication from src; seed is a source dump for engines that cannot copy the data
	// themselves.
	AttachReplica(ctx context.Context, src ReplicaSource, seed []byte) error
	// ReplicaSeed returns the dump a MySQL replica starts from; PostgreSQL replicas copy the data themselves.
	ReplicaSeed(ctx context.Context, dbs []string) ([]byte, error)
	// Promote detaches a replica from its source and makes it writable.
	Promote(ctx context.Context) error
	// SetReplication pauses (false) or resumes (true) replication on a replica.
	SetReplication(ctx context.Context, on bool) error
	ReplicationStatus(ctx context.Context) (dbrepl.Status, error)
}

Replicator is implemented by engines that can feed or follow a replica.

type RestoreBackupInput

type RestoreBackupInput struct {
	BackupRunID jsonx.Number `json:"backupRunId"`
	InstanceID  string       `json:"instanceId"`
	Project     string       `json:"project"`
}

RestoreBackupInput is the restoreBackupContext of instances.restoreBackup.

type SQLExecutor

type SQLExecutor interface {
	ExecuteSQL(ctx context.Context, req ExecRequest) (ExecOutcome, error)
}

SQLExecutor is implemented by engines that can run client SQL for instances.executeSql.

type SecretReader

type SecretReader interface {
	AccessSecret(versionName string) ([]byte, error)
}

SecretReader resolves a Secret Manager version name to its payload.

type ServerCas

type ServerCas struct {
	Kind          string     `json:"kind"`
	ActiveVersion string     `json:"activeVersion,omitempty"`
	Certs         []*SslCert `json:"certs"`
}

ServerCas is the instances.listServerCas response.

type Settings

type Settings struct {
	Engine string `` //nolint:lll // config struct tags are intentionally verbose
	/* 219-byte string literal not displayed */
	Port int `` //nolint:lll // config struct tags are intentionally verbose
	/* 208-byte string literal not displayed */
	StartupTimeout time.Duration `` //nolint:lll // config struct tags are intentionally verbose
	/* 194-byte string literal not displayed */
}

Settings holds service-level configuration, embedded in the root CLI command as CLI.GCPSQL.

func DefaultSettings

func DefaultSettings() Settings

DefaultSettings returns the settings used when no ConfigProvider is available.

type SslCert

type SslCert struct {
	Kind             string `json:"kind"`
	CertSerialNumber string `json:"certSerialNumber,omitempty"`
	Cert             string `json:"cert,omitempty"`
	CommonName       string `json:"commonName,omitempty"`
	Sha1Fingerprint  string `json:"sha1Fingerprint,omitempty"`
	Instance         string `json:"instance,omitempty"`
	CreateTime       string `json:"createTime,omitempty"`
	ExpirationTime   string `json:"expirationTime,omitempty"`
	SelfLink         string `json:"selfLink,omitempty"`
}

SslCert is a server CA, client or ephemeral certificate.

type TierInfo

type TierInfo struct {
	Tier      string   `json:"tier"`
	Kind      string   `json:"kind"`
	RAM       string   `json:"RAM"`
	DiskQuota string   `json:"DiskQuota"`
	Region    []string `json:"region"`
}

TierInfo is one entry of tiers.list.

func ListTiers

func ListTiers() []TierInfo

ListTiers returns the machine tiers the emulator knows.

type User

type User struct {
	PasswordPolicy map[string]any `json:"passwordPolicy,omitempty"`
	Kind           string         `json:"kind"`
	Name           string         `json:"name"`
	Host           string         `json:"host,omitempty"`
	Instance       string         `json:"instance"`
	Project        string         `json:"project"`
	Type           string         `json:"type,omitempty"`
	Etag           string         `json:"etag"`
	DatabaseRoles  []string       `json:"databaseRoles,omitempty"`
}

User is the sql#user resource; the password is never serialised.

type UserInput

type UserInput struct {
	PasswordPolicy map[string]any `json:"passwordPolicy"`
	Name           string         `json:"name"`
	Host           string         `json:"host"`
	Password       string         `json:"password"`
	Type           string         `json:"type"`
	DatabaseRoles  []string       `json:"databaseRoles"`
}

UserInput is the writable part of sql#user.

type UserSpec

type UserSpec struct {
	Name     string
	Host     string
	Password string
}

UserSpec is a database account to create or update.

type VolumeRemover

type VolumeRemover interface {
	RemoveVolumes(ctx context.Context)
}

VolumeRemover is implemented by engines whose persistent volumes can be deleted after Close; Reset closes every engine before removing any volume so a clone's mount of its source's archive cannot block the removal.

type VolumeSweeper

type VolumeSweeper interface {
	SweepVolumes(ctx context.Context, keep map[string]bool)
}

VolumeSweeper is implemented by launchers that can delete persistent volumes no instance owns.

Jump to

Keyboard shortcuts

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