Course › Week 4 · Concurrency and plugging into Laravel › Day 4 · lesson 25 of 42 · 45 min reading + 75 min practice
Postgres with database/sql and pgx
A connection pool, queries with placeholders, scanning rows into structs, and transactions, on your Laravel database.
A Go tool next to a Laravel app usually reads and writes the same database. There is no Eloquent: you write the SQL, and Go scans each row into variables or a struct. The standard library’s database/sql package is the interface; a driver for each database plugs into it. For Postgres that is pgx, the one third-party module of this lesson.
Today: a pool, one row, many rows, NULL, placeholders, writes, and a transaction. Every program runs on the tables Laravel’s migration below creates.
The tables
0. The Laravel side
The migration Laravel owns. The Go programs never change the schema: migrations stay in Laravel, where the rest of the team expects them.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('bookings', function (Blueprint $table) {
$table->id();
$table->string('guest');
$table->integer('nights');
$table->bigInteger('total_cents');
$table->string('status', 20)->default('pending');
$table->string('note')->nullable();
$table->timestamps();
});
Schema::create('payments', function (Blueprint $table) {
$table->id();
$table->foreignId('booking_id')->constrained();
$table->string('provider_ref')->unique();
$table->bigInteger('amount_cents');
});
}
};
id() is a bigint, so IDs are int64 in Go. integer columns are int32 in Postgres, and scan into an int fine. nullable() columns need care, as section 4 shows.
Connecting
1. A pool, from DATABASE_URL
go get github.com/jackc/pgx/v5 adds the driver to go.mod. The import _ "github.com/jackc/pgx/v5/stdlib" uses the blank identifier as the package name: nothing from the package is used by name, but importing it registers the driver as "pgx" with database/sql. That is the one common use of a blank import.
sql.Open returns a *sql.DB, which is not one connection but a pool of them, safe to share between goroutines. Open itself does not connect; PingContext does, and fails fast with a clear message if the database is not there.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
// openDB opens the pool from DATABASE_URL and checks that the database answers.
func openDB(ctx context.Context) (*sql.DB, error) {
url := os.Getenv("DATABASE_URL")
if url == "" {
return nil, errors.New("DATABASE_URL is not set")
}
db, err := sql.Open("pgx", url)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(5)
if err := db.PingContext(ctx); err != nil {
db.Close()
return nil, fmt.Errorf("connecting to the database: %w", err)
}
return db, nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
db, err := openDB(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer db.Close()
var version string
if err := db.QueryRowContext(ctx, "select current_setting('server_version')").Scan(&version); err != nil {
fmt.Fprintln(os.Stderr, "reading the version:", err)
os.Exit(1)
}
fmt.Println("connected to Postgres", version)
}
connected to Postgres 16.15 (Ubuntu 16.15-0ubuntu0.24.04.1)Run it with the same URL as Laravel’s .env: DATABASE_URL=postgres://user:password@127.0.0.1:5432/nordic go run .. Laravel splits it into DB_HOST, DB_PORT and friends; the URL form is what Go tools expect.
SetMaxOpenConns(5) caps the pool. Postgres has a connection limit shared by Laravel’s workers too, so a Go tool should never open as many as it likes. Every call takes the ctx (the context lesson), so the 5-second budget covers connecting and every query.
Reading
2. One row, and sql.ErrNoRows
QueryRowContext runs a query that returns at most one row; Scan copies its columns, in order, into the variables you point to. No row at all is the error sql.ErrNoRows.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
// openDB opens the pool from DATABASE_URL and checks that the database answers.
func openDB(ctx context.Context) (*sql.DB, error) {
url := os.Getenv("DATABASE_URL")
if url == "" {
return nil, errors.New("DATABASE_URL is not set")
}
db, err := sql.Open("pgx", url)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(5)
if err := db.PingContext(ctx); err != nil {
db.Close()
return nil, fmt.Errorf("connecting to the database: %w", err)
}
return db, nil
}
func bookingGuest(ctx context.Context, db *sql.DB, id int64) (string, int, error) {
var guest string
var nights int
err := db.QueryRowContext(ctx, "select guest, nights from bookings where id = $1", id).Scan(&guest, &nights)
if err != nil {
return "", 0, fmt.Errorf("reading booking %d: %w", id, err)
}
return guest, nights, nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
db, err := openDB(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer db.Close()
for _, id := range []int64{2, 99} {
guest, nights, err := bookingGuest(ctx, db, id)
if errors.Is(err, sql.ErrNoRows) {
fmt.Println("booking", id, "does not exist")
continue
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println("booking", id, "is", guest, "for", nights, "nights")
}
}
booking 2 is Omar for 7 nights
booking 99 does not exist$1 is a placeholder: the value id is sent separately from the SQL, so it can never change the query. Never build SQL with fmt.Sprintf: that is SQL injection, exactly as with string concatenation in PHP. Postgres numbers its placeholders $1, $2…; MySQL drivers use ?.
The error is wrapped with %w, so errors.Is(err, sql.ErrNoRows) still finds it in main. “Not found” is a normal answer here, not a failure: Laravel’s find() returns null, findOrFail() throws.
3. Many rows, into structs
QueryContext returns *sql.Rows. Loop with rows.Next(), Scan each row, close the rows, and check rows.Err() after the loop, the same pattern as bufio.Scanner (the logstat build day).
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
// openDB opens the pool from DATABASE_URL and checks that the database answers.
func openDB(ctx context.Context) (*sql.DB, error) {
url := os.Getenv("DATABASE_URL")
if url == "" {
return nil, errors.New("DATABASE_URL is not set")
}
db, err := sql.Open("pgx", url)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(5)
if err := db.PingContext(ctx); err != nil {
db.Close()
return nil, fmt.Errorf("connecting to the database: %w", err)
}
return db, nil
}
type Booking struct {
ID int64
Guest string
Nights int
TotalCents int64
}
func pendingBookings(ctx context.Context, db *sql.DB) ([]Booking, error) {
rows, err := db.QueryContext(ctx, "select id, guest, nights, total_cents from bookings where status = $1 order by id", "pending")
if err != nil {
return nil, fmt.Errorf("listing pending bookings: %w", err)
}
defer rows.Close()
var bookings []Booking
for rows.Next() {
var b Booking
if err := rows.Scan(&b.ID, &b.Guest, &b.Nights, &b.TotalCents); err != nil {
return nil, fmt.Errorf("reading a pending booking: %w", err)
}
bookings = append(bookings, b)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("listing pending bookings: %w", err)
}
return bookings, nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
db, err := openDB(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer db.Close()
bookings, err := pendingBookings(ctx, db)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
for _, b := range bookings {
fmt.Printf("%+v\n", b)
}
}
{ID:2 Guest:Omar Nights:7 TotalCents:105070}
{ID:3 Guest:Sara Nights:2 TotalCents:30020}defer rows.Close() gives the connection back to the pool however the function returns. Forget it after an early return, and the pool slowly runs dry.
The struct’s fields are scanned by position, matching the select. A column added to the query without a matching &b.… is an error at runtime, not compile time, so keep the two side by side.
4. A NULL column
note is nullable(). Scanning a NULL into a string fails, because a string has no “no value”:
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
// openDB opens the pool from DATABASE_URL and checks that the database answers.
func openDB(ctx context.Context) (*sql.DB, error) {
url := os.Getenv("DATABASE_URL")
if url == "" {
return nil, errors.New("DATABASE_URL is not set")
}
db, err := sql.Open("pgx", url)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(5)
if err := db.PingContext(ctx); err != nil {
db.Close()
return nil, fmt.Errorf("connecting to the database: %w", err)
}
return db, nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
db, err := openDB(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer db.Close()
var note string
if err := db.QueryRowContext(ctx, "select note from bookings where id = $1", 1).Scan(¬e); err != nil {
fmt.Fprintln(os.Stderr, "reading the note:", err)
os.Exit(1)
}
fmt.Println("note:", note)
}
reading the note: sql: Scan error on column index 0, name "note": converting NULL to string is unsupported
exit status 1Scan into a pointer instead: NULL leaves it nil, a value points to it. It is the same idea as the optional JSON field in the JSON lesson.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
// openDB opens the pool from DATABASE_URL and checks that the database answers.
func openDB(ctx context.Context) (*sql.DB, error) {
url := os.Getenv("DATABASE_URL")
if url == "" {
return nil, errors.New("DATABASE_URL is not set")
}
db, err := sql.Open("pgx", url)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(5)
if err := db.PingContext(ctx); err != nil {
db.Close()
return nil, fmt.Errorf("connecting to the database: %w", err)
}
return db, nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
db, err := openDB(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer db.Close()
for _, id := range []int64{1, 2} {
var note *string
if err := db.QueryRowContext(ctx, "select note from bookings where id = $1", id).Scan(¬e); err != nil {
fmt.Fprintln(os.Stderr, "reading the note:", err)
os.Exit(1)
}
if note == nil {
fmt.Println(id, "has no note")
continue
}
fmt.Println(id, "note:", *note)
}
}
1 has no note
2 note: Late check-indatabase/sql also has sql.Null[string], a struct with V and Valid fields; it does the same job without a pointer. Pick one style per project. When a NULL should simply read as "", say so in SQL instead: coalesce(note, '').
Writing
5. Exec, RowsAffected and RETURNING
ExecContext runs a statement that returns no rows; its result tells you how many rows it changed. For an insert, returning id turns it into a query that returns the new ID.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
// openDB opens the pool from DATABASE_URL and checks that the database answers.
func openDB(ctx context.Context) (*sql.DB, error) {
url := os.Getenv("DATABASE_URL")
if url == "" {
return nil, errors.New("DATABASE_URL is not set")
}
db, err := sql.Open("pgx", url)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(5)
if err := db.PingContext(ctx); err != nil {
db.Close()
return nil, fmt.Errorf("connecting to the database: %w", err)
}
return db, nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
db, err := openDB(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer db.Close()
result, err := db.ExecContext(ctx, "update bookings set status = 'confirmed', updated_at = now() where id = $1 and status = 'pending'", 2)
if err != nil {
fmt.Fprintln(os.Stderr, "confirming booking 2:", err)
os.Exit(1)
}
changed, err := result.RowsAffected()
if err != nil {
fmt.Fprintln(os.Stderr, "confirming booking 2:", err)
os.Exit(1)
}
fmt.Println("rows changed:", changed)
var id int64
err = db.QueryRowContext(ctx,
"insert into bookings (guest, nights, total_cents, created_at, updated_at) values ($1, $2, $3, now(), now()) returning id",
"Youssef", 14, 196140,
).Scan(&id)
if err != nil {
fmt.Fprintln(os.Stderr, "creating the booking:", err)
os.Exit(1)
}
fmt.Println("new booking:", id)
}
rows changed: 1
new booking: 4where … and status = 'pending' makes the update safe to run twice: the second time it changes 0 rows, and RowsAffected says so. Checking it is how a Go tool notices that someone else already processed a row.
Laravel fills created_at and updated_at for you; plain SQL does not, so the queries set them with now(). A long query string can go on its own line inside the call’s parentheses, as here.
6. A transaction
db.BeginTx starts a transaction and returns a *sql.Tx with the same query methods. defer tx.Rollback() right after it undoes everything if the function returns early; after a successful Commit, the deferred Rollback does nothing.
Here the second payment reuses a provider reference that already exists, so the unique index rejects it, and the booking’s status change before it is rolled back too.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"time"
"github.com/jackc/pgx/v5/pgconn"
_ "github.com/jackc/pgx/v5/stdlib"
)
// openDB opens the pool from DATABASE_URL and checks that the database answers.
func openDB(ctx context.Context) (*sql.DB, error) {
url := os.Getenv("DATABASE_URL")
if url == "" {
return nil, errors.New("DATABASE_URL is not set")
}
db, err := sql.Open("pgx", url)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(5)
if err := db.PingContext(ctx); err != nil {
db.Close()
return nil, fmt.Errorf("connecting to the database: %w", err)
}
return db, nil
}
// recordPayment marks the booking paid and stores the payment, both or neither.
func recordPayment(ctx context.Context, db *sql.DB, bookingID int64, providerRef string, cents int64) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, "update bookings set status = 'paid', updated_at = now() where id = $1", bookingID); err != nil {
return fmt.Errorf("marking booking %d paid: %w", bookingID, err)
}
if _, err := tx.ExecContext(ctx, "insert into payments (booking_id, provider_ref, amount_cents) values ($1, $2, $3)", bookingID, providerRef, cents); err != nil {
return fmt.Errorf("storing payment %s: %w", providerRef, err)
}
return tx.Commit()
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
db, err := openDB(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer db.Close()
err = recordPayment(ctx, db, 3, "pi_3QX2", 30020)
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
fmt.Println("duplicate payment, nothing saved:", pgErr.ConstraintName)
} else if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
var status string
if err := db.QueryRowContext(ctx, "select status from bookings where id = 3").Scan(&status); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println("booking 3 is still", status)
}
duplicate payment, nothing saved: payments_provider_ref_unique
booking 3 is still pending*pgconn.PgError is pgx’s error type for an error Postgres reported; 23505 is Postgres’s code for a unique violation, the case Laravel shows as UniqueConstraintViolationException. errors.As finds it through the wrapping (the error-wrapping lesson).
The deferred Rollback’s error is ignored on purpose: after a Commit it always returns sql.ErrTxDone, and after a failure the transaction is being abandoned anyway. It is DB::transaction(function () { … }), written out.
Coming from PHP
<?php
$booking = Booking::find(2); // null when missing: sql.ErrNoRows
DB::transaction(function () use ($booking, $ref, $cents) {
$booking->update(['status' => 'paid']);
$booking->payments()->create(['provider_ref' => $ref, 'amount_cents' => $cents]);
});
Eloquent writes the SQL, maps columns to properties, fills timestamps and casts NULL to null for you. In Go each of those is a line you write: the query, the Scan, now(), a pointer for a nullable column. The gain is that every query the tool runs is in front of you, and none runs unless you wrote it.
Libraries like sqlc (Go code generated from SQL files) and ORMs like GORM exist; for a tool next to a Laravel app, plain database/sql is usually all it needs, and Laravel keeps the migrations.
PracticeThe official database tutorial; one report
Read Tutorial: Accessing a relational database on go.dev. It uses MySQL and ? placeholders; everything else is the same as today.
Exercise: revenue per status
Write revenueByStatus(ctx, db) (map[string]int64, error) that runs one select status, sum(total_cents) … group by status and returns the totals. Print them sorted by status (the closures lesson has the one-liner). Then add a booking with a NULL total_cents column by changing the schema in a scratch database: what does sum do with it, and what does your Scan need?
Remember
- One
*sql.DBpool per program, capped withSetMaxOpenConns, every call withContext. - Always
$1placeholders, neverfmt.Sprintfinto SQL. defer rows.Close(), checkrows.Err(), and scan nullable columns into pointers.- A batch of writes is one transaction with
defer tx.Rollback().
Tomorrow: errgroup for many tasks that can fail, limits on how many run at once, and the race detector.