Convert Figma logo to code with AI

lib logopq

Pure Go Postgres driver for database/sql

9,698
936
9,698
342

Top Related Projects

15,272

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

12,820

PostgreSQL driver and toolkit for Go

sqlite3 driver for go using database/sql

Microsoft SQL server driver written in go language

39,136

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

17,325

general purpose extensions to golang's database/sql

Quick Overview

The lib/pq project is a pure Go PostgreSQL driver that provides an interface for interacting with PostgreSQL databases. It is a fork of the popular pq library, which is a pure Go PostgreSQL driver that provides an interface for interacting with PostgreSQL databases.

Pros

  • Pure Go: The lib/pq project is written entirely in Go, making it a lightweight and efficient solution for working with PostgreSQL databases.
  • Compatibility: The project is compatible with the standard database/sql package, allowing developers to use it seamlessly with existing Go applications.
  • Performance: The lib/pq project is designed to be fast and efficient, with a focus on minimizing overhead and maximizing performance.
  • Active Development: The project is actively maintained and regularly updated, ensuring that it stays up-to-date with the latest PostgreSQL features and bug fixes.

Cons

  • Limited Functionality: While the lib/pq project provides a solid foundation for working with PostgreSQL databases, it may not offer the same level of advanced functionality as some other PostgreSQL drivers.
  • Dependency Management: Depending on the size and complexity of your project, managing the dependencies of the lib/pq library may require additional effort.
  • Lack of Widespread Adoption: While the lib/pq project is a popular choice for working with PostgreSQL in Go, it may not have the same level of widespread adoption and community support as some other PostgreSQL drivers.
  • Potential Compatibility Issues: As with any third-party library, there is a risk of compatibility issues with certain versions of PostgreSQL or other dependencies.

Code Examples

Here are a few examples of how to use the lib/pq library in Go:

  1. Connecting to a PostgreSQL Database:
import (
    "database/sql"
    _ "github.com/lib/pq"
)

func main() {
    db, err := sql.Open("postgres", "user=myuser password=mypassword dbname=mydb sslmode=disable")
    if err != nil {
        panic(err)
    }
    defer db.Close()
}
  1. Executing a Query:
rows, err := db.Query("SELECT * FROM users WHERE id = $1", 1)
if err != nil {
    panic(err)
}
defer rows.Close()

for rows.Next() {
    var id int
    var name string
    if err := rows.Scan(&id, &name); err != nil {
        panic(err)
    }
    fmt.Printf("ID: %d, Name: %s\n", id, name)
}
  1. Inserting Data:
_, err := db.Exec("INSERT INTO users (name) VALUES ($1)", "John Doe")
if err != nil {
    panic(err)
}
  1. Handling Transactions:
tx, err := db.Begin()
if err != nil {
    panic(err)
}

_, err = tx.Exec("INSERT INTO users (name) VALUES ($1)", "Jane Doe")
if err != nil {
    tx.Rollback()
    panic(err)
}

if err := tx.Commit(); err != nil {
    panic(err)
}

Getting Started

To get started with the lib/pq library, you can follow these steps:

  1. Install the library using the Go package manager:
go get github.com/lib/pq
  1. Import the library in your Go code:
import (
    "database/sql"
    _ "github.com/lib/pq"
)
  1. Establish a connection to your PostgreSQL database:
db, err := sql.Open("postgres", "user=myuser password=mypassword dbname=mydb sslmode=disable")
if err != nil {
    panic(err)
}
defer db.Close()
  1. Use the db object to execute queries, insert data, and perform other database operations:
rows, err := db.Query("SELECT * FROM users")
if err != nil {
    panic(err)
}

Competitor Comparisons

15,272

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

Pros of mysql

  • Pure Go implementation, no C dependencies
  • Supports more MySQL-specific features (e.g., prepared statements)
  • Generally faster performance for MySQL databases

Cons of mysql

  • Limited to MySQL databases only
  • Less extensive type support compared to pq
  • May require more manual configuration for certain advanced features

Code Comparison

pq example:

import (
    "database/sql"
    _ "github.com/lib/pq"
)

db, err := sql.Open("postgres", "user=pqgotest dbname=pqgotest sslmode=verify-full")

mysql example:

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/dbname")

Both drivers implement the database/sql interface, making them interchangeable in many cases. The main differences lie in the connection string format and database-specific features.

