### URL Connection String Example Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md An example demonstrating the URL format with user, password, host, port, database, and SSL/timeout parameters. ```text postgresql://user:password@localhost:5432/mydb?sslmode=require&connect_timeout=5 ``` -------------------------------- ### Service-Based Configuration Example Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Connects to the database using a service name defined in a service file. ```go dsn := "service=production" db, err := sql.Open("postgres", dsn) ``` -------------------------------- ### Service File Configuration Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Example of using the 'service' parameter to load configuration from a service file. ```go cfg, _ := pq.NewConfig("service=production") ``` -------------------------------- ### Key=Value Connection String Example Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md An example of the Key=Value format, including a password with spaces, demonstrating quoting and escaping. ```text host=localhost port=5432 dbname=mydb user=pquser password='with spaces' ``` -------------------------------- ### Service File Format Example Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Demonstrates the INI-like format for the ~/.pg_service.conf file. ```ini [myservice] dbname=mydb host=db.example.com port=5433 user=myuser password=mypassword [production] host=prod.example.com dbname=prod_db sslmode=verify-full ``` -------------------------------- ### Complete Bulk Insert Example with COPY Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md A full Go program demonstrating how to perform a bulk insert of user data using the COPY command. It includes transaction management and error handling. ```go package main import ( "database/sql" "fmt" "log" _ "github.com/lib/pq" ) func bulkInsert(db *sql.DB, rows [][]interface{}) error { tx, err := db.Begin() if err != nil { return err } defer tx.Rollback() stmt, err := tx.Prepare("COPY users (id, name, email) FROM STDIN") if err != nil { return err } for _, row := range rows { _, err := stmt.Exec(row...) if err != nil { return err } } // Flush and complete if _, err := stmt.Exec(); err != nil { return err } return tx.Commit() } func main() { db, _ := sql.Open("postgres", "dbname=testdb") defer db.Close() rows := [][]interface{}{ {1, "Alice", "alice@example.com"}, {2, "Bob", "bob@example.com"}, {3, "Charlie", "charlie@example.com"}, } if err := bulkInsert(db, rows); err != nil { log.Fatal(err) } fmt.Println("Bulk insert complete") } ``` -------------------------------- ### Password File Format Example Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Shows the format for the ~/.pgpass file to store passwords for automatic authentication. ```plaintext hostname:port:database:user:password localhost:5432:mydb:pquser:mysecret db.example.com:5432:*:admin:admin_password *:*:mydb:*:default_password ``` -------------------------------- ### Keyset Pagination Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md For large result sets, consider cursor-based pagination using keyset pagination. This example shows fetching the next page based on the last ID from the previous page. ```go // After getting last ID from previous page rows, _ := db.Query( "SELECT id, name FROM users WHERE id > $1 ORDER BY id LIMIT $2", lastID, pageSize, ) ``` -------------------------------- ### Running Tests with Pgpool Source: https://github.com/lib/pq/blob/master/README.md Execute tests against a pgpool instance by starting the necessary services and setting the PGPORT environment variable. ```bash docker compose up -d pgpool pg18 PGPORT=7432 go test ./... ``` -------------------------------- ### Runtime Parameters Example Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Unrecognized DSN parameters are treated as PostgreSQL runtime parameters. ```plaintext search_path=my_schema work_mem=100kB statement_timeout=30000 application_name=myapp ``` -------------------------------- ### Row Limiting and Pagination with LIMIT/OFFSET Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Use LIMIT and OFFSET clauses for basic pagination. This example demonstrates fetching a page of users. ```go const pageSize = 20 func getPage(db *sql.DB, pageNum int) ([]User, error) { offset := (pageNum - 1) * pageSize rows, _ := db.Query( "SELECT id, name FROM users ORDER BY id LIMIT $1 OFFSET $2", pageSize, offset, ) defer rows.Close() var users []User for rows.Next() { var u User rows.Scan(&u.ID, &u.Name) users = append(users, u) } return users, rows.Err() } ``` -------------------------------- ### Registering GSSAPI authentication provider Source: https://github.com/lib/pq/blob/master/README.md Provides an example of how to register a GSSAPI authentication provider for Kerberos authentication with PostgreSQL. ```go import "github.com/lib/pq/auth/kerberos" func init() { pq.RegisterGSSProvider(func() (pq.Gss, error) { return kerberos.NewGSS() }) } ``` -------------------------------- ### Int64Array Scan Example Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-arrays.md Demonstrates scanning a PostgreSQL bigint array into an Int64Array. Ensure the database query returns an array of integers. ```go var ids pq.Int64Array db.QueryRow("SELECT ARRAY[1, 2, 3, 4, 5]").Scan(pq.Array(&ids)) for _, id := range ids { fmt.Println(id) } ``` -------------------------------- ### Running Tests with Pgbouncer Source: https://github.com/lib/pq/blob/master/README.md Execute tests against a pgbouncer instance by starting the necessary services and setting the PGPORT environment variable. ```bash docker compose up -d pgbouncer pg18 PGPORT=6432 go test ./... ``` -------------------------------- ### StringArray Scan Example Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-arrays.md Shows how to scan a PostgreSQL text array into a StringArray. The database query should return an array of strings. ```go var names pq.StringArray db.QueryRow("SELECT ARRAY['Alice', 'Bob', 'Charlie']").Scan(pq.Array(&names)) for _, name := range names { fmt.Println(name) } ``` -------------------------------- ### Running Tests with Docker Compose Source: https://github.com/lib/pq/blob/master/README.md Start a PostgreSQL database using Docker Compose for running tests. Ensure your /etc/hosts file has the correct entry for 'postgres' and 'postgres-invalid'. ```bash docker compose up -d ``` -------------------------------- ### GenericArray Scan Example for Custom Types Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-arrays.md Illustrates scanning a PostgreSQL array into a GenericArray, which can then populate a custom slice. This is useful for types not explicitly supported by pq. ```go // For custom types var items GenericArray{A: &myCustomSlice} db.QueryRow("SELECT array_agg(...) FROM ...").Scan(pq.Array(&items)) ``` -------------------------------- ### Running Tests with Specific PostgreSQL Version Source: https://github.com/lib/pq/blob/master/README.md Start a specific version of PostgreSQL for testing by appending the version number to the 'pg' tag in the docker compose command. ```bash docker compose up -d pg18 ``` -------------------------------- ### Perform Bulk Inserts with COPY Source: https://github.com/lib/pq/blob/master/_autodocs/README.md Utilizes the PostgreSQL COPY FROM STDIN command for efficient bulk data insertion. This involves starting a transaction, preparing a COPY statement, executing data, and committing the transaction. ```go tx, _ := db.Begin() stmt, _ := tx.Prepare("COPY users (id, name) FROM STDIN") stmt.Exec(1, "Alice") stmt.Exec(2, "Bob") stmt.Exec() // Flush and complete tx.Commit() ``` -------------------------------- ### Get Full Error Context Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-errors.md Retrieve detailed error context, including schema, table, and column names, by using pq.As to cast the error. This provides more information than the standard error string. ```go err := db.QueryRow("SELECT invalid_col FROM users").Scan() if pqErr := pq.As(err); pqErr != nil { fmt.Println(pqErr.ErrorWithDetail()) fmt.Printf("Schema: %s, Table: %s, Column: %s\n", pqErr.Schema, pqErr.Table, pqErr.Column) } ``` -------------------------------- ### Deprecated Get Method on Error Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-errors.md The Get method on the Error type is deprecated. Access fields on pq.Error directly for retrieving error details. ```go // Deprecated: use fields on pq.Error directly func (e *Error) Get(k byte) string ``` -------------------------------- ### Using options parameter for run-time parameters Source: https://github.com/lib/pq/blob/master/README.md Shows the libpq-compatible method of specifying run-time parameters using the 'options' parameter in the connection string. ```go sql.Open("postgres", "dbname=pqgo options='-c work_mem=100kB -c search_path=xyz'") ``` -------------------------------- ### Connect to PostgreSQL using sql.Open Source: https://github.com/lib/pq/blob/master/README.md Establishes a database connection pool using the 'postgres' driver name and a connection string. Ensure to call db.Ping() to verify the connection. ```go package main import ( "database/sql" "log" _ "github.com/lib/pq" // To register the driver. ) func main() { // Or as URL: postgresql://localhost/pqgo db, err := sql.Open("postgres", "host=localhost dbname=pqgo connect_timeout=5") if err != nil { log.Fatal(err) } defer db.Close() // db.Open() only creates a connection pool, and doesn't actually establish // a connection. To ensure the connection works you need to do *something* // with a connection. err = db.Ping() if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Connect to a Database Source: https://github.com/lib/pq/blob/master/_autodocs/README.md Demonstrates how to establish a connection to a PostgreSQL database using the pq driver with the standard Go database/sql interface. ```APIDOC ## Connect to a Database ### Description Establishes a connection to a PostgreSQL database using the `database/sql` package and the `github.com/lib/pq` driver. ### Method `sql.Open` followed by `db.Close()` ### Endpoint N/A (This is an SDK usage example) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go import "database/sql" import _ "github.com/lib/pq" db, err := sql.Open("postgres", "host=localhost dbname=mydb user=postgres") defer db.Close() ``` ### Response #### Success Response A `*sql.DB` object representing the database connection. #### Response Example `db` (*sql.DB), `err` (error) ``` -------------------------------- ### Connect with Default Configuration Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Open a database connection using the default settings by providing an empty DSN. ```go db, _ := sql.Open("postgres", "") ``` -------------------------------- ### Connect to PostgreSQL using pq.Config Source: https://github.com/lib/pq/blob/master/README.md Configures a PostgreSQL connection using the pq.Config struct and then creates a connection pool. Verifies the connection with db.Ping(). ```go cfg := pq.Config{ Host: "localhost", Port: 5432, User: "pqgo", ConnectTimeout: 5 * time.Second, } // Or: create a new Config from the defaults, environment, and DSN. // cfg, err := pq.NewConfig("host=postgres dbname=pqgo") // if err != nil { // log.Fatal(err) // } c, err := pq.NewConnectorConfig(cfg) if err != nil { log.Fatal(err) } // Create connection pool. db := sql.OpenDB(c) defer db.Close() // Make sure it works. err = db.Ping() if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Notification Channel Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-notifications.md Retrieves the read-only channel used for receiving notifications. This is an alternative to directly accessing the `Notify` field. ```go notifyChan := l.NotificationChannel() // Use this instead of l.Notify if preferred ``` -------------------------------- ### SSL Connection with Certificate Verification Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Sets up an SSL-secured connection with full certificate verification. ```go dsn := "host=secure.example.com " + "sslmode=verify-full " + "sslrootcert=/etc/ssl/certs/ca.crt" db, err := sql.Open("postgres", dsn) ``` -------------------------------- ### Go LISTEN/NOTIFY Pattern with pq.Listener Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-notifications.md Demonstrates setting up a dedicated listener with reconnection backoff and handling notifications on multiple channels. Includes a periodic ping for health checks. ```go package main import ( "fmt" "log" "time" "github.com/lib/pq" ) func main() { // Create listener with 1s-1m reconnection backoff listener := pq.NewListener( "dbname=mydb", time.Second, time.Minute, func(event pq.ListenerEventType, err error) { if err != nil { log.Printf("Listener event %d: %v\n", event, err) } }, ) defer listener.Close() // Start listening on multiple channels for _, channel := range []string{"events", "alerts"} { if err := listener.Listen(channel); err != nil { log.Fatal(err) } } // Wait for notifications for { select { case notification := <-listener.Notify: if notification == nil { fmt.Println("Reconnected after disconnect") continue } fmt.Printf("[%s] %s\n", notification.Channel, notification.Extra) case <-time.After(30 * time.Second): // Periodic health check if err := listener.Ping(); err != nil { log.Fatal(err) } } } } ``` -------------------------------- ### Running Tests with Binary Parameters Source: https://github.com/lib/pq/blob/master/README.md Enable binary parameters for all connection strings during test execution by setting the PQTEST_BINARY_PARAMETERS environment variable. ```bash PQTEST_BINARY_PARAMETERS=1 go test ``` -------------------------------- ### Programmatic Configuration Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Manually configure connection parameters using the pq.Config struct and create a new connector. ```go cfg := pq.Config{ Host: "localhost", Port: 5432, User: "pquser", Password: "secret", Database: "mydb", SSLMode: pq.SSLModeDisable, ConnectTimeout: 5 * time.Second, } connector, _ := pq.NewConnectorConfig(cfg) db := sql.OpenDB(connector) ``` -------------------------------- ### Custom Array Delimiter Example Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-arrays.md Defines a custom type that implements the ArrayDelimiter interface to specify a non-default delimiter for array encoding/decoding within GenericArray operations. ```go type CustomValue string func (c CustomValue) ArrayDelimiter() string { return "|" // Use pipe instead of comma } var values []CustomValue pq.Array(&values) // Will use "|" as delimiter ``` -------------------------------- ### Handling Bytea Data with COPY Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Illustrates how to correctly pass bytea data when using the COPY command. It requires converting `[]byte` to `string` to avoid format ambiguity. ```go // For bytea columns in COPY, use string instead of []byte to avoid format ambiguity _, err := stmt.Exec("column1_value", "column2_value", string(byteaData)) ``` -------------------------------- ### Using run-time parameters in DSN Source: https://github.com/lib/pq/blob/master/README.md Demonstrates how to include PostgreSQL run-time parameters like 'work_mem' and 'search_path' directly in the connection string. ```go sql.Open("postgres", "dbname=pqgo work_mem=100kB search_path=xyz") ``` -------------------------------- ### LISTEN/NOTIFY Implementation Source: https://github.com/lib/pq/blob/master/_autodocs/README.md Set up a listener for PostgreSQL's LISTEN/NOTIFY feature to receive real-time notifications. ```go listener := pq.NewListener(dsn, time.Second, time.Minute, func(et pq.ListenerEventType, err error) { if err != nil { fmt.Println("Listener error:", err) } }, ) listener.Listen("my_channel") for n := range listener.Notify { fmt.Println("Notification:", n.Extra) } ``` -------------------------------- ### Verify Configuration Parsing Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Parse a DSN and print the extracted configuration parameters to verify correct parsing. ```go cfg, err := pq.NewConfig(dsn) if err != nil { log.Fatal(err) } fmt.Printf("Host: %s, Port: %d, DB: %s, User: %s\n", cfg.Host, cfg.Port, cfg.Database, cfg.User) ``` -------------------------------- ### Basic Connection with DSN Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Establishes a basic database connection using a DSN string. ```go dsn := "host=localhost user=pquser password=secret dbname=mydb" db, err := sql.Open("postgres", dsn) ``` -------------------------------- ### Accessing Raw Driver Connection Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Shows how to obtain a direct reference to the underlying `pq.conn` from a `sql.DB` connection for advanced manipulation. ```go import ( "database/sql" "fmt" "github.com/lib/pq" ) db, _ := sql.Open("postgres", dsn) // Get a raw connection from the pool sqlConn, err := db.Conn(ctx) if err != nil { log.Fatal(err) } deferral sqlConn.Close() // Extract the underlying driver.Conn err = sqlConn.Raw(func(driverConn interface{}) error { pqConn := driverConn.(*pq.conn) // Now you have access to the underlying connection return nil }) ``` -------------------------------- ### Use Password File (pgpass) for Authentication Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Configure pq to automatically read passwords from the `~/.pgpass` file. This enhances security by avoiding hardcoded passwords in connection strings. ```text db.example.com:5432:mydb:user:password ``` -------------------------------- ### Setting a Notice Handler Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Demonstrates how to register a callback function to handle PostgreSQL NOTICE and WARNING messages received from the server. This can be done on a raw connection or via a connector wrapper. ```go import ( "database/sql" "fmt" "github.com/lib/pq" ) // On a regular database connection sqlConn, _ := db.Conn(ctx) sqlConn.Raw(func(driverConn interface{}) error { pq.SetNoticeHandler(driverConn, func(err *pq.Error) { fmt.Printf("[%s] %s\n", err.Severity, err.Message) }) return nil }) // Or use a connector wrapper connector, _ := pq.NewConnector(dsn) wrapped := pq.ConnectorWithNoticeHandler(connector, func(err *pq.Error) { fmt.Printf("Notice: %s\n", err.Message) }) db := sql.OpenDB(wrapped) ``` -------------------------------- ### Validate Configuration with DSN Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Parse a DSN string, validate the configuration, and establish a database connection, including a ping to verify connectivity. ```go cfg, err := pq.NewConfig(dsn) if err != nil { log.Fatal("Invalid DSN:", err) } connector, err := pq.NewConnectorConfig(cfg) if err != nil { log.Fatal("Connection config error:", err) } db := sql.OpenDB(connector) if err := db.Ping(); err != nil { log.Fatal("Cannot connect:", err) } ``` -------------------------------- ### Bulk Insert with COPY Source: https://github.com/lib/pq/blob/master/_autodocs/README.md Demonstrates how to perform efficient bulk data insertion into PostgreSQL using the COPY FROM STDIN command via the `database/sql` interface. ```APIDOC ## Bulk Insert with COPY ### Description Utilizes the PostgreSQL `COPY` command for high-performance bulk data loading by streaming data directly from the application. ### Method `db.Begin()`, `tx.Prepare()`, `stmt.Exec()`, `tx.Commit()` ### Endpoint N/A (This is an SDK usage example) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go tx, _ := db.Begin() stmt, _ := tx.Prepare("COPY users (id, name) FROM STDIN") stmt.Exec(1, "Alice") stmt.Exec(2, "Bob") stmt.Exec() // Flush and complete tx.Commit() ``` ### Response #### Success Response Data is successfully copied into the specified table. #### Response Example `tx` (*sql.Tx), `stmt` (*sql.Stmt) ``` -------------------------------- ### Create Low-Level Listener Connection Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-notifications.md Creates a low-level listener connection. Use NewListener for most applications. ```go func NewListenerConn(name string, notificationChan chan<- *Notification) (*ListenerConn, error) ``` -------------------------------- ### Explicit Prepared Statements Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Use explicit preparation for full control over prepared statements. Remember to close the statement when done. ```go stmt, _ := db.Prepare("SELECT * FROM users WHERE id = $1") defer stmt.Close() err := stmt.QueryRow(1).Scan(...) err := stmt.QueryRow(2).Scan(...) ``` -------------------------------- ### Bulk Import with COPY FROM STDIN Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Demonstrates the pattern for performing bulk inserts using PostgreSQL's COPY FROM STDIN command within a transaction. Data is buffered and flushed with a final Exec() call. ```go import ( "database/sql" "fmt" "log" ) // COPY must be used inside a transaction tx, err := db.Begin() if err != nil { log.Fatal(err) } deferral tx.Rollback() // Prepare a COPY statement stmt, err := tx.Prepare("COPY table_name (col1, col2, col3) FROM STDIN") if err != nil { log.Fatal(err) } // Insert rows by calling Exec() with values // Each Exec() call is buffered internally _, err = stmt.Exec("value1", "value2", "value3") _, err = stmt.Exec("value4", "value5", "value6") // Flush the buffer and complete the COPY by calling Exec() with no arguments result, err := stmt.Exec() if err != nil { log.Fatal(err) } // Commit the transaction if err := tx.Commit(); err != nil { log.Fatal(err) } fmt.Println("Inserted rows") ``` -------------------------------- ### Enable Binary Parameter Transfer Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Configure pq to send parameters in binary format for improved performance, especially with frequently executed queries. This reduces encoding and decoding overhead. ```go cfg := pq.Config{ Host: "localhost", BinaryParameters: true, // Send parameters in binary format DisablePreparedBinaryResult: false, // OK to receive binary results } connector, _ := pq.NewConnectorConfig(cfg) db := sql.OpenDB(connector) ``` -------------------------------- ### Work with Arrays Source: https://github.com/lib/pq/blob/master/_autodocs/README.md Illustrates how to send and receive PostgreSQL array types using the `pq.Array` function and Go array types. ```APIDOC ## Work with Arrays ### Description Demonstrates the usage of `pq.Array` to marshal Go slices into PostgreSQL array types for queries and unmarshal PostgreSQL array types into Go slices. ### Method `pq.Array()` ### Endpoint N/A (This is an SDK usage example) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go var ids pq.Int64Array // Send array db.Query("SELECT * FROM users WHERE id = ANY($1)", pq.Array(&ids)) // Receive array db.QueryRow("SELECT tags FROM posts WHERE id = $1", id).Scan(pq.Array(&tags)) ``` ### Response #### Success Response Successful execution of database queries involving array parameters or results. #### Response Example `pq.Array(&ids)` (driver.Valuer), `pq.Array(&tags)` (driver.Scanner) ``` -------------------------------- ### Listen for Notifications Source: https://github.com/lib/pq/blob/master/_autodocs/README.md Explains how to use the `pq.NewListener` to subscribe to PostgreSQL's LISTEN/NOTIFY functionality and process incoming notifications. ```APIDOC ## Listen for Notifications ### Description Sets up a listener to receive asynchronous notifications from PostgreSQL channels using the `pq.NewListener` function. ### Method `pq.NewListener()`, `listener.Listen()`, `listener.Close()` ### Endpoint N/A (This is an SDK usage example) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go listener := pq.NewListener("dbname=mydb", time.Second, time.Minute, nil) defer listener.Close() listener.Listen("my_channel") for notification := range listener.Notify { fmt.Printf("Got: %s\n", notification.Extra) } ``` ### Response #### Success Response Notifications received on the listened channel are available in the `listener.Notify` channel. #### Response Example `notification` (*pq.Notification) ``` -------------------------------- ### Create Connector from Config Struct Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-config-connector.md Creates a new database/sql/driver.Connector programmatically using a `Config` struct. This method avoids DSN parsing and is useful for setting connection parameters directly. ```go cfg := pq.Config{ Host: "localhost", Port: 5432, User: "pqgo", Database: "pqgo", SSLMode: pq.SSLModeDisable, } connector, err := pq.NewConnectorConfig(cfg) if err != nil { log.Fatal(err) } db := sql.OpenDB(connector) ``` -------------------------------- ### Basic Connection String Source: https://github.com/lib/pq/blob/master/_autodocs/README.md A simple connection string for establishing a connection to a PostgreSQL database. ```sql host=localhost dbname=mydb user=postgres ``` -------------------------------- ### Connect to a PostgreSQL Database Source: https://github.com/lib/pq/blob/master/_autodocs/README.md Opens a connection to a PostgreSQL database using a connection string. Ensure the database name, user, and host are correctly specified. The connection should be closed when no longer needed. ```go import "database/sql" import _ "github.com/lib/pq" db, err := sql.Open("postgres", "host=localhost dbname=mydb user=postgres") deffer db.Close() ``` -------------------------------- ### Connection String with SSL Enabled Source: https://github.com/lib/pq/blob/master/_autodocs/README.md Establish a secure connection using SSL, specifying verification mode and root certificate path. ```sql sslmode=verify-full sslrootcert=/etc/ssl/certs/ca.crt ``` -------------------------------- ### Create a New Listener with a Custom Dialer Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-notifications.md Initializes a new Listener using a custom Dialer for network I/O, alongside connection parameters and an optional event callback. ```go l := pq.NewDialListener(d, "dbname=pqgo", time.Second, time.Minute, func(ev pq.ListenerEventType, err error) { if err != nil { fmt.Printf("Listener error: %v\n", err) } else { fmt.Println("Listener event:", ev) } }) ``` -------------------------------- ### Catching Specific PostgreSQL Errors in Go Source: https://github.com/lib/pq/blob/master/_autodocs/errors.md Demonstrates how to use pq.As to check for specific error types like UniqueViolation and ForeignKeyViolation. Ensure you import the necessary packages. ```go import ( "database/sql" "github.com/lib/pq" "github.com/lib/pq/pqerror" ) result, err := db.Exec( "INSERT INTO users(email) VALUES($1)", "test@example.com", ) if pqErr := pq.As(err, pqerror.UniqueViolation); pqErr != nil { // Email already exists fmt.Printf("User already exists: %s\n", pqErr.Detail) return fmt.Errorf("duplicate email: %s", pqErr.Message) } if pqErr := pq.As(err, pqerror.ForeignKeyViolation); pqErr != nil { // Invalid foreign key return fmt.Errorf("invalid reference: %s", pqErr.Message) } if err != nil { return err } ``` -------------------------------- ### Send and Receive PostgreSQL Arrays Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-arrays.md Demonstrates sending Go slices as PostgreSQL arrays and receiving PostgreSQL arrays into Go slices using pq.Array. Ensure the 'github.com/lib/pq' package is imported. ```go package main import ( "database/sql" "fmt" "log" _ "github.com/lib/pq" "github.com/lib/pq" ) func main() { db, err := sql.Open("postgres", "dbname=testdb") if err != nil { log.Fatal(err) } defer db.Close() // Sending arrays to PostgreSQL userIDs := pq.Int64Array{1, 2, 3, 4, 5} tags := pq.StringArray{"golang", "database", "sql"} _, err = db.Exec( "INSERT INTO articles(user_ids, tags) VALUES($1, $2)", pq.Array(&userIDs), pq.Array(&tags), ) if err != nil { log.Fatal(err) } // Receiving arrays from PostgreSQL var receivedUserIDs pq.Int64Array var receivedTags pq.StringArray row := db.QueryRow("SELECT user_ids, tags FROM articles LIMIT 1") err = row.Scan(pq.Array(&receivedUserIDs), pq.Array(&receivedTags)) if err != nil { log.Fatal(err) } fmt.Println("User IDs:", receivedUserIDs) fmt.Println("Tags:", receivedTags) } ``` -------------------------------- ### Open Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-utilities.md Opens a connection using the default dialer. Used by `database/sql` internally. ```APIDOC ## Open ### Description Opens a connection using the default dialer. Used by `database/sql` internally. ### Function Signature ```go func Open(dsn string) (_ driver.Conn, err error) ``` ### Parameters #### Path Parameters - **dsn** (string) - Required - Connection string ### Return Type `driver.Conn` - New connection. ``` -------------------------------- ### Listen for PostgreSQL Notifications Source: https://github.com/lib/pq/blob/master/_autodocs/README.md Sets up a listener to receive notifications from PostgreSQL channels using LISTEN/NOTIFY. The listener requires connection details and timeout configurations. Notifications are received from the `Notify` channel. ```go listener := pq.NewListener("dbname=mydb", time.Second, time.Minute, nil) deffer listener.Close() listener.Listen("my_channel") for notification := range listener.Notify { fmt.Printf("Got: %s\n", notification.Extra) } ``` -------------------------------- ### Bulk Imports with COPY FROM STDIN Source: https://github.com/lib/pq/blob/master/README.md Perform bulk imports by preparing a COPY FROM STDIN statement within a transaction. The returned sql.Stmt can be executed repeatedly to copy data. Call Exec() with no arguments to flush buffered data after all data has been processed. ```go l := pq.NewListener("dbname=pqgo", time.Second, time.Minute, nil) defer l.Close() err := l.Listen("coconut") if err != nil { log.Fatal(err) } for { n := <-l.Notify if n == nil { fmt.Println("nil notify: closing Listener") return } fmt.Printf("notification on %q with data %q\n", n.Channel, n.Extra) } ``` -------------------------------- ### Enable Infinity Timestamps Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Enable support for PostgreSQL's 'infinity' timestamp values by calling pq.EnableInfinityTs once at application startup. This maps PostgreSQL infinity values to specific time.Time values. ```go import ( "time" "github.com/lib/pq" ) pq.EnableInfinityTs( time.Date(1000, 1, 1, 0, 0, 0, 0, time.UTC), // -infinity time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC), // infinity ) var expireTime time.Time db.QueryRow("SELECT TIMESTAMP 'infinity'").Scan(&expireTime) // expireTime is now time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC) ``` -------------------------------- ### Enable Debug Output Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Enable protocol debug output for the Go PostgreSQL driver by setting the PQGO_DEBUG environment variable. ```bash PQGO_DEBUG=1 go run myapp.go ``` -------------------------------- ### Multi-host Connection String with Failover Source: https://github.com/lib/pq/blob/master/_autodocs/README.md Configure multiple hosts for failover and specify load balancing and session attribute preferences. ```sql host=primary,replica load_balance_hosts=random target_session_attrs=prefer-standby ``` -------------------------------- ### Multi-Host Connection with Failover and Load Balancing Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Configures a connection to multiple hosts, enabling failover and random load balancing. ```go dsn := "host=primary.example.com,replica1.example.com,replica2.example.com " + "target_session_attrs=prefer-standby " + "load_balance_hosts=random" db, err := sql.Open("postgres", dsn) ``` -------------------------------- ### Configure Multi-Host Connections for Failover Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Connect to multiple PostgreSQL servers for high availability and load balancing. The driver automatically attempts failover to the next host if a connection fails. ```go // Comma-separated host list with matching ports dsn := "host=primary,replica1,replica2 port=5432,5432,5433 " + "target_session_attrs=prefer-standby " + "load_balance_hosts=random" db, _ := sql.Open("postgres", dsn) ``` -------------------------------- ### Create and Use a New Listener Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-notifications.md Creates a new Listener, registers for notifications on a channel, and processes incoming notifications. Ensure to close the listener when done. ```go l := pq.NewListener("dbname=pqgo", time.Second, time.Minute, func(ev pq.ListenerEventType, err error) { if err != nil { fmt.Printf("Listener error: %v\n", err) } else { fmt.Println("Listener event:", ev) } }) defer l.Close() err := l.Listen("myChannel") if err != nil { log.Fatal(err) } for n := range l.Notify { if n == nil { fmt.Println("Connection re-established") continue } fmt.Printf("Got notification: %q from PID %d: %q\n", n.Channel, n.BePid, n.Extra) } ``` -------------------------------- ### URL Format Connection Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Connects to the database using a URL-formatted DSN string. ```go dsn := "postgresql://pquser:secret@localhost/mydb" db, err := sql.Open("postgres", dsn) ``` -------------------------------- ### Create Connector from DSN Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-config-connector.md Creates a new database/sql/driver.Connector from a DSN string. This connector can then be used with `sql.OpenDB` to establish a database connection. ```go package main import ( "database/sql" "log" "github.com/lib/pq" ) func main() { connector, err := pq.NewConnector("user=pqgo dbname=pqgo host=localhost") if err != nil { log.Fatal(err) } db := sql.OpenDB(connector) defer db.Close() } ``` -------------------------------- ### Work with PostgreSQL Array Types Source: https://github.com/lib/pq/blob/master/_autodocs/README.md Demonstrates sending and receiving PostgreSQL arrays using the pq driver. The `pq.Array()` function is used to scan and query array data types. ```go var ids pq.Int64Array // Send array db.Query("SELECT * FROM users WHERE id = ANY($1)", pq.Array(&ids)) // Receive array db.QueryRow("SELECT tags FROM posts WHERE id = $1", id).Scan(pq.Array(&tags)) ``` -------------------------------- ### COPY Statement Formats Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Shows the basic syntax for the PostgreSQL COPY FROM STDIN command, specifying columns or using all columns. ```sql COPY table_name (column1, column2, ...) FROM STDIN ``` ```sql COPY table_name FROM STDIN ``` -------------------------------- ### URL Format Connection String Source: https://github.com/lib/pq/blob/master/_autodocs/README.md Connect to a PostgreSQL database using a URL formatted string. ```sql postgresql://postgres:password@localhost/mydb ``` -------------------------------- ### Connect using PostgreSQL Service File Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Utilize PostgreSQL's service file (`~/.pg_service.conf`) to manage connection profiles. This centralizes connection parameters, simplifying connection strings. ```ini [production] dbname=prod_db host=prod.example.com port=5432 user=prod_user sslmode=require [development] dbname=dev_db host=localhost port=5432 user=dev_user sslmode=disable ``` ```go // Uses [production] section from service file db, _ := sql.Open("postgres", "service=production") ``` -------------------------------- ### RegisterTLSConfig Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-utilities.md Registers a custom TLS configuration for use with `sslmode=pqgo-«key»` in connection strings, allowing customization of SSL/TLS behavior. ```APIDOC ## RegisterTLSConfig ### Description Registers a custom TLS configuration for use with `sslmode=pqgo-«key»` in connection strings. This allows customizing SSL/TLS behavior beyond the standard config options. ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters - **key** (string) - Yes - Key name (with or without `pqgo-` prefix) - **config** (*tls.Config) - No - TLS configuration, or nil to unregister ### Return Type `error` - Always nil (no validation performed). ### Usage ```go // Register custom TLS config customTLSConfig := &tls.Config{ Certificates: []tls.Certificate{clientCert}, MinVersion: tls.VersionTLS12, // ... other settings } pq.RegisterTLSConfig("mycert", customTLSConfig) // Use in connection string dsn := "host=db.example.com sslmode=pqgo-mycert" db, err := sql.Open("postgres", dsn) // Unregister pq.RegisterTLSConfig("mycert", nil) ``` ``` -------------------------------- ### NewListenerConn Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-notifications.md Creates a low-level listener connection. Use NewListener for most applications. ```APIDOC ## NewListenerConn ### Description Creates a low-level listener connection. Use `NewListener` for most applications. ### Method *Not specified, likely a function call* ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **name** (string) - Required - Connection string - **notificationChan** (chan<- *Notification) - Required - Channel to receive notifications on ### Return Type - **`*ListenerConn`** - Low-level listener or error. ``` -------------------------------- ### Register Custom TLS Configuration Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-utilities.md Registers a custom TLS configuration for use with 'sslmode=pqgo-«key»'. Allows customization of SSL/TLS behavior. Can also be used to unregister a configuration. ```go func RegisterTLSConfig(key string, config *tls.Config) error ``` ```go // Register custom TLS config customTLSConfig := &tls.Config{ Certificates: []tls.Certificate{clientCert}, MinVersion: tls.VersionTLS12, // ... other settings } pq.RegisterTLSConfig("mycert", customTLSConfig) // Use in connection string dsN := "host=db.example.com sslmode=pqgo-mycert" db, err := sql.Open("postgres", dsn) // Unregister pq.RegisterTLSConfig("mycert", nil) ``` -------------------------------- ### Typed Array Operations Source: https://github.com/lib/pq/blob/master/_autodocs/README.md Demonstrates sending and receiving typed arrays to/from PostgreSQL using pq. ```go var ids pq.Int64Array var tags pq.StringArray var flags pq.BoolArray // Send to PostgreSQL db.Query("WHERE id = ANY($1)", pq.Array(&ids)) // Receive from PostgreSQL db.QueryRow("SELECT ...").Scan(pq.Array(&tags)) ``` -------------------------------- ### Configure Connection Pooling Source: https://github.com/lib/pq/blob/master/_autodocs/configuration.md Set parameters for the database connection pool, including maximum open connections, idle connections, and connection lifetime. ```go db.SetMaxOpenConns(25) // Max simultaneous connections db.SetMaxIdleConns(5) // Max idle connections in pool db.SetConnMaxLifetime(5 * time.Minute) // Connection max lifetime ``` -------------------------------- ### Register Custom TLS Configuration Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Provide custom TLS configurations for advanced SSL/TLS scenarios, such as using specific client certificates or custom Certificate Authority (CA) bundles. Register the configuration with a unique name to use it in the connection string. ```go import ( "crypto/tls" "crypto/x509" "io/ioutil" "github.com/lib/pq" ) // Load client certificate cert, err := tls.LoadX509KeyPair("client.crt", "client.key") if err != nil { log.Fatal(err) } // Load CA certificate caCert, _ := ioutil.ReadFile("ca.crt") caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert) // Create custom TLS config tlsConfig := &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: caCertPool, MinVersion: tls.VersionTLS12, } // Register it pq.RegisterTLSConfig("production", tlsConfig) // Use in connection string db, _ := sql.Open("postgres", "host=db.example.com sslmode=pqgo-production") ``` -------------------------------- ### Register GSSAPI Provider for Kerberos Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Enable Kerberos/GSSAPI authentication by registering a GSS provider. This allows connections to servers configured for GSSAPI authentication. ```go import ( "github.com/lib/pq" "github.com/lib/pq/auth/kerberos" ) func init() { pq.RegisterGSSProvider(func() (pq.Gss, error) { return kerberos.NewGSS() }) } // Now connections with require_auth=gss will work dsn := "host=kerb-db.example.com require_auth=gss" db, _ := sql.Open("postgres", dsn) ``` -------------------------------- ### NewConfig Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-config-connector.md Parses a connection string (DSN) and returns a `Config` struct. This function merges defaults, environment variables, service file settings, and DSN parameters. ```APIDOC ## NewConfig ### Description Parses a connection string and returns a configuration struct. Merges defaults, environment variables, service file settings, and DSN parameters in that order. ### Method `NewConfig(dsn string) (Config, error)` ### Parameters #### Path Parameters - **dsn** (string) - Required - Connection string in key=value or postgres:// URL format ### Return Type - `Config` - Parsed connection configuration. - `error` - If DSN is malformed. ``` -------------------------------- ### Set Notice Handler Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-utilities.md Sets a synchronous notice handler on a connection. Use this to process informational messages from the database. ```go func SetNoticeHandler(c driver.Conn, handler func(*Error)) ``` ```go pq.SetNoticeHandler(conn, func(err *pq.Error) { fmt.Printf("Notice [%s]: %s\n", err.Code, err.Message) }) ``` -------------------------------- ### Configure Connection Connect Timeout Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Set a specific timeout duration for establishing an initial connection to the PostgreSQL server. This prevents applications from hanging indefinitely during connection attempts. ```go cfg := pq.Config{ Host: "localhost", ConnectTimeout: 5 * time.Second, } ``` -------------------------------- ### Build COPY FROM STDIN Statement Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-utilities.md Builds a COPY FROM STDIN statement string for use with Tx.Prepare(). This function is deprecated; build COPY statements directly as strings. ```go func CopyIn(table string, columns ...string) string ``` ```go func CopyInSchema(schema, table string, columns ...string) string ``` -------------------------------- ### Target Standby Replicas for Read Operations Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Configure connections to prioritize targeting standby replicas for read operations. The driver will attempt to connect to standbys first and fall back to the primary if none are available. ```go dsn := "host=primary,replica1,replica2 " + "target_session_attrs=prefer-standby" // Will try replicas first, fall back to primary if no standbys available db, _ := sql.Open("postgres", dsn) ``` -------------------------------- ### ConfigMultihost Structure Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-config-connector.md Defines an additional server for connection failover in multi-host scenarios. Use this to specify fallback hosts for your PostgreSQL connection. ```go type ConfigMultihost struct { Host string Hostaddr netip.Addr Port uint16 } ``` -------------------------------- ### Automatic Prepared Statements Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md pq automatically uses prepared statements for repeated queries. The database/sql package manages a statement cache per connection. ```go // First execution: query is prepared err = db.QueryRow("SELECT * FROM users WHERE id = $1", 1).Scan(...) // Second execution: uses prepared statement err = db.QueryRow("SELECT * FROM users WHERE id = $1", 2).Scan(...) ``` -------------------------------- ### Wrap Slices and Arrays with pq.Array Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-arrays.md Use `pq.Array` to wrap slices or multi-dimensional arrays for sending to PostgreSQL and scanning results back. It returns a wrapper implementing `driver.Valuer` and `sql.Scanner`. ```go var ids = []int64{1, 2, 3} db.Query("SELECT * FROM users WHERE id = ANY($1)", pq.Array(ids)) ``` ```go var tags []string db.QueryRow("SELECT tags FROM articles WHERE id = $1", articleID).Scan(pq.Array(&tags)) ``` ```go var optionalTags *[]string db.QueryRow("SELECT tags FROM articles WHERE id = $1", articleID).Scan(pq.Array(&optionalTags)) ``` -------------------------------- ### Enable Infinity Timestamp Support Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-utilities.md Enables support for PostgreSQL's 'infinity' and '-infinity' timestamp values. Must be called once before parsing or formatting infinity timestamps. ```go func EnableInfinityTs(negative time.Time, positive time.Time) ``` ```go // At application startup pq.EnableInfinityTs( time.Date(1000, 1, 1, 0, 0, 0, 0, time.UTC), // -infinity time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC), // infinity ) // Now you can scan infinity values var expireTime time.Time db.QueryRow("SELECT TIMESTAMP 'infinity'").Scan(&expireTime) if expireTime.Equal(time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)) { fmt.Println("Never expires") } ``` -------------------------------- ### NewListener Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-notifications.md Creates a new Listener connected to a PostgreSQL database. It manages the connection and handles reconnections with exponential backoff. ```APIDOC ## NewListener ### Description Creates a new Listener connected to a PostgreSQL database. ### Method `func NewListener(dsn string, minReconnect time.Duration, maxReconnect time.Duration, cb EventCallbackType) *Listener` ### Parameters #### Path Parameters - **dsn** (string) - Required - Connection string (same format as for `sql.Open`) - **minReconnect** (time.Duration) - Required - Minimum interval before reconnection attempts (e.g., 1*time.Second) - **maxReconnect** (time.Duration) - Required - Maximum interval between reconnection attempts (e.g., 1*time.Minute) - **cb** (EventCallbackType) - Optional - Optional callback for connection state changes (nil for no callback) ### Return Type `*Listener` - Ready to use for LISTEN/NOTIFY. ``` -------------------------------- ### Wrap Connector with Notice Handler Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-utilities.md Wraps a connector to set a notice handler on all connections it creates. This is useful for applying a consistent notice handling strategy across multiple connections. ```go func ConnectorWithNoticeHandler(c driver.Connector, handler func(*Error)) *NoticeHandlerConnector ``` ```go connector, _ := pq.NewConnector(dsn) wrapped := pq.ConnectorWithNoticeHandler(connector, func(err *pq.Error) { log.Printf("DB Notice: %s", err.Message) }) db := sql.OpenDB(wrapped) ``` -------------------------------- ### ListenerConn Structure Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-notifications.md Low-level interface for waiting on notifications. Most users should use Listener instead. ```go type ListenerConn struct { // ... unexported fields ... } ``` -------------------------------- ### Set Max Open Connections Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-advanced.md Configure the maximum number of open connections in the connection pool. Adjust this based on your database's max_connections setting. ```go db.SetMaxOpenConns(25) // Adjust based on your database's max_connections ``` -------------------------------- ### Error.ErrorWithDetail() Method Source: https://github.com/lib/pq/blob/master/_autodocs/api-reference-errors.md Generates a detailed, multi-line error message with all available diagnostic information, including detail, hint, and context. Ideal for logging and debugging. ```go func (e *Error) ErrorWithDetail() string ``` ```go err := db.QueryRow("SELECT 'invalid'::json").Scan() if err != nil { fmt.Println(err.(*pq.Error).ErrorWithDetail()) } ``` -------------------------------- ### Driver Struct Source: https://github.com/lib/pq/blob/master/_autodocs/types.md Defines the main PostgreSQL driver struct. Implements the database/sql/driver.Driver interface. ```go type Driver struct{} ```