Convert Figma logo to code with AI

jackc logopgx

PostgreSQL driver and toolkit for Go

10,313
815
10,313
196

Top Related Projects

5,649

Golang ORM with focus on PostgreSQL features and performance

9,003

Pure Go Postgres driver for database/sql

15,960

general purpose extensions to golang's database/sql

36,491

The fantastic ORM library for Golang, aims to be developer friendly

Microsoft SQL server driver written in go language

14,442

Go MySQL Driver is a MySQL driver for Go's (golang) database/sql package

Quick Overview

pgx is a pure Go driver and toolkit for PostgreSQL. It aims to be low-level, fast, and performant while also providing high-level features and a developer-friendly API. pgx supports the latest PostgreSQL features and focuses on taking full advantage of PostgreSQL's capabilities.

Pros

  • High performance with optimized, low-level implementation
  • Extensive feature set, including support for advanced PostgreSQL features
  • Supports both database/sql and direct usage
  • Active development and community support

Cons

  • Steeper learning curve compared to simpler drivers
  • May be overkill for simple applications
  • Some features require direct usage instead of database/sql interface
  • Documentation can be overwhelming for beginners

Code Examples

Connecting to a database:

conn, err := pgx.Connect(context.Background(), "postgres://username:password@localhost:5432/database_name")
if err != nil {
    log.Fatal(err)
}
defer conn.Close(context.Background())

Executing a query and scanning results:

var name string
var age int
err := conn.QueryRow(context.Background(), "SELECT name, age FROM users WHERE id=$1", 1).Scan(&name, &age)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Name: %s, Age: %d\n", name, age)

Using a prepared statement:

stmt, err := conn.Prepare(context.Background(), "insert_user", "INSERT INTO users(name, age) VALUES($1, $2)")
if err != nil {
    log.Fatal(err)
}
_, err = conn.Exec(context.Background(), "insert_user", "John Doe", 30)
if err != nil {
    log.Fatal(err)
}

Getting Started

  1. Install pgx:

    go get github.com/jackc/pgx/v5
    
  2. Import pgx in your Go code:

    import (
        "context"
        "github.com/jackc/pgx/v5"
    )
    
  3. Connect to a PostgreSQL database:

    conn, err := pgx.Connect(context.Background(), "postgres://username:password@localhost:5432/database_name")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close(context.Background())
    
  4. Start using pgx to interact with your database!

Competitor Comparisons

5,649

Golang ORM with focus on PostgreSQL features and performance

Pros of pg

  • Offers an ORM-like interface for easier database interactions
  • Provides automatic query result mapping to structs
  • Includes a query builder for constructing complex SQL queries

Cons of pg

  • Less focus on low-level driver functionality
  • May have slightly higher overhead due to ORM-like features
  • Smaller community and fewer contributors compared to pgx

Code Comparison

pg:

db := pg.Connect(&pg.Options{
    User:     "user",
    Password: "pass",
    Database: "db",
})

var users []User
err := db.Model(&users).Where("active = ?", true).Select()

pgx:

conn, err := pgx.Connect(context.Background(), "postgres://user:pass@localhost:5432/db")
if err != nil {
    log.Fatal(err)
}

rows, _ := conn.Query(context.Background(), "SELECT * FROM users WHERE active = $1", true)

Both pgx and pg are popular PostgreSQL drivers for Go, each with its own strengths. pgx focuses on being a low-level driver with high performance, while pg provides more high-level abstractions and ORM-like features. The choice between them depends on the specific needs of your project, such as performance requirements, ease of use, and desired level of abstraction.

9,003

Pure Go Postgres driver for database/sql

Pros of pq

  • Widely adopted and well-established in the Go ecosystem
  • Simple and straightforward API for basic PostgreSQL operations
  • Lightweight with minimal dependencies

Cons of pq

  • Limited support for advanced PostgreSQL features
  • No built-in connection pooling
  • Less performant compared to pgx for high-concurrency scenarios

Code Comparison

pq:

db, err := sql.Open("postgres", "postgres://user:password@localhost/dbname")
rows, err := db.Query("SELECT * FROM users WHERE id = $1", id)

pgx:

conn, err := pgx.Connect(context.Background(), "postgres://user:password@localhost/dbname")
rows, err := conn.Query(context.Background(), "SELECT * FROM users WHERE id = $1", id)

Key Differences

  • pgx offers better performance and more advanced features
  • pq uses database/sql interface, while pgx has its own API (but can also work with database/sql)
  • pgx provides built-in connection pooling and more PostgreSQL-specific functionality
  • pq is more suitable for simple applications, while pgx is better for complex, high-performance systems

