kataras/pg

A Go library for PostgreSQL (16 and 18 are tested in CI). You declare entities as structs with pg tags, register them in a schema, and perform CRUD operations through a repository pattern. It also handles database connections, schema creation and verification, and query generation and execution, so you write concise, readable code against PostgreSQL.
🤖 Ask AI about pg. Google's free Code Wiki for pg is generated from this repository and stays in sync with it, commit by commit. Browse the architecture with diagrams, or ask its chat plain-language questions about the codebase and get answers grounded in the actual source. For an assistant that writes pg code with you, Plexon AI, the desktop assistant built by the author of pg, ships the pg skill built in; see AI Tools for pg below.
📚 The pg Book
A preface, 16 chapters and an epilogue, every code example verified against the library source. Each chapter opens with a plain-language background for newcomers and closes with curated further reading, and the book explains not just what each API does but why it is shaped the way it is.
Read the PDF (165 pages), or start with the preface and read the chapters as Markdown:
The book is rebuilt from its own module: cd book && go run .. See book/README_EBOOK.md.
💻 Installation
The only requirement is the Go Programming Language, version 1.27 or newer.
Create a new project
$ mkdir myapp
$ cd myapp
$ go mod init myapp
$ go get github.com/kataras/pg@latest
Install on existing project
$ cd myapp
$ go get github.com/kataras/pg@latest
Run
$ go mod tidy
$ go run .
📖 Example
PG contains extensive and thorough documentation making it easy to get started with the library.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/kataras/pg"
)
// Base is a struct that contains common fields for all entities.
type Base struct {
ID string `pg:"type=uuid,primary"` // UUID as primary key
CreatedAt time.Time `pg:"type=timestamp,default=clock_timestamp()"` // Timestamp of creation
UpdatedAt time.Time `pg:"type=timestamp,default=clock_timestamp()"` // Last update
}
// Customer is a struct that represents a customer entity.
type Customer struct {
Base // Embed Base struct
Firstname string `pg:"type=varchar(255)"` // First name of the customer
}
func main() {
// Default value for struct field tag `pg`.
// It can be modified to a custom one as well, e.g.
// pg.SetDefaultTag("db")
// Create Schema instance.
schema := pg.NewSchema()
// First argument is the table name, second is the struct entity.
schema.MustRegister("customers", Customer{})
// Create Database instance.