### Running Survey Examples Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/AlecAivazis/survey/v2/README.md Instructions for getting and running the example surveys. Ensure you have the survey library installed. ```bash go get github.com/AlecAivazis/survey/v2 cd $GOPATH/src/github.com/AlecAivazis/survey go run examples/simple.go go run examples/validation.go ``` -------------------------------- ### Install and Run Go OLE Example Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/go-ole/go-ole/README.md Commands to fetch the package, run tests, and execute the Excel example program. ```bash go get github.com/go-ole/go-ole cd /path/to/go-ole/ go test cd /path/to/go-ole/example/excel go run excel.go ``` -------------------------------- ### Install go-syslog Package Source: https://github.com/pganalyze/collector/blob/main/vendor/gopkg.in/mcuadros/go-syslog.v2/README.md Use 'go get' to install the go-syslog library. This is the recommended installation method. ```go go get gopkg.in/mcuadros/go-syslog.v2 ``` -------------------------------- ### Install the AMQP module Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/go-amqp/README.md Use the go get command to install the package. ```sh go get github.com/Azure/go-amqp ``` -------------------------------- ### Install cronexpr Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/gorhill/cronexpr/README.md Use the go get command to install the library. ```bash go get github.com/gorhill/cronexpr ``` -------------------------------- ### Install color package Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/fatih/color/README.md Use the go get command to install the package. ```bash go get github.com/fatih/color ``` -------------------------------- ### Install OpenCensus Go Source: https://github.com/pganalyze/collector/blob/main/vendor/go.opencensus.io/README.md Use the go get command to install the OpenCensus Go library. ```bash $ go get -u go.opencensus.io ``` -------------------------------- ### Install go-isatty Package Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/mattn/go-isatty/README.md Install the go-isatty package using the go get command. ```bash $ go get github.com/mattn/go-isatty ``` -------------------------------- ### Install pg_query_go Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/pganalyze/pg_query_go/v6/README.md Use the go get command to install the library. Note that the first build may take up to 3 minutes due to compiling PostgreSQL source. ```bash go get github.com/pganalyze/pg_query_go/v6@latest ``` -------------------------------- ### Install go-colorable Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/mattn/go-colorable/README.md Use the go get command to add the package to your project. ```bash $ go get github.com/mattn/go-colorable ``` -------------------------------- ### Setup Test Database in New Cluster Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md Commands to create the database and run the setup SQL script. ```bash createdb psql --no-psqlrc -f testsetup/postgresql_setup.sql ``` -------------------------------- ### Install go-ini/ini Package Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/go-ini/ini/README.md Install the go-ini/ini package using the go get command. Use the -u flag for future updates. ```sh go get gopkg.in/ini.v1 ``` -------------------------------- ### Install Make Tools and Run Tests Source: https://github.com/pganalyze/collector/blob/main/vendor/go.opencensus.io/CONTRIBUTING.md Install necessary tools using 'make install-tools' (only required the first time) and then run 'make' to execute the project's tests. This ensures your changes do not break existing functionality. ```bash $ make install-tools # Only first time. $ make ``` -------------------------------- ### Install and Configure Repository Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Commands to install the package and manage feature branches during development. ```bash go get -u github.com/fsnotify/fsnotify ``` ```bash git checkout -b my-new-feature ``` ```bash git commit -am 'Add some feature' ``` -------------------------------- ### Run local Go Doc site Source: https://github.com/pganalyze/collector/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Commands to install and launch a local documentation server. ```sh go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Install AlloyDB Go Connector Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/alloydbconn/README.md Install the AlloyDB Go Connector package using go get. ```sh go get cloud.google.com/go/alloydbconn ``` -------------------------------- ### Install the longrunning Library Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/longrunning/README.md Use this command to install the Go helper library for long-running operations. ```bash go get cloud.google.com/go/longrunning ``` -------------------------------- ### Install Cloud SQL Go Connector Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/cloudsqlconn/README.md Use the go get command to add the connector package to your Go project. ```sh go get cloud.google.com/go/cloudsqlconn ``` -------------------------------- ### Install Google Auth Library for Go Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/auth/README.md Use this command to install the latest version of the Google Auth Library for Go. ```bash go get cloud.google.com/go/auth@latest ``` -------------------------------- ### Install Azure Event Hubs Go Package Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs/README.md Install the Azure Event Hubs client module for Go using the go get command. Ensure you have Go version 1.18 or higher installed. ```bash go get github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs ``` -------------------------------- ### Install Google Cloud Go packages Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/README.md Use the go get command to add specific Google Cloud service packages to your project. ```bash go get cloud.google.com/go/firestore@latest # Replace firestore with the package you want to use. ``` -------------------------------- ### Basic Syslog UDP Server Example Source: https://github.com/pganalyze/collector/blob/main/vendor/gopkg.in/mcuadros/go-syslog.v2/README.md This example demonstrates how to set up a basic syslog server over UDP. It configures the server to use RFC5424 format and listens on all interfaces on port 514. Received log parts are printed to the console. ```go channel := make(syslog.LogPartsChannel) handler := syslog.NewChannelHandler(channel) server := syslog.NewServer() server.SetFormat(syslog.RFC5424) server.SetHandler(handler) server.ListenUDP("0.0.0.0:514") server.Boot() go func(channel syslog.LogPartsChannel) { for logParts := range channel { fmt.Println(logParts) } }(channel) server.Wait() ``` -------------------------------- ### Install the Azure Cosmos for PostgreSQL module Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cosmosforpostgresql/armcosmosforpostgresql/README.md Use the go get command to add the module to your project dependencies. ```sh go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cosmosforpostgresql/armcosmosforpostgresql ``` -------------------------------- ### Verify Go Installation Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/CONTRIBUTING.md Check that the Go toolchain is correctly installed and accessible in the system path. ```bash go version ``` -------------------------------- ### Install ansi Package Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/mgutz/ansi/README.md Use 'go get' to install the ansi package. This command fetches and installs the specified package and its dependencies. ```sh go get -u github.com/mgutz/ansi ``` -------------------------------- ### Initialize Procfs and Get Stats Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem mount point and retrieves CPU statistics. Use this to start gathering data from /proc. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Advanced JMESPath Query Examples Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/jmespath/go-jmespath/README.md Examples demonstrating object selection, projection, and filtering using JMESPath expressions. ```go > var jsondata = []byte(`{"foo": {"bar": {"baz": [0, 1, 2, 3, 4]}}}`) // your data > var data interface{} > err := json.Unmarshal(jsondata, &data) > result, err := jmespath.search("foo.bar", data) result = { "baz": [ 0, 1, 2, 3, 4 ] } > var jsondata = []byte(`{"foo": [{"first": "a", "last": "b"}, {"first": "c", "last": "d"}]}`) // your data > var data interface{} > err := json.Unmarshal(jsondata, &data) > result, err := jmespath.search({"foo[*].first", data) result [ 'a', 'c' ] > var jsondata = []byte(`{"foo": [{"age": 20}, {"age": 25}, {"age": 30}, {"age": 35}, {"age": 40}]}`) // your data > var data interface{} > err := json.Unmarshal(jsondata, &data) > result, err := jmespath.search("foo[?age > `30`]") result = [ { age: 35 }, { age: 40 } ] ``` -------------------------------- ### Setup Cloud Storage Bucket Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/CONTRIBUTING.md Creates a storage bucket and assigns the Cloud Logging service account as owner. ```bash $ gsutil mb gs://$GCLOUD_TESTS_GOLANG_PROJECT_ID $ gsutil acl ch -g cloud-logs@google.com:O gs://$GCLOUD_TESTS_GOLANG_PROJECT_ID ``` -------------------------------- ### Install Azure Monitor Query packages Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/monitor/azquery/README.md Use these commands to install the necessary SDK modules for querying Azure Monitor and handling authentication. ```bash go get github.com/Azure/azure-sdk-for-go/sdk/monitor/azquery go get github.com/Azure/azure-sdk-for-go/sdk/azidentity ``` -------------------------------- ### Download the project using go get Source: https://github.com/pganalyze/collector/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use this command to download the project source code into your GOPATH. ```sh go get -d go.opentelemetry.io/otel ``` -------------------------------- ### Setup Existing PostgreSQL Test Database Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md Commands to create and configure a test database on an existing PostgreSQL cluster. ```bash export PGDATABASE=pgx_test createdb psql -c 'create extension hstore;' psql -c 'create extension ltree;' psql -c 'create domain uint64 as numeric(20,0);' ``` -------------------------------- ### Install uuid package Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/google/uuid/README.md Use this command to install the package via the Go toolchain. ```sh go get github.com/google/uuid ``` -------------------------------- ### Compile and run the collector Source: https://github.com/pganalyze/collector/blob/main/CONTRIBUTING.md Commands to build the binary and verify installation. ```sh make build ``` ```sh ./pganalyze-collector --help ``` -------------------------------- ### Get Partition Properties with ProducerClient (New) Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs/migrationguide.md Shows how to retrieve partition properties using the ProducerClient. ```go producerClient.GetPartitionProperties(context.TODO(), "partition-id", nil) ``` -------------------------------- ### Initialize SDK Component with Constructor Source: https://github.com/pganalyze/collector/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Encapsulate instrumentation setup within a constructor function to ensure clear ownership and scope. ```go import ( "errors" semconv "go.opentelemetry.io/otel/semconv/v1.40.0" "go.opentelemetry.io/otel/semconv/v1.40.0/otelconv" ) type SDKComponent struct { inst *instrumentation } func NewSDKComponent(config Config) (*SDKComponent, error) { inst, err := newInstrumentation() if err != nil { return nil, err } return &SDKComponent{inst: inst}, nil } type instrumentation struct { inflight otelconv.SDKComponentInflight exported otelconv.SDKComponentExported } func newInstrumentation() (*instrumentation, error) { if !x.Observability.Enabled() { return nil, nil } meter := otel.GetMeterProvider().Meter( "", metric.WithInstrumentationVersion(sdk.Version()), metric.WithSchemaURL(semconv.SchemaURL), ) inst := &instrumentation{} var err, e error inst.inflight, e = otelconv.NewSDKComponentInflight(meter) err = errors.Join(err, e) inst.exported, e = otelconv.NewSDKComponentExported(meter) err = errors.Join(err, e) return inst, err } ``` -------------------------------- ### Install dependencies for fsnotify Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/fsnotify/fsnotify/README.md Run this command to ensure the latest version of the required system package is installed. ```console go get -u golang.org/x/sys/... ``` -------------------------------- ### Install jwt-go Package Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/golang-jwt/jwt/v5/README.md Use this command to add jwt-go as a dependency in your Go program. Ensure Go is installed first. ```sh go get -u github.com/golang-jwt/jwt/v5 ``` -------------------------------- ### Install Compute Metadata Library Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/compute/metadata/README.md Use this command to add the compute metadata package to your Go project. ```bash go get cloud.google.com/go/compute/metadata ``` -------------------------------- ### Install Azure Identity module Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md Use the Go CLI to add the azidentity module as a dependency to your project. ```sh go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity ``` -------------------------------- ### Get Partition Properties (New) Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs/migrationguide.md Illustrates retrieving partition properties using the ConsumerClient, replacing the older GetPartitionInformation. ```go // equivalent to: hub.GetPartitionInformation consumerClient.GetPartitionProperties(context.TODO(), "partition-id", nil) ``` -------------------------------- ### Get Partition Information (Old) Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs/migrationguide.md Demonstrates the older method of retrieving partition information using the Hub type. ```go // old hub.GetPartitionInformation(context.TODO(), "0") hub.GetRuntimeInformation(context.TODO()) ``` -------------------------------- ### Configure Ubuntu 24.04 for Docker Release Source: https://github.com/pganalyze/collector/blob/main/CONTRIBUTING.md Commands to install Docker, QEMU emulation, and build dependencies on an Ubuntu 24.04 VM, followed by authentication and the build execution. ```bash # Add Docker's official GPG key: sudo apt-get update && \ sudo apt-get install -y ca-certificates curl gnupg && \ sudo install -m 0755 -d /etc/apt/keyrings && \ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg && \ sudo chmod a+r /etc/apt/keyrings/docker.gpg # Add the repository to Apt sources: echo \ "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \ $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \ sudo tee /etc/apt/sources.list.d/docker.list > /dev/null && \ sudo apt-get update && \ sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin qemu-user-static binfmt-support make # Get password (entered interactively) from Quay.io # (under the robot accounts of the pganalyze organization) sudo docker login -u="pganalyze+push" quay.io # Pull collector repository and build git clone https://github.com/pganalyze/collector.git && \ cd collector && \ sudo make docker_release ``` -------------------------------- ### Format DSN for IAM Authentication Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/cloudsqlconn/README.md DSN configuration examples for Postgres and MySQL using a service account. ```go dsn := "user=test-sa@test-project.iam dbname=mydb sslmode=disable" ``` ```go dsn := "user=test-sa dbname=mydb sslmode=disable" ``` -------------------------------- ### Configuring Prompts with AskOpts Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/AlecAivazis/survey/v2/README.md Shows how to configure prompts using `AskOpts` for validators or defaults, applicable to both `Ask` and `AskOne` functions. ```go prompt := &Select{ Message: "Choose a color:", Options: []string{"red", "blue", "green"}, // can pass a validator directly Validate: survey.Required, } // or define a default for the single call to `AskOne` // the answer will get written to the color variable survey.AskOne(prompt, &color, survey.WithValidator(survey.Required)) // or define a default for every entry in a list of questions // the answer will get copied into the matching field of the struct as shown above survey.Ask(questions, &answers, survey.WithValidator(survey.Required)) ``` -------------------------------- ### Start Dedicated Test Cluster Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md Command to start the PostgreSQL cluster for testing. ```bash postgres -D .testdb/$POSTGRESQL_DATA_DIR ``` -------------------------------- ### Initialize a Google Cloud client Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/README.md Initialize a client using default credentials or explicit configuration options. ```go client, err := storage.NewClient(ctx) ``` ```go client, err := storage.NewClient(ctx, option.WithCredentialsFile("path/to/keyfile.json")) ``` ```go creds, err := credentials.DetectDefault(&credentials.DetectOptions{...}) ... client, err := storage.NewClient(ctx, option.WithAuthCredentials(creds)) ``` -------------------------------- ### Apply Tags for Profiling Source: https://github.com/pganalyze/collector/blob/main/vendor/go.opencensus.io/README.md Demonstrates how to create a new context with tags and then use tag.Do to execute a function where samples will be recorded with these tags. Ensure keys like osKey and userIDKey are defined. ```go ctx, err = tag.New(ctx, tag.Insert(osKey, "macOS-10.12.5"), tag.Insert(userIDKey, "fff0989878"), ) if err != nil { log.Fatal(err) } tag.Do(ctx, func(ctx context.Context) { // Do work. // When profiling is on, samples will be // recorded with the key/values from the tag map. }) ``` -------------------------------- ### Initialize the Client Factory Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cosmosforpostgresql/armcosmosforpostgresql/README.md Create a client factory to manage service clients using your subscription ID and credentials. ```go clientFactory, err := armcosmosforpostgresql.NewClientFactory(, cred, nil) ``` -------------------------------- ### Connect and Execute Query with pgconn Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/jackc/pgx/v5/pgconn/README.md Demonstrates connecting to a PostgreSQL database using a connection string and executing a parameterized query. Ensure the DATABASE_URL environment variable is set. ```go pgConn, err := pgconn.Connect(context.Background(), os.Getenv("DATABASE_URL")) if err != nil { log.Fatalln("pgconn failed to connect:", err) } deffer pgConn.Close(context.Background()) result := pgConn.ExecParams(context.Background(), "SELECT email FROM users WHERE id=$1", [][]byte{[]byte("123")}, nil, nil, nil) for result.NextRow() { fmt.Println("User 123 has email:", string(result.Values()[0])) } _, err = result.Close() if err != nil { log.Fatalln("failed reading result:", err) } ``` -------------------------------- ### Create an AMQP session Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/go-amqp/README.md Initialize a session from an existing connection. ```go session, err := conn.NewSession(context.TODO(), nil) if err != nil { // handle error } ``` -------------------------------- ### Create and Use a Generic Resource Pool in Go Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/jackc/puddle/v2/README.md Demonstrates creating a pool of net.Conn resources, acquiring a connection, writing data, and releasing the connection back to the pool. Ensure the constructor and destructor functions are correctly defined for the resource type. ```go package main import ( "context" "log" "net" "github.com/jackc/puddle/v2" ) func main() { constructor := func(context.Context) (net.Conn, error) { return net.Dial("tcp", "127.0.0.1:8080") } destructor := func(value net.Conn) { value.Close() } maxPoolSize := int32(10) pool, err := puddle.NewPool(&puddle.Config[net.Conn]{Constructor: constructor, Destructor: destructor, MaxSize: maxPoolSize}) if err != nil { log.Fatal(err) } // Acquire resource from the pool. res, err := pool.Acquire(context.Background()) if err != nil { log.Fatal(err) } // Use resource. _, err = res.Value().Write([]byte{1}) if err != nil { log.Fatal(err) } // Release when done. res.Release() } ``` -------------------------------- ### Install pganalyze collector via Helm Source: https://github.com/pganalyze/collector/blob/main/README.md Adds the official pganalyze Helm repository and installs the collector using a local values file. ```bash helm repo add pganalyze https://charts.pganalyze.com/ helm install my-collector pganalyze/pganalyze-collector --values=myvalues.yml ``` -------------------------------- ### Start and End a Span Source: https://github.com/pganalyze/collector/blob/main/vendor/go.opencensus.io/README.md Illustrates how to start a new span for a specific operation and ensure it is ended using defer. This is crucial for tracing operations. ```go ctx, span := trace.StartSpan(ctx, "cache.Get") defer span.End() // Do work to get from cache. ``` -------------------------------- ### Perform a GET Request with Retries Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/hashicorp/go-retryablehttp/README.md Use this for simple GET requests. The call will block and retry with exponential backoff on network errors or 5xx responses. ```go resp, err := retryablehttp.Get("/foo") if err != nil { panic(err) } ``` -------------------------------- ### Install Azure Database for PostgreSQL Module Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/postgresql/armpostgresqlflexibleservers/v4/README.md Use this command to install the Azure Database for PostgreSQL module for Go. This command utilizes Go modules for dependency management. ```sh go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/postgresql/armpostgresqlflexibleservers/v4 ``` -------------------------------- ### Get Private Link Resource Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/postgresql/armpostgresqlflexibleservers/v4/CHANGELOG.md Retrieves a specific private link resource. Requires context, subscription ID, resource group name, server name, and optional get options. ```go *PrivateLinkResourcesClient.Get(context.Context, string, string, string, *PrivateLinkResourcesClientGetOptions) (PrivateLinkResourcesClientGetResponse, error) ``` -------------------------------- ### Retrieve system configuration variables in Go Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/tklauser/go-sysconf/README.md Demonstrates how to use the sysconf package to retrieve system parameters like clock ticks. ```Go package main import ( "fmt" "github.com/tklauser/go-sysconf" ) func main() { // get clock ticks, this will return the same as C.sysconf(C._SC_CLK_TCK) clktck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) if err == nil { fmt.Printf("SC_CLK_TCK: %v\n", clktck) } } ``` -------------------------------- ### Get Private Endpoint Connection Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/postgresql/armpostgresqlflexibleservers/v4/CHANGELOG.md Retrieves a specific private endpoint connection. Requires context, subscription ID, resource group name, private endpoint connection name, and optional get options. ```go *PrivateEndpointConnectionsClient.Get(context.Context, string, string, string, *PrivateEndpointConnectionsClientGetOptions) (PrivateEndpointConnectionsClientGetResponse, error) ``` -------------------------------- ### GET /migrations/{migrationName} Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/postgresql/armpostgresqlflexibleservers/v4/CHANGELOG.md Retrieves the details of a specific migration. ```APIDOC ## GET /migrations/{migrationName} ### Description Retrieves the current status and properties of a specific migration. ### Method GET ### Parameters #### Path Parameters - **migrationName** (string) - Required - The name of the migration to retrieve. ### Response #### Success Response (200) - **MigrationsClientGetResponse** (object) - The migration resource details. ``` -------------------------------- ### Define an Exporter interface Source: https://github.com/pganalyze/collector/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Defines the base Exporter interface for the example. ```go type Exporter interface { Export() } ``` -------------------------------- ### Implement and test with a mock client Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/testing.md Create a lightweight mock implementation of the interface and use it within a standard Go test function. ```go import ( "context" "testing" "github.com/googleapis/gax-go/v2" translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" ) type mockClient struct{} func (*mockClient) TranslateText(_ context.Context, req *translatepb.TranslateTextRequest, opts ...gax.CallOption) (*translatepb.TranslateTextResponse, error) { resp := &translatepb.TranslateTextResponse{ Translations: []*translatepb.Translation{ &translatepb.Translation{ TranslatedText: "Hello World", }, }, } return resp, nil } func TestTranslateTextWithAbstractClient(t *testing.T) { client := &mockClient{} text, err := TranslateTextWithInterfaceClient(client, "Hola Mundo", "en-US") if err != nil { t.Fatal(err) } if text != "Hello World" { t.Fatalf("got %q, want Hello World", text) } } ``` -------------------------------- ### Define Environment Variables Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/CONTRIBUTING.md Example shell configuration for test environment variables. ```bash #### START GO SDK Test Variables # Developers Console project's ID (e.g. bamboo-shift-455) for the general project. export GCLOUD_TESTS_GOLANG_PROJECT_ID=your-project # Developers Console project's ID (e.g. bamboo-shift-455) for the Bigtable project. export GCLOUD_TESTS_GOLANG_SECONDARY_BIGTABLE_PROJECT_ID=your-bigtable-optional-secondary-project # The path to the JSON key file of the general project's service account. export GCLOUD_TESTS_GOLANG_KEY=~/directory/your-project-abcd1234.json # Comma separated list of developer's Datastore databases. If not provided, # default database i.e. empty string is used. export GCLOUD_TESTS_GOLANG_DATASTORE_DATABASES=your-database-1,your-database-2 # Developers Console project's ID (e.g. doorway-cliff-677) for the Firestore project. export GCLOUD_TESTS_GOLANG_FIRESTORE_PROJECT_ID=your-firestore-project # Comma separated list of developer's Firestore databases. If not provided, default database is used. export GCLOUD_TESTS_GOLANG_FIRESTORE_DATABASES=your-database-1,your-database-2 # The path to the JSON key file of the Firestore project's service account. export GCLOUD_TESTS_GOLANG_FIRESTORE_KEY=~/directory/your-firestore-project-abcd1234.json # The full name of the keyring for the tests, in the form "projects/P/locations/L/keyRings/R". # The creation of this is described below. export MY_KEYRING=my-golang-sdk-test export MY_LOCATION=global export GCLOUD_TESTS_GOLANG_KEYRING=projects/$GCLOUD_TESTS_GOLANG_PROJECT_ID/locations/$MY_LOCATION/keyRings/$MY_KEYRING # API key for using the Translate API. export GCLOUD_TESTS_API_KEY=abcdefghijk123456789 ``` -------------------------------- ### Conventional Commit Example Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/CONTRIBUTING.md Format commit messages according to the Conventional Commits specification. ```text feat(functions): add gophers codelab ``` -------------------------------- ### Import go-syslog Package Source: https://github.com/pganalyze/collector/blob/main/vendor/gopkg.in/mcuadros/go-syslog.v2/README.md Import the go-syslog package into your Go project to start using its functionalities. ```go import "gopkg.in/mcuadros/go-syslog.v2" ``` -------------------------------- ### Run Benchmarks with make benchmark Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/pganalyze/pg_query_go/v6/README.md Execute the benchmark suite using the provided make command. This command builds the Go project and runs the performance tests, reporting metrics such as operations per second, memory allocation, and number of allocations. ```bash $ make benchmark go build -a go test -test.bench=. -test.run=XXX -test.benchtime 10s -test.benchmem -test.cpu=4 goos: darwin goarch: arm64 pkg: github.com/pganalyze/pg_query_go/v6 BenchmarkParseSelect1-4 2874156 4186 ns/op 1040 B/op 18 allocs/op BenchmarkParseSelect2-4 824781 14572 ns/op 2832 B/op 57 allocs/op BenchmarkParseCreateTable-4 351037 34591 ns/op 8480 B/op 149 allocs/op BenchmarkParseSelect1Parallel-4 9027080 1320 ns/op 1040 B/op 18 allocs/op BenchmarkParseSelect2Parallel-4 2745390 4369 ns/op 2832 B/op 57 allocs/op BenchmarkParseCreateTableParallel-4 1000000 10487 ns/op 8480 B/op 149 allocs/op BenchmarkRawParseSelect1-4 3778771 3183 ns/op 128 B/op 3 allocs/op BenchmarkRawParseSelect2-4 1000000 10985 ns/op 288 B/op 3 allocs/op BenchmarkRawParseCreateTable-4 460714 26397 ns/op 1056 B/op 3 allocs/op BenchmarkRawParseSelect1Parallel-4 13338790 902.7 ns/op 128 B/op 3 allocs/op BenchmarkRawParseSelect2Parallel-4 4060762 2956 ns/op 288 B/op 3 allocs/op BenchmarkRawParseCreateTableParallel-4 1709883 7001 ns/op 1056 B/op 3 allocs/op BenchmarkFingerprintSelect1-4 6394882 1875 ns/op 48 B/op 2 allocs/op BenchmarkFingerprintSelect2-4 2865390 4174 ns/op 48 B/op 2 allocs/op BenchmarkFingerprintCreateTable-4 1688920 7143 ns/op 48 B/op 2 allocs/op BenchmarkNormalizeSelect1-4 10604962 1133 ns/op 32 B/op 2 allocs/op BenchmarkNormalizeSelect2-4 6226136 1938 ns/op 64 B/op 2 allocs/op BenchmarkNormalizeCreateTable-4 4542387 2635 ns/op 144 B/op 2 allocs/op PASS ok github.com/pganalyze/pg_query_go/v6 258.376s ``` -------------------------------- ### Create PostgreSQL Flexible Servers Client Factory with Custom Cloud Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/postgresql/armpostgresqlflexibleservers/v4/README.md This example shows how to create a client factory with custom `ClientOptions`, allowing connection to specific Azure clouds like Azure China. This is useful for sovereign clouds or Azure Stack deployments. ```go options := arm.ClientOptions { ClientOptions: azcore.ClientOptions { Cloud: cloud.AzureChina, }, } clientFactory, err := armpostgresqlflexibleservers.NewClientFactory(, cred, &options) ``` -------------------------------- ### Run the migration tool Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/migration.md Execute the aliasfix tool at the root of the project to automatically update import paths, followed by go mod tidy to clean up dependencies. ```bash go run cloud.google.com/go/internal/aliasfix/cmd/aliasfix@latest . go mod tidy ``` -------------------------------- ### Define Renamed Wait Events in Protobuf Source: https://github.com/pganalyze/collector/blob/main/CONTRIBUTING.md Example of defining a renamed wait event in the compact_activity_snapshot.proto file. ```protobuf WAIT_EVENT_RELATION_MAP_SYNC = 932; // RelationMapSync (renamed to RelationMapReplace) WAIT_EVENT_RELATION_MAP_REPLACE = 978; // RelationMapReplace (PG17+, renamed from RelationMapSync) ``` -------------------------------- ### Basic ANSI Colorization in Go Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/mgutz/ansi/README.md Demonstrates basic string colorization using the ansi package. For performance, consider using ColorFunc for repeated coloring. ```go import "github.com/mgutz/ansi" // colorize a string, SLOW msg := ansi.Color("foo", "red+b:white") // create a FAST closure function to avoid computation of ANSI code phosphorize := ansi.ColorFunc("green+h:black") msg = phosphorize("Bring back the 80s!") msg2 := phospohorize("Look, I'm a CRT!") // cache escape codes and build strings manually lime := ansi.ColorCode("green+h:black") reset := ansi.ColorCode("reset") fmt.Println(lime, "Bring back the 80s!", reset) ``` -------------------------------- ### Import jwt-go in Go Code Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/golang-jwt/jwt/v5/README.md Import the jwt package into your Go source files to start using its functionalities. ```go import "github.com/golang-jwt/jwt/v5" ``` -------------------------------- ### FlexibleServerClient Operations Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/postgresql/armpostgresqlflexibleservers/v4/CHANGELOG.md Details on operations available for the FlexibleServerClient, including starting LTR backups and triggering pre-backup actions. ```APIDOC ## FlexibleServerClient Operations ### Description This section covers specific operations that can be performed using the `FlexibleServerClient`. ### Operations: #### BeginStartLtrBackup ##### Description Initiates a Long-Term Retention (LTR) backup operation for a flexible server. ##### Method POST ##### Endpoint `/servers/{serverName}/startLtrBackup` (Illustrative endpoint, actual may vary) ##### Parameters ###### Path Parameters - **serverName** (string) - Required - The name of the flexible server. ###### Request Body - **LtrBackupRequest** (object) - Required - Details for the LTR backup request. - `backupName` (string) - Optional - Name of the backup. - `sourceServerName` (string) - Optional - Name of the source server. ##### Request Example ```json { "backupName": "myLtrBackup", "sourceServerName": "mySourceServer" } ``` ##### Response ###### Success Response (200 OK) - **Poller** (*runtime.Poller[FlexibleServerClientStartLtrBackupResponse]) - A poller object to track the LTR backup operation status. #### TriggerLtrPreBackup ##### Description Triggers a pre-backup action for Long-Term Retention (LTR) on a flexible server. ##### Method POST ##### Endpoint `/servers/{serverName}/triggerLtrPreBackup` (Illustrative endpoint, actual may vary) ##### Parameters ###### Path Parameters - **serverName** (string) - Required - The name of the flexible server. ###### Request Body - **LtrPreBackupRequest** (object) - Required - Details for the LTR pre-backup request. - `backupName` (string) - Optional - Name of the backup. - `sourceServerName` (string) - Optional - Name of the source server. ##### Request Example ```json { "backupName": "myLtrPreBackup", "sourceServerName": "mySourceServer" } ``` ##### Response ###### Success Response (200 OK) - **FlexibleServerClientTriggerLtrPreBackupResponse** (object) - Response object indicating the success of the pre-backup trigger. ``` -------------------------------- ### Manage ConsumerClient TCP connections Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs/migrationguide.md Demonstrates how a ConsumerClient manages a single TCP connection while creating multiple partition links. ```go // consumerClient will own a TCP connection. consumerClient, err := azeventhubs.NewConsumerClient(/* arguments elided for example */) // Close the TCP connection (and any child links) defer consumerClient.Close(context.TODO()) // this call will lazily create a set of AMQP links using the consumerClient's TCP connection. partClient0, err := consumerClient.NewPartitionClient("0", nil) defer partClient0.Close(context.TODO()) // will close the AMQP link, not the connection // this call will also lazily create a set of AMQP links using the consumerClient's TCP connection. partClient1, err := consumerClient.NewPartitionClient("1", nil) defer partClient1.Close(context.TODO()) // will close the AMQP link, not the connection ``` -------------------------------- ### Create an Editor Prompt Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/AlecAivazis/survey/v2/README.md Opens the system's default editor to capture multi-line input. ```golang prompt := &survey.Editor{ Message: "Shell code snippet", FileName: "*.sh", } survey.AskOne(prompt, &content) ``` -------------------------------- ### Monitoring Client Beta Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/CHANGES.md The monitoring client is now in beta. ```go monitoring: client is now beta ``` -------------------------------- ### Clone the project using git Source: https://github.com/pganalyze/collector/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use this command to clone the repository directly if you prefer not to use go get. ```sh git clone https://github.com/open-telemetry/opentelemetry-go ``` -------------------------------- ### Build and Test Commands Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/jackc/pgx/v5/CLAUDE.md Standard commands for running tests, formatting code, and linting the project. ```bash # Run all tests (requires PGX_TEST_DATABASE to be set) go test ./... # Run a specific test go test -run TestFunctionName ./... # Run tests for a specific package go test ./pgconn/... # Run tests with race detector go test -race ./... # DevContainer: run tests against specific PostgreSQL versions ./test.sh pg18 # Default: PostgreSQL 18 ./test.sh pg16 -run TestConnect # Specific test against PG16 ./test.sh crdb # CockroachDB ./test.sh all # All targets (pg14-18 + crdb) # Format (always run after making changes) goimports -w . # Lint golangci-lint run ./... ``` -------------------------------- ### Get Event Hub Properties with ProducerClient (New) Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs/migrationguide.md Demonstrates retrieving Event Hub properties using the ProducerClient. ```go // // or, using the ProducerClient // producerClient.GetEventHubProperties(context.TODO(), nil) ``` -------------------------------- ### Navigate to Source Directory Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/CONTRIBUTING.md Change the current working directory to the project root. ```bash cd google-cloud-go ``` -------------------------------- ### Basic Survey with Multiple Questions Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/AlecAivazis/survey/v2/README.md Demonstrates how to ask a series of questions and store the answers in a struct. Supports required fields, transformations, and type conversions. ```go package main import ( "fmt" "github.com/AlecAivazis/survey/v2" ) // the questions to ask var qs = []*survey.Question{ { Name: "name", Prompt: &survey.Input{Message: "What is your name?"}, Validate: survey.Required, Transform: survey.Title, }, { Name: "color", Prompt: &survey.Select{ Message: "Choose a color:", Options: []string{"red", "blue", "green"}, Default: "red", }, }, { Name: "age", Prompt: &survey.Input{Message: "How old are you?"}, }, } func main() { // the answers will be written to this struct answers := struct { Name string // survey will match the question and field names FavoriteColor string `survey:"color"` // or you can tag fields to match a specific name Age int // if the types don't match, survey will convert it }{} // perform the questions err := survey.Ask(qs, &answers) if err != nil { fmt.Println(err.Error()) return } fmt.Printf("%s chose %s.", answers.Name, answers.FavoriteColor) } ``` -------------------------------- ### Define Instantiation Function Source: https://github.com/pganalyze/collector/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Standard constructor signature using variadic options. ```go func NewT(options ...Option) T {…} ``` -------------------------------- ### Structured JSON Log Output Source: https://github.com/pganalyze/collector/blob/main/CHANGELOG.md Example of the structured JSON format emitted by the collector when the --json-logs option is enabled. ```json {"severity":"INFO","message":"Running collector test with pganalyze-collector ...","time":"2022-04-19T12:31:05.100489-07:00"} ``` -------------------------------- ### Authenticate with Client Certificate Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md Demonstrates using a PFX certificate file for service principal authentication. ```go import ( "os" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/adal" ) certData, err := os.ReadFile("./example.pfx") handle(err) certificate, rsaPrivateKey, err := decodePkcs12(certData, "") handle(err) oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID) handle(err) spt, err := adal.NewServicePrincipalTokenFromCertificate( *oauthConfig, clientID, certificate, rsaPrivateKey, "https://management.azure.com/", ) client := subscriptions.NewClient() client.Authorizer = autorest.NewBearerAuthorizer(spt) ``` ```go import ( "os" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions" ) certData, err := os.ReadFile("./example.pfx") handle(err) certs, key, err := azidentity.ParseCertificates(certData, nil) handle(err) cred, err = azidentity.NewClientCertificateCredential(tenantID, clientID, certs, key, nil) handle(err) client, err := armsubscriptions.NewClient(cred, nil) handle(err) ``` -------------------------------- ### Run Benchmarks with go test Source: https://github.com/pganalyze/collector/blob/main/vendor/github.com/lib/pq/TESTS.md Execute the benchmark suite using the `go test -bench .` command. This command runs all benchmarks defined in the project. ```bash go test -bench . ``` -------------------------------- ### Update Semantic Convention Imports Source: https://github.com/pganalyze/collector/blob/main/vendor/go.opentelemetry.io/otel/RELEASING.md Example of updating Go import paths to reference a newer semantic convention version. ```go // Before semconv "go.opentelemetry.io/otel/semconv/v1.37.0" "go.opentelemetry.io/otel/semconv/v1.37.0/otelconv" // After semconv "go.opentelemetry.io/otel/semconv/v1.39.0" "go.opentelemetry.io/otel/semconv/v1.39.0/otelconv" ``` -------------------------------- ### Initialize Dialer with NewDialer and Options Source: https://github.com/pganalyze/collector/blob/main/vendor/cloud.google.com/go/alloydbconn/README.md Use NewDialer to initialize the Dialer directly when you need to customize its behavior, such as specifying a credentials file. ```go ctx := context.Background() d, err := alloydbconn.NewDialer( ctx, alloydbconn.WithCredentialsFile("key.json"), ) if err != nil { log.Fatalf("unable to initialize dialer: %s", err) } conn, err := d.Dial(ctx, "projects//locations//clusters//instances/") ```