diff --git a/batch.go b/batch.go index 702fcff5b..805cc39ef 100644 --- a/batch.go +++ b/batch.go @@ -8,7 +8,7 @@ import ( "github.com/jackc/pgx/v5/pgconn" ) -// QueuedQuery is a query that has been queued for execution via a Batch. +// QueuedQuery is a query that has been queued for execution via a [Batch]. type QueuedQuery struct { SQL string Arguments []any @@ -46,7 +46,7 @@ func (qq *QueuedQuery) QueryRow(fn func(row Row) error) { // // Note: for simple batch insert uses where it is not required to handle // each potential error individually, it's sufficient to not set any callbacks, -// and just handle the return value of BatchResults.Close. +// and just handle the return value of [BatchResults.Close]. func (qq *QueuedQuery) Exec(fn func(ct pgconn.CommandTag) error) { qq.Fn = func(br BatchResults) error { ct, err := br.Exec() @@ -65,12 +65,13 @@ type Batch struct { } // Queue queues a query to batch b. query can be an SQL query or the name of a prepared statement. The only pgx option -// argument that is supported is QueryRewriter. Queries are executed using the connection's DefaultQueryExecMode. +// argument that is supported is [QueryRewriter]. Queries are executed using the connection's DefaultQueryExecMode +// (see [ConnConfig.DefaultQueryExecMode]). // -// While query can contain multiple statements if the connection's DefaultQueryExecMode is QueryModeSimple, this should -// be avoided. QueuedQuery.Fn must not be set as it will only be called for the first query. That is, QueuedQuery.Query, -// QueuedQuery.QueryRow, and QueuedQuery.Exec must not be called. In addition, any error messages or tracing that -// include the current query may reference the wrong query. +// While query can contain multiple statements if the connection's DefaultQueryExecMode is [QueryExecModeSimpleProtocol], +// this should be avoided. QueuedQuery.Fn must not be set as it will only be called for the first query. That is, +// [QueuedQuery.Query], [QueuedQuery.QueryRow], and [QueuedQuery.Exec] must not be called. In addition, any error +// messages or tracing that include the current query may reference the wrong query. func (b *Batch) Queue(query string, arguments ...any) *QueuedQuery { qq := &QueuedQuery{ SQL: query, @@ -86,20 +87,20 @@ func (b *Batch) Len() int { } type BatchResults interface { - // Exec reads the results from the next query in the batch as if the query has been sent with Conn.Exec. Prefer + // Exec reads the results from the next query in the batch as if the query has been sent with [Conn.Exec]. Prefer // calling Exec on the QueuedQuery, or just calling Close. Exec() (pgconn.CommandTag, error) - // Query reads the results from the next query in the batch as if the query has been sent with Conn.Query. Prefer - // calling Query on the QueuedQuery. + // Query reads the results from the next query in the batch as if the query has been sent with [Conn.Query]. Prefer + // calling [QueuedQuery.Query]. Query() (Rows, error) - // QueryRow reads the results from the next query in the batch as if the query has been sent with Conn.QueryRow. - // Prefer calling QueryRow on the QueuedQuery. + // QueryRow reads the results from the next query in the batch as if the query has been sent with [Conn.QueryRow]. + // Prefer calling [QueuedQuery.QueryRow]. QueryRow() Row // Close closes the batch operation. All unread results are read and any callback functions registered with - // QueuedQuery.Query, QueuedQuery.QueryRow, or QueuedQuery.Exec will be called. If a callback function returns an + // [QueuedQuery.Query], [QueuedQuery.QueryRow], or [QueuedQuery.Exec] will be called. If a callback function returns an // error or the batch encounters an error subsequent callback functions will not be called. // // For simple batch inserts inside a transaction or similar queries, it's sufficient to not set any callbacks, diff --git a/conn.go b/conn.go index 67c52ac97..4f27a5df2 100644 --- a/conn.go +++ b/conn.go @@ -17,8 +17,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) -// ConnConfig contains all the options used to establish a connection. It must be created by ParseConfig and -// then it can be modified. A manually initialized ConnConfig will cause ConnectConfig to panic. +// ConnConfig contains all the options used to establish a connection. It must be created by [ParseConfig] and +// then it can be modified. A manually initialized ConnConfig will cause [ConnectConfig] to panic. type ConnConfig struct { pgconn.Config @@ -37,8 +37,8 @@ type ConnConfig struct { // DefaultQueryExecMode controls the default mode for executing queries. By default pgx uses the extended protocol // and automatically prepares and caches prepared statements. However, this may be incompatible with proxies such as - // PGBouncer. In this case it may be preferable to use QueryExecModeExec or QueryExecModeSimpleProtocol. The same - // functionality can be controlled on a per query basis by passing a QueryExecMode as the first query argument. + // PGBouncer. In this case it may be preferable to use [QueryExecModeExec] or [QueryExecModeSimpleProtocol]. The same + // functionality can be controlled on a per query basis by passing a [QueryExecMode] as the first query argument. DefaultQueryExecMode QueryExecMode createdByParseConfig bool // Used to enforce created by ParseConfig rule. @@ -131,7 +131,7 @@ var ( ) // Connect establishes a connection with a PostgreSQL server with a connection string. See -// pgconn.Connect for details. +// [pgconn.Connect] for details. func Connect(ctx context.Context, connString string) (*Conn, error) { connConfig, err := ParseConfig(connString) if err != nil { @@ -141,7 +141,7 @@ func Connect(ctx context.Context, connString string) (*Conn, error) { } // ConnectWithOptions behaves exactly like Connect with the addition of options. At the present options is only used to -// provide a GetSSLPassword function. +// provide a [pgconn.GetSSLPasswordFunc] function. func ConnectWithOptions(ctx context.Context, connString string, options ParseConfigOptions) (*Conn, error) { connConfig, err := ParseConfigWithOptions(connString, options) if err != nil { @@ -151,7 +151,7 @@ func ConnectWithOptions(ctx context.Context, connString string, options ParseCon } // ConnectConfig establishes a connection with a PostgreSQL server with a configuration struct. -// connConfig must have been created by ParseConfig. +// connConfig must have been created by [ParseConfig]. func ConnectConfig(ctx context.Context, connConfig *ConnConfig) (*Conn, error) { // In general this improves safety. In particular avoid the config.Config.OnNotification mutation from affecting other // connections with the same config. See https://github.com/jackc/pgx/issues/618. @@ -160,8 +160,8 @@ func ConnectConfig(ctx context.Context, connConfig *ConnConfig) (*Conn, error) { return connect(ctx, connConfig) } -// ParseConfigWithOptions behaves exactly as ParseConfig does with the addition of options. At the present options is -// only used to provide a GetSSLPassword function. +// ParseConfigWithOptions behaves exactly as [ParseConfig] does with the addition of options. At the present options is +// only used to provide a [pgconn.GetSSLPasswordFunc] function. func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*ConnConfig, error) { config, err := pgconn.ParseConfigWithOptions(connString, options.ParseConfigOptions) if err != nil { @@ -308,8 +308,8 @@ func (c *Conn) Close(ctx context.Context) error { } // 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 Query, QueryRow, and -// Exec to execute the statement. It can also be used with Batch.Queue. +// 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. @@ -933,7 +933,7 @@ func (c *Conn) QueryRow(ctx context.Context, sql string, args ...any) Row { } // SendBatch sends all queued queries to the server at once. All queries are run in an implicit transaction unless -// explicit transaction control statements are executed. The returned BatchResults must be closed before the connection +// explicit transaction control statements are executed. The returned [BatchResults] must be closed before the connection // is used again. // // Depending on the QueryExecMode, all queries may be prepared before any are executed. This means that creating a table @@ -1277,7 +1277,7 @@ func (c *Conn) sanitizeForSimpleQuery(sql string, args ...any) (string, error) { return sanitize.SanitizeSQL(sql, valueArgs...) } -// LoadType inspects the database for typeName and produces a pgtype.Type suitable for registration. typeName must be +// LoadType inspects the database for typeName and produces a [pgtype.Type] suitable for registration. typeName must be // the name of a type where the underlying type(s) is already understood by pgx. It is for derived types. In particular, // typeName must be one of the following: // - An array type name of a type that is already registered. e.g. "_foo" when "foo" is registered. diff --git a/copy_from.go b/copy_from.go index abcd22396..038c568cf 100644 --- a/copy_from.go +++ b/copy_from.go @@ -10,8 +10,8 @@ import ( "github.com/jackc/pgx/v5/pgconn" ) -// CopyFromRows returns a CopyFromSource interface over the provided rows slice -// making it usable by *Conn.CopyFrom. +// CopyFromRows returns a [CopyFromSource] interface over the provided rows slice +// making it usable by [Conn.CopyFrom]. func CopyFromRows(rows [][]any) CopyFromSource { return ©FromRows{rows: rows, idx: -1} } @@ -34,8 +34,8 @@ func (ctr *copyFromRows) Err() error { return nil } -// CopyFromSlice returns a CopyFromSource interface over a dynamic func -// making it usable by *Conn.CopyFrom. +// CopyFromSlice returns a [CopyFromSource] interface over a dynamic func +// making it usable by [Conn.CopyFrom]. func CopyFromSlice(length int, next func(int) ([]any, error)) CopyFromSource { return ©FromSlice{next: next, idx: -1, len: length} } @@ -64,7 +64,7 @@ func (cts *copyFromSlice) Err() error { return cts.err } -// CopyFromFunc returns a CopyFromSource interface that relies on nxtf for values. +// CopyFromFunc returns a [CopyFromSource] interface that relies on nxtf for values. // nxtf returns rows until it either signals an 'end of data' by returning row=nil and err=nil, // or it returns an error. If nxtf returns an error, the copy is aborted. func CopyFromFunc(nxtf func() (row []any, err error)) CopyFromSource { @@ -91,7 +91,7 @@ func (g *copyFromFunc) Err() error { return g.err } -// CopyFromSource is the interface used by *Conn.CopyFrom as the source for copy data. +// CopyFromSource is the interface used by [Conn.CopyFrom] as the source for copy data. type CopyFromSource interface { // Next returns true if there is another row and makes the next row data // available to Values(). When there are no more rows available or an error @@ -260,8 +260,8 @@ func (ct *copyFrom) buildCopyBuf(buf []byte, sd *pgconn.StatementDescription) (b // CopyFrom requires all values use the binary format. A pgtype.Type that supports the binary format must be registered // for the type of each column. Almost all types implemented by pgx support the binary format. // -// Even though enum types appear to be strings they still must be registered to use with CopyFrom. This can be done with -// Conn.LoadType and pgtype.Map.RegisterType. +// Even though enum types appear to be strings they still must be registered to use with [Conn.CopyFrom]. This can be done with +// [Conn.LoadType] and [pgtype.Map.RegisterType]. func (c *Conn) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) { ct := ©From{ conn: c, diff --git a/doc.go b/doc.go index 5d2ae3889..225b46472 100644 --- a/doc.go +++ b/doc.go @@ -1,8 +1,8 @@ // Package pgx is a PostgreSQL database driver. /* -pgx provides a native PostgreSQL driver and can act as a database/sql driver. The native PostgreSQL interface is similar -to the database/sql interface while providing better speed and access to PostgreSQL specific features. Use -github.com/jackc/pgx/v5/stdlib to use pgx as a database/sql compatible driver. See that package's documentation for +pgx provides a native PostgreSQL driver and can act as a [database/sql/driver]. The native PostgreSQL interface is similar +to the [database/sql] interface while providing better speed and access to PostgreSQL specific features. Use +[github.com/jackc/pgx/v5/stdlib] to use pgx as a database/sql compatible driver. See that package's documentation for details. Establishing a Connection @@ -19,15 +19,15 @@ string. Connection Pool [*pgx.Conn] represents a single connection to the database and is not concurrency safe. Use package -github.com/jackc/pgx/v5/pgxpool for a concurrency safe connection pool. +[github.com/jackc/pgx/v5/pgxpool] for a concurrency safe connection pool. Query Interface -pgx implements Query in the familiar database/sql style. However, pgx provides generic functions such as CollectRows and -ForEachRow that are a simpler and safer way of processing rows than manually calling defer rows.Close(), rows.Next(), -rows.Scan, and rows.Err(). +pgx implements [Conn.Query] in the familiar database/sql style. However, pgx provides generic functions such as [CollectRows] and +[ForEachRow] that are a simpler and safer way of processing rows than manually calling defer [Rows.Close], [Rows.Next], +[Rows.Scan], and [Rows.Err]. -CollectRows can be used collect all returned rows into a slice. +[CollectRows] can be used collect all returned rows into a slice. rows, _ := conn.Query(context.Background(), "select generate_series(1,$1)", 5) numbers, err := pgx.CollectRows(rows, pgx.RowTo[int32]) @@ -36,7 +36,7 @@ CollectRows can be used collect all returned rows into a slice. } // numbers => [1 2 3 4 5] -ForEachRow can be used to execute a callback function for every row. This is often easier than iterating over rows +[ForEachRow] can be used to execute a callback function for every row. This is often easier than iterating over rows directly. var sum, n int32 @@ -49,7 +49,7 @@ directly. return err } -pgx also implements QueryRow in the same style as database/sql. +pgx also implements [Conn.QueryRow] in the same style as database/sql. var name string var weight int64 @@ -58,7 +58,7 @@ pgx also implements QueryRow in the same style as database/sql. return err } -Use Exec to execute a query that does not return a result set. +Use [Conn.Exec] to execute a query that does not return a result set. commandTag, err := conn.Exec(context.Background(), "delete from widgets where id=$1", 42) if err != nil { @@ -70,13 +70,13 @@ Use Exec to execute a query that does not return a result set. PostgreSQL Data Types -pgx uses the pgtype package to converting Go values to and from PostgreSQL values. It supports many PostgreSQL types +pgx uses the [pgtype] package to converting Go values to and from PostgreSQL values. It supports many PostgreSQL types directly and is customizable and extendable. User defined data types such as enums, domains, and composite types may require type registration. See that package's documentation for details. Transactions -Transactions are started by calling Begin. +Transactions are started by calling [Conn.Begin]. tx, err := conn.Begin(context.Background()) if err != nil { @@ -96,13 +96,13 @@ Transactions are started by calling Begin. return err } -The Tx returned from Begin also implements the Begin method. This can be used to implement pseudo nested transactions. +The [Tx] returned from [Conn.Begin] also implements the [Tx.Begin] method. This can be used to implement pseudo nested transactions. These are internally implemented with savepoints. -Use BeginTx to control the transaction mode. BeginTx also can be used to ensure a new transaction is created instead of +Use [Conn.BeginTx] to control the transaction mode. [Conn.BeginTx] also can be used to ensure a new transaction is created instead of a pseudo nested transaction. -BeginFunc and BeginTxFunc are functions that begin a transaction, execute a function, and commit or rollback the +[BeginFunc] and [BeginTxFunc] are functions that begin a transaction, execute a function, and commit or rollback the transaction depending on the return value of the function. These can be simpler and less error prone to use. err = pgx.BeginFunc(context.Background(), conn, func(tx pgx.Tx) error { @@ -115,16 +115,16 @@ transaction depending on the return value of the function. These can be simpler Prepared Statements -Prepared statements can be manually created with the Prepare method. However, this is rarely necessary because pgx -includes an automatic statement cache by default. Queries run through the normal Query, QueryRow, and Exec functions are -automatically prepared on first execution and the prepared statement is reused on subsequent executions. See ParseConfig -for information on how to customize or disable the statement cache. +Prepared statements can be manually created with the [Conn.Prepare] method. However, this is rarely necessary because pgx +includes an automatic statement cache by default. Queries run through the normal [Conn.Query], [Conn.QueryRow], and [Conn.Exec] +functions are automatically prepared on first execution and the prepared statement is reused on subsequent executions. +See [ParseConfig] for information on how to customize or disable the statement cache. Copy Protocol -Use CopyFrom to efficiently insert multiple rows at a time using the PostgreSQL copy protocol. CopyFrom accepts a -CopyFromSource interface. If the data is already in a [][]any use CopyFromRows to wrap it in a CopyFromSource interface. -Or implement CopyFromSource to avoid buffering the entire data set in memory. +Use [Conn.CopyFrom] to efficiently insert multiple rows at a time using the PostgreSQL copy protocol. [Conn.CopyFrom] accepts a +[CopyFromSource] interface. If the data is already in a [][]any use [CopyFromRows] to wrap it in a [CopyFromSource] interface. +Or implement [CopyFromSource] to avoid buffering the entire data set in memory. rows := [][]any{ {"John", "Smith", int32(36)}, @@ -138,7 +138,7 @@ Or implement CopyFromSource to avoid buffering the entire data set in memory. pgx.CopyFromRows(rows), ) -When you already have a typed array using CopyFromSlice can be more convenient. +When you already have a typed array using [CopyFromSlice] can be more convenient. rows := []User{ {"John", "Smith", 36}, @@ -158,7 +158,7 @@ CopyFrom can be faster than an insert with as few as 5 rows. Listen and Notify -pgx can listen to the PostgreSQL notification system with the `Conn.WaitForNotification` method. It blocks until a +pgx can listen to the PostgreSQL notification system with the [Conn.WaitForNotification] method. It blocks until a notification is received or the context is canceled. _, err := conn.Exec(context.Background(), "listen channelname") @@ -175,20 +175,25 @@ notification is received or the context is canceled. Tracing and Logging -pgx supports tracing by setting ConnConfig.Tracer. To combine several tracers you can use the multitracer.Tracer. +pgx supports tracing by setting [ConnConfig.Tracer]. To combine several tracers you can use the [github.com/jackc/pgx/v5/multitracer.Tracer]. -In addition, the tracelog package provides the TraceLog type which lets a traditional logger act as a Tracer. +In addition, the [github.com/jackc/pgx/v5/tracelog] package provides the [github.com/jackc/pgx/v5/tracelog.TraceLog] type which lets a +traditional logger act as a [QueryTracer]. -For debug tracing of the actual PostgreSQL wire protocol messages see github.com/jackc/pgx/v5/pgproto3. +For debug tracing of the actual PostgreSQL wire protocol messages see [github.com/jackc/pgx/v5/pgproto3]. Lower Level PostgreSQL Functionality -github.com/jackc/pgx/v5/pgconn contains a lower level PostgreSQL driver roughly at the level of libpq. pgx.Conn is -implemented on top of pgconn. The Conn.PgConn() method can be used to access this lower layer. +[github.com/jackc/pgx/v5/pgconn] contains a lower level PostgreSQL driver roughly at the level of libpq. [Conn] is +implemented on top of [pgconn.PgConn]. The [Conn.PgConn] method can be used to access this lower layer. PgBouncer By default pgx automatically uses prepared statements. Prepared statements are incompatible with PgBouncer. This can be -disabled by setting a different QueryExecMode in ConnConfig.DefaultQueryExecMode. +disabled by setting a different [QueryExecMode] in [ConnConfig.DefaultQueryExecMode]. */ package pgx + +import ( + _ "github.com/jackc/pgx/v5/pgconn" // Just for allowing godoc to resolve "pgconn" +) diff --git a/pgconn/pgconn.go b/pgconn/pgconn.go index ca9a48cad..d6587cef8 100644 --- a/pgconn/pgconn.go +++ b/pgconn/pgconn.go @@ -538,7 +538,7 @@ func (pgConn *PgConn) signalMessage() chan struct{} { } // ReceiveMessage receives one wire protocol message from the PostgreSQL server. It must only be used when the -// connection is not busy. e.g. It is an error to call ReceiveMessage while reading the result of a query. The messages +// connection is not busy. e.g. It is an error to call [PgConn.ReceiveMessage] while reading the result of a query. The messages // are still handled by the core pgconn message handling system so receiving a NotificationResponse will still trigger // the OnNotification callback. // @@ -1125,7 +1125,7 @@ func (pgConn *PgConn) WaitForNotification(ctx context.Context) error { // implicitly wrapped in a transaction unless a transaction is already in progress or SQL contains transaction control // statements. // -// Prefer ExecParams unless executing arbitrary SQL that may contain multiple queries. +// Prefer [PgConn.ExecParams] unless executing arbitrary SQL that may contain multiple queries. func (pgConn *PgConn) Exec(ctx context.Context, sql string) *MultiResultReader { if err := pgConn.lock(); err != nil { return &MultiResultReader{ @@ -1183,7 +1183,7 @@ func (pgConn *PgConn) Exec(ctx context.Context, sql string) *MultiResultReader { // resultFormats is a slice of format codes determining for each result column whether it is encoded in text or // binary format. If resultFormats is nil all results will be in text format. // -// ResultReader must be closed before PgConn can be used again. +// [ResultReader] must be closed before [PgConn] can be used again. func (pgConn *PgConn) ExecParams(ctx context.Context, sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats, resultFormats []int16) *ResultReader { result := pgConn.execExtendedPrefix(ctx, paramValues) if result.closed { @@ -1209,7 +1209,7 @@ func (pgConn *PgConn) ExecParams(ctx context.Context, sql string, paramValues [] // resultFormats is a slice of format codes determining for each result column whether it is encoded in text or // binary format. If resultFormats is nil all results will be in text format. // -// ResultReader must be closed before PgConn can be used again. +// [ResultReader] must be closed before [PgConn] can be used again. func (pgConn *PgConn) ExecPrepared(ctx context.Context, stmtName string, paramValues [][]byte, paramFormats, resultFormats []int16) *ResultReader { result := pgConn.execExtendedPrefix(ctx, paramValues) if result.closed { @@ -1225,20 +1225,20 @@ func (pgConn *PgConn) ExecPrepared(ctx context.Context, stmtName string, paramVa // ExecStatement enqueues the execution of a prepared statement via the PostgreSQL extended query protocol. // -// This differs from ExecPrepared in that it takes a *StatementDescription instead of the prepared statement name. -// Because it has the *StatementDescription it can avoid the Describe Portal message that ExecPrepared must send to get +// This differs from [PgConn.ExecPrepared] in that it takes a [*StatementDescription] instead of the prepared statement name. +// Because it has the [*StatementDescription] it can avoid the Describe Portal message that [PgConn.ExecPrepared] must send to get // the result column descriptions. // // paramValues are the parameter values. It must be encoded in the format given by paramFormats. // // paramFormats is a slice of format codes determining for each paramValue column whether it is encoded in text or -// binary format. If paramFormats is nil all params are text format. ExecPrepared will panic if len(paramFormats) is not +// binary format. If paramFormats is nil all params are text format. ExecStatement will panic if len(paramFormats) is not // 0, 1, or len(paramValues). // // resultFormats is a slice of format codes determining for each result column whether it is encoded in text or binary // format. If resultFormats is nil all results will be in text format. // -// ResultReader must be closed before PgConn can be used again. +// [ResultReader] must be closed before [PgConn] can be used again. func (pgConn *PgConn) ExecStatement(ctx context.Context, statementDescription *StatementDescription, paramValues [][]byte, paramFormats, resultFormats []int16) *ResultReader { result := pgConn.execExtendedPrefix(ctx, paramValues) if result.closed { diff --git a/pgtype/doc.go b/pgtype/doc.go index 83dfc5de5..dbcdf692f 100644 --- a/pgtype/doc.go +++ b/pgtype/doc.go @@ -1,10 +1,10 @@ // Package pgtype converts between Go and PostgreSQL values. /* -The primary type is the Map type. It is a map of PostgreSQL types identified by OID (object ID) to a Codec. A Codec is -responsible for converting between Go and PostgreSQL values. NewMap creates a Map with all supported standard PostgreSQL -types already registered. Additional types can be registered with Map.RegisterType. +The primary type is the [Map] type. It is a map of PostgreSQL types identified by OID (object ID) to a [Codec]. A [Codec] is +responsible for converting between Go and PostgreSQL values. [NewMap] creates a [Map] with all supported standard PostgreSQL +types already registered. Additional types can be registered with [Map.RegisterType]. -Use Map.Scan and Map.Encode to decode PostgreSQL values to Go and encode Go values to PostgreSQL respectively. +Use [Map.Scan] and [Map.Encode] to decode PostgreSQL values to Go and encode Go values to PostgreSQL respectively. Base Type Mapping @@ -63,8 +63,8 @@ pgtype automatically marshals and unmarshals data from json and jsonb PostgreSQL Extending Existing PostgreSQL Type Support Generally, all Codecs will support interfaces that can be implemented to enable scanning and encoding. For example, -PointCodec can use any Go type that implements the PointScanner and PointValuer interfaces. So rather than use -pgtype.Point and application can directly use its own point type with pgtype as long as it implements those interfaces. +[PointCodec] can use any Go type that implements the [PointScanner] and [PointValuer] interfaces. So rather than use +[Point] an application can directly use its own point type with pgtype as long as it implements those interfaces. See example_custom_type_test.go for an example of a custom type for the PostgreSQL point type. @@ -77,10 +77,10 @@ New PostgreSQL Type Support pgtype uses the PostgreSQL OID to determine how to encode or decode a value. pgtype supports array, composite, domain, and enum types. However, any type created in PostgreSQL with CREATE TYPE will receive a new OID. This means that the OID -of each new PostgreSQL type must be registered for pgtype to handle values of that type with the correct Codec. +of each new PostgreSQL type must be registered for pgtype to handle values of that type with the correct [Codec]. -The pgx.Conn LoadType method can return a *Type for array, composite, domain, and enum types by inspecting the database -metadata. This *Type can then be registered with Map.RegisterType. +The [github.com/jackc/pgx/v5.Conn.LoadType] method can return a [*Type] for array, composite, domain, and enum types by +inspecting the database metadata. This [*Type] can then be registered with [Map.RegisterType]. For example, the following function could be called after a connection is established: @@ -106,30 +106,30 @@ For example, the following function could be called after a connection is establ A type cannot be registered unless all types it depends on are already registered. e.g. An array type cannot be registered until its element type is registered. -ArrayCodec implements support for arrays. If pgtype supports type T then it can easily support []T by registering an -ArrayCodec for the appropriate PostgreSQL OID. In addition, Array[T] type can support multi-dimensional arrays. +[ArrayCodec] implements support for arrays. If pgtype supports type T then it can easily support []T by registering an +[ArrayCodec] for the appropriate PostgreSQL OID. In addition, [Array] type can support multi-dimensional arrays. -CompositeCodec implements support for PostgreSQL composite types. Go structs can be scanned into if the public fields of -the struct are in the exact order and type of the PostgreSQL type or by implementing CompositeIndexScanner and -CompositeIndexGetter. +[CompositeCodec] implements support for PostgreSQL composite types. Go structs can be scanned into if the public fields of +the struct are in the exact order and type of the PostgreSQL type or by implementing [CompositeIndexScanner] and +[CompositeIndexGetter]. Domain types are treated as their underlying type if the underlying type and the domain type are registered. -PostgreSQL enums can usually be treated as text. However, EnumCodec implements support for interning strings which can +PostgreSQL enums can usually be treated as text. However, [EnumCodec] implements support for interning strings which can reduce memory usage. While pgtype will often still work with unregistered types it is highly recommended that all types be registered due to an improvement in performance and the elimination of certain edge cases. If an entirely new PostgreSQL type (e.g. PostGIS types) is used then the application or a library can create a new -Codec. Then the OID / Codec mapping can be registered with Map.RegisterType. There is no difference between a Codec -defined and registered by the application and a Codec built in to pgtype. See any of the Codecs in pgtype for Codec +[Codec]. Then the OID / [Codec] mapping can be registered with [Map.RegisterType]. There is no difference between a [Codec] +defined and registered by the application and a [Codec] built in to pgtype. See any of the [Codec]s in pgtype for [Codec] examples and for examples of type registration. Encoding Unknown Types pgtype works best when the OID of the PostgreSQL type is known. But in some cases such as using the simple protocol the -OID is unknown. In this case Map.RegisterDefaultPgType can be used to register an assumed OID for a particular Go type. +OID is unknown. In this case [Map.RegisterDefaultPgType] can be used to register an assumed OID for a particular Go type. Renamed Types @@ -137,18 +137,18 @@ If pgtype does not recognize a type and that type is a renamed simple type simpl as if it is the underlying type. It currently cannot automatically detect the underlying type of renamed structs (eg.g. type MyTime time.Time). -Compatibility with database/sql +Compatibility with [database/sql] -pgtype also includes support for custom types implementing the database/sql.Scanner and database/sql/driver.Valuer +pgtype also includes support for custom types implementing the [database/sql.Scanner] and [database/sql/driver.Valuer] interfaces. Encoding Typed Nils -pgtype encodes untyped and typed nils (e.g. nil and []byte(nil)) to the SQL NULL value without going through the Codec -system. This means that Codecs and other encoding logic do not have to handle nil or *T(nil). +pgtype encodes untyped and typed nils (e.g. nil and []byte(nil)) to the SQL NULL value without going through the [Codec] +system. This means that [Codec]s and other encoding logic do not have to handle nil or *T(nil). -However, database/sql compatibility requires Value to be called on T(nil) when T implements driver.Valuer. Therefore, -driver.Valuer values are only considered NULL when *T(nil) where driver.Valuer is implemented on T not on *T. See +However, [database/sql] compatibility requires Value to be called on T(nil) when T implements [database/sql/driver.Valuer]. Therefore, +[database/sql/driver.Valuer] values are only considered NULL when *T(nil) where [database/sql/driver.Valuer] is implemented on T not on *T. See https://github.com/golang/go/issues/8415 and https://github.com/golang/go/commit/0ce1d79a6a771f7449ec493b993ed2a720917870. @@ -159,38 +159,38 @@ example_child_records_test.go for an example. Overview of Scanning Implementation -The first step is to use the OID to lookup the correct Codec. The Map will call the Codec's PlanScan method to get a -plan for scanning into the Go value. A Codec will support scanning into one or more Go types. Oftentime these Go types -are interfaces rather than explicit types. For example, PointCodec can use any Go type that implements the PointScanner -and PointValuer interfaces. +The first step is to use the OID to lookup the correct [Codec]. The [Map] will call the [Codec.PlanScan] method to get a +plan for scanning into the Go value. A [Codec] will support scanning into one or more Go types. Oftentime these Go types +are interfaces rather than explicit types. For example, [PointCodec] can use any Go type that implements the [PointScanner] +and [PointValuer] interfaces. -If a Go value is not supported directly by a Codec then Map will try see if it is a sql.Scanner. If is then that -interface will be used to scan the value. Most sql.Scanners require the input to be in the text format (e.g. UUIDs and +If a Go value is not supported directly by a [Codec] then [Map] will try see if it is a [database/sql.Scanner]. If is then that +interface will be used to scan the value. Most [database/sql.Scanner]s require the input to be in the text format (e.g. UUIDs and numeric). However, pgx will typically have received the value in the binary format. In this case the binary value will be -parsed, reencoded as text, and then passed to the sql.Scanner. This may incur additional overhead for query results with +parsed, reencoded as text, and then passed to the [database/sql.Scanner]. This may incur additional overhead for query results with a large number of affected values. -If a Go value is not supported directly by a Codec then Map will try wrapping it with additional logic and try again. -For example, Int8Codec does not support scanning into a renamed type (e.g. type myInt64 int64). But Map will detect that +If a Go value is not supported directly by a [Codec] then [Map] will try wrapping it with additional logic and try again. +For example, [Int8Codec] does not support scanning into a renamed type (e.g. type myInt64 int64). But [Map] will detect that myInt64 is a renamed type and create a plan that converts the value to the underlying int64 type and then passes that to -the Codec (see TryFindUnderlyingTypeScanPlan). +the [Codec] (see [TryFindUnderlyingTypeScanPlan]). -These plan wrappers are contained in Map.TryWrapScanPlanFuncs. By default these contain shared logic to handle renamed +These plan wrappers are contained in [Map.TryWrapScanPlanFuncs]. By default these contain shared logic to handle renamed types, pointers to pointers, slices, composite types, etc. Additional plan wrappers can be added to seamlessly integrate types that do not support pgx directly. For example, the before mentioned https://github.com/jackc/pgx-shopspring-decimal package detects decimal.Decimal values, wraps them in something -implementing NumericScanner and passes that to the Codec. +implementing [NumericScanner] and passes that to the [Codec]. -Map.Scan and Map.Encode are convenience methods that wrap Map.PlanScan and Map.PlanEncode. Determining how to scan or +[Map.Scan] and [Map.Encode] are convenience methods that wrap [Map.PlanScan] and [Map.PlanEncode]. Determining how to scan or encode a particular type may be a time consuming operation. Hence the planning and execution steps of a conversion are internally separated. Reducing Compiled Binary Size -pgx.QueryExecModeExec and pgx.QueryExecModeSimpleProtocol require the default PostgreSQL type to be registered for each -Go type used as a query parameter. By default pgx does this for all supported types and their array variants. If an -application does not use those query execution modes or manually registers the default PostgreSQL type for the types it -uses as query parameters it can use the build tag nopgxregisterdefaulttypes. This omits the default type registration -and reduces the compiled binary size by ~2MB. +[github.com/jackc/pgx/v5.QueryExecModeExec] and [github.com/jackc/pgx/v5.QueryExecModeSimpleProtocol] require the default +PostgreSQL type to be registered for each Go type used as a query parameter. By default pgx does this for all supported +types and their array variants. If an application does not use those query execution modes or manually registers the default +PostgreSQL type for the types it uses as query parameters it can use the build tag nopgxregisterdefaulttypes. This omits +the default type registration and reduces the compiled binary size by ~2MB. */ package pgtype diff --git a/pgtype/pgtype.go b/pgtype/pgtype.go index 58f327abd..253d80966 100644 --- a/pgtype/pgtype.go +++ b/pgtype/pgtype.go @@ -156,7 +156,7 @@ const ( BinaryFormatCode = 1 ) -// A Codec converts between Go and PostgreSQL values. A Codec must not be mutated after it is registered with a Map. +// A Codec converts between Go and PostgreSQL values. A Codec must not be mutated after it is registered with a [Map]. type Codec interface { // FormatSupported returns true if the format is supported. FormatSupported(int16) bool @@ -187,7 +187,7 @@ func (e *nullAssignmentError) Error() string { return fmt.Sprintf("cannot assign NULL to %T", e.dst) } -// Type represents a PostgreSQL data type. It must not be mutated after it is registered with a Map. +// Type represents a PostgreSQL data type. It must not be mutated after it is registered with a [Map]. type Type struct { Codec Codec Name string @@ -269,7 +269,7 @@ func (m *Map) RegisterTypes(types []*Type) { } } -// RegisterType registers a data type with the Map. t must not be mutated after it is registered. +// RegisterType registers a data type with the [Map]. t must not be mutated after it is registered. func (m *Map) RegisterType(t *Type) { m.oidToType[t.OID] = t m.nameToType[t.Name] = t @@ -295,7 +295,7 @@ func (m *Map) RegisterDefaultPgType(value any, name string) { } } -// TypeForOID returns the Type registered for the given OID. The returned Type must not be mutated. +// TypeForOID returns the [Type] registered for the given OID. The returned [Type] must not be mutated. func (m *Map) TypeForOID(oid uint32) (*Type, bool) { if dt, ok := m.oidToType[oid]; ok { return dt, true @@ -305,7 +305,7 @@ func (m *Map) TypeForOID(oid uint32) (*Type, bool) { return dt, ok } -// TypeForName returns the Type registered for the given name. The returned Type must not be mutated. +// TypeForName returns the [Type] registered for the given name. The returned [Type] must not be mutated. func (m *Map) TypeForName(name string) (*Type, bool) { if dt, ok := m.nameToType[name]; ok { return dt, true @@ -324,8 +324,8 @@ func (m *Map) buildReflectTypeToType() { } } -// TypeForValue finds a data type suitable for v. Use RegisterType to register types that can encode and decode -// themselves. Use RegisterDefaultPgType to register that can be handled by a registered data type. The returned Type +// TypeForValue finds a data type suitable for v. Use [Map.RegisterType] to register types that can encode and decode +// themselves. Use [Map.RegisterDefaultPgType] to register that can be handled by a registered data type. The returned [Type] // must not be mutated. func (m *Map) TypeForValue(v any) (*Type, bool) { if m.reflectTypeToType == nil { diff --git a/pgxpool/pool.go b/pgxpool/pool.go index 8291ed820..dac8058c3 100644 --- a/pgxpool/pool.go +++ b/pgxpool/pool.go @@ -122,7 +122,7 @@ type ShouldPingParams struct { type Config struct { ConnConfig *pgx.ConnConfig - // BeforeConnect is called before a new connection is made. It is passed a copy of the underlying pgx.ConnConfig and + // BeforeConnect is called before a new connection is made. It is passed a copy of the underlying [pgx.ConnConfig] and // will not impact any existing open connections. BeforeConnect func(context.Context, *pgx.ConnConfig) error @@ -218,7 +218,7 @@ func New(ctx context.Context, connString string) (*Pool, error) { return NewWithConfig(ctx, config) } -// NewWithConfig creates a new Pool. config must have been created by [ParseConfig]. +// NewWithConfig creates a new [Pool]. config must have been created by [ParseConfig]. func NewWithConfig(ctx context.Context, config *Config) (*Pool, error) { // Default values are set in ParseConfig. Enforce initial creation by ParseConfig rather than setting defaults from // zero values. @@ -453,7 +453,7 @@ func ParseConfig(connString string) (*Config, error) { return config, nil } -// Close closes all connections in the pool and rejects future Acquire calls. Blocks until all connections are returned +// Close closes all connections in the pool and rejects future [Pool.Acquire] calls. Blocks until all connections are returned // to pool and closed. func (p *Pool) Close() { p.closeOnce.Do(func() { @@ -595,7 +595,7 @@ func (p *Pool) createIdleResources(parentCtx context.Context, targetResources in return firstError } -// Acquire returns a connection (*Conn) from the Pool +// Acquire returns a connection ([Conn]) from the [Pool]. func (p *Pool) Acquire(ctx context.Context) (c *Conn, err error) { if p.acquireTracer != nil { ctx = p.acquireTracer.TraceAcquireStart(ctx, p, TraceAcquireStartData{}) @@ -657,8 +657,8 @@ func (p *Pool) Acquire(ctx context.Context) (c *Conn, err error) { return nil, errors.New("pgxpool: too many failed attempts acquiring connection; likely bug in PrepareConn, BeforeAcquire, or ShouldPing hook") } -// AcquireFunc acquires a *Conn and calls f with that *Conn. ctx will only affect the Acquire. It has no effect on the -// call of f. The return value is either an error acquiring the *Conn or the return value of f. The *Conn is +// AcquireFunc acquires a [Conn] and calls f with that [Conn]. ctx will only affect the [Pool.Acquire]. It has no effect on the +// call of f. The return value is either an error acquiring the [Conn] or the return value of f. The [Conn] is // automatically released after the call of f. func (p *Pool) AcquireFunc(ctx context.Context, f func(*Conn) error) error { conn, err := p.Acquire(ctx) @@ -699,7 +699,7 @@ func (p *Pool) Reset() { p.p.Reset() } -// Config returns a copy of config that was used to initialize this pool. +// Config returns a copy of config that was used to initialize this [Pool]. func (p *Pool) Config() *Config { return p.config.Copy() } // Stat returns a pgxpool.Stat struct with a snapshot of Pool statistics. @@ -712,10 +712,10 @@ func (p *Pool) Stat() *Stat { } } -// Exec acquires a connection from the Pool and executes the given SQL. +// Exec acquires a connection from the [Pool] and executes the given SQL. // SQL can be either a prepared statement name or an SQL string. // Arguments should be referenced positionally from the SQL string as $1, $2, etc. -// The acquired connection is returned to the pool when the Exec function returns. +// The acquired connection is returned to the pool when the [Pool.Exec] function returns. func (p *Pool) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) { c, err := p.Acquire(ctx) if err != nil { @@ -726,15 +726,15 @@ func (p *Pool) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.C return c.Exec(ctx, sql, arguments...) } -// Query acquires a connection and executes a query that returns pgx.Rows. +// Query acquires a connection and executes a query that returns [pgx.Rows]. // Arguments should be referenced positionally from the SQL string as $1, $2, etc. -// See pgx.Rows documentation to close the returned Rows and return the acquired connection to the Pool. +// See [pgx.Rows] documentation to close the returned [pgx.Rows] and return the acquired connection to the [Pool]. // -// If there is an error, the returned pgx.Rows will be returned in an error state. -// If preferred, ignore the error returned from Query and handle errors using the returned pgx.Rows. +// If there is an error, the returned [pgx.Rows] will be returned in an error state. +// If preferred, ignore the error returned from [Pool.Query] and handle errors using the returned [pgx.Rows]. // -// For extra control over how the query is executed, the types QuerySimpleProtocol, QueryResultFormats, and -// QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely +// For extra control over how the query is executed, the types [pgx.QueryExecMode], [pgx.QueryResultFormats], and +// [pgx.QueryResultFormatsByOID] may be used as the first args to control exactly how the query is executed. This is rarely // needed. See the documentation for those types for details. func (p *Pool) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) { c, err := p.Acquire(ctx) @@ -752,16 +752,16 @@ func (p *Pool) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, er } // QueryRow acquires a connection and executes a query that is expected -// to return at most one row (pgx.Row). Errors are deferred until pgx.Row's -// Scan method is called. If the query selects no rows, pgx.Row's Scan will -// return ErrNoRows. Otherwise, pgx.Row's Scan scans the first selected row -// and discards the rest. The acquired connection is returned to the Pool when -// pgx.Row's Scan method is called. +// to return at most one row ([pgx.Row]). Errors are deferred until [pgx.Row]'s +// Scan method is called. If the query selects no rows, [pgx.Row]'s Scan will +// return [pgx.ErrNoRows]. Otherwise, [pgx.Row]'s Scan scans the first selected row +// and discards the rest. The acquired connection is returned to the [Pool] when +// [pgx.Row]'s Scan method is called. // // Arguments should be referenced positionally from the SQL string as $1, $2, etc. // -// For extra control over how the query is executed, the types QuerySimpleProtocol, QueryResultFormats, and -// QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely +// For extra control over how the query is executed, the types [pgx.QueryExecMode], [pgx.QueryResultFormats], and +// [pgx.QueryResultFormatsByOID] may be used as the first args to control exactly how the query is executed. This is rarely // needed. See the documentation for those types for details. func (p *Pool) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row { c, err := p.Acquire(ctx) @@ -783,18 +783,18 @@ func (p *Pool) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults { return &poolBatchResults{br: br, c: c} } -// Begin acquires a connection from the Pool and starts a transaction. Unlike database/sql, the context only affects the begin command. i.e. there is no -// auto-rollback on context cancellation. Begin initiates a transaction block without explicitly setting a transaction mode for the block (see BeginTx with TxOptions if transaction mode is required). -// *pgxpool.Tx is returned, which implements the pgx.Tx interface. -// Commit or Rollback must be called on the returned transaction to finalize the transaction block. +// Begin acquires a connection from the [Pool] and starts a transaction. Unlike [database/sql], the context only affects the begin command. i.e. there is no +// auto-rollback on context cancellation. Begin initiates a transaction block without explicitly setting a transaction mode for the block (see [Pool.BeginTx] with [pgx.TxOptions] if transaction mode is required). +// [*Tx] is returned, which implements the [pgx.Tx] interface. +// [Tx.Commit] or [Tx.Rollback] must be called on the returned transaction to finalize the transaction block. func (p *Pool) Begin(ctx context.Context) (pgx.Tx, error) { return p.BeginTx(ctx, pgx.TxOptions{}) } -// BeginTx acquires a connection from the Pool and starts a transaction with pgx.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. -// *pgxpool.Tx is returned, which implements the pgx.Tx interface. -// Commit or Rollback must be called on the returned transaction to finalize the transaction block. +// BeginTx acquires a connection from the [Pool] and starts a transaction with [pgx.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. +// [*Tx] is returned, which implements the [pgx.Tx] interface. +// [Tx.Commit] or [Tx.Rollback] must be called on the returned transaction to finalize the transaction block. func (p *Pool) BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error) { c, err := p.Acquire(ctx) if err != nil { @@ -820,8 +820,8 @@ func (p *Pool) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNam return c.Conn().CopyFrom(ctx, tableName, columnNames, rowSrc) } -// Ping acquires a connection from the Pool and executes an empty sql statement against it. -// If the sql returns without error, the database Ping is considered successful, otherwise, the error is returned. +// Ping acquires a connection from the [Pool] and executes an empty sql statement against it. +// If the sql returns without error, the database [Pool.Ping] is considered successful, otherwise, the error is returned. func (p *Pool) Ping(ctx context.Context) error { c, err := p.Acquire(ctx) if err != nil { diff --git a/rows.go b/rows.go index d74518de4..2c5d24245 100644 --- a/rows.go +++ b/rows.go @@ -13,12 +13,12 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) -// Rows is the result set returned from *Conn.Query. Rows must be closed before -// the *Conn can be used again. Rows are closed by explicitly calling Close(), -// calling Next() until it returns false, or when a fatal error occurs. +// Rows is the result set returned from [Conn.Query]. Rows must be closed before +// the [Conn] can be used again. Rows are closed by explicitly calling [Rows.Close], +// calling [Rows.Next] until it returns false, or when a fatal error occurs. // -// Once a Rows is closed the only methods that may be called are Close(), Err(), -// and CommandTag(). +// Once a Rows is closed the only methods that may be called are [Rows.Close], [Rows.Err], +// and [Rows.CommandTag]. // // Rows is an interface instead of a struct to allow tests to mock Query. However, // adding a method to an interface is technically a breaking change. Because of this @@ -46,9 +46,9 @@ type Rows interface { // having been read or due to an error). // // Callers should check rows.Err() after rows.Next() returns false to detect whether result-set reading ended - // prematurely due to an error. See Conn.Query for details. + // prematurely due to an error. See [Conn.Query] for details. // - // For simpler error handling, consider using the higher-level pgx v5 CollectRows() and ForEachRow() helpers instead. + // For simpler error handling, consider using the higher-level pgx v5 [CollectRows()] and [ForEachRow()] helpers instead. Next() bool // Scan reads the values from the current row into dest values positionally. dest can include pointers to core types, @@ -70,7 +70,7 @@ type Rows interface { Conn() *Conn } -// Row is a convenience wrapper over Rows that is returned by QueryRow. +// Row is a convenience wrapper over [Rows] that is returned by [Conn.QueryRow]. // // Row is an interface instead of a struct to allow tests to mock QueryRow. However, // adding a method to an interface is technically a breaking change. Because of this @@ -358,7 +358,7 @@ func (e ScanArgError) Unwrap() error { return e.Err } -// ScanRow decodes raw row data into dest. It can be used to scan rows read from the lower level pgconn interface. +// ScanRow decodes raw row data into dest. It can be used to scan rows read from the lower level [pgconn] interface. // // typeMap - OID to Go type mapping. // fieldDescriptions - OID and format of values @@ -386,8 +386,8 @@ func ScanRow(typeMap *pgtype.Map, fieldDescriptions []pgconn.FieldDescription, v return nil } -// RowsFromResultReader returns a Rows that will read from values resultReader and decode with typeMap. It can be used -// to read from the lower level pgconn interface. +// RowsFromResultReader returns a [Rows] that will read from values resultReader and decode with typeMap. It can be used +// to read from the lower level [pgconn] interface. func RowsFromResultReader(typeMap *pgtype.Map, resultReader *pgconn.ResultReader) Rows { return &baseRows{ typeMap: typeMap, @@ -460,7 +460,7 @@ func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error) { } // CollectOneRow calls fn for the first row in rows and returns the result. If no rows are found returns an error where errors.Is(ErrNoRows) is true. -// CollectOneRow is to CollectRows as QueryRow is to Query. +// CollectOneRow is to [CollectRows] as [Conn.QueryRow] is to [Conn.Query]. // // This function closes the rows automatically on return. func CollectOneRow[T any](rows Rows, fn RowToFunc[T]) (T, error) { diff --git a/tx.go b/tx.go index 571e5e00f..3f93a6f24 100644 --- a/tx.go +++ b/tx.go @@ -89,13 +89,13 @@ var ErrTxClosed = errors.New("tx is closed") // it is treated as ROLLBACK. var ErrTxCommitRollback = errors.New("commit unexpectedly resulted in rollback") -// Begin starts a transaction. Unlike database/sql, the context only affects the begin command. i.e. there is no +// Begin starts a transaction. Unlike [database/sql], the context only affects the begin command. i.e. there is no // auto-rollback on context cancellation. func (c *Conn) Begin(ctx context.Context) (Tx, error) { return c.BeginTx(ctx, TxOptions{}) } -// BeginTx starts a transaction with txOptions determining the transaction mode. Unlike database/sql, the context only +// BeginTx 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. func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) { _, err := c.Exec(ctx, txOptions.beginSQL()) @@ -385,8 +385,8 @@ func (sp *dbSimulatedNestedTx) Conn() *Conn { return sp.tx.Conn() } -// BeginFunc calls Begin on db and then calls fn. If fn does not return an error then it calls Commit on db. If fn -// returns an error it calls Rollback on db. The context will be used when executing the transaction control statements +// BeginFunc calls Begin on db and then calls fn. If fn does not return an error then it calls [Tx.Commit] on db. If fn +// returns an error it calls [Tx.Rollback] on db. The context will be used when executing the transaction control statements // (BEGIN, ROLLBACK, and COMMIT) but does not otherwise affect the execution of fn. func BeginFunc( ctx context.Context, @@ -404,8 +404,8 @@ func BeginFunc( return beginFuncExec(ctx, tx, fn) } -// BeginTxFunc calls BeginTx on db and then calls fn. If fn does not return an error then it calls Commit on db. If fn -// returns an error it calls Rollback on db. The context will be used when executing the transaction control statements +// BeginTxFunc calls BeginTx on db and then calls fn. If fn does not return an error then it calls [Tx.Commit] on db. If fn +// returns an error it calls [Tx.Rollback] on db. The context will be used when executing the transaction control statements // (BEGIN, ROLLBACK, and COMMIT) but does not otherwise affect the execution of fn. func BeginTxFunc( ctx context.Context,