Help us shape the future of Go! Take the 2026 Go Developer Survey

postgres

package module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 7, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

Sevlumen PostgreSQL

A PostgreSQL-native database/sql driver written in Go without pgx, libpq, or C dependencies.

Status: stable v1.0.0, validated on Go 1.23/current and PostgreSQL 14 through 18.

v1 scope

The stable v1 contract is intentionally focused on production service workloads such as Identity:

  • PostgreSQL protocol 3.0 over TCP;
  • TLS modes disable, require, verify-ca, and verify-full;
  • SCRAM-SHA-256, MD5, and TLS-protected cleartext authentication;
  • extended query protocol with positional parameters;
  • database/sql connector and registered stdlib driver;
  • query, exec, prepared-statement facade, transactions, and pooling through database/sql;
  • context cancellation through PostgreSQL CancelRequest;
  • structured PostgreSQL errors and SQLSTATE helpers;
  • text codecs for bool, integers, floats, numeric, text, bytea, date, timestamp, timestamptz, UUID, JSON, and JSONB;
  • PostgreSQL 14–18 compatibility matrix.

Explicitly outside v1:

  • Unix-domain sockets;
  • SCRAM-SHA-256-PLUS/channel binding;
  • protocol 3.2 variable-length cancellation keys;
  • COPY, LISTEN/NOTIFY public APIs, replication, and pipelining;
  • binary parameter/result codecs;
  • server-side prepared-statement caching.

Those exclusions do not block Identity workloads and prevent the first stable API from becoming unnecessarily broad.

Install

go get github.com/sevlumen/postgres@v1.0.0
package main

import (
    "context"
    "log"
    "time"

    postgres "github.com/sevlumen/postgres"
)

func main() {
    db, err := postgres.Open(
        "postgres://identity:password@localhost:5432/identity?sslmode=verify-full",
    )
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    db.SetMaxOpenConns(20)
    db.SetMaxIdleConns(5)
    db.SetConnMaxLifetime(30 * time.Minute)

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()

    if err := db.PingContext(ctx); err != nil {
        log.Fatal(err)
    }
}

Registered database/sql driver

import (
    "database/sql"
    _ "github.com/sevlumen/postgres/stdlib"
)

 db, err := sql.Open(
    "sevlumen-postgres",
    "postgres://identity:password@localhost:5432/identity?sslmode=require",
 )

Prefer postgres.Open or sql.OpenDB(postgres.NewConnector(...)) because these paths validate configuration before returning the pool.

Queries and parameters

var id string
var email string

err := db.QueryRowContext(
    ctx,
    `SELECT id, email FROM users WHERE email = $1`,
    "admin@example.com",
).Scan(&id, &email)

Arguments are encoded separately from SQL through PostgreSQL's extended query protocol. Do not interpolate request values into SQL strings.

Transactions

tx, err := db.BeginTx(ctx, nil)
if err != nil {
    return err
}
defer tx.Rollback()

if _, err := tx.ExecContext(ctx,
    `UPDATE refresh_tokens SET consumed_at = now()
     WHERE token_hash = $1 AND consumed_at IS NULL`, tokenHash,
); err != nil {
    return err
}

if _, err := tx.ExecContext(ctx,
    `INSERT INTO refresh_tokens(id, token_hash) VALUES($1, $2)`, id, replacementHash,
); err != nil {
    return err
}

return tx.Commit()

SQLSTATE

_, err := db.ExecContext(ctx, statement, email)
if postgres.IsUniqueViolation(err) {
    // duplicate email
}

postgres.Error exposes severity, SQLSTATE, detail, hint, schema, table, column, and constraint fields.

TLS defaults

The default is sslmode=verify-full. Production services should keep that setting and provide a certificate chain trusted by the operating system or a custom RootCAs pool.

sslmode=require encrypts the transport but does not verify the server identity. sslmode=disable should be limited to local development and isolated CI. Cleartext and MD5 password authentication are rejected on an unencrypted transport unless AllowInsecureAuthentication is explicitly enabled.

Validation

Local unit and race tests:

go vet ./...
go test -race ./...

PostgreSQL integration suite:

SEVLUMEN_POSTGRES_TEST_DSN='postgres://postgres:postgres@127.0.0.1:5432/postgres?sslmode=disable' \
  go test -race ./integration -count=1

See architecture, security boundaries, and the release checklist.

Documentation

Index

Constants

View Source
const Version = "1.1.1"

Version is the stable semantic version of the driver.

Variables

View Source
var ErrOperationOutcomeUnknown = errors.New("postgres: connection lost after operation started; outcome is unknown")

ErrOperationOutcomeUnknown means a connection failed after an operation may have reached PostgreSQL. The driver returns this instead of driver.ErrBadConn so database/sql does not retry a potentially non-idempotent statement.

Functions

func IsDeadlockDetected

func IsDeadlockDetected(err error) bool

func IsForeignKeyViolation

func IsForeignKeyViolation(err error) bool