pq is specifically designed for PostgreSQL and offers better support for PostgreSQL-specific types and features. It's the go-to choice for PostgreSQL users.

mysql is optimized for MySQL and MariaDB, providing better performance and support for MySQL-specific features. It's the preferred option for MySQL users.

The choice between these drivers largely depends on the database system you're using and any specific requirements of your project.

12,820

PostgreSQL driver and toolkit for Go

Pros of pgx

  • Better performance due to optimized implementation and connection pooling
  • Richer feature set, including support for custom types and COPY protocol
  • More active development and maintenance

Cons of pgx

  • Steeper learning curve due to more complex API
  • Potentially more dependencies and larger binary size
  • May require more configuration for optimal performance

Code Comparison

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

pq:

db, err := sql.Open("postgres", "postgres://username:password@localhost:5432/database_name")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

Both libraries provide PostgreSQL drivers for Go, but pgx offers more advanced features and better performance at the cost of increased complexity. pq is simpler to use and integrates well with Go's standard database/sql package, making it a good choice for basic PostgreSQL operations. However, for applications requiring high performance or advanced PostgreSQL features, pgx is generally the preferred option.

sqlite3 driver for go using database/sql

Pros of go-sqlite3

  • Lightweight and self-contained, ideal for embedded applications
  • No need for a separate database server, simplifying deployment
  • Supports both in-memory and file-based databases

Cons of go-sqlite3

  • Limited concurrency support, not suitable for high-traffic applications
  • Lacks advanced features like full-text search or geospatial data handling
  • Performance may degrade with large datasets compared to PostgreSQL

Code Comparison

go-sqlite3:

import (
    "database/sql"
    _ "github.com/mattn/go-sqlite3"
)

db, err := sql.Open("sqlite3", "./database.db")

pq:

import (
    "database/sql"
    _ "github.com/lib/pq"
)

db, err := sql.Open("postgres", "user=pqgotest dbname=pqgotest sslmode=verify-full")

Key Differences

  • go-sqlite3 uses a local file or in-memory database, while pq connects to a PostgreSQL server
  • go-sqlite3 is ideal for small to medium-sized applications, while pq is better suited for larger, more complex systems
  • pq offers more advanced features and better scalability, but requires more setup and maintenance
  • go-sqlite3 is easier to deploy and manage for simple applications, but may lack some enterprise-level features

Both libraries implement the database/sql interface, making it relatively easy to switch between them if needed. The choice between go-sqlite3 and pq depends on the specific requirements of your project, such as scalability, deployment simplicity, and feature needs.

Microsoft SQL server driver written in go language

Pros of go-mssqldb

  • Native support for Microsoft SQL Server, including specific features and optimizations
  • Better performance for MSSQL-specific operations and large result sets
  • More comprehensive support for MSSQL data types and stored procedures

Cons of go-mssqldb

  • Limited to Microsoft SQL Server, while pq supports PostgreSQL
  • Less mature and potentially less stable compared to the well-established pq
  • Smaller community and fewer third-party tools/extensions

Code Comparison

pq (PostgreSQL):

import (
    "database/sql"
    _ "github.com/lib/pq"
)

db, err := sql.Open("postgres", "user=pqgotest dbname=pqgotest sslmode=verify-full")

go-mssqldb (Microsoft SQL Server):

import (
    "database/sql"
    _ "github.com/denisenkom/go-mssqldb"
)

db, err := sql.Open("sqlserver", "server=localhost;user id=sa;password=secret;database=master")

Both libraries implement the database/sql interface, allowing for similar usage patterns. The main difference lies in the connection string format and specific features supported by each database system. go-mssqldb is tailored for MSSQL-specific functionality, while pq focuses on PostgreSQL features and optimizations.

39,136

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

Pros of gorm

  • Higher-level ORM with more features and abstractions
  • Supports multiple databases beyond PostgreSQL
  • Provides convenient methods for CRUD operations and migrations

Cons of gorm

  • Steeper learning curve due to more complex API
  • Potential performance overhead compared to raw SQL queries
  • May hide some database-specific optimizations

Code Comparison

pq (raw SQL):

rows, err := db.Query("SELECT * FROM users WHERE age > $1", 18)
for rows.Next() {
    var user User
    err := rows.Scan(&user.ID, &user.Name, &user.Age)
    // ...
}

gorm (ORM):

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

Summary

pq is a low-level PostgreSQL driver for Go, offering direct SQL execution and fine-grained control. gorm is a feature-rich ORM supporting multiple databases, providing a higher level of abstraction and convenience at the cost of some performance and complexity. pq is better suited for projects requiring raw SQL and PostgreSQL-specific optimizations, while gorm excels in rapid development and database-agnostic applications.

17,325

general purpose extensions to golang's database/sql

Pros of sqlx

  • Provides a higher-level, more feature-rich API for database operations
  • Supports multiple database drivers (PostgreSQL, MySQL, SQLite) with a unified interface
  • Offers convenient methods for scanning query results into structs and slices

Cons of sqlx

  • Slightly higher learning curve due to more advanced features
  • May have a small performance overhead compared to pq's lower-level implementation
  • Requires more dependencies, potentially increasing build times and binary size

Code Comparison

sqlx:

db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
var users []User
err = db.Select(&users, "SELECT * FROM users WHERE status = $1", "active")

pq:

db, err := sql.Open("postgres", "user=foo dbname=bar sslmode=disable")
rows, err := db.Query("SELECT * FROM users WHERE status = $1", "active")
// Manual scanning of rows required

Summary

sqlx offers a more feature-rich and convenient API for database operations, supporting multiple drivers and providing easier result scanning. However, it comes with a slightly steeper learning curve and potential performance trade-offs. pq, being a lower-level driver, offers simplicity and potentially better performance but requires more manual work for result handling. The choice between the two depends on project requirements and developer preferences.

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

pq is a Go PostgreSQL driver for database/sql.

All maintained versions of PostgreSQL are supported. Older versions may work, but this is not tested.

API docs: https://pkg.go.dev/github.com/lib/pq

Install with:

go get github.com/lib/pq@latest

Features

  • SSL
  • Handles bad connections for database/sql
  • Scan time.Time correctly (i.e. timestamp[tz], time[tz], date)
  • Scan binary blobs correctly (i.e. bytea)
  • Package for hstore support
  • COPY FROM support
  • pq.ParseURL for converting urls to connection strings for sql.Open.
  • Many libpq compatible environment variables
  • Unix socket support
  • Notifications: LISTEN/NOTIFY
  • pgpass support
  • GSS (Kerberos) auth

Running Tests

Tests need to be run against a PostgreSQL database; you can use Docker compose to start one:

docker compose up -d

This starts the latest PostgreSQL; use docker compose up -d pg«v» to start a different version.

In addition, your /etc/hosts currently needs an entry:

127.0.0.1 postgres postgres-invalid

Or you can use any other PostgreSQL instance; see testdata/init/docker-entrypoint-initdb.d for the required setup. You can use the standard PG* environment variables to control the connection details; it uses the following defaults:

PGHOST=localhost
PGDATABASE=pqgo
PGUSER=pqgo
PGSSLMODE=disable
PGCONNECT_TIMEOUT=20

PQTEST_BINARY_PARAMETERS can be used to add binary_parameters=yes to all connection strings:

PQTEST_BINARY_PARAMETERS=1 go test

Tests can be run against pgbouncer with:

docker compose up -d pgbouncer pg18
PGPORT=6432 go test ./...

and pgpool with:

docker compose up -d pgpool pg18
PGPORT=7432 go test ./...

You can use PQGO_DEBUG=1 to make the driver print the communication with PostgreSQL to stderr; this works anywhere (test or applications) and can be useful to debug protocol problems.

For example:

% PQGO_DEBUG=1 go test -run TestSimpleQuery
CLIENT → Startup                 69  "\x00\x03\x00\x00database\x00pqgo\x00user [..]"
SERVER ← (R) AuthRequest          4  "\x00\x00\x00\x00"
SERVER ← (S) ParamStatus         19  "in_hot_standby\x00off\x00"
[..]
SERVER ← (Z) ReadyForQuery        1  "I"
         START conn.query
         START conn.simpleQuery
CLIENT → (Q) Query                9  "select 1\x00"
SERVER ← (T) RowDescription      29  "\x00\x01?column?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x17\x00\x04\xff\xff\xff\xff\x00\x00"
SERVER ← (D) DataRow              7  "\x00\x01\x00\x00\x00\x011"
         END conn.simpleQuery
         END conn.query
SERVER ← (C) CommandComplete      9  "SELECT 1\x00"
SERVER ← (Z) ReadyForQuery        1  "I"
CLIENT → (X) Terminate            0  ""
PASS
ok      github.com/lib/pq       0.010s