Conclusion

While pq is a solid choice for basic PostgreSQL operations in Go, pgx offers superior performance and more advanced features. The choice between the two depends on the specific requirements of your project, with pgx being the preferred option for more demanding applications.

15,960

general purpose extensions to golang's database/sql

Pros of sqlx

  • Database-agnostic: Supports multiple databases (PostgreSQL, MySQL, SQLite)
  • Simpler API: Easier to use for basic database operations
  • Lightweight: Smaller codebase and fewer dependencies

Cons of sqlx

  • Less PostgreSQL-specific features: Lacks some advanced Postgres functionalities
  • Performance: Generally slower than pgx for PostgreSQL operations
  • Limited support for custom types: Less flexible with user-defined types

Code Comparison

sqlx:

rows, err := db.Query("SELECT name FROM users WHERE id = $1", id)
var name string
if rows.Next() {
    err = rows.Scan(&name)
}

pgx:

var name string
err := conn.QueryRow(context.Background(), "SELECT name FROM users WHERE id = $1", id).Scan(&name)

Both pgx and sqlx are popular Go database libraries, but they serve different purposes. sqlx is a general-purpose database library that supports multiple database systems, while pgx is specifically designed for PostgreSQL and offers more advanced features and better performance for Postgres operations. The choice between them depends on your specific project requirements and the database system you're using.

36,491

The fantastic ORM library for Golang, aims to be developer friendly

Pros of gorm

  • Higher-level abstraction with ORM features, simplifying database operations
  • Supports multiple databases beyond PostgreSQL (MySQL, SQLite, etc.)
  • Provides automatic migrations and schema management

Cons of gorm

  • Performance overhead due to ORM layer and reflection
  • Less flexibility for complex queries compared to raw SQL
  • Steeper learning curve for gorm-specific conventions and APIs

Code Comparison

pgx example:

rows, err := conn.Query(context.Background(), "SELECT id, name FROM users WHERE age > $1", 18)
for rows.Next() {
    var id int, name string
    err := rows.Scan(&id, &name)
    // Process results
}

gorm example:

var users []User
db.Where("age > ?", 18).Find(&users)
for _, user := range users {
    // Process results
}

Summary

pgx is a low-level PostgreSQL driver focusing on performance and PostgreSQL-specific features. It offers more control and efficiency for PostgreSQL-specific applications. gorm, on the other hand, is a full-featured ORM that supports multiple databases and provides higher-level abstractions. It simplifies database operations but may introduce performance overhead and limit flexibility for complex queries. The choice between pgx and gorm depends on the specific requirements of your project, such as database type, performance needs, and development speed priorities.

Microsoft SQL server driver written in go language

Pros of go-mssqldb

  • Native support for Microsoft SQL Server, including specific features and data types
  • Implements the database/sql interface, making it familiar for Go developers
  • Supports Windows authentication

Cons of go-mssqldb

  • Less active development and fewer contributors compared to pgx
  • Limited additional features beyond basic database/sql functionality
  • May have performance limitations for high-throughput scenarios

Code Comparison

go-mssqldb:

db, err := sql.Open("mssql", "server=localhost;user id=sa;password=secret")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

pgx:

conn, err := pgx.Connect(context.Background(), "postgres://username:password@localhost:5432/database_name")
if err != nil {
    log.Fatal(err)
}
defer conn.Close(context.Background())

Key Differences

  • pgx offers more advanced features like automatic statement preparation and custom type handling
  • go-mssqldb focuses on SQL Server compatibility, while pgx is PostgreSQL-specific
  • pgx provides both a database/sql driver and a native interface, offering more flexibility
  • Performance benchmarks generally favor pgx for PostgreSQL operations

Conclusion

Choose go-mssqldb for SQL Server projects or when Windows authentication is required. Opt for pgx when working with PostgreSQL and seeking enhanced performance and features beyond the standard database/sql interface.

14,442

Go MySQL Driver is a MySQL driver for Go's (golang) database/sql package

Pros of mysql

  • Simpler API, easier to get started for beginners
  • Wider adoption and community support
  • Better compatibility with older MySQL versions

Cons of mysql

  • Less feature-rich compared to pgx
  • Lower performance in some scenarios
  • Lacks advanced PostgreSQL-specific features

Code Comparison

mysql:

db, err := sql.Open("mysql", "user:password@/dbname")
rows, err := db.Query("SELECT * FROM users WHERE id = ?", 1)

pgx:

conn, err := pgx.Connect(context.Background(), "postgres://user:password@localhost:5432/dbname")
rows, err := conn.Query(context.Background(), "SELECT * FROM users WHERE id = $1", 1)

The main differences in the code are:

  1. Connection string format
  2. Use of context in pgx
  3. Placeholder syntax (? vs $1)

pgx offers more advanced features and better performance for PostgreSQL, while mysql provides a simpler interface and broader MySQL version support. Choose based on your specific database and project requirements.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Go Reference Build Status

pgx - PostgreSQL Driver and Toolkit

pgx is a pure Go driver and toolkit for PostgreSQL.

The pgx driver is a low-level, high performance interface that exposes PostgreSQL-specific features such as LISTEN / NOTIFY and COPY. It also includes an adapter for the standard database/sql interface.

The toolkit component is a related set of packages that implement PostgreSQL functionality such as parsing the wire protocol and type mapping between PostgreSQL and Go. These underlying packages can be used to implement alternative drivers, proxies, load balancers, logical replication clients, etc.

Example Usage

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)
}

See the getting started guide for more information.

Features

  • Support for approximately 70 different PostgreSQL types
  • Automatic statement preparation and caching
  • Batch queries
  • Single-round trip query mode
  • Full TLS connection control
  • Binary format support for custom types (allows for much quicker encoding/decoding)
  • COPY protocol support for faster bulk data loads
  • Tracing and logging support
  • Connection pool with after-connect hook for arbitrary connection setup
  • LISTEN / NOTIFY
  • Conversion of PostgreSQL arrays to Go slice mappings for integers, floats, and strings
  • hstore support
  • json and jsonb support
  • Maps inet and cidr PostgreSQL types to netip.Addr and netip.Prefix
  • Large object support
  • NULL mapping to pointer to pointer
  • Supports database/sql.Scanner and database/sql/driver.Valuer interfaces for custom types
  • Notice response handling
  • Simulated nested transactions with savepoints

Choosing Between the pgx and database/sql Interfaces

The pgx interface is faster. Many PostgreSQL specific features such as LISTEN / NOTIFY and COPY are not available through the database/sql interface.

The pgx interface is recommended when:

  1. The application only targets PostgreSQL.
  2. No other libraries that require database/sql are in use.

It is also possible to use the database/sql interface and convert a connection to the lower-level pgx interface as needed.

Testing

See CONTRIBUTING.md for setup instructions.

Architecture

See the presentation at Golang Estonia, PGX Top to Bottom for a description of pgx architecture.

Supported Go and PostgreSQL Versions

pgx supports the same versions of Go and PostgreSQL that are supported by their respective teams. For Go that is the two most recent major releases and for PostgreSQL the major releases in the last 5 years. This means pgx supports Go 1.21 and higher and PostgreSQL 12 and higher. pgx also is tested against the latest version of CockroachDB.

Version Policy

pgx follows semantic versioning for the documented public API on stable releases. v5 is the latest stable major version.

PGX Family Libraries

github.com/jackc/pglogrepl

pglogrepl provides functionality to act as a client for PostgreSQL logical replication.

github.com/jackc/pgmock

pgmock offers the ability to create a server that mocks the PostgreSQL wire protocol. This is used internally to test pgx by purposely inducing unusual errors. pgproto3 and pgmock together provide most of the foundational tooling required to implement a PostgreSQL proxy or MitM (such as for a custom connection pooler).

github.com/jackc/tern

tern is a stand-alone SQL migration system.

github.com/jackc/pgerrcode

pgerrcode contains constants for the PostgreSQL error codes.

Adapters for 3rd Party Types

Adapters for 3rd Party Tracers

Adapters for 3rd Party Loggers

These adapters can be used with the tracelog package.

3rd Party Libraries with PGX Support

github.com/pashagolub/pgxmock

pgxmock is a mock library implementing pgx interfaces. pgxmock has one and only purpose - to simulate pgx behavior in tests, without needing a real database connection.

github.com/georgysavva/scany

Library for scanning data from a database into Go structs and more.

github.com/vingarcia/ksql

A carefully designed SQL client for making using SQL easier, more productive, and less error-prone on Golang.

https://github.com/otan/gopgkrb5

Adds GSSAPI / Kerberos authentication support.

github.com/wcamarao/pmx

Explicit data mapping and scanning library for Go structs and slices.

github.com/stephenafamo/scan

Type safe and flexible package for scanning database data into Go types. Supports, structs, maps, slices and custom mapping functions.

https://github.com/z0ne-dev/mgx

Code first migration library for native pgx (no database/sql abstraction).