Documentation
¶
Overview ¶
Package cloudsql provides shared utilities for Cloud SQL connection tools. This package is used by both cloudsqlpg and cloudsqlmysql tool packages to provide consistent connection recommendations, validation, and code generation.
Index ¶
- Constants
- Variables
- func DefaultDatabaseName(dbType DatabaseType) string
- func ExtractNetworkName(path string) string
- func FindVM(ctx context.Context, service *compute.Service, project, vmName string) (*compute.Instance, string, error)
- func GenerateGKESidecarYAML(connectionName string, port int) string
- func GenerateKubernetesSecretYAML(dbName string) string
- func GetCloudRunRecommendations(sqlInfo *CloudSQLInstanceInfo, runInfo *CloudRunServiceInfo) (ConnectionRecommendation, []ConnectionRecommendation)
- func GetComputeService(ctx context.Context, accessToken string) (*compute.Service, error)
- func GetDatabasePort(dbType DatabaseType) int
- func GetGCERecommendations(sqlInfo *CloudSQLInstanceInfo, vmInfo *GCEInstanceInfo, sameVPC bool) (ConnectionRecommendation, []ConnectionRecommendation)
- func GetGKERecommendations(sqlInfo *CloudSQLInstanceInfo, gkeInfo *GKEClusterInfo, sameVPC bool) (ConnectionRecommendation, []ConnectionRecommendation)
- func GetLocalRecommendations(sqlInfo *CloudSQLInstanceInfo) (ConnectionRecommendation, []ConnectionRecommendation)
- func IsSameVPC(sqlVPC, vmVPC string) bool
- func IsValidLanguage(lang string) bool
- func ParseConnectionName(connName string) (project, region, instance string, err error)
- func ValidateDatabaseName(name string) error
- func ValidateGCEResourceName(name, kind string) error
- func ValidateInstanceConnectionName(connName string) (project, region, instance string, err error)
- func ValidateLanguage(lang string) error
- type CloudRunServiceInfo
- type CloudSQLInstanceInfo
- type CodeSnippet
- type ComputeType
- type ConnectResult
- type ConnectionMethod
- type ConnectionRecommendation
- type ConnectionStrings
- type DatabaseType
- type EnvironmentConfig
- type GCEInstanceInfo
- type GKEClusterInfo
- type Language
- type SetupStep
- func GenerateCloudRunSetupSteps(connectionName, serviceAccount, region string) []SetupStep
- func GenerateGCESetupSteps(method ConnectionMethod, connectionName string, port int, privateIP string, ...) []SetupStep
- func GenerateGKESetupSteps(connectionName string, port int, projectID string, namespace string) []SetupStep
- func GenerateLocalSetupSteps(connectionName string, port int) []SetupStep
- type ValidationCheck
- type ValidationResult
- func ValidateCloudRunConnection(sqlInfo *CloudSQLInstanceInfo, runInfo *CloudRunServiceInfo) *ValidationResult
- func ValidateGCEConnection(sqlInfo *CloudSQLInstanceInfo, vmInfo *GCEInstanceInfo) *ValidationResult
- func ValidateGKEConnection(sqlInfo *CloudSQLInstanceInfo, gkeInfo *GKEClusterInfo) *ValidationResult
- func ValidateLocalConnection(sqlInfo *CloudSQLInstanceInfo) *ValidationResult
Constants ¶
const ( MethodNameAuthProxy = "Cloud SQL Auth Proxy" MethodNameConnector = "Cloud SQL Connector Library" MethodNameDirectPrivateIP = "Direct Private IP Connection" MethodNameUnixSocket = "Built-in Cloud SQL Connection (Unix Socket)" )
Connection method display names for user-facing messages
Variables ¶
var AllDatabaseTypes = []DatabaseType{PostgreSQL, MySQL, SQLServer}
AllDatabaseTypes lists every Cloud SQL engine this package supports.
var AvailableLanguages = []Language{LangPython, LangNodeJS, LangJava, LangGo}
AvailableLanguages lists all supported languages.
Functions ¶
func DefaultDatabaseName ¶
func DefaultDatabaseName(dbType DatabaseType) string
DefaultDatabaseName returns the conventional default database name for an engine.
func ExtractNetworkName ¶
ExtractNetworkName pulls the trailing element off a fully-qualified network or subnetwork resource path. Idempotent for inputs that are already a name.
func FindVM ¶
func FindVM(ctx context.Context, service *compute.Service, project, vmName string) (*compute.Instance, string, error)
FindVM resolves a VM by name across all zones in a project. It uses a server-side name filter so the API short-circuits per-zone scans, and stops paging once a second match is seen (so we don't read pages we don't need just to error out).
func GenerateGKESidecarYAML ¶
GenerateGKESidecarYAML generates the sidecar container YAML for GKE deployments.
func GenerateKubernetesSecretYAML ¶
GenerateKubernetesSecretYAML generates a Kubernetes Secret manifest.
func GetCloudRunRecommendations ¶
func GetCloudRunRecommendations(sqlInfo *CloudSQLInstanceInfo, runInfo *CloudRunServiceInfo) (ConnectionRecommendation, []ConnectionRecommendation)
GetCloudRunRecommendations returns connection recommendations for Cloud Run.
func GetComputeService ¶
GetComputeService returns a Compute Engine read-only client.
When accessToken is non-empty the returned client is scoped to that caller-supplied OAuth token, so IAM decisions on the Compute API are evaluated as the caller (matching how cloudsqladmin.Source.GetService treats its accessToken). When accessToken is empty the function returns the process-wide client backed by Application Default Credentials, built once on first call.
The ADC-backed initializer runs with context.Background() on purpose: a request-scoped ctx cached inside sync.Once would poison every subsequent invocation if the first caller cancelled. Callers still propagate their request ctx to individual API calls via Instances.Get(...).Context(ctx).Do().
func GetDatabasePort ¶
func GetDatabasePort(dbType DatabaseType) int
GetDatabasePort returns the default listening port for a Cloud SQL engine.
func GetGCERecommendations ¶
func GetGCERecommendations(sqlInfo *CloudSQLInstanceInfo, vmInfo *GCEInstanceInfo, sameVPC bool) (ConnectionRecommendation, []ConnectionRecommendation)
GetGCERecommendations returns connection recommendations for GCE VM. It analyzes the network configuration and returns the best connection method as primary, along with alternatives.
func GetGKERecommendations ¶
func GetGKERecommendations(sqlInfo *CloudSQLInstanceInfo, gkeInfo *GKEClusterInfo, sameVPC bool) (ConnectionRecommendation, []ConnectionRecommendation)
GetGKERecommendations returns connection recommendations for GKE cluster.
func GetLocalRecommendations ¶
func GetLocalRecommendations(sqlInfo *CloudSQLInstanceInfo) (ConnectionRecommendation, []ConnectionRecommendation)
GetLocalRecommendations returns connection recommendations for local development.
func IsSameVPC ¶
IsSameVPC reports whether the Cloud SQL VPC and the GCE VM VPC resolve to the same network name.
func IsValidLanguage ¶
IsValidLanguage checks if the given language is supported.
func ParseConnectionName ¶
ParseConnectionName splits a Cloud SQL instance connection name ("project:region:instance") into its three components, rejecting any input that doesn't have exactly three non-empty parts.
func ValidateDatabaseName ¶
ValidateDatabaseName accepts the conservative subset of database identifier characters that's safe in DSNs and code-snippet templates across Postgres, MySQL and SQL Server. It deliberately rejects quotes, semicolons, and whitespace even when the engine itself would accept them.
func ValidateGCEResourceName ¶
ValidateGCEResourceName checks a VM name or zone name against the standard GCE resource-name rule (lowercase, digits, hyphen; must start with a letter and not end with a hyphen, max 63 chars).
func ValidateInstanceConnectionName ¶
ValidateInstanceConnectionName splits and validates project, region, and instance ID per the GCP naming rules. Use this in place of plain ParseConnectionName when the parts will flow into generated code or shell.
func ValidateLanguage ¶
ValidateLanguage returns an error if the language is not supported.
Types ¶
type CloudRunServiceInfo ¶
type CloudRunServiceInfo struct {
Name string
Region string
Project string
ServiceAccount string
VPCConnector string
DirectVPCEgress bool
CloudSQLInstances []string
}
CloudRunServiceInfo contains information about a Cloud Run service.
type CloudSQLInstanceInfo ¶
type CloudSQLInstanceInfo struct {
Name string
Project string
Region string
ConnectionName string
DatabaseVersion string
DatabaseType DatabaseType
PublicIPAddress string
PrivateIPAddress string
PublicIPEnabled bool
PrivateIPEnabled bool
VPCNetwork string
RequireSSL bool
AuthorizedNetworks []string
}
CloudSQLInstanceInfo contains information about a Cloud SQL instance.
func ExtractSQLInfo ¶
func ExtractSQLInfo(inst *sqladmin.DatabaseInstance) *CloudSQLInstanceInfo
ExtractSQLInfo lifts the fields the connect tools need out of a Cloud SQL Admin DatabaseInstance.
type CodeSnippet ¶
type CodeSnippet struct {
Language Language `json:"language"`
Code string `json:"code"`
Dependencies []string `json:"dependencies"`
Notes []string `json:"notes,omitempty"`
}
CodeSnippet represents generated code for connecting to Cloud SQL.
func GenerateCodeSnippet ¶
func GenerateCodeSnippet(lang Language, method ConnectionMethod, dbType DatabaseType, connectionName, dbName string, port int, privateIP string) *CodeSnippet
GenerateCodeSnippet generates a code snippet for the given configuration. SQL Server is routed to dedicated generators because the Cloud SQL Connector libraries fully support only Postgres and MySQL.
Every returned snippet carries a Dependencies list floor-pinned to the minimum tested version of each library (pip `>=`, npm `^`, Maven exact, Go module `@version`), plus an install-command note derived from that list, so the caller can install a known-working environment without hitting the "which version?" question.
type ComputeType ¶
type ComputeType string
ComputeType represents the type of compute environment.
const ( // ComputeGCE represents Google Compute Engine VMs ComputeGCE ComputeType = "gce" // ComputeGKE represents Google Kubernetes Engine clusters ComputeGKE ComputeType = "gke" // ComputeCloudRun represents Cloud Run services ComputeCloudRun ComputeType = "cloudrun" // ComputeLocal represents local development environments ComputeLocal ComputeType = "local" )
type ConnectResult ¶
type ConnectResult struct {
// Instance information
InstanceConnectionName string `json:"instanceConnectionName"`
Project string `json:"project"`
Region string `json:"region"`
DatabaseType DatabaseType `json:"databaseType"`
DatabaseVersion string `json:"databaseVersion"`
// Compute information
ComputeType ComputeType `json:"computeType"`
ComputeResource string `json:"computeResource"`
ComputeLocation string `json:"computeLocation,omitempty"`
// Network validation
Validation ValidationResult `json:"validation"`
// Recommendations
RecommendedMethod ConnectionRecommendation `json:"recommendedMethod"`
AlternativeMethods []ConnectionRecommendation `json:"alternativeMethods,omitempty"`
// Configuration
ConnectionStrings ConnectionStrings `json:"connectionStrings"`
EnvironmentConfig EnvironmentConfig `json:"environmentConfig"`
// Setup instructions
SetupSteps []SetupStep `json:"setupSteps"`
// Code snippet (only if language was specified)
CodeSnippet *CodeSnippet `json:"codeSnippet,omitempty"`
AvailableLanguages []Language `json:"availableLanguages"`
// Required permissions and APIs
RequiredIAMRoles []string `json:"requiredIamRoles"`
RequiredAPIs []string `json:"requiredApis"`
}
ConnectResult is the comprehensive result returned by connect tools.
type ConnectionMethod ¶
type ConnectionMethod string
ConnectionMethod represents a method to connect to Cloud SQL.
const ( // MethodAuthProxy uses Cloud SQL Auth Proxy for secure connections MethodAuthProxy ConnectionMethod = "auth_proxy" // MethodConnector uses Cloud SQL Connector libraries MethodConnector ConnectionMethod = "connector" // MethodDirectPrivateIP uses direct private IP connection MethodDirectPrivateIP ConnectionMethod = "direct_private_ip" // MethodUnixSocket uses Unix socket (Cloud Run built-in) MethodUnixSocket ConnectionMethod = "unix_socket" )
type ConnectionRecommendation ¶
type ConnectionRecommendation struct {
Method ConnectionMethod `json:"method"`
Name string `json:"name"`
Description string `json:"description"`
Priority int `json:"priority"`
Security string `json:"security"`
Complexity string `json:"complexity"`
Performance string `json:"performance"`
Requirements []string `json:"requirements"`
Considerations []string `json:"considerations,omitempty"`
}
ConnectionRecommendation represents a recommended connection method.
type ConnectionStrings ¶
type ConnectionStrings struct {
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
SocketPath string `json:"socketPath,omitempty"`
DSN string `json:"dsn,omitempty"`
JDBC string `json:"jdbc,omitempty"`
}
ConnectionStrings contains connection string templates. Credential placeholders use UPPERCASE tokens (USER, PASS) so they're obviously not real values.
func BuildConnectionStrings ¶
func BuildConnectionStrings(method ConnectionMethod, dbType DatabaseType, sqlInfo *CloudSQLInstanceInfo, dbName, connName string) ConnectionStrings
BuildConnectionStrings returns engine-aware DSN/JDBC templates for the given recommended connection method.
type DatabaseType ¶
type DatabaseType string
DatabaseType represents the type of database.
const ( // PostgreSQL database type PostgreSQL DatabaseType = "postgres" // MySQL database type MySQL DatabaseType = "mysql" // SQLServer (Cloud SQL for SQL Server) database type SQLServer DatabaseType = "sqlserver" )
func ParseDatabaseType ¶
func ParseDatabaseType(version string) DatabaseType
ParseDatabaseType maps a Cloud SQL Admin API DatabaseVersion string (e.g. "POSTGRES_15", "MYSQL_8_0", "SQLSERVER_2022_STANDARD") to a DatabaseType. Unknown or empty versions fall back to PostgreSQL; callers that need to reject unknown values should use ParseDatabaseTypeStrict.
func ParseDatabaseTypeStrict ¶
func ParseDatabaseTypeStrict(version string) (DatabaseType, error)
ParseDatabaseTypeStrict is like ParseDatabaseType but returns an error instead of silently defaulting when the DatabaseVersion prefix is not one of the engines this package supports. Use it when auto-detecting the engine from a live sqladmin response so a new Cloud SQL engine (or a malformed value) surfaces a clear diagnostic instead of producing wrong output.
type EnvironmentConfig ¶
type EnvironmentConfig struct {
// Common config
EnvironmentVariables map[string]string `json:"environmentVariables"`
// Auth Proxy config
AuthProxyCommand string `json:"authProxyCommand,omitempty"`
// GKE-specific config
KubernetesServiceAccount string `json:"kubernetesServiceAccount,omitempty"`
SidecarYAML string `json:"sidecarYaml,omitempty"`
SecretYAML string `json:"secretYaml,omitempty"`
// Cloud Run-specific config
CloudRunFlags []string `json:"cloudRunFlags,omitempty"`
}
EnvironmentConfig represents environment-specific configuration.
func GenerateEnvironmentConfig ¶
func GenerateEnvironmentConfig(method ConnectionMethod, computeType ComputeType, connectionName string, port int, privateIP, dbName, projectID string) EnvironmentConfig
GenerateEnvironmentConfig generates environment configuration for the connection.
type GCEInstanceInfo ¶
type GCEInstanceInfo struct {
Name string
Zone string
Project string
InternalIP string
ExternalIP string
VPCNetwork string
Subnetwork string
ServiceAccount string
HasExternalIP bool
}
GCEInstanceInfo contains information about a GCE VM instance.
func ExtractVMInfo ¶
func ExtractVMInfo(inst *compute.Instance, zone string) *GCEInstanceInfo
ExtractVMInfo lifts the fields the connect tools need out of a Compute Engine instance.
type GKEClusterInfo ¶
type GKEClusterInfo struct {
Name string
Location string
Project string
VPCNetwork string
Subnetwork string
WorkloadIdentity bool
PrivateCluster bool
VPCNative bool
}
GKEClusterInfo contains information about a GKE cluster.
type Language ¶
type Language string
Language represents a programming language for code generation.
type SetupStep ¶
type SetupStep struct {
Order int `json:"order"`
Title string `json:"title"`
Description string `json:"description"`
Command string `json:"command,omitempty"`
}
SetupStep represents a step in the setup process.
func GenerateCloudRunSetupSteps ¶
GenerateCloudRunSetupSteps generates setup steps for Cloud Run connection.
func GenerateGCESetupSteps ¶
func GenerateGCESetupSteps(method ConnectionMethod, connectionName string, port int, privateIP string, serviceAccount string) []SetupStep
GenerateGCESetupSteps generates setup steps for GCE VM connection.
func GenerateGKESetupSteps ¶
func GenerateGKESetupSteps(connectionName string, port int, projectID string, namespace string) []SetupStep
GenerateGKESetupSteps generates setup steps for GKE connection. The namespace parameter specifies the Kubernetes namespace for deployment.
func GenerateLocalSetupSteps ¶
GenerateLocalSetupSteps generates setup steps for local development. This focuses on public IP connections via Auth Proxy, which is the recommended approach for local development. Private IP connections require VPN or Cloud Interconnect setup, which is outside the scope of this tool.
type ValidationCheck ¶
type ValidationCheck struct {
Name string `json:"name"`
Status string `json:"status"` // "pass", "fail", "warn", "info"
Message string `json:"message"`
}
ValidationCheck represents a single validation check result.
type ValidationResult ¶
type ValidationResult struct {
Valid bool `json:"valid"`
Checks []ValidationCheck `json:"checks"`
Issues []string `json:"issues,omitempty"`
Recommendations []string `json:"recommendations,omitempty"`
}
ValidationResult represents the result of network validation.
func ValidateCloudRunConnection ¶
func ValidateCloudRunConnection(sqlInfo *CloudSQLInstanceInfo, runInfo *CloudRunServiceInfo) *ValidationResult
ValidateCloudRunConnection validates network connectivity between Cloud SQL and Cloud Run.
func ValidateGCEConnection ¶
func ValidateGCEConnection(sqlInfo *CloudSQLInstanceInfo, vmInfo *GCEInstanceInfo) *ValidationResult
ValidateGCEConnection validates network connectivity between Cloud SQL and GCE VM.
func ValidateGKEConnection ¶
func ValidateGKEConnection(sqlInfo *CloudSQLInstanceInfo, gkeInfo *GKEClusterInfo) *ValidationResult
ValidateGKEConnection validates network connectivity between Cloud SQL and GKE cluster.
func ValidateLocalConnection ¶
func ValidateLocalConnection(sqlInfo *CloudSQLInstanceInfo) *ValidationResult
ValidateLocalConnection validates requirements for local IDE connection.