func IsSQLState

func IsSQLState(err error, code string) bool

func IsSerializationFailure

func IsSerializationFailure(err error) bool

func IsUniqueViolation

func IsUniqueViolation(err error) bool

func Open

func Open(dsn string) (*sql.DB, error)

func OpenConfig

func OpenConfig(config Config) (*sql.DB, error)

Types

type Config

type Config struct {
	Host       string
	Port       uint16
	User       string
	Password   string
	Database   string
	TLSMode    TLSMode
	TLSConfig  *tls.Config
	RootCAs    *x509.CertPool
	ServerName string

	ConnectTimeout  time.Duration
	CancelTimeout   time.Duration
	MaxMessageSize  int32
	ApplicationName string
	RuntimeParams   map[string]string

	// AllowInsecureAuthentication permits cleartext or MD5 password authentication
	// on an unencrypted transport. It is false by default.
	AllowInsecureAuthentication bool
}

Config contains connection settings for one PostgreSQL server.

func ParseConfig

func ParseConfig(dsn string) (Config, error)

ParseConfig parses a postgres:// or postgresql:// URL.

func (*Config) Validate

func (c *Config) Validate() error

Validate normalizes defaults and rejects insecure or incomplete settings.

type Connector

type Connector struct {
	// contains filtered or unexported fields
}

Connector implements database/sql/driver.Connector.

func NewConnector

func NewConnector(config Config) (*Connector, error)

func (*Connector) Connect

func (c *Connector) Connect(ctx context.Context) (driver.Conn, error)

func (*Connector) Driver

func (c *Connector) Driver() driver.Driver

type Error

type Error struct {
	Severity         string
	SeverityNonLocal string
	Code             string
	Message          string
	Detail           string
	Hint             string
	Position         string
	InternalPosition string
	InternalQuery    string
	Where            string
	Schema           string
	Table            string
	Column           string
	DataType         string
	Constraint       string
	File             string
	Line             string
	Routine          string
}

Error is a structured PostgreSQL ErrorResponse.

func (*Error) Error

func (e *Error) Error() string

func (*Error) SQLState

func (e *Error) SQLState() string

SQLState returns the five-character PostgreSQL SQLSTATE code.

type Row added in v1.1.0

type Row interface {
	Scan(dest ...any) error
}

Row is the minimal scan surface shared by sql.Row and ORM-generated scanners.

type ScriptResult added in v1.1.0

type ScriptResult struct {
	CommandTags []string
}

ScriptResult describes the CommandComplete tags returned by a trusted SQL script in execution order.

type Session added in v1.1.0

type Session struct {
	// contains filtered or unexported fields
}

Session owns one pinned database/sql connection until Close or Discard.

Sessions are intended for PostgreSQL session-scoped operations such as advisory locks and migration execution. A Session must not be used concurrently by multiple goroutines.

func Acquire added in v1.1.0

func Acquire(ctx context.Context, db *sql.DB) (*Session, error)

Acquire obtains one pinned connection from db.

func (*Session) BeginTx added in v1.1.0

func (s *Session) BeginTx(ctx context.Context, options *sql.TxOptions) (*sql.Tx, error)

BeginTx begins a database/sql transaction on the pinned connection.

func (*Session) Close added in v1.1.0

func (s *Session) Close() error

Close returns the pinned connection to the database/sql pool.

func (*Session) Discard added in v1.1.0

func (s *Session) Discard() error

Discard permanently removes the pinned backend from the database/sql pool. It is intended for failed advisory-lock cleanup, protocol uncertainty, or any other situation where returning the backend to the pool is unsafe.

func (*Session) ExecContext added in v1.1.0

func (s *Session) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecContext executes one parameterized statement on the pinned connection.

func (*Session) ExecScriptContext added in v1.1.0

func (s *Session) ExecScriptContext(ctx context.Context, script string) (ScriptResult, error)

ExecScriptContext executes trusted, developer-authored SQL through the PostgreSQL simple-query protocol on the pinned session.

This API intentionally accepts no arguments. Request or user-controlled data must never be interpolated into script. Use ExecContext or QueryContext for parameterized application values.

func (*Session) QueryContext added in v1.1.0

func (s *Session) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

QueryContext executes one parameterized query on the pinned connection.

func (*Session) QueryRowContext added in v1.1.0

func (s *Session) QueryRowContext(ctx context.Context, query string, args ...any) Row

QueryRowContext executes one parameterized query and returns its first row.

type TLSMode

type TLSMode string

TLSMode controls PostgreSQL transport encryption and certificate checks.

const (
	TLSDisable    TLSMode = "disable"
	TLSRequire    TLSMode = "require"
	TLSVerifyCA   TLSMode = "verify-ca"
	TLSVerifyFull TLSMode = "verify-full"
)

Directories

Path Synopsis
internal
Package stdlib registers the sevlumen-postgres database/sql driver.
Package stdlib registers the sevlumen-postgres database/sql driver.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL