Skip to content

Instantly share code, notes, and snippets.

@andrewdoss-bit
Last active December 28, 2021 20:56
Show Gist options
  • Save andrewdoss-bit/131decb8f19d7e2333d87653a3862841 to your computer and use it in GitHub Desktop.
Save andrewdoss-bit/131decb8f19d7e2333d87653a3862841 to your computer and use it in GitHub Desktop.
pgx connection functions (with and without app name, with and without pool)
package database
import (
"context"
"fmt"
"os"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
)
const URL = "postgres://andrew:fakepassword@localhost:5432/postgres?application_name=test_name"
const URL_NONAME = "postgres://andrew:fakepassword@localhost:5432/postgres"
func ConnWithName() int {
conn, err := pgx.Connect(context.Background(), URL)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
}
defer conn.Close(context.Background())
var count int
sql := "SELECT count(*) FROM pg_stat_activity WHERE state = 'active' OR state = 'idle';"
err = conn.QueryRow(context.Background(), sql).Scan(&count)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to get count: %v\n", err)
os.Exit(1)
} else {
fmt.Fprintf(os.Stdout, "Got count %d\n", count)
}
return count
}
func ConnWithoutName() int {
conn, err := pgx.Connect(context.Background(), URL_NONAME)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
}
defer conn.Close(context.Background())
var count int
sql := "SELECT count(*) FROM pg_stat_activity WHERE state = 'active' OR state = 'idle';"
err = conn.QueryRow(context.Background(), sql).Scan(&count)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to get count: %v\n", err)
os.Exit(1)
} else {
fmt.Fprintf(os.Stdout, "Got count %d\n", count)
}
return count
}
func PoolWithName() int {
pool, err := pgxpool.Connect(context.Background(), URL)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
}
defer pool.Close()
var count int
sql := "SELECT count(*) FROM pg_stat_activity WHERE state = 'active' OR state = 'idle';"
err = pool.QueryRow(context.Background(), sql).Scan(&count)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to get count: %v\n", err)
os.Exit(1)
} else {
fmt.Fprintf(os.Stdout, "Got count %d\n", count)
}
return count
}
func PoolWithoutName() int {
pool, err := pgxpool.Connect(context.Background(), URL_NONAME)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
}
defer pool.Close()
var count int
sql := "SELECT count(*) FROM pg_stat_activity WHERE state = 'active' OR state = 'idle';"
err = pool.QueryRow(context.Background(), sql).Scan(&count)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to get count: %v\n", err)
os.Exit(1)
} else {
fmt.Fprintf(os.Stdout, "Got count %d\n", count)
}
return count
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment