### Example Setup and Execution Workflow Source: https://pkg.go.dev/github.com/jackc/pgx/v5/examples/todo A comprehensive sequence of commands demonstrating the entire setup and operational flow of the todo application, from database creation to task management. ```bash jack@hk-47~/dev/go/src/github.com/jackc/pgx/examples/todo$ createdb todo jack@hk-47~/dev/go/src/github.com/jackc/pgx/examples/todo$ psql todo < structure.sql Expanded display is used automatically. Timing is on. CREATE TABLE Time: 6.363 ms jack@hk-47~/dev/go/src/github.com/jackc/pgx/examples/todo$ go build jack@hk-47~/dev/go/src/github.com/jackc/pgx/examples/todo$ export PGDATABASE=todo jack@hk-47~/dev/go/src/github.com/jackc/pgx/examples/todo$ ./todo list jack@hk-47~/dev/go/src/github.com/jackc/pgx/examples/todo$ ./todo add 'Learn Go' jack@hk-47~/dev/go/src/github.com/jackc/pgx/examples/todo$ ./todo list 1. Learn Go jack@hk-47~/dev/go/src/github.com/jackc/pgx/examples/todo$ ./todo update 1 'Learn more Go' jack@hk-47~/dev/go/src/github.com/jackc/pgx/examples/todo$ ./todo list 1. Learn more Go jack@hk-47~/dev/go/src/github.com/jackc/pgx/examples/todo$ ./todo remove 1 jack@hk-47~/dev/go/src/github.com/jackc/pgx/examples/todo$ ./todo list ``` -------------------------------- ### Install pgfortune Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgproto3/example/pgfortune Install the pgfortune tool using go get. Ensure you have Go installed and configured. ```bash go get -u github.com/jackc/pgproto3/example/pgfortune ``` -------------------------------- ### PostgreSQL Connection String Examples Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Examples of connection strings for single and multiple host configurations. ```text postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca ``` ```text postgres://jack:secret@foo.example.com:5432,bar.example.com:5432/mydb ``` -------------------------------- ### ForEachRow Example Output Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Example output for the ForEachRow function. ```text Output: 1, 2 2, 4 3, 6 ``` -------------------------------- ### Example Output: Json Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype This example illustrates the output when scanning JSON data into Go types. ```text Output: John 42 ``` -------------------------------- ### Start a Transaction with Options on a Connection Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool BeginTx starts a transaction block from a *Conn with txOptions determining the transaction mode. This allows for fine-grained control over transaction behavior. ```go func (c *Conn) BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error) ``` -------------------------------- ### Start and Manage a Transaction in Go Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Use Conn.Begin to start a transaction. Defer tx.Rollback to ensure it's rolled back if an error occurs. Commit the transaction explicitly on success. ```go tx, err := conn.Begin(context.Background()) if err != nil { return err } // Rollback is safe to call even if the tx is already closed, so if // the tx commits successfully, this is a no-op deferr tx.Rollback(context.Background()) _, err = tx.Exec(context.Background(), "insert into foo(id) values (1)") if err != nil { return err } err = tx.Commit(context.Background()) if err != nil { return err } ``` -------------------------------- ### Example Output: CustomType Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype This example shows the output for a custom type, potentially involving null values and specific formatting. ```text Output: null point 1.5, 2.5 ``` -------------------------------- ### Example Output: ChildRecords Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype This example demonstrates a single query returning parent and child records, showing hierarchical data. ```text Output: Alpha Adam: wing Bill: halfback Charlie: fullback Beta Don: halfback Edgar: halfback Frank: fullback ``` -------------------------------- ### Start a Transaction from the Pool Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool Begin acquires a connection from the Pool and starts a transaction. The context only affects the begin command. The returned Tx must have Commit or Rollback called. ```go func (p *Pool) Begin(ctx context.Context) (pgx.Tx, error) ``` -------------------------------- ### CollectRows Example Usage Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Example demonstrating the usage of CollectRows with a manually written collector function. ```text Output: [1 2 3 4 5] ``` -------------------------------- ### POST /Pool/BeginTx Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool Acquires a connection from the pool and starts a transaction. ```APIDOC ## POST /Pool/BeginTx ### Description Acquires a connection from the Pool and starts a transaction with pgx.TxOptions determining the transaction mode. ### Method POST ### Parameters #### Request Body - **ctx** (context.Context) - Required - The context for the begin command. - **txOptions** (pgx.TxOptions) - Required - Options determining the transaction mode. ### Response #### Success Response (200) - **tx** (pgx.Tx) - The started transaction object. - **error** (error) - Error if the transaction could not be started. ``` -------------------------------- ### Example Usage: Connecting and Executing a Query Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Demonstrates how to establish a connection using `pgconn.Connect` and execute a query with parameters using `pgConn.ExecParams`. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address for the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201 Created) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Conn.Begin Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Starts a transaction. The context only affects the begin command and does not provide auto-rollback on cancellation. ```APIDOC ## Begin ### Description Starts a transaction. Unlike database/sql, the context only affects the begin command; i.e., there is no auto-rollback on context cancellation. ### Method ```go func (c *Conn) Begin(ctx context.Context) (Tx, error) ``` ### Parameters - **ctx** (context.Context): The context for the begin transaction command. ``` -------------------------------- ### Start a Transaction on a Connection Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool Begin starts a transaction block from a *Conn without explicitly setting a transaction mode. Use BeginTx for specific transaction modes. ```go func (c *Conn) Begin(ctx context.Context) (pgx.Tx, error) ``` -------------------------------- ### RowToAddrOf Example Output Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Example output for the RowToAddrOf function. ```text Output: 1 2 3 4 5 ``` -------------------------------- ### Define TraceConnectStartData Structure Source: https://pkg.go.dev/github.com/jackc/pgx/v5 TraceConnectStartData holds configuration information at the start of a connection attempt. ```go type TraceConnectStartData struct { ConnConfig *ConnConfig } ``` -------------------------------- ### Begin Transaction Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Starts a new transaction. The context provided only affects the BEGIN command; it does not trigger an auto-rollback on cancellation. ```go func (c *Conn) Begin(ctx context.Context) (Tx, error) ``` -------------------------------- ### Conn.BeginTx Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Starts a transaction with specified transaction options. The context only affects the begin command. ```APIDOC ## BeginTx ### Description Starts a transaction with txOptions determining the transaction mode. Unlike database/sql, the context only affects the begin command; i.e., there is no auto-rollback on context cancellation. ### Method ```go func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) ``` ### Parameters - **ctx** (context.Context): The context for the begin transaction command. - **txOptions** (TxOptions): Specifies the transaction mode. ``` -------------------------------- ### Trace for Frontend Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgproto3 Starts tracing message traffic to a specified writer. Writes in a format similar to libpq's PQtrace. ```go func (f *Frontend) Trace(w io.Writer, options TracerOptions) ``` -------------------------------- ### BeginTx Transaction with Options Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Starts a transaction with specified transaction modes defined by TxOptions. Similar to Begin, the context only impacts the BEGIN command. ```go func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) ``` -------------------------------- ### Run pgfortune Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgproto3/example/pgfortune Execute the pgfortune command to start the mock PostgreSQL server. By default, it listens on 127.0.0.1:15432. ```bash $ pgfortune ``` -------------------------------- ### Get Connection Configuration Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Retrieves a copy of the configuration used to establish the current connection. ```go func (c *Conn) Config() *ConnConfig ``` -------------------------------- ### TraceQueryStartData Struct Definition Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Defines the data structure for tracing the start of a query operation. ```go type TraceQueryStartData struct { SQL string Args []any } ``` -------------------------------- ### Example Query Output Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn This snippet shows a sequence of operations that result in the output '1', '2', '3', and 'SELECT 3'. It implies a series of commands executed in sequence. ```sql 1 2 3 SELECT 3 ``` -------------------------------- ### Listen for PostgreSQL Notifications in Go Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Use Conn.Exec to start listening on a channel and Conn.WaitForNotification to block until a notification is received or the context is canceled. ```go _ := conn.Exec(context.Background(), "listen channelname") if err != nil { return err } notification, err := conn.WaitForNotification(context.Background()) if err != nil { return err } // do something with notification ``` -------------------------------- ### Trace: Start Message Traffic Tracing Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgproto3 Initiates tracing of message traffic to a specified io.Writer. The output format is similar to libpq's PQtrace function. ```go func (b *Backend) Trace(w io.Writer, options TracerOptions) ``` -------------------------------- ### Get pgx Connection String Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Returns the connection string representation of a ConnConfig object. ```go func (cc *ConnConfig) ConnString() string ``` -------------------------------- ### Trace pgx Connection Events Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Interface for tracing the start and end of database connection attempts. The returned context from TraceConnectStart is used throughout the connection process. ```go type ConnectTracer interface { // TraceConnectStart is called at the beginning of Connect and ConnectConfig calls. The returned context is used for // the rest of the call and will be passed to TraceConnectEnd. TraceConnectStart(ctx context.Context, data TraceConnectStartData) context.Context TraceConnectEnd(ctx context.Context, data TraceConnectEndData) } ``` -------------------------------- ### psql interaction with pgfortune Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgproto3/example/pgfortune Example of a psql session interacting with pgfortune, showing a query and the fortune response. ```text Timing is on. Null display is "∅". Line style is unicode. psql (11.5, server 0.0.0) Type "help" for help. jack@127.0.0.1:15432 jack=# select foo; fortune _________________________________________ / Ships are safe in harbor, but they were \ / never meant to stay there. / ----------------------------------------- \ /\ ___ /\ \ // \/ \/ \\ (( O O )) \\ / \ // \/ | | \/ | | | | | | | | | o | | | | | |m| |m| (1 row) Time: 28.161 ms ``` -------------------------------- ### Implement TryWrapBuiltinTypeEncodePlan Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Tries to wrap a builtin type with a wrapper that provides additional methods. For example, if the value was of type int32, a wrapper plan would be returned that converts the value to a type implementing Int64Valuer. ```go func TryWrapBuiltinTypeEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) ``` -------------------------------- ### Connect and Execute Query with pgconn Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Demonstrates establishing a connection using a DATABASE_URL environment variable and executing a parameterized query. Ensure the DATABASE_URL is set before running. Errors during connection or query execution will cause the program to exit. ```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) } ``` -------------------------------- ### Connect to PostgreSQL Database with Options Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Establishes a new connection to a PostgreSQL database using a connection string and specific parsing options. Useful for advanced connection configurations. ```go func ConnectWithOptions(ctx context.Context, connString string, parseConfigOptions ParseConfigOptions) (*PgConn, error) ``` -------------------------------- ### Get Statement Description from LRUCache - stmtcache Source: https://pkg.go.dev/github.com/jackc/pgx/v5/internal/stmtcache The Get method retrieves a statement description from the LRUCache using its SQL string as the key. It returns nil if the statement is not found in the cache. ```go func (c *LRUCache) Get(key string) *pgconn.StatementDescription ``` -------------------------------- ### Establishing a Connection Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Demonstrates how to establish a connection to a PostgreSQL database using pgx.Connect. ```APIDOC ## Establishing a Connection The primary way of establishing a connection is with `pgx.Connect`: ```go conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) ``` The database connection string can be in URL or key/value format. Both PostgreSQL settings and pgx settings can be specified here. In addition, a config struct can be created by `ParseConfig` and modified before establishing the connection with `ConnectConfig` to configure settings such as tracing that cannot be configured with a connection string. ``` -------------------------------- ### GET /Pool/Query Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool Executes a query and returns rows. ```APIDOC ## GET /Pool/Query ### Description Acquires a connection and executes a query that returns pgx.Rows. ### Method GET ### Parameters #### Request Body - **ctx** (context.Context) - Required - The context for the operation. - **sql** (string) - Required - The SQL query string. - **args** (...any) - Optional - Positional arguments for the query. ### Response #### Success Response (200) - **rows** (pgx.Rows) - The result set. - **error** (error) - Error if the query fails. ``` -------------------------------- ### Connect to PostgreSQL and Query Data Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Demonstrates connecting to a PostgreSQL database using a connection URL and executing a query to retrieve data. Ensure the DATABASE_URL environment variable is set. ```go package main import ( "context" "fmt" "os" "github.com/jackc/pgx/v5" ) func main() { // urlExample := "postgres://username:password@localhost:5432/database_name" conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_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 name string var weight int64 err = conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight) if err != nil { fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err) os.Exit(1) } fmt.Println(name, weight) } ``` -------------------------------- ### Get Error from CompositeTextScanner Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Retrieves any error encountered by the CompositeTextScanner. ```go func (cfs *CompositeTextScanner) Err() error ``` -------------------------------- ### GET /Pool/Stat/AcquireCount Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool Returns the cumulative count of successful acquires from the pool. ```APIDOC ## GET /Pool/Stat/AcquireCount ### Description Returns the cumulative count of successful acquires from the pool. ### Method GET ### Response #### Success Response (200) - **count** (int64) - The cumulative count of successful acquires. ``` -------------------------------- ### Conn.ConnectWithOptions Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Establishes a connection with a PostgreSQL server using a connection string and additional options. ```APIDOC ## ConnectWithOptions ### Description Behaves exactly like Connect with the addition of options. At the present, options are only used to provide a pgconn.GetSSLPasswordFunc function. ### Method ```go func ConnectWithOptions(ctx context.Context, connString string, options ParseConfigOptions) (*Conn, error) ``` ### Parameters - **ctx** (context.Context): The context for the connection attempt. - **connString** (string): The PostgreSQL connection string. - **options** (ParseConfigOptions): Options for parsing the configuration. ``` -------------------------------- ### func Get Source: https://pkg.go.dev/github.com/jackc/pgx/v5/internal/iobufpool Retrieves a byte slice from the pool with a specified size. ```APIDOC ## func Get(size int) *[]byte ### Description Get retrieves a []byte of length size with capacity less than or equal to size*2 from the pool. ### Parameters #### Arguments - **size** (int) - Required - The desired length of the byte slice. ### Response - **Returns** (*[]byte) - A pointer to a byte slice from the pool. ``` -------------------------------- ### Get transaction status Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Returns the current transaction status reported by the server. ```go func (pgConn *PgConn) TxStatus() byte ``` ```text 'I' - idle / not in transaction 'T' - in a transaction 'E' - in a failed transaction ``` -------------------------------- ### Connect to PostgreSQL Database with Config Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Establishes a new connection to a PostgreSQL database using a pre-parsed Config struct. This allows for more control over connection parameters. ```go func ConnectConfig(ctx context.Context, config *Config) (*PgConn, error) ``` -------------------------------- ### Connect Function Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Establishes a PostgreSQL connection using a connection string. Refer to pgconn.Connect for detailed options. ```go func Connect(ctx context.Context, connString string) (*Conn, error) ``` -------------------------------- ### Get Bytes from CompositeTextScanner Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Retrieves the bytes of the field most recently read by Scan() from CompositeTextScanner. ```go func (cfs *CompositeTextScanner) Bytes() []byte ``` -------------------------------- ### Get SQL from Preprocessing Error Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Retrieves the SQL statement associated with an ErrPreprocessingBatch error. ```go func (e ErrPreprocessingBatch) SQL() string ``` -------------------------------- ### ConnectWithOptions Function (v5.1.0+) Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Connects to PostgreSQL with additional options, primarily for providing a pgconn.GetSSLPasswordFunc. Behaves like Connect otherwise. ```go func ConnectWithOptions(ctx context.Context, connString string, options ParseConfigOptions) (*Conn, error) ``` -------------------------------- ### Register pgx.ConnConfig and Open Connection Source: https://pkg.go.dev/github.com/jackc/pgx/v5/stdlib Register a custom pgx.ConnConfig with the driver and then open a database/sql connection using the returned connection string. ```go connConfig, _ := pgx.ParseConfig(os.Getenv("DATABASE_URL")) connConfig.Tracer = &tracelog.TraceLog{Logger: myLogger, LogLevel: tracelog.LogLevelInfo} stdlib.RegisterConnConfig(connConfig) db, _ := sql.Open("pgx", stdlib.RegisterConnConfig(connConfig)) ``` -------------------------------- ### Backend Server Implementation Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgproto3 Core methods for the PostgreSQL wire protocol backend server. ```go type Backend struct { // contains filtered or unexported fields } ``` ```go func NewBackend(r io.Reader, w io.Writer) *Backend ``` ```go func (b *Backend) Flush() error ``` ```go func (b *Backend) Receive() (FrontendMessage, error) ``` ```go func (b *Backend) ReceiveStartupMessage() (FrontendMessage, error) ``` ```go func (b *Backend) Send(msg BackendMessage) ``` ```go func (b *Backend) SetAuthType(authType uint32) error ``` ```text Byte1('p') Identifies the message as a password response. Note that this is also used for GSSAPI, SSPI and SASL response messages. The exact message type can be deduced from the context. ``` -------------------------------- ### Get Array Element by Index Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Returns the element at the specified index `i`. The return type is `any`. ```go func (a Array[T]) Index(i int) any ``` -------------------------------- ### Connect to pgfortune with psql Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgproto3/example/pgfortune Connect to the running pgfortune server using the psql client. This demonstrates how to interact with the mock server. ```bash $ psql -h 127.0.0.1 -p 15432 ``` -------------------------------- ### Get Array Dimensions Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Returns the dimensions of the array. If the array is nil, nil is returned. ```go func (a Array[T]) Dimensions() []ArrayDimension ``` -------------------------------- ### TracePrepareStartData Struct Definition Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Defines the data structure for tracing the start of a prepare statement operation. ```go type TracePrepareStartData struct { Name string SQL string } ``` -------------------------------- ### Connect to PostgreSQL Database Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Establishes a new connection to a PostgreSQL database using a connection string. Ensure the connection string is valid and the database is accessible. ```go func Connect(ctx context.Context, connString string) (*PgConn, error) ``` -------------------------------- ### Timestamptz.TimestamptzValue() Implementation Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Implements the TimestamptzValuer interface for Timestamptz. Use to explicitly get a Timestamptz value. ```go func (tstz Timestamptz) TimestamptzValue() (Timestamptz, error) ``` -------------------------------- ### Timestamp.TimestampValue() Implementation Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Implements the TimestampValuer interface for Timestamp. Use to explicitly get a Timestamp value. ```go func (ts Timestamp) TimestampValue() (Timestamp, error) ``` -------------------------------- ### Get Number of Queued Queries in Batch Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Returns the count of queries that have been added to the batch so far. ```go func (b *Batch) Len() int ``` -------------------------------- ### Establish PostgreSQL Connection Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Use pgx.Connect to establish a connection to the PostgreSQL database using a connection string. The context and the database URL are required arguments. ```go conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) ``` -------------------------------- ### Example Output for Row Scanning Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Illustrates the expected output format when scanning rows into structures or maps. ```text Output: Cheeseburger: $10 Fries: $5 Soft Drink: $3 ``` -------------------------------- ### Connect Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Establishes a connection to a PostgreSQL server using a connection string. ```APIDOC ## Connect ### Description Establishes a connection to a PostgreSQL server using the environment and connString (in URL or keyword/value format) to provide configuration. ### Method Function ### Parameters - **ctx** (context.Context) - Required - Context for cancellation. - **connString** (string) - Required - Connection string in URL or keyword/value format. ### Response - **PgConn** (*PgConn) - The connection handle. - **error** (error) - Error if connection fails. ``` -------------------------------- ### Identify StartupMessage as Frontend Message in Go Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgproto3 Identifies this message as one that can be sent by a PostgreSQL frontend. ```go func (*StartupMessage) Frontend() ``` -------------------------------- ### Time.TimeValue() Implementation Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Implements the TimeValuer interface for the Time type. Use when needing to explicitly get a Time value. ```go func (t Time) TimeValue() (Time, error) ``` -------------------------------- ### Get Current Large Object Position Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Returns the current read or write location of the large object descriptor. ```go func (o *LargeObject) Tell() (n int64, err error) ``` -------------------------------- ### StartPipeline Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Switches the connection to pipeline mode and returns a *Pipeline. In pipeline mode, requests can be sent to the server without waiting for a response. Close must be called on the returned *Pipeline to return the connection to normal mode. ```APIDOC ## StartPipeline ### Description Switches the connection to pipeline mode and returns a *Pipeline. In pipeline mode requests can be sent to the server without waiting for a response. Close must be called on the returned *Pipeline to return the connection to normal mode. While in pipeline mode, no methods that communicate with the server may be called except CancelRequest and Close. ctx is in effect for entire life of the *Pipeline. Prefer ExecBatch when only sending one group of queries at once. ### Method *(*PgConn) StartPipeline ### Endpoint N/A (Method on PgConn type) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **Pipeline** (*Pipeline) - A pointer to the Pipeline object. #### Response Example None ``` -------------------------------- ### Construct PgConn from Hijacked Connection Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Constructs a PgConn from an existing HijackedConn. Use this when taking over an already established network connection. ```go func Construct(hc *HijackedConn) (*PgConn, error) ``` -------------------------------- ### Get Array Element Type Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Returns a non-nil scan target of the type that `Index` will return. This is used by `ArrayCodec.PlanEncode`. ```go func (a Array[T]) IndexType() any ``` -------------------------------- ### Define Notice and Handler Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Structures and types for handling PostgreSQL server notices. ```go type Notice PgError ``` ```go type NoticeHandler func(*PgConn, *Notice) ``` -------------------------------- ### Get Type Map from pgx Connection Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Retrieves the type map associated with the pgx connection, used for type conversions. ```go func (c *Conn) TypeMap() *pgtype.Map ``` -------------------------------- ### Implement net.Conn interface methods Source: https://pkg.go.dev/github.com/jackc/pgx/v5/internal/faultyconn Standard net.Conn interface methods implemented by the Conn wrapper. ```go func (c *Conn) Close() error ``` ```go func (c *Conn) LocalAddr() net.Addr ``` ```go func (c *Conn) Read(b []byte) (n int, err error) ``` ```go func (c *Conn) RemoteAddr() net.Addr ``` ```go func (c *Conn) SetDeadline(t time.Time) error ``` ```go func (c *Conn) SetReadDeadline(t time.Time) error ``` ```go func (c *Conn) SetWriteDeadline(t time.Time) error ``` ```go func (c *Conn) Write(b []byte) (n int, err error) ``` -------------------------------- ### Get Frontend Protocol Handler Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Returns the pgproto3.Frontend handler for the connection. This provides low-level access to the PostgreSQL wire protocol. ```go func (pgConn *PgConn) Frontend() *pgproto3.Frontend ``` -------------------------------- ### Marshal StartupMessage to JSON in Go Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgproto3 Implements the encoding/json.Marshaler interface for StartupMessage. ```go func (src StartupMessage) MarshalJSON() ([]byte, error) ``` -------------------------------- ### Build Extended Query Parameters Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Sets ParamValues, ParamFormats, and ResultFormats for use with PgConn.ExecParams or PgConn.ExecPrepared. If sd is nil then QueryExecModeExec behavior will be used. ```go func (eqb *ExtendedQueryBuilder) Build(m *pgtype.Map, sd *pgconn.StatementDescription, args []any) error ``` -------------------------------- ### Get Connection Cleanup Channel Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Returns a channel that is closed when the connection cleanup is complete. Useful for managing connection lifecycle. ```go func (pgConn *PgConn) CleanupDone() chan (struct{}) ``` -------------------------------- ### Prepare Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Creates a prepared statement with name and sql. sql can contain placeholders for bound parameters. These placeholders are referenced positionally as $1, $2, etc. name can be used instead of sql with Conn.Query, Conn.QueryRow, and Conn.Exec to execute the statement. It can also be used with Batch.Queue. Prepare is idempotent. ```APIDOC ## Prepare ### Description Prepare creates a prepared statement with name and sql. sql can contain placeholders for bound parameters. These placeholders are referenced positionally as $1, $2, etc. name can be used instead of sql with Conn.Query, Conn.QueryRow, and Conn.Exec to execute the statement. It can also be used with Batch.Queue. The underlying PostgreSQL identifier for the prepared statement will be name if name != sql or a digest of sql if name == sql. Prepare is idempotent; i.e. it is safe to call Prepare multiple times with the same name and sql arguments. This allows a code path to Prepare and Query/Exec without concern for if the statement has already been prepared. ### Signature ```go func (c *Conn) Prepare(ctx context.Context, name, sql string) (sd *pgconn.StatementDescription, err error) ``` ``` -------------------------------- ### Conn.ConnectConfig Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Establishes a connection with a PostgreSQL server using a configuration struct. ```APIDOC ## ConnectConfig ### Description Establishes a connection with a PostgreSQL server using a configuration struct. connConfig must have been created by ParseConfig. ### Method ```go func ConnectConfig(ctx context.Context, connConfig *ConnConfig) (*Conn, error) ``` ### Parameters - **ctx** (context.Context): The context for the connection attempt. - **connConfig** (*ConnConfig): A pointer to the connection configuration struct. ``` -------------------------------- ### Conn.Connect Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Establishes a connection with a PostgreSQL server using a connection string. ```APIDOC ## Connect ### Description Establishes a connection with a PostgreSQL server using a connection string. See pgconn.Connect for details. ### Method ```go func Connect(ctx context.Context, connString string) (*Conn, error) ``` ### Parameters - **ctx** (context.Context): The context for the connection attempt. - **connString** (string): The PostgreSQL connection string. ``` -------------------------------- ### Hijack Network Connection Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Hijacks the underlying network connection. Use this to take manual control of the connection, for example, to integrate with other network protocols. ```go func (pgConn *PgConn) Hijack() (*HijackedConn, error) ``` -------------------------------- ### Define TraceBatchStartData Structure Source: https://pkg.go.dev/github.com/jackc/pgx/v5 TraceBatchStartData captures information at the beginning of a batch operation, referencing the batch itself. ```go type TraceBatchStartData struct { Batch *Batch } ``` -------------------------------- ### QueryTracer Interface Source: https://pkg.go.dev/github.com/jackc/pgx/v5 The QueryTracer interface provides methods for tracing the start and end of query executions. It is called during Query, QueryRow, and Exec operations. ```APIDOC ## QueryTracer Interface ### Description Traces the start and end of Query, QueryRow, and Exec calls. ### Methods - **TraceQueryStart**(ctx context.Context, conn *Conn, data TraceQueryStartData) context.Context - **TraceQueryEnd**(ctx context.Context, conn *Conn, data TraceQueryEndData) ``` -------------------------------- ### Trace pgx CopyFrom Events Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Interface for tracing the start and end of CopyFrom operations. It receives the connection object and relevant data for tracing. ```go type CopyFromTracer interface { // TraceCopyFromStart is called at the beginning of CopyFrom calls. The returned context is used for // the rest of the call and will be passed to TraceCopyFromEnd. TraceCopyFromStart(ctx context.Context, conn *Conn, data TraceCopyFromStartData) context.Context TraceCopyFromEnd(ctx context.Context, conn *Conn, data TraceCopyFromEndData) } ``` -------------------------------- ### StartupMessage Encoding, Decoding, and Frontend Identification Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgproto3 Details the methods for encoding, decoding, and identifying StartupMessage as a frontend message. ```APIDOC ## type StartupMessage ¶ ``` type StartupMessage struct { ProtocolVersion uint32 Parameters map[string]string } ``` ### Description Represents a PostgreSQL startup message, including protocol version and parameters. ## func (*StartupMessage) Decode ¶ ``` func (dst *StartupMessage) Decode(src []byte) error ``` ### Description Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message type identifier and 4 byte message length. ### Method Decode ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## func (*StartupMessage) Encode ¶ ``` func (src *StartupMessage) Encode(dst []byte) ([]byte, error) ``` ### Description Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. ### Method Encode ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## func (*StartupMessage) Frontend ¶ ``` func (*StartupMessage) Frontend() ``` ### Description Frontend identifies this message as sendable by a PostgreSQL frontend. ### Method Frontend ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Response Example N/A ``` -------------------------------- ### Parse Configuration Options Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Contains options that control how a configuration is built, such as retrieving SSL passwords. Added in v5.1.0. ```go type ParseConfigOptions struct { pgconn.ParseConfigOptions } ``` -------------------------------- ### Get Connection Process ID Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Returns the process ID (PID) of the backend server process handling this connection. Useful for monitoring and debugging. ```go func (pgConn *PgConn) PID() uint32 ``` -------------------------------- ### Define QueryTracer Interface Source: https://pkg.go.dev/github.com/jackc/pgx/v5 The QueryTracer interface allows for tracing the start and end of query executions. Use this for logging, performance monitoring, or custom query behavior. ```go type QueryTracer interface { // TraceQueryStart is called at the beginning of Query, QueryRow, and Exec calls. The returned context is used for the // rest of the call and will be passed to TraceQueryEnd. TraceQueryStart(ctx context.Context, conn *Conn, data TraceQueryStartData) context.Context TraceQueryEnd(ctx context.Context, conn *Conn, data TraceQueryEndData) } ``` -------------------------------- ### Prepare Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Creates a prepared statement using PostgreSQL Parse and Describe protocol messages. ```APIDOC ## Prepare ### Description Creates a prepared statement. If the name is empty, the anonymous prepared statement is used. ### Parameters - **ctx** (context.Context) - Required - The context for the operation. - **name** (string) - Required - The name of the statement. - **sql** (string) - Required - The SQL query string. - **paramOIDs** ([]uint32) - Optional - Parameter OIDs. ### Response - **StatementDescription** - Returns the description of the prepared statement. - **error** - Returns an error if the preparation fails. ``` -------------------------------- ### Define TraceCopyFromStartData Structure Source: https://pkg.go.dev/github.com/jackc/pgx/v5 TraceCopyFromStartData captures details at the beginning of a CopyFrom operation, such as table name and column names. ```go type TraceCopyFromStartData struct { TableName Identifier ColumnNames []string } ``` -------------------------------- ### pgconn Package Overview Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn This section provides an overview of the pgconn package, including its purpose, connection establishment, query execution, pipeline mode, and context support. ```APIDOC ## Package pgconn ### Description Package pgconn is a low-level PostgreSQL database driver. It operates at nearly the same level as the C library libpq. It is primarily intended to serve as the foundation for higher level libraries such as https://github.com/jackc/pgx. Applications should handle normal queries with a higher level library and only use pgconn directly when required for low-level access to PostgreSQL functionality. ### Establishing a Connection Use `Connect` to establish a connection. It accepts a connection string in URL or keyword/value format and will read the environment for libpq style environment variables. ### Executing a Query `ExecParams` and `ExecPrepared` execute a single query. They return readers that iterate over each row. The `Read` method reads all rows into memory. ### Executing Multiple Queries in a Single Round Trip `Exec` and `ExecBatch` can execute multiple queries in a single round trip. They return readers that iterate over each query result. The `ReadAll` method reads all query results into memory. ### Pipeline Mode Pipeline mode allows sending queries without having read the results of previously sent queries. It allows control of exactly how many and when network round trips occur. ### Context Support All potentially blocking operations take a `context.Context`. The default behavior when a context is canceled is for the method to immediately return. In most circumstances, this will also close the underlying connection. This behavior can be customized by using `BuildContextWatcherHandler` on the `Config` to create a `ctxwatch.Handler` with different behavior. This can be especially useful when queries that are frequently canceled and the overhead of creating new connections is a problem. `DeadlineContextWatcherHandler` and `CancelRequestContextWatcherHandler` can be used to introduce a delay before interrupting the query in such a way as to close the connection. The `CancelRequest` method may be used to request the PostgreSQL server cancel an in-progress query without forcing the client to abort. ``` -------------------------------- ### Get Underlying pgx.Conn from Pool Conn Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool Conn returns the underlying *pgx.Conn from a pooled connection. This can be useful for advanced operations that require direct access to the pgx.Conn. ```go func (c *Conn) Conn() *pgx.Conn ``` -------------------------------- ### Get Connection String from Config Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool ConnString returns the connection string as parsed by pgxpool.ParseConfig into pgxpool.Config. Use this to retrieve the formatted connection string from a Config object. ```go func (c *Config) ConnString() string ``` -------------------------------- ### Get LRUCache Capacity - stmtcache Source: https://pkg.go.dev/github.com/jackc/pgx/v5/internal/stmtcache The Cap method returns the maximum number of statement descriptions that the LRUCache can hold. This value is set during the cache's creation. ```go func (c *LRUCache) Cap() int ``` -------------------------------- ### Implement PlanScan for Uint64Codec Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Implement the PlanScan method for Uint64Codec. This prepares a scanning plan for Uint64 values. ```go func (Uint64Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan ``` -------------------------------- ### Get Current Length of LRUCache - stmtcache Source: https://pkg.go.dev/github.com/jackc/pgx/v5/internal/stmtcache The Len method returns the current number of statement descriptions stored in the LRUCache. This indicates how many items are actively cached. ```go func (c *LRUCache) Len() int ``` -------------------------------- ### Create a New Connection Pool Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool New creates a new Pool using the provided connection string. See ParseConfig for information on connString format. ```go func New(ctx context.Context, connString string) (*Pool, error) ``` -------------------------------- ### BeginTxFunc Transaction Helper Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Executes a function within a database transaction with specified options. Automatically commits on success or rolls back on error. Uses the provided context for transaction control statements. ```go func BeginTxFunc( ctx context.Context, db interface { BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) }, txOptions TxOptions, fn func(Tx) error, ) (err error) ``` -------------------------------- ### BatchTracer Interface Source: https://pkg.go.dev/github.com/jackc/pgx/v5 The BatchTracer interface is used for tracing the lifecycle of SendBatch calls. It provides methods to trace the start of a batch, individual queries within the batch, and the end of the batch. ```APIDOC ## BatchTracer Interface ### Description Used for tracing the lifecycle of SendBatch calls. Provides methods to trace the start of a batch, individual queries within the batch, and the end of the batch. ### Methods - **TraceBatchStart(ctx context.Context, conn *Conn, data TraceBatchStartData) context.Context**: Called at the beginning of SendBatch calls. Returns a context used for the rest of the call. - **TraceBatchQuery(ctx context.Context, conn *Conn, data TraceBatchQueryData)**: Traces individual queries within the batch. - **TraceBatchEnd(ctx context.Context, conn *Conn, data TraceBatchEndData)**: Traces the end of the batch operation. ``` -------------------------------- ### Get Invalidated Statements from LRUCache - stmtcache Source: https://pkg.go.dev/github.com/jackc/pgx/v5/internal/stmtcache GetInvalidated returns a list of statement descriptions that have been marked as invalidated since the last call to RemoveInvalidated. This method is available from v5.5.3 onwards. ```go func (c *LRUCache) GetInvalidated() []*pgconn.StatementDescription ``` -------------------------------- ### Conn.Config Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Returns a copy of the configuration that was used to establish this connection. ```APIDOC ## Config ### Description Returns a copy of config that was used to establish this connection. ### Method ```go func (c *Conn) Config() *ConnConfig ``` ### Returns - **(*ConnConfig)**: A pointer to the connection configuration struct. ``` -------------------------------- ### Implement TryWrapArrayEncodePlan Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Attempts to wrap an array encode plan. Returns the wrapper, the next value to process, and a boolean indicating success. ```go func TryWrapArrayEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) ``` -------------------------------- ### Cache Interface Definition - stmtcache Source: https://pkg.go.dev/github.com/jackc/pgx/v5/internal/stmtcache The Cache interface defines the contract for statement caching operations. Implementations must provide methods for getting, putting, invalidating, and managing cached statement descriptions. ```go type Cache interface { // Get returns the statement description for sql. Returns nil if not found. Get(sql string) *pgconn.StatementDescription // Put stores sd in the cache. Put panics if sd.SQL is "". Put does nothing if sd.SQL already exists in the cache. Put(sd *pgconn.StatementDescription) // Invalidate invalidates statement description identified by sql. Does nothing if not found. Invalidate(sql string) // InvalidateAll invalidates all statement descriptions. InvalidateAll() // GetInvalidated returns a slice of all statement descriptions invalidated since the last call to RemoveInvalidated. GetInvalidated() []*pgconn.StatementDescription // RemoveInvalidated removes all invalidated statement descriptions. No other calls to Cache must be made between a // call to GetInvalidated and RemoveInvalidated or RemoveInvalidated may remove statement descriptions that were // never seen by the call to GetInvalidated. RemoveInvalidated() // Len returns the number of cached prepared statement descriptions. Len() int // Cap returns the maximum number of cached prepared statement descriptions. Cap() int } ``` -------------------------------- ### Implement database/sql.Scanner for Uint64 Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Implement the database/sql.Scanner interface for the Uint64 type. This enables Uint64 values to be scanned from database query results. ```go func (dst *Uint64) Scan(src any) error ``` -------------------------------- ### ConnectConfig Function Source: https://pkg.go.dev/github.com/jackc/pgx/v5 Establishes a PostgreSQL connection using a pre-configured ConnConfig struct. The config must be parsed by ParseConfig. ```go func ConnectConfig(ctx context.Context, connConfig *ConnConfig) (*Conn, error) ``` -------------------------------- ### Encode StartupMessage in Go Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgproto3 Encodes a StartupMessage into a byte slice. The destination slice will include the 1-byte message type identifier and the 4-byte message length. ```go func (src *StartupMessage) Encode(dst []byte) ([]byte, error) ``` -------------------------------- ### Implement PreferredFormat for Uint64Codec Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Implement the PreferredFormat method for Uint64Codec to return the preferred data format. ```go func (Uint64Codec) PreferredFormat() int16 ``` -------------------------------- ### Parse Connection String Keyword/Value Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool Use keyword/value pairs to configure a PostgreSQL connection. This format is useful for direct configuration. ```go user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca pool_max_conns=10 pool_max_conn_lifetime=1h30m ``` -------------------------------- ### ExecPrepared Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Enqueues the execution of a prepared statement via the PostgreSQL extended query protocol. ```APIDOC ## ExecPrepared ### Description Enqueues the execution of a prepared statement via the PostgreSQL extended query protocol. ### Parameters - **ctx** (context.Context) - Required - The context for the operation. - **stmtName** (string) - Required - The name of the prepared statement. - **paramValues** ([][]byte) - Required - The parameter values. - **paramFormats** ([]int16) - Optional - Format codes for parameters. - **resultFormats** ([]int16) - Optional - Format codes for result columns. ### Response - **ResultReader** - Returns a ResultReader which must be closed after use. ``` -------------------------------- ### Execute Prepared Statement Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn Executes a prepared statement with parameters and returns a ResultReader. Use this for performance when executing the same query multiple times. ```go func (pgConn *PgConn) ExecPrepared(ctx context.Context, stmtName string, paramValues [][]byte, ...) *ResultReader ``` -------------------------------- ### Prepare Tracer Interface Source: https://pkg.go.dev/github.com/jackc/pgx/v5 An interface for tracing Prepare calls. It includes methods to be called at the beginning and end of Prepare operations. ```go type PrepareTracer interface { // TracePrepareStart is called at the beginning of Prepare calls. The returned context is used for the // rest of the call and will be passed to TracePrepareEnd. TracePrepareStart(ctx context.Context, conn *Conn, data TracePrepareStartData) context.Context TracePrepareEnd(ctx context.Context, conn *Conn, data TracePrepareEndData) } ``` -------------------------------- ### Create New CompositeTextBuilder Source: https://pkg.go.dev/github.com/jackc/pgx/v5/pgtype Initializes a new CompositeTextBuilder with a given Map and buffer. ```go func NewCompositeTextBuilder(m *Map, buf []byte) *CompositeTextBuilder ```