Skip to content

database/sql & pgx: Connections, Prepared Statements, Transactions, Repository Pattern ​

"DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines." — سورس بستهٔ database/sql، توضیح نوع DB (Go 1.27)

خلاصه (Summary): این صفحه نشان می‌دهد سرویس Go چگونه درست با PostgreSQL کار می‌کند: database/sql و مخزن اتصال (Connection pool)، driverهای pgx stdlib، lib/pq و go-sql-driver/mysql، query و خواندن نتیجه، NULL، جای‌نگهدار (Placeholder)، دستور آماده (Prepared statement) و cache آن در pgx، تراکنش (Transaction) با الگوی defer-Rollback و تلاش مجدد (Retry)، API بومی pgx v5 شامل pgxpool، CollectRows، batch، COPY و LISTEN/NOTIFY، تشخیص خطا با SQLSTATE، timeout و لایهٔ repository که این جزئیات را از کد دامنه دور نگه می‌دارد. تمرکز (Focus): sql.Open اتصال را به تعویق می‌اندازد و *sql.DB یک pool است؛ چهار تنظیم pool را کنار چرخهٔ QueryContext/QueryRowContext/ExecContext و rows.Next/Scan/Err/Close بررسی می‌کنیم. سپس sql.ErrNoRows، نمایش NULL با sql.NullString، sql.Null[T] و pointer، تفاوت $1 و ?، Stmt و prepare ضمنی روی هر اتصال، QueryExecMode در pgx، BeginTx و سطح جداسازی، Commit/Rollback و لغو ctx را می‌بینیم. تشخیص خطا با pgconn.PgError و SQLSTATEهای 40001/23505/57014، تنظیم pgxpool.Config، حالت transaction در PgBouncer و انتخاب repository، sqlc، ORM، migration، تست و مشاهده‌پذیری ادامهٔ مسیرند. هدف یادگیری (Learning goal): هنگام راه‌اندازی برای هر پایگاه داده یک pool با اندازهٔ حساب‌شده بسازید؛ queryهایی بنویسید که اتصال نشت ندهند و خطا را نبلعند؛ تغییرهای چنددستوری را در یک Transaction اجرا کنید که در هر خروج ناموفق rollback شود و در شکست serialization دوباره اجرا شود. بتوانید با دلیل بین database/sql و pgx بومی انتخاب کنید و با دیدن SQLSTATE 40001، context deadline exceeded یا prepared statement "stmtcache_..." does not exist بدانید کدام بخش باید تغییر کند.

موضوع این صفحه سمت Go در دسترسی به دادهٔ رابطه‌ای است: بستهٔ database/sql، driver و ابزارهای pgx و الگوهای کد روی آن‌ها. نظریهٔ پایگاه داده در صفحات همسایه است: اندازه‌گذاری pool نسبت به max_connections و poolerها در Connection Pooling، تضمین Transaction در ACID & Transactions، ناهنجاری‌های هر سطح در Isolation Levels، lazy loading و N+1 در ORM Pitfalls، راهبرد expand/contract و تغییر بدون قطعی در Schema Migrations و خود سرور در PostgreSQL Fundamentals. برای context، deadline و واکنش pgx به لغو، context را ببینید؛ interface و fake در Mocking with Interfaces & DI، نقش repository در DDD در Repositories، ثبت event همراه تغییر داده در Outbox Pattern و یک سرویس کامل HTTP در A REST API in Go آمده است.

مبنای بررسی مطالب، سورس کتابخانهٔ استاندارد Go 1.27 (database/sql، database/sql/driver)، راهنماهای «Accessing relational databases» در go.dev، یادداشت‌های انتشار Go 1.8، 1.10، 1.13، 1.15، 1.17 و 1.22 و فایل‌های api/go1.N.txt است. برای pgx از سورس tag نسخهٔ v5.8.0 شامل doc.go، conn.go، rows.go، named_args.go، batch.go، copy_from.go، tx.go، tracer.go، pgxpool، stdlib و pgconn، CHANGELOG تا 5.13.0 و ویکی استفاده شده است. مستندات جاری PostgreSQL دربارهٔ isolation، PREPARE، COPY، LISTEN/NOTIFY، تنظیمات کلاینت، خطاها و پروتکل، صفحات تنظیمات و قابلیت‌ها و changelog در PgBouncer و READMEهای lib/pq، go-sql-driver/mysql، sqlc، golang-migrate، goose، tern، bun، squirrel، goqu، otelsql، otelpgx، pgxmock، sqlmock و dockertest نیز مبنا هستند. snippetها go 1.24 اعلام می‌کنند و github.com/jackc/pgx/v5 v5.8.0 را pin کرده‌اند؛ آخرین نسخه‌ای که go.mod آن 1.24 است، چون از 5.9.0 به بعد Go 1.25 لازم است. این pin فقط متعلق به همین ماژول است: pgx 5.12.0 تزریق SQL در batchهای simple protocol و دور زدن احراز هویت را اصلاح کرد؛ کد production روی Go 1.25+ باید آخرین 5.x را به کار ببرد. snippetها روی Go 1.27.4 در macOS کامپایل، vet و با -race تست شده‌اند. ماشین ساخت PostgreSQL ندارد؛ تست‌ها از driver کوچک جعلی database/sql و مسیرهای بدون سرور pgx استفاده می‌کنند. آزمایش‌های نیازمند سرور با «خروجی مورد انتظار؛ اجرا نشده» مشخص‌اند.

نقشهٔ صفحه (Page map) ​

اگر دنبال این هستیدبروید به
جدول‌هایی برای مرور در یک دقیقههمه‌چیز در یک دقیقه
چرا pool و رابط driver لازم‌اندچرا وجود دارد
تاریخچه به تفکیک نسخهاز کجا آمده
repository مشکل‌دار و اصلاح آنGo
چرا sql.Open تنبل است و DB یک pool است و Ping چه می‌کندباز کردن پایگاه داده
کنترل ظرفیت و عمر اتصال با SetMaxOpenConns، SetMaxIdleConns، SetConnMaxLifetime و SetConnMaxIdleTimeتنظیمات pool
انتخاب میان pgx stdlib، lib/pq قدیمی و go-sql-driver/mysqlDriverها
انتخاب QueryContext/QueryRowContext/ExecContext و چرخهٔ rows.Next/Scan/Err/Closeاجرای query
برخورد درست با sql.ErrNoRowsوقتی سطری نیست
نمایش NULL با sql.NullString، sql.Null[T] در 1.22 و pointerNULL
تفاوت $1 و ? و جلوگیری از SQL injectionجای‌نگهدارها
عمر prepared statement، Stmt و prepare ضمنی روی هر اتصالدستور آماده
حالت‌های cache در pgx و QueryExecModecache دستور در pgx
BeginTx، سطح جداسازی، Commit/Rollback و الگوی defer Rollbackتراکنش‌ها
تکرار Transaction پس از serialization failure با کد 40001تلاش مجدد
اثر لغو context و درخواست cancel در pgxلغو
API بومی pgx v5 و تفاوت pgx.Conn با pgxpool.Poolpgx بومی
جمع‌آوری نتیجه با CollectRows، RowToStructByName و named argsجمع‌آوری سطرها
کاهش رفت‌وبرگشت با batch، CopyFrom، COPY، unnest و bulk insertدسته و بارگذاری انبوه
ارسال اعلان با LISTEN/NOTIFYLISTEN/NOTIFY
نگاشت نوع‌ها با pgtype و ثبت نوع اختصاصی در AfterConnectنوع‌ها
تنظیم MaxConns، health check و رشتهٔ اتصال/DSN در pgxpoolپیکربندی pgxpool
محدود کردن زمان با statement_timeout و lock_timeoutTimeoutها
دسته‌بندی خطا با pgconn.PgError و SQLSTATEخطاها
سازگاری prepared statement با حالت transaction در PgBouncerPgBouncer
الگوی repository و interface برای هر aggregateالگوی repository
انتشار tx در context یا UnitOfWorkاشتراک تراکنش
انتخاب sqlc، سازنده‌های squirrel/goqu و ORMهای GORM/ent/bunsqlc، builder و ORM
مدیریت migration با golang-migrate، goose، atlas و ternMigrationها
تشخیص N+1 در GoN+1
انتخاب fake driver، pgx mock یا DB واقعی با dockertest/testcontainersتست
مشاهده‌پذیری با otelsql، pgx tracer و آمار poolمشاهده‌پذیری
جزئیات درونی و متن دقیق خطاهاسازوکار
باگ‌های متداول و اصلاحشانحل مسئله‌های کلاسیک
چه وقت از چه استفاده کنیمانتخاب
مسیر monolith تا سیستم توزیع‌شدهدر معماری
بازسازی رفتارهاآزمایشگاه
مقایسهٔ Eloquent و PDO با Goبرای توسعه‌دهندگان PHP/Laravel

همه‌چیز در یک دقیقه (One minute) ​

اشیای database/sql. هر سطر در فهرست مفاهیم باز می‌شود.

نوعچیستطول عمرامن برای استفادهٔ هم‌زماناتصال را نگه می‌دارد
*sql.DBمخزن اتصال (Connection pool) همراه driverتمام عمر فرایند؛ یک‌بار باز کنیدبلهدر هر فراخوانی یکی قرض می‌گیرد
*sql.Connیک اتصال رزروشدهتا Closeبرای دستورهای هم‌زمان نهبله، تا Close
*sql.Txیک تراکنش (Transaction)تا Commit یا Rollbackنهبله، در تمام مدت
*sql.Stmtدستور آماده (Prepared statement)تا Closeبلهروی هر اتصال مورد استفاده، تنبل آماده می‌شود
*sql.Rowsمکان‌نمای نتیجه (Cursor)تا Close یا آخرین Nextنهبله، تا بسته شدن
*sql.Rowنتیجهٔ QueryRowContextتا ScanنهScan آن را آزاد می‌کند

فراخوانی‌های روزمره.

فراخوانیخروجیکاربردکار لازم پس از آن
db.QueryContext(ctx, q, args...)*sql.Rows, errorچند سطرdefer rows.Close()، حلقهٔ Next و بررسی rows.Err()
db.QueryRowContext(ctx, q, args...)*sql.Rowصفر یا یک سطر.Scan(...)؛ در نتیجهٔ خالی sql.ErrNoRows
db.ExecContext(ctx, q, args...)sql.Result, errorINSERT/UPDATE/DELETE/DDLاگر تعداد مهم است RowsAffected()
db.BeginTx(ctx, opts)*sql.Tx, errorچند دستور در یک واحدdefer tx.Rollback()، سپس tx.Commit()
db.PrepareContext(ctx, q)*sql.Stmt, errorاستفادهٔ مکرر از یک دستور پرتکرارstmt.Close() هنگام خاموشی
db.PingContext(ctx)errorراه‌اندازی و readinessهیچ

همان کار در API بومی pgx v5.

database/sqlpgx v5تفاوت
sql.Open("pgx", dsn)pgxpool.New(ctx, dsn)هر دو تنبل؛ pgxpool برمی‌گردد "without waiting for any connections"
db.QueryContext و حلقهpool.Query + pgx.CollectRows(rows, pgx.RowToStructByName[T])Collect سطرها را می‌بندد و خطا را بررسی می‌کند
sql.NullString*string یا pgtype.Textpgx مقدار NULL را به pointer nil نگاشت می‌کند
فقط ?/$1$1 یا @name با pgx.NamedArgsبازنویسی named args در کلاینت
tx.Commit()tx.Commit(ctx)متدهای pgx، ctx می‌گیرند
موجود نیستpool.SendBatch، pool.CopyFrom، conn.WaitForNotificationقابلیت‌های مخصوص PostgreSQL
sql.ErrNoRowspgx.ErrNoRowsاز pgx 5.7.0، sql.ErrNoRows را wrap می‌کند

خطاهایی که در log می‌بینید.

متنمعنیاقدام
sql: no rows in result setsql.ErrNoRows از Row.Scanتبدیل به «پیدا نشد» دامنه
sql: transaction has already been committed or rolled backsql.ErrTxDoneاز Rollback معوق طبیعی است؛ جای دیگر باگ است
context deadline exceededctx هنگام انتظار اتصال یا اجرای query منقضی شدهآمار انتظار pool و زمان query را ببینید
ERROR: could not serialize access due to concurrent update (SQLSTATE 40001)شکست serialization در Repeatable Read یا Serializableتکرار کل Transaction
ERROR: duplicate key value violates unique constraint "users_email_key" (SQLSTATE 23505)نقض یکتایینگاشت constraint به 409
ERROR: canceling statement due to statement timeout (SQLSTATE 57014)فعال شدن statement_timeoutاصلاح query یا افزایش سقف برای همان job
ERROR: prepared statement "stmtcache_..." does not exist (SQLSTATE 26000)cache دستور پشت pooler با حالت transactionPgBouncer را ببینید
sql: Scan error on column index 0, name "phone": converting NULL to string is unsupportedخواندن NULL در string معمولیpointer یا sql.Null[string]

چرا وجود دارد (Why) ​

باز کردن اتصال PostgreSQL هزینهٔ handshake در TCP و معمولاً TLS، احراز هویت و یک فرایند تازه در سرور دارد؛ max_connections هم سقف تعداد را تعیین می‌کند. سرور Go هزاران درخواست هم‌زمان را با goroutine پاسخ می‌دهد. نه می‌تواند برای هر درخواست اتصال بسازد، نه می‌تواند یک اتصال را میان همه مشترک کند: هر اتصال در هر لحظه یک دستور اجرا می‌کند و حالت نشست (Session state) مثل Transaction باز، مقدارهای SET و prepared statement دارد. راه‌حل مخزن اتصال (Connection pool) است: چند اتصال بلندعمر که هر بار به یک goroutine قرض داده و پس گرفته می‌شوند. database/sql همین pool به‌علاوهٔ رابط driver است. در نتیجه کد و کتابخانه‌های migration، ORM و tracing با PostgreSQL، MySQL، SQLite و SQL Server کار می‌کنند و هر driver فقط پروتکل شبکه را پیاده می‌کند.

database/sql قابل حملpgx بومی
یک API برای همهٔ پایگاه‌ها؛ انتظار کتابخانه‌ها همین استفقط PostgreSQL
pool در کتابخانهٔ استانداردpgxpool روی puddle
نوع‌ها محدود به driver.Value و Scanner/Valuerحدود 70 نوع PostgreSQL با pgtype و قالب binary
بدون COPY، batch و LISTENCopyFrom، SendBatch، WaitForNotification
مدیریت statement وابسته به drivercache خودکار و پنج حالت اجرا
کمی کندتر؛ README: "The pgx interface is faster"سریع‌تر و allocation کمتر

تصویری از زندگی روزمره. شرکت اجارهٔ خودرو تعداد مشخصی خودرو دارد؛ همان اتصال‌های فرایند شما. هر کارمند، یعنی goroutine، کلید می‌گیرد و پس از سفر باید برگرداند. اگر همه کلید را نگه دارند، مثل Rows بسته‌نشده، نفر بعدی پشت باجه و صف انتظار می‌ماند تا کلیدی برگردد یا مهلت ctx تمام شود. سفر چندمرحله‌ای که باید یکپارچه انجام شود، یک رزرو یا Transaction است: در تمام مسیر همان خودرو را دارید. خودروهای قدیمی با SetConnMaxLifetime بازنشسته می‌شوند و آن‌هایی که زیاد پارک مانده‌اند با SetConnMaxIdleTime برگردانده می‌شوند.

سه بدفهمی رایج، از همان اول ​

  1. «sql.Open به پایگاه داده وصل می‌شود.» مستند می‌گوید "may just validate its arguments without creating a connection"؛ اولین query یا Ping اتصال می‌سازد. بدون PingContext هنگام startup، رمز اشتباه تازه در اولین درخواست آشکار می‌شود.
  2. «برای هر درخواست یک *sql.DB باز کنم و ببندم.» *sql.DB خود pool است. "The Open function should be called just once. It is rarely necessary to close a DB." ساختن آن برای هر درخواست یعنی هر بار pool تازه، اتصال تازه و بستن اتصال.
  3. «defer tx.Rollback()، Transaction ثبت‌شده را برمی‌گرداند.» پس از Commit موفق، Rollback معوق فقط sql.ErrTxDone می‌دهد و چیزی به سرور نمی‌فرستد؛ تست Go ثابت می‌کند driver آن را نمی‌بیند.

از کجا آمده (History) ​

database/sql از Go 1 در کتابخانهٔ استاندارد بوده و در api/go1.txt ثبت است. رابط‌های driver در database/sql/driver هستند و driver داخلی ندارد: "No database drivers are included in the Go standard library". ویکی SQLInterface در go.dev هنوز کاربرد پایه را شرح می‌دهد و SQLDrivers driverهای ثالث را با علامت قبولی مجموعه‌تست سازگاری فهرست می‌کند؛ jackc/pgx و lib/pq هر دو علامت دارند. Go 1.6، SetConnMaxLifetime را افزود (api/go1.6.txt). جهش اصلی Go 1.8 بود: متدهای ...Context که "enables canceling in-progress queries should the driver support that"، TxOptions با IsolationLevel و ReadOnly برای BeginTx، NamedArg و sql.Named، چند result set و ColumnTypes. Go 1.10، driver.Connector و sql.OpenDB را آورد (api/go1.10.txt)؛ Go 1.13، NullTime و NullInt32 را. Go 1.15، Row.Err و SetConnMaxIdleTime را اضافه کرد که "allows removing a connection from the connection pool after it has been idle for a period of time, without regard to the total lifespan of the connection". Go 1.17، NullInt16 و NullByte را آورد و Go 1.22 Null[T] جنریک را آورد تا، به گفتهٔ یادداشت انتشار، "provide a way to scan nullable columns for any column types".

در PostgreSQL، lib/pq اولین driver پرکاربرد pure-Go بود. README نسخهٔ v1.10.9 آن را در حالت نگهداری معرفی می‌کرد: "It generally does not accept new features" و توصیه می‌کرد: "For users that require new features or reliable resolution of reported bugs, we recommend using pgx". انتشارها در ۲۰۲۶ از سر گرفته شد؛ v1.12.0 در مارس ۲۰۲۶ آمد و README جاری دیگر آن هشدار را ندارد. بااین‌حال بیشتر کدهای جدید PostgreSQL، pgx را انتخاب می‌کنند. sqlc می‌تواند کد pgx تولید کند (sql_package: pgx/v5) ولی sql_package آن "Defaults to database/sql". pgx ساختهٔ Jack Christensen از v3 و v4 گذشت؛ v5.0.0 در ۱۷ سپتامبر ۲۰۲۲، pgconn، pgtype و pgproto3 را در یک repository ادغام کرد و CollectRows مبتنی بر generics، NamedArgs و pgtype جدید را آورد. نسخه‌های بعدی 5.x به‌ترتیب RowToStructByName در 5.1.0، StrictNamedArgs در 5.6.0، wrap شدن sql.ErrNoRows در pgx.ErrNoRows از 5.7.0، MinIdleConns در 5.7.3 و hook PrepareConn در pgxpool در 5.7.6 را اضافه کردند. نسخهٔ 5.8.0 در دسامبر ۲۰۲۵ Go 1.24 خواست و از 5.9.0 به بعد Go 1.25 لازم شد؛ نسخهٔ جاری 5.13.0 در نوامبر ۲۰۲۶ است.

Go ​

قبل (Before) ​

storeی که روز آرام کار می‌کند، ولی ورودی کاربر را به SQL می‌چسباند، context ندارد، هنگام خطای Scan اتصال را نشت می‌دهد و هیچ‌وقت rows.Err() را نمی‌بیند. sql.NullString هم به نوع دامنه راه یافته و انتقال پول با دو دستور مستقل autocommit انجام می‌شود.

go
// Package before is a first repository that works on a quiet day: it builds SQL
// with string concatenation, has no context, leaks rows on error paths, never
// checks rows.Err, lets sql.NullString leak into the domain and moves money
// with two independent autocommit statements.
package before

import (
	"database/sql"
	"fmt"
)

// Order leaks a database/sql type (sql.NullString) into the domain model.
type Order struct {
	ID         int64
	Email      string
	Note       sql.NullString
	TotalCents int64
}

// Store holds the pool; the bad parts are in the methods.
type Store struct{ DB *sql.DB }

// ByCustomer concatenates user input into SQL (injection) and uses Query without a context.
func (s *Store) ByCustomer(email string) ([]Order, error) {
	rows, err := s.DB.Query("SELECT id, email, note, total_cents FROM orders WHERE email = '" + email + "'")
	if err != nil {
		return nil, err
	}
	var out []Order
	for rows.Next() {
		var o Order
		if err := rows.Scan(&o.ID, &o.Email, &o.Note, &o.TotalCents); err != nil {
			return nil, err // rows is never closed on this path: the connection stays busy
		}
		out = append(out, o)
	}
	return out, nil // rows.Err() is never checked: a broken stream looks like a short list
}

// Transfer runs two autocommit statements: if the second fails, the money is gone.
func (s *Store) Transfer(from, to, cents int64) error {
	if _, err := s.DB.Exec(fmt.Sprintf("UPDATE accounts SET balance = balance - %d WHERE id = %d", cents, from)); err != nil {
		return err
	}
	_, err := s.DB.Exec(fmt.Sprintf("UPDATE accounts SET balance = balance + %d WHERE id = %d", cents, to))
	return err
}

تست‌ها با driver جعلی دو ایراد را اثبات می‌کنند: ورودی داخل متن SQL و با صفر آرگومان به driver می‌رسد؛ وقتی واریز شکست می‌خورد، برداشت قبلاً commit شده است، چون هیچ BEGIN یا ROLLBACK به driver نرسیده.

go
package before

import (
	"errors"
	"strings"
	"testing"

	"academy/database-sql-pgx/internal/fakedb"
)

func TestInputBecomesSQL(t *testing.T) {
	fake := fakedb.New(nil)
	s := &Store{DB: fake.Open()}
	if _, err := s.ByCustomer("x' OR '1'='1"); err != nil {
		t.Fatal(err)
	}
	q := fake.Calls()[1] // calls[0] is the connect
	if !strings.Contains(q.Query, "OR '1'='1'") || len(q.Args) != 0 {
		t.Fatalf("expected the input inside the SQL text, got %q args=%v", q.Query, q.Args)
	}
}

func TestTransferIsNotAtomic(t *testing.T) {
	fake := fakedb.New(func(kind, q string, _ []any) fakedb.Response {
		if strings.Contains(q, "balance + ") {
			return fakedb.Response{Err: errors.New("connection reset")}
		}
		return fakedb.Response{Affected: 1}
	})
	s := &Store{DB: fake.Open()}
	if err := s.Transfer(1, 2, 500); err == nil {
		t.Fatal("expected the second statement to fail")
	}
	// The debit ran and was committed on its own: no BEGIN, no ROLLBACK.
	if fake.Count("begin") != 0 || fake.Count("rollback") != 0 || fake.Count("exec") != 2 {
		t.Fatalf("calls: %v", fake.Kinds())
	}
}

بعد (After) ​

همان store مطابق قرارداد database/sql: در هر فراخوانی ctx، جای‌نگهدار $1، defer rows.Close() و rows.Err() دارد؛ sql.ErrNoRows را به ErrNotFound دامنه تبدیل می‌کند، برای ستون nullable از *string استفاده می‌کند و انتقال پول را در یک Transaction با defer tx.Rollback() می‌گذارد. هر UPDATE باید دقیقاً یک سطر را بگیرد. به‌روزرسانی حساب ناموجود خطای SQL نیست؛ فقط صفر سطر را تغییر می‌دهد. بنابراین updateOne، RowsAffected() را بررسی و ErrAccountNotFound برمی‌گرداند تا تمام انتقال rollback شود.

go
// Package after is the same store written the way database/sql expects:
// context on every call, placeholders, rows closed and checked, ErrNoRows
// mapped to a domain error, NULL mapped to a pointer, and one transaction
// with the defer-Rollback pattern for the transfer.
package after

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
)

// ErrNotFound is the domain error callers check; sql.ErrNoRows stays inside the store.
var ErrNotFound = errors.New("order not found")

// ErrAccountNotFound is returned when a transfer names an account that does not exist.
var ErrAccountNotFound = errors.New("account not found")

// Order uses a plain pointer for the nullable note: nil means SQL NULL.
type Order struct {
	ID         int64
	Email      string
	Note       *string
	TotalCents int64
}

// Store wraps the pool. *sql.DB is safe for concurrent use; create it once.
type Store struct{ db *sql.DB }

// NewStore takes the shared pool.
func NewStore(db *sql.DB) *Store { return &Store{db: db} }

// Get returns one order or ErrNotFound.
func (s *Store) Get(ctx context.Context, id int64) (Order, error) {
	var o Order
	err := s.db.QueryRowContext(ctx,
		`SELECT id, email, note, total_cents FROM orders WHERE id = $1`, id,
	).Scan(&o.ID, &o.Email, &o.Note, &o.TotalCents)
	if errors.Is(err, sql.ErrNoRows) {
		return Order{}, fmt.Errorf("get order %d: %w", id, ErrNotFound)
	}
	if err != nil {
		return Order{}, fmt.Errorf("get order %d: %w", id, err)
	}
	return o, nil
}

// ByCustomer passes the input as an argument ($1), never as SQL text.
func (s *Store) ByCustomer(ctx context.Context, email string) ([]Order, error) {
	rows, err := s.db.QueryContext(ctx,
		`SELECT id, email, note, total_cents FROM orders WHERE email = $1 ORDER BY id`, email)
	if err != nil {
		return nil, fmt.Errorf("orders by customer: %w", err)
	}
	defer rows.Close() // returns the connection to the pool on every path

	var out []Order
	for rows.Next() {
		var o Order
		if err := rows.Scan(&o.ID, &o.Email, &o.Note, &o.TotalCents); err != nil {
			return nil, fmt.Errorf("scan order: %w", err)
		}
		out = append(out, o)
	}
	if err := rows.Err(); err != nil { // errors during iteration surface here, not in Next
		return nil, fmt.Errorf("iterate orders: %w", err)
	}
	return out, nil
}

// Transfer moves money in one transaction: both updates or neither.
func (s *Store) Transfer(ctx context.Context, from, to, cents int64) error {
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return fmt.Errorf("begin: %w", err)
	}
	defer tx.Rollback() // no-op after a successful Commit (returns sql.ErrTxDone)

	if err := updateOne(ctx, tx, `UPDATE accounts SET balance = balance - $1 WHERE id = $2`, cents, from); err != nil {
		return fmt.Errorf("debit %d: %w", from, err)
	}
	if err := updateOne(ctx, tx, `UPDATE accounts SET balance = balance + $1 WHERE id = $2`, cents, to); err != nil {
		return fmt.Errorf("credit %d: %w", to, err)
	}
	return tx.Commit()
}

// updateOne runs an UPDATE that must match exactly one row. An UPDATE that
// matches nothing is not an error in SQL, so a missing account would
// otherwise let the other half of the transfer commit alone.
func updateOne(ctx context.Context, tx *sql.Tx, q string, args ...any) error {
	res, err := tx.ExecContext(ctx, q, args...)
	if err != nil {
		return err
	}
	n, err := res.RowsAffected()
	if err != nil {
		return err
	}
	if n != 1 {
		return ErrAccountNotFound
	}
	return nil
}

تست‌ها ترتیب دقیق driver را بررسی می‌کنند: در شکست واریز connect, begin, exec, exec, rollback و در موفقیت connect, begin, exec, exec, commit. این هم ثابت می‌کند Rollback معوق بعد از Commit هرگز به driver نمی‌رسد. TestTransferRejectsMissingAccount واریز به حساب 999 را با صفر سطر بازسازی می‌کند و ErrAccountNotFound، یک rollback و نبود commit را می‌سنجد.

go
package after

import (
	"database/sql/driver"
	"errors"
	"slices"
	"strings"
	"testing"

	"academy/database-sql-pgx/internal/fakedb"
)

var cols = []string{"id", "email", "note", "total_cents"}

func TestInputStaysAnArgument(t *testing.T) {
	fake := fakedb.New(nil)
	s := NewStore(fake.Open())
	if _, err := s.ByCustomer(t.Context(), "x' OR '1'='1"); err != nil {
		t.Fatal(err)
	}
	q := fake.Calls()[1]
	if strings.Contains(q.Query, "'1'='1'") || q.Args[0] != "x' OR '1'='1" {
		t.Fatalf("query %q args %v", q.Query, q.Args)
	}
}

func TestGetMapsNoRowsAndNull(t *testing.T) {
	fake := fakedb.New(func(kind, q string, args []any) fakedb.Response {
		if args[0] == int64(1) {
			return fakedb.Response{Columns: cols, Rows: [][]driver.Value{{int64(1), "a@example.test", nil, int64(900)}}}
		}
		return fakedb.Response{Columns: cols} // zero rows
	})
	s := NewStore(fake.Open())
	o, err := s.Get(t.Context(), 1)
	if err != nil || o.Note != nil || o.TotalCents != 900 {
		t.Fatalf("got %+v, %v", o, err)
	}
	if _, err := s.Get(t.Context(), 2); !errors.Is(err, ErrNotFound) {
		t.Fatalf("want ErrNotFound, got %v", err)
	}
}

func TestRowsErrIsReported(t *testing.T) {
	fake := fakedb.New(func(string, string, []any) fakedb.Response {
		return fakedb.Response{Columns: cols,
			Rows:   [][]driver.Value{{int64(1), "a@example.test", "gift", int64(1)}},
			RowErr: errors.New("server closed the connection unexpectedly")}
	})
	_, err := NewStore(fake.Open()).ByCustomer(t.Context(), "a@example.test")
	if err == nil || !strings.Contains(err.Error(), "iterate orders") {
		t.Fatalf("want iteration error, got %v", err)
	}
}

func TestTransferRollsBackOnError(t *testing.T) {
	fake := fakedb.New(func(kind, q string, _ []any) fakedb.Response {
		if strings.Contains(q, "balance + ") {
			return fakedb.Response{Err: errors.New("connection reset")}
		}
		return fakedb.Response{Affected: 1}
	})
	if err := NewStore(fake.Open()).Transfer(t.Context(), 1, 2, 500); err == nil {
		t.Fatal("expected an error")
	}
	want := []string{"connect", "begin", "exec", "exec", "rollback"}
	if got := fake.Kinds(); !slices.Equal(got, want) {
		t.Fatalf("got %v want %v", got, want)
	}
}

func TestTransferCommitsOnce(t *testing.T) {
	fake := fakedb.New(func(string, string, []any) fakedb.Response { return fakedb.Response{Affected: 1} })
	if err := NewStore(fake.Open()).Transfer(t.Context(), 1, 2, 500); err != nil {
		t.Fatal(err)
	}
	// The deferred Rollback after Commit never reaches the driver.
	want := []string{"connect", "begin", "exec", "exec", "commit"}
	if got := fake.Kinds(); !slices.Equal(got, want) {
		t.Fatalf("got %v want %v", got, want)
	}
}

// Round 1: a credit to a missing account matches zero rows without an error;
// the transfer must fail and roll back instead of committing the debit alone.
func TestTransferRejectsMissingAccount(t *testing.T) {
	fake := fakedb.New(func(kind, q string, args []any) fakedb.Response {
		if strings.Contains(q, "balance + ") && args[1] == int64(999) {
			return fakedb.Response{Affected: 0}
		}
		return fakedb.Response{Affected: 1}
	})
	err := NewStore(fake.Open()).Transfer(t.Context(), 1, 999, 100)
	if !errors.Is(err, ErrAccountNotFound) {
		t.Fatalf("want ErrAccountNotFound, got %v", err)
	}
	if fake.Count("commit") != 0 || fake.Count("rollback") != 1 {
		t.Fatalf("calls %v", fake.Kinds())
	}
}

زاویهٔ Go ​

Go دسترسی به پایگاه داده را میان لایهٔ کوچک و پایدار استاندارد و اکوسیستم رقابتی driverها تقسیم کرده است. database/sql مسئول pool، شیء Transaction، لغو از راه context و قرارداد scan است؛ driver پروتکل شبکه، نگاشت نوع، شکل placeholder و توقف query در سرور پس از لغو را تعیین می‌کند. چیزی پنهان نیست: identity map، lazy loading و Transaction ضمنی ندارید و هر query رشته‌ای است که خودتان نوشته یا تولید کرده‌اید. به همین دلیل ابزارهای SQL-first مثل sqlc، CollectRows در pgx و squirrel رایج‌اند و ساخت لایهٔ repository کم‌هزینه است: یک struct با *sql.DB یا pgxpool.Pool و چند متد.

فهرست مفاهیم ​

your repositories and servicesORM: GORM, ent, bunbuilders: squirrel, goqusqlc generated codeemits database/sql or pgx/v5hand-written SQL$1 placeholdersdatabase/sql (*sql.DB pool)portable; driver.Conn interfacespgx v5 native: pgxpool.PoolCopyFrom, Batch, LISTEN, pgtypepgx/v5/stdliblib/pq, mysqlpgx.Conn on pgconn (wire protocol)TCP / TLS to PostgreSQL (optionally through PgBouncer)dashed: stdlib.OpenDBFromPool and (*sql.Conn).Raw bridge the two paths

باز کردن پایگاه داده: sql.Open تنبل است، DB یک pool است، Ping حیاتی ​

به زبان ساده: sql.Open("pgx", dsn) شیء مخزن اتصال (Connection pool) می‌سازد و روش اتصال را نگه می‌دارد؛ وصل نمی‌شود. هنگام startup، PingContext بزنید تا رمز اشتباه deploy را شکست دهد، نه اولین درخواست مشتری را. یک‌بار بسازید و مشترک استفاده کنید.

بدفهمی رایج: «اگر sql.Open خطای nil داد، پایگاه داده در دسترس است.» مستند: "Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call DB.Ping." اشتباه مقابل هم رایج است: sql.Open در هر handler یعنی یک pool برای هر درخواست.

تعریف: sql.Open(driverName, dataSourceName) driver ثبت‌شده با sql.Register را پیدا می‌کند؛ معمولاً ثبت با blank import مثل _ "github.com/jackc/pgx/v5/stdlib" انجام شده است. خروجی *sql.DB است. sql.OpenDB(connector) از Go 1.10 همین کار را با driver.Connector انجام می‌دهد تا ثبت رشته‌ای لازم نباشد و config در کد ساخته شود. DB برگشتی "is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once." PingContext یک اتصال قرض می‌گیرد، در صورت نیاز dial می‌کند و Pinger driver را صدا می‌زند.

1  main()          db, err := sql.Open("pgx", dsn)     -> err only for unknown driver / bad DSN syntax
2                  connections open: 0
3                  err = db.PingContext(ctx)           -> dials 1 connection, authenticates
4                  connections open: 1 (now idle)
5  handler A       db.QueryContext(ctx, ...)           -> reuses the idle connection
6  handler B       db.QueryContext(ctx, ...)  (same time) -> dials connection 2
7  shutdown        db.Close()                          -> closes idle conns; in-use ones close when released

سناریوی واقعی: pod در Kubernetes با رمز اشتباه readiness را رد نمی‌کند چون هیچ pingی انجام نشده؛ CLI برای هر subcommand یک DB باز می‌کند که طبیعی است، اما وب‌سروری که برای هر درخواست چنین کند در دقیقه 2,000 اتصال می‌سازد و PostgreSQL با 53300 too_many_connections رد می‌کند. سرویس دیگری db.Close() را در defer handler گذاشته و درخواست‌های دیگر را خراب می‌کند.

سازندهDial می‌کند؟منبع پیکربندیزمان استفاده
sql.Open("pgx", dsn)نهرشتهٔ DSNانتخاب معمول با pgx stdlib یا lib/pq
sql.OpenDB(connector)نهیک driver.Connectorپیکربندی در کد با stdlib.GetConnector
stdlib.OpenDB(connConfig)نهpgx.ConnConfigtracer یا TLS config غیرقابل بیان در DSN
stdlib.OpenDBFromPool(pool)نهpgxpool.Pool موجودیک pool برای هر دو API
pgxpool.New(ctx, dsn)نه؛ "returns without waiting"DSNpgx بومی
pgx.Connect(ctx, dsn)بله، یک اتصالDSNscript، migration و LISTEN

راه‌حل / روش استفاده: در main باز کنید، با یک timeout ping کنید و *sql.DB یا یک interface را به constructorها بدهید. تابع Open در snippet pool همین کار را می‌کند و تست اول تنبلی را اثبات می‌کند: پس از sql.OpenDB صفر اتصال، پس از PingContext یک اتصال.

go
// Package pool configures a *sql.DB: the four pool knobs, a Ping at startup
// (because sql.Open is lazy) and a Stats snapshot for metrics.
package pool

import (
	"context"
	"database/sql"
	"database/sql/driver"
	"fmt"
	"time"
)

// Settings are the four database/sql pool knobs.
type Settings struct {
	MaxOpen     int           // SetMaxOpenConns: hard cap; 0 = unlimited (the default)
	MaxIdle     int           // SetMaxIdleConns: idle connections kept; default 2
	MaxLifetime time.Duration // SetConnMaxLifetime: recycle after this age; 0 = never
	MaxIdleTime time.Duration // SetConnMaxIdleTime: close after this long idle; 0 = never (Go 1.15+)
}

// ForService is a starting point for one service instance talking to PostgreSQL.
// Size MaxOpen from the server's max_connections divided by the number of instances.
func ForService(maxOpen int) Settings {
	return Settings{
		MaxOpen:     maxOpen,
		MaxIdle:     maxOpen, // keep the pool warm; the idle timeout trims it when quiet
		MaxLifetime: 30 * time.Minute,
		MaxIdleTime: 5 * time.Minute,
	}
}

// Apply sets the knobs on an existing pool.
func Apply(db *sql.DB, s Settings) {
	db.SetMaxOpenConns(s.MaxOpen)
	db.SetMaxIdleConns(s.MaxIdle)
	db.SetConnMaxLifetime(s.MaxLifetime)
	db.SetConnMaxIdleTime(s.MaxIdleTime)
}

// Open builds the pool from a driver.Connector (sql.OpenDB), applies the
// settings and pings, so a bad DSN or an unreachable server fails at startup
// instead of on the first request.
func Open(ctx context.Context, c driver.Connector, s Settings) (*sql.DB, error) {
	db := sql.OpenDB(c) // like sql.Open: no connection yet
	Apply(db, s)
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
	if err := db.PingContext(ctx); err != nil {
		db.Close()
		return nil, fmt.Errorf("ping database: %w", err)
	}
	return db, nil
}

// Snapshot is the subset of sql.DBStats worth exporting as metrics.
type Snapshot struct {
	Open, InUse, Idle      int
	WaitCount              int64
	WaitDuration           time.Duration
	MaxIdleClosed          int64
	MaxIdleTimeClosed      int64
	MaxLifetimeClosed      int64
	MaxOpenConnectionsConf int
}

// Stats reads db.Stats(). A growing WaitCount means callers queue for a connection.
func Stats(db *sql.DB) Snapshot {
	st := db.Stats()
	return Snapshot{
		Open: st.OpenConnections, InUse: st.InUse, Idle: st.Idle,
		WaitCount: st.WaitCount, WaitDuration: st.WaitDuration,
		MaxIdleClosed: st.MaxIdleClosed, MaxIdleTimeClosed: st.MaxIdleTimeClosed,
		MaxLifetimeClosed: st.MaxLifetimeClosed, MaxOpenConnectionsConf: st.MaxOpenConnections,
	}
}

تنظیمات pool: SetMaxOpenConns، SetMaxIdleConns، SetConnMaxLifetime، SetConnMaxIdleTime حیاتی ​

به زبان ساده: چهار عدد تعیین می‌کنند فرایند چند اتصال می‌تواند داشته باشد، چند اتصال گرم نگه دارد و چه وقت بازیافتشان کند. پیش‌فرض‌ها «نامحدود»، «2»، «همیشه» و «همیشه» هستند و تقریباً برای هیچ سرویس واقعی مناسب نیستند.

بدفهمی رایج: «اتصال نامحدود یعنی بیشترین توان عملیاتی (Throughput).» یعنی هنگام جهش ترافیک، هر goroutine اتصال خودش را باز می‌کند تا PostgreSQL با سقف max_connections رد کند؛ مستند می‌گوید "The default is typically 100 connections". تمام instanceها هم برای همان ظرفیت رقابت می‌کنند. راهنمای go.dev دربارهٔ سمت دیگر هشدار می‌دهد: "setting a limit makes database usage similar to acquiring a lock or semaphore, with the result that your application can deadlock waiting for a new database connection"؛ مثل goroutineی که Tx دارد و از pool تک‌اتصالی، اتصال دوم می‌خواهد.

تعریف:

تنظیمپیش‌فرضگفتهٔ مستندمقدار معمول سرویس
SetMaxOpenConns(n)0 = نامحدود"If n <= 0, then there is no limit"بودجهٔ سرور ÷ instanceها، مثلاً 20
SetMaxIdleConns(n)2"The default max idle connections is currently 2"؛ اگر بیشتر باشد تا MaxOpen کم می‌شودبرای بار پایدار برابر MaxOpen
SetConnMaxLifetime(d)0 = هرگز"maximum amount of time a connection may be reused"؛ "closed lazily before reuse"30–60 دقیقه؛ پشت load balancer کوتاه‌تر
SetConnMaxIdleTime(d)0 = هرگزGo 1.15+؛ "maximum amount of time a connection may be idle"1–5 دقیقه برای کوچک شدن پس از جهش بار
pool MaxOpen=2, MaxIdle=2
t=0   G1 QueryContext   -> conn#1 in use        open=1 inUse=1
t=0   G2 ExecContext    -> conn#2 dialed        open=2 inUse=2
t=1   G3 QueryContext   -> waits (connRequests) WaitCount=1
t=5   G1 rows.Close()   -> conn#1 handed to G3  WaitDuration += 4
t=9   G3 ctx deadline?  -> if it fired at t=3: "context deadline exceeded" without running any SQL

سناریوی واقعی: p99 یک API پرداخت بالا رفته چون MaxOpen=10 است و endpoint گزارش، 8 اتصال را 30 ثانیه نگه می‌دارد؛ 40 pod با اتصال نامحدود، PostgreSQL با ظرفیت 200 اتصال را در اوج بار از پا می‌اندازند. NAT gateway یا load balancer جریان TCP بیکار را پس از چند دقیقه بی‌صدا حذف می‌کند و SetConnMaxIdleTime(time.Minute) اصلاحش می‌کند. پس از failover هم اتصال‌های قدیمی به گره تنزل‌یافته اشاره می‌کنند تا SetConnMaxLifetime بازیافتشان کند.

نشانه در db.Stats()معنیتغییر
رشد WaitCount و WaitDurationصف انتظار اتصالاول query و Transaction کوتاه‌تر؛ بعد MaxOpen بیشتر
InUse == MaxOpenConnections برای مدت طولانیاشباع یا نشت؛ rows باز یا tx طولانیبررسی نبود rows.Close و Transaction طولانی
MaxIdleClosed زیادسقف idle کوچک و اتصال‌ها مدام باز و بسته می‌شوندMaxIdle را به MaxOpen نزدیک کنید
MaxLifetimeClosed پیوستهبازیافت طبق تنظیمطبیعی
OpenConnections بسیار کمتر از MaxOpenpool بزرگ‌تر از نیازکاهش سقف؛ سقف است نه هدف

راه‌حل / روش استفاده: هر چهار مقدار را هنگام startup تنظیم کنید، db.Stats() را به gauge تبدیل کنید و مجموع instanceها را با ظرفیت سرور بسنجید؛ حساب آن در Connection Pooling آمده است. تست‌ها timeout هنگام انتظار تنها اتصال با WaitCount == 1 و گرسنگی pool به‌خاطر *sql.Rows بسته‌نشده را نشان می‌دهند.

go
package pool

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/database-sql-pgx/internal/fakedb"
)

func TestOpenIsLazyPingConnects(t *testing.T) {
	fake := fakedb.New(nil)
	db := fake.Open()
	defer db.Close()
	if fake.Opens() != 0 {
		t.Fatalf("sql.OpenDB opened %d connections", fake.Opens())
	}
	if err := db.PingContext(t.Context()); err != nil {
		t.Fatal(err)
	}
	if fake.Opens() != 1 {
		t.Fatalf("after Ping: %d connections", fake.Opens())
	}
}

func TestMaxOpenMakesCallersWait(t *testing.T) {
	fake := fakedb.New(nil)
	db := fake.Open()
	defer db.Close()
	Apply(db, Settings{MaxOpen: 1, MaxIdle: 1})

	held, err := db.Conn(t.Context()) // take the only connection
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
	defer cancel()
	_, err = db.ExecContext(ctx, "SELECT 1")
	if !errors.Is(err, context.DeadlineExceeded) {
		t.Fatalf("want deadline while waiting for a connection, got %v", err)
	}
	if s := Stats(db); s.WaitCount != 1 || s.InUse != 1 || s.MaxOpenConnectionsConf != 1 {
		t.Fatalf("stats %+v", s)
	}
	held.Close()
	if _, err := db.ExecContext(t.Context(), "SELECT 1"); err != nil {
		t.Fatal(err)
	}
}

func TestUnclosedRowsHoldTheConnection(t *testing.T) {
	fake := fakedb.New(func(string, string, []any) fakedb.Response {
		return fakedb.Response{Columns: []string{"n"}}
	})
	db := fake.Open()
	defer db.Close()
	Apply(db, Settings{MaxOpen: 1, MaxIdle: 1})

	rows, err := db.QueryContext(t.Context(), "SELECT n FROM t") // never iterated, never closed
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
	defer cancel()
	if err := db.QueryRowContext(ctx, "SELECT 1").Scan(new(int)); !errors.Is(err, context.DeadlineExceeded) {
		t.Fatalf("want pool exhaustion, got %v", err)
	}
	rows.Close()
}

func TestOpenPings(t *testing.T) {
	fake := fakedb.New(nil)
	db, err := Open(t.Context(), fake.Connector(), ForService(10))
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()
	if fake.Count("ping") != 1 || db.Stats().MaxOpenConnections != 10 {
		t.Fatalf("calls %v", fake.Kinds())
	}
}
goroutinesQueryContextExecContextBeginTx (pins one)caller #MaxOpen+1*sql.DB = a poolin use: at most MaxOpenConns(default 0 = unlimited)wait queue (connRequests)WaitCount; ctx ends the waitidle list: MaxIdleConns(default 2)PostgreSQL backendsbackend process 1backend process 2backend process 3closedMaxIdleTime / MaxLifetimesql.Open creates no connection; the first query or Ping dials one.Rows not closed keep a connection "in use" until Close or EOF.

Driverها: pgx stdlib، lib/pq قدیمی، go-sql-driver/mysql مهم ​

به زبان ساده: database/sql زبان هیچ پایگاه داده‌ای را بلد نیست. بستهٔ راه‌انداز (Driver) با یک نام ثبت می‌شود و پروتکل را پیاده می‌کند؛ با blank import و همان نام در sql.Open انتخابش می‌کنید.

بدفهمی رایج: «همهٔ driverهای PostgreSQL زیر database/sql یکسان‌اند.» در لغو تفاوت دارند؛ pgx اتصال را می‌بندد یا CancelRequest می‌فرستد، ببینید context. پشتیبانی نوع‌هایی مثل array، jsonb و numeric، prepare ضمنی و وضعیت نگهداری هم متفاوت است.

تعریف: driver، driver.Driver یا driver.Connector و driver.Conn را پیاده می‌کند. رابط‌های اختیاری QueryerContext، ExecerContext، ConnBeginTx، Pinger، SessionResetter و NamedValueChecker پشتیبانی context، اجرای مستقیم بدون prepare، سطح جداسازی، بررسی سلامت و نوع آرگومان اختصاصی را فعال می‌کنند.

import _ "github.com/jackc/pgx/v5/stdlib"   // init(): sql.Register("pgx", ...)
db, _ := sql.Open("pgx", "postgres://app:secret@db:5432/orders?sslmode=verify-full")
   -> database/sql: look up "pgx" -> driver.Open(dsn) on first use -> *stdlib.Conn wraps *pgx.Conn

سناریوی واقعی: تیمی از lib/pq به pgx می‌رود چون COPY و LISTEN با reconnect می‌خواهد؛ سرویس MySQL برای خواندن DATETIME در time.Time به placeholderهای ? و parseTime=true در DSN نیاز دارد. کتابخانه‌ای مثل goose، sqlx یا otelsql فقط *sql.DB می‌پذیرد و pool بومی با stdlib.OpenDBFromPool در اختیارش قرار می‌گیرد.

Driverنام در sql.Openجای‌نگهداروضعیت / نکته
github.com/jackc/pgx/v5/stdlib"pgx" و "pgx/v5"$1؛ بدون پارامتر نام‌دار از راه database/sqlتوسعهٔ فعال؛ (*sql.Conn).Raw دسترسی به *pgx.Conn می‌دهد
github.com/lib/pq"postgres"$1مدت طولانی در نگهداری؛ README نسخهٔ v1.10.9، pgx را توصیه می‌کند؛ انتشار از 2026 از سر گرفته شد؛ اغلب کد قدیمی
github.com/go-sql-driver/mysql"mysql"?MySQL/MariaDB؛ گزینه‌های DSN یعنی interpolateParams و parseTime
modernc.org/sqlite، github.com/mattn/go-sqlite3"sqlite"، "sqlite3"?، $1Pure Go در برابر cgo
github.com/microsoft/go-mssqldb"sqlserver"@p1SQL Server

راه‌حل / روش استفاده: برای PostgreSQL، pgx را انتخاب کنید؛ اگر سازگاری database/sql لازم است adapter stdlib، وگرنه API بومی آن را بگیرید (pgx بومی). قاعدهٔ README برای native: "is recommended when: 1. The application only targets PostgreSQL. 2. No other libraries that require database/sql are in use."

اجرای query: QueryContext/QueryRowContext/ExecContext و rows.Next/Scan/Err/Close حیاتی ​

به زبان ساده: QueryContext مکان‌نمای نتیجه (Cursor) می‌دهد که باید پیمایش کنید و ببندید؛ QueryRowContext برای یک سطر است و هنگام Scan اتصال را آزاد می‌کند. ExecContext برای دستورهای بدون سطر خروجی است. همیشه نسخه‌های Context را به کار ببرید.

بدفهمی رایج: «حلقه تمام شد، پس همه‌چیز درست بود.» Next هم در پایان و هم هنگام خطا false می‌دهد: "Rows.Err should be consulted to distinguish between the two cases." وگرنه قطع اتصال وسط جریان شبیه فهرست کوتاه‌تر دیده می‌شود. اشتباه دوم: «defer rows.Close() اختیاری است.» وقتی Next مقدار false می‌دهد، rows خودش بسته می‌شود؛ ولی خروج زودهنگام با return، خطای Scan یا break اتصال را مشغول می‌گذارد، تا شاید garbage collector برسد.

تعریف: Rows.Next، "prepares the next result row for reading with the Rows.Scan method"؛ "Every call to Rows.Scan, even the first one, must be preceded by a call to Rows.Next." Rows.Close تکرارپذیر است "and does not affect the result of Rows.Err". Scan به *string، *[]byte، pointerهای integer و float، *bool، *time.Time، *any، *sql.RawBytes و هر Scanner تبدیل می‌کند و overflow را می‌سنجد: "a float64 with value 300 or a string with value "300" can scan into a uint16, but not into a uint8". متدهای بدون Context یعنی Query و Exec نسخهٔ Context را با context.Background() صدا می‌زنند.

1  rows, err := db.QueryContext(ctx, q, 42)   conn#3 borrowed
2  defer rows.Close()
3  for rows.Next() {                          row 1, row 2, ...
4      rows.Scan(&a, &b)
5  }                                          Next == false: EOF or error
6  if err := rows.Err(); err != nil { ... }   tells the two apart
7  return                                     Close (no-op if already closed); conn#3 back to the pool

سناریوی واقعی: export بعد از failover بی‌صدا نصف CSV را تولید می‌کند چون rows.Err() بررسی نشده؛ API هر چند ساعت به کمبود اتصال می‌خورد چون مسیر خطای Scan بدون بستن برگشته است. کاربرد درست و رایج دیگر، QueryRowContext برای INSERT ... RETURNING id است.

نیازفراخوانینکته
چند سطرQueryContextdefer rows.Close() و بررسی rows.Err()
یک سطرQueryRowContext(...).Scan(...)Row.Err() از Go 1.15 برای بررسی بدون scan
INSERT ... RETURNINGQueryRowContextستون‌های برگشتی را scan کنید
بدون سطر خروجیExecContextResult.RowsAffected()؛ driverهای PostgreSQL، LastInsertId ندارند
نتیجهٔ عظیمQueryContext و streamingدر slice جمع نکنید؛ Cursors & Streaming
چند result setrows.NextResultSet()از Go 1.8؛ وابسته به driver

راه‌حل / روش استفاده: متد ByCustomer در بعد الگوست؛ TestRowsErrIsReported، driver جعلی را بعد از سطر اول خراب می‌کند و بررسی می‌کند خطا از rows.Err() بیرون بیاید.

وقتی سطری نیست: sql.ErrNoRows حیاتی ​

به زبان ساده: اگر QueryRowContext چیزی پیدا نکند، خطا هنگام Scan به شکل sql.ErrNoRows ظاهر می‌شود. پایگاه داده خراب نشده؛ همان‌جا آن را به «پیدا نشد» دامنه تبدیل کنید.

بدفهمی رایج: «خود QueryRowContext خطا را برمی‌گرداند.» خروجی آن *Row است که "defers this error until a Scan". از طرف دیگر QueryContext با صفر سطر اصلاً خطا ندارد؛ فقط حلقه خالی است.

تعریف: var ErrNoRows = errors.New("sql: no rows in result set") که "returned by Row.Scan when DB.QueryRow doesn't return a row". در pgx، pgx.ErrNoRows با متن "no rows in result set" از 5.7.0، sql.ErrNoRows را wrap می‌کند؛ پس errors.Is(err, sql.ErrNoRows) برای هر دو API جواب می‌دهد و تست errs همین را می‌سنجد.

1  err := db.QueryRowContext(ctx, `SELECT ... WHERE id = $1`, 99).Scan(&o.ID, ...)
2  errors.Is(err, sql.ErrNoRows)  -> true
3  return fmt.Errorf("get order 99: %w", ErrNotFound)   -> handler maps ErrNotFound to 404

سناریوی واقعی: handler هر خطایی را log می‌کند و برای id ناشناخته 500 می‌دهد؛ repository برای not-found مقدار (nil, nil) می‌دهد و صدازننده nil را dereference می‌کند؛ یا «find or create» پس از ErrNoRows با insert هم‌زمان مسابقه می‌دهد؛ به‌جایش INSERT ... ON CONFLICT بزنید.

وضعیتنتیجهنگاشت به
QueryRowContext چیزی نمی‌یابدsql.ErrNoRows در ScanErrNotFound دامنه
QueryContext چیزی نمی‌یابدبدون خطا، صفر تکرارslice خالی
UPDATE چیزی نمی‌گیردRowsAffected() == 0نبودن یا تعارض نسخه
CollectOneRow در pgx چیزی نمی‌یابدpgx.ErrNoRows با errors.Is برای sql.ErrNoRowsErrNotFound دامنه
CollectExactlyOneRow در pgx دو سطر می‌یابدpgx.ErrTooManyRowsباگ یا constraint جاافتاده

راه‌حل / روش استفاده: با errors.Is بررسی کنید، خطای دامنه را با %w wrap کنید و نگذارید ErrNoRows از repository بیرون برود؛ Get در بعد همین کار را می‌کند.

مدیریت NULL: sql.NullString، sql.Null[T] در 1.22 و pointerها حیاتی ​

به زبان ساده: NULL در SQL داخل string یا int64 معمولی Go جا نمی‌گیرد. مقصد Scan باید بتواند «مقداری نیست» را نمایش دهد: structی مثل sql.NullString، نوع جنریک sql.Null[T] یا اشاره‌گر (Pointer).

بدفهمی رایج: «رشتهٔ خالی همان NULL است.» در PostgreSQL، '' و NULL متفاوت‌اند؛ برخلاف Oracle Database که مستند SQL آن می‌گوید "currently treats a character value with a length of zero as null". خواندن NULL در string ساده با "converting NULL to string is unsupported" شکست می‌خورد؛ خروجی واقعی تست nulls همین است.

تعریف: structهای نوع‌دار NullString، NullInt64، NullInt32 از 1.13، NullInt16 و NullByte از 1.17، NullFloat64، NullBool و NullTime از 1.13، یک فیلد مقدار و Valid bool دارند. sql.Null[T] در Go 1.22 همان struct { V T; Valid bool } با پیاده‌سازی Scanner و Valuer است؛ "T should be one of the types accepted by driver.Value". مقصد pointer یعنی **string که به‌شکل &p می‌دهید، برای NULL برابر nil می‌شود. در مسیر نوشتن هم pointer nil یا مقدار با Valid == false به NULL تبدیل می‌شود.

row: (id=1, middle_name=NULL, deleted_at=NULL, phone=NULL)
Scan(&c.ID, &c.MiddleName, &c.DeletedAt, &c.Phone)
  c.MiddleName = sql.NullString{String: "", Valid: false}
  c.DeletedAt  = sql.Null[time.Time]{V: zero, Valid: false}
  c.Phone      = (*string)(nil)
Scan(&plainString) on NULL -> error: converting NULL to string is unsupported

سناریوی واقعی: پس از nullable شدن ستون در migration، صفحهٔ پروفایل کاربران بدون تلفن خراب می‌شود؛ API باید در JSON مقدار null بدهد، درحالی‌که pointer به null و sql.NullString بدون wrapper به object تبدیل می‌شود. اگر دامنه واقعاً مفهوم NULL ندارد، COALESCE(note, '') در SQL انتخاب مناسبی است.

روشScanJSONAllocationمناسب برای
sql.NullString و مشابهبلهشیء {"String":..,"Valid":..}نداردکد قدیمی و پیش‌فرض sqlc با database/sql
sql.Null[T] از 1.22بلهشیء {"V":..,"Valid":..}نداردهر نوع، از جمله نوع خودتان
pointer از نوع *Tبلهnull یا مقداریکی برای هر مقدار غیرNULLstructهای API، pgx و sqlc با emit_pointers_for_null_types
pgtype.Text، pgtype.Int8بله، pgxJSON را پیاده می‌کندنداردکد بومی pgx
COALESCE در SQLنامربوطنامربوطنداردوقتی NULL در دامنه معنایی ندارد

راه‌حل / روش استفاده: در هر codebase یک رویه داشته باشید؛ pointer در مرزها و sql.Null[T] در structهای ذخیره‌سازی تقسیم مناسبی است. مسیر NULL و غیرNULL را هر دو تست کنید.

go
// Package nulls shows the three ways to scan a nullable column with
// database/sql: the typed Null* structs, sql.Null[T] (Go 1.22) and pointers.
package nulls

import (
	"context"
	"database/sql"
	"time"
)

// Customer keeps NULL-ability explicit in three styles; pick one per codebase.
type Customer struct {
	ID         int64
	MiddleName sql.NullString      // pre-generics style: NullString, NullInt64, NullTime, ...
	DeletedAt  sql.Null[time.Time] // Go 1.22+: one generic type for any column type
	Phone      *string             // pointer: nil means NULL; what pgx scans NULL into (sqlc emits it only with emit_pointers_for_null_types: true)
}

// Get scans a row whose last three columns may be NULL.
func Get(ctx context.Context, db *sql.DB, id int64) (Customer, error) {
	var c Customer
	err := db.QueryRowContext(ctx,
		`SELECT id, middle_name, deleted_at, phone FROM customers WHERE id = $1`, id,
	).Scan(&c.ID, &c.MiddleName, &c.DeletedAt, &c.Phone)
	return c, err
}

// SetPhone writes NULL when phone is nil: a nil *string and a zero-Valid Null[T]
// are both sent as NULL by database/sql.
func SetPhone(ctx context.Context, db *sql.DB, id int64, phone *string) error {
	_, err := db.ExecContext(ctx, `UPDATE customers SET phone = $1 WHERE id = $2`, phone, id)
	return err
}

// NullIfEmpty turns "" into NULL, the usual rule for optional form fields.
func NullIfEmpty(s string) sql.Null[string] {
	return sql.Null[string]{V: s, Valid: s != ""}
}
go
package nulls

import (
	"database/sql/driver"
	"testing"
	"time"

	"academy/database-sql-pgx/internal/fakedb"
)

func TestScanNulls(t *testing.T) {
	deleted := time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC)
	fake := fakedb.New(func(kind, q string, args []any) fakedb.Response {
		cols := []string{"id", "middle_name", "deleted_at", "phone"}
		if args[0] == int64(1) {
			return fakedb.Response{Columns: cols, Rows: [][]driver.Value{{int64(1), nil, nil, nil}}}
		}
		return fakedb.Response{Columns: cols, Rows: [][]driver.Value{{int64(2), "Ann", deleted, "+1-555-0100"}}}
	})
	db := fake.Open()

	c, err := Get(t.Context(), db, 1)
	if err != nil {
		t.Fatal(err)
	}
	if c.MiddleName.Valid || c.DeletedAt.Valid || c.Phone != nil {
		t.Fatalf("all three should be NULL: %+v", c)
	}
	c, err = Get(t.Context(), db, 2)
	if err != nil {
		t.Fatal(err)
	}
	if c.MiddleName.String != "Ann" || !c.DeletedAt.V.Equal(deleted) || *c.Phone != "+1-555-0100" {
		t.Fatalf("values not scanned: %+v", c)
	}
}

func TestScanNullIntoStringFails(t *testing.T) {
	fake := fakedb.New(func(string, string, []any) fakedb.Response {
		return fakedb.Response{Columns: []string{"phone"}, Rows: [][]driver.Value{{nil}}}
	})
	var phone string // not nullable
	err := fake.Open().QueryRowContext(t.Context(), "SELECT phone FROM customers").Scan(&phone)
	if err == nil {
		t.Fatal("scanning NULL into a plain string must fail")
	}
	t.Log(err) // converting NULL to string is unsupported
}

func TestWriteNull(t *testing.T) {
	fake := fakedb.New(nil)
	if err := SetPhone(t.Context(), fake.Open(), 7, nil); err != nil {
		t.Fatal(err)
	}
	if got := fake.Calls()[1].Args[0]; got != nil {
		t.Fatalf("nil *string should be sent as NULL, got %#v", got)
	}
	if v := NullIfEmpty(""); v.Valid {
		t.Fatal("empty string should be NULL")
	}
}

جای‌نگهدارها: $1 در برابر ? و تزریق SQL حیاتی ​

به زبان ساده: SQL را با چسباندن مقدارها به رشته نسازید. جای‌نگهدار (Placeholder) بنویسید و مقدار را جدا بدهید؛ driver آن را به‌عنوان داده می‌فرستد و quote ورودی نمی‌تواند literal رشته را تمام کند.

بدفهمی رایج: «database/sql، ? را برای هر پایگاه ترجمه می‌کند.» این بسته اصلاً متن SQL را دست نمی‌زند. شکل placeholder متعلق به driver است: PostgreSQL از $1, $2، MySQL و SQLite از ? و SQL Server از @p1 استفاده می‌کنند. راهنمای go.dev: "Parameter placeholders vary depending on the DBMS and driver you're using. For example, pq driver for Postgres accepts a placeholder form such as $1 instead of ?."

تعریف: در pgx با حالت اجرای پیش‌فرض، متن SQL در پیام Parse و مقدارها در Bind می‌روند؛ سرور ورودی کاربر را به‌عنوان SQL parse نمی‌کند. go-sql-driver/mysql با interpolateParams=true برای کاهش رفت‌وبرگشت، یک رشتهٔ query در کلاینت می‌سازد؛ README هشدار می‌دهد این کار فقط با charset مؤثرِ معلوم امن است. شناسه‌ها (Identifier)، مثل نام جدول و ستون، placeholder نمی‌پذیرند؛ با pgx.Identifier{name}.Sanitize() quote کنید یا از allow-list انتخاب کنید.

Before: "... WHERE email = '" + email + "'"     email = x' OR '1'='1
        -> WHERE email = 'x' OR '1'='1'         every row returned, args = []
After:  "... WHERE email = $1", email
        -> Parse("... = $1") Bind(["x' OR '1'='1"])   no row matches, args = [input]

سناریوی واقعی: جست‌وجویی که با ' OR '1'='1 همهٔ مشتریان را بیرون می‌دهد؛ ORDER BY ساخته‌شده از پارامتر درخواست که باید از map ستون‌های مجاز انتخاب شود؛ جست‌وجوی LIKE که % کاربر باید escape شود ولی همچنان آرگومان بماند؛ فهرست IN (...) ساخته‌شده با join رشته‌ای به‌جای = ANY($1).

پایگاه / driverجای‌نگهدارنام‌دارنکته
PostgreSQL / pgx stdlib، lib/pq$1نه؛ در pgx بومی @name با NamedArgs$1 می‌تواند در متن تکرار شود
MySQL / go-sql-driver/mysql?نهگزینهٔ interpolateParams
SQLite / modernc، mattn?، ?NNN، :AAAA، @AAAA، $AAAA طبق مستند expressionsبله، sql.Namedمستند SQLite دربارهٔ ? ساده می‌گوید "is discouraged"
SQL Server / go-mssqldb@p1 تا @pN و @Name طبق READMEبله، sql.Named
Oracle / godror:1، :2 در مثال‌های READMEاین‌جا بررسی نشده

راه‌حل / روش استفاده: همیشه placeholder؛ برای فهرست، slice و = ANY($1)؛ برای identifier، allow-list. دو تست Go نشان می‌دهند ورودی تزریق‌شده در store قبل داخل متن SQL است و در store بعد به‌صورت آرگومان می‌رسد.

دستور آماده: Stmt و prepare ضمنی روی هر اتصال مهم ​

به زبان ساده: دستور آماده (Prepared statement) SQLی است که سرور یک‌بار parse و شاید plan کرده، با نامی در یک اتصال نگه می‌دارد و بارها با مقدارهای متفاوت اجرا می‌کند. در Go معمولاً prepare دستی لازم نیست؛ driver انجامش می‌دهد و *sql.Stmt پنهان می‌کند که در واقع «یک prepare برای هر اتصال» داریم.

بدفهمی رایج: «db.Prepare فقط یک‌بار در سرور آماده می‌کند.» prepared statement سرور متعلق به یک نشست (Session) است. مستند: "If a Stmt is prepared on a DB, it will remain usable for the lifetime of the DB. When the Stmt needs to execute on a new underlying connection, it will prepare itself on the new connection automatically." با 20 اتصال تا 20 prepare داریم. Stmt ساخته‌شده روی Tx نیز "will be bound to a single underlying connection forever" و با پایان Tx غیرقابل استفاده می‌شود.

تعریف: database/sql ابتدا QueryerContext/ExecerContext و سپس رابط‌های منسوخ Queryer/Execer را امتحان می‌کند. تنها اگر اتصال هیچ‌کدام را نداشته باشد prepare می‌کند. مستند driver دربارهٔ DB.Query می‌گوید "will first prepare a query, execute the statement, and then close the statement"؛ در queryDC، ctxDriverPrepare بعد از هر دو بررسی صدا زده می‌شود. پس هر QueryContext هزینهٔ Prepare و Execute دارد؛ همان prepare ضمنی روی هر اتصال. stdlib در pgx هر دو رابط را پیاده کرده و از cache دستور خودش استفاده می‌کند. در PostgreSQL، "Prepared statements only last for the duration of the current database session"؛ با plan_cache_mode = auto، "the first five executions are done with custom plans" و بعد سرور plan عمومی را بررسی می‌کند.

pool of 3 connections, stmt := db.Prepare(q)       prepared on conn#1
G1 stmt.Query  -> conn#1 free, already prepared     Bind/Execute
G2 stmt.Query  -> conn#1 busy, take conn#2          Parse on conn#2, then Execute
G3 stmt.Query  -> conn#3                            Parse on conn#3, then Execute
stmt.Close()   -> closes it on conn#1..#3

سناریوی واقعی: جست‌وجوی پرتکرار قیمت که هنگام startup آماده می‌شود و دوباره استفاده می‌شود؛ حلقهٔ insert انبوه در یک Transaction با tx.PrepareContext؛ driver قدیمی بدون QueryerContext و Queryer که رفت‌وبرگشت هر query را دوبرابر کرده؛ خطای ERROR: cached plan must not change result type پس از ALTER TABLE وقتی کلاینت prepared SELECT * نگه داشته است.

روشآماده‌کنندهمحل نگهداریهزینه
db.QueryContext با pgx stdlibcache دستور pgxهر اتصال، LRU با 512 ورودیاولین استفاده در هر اتصال یک رفت‌وبرگشت اضافه
db.QueryContext با driver بدون QueryerContext و Queryerdatabase/sqlدر هر فراخوانی آماده و بسته می‌شودهر بار 2–3 رفت‌وبرگشت
db.PrepareContext → *sql.Stmtdatabase/sqlتنبل روی هر اتصال مورد استفادهprepare برای هر اتصال؛ Close لازم
tx.PrepareContextdatabase/sqlاتصال همان txبسته شدن در Commit/Rollback
SQL PREPARE name AS ...شماSessionپشت transaction pooling می‌شکند

راه‌حل / روش استفاده: با pgx، db.Prepare را کنار بگذارید؛ cache انجامش می‌دهد. با driverهای دیگر فقط دستورهای هزاران‌بار اجراشونده را prepare کنید. تست‌ها فراخوانی driver جعلی را می‌شمارند: سه query با driver دارای فقط Prepare، بدون QueryerContext و Queryer، سه prepare و سه close می‌دهد. یک Stmt در سطح DB هم وقتی اتصال اولش مشغول باشد روی اتصال تازه دوباره آماده می‌شود.

go
// Package prepared shows explicit *sql.Stmt use. A Stmt prepared on the DB is
// re-prepared lazily on every pool connection it runs on; a Stmt prepared on a
// Tx lives and dies with that transaction.
package prepared

import (
	"context"
	"database/sql"
	"fmt"
)

// PriceLookup prepares one hot statement at startup and reuses it.
type PriceLookup struct{ stmt *sql.Stmt }

// NewPriceLookup prepares on the pool. Close it on shutdown.
func NewPriceLookup(ctx context.Context, db *sql.DB) (*PriceLookup, error) {
	st, err := db.PrepareContext(ctx, `SELECT price_cents FROM products WHERE sku = $1`)
	if err != nil {
		return nil, fmt.Errorf("prepare price lookup: %w", err)
	}
	return &PriceLookup{stmt: st}, nil
}

// Price runs the prepared statement; safe for concurrent use.
func (p *PriceLookup) Price(ctx context.Context, sku string) (int64, error) {
	var cents int64
	err := p.stmt.QueryRowContext(ctx, sku).Scan(&cents)
	return cents, err
}

// Close releases the statement on every connection it was prepared on.
func (p *PriceLookup) Close() error { return p.stmt.Close() }

// InsertLines uses a transaction-scoped statement for a loop of inserts.
func InsertLines(ctx context.Context, db *sql.DB, orderID int64, skus []string) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	st, err := tx.PrepareContext(ctx, `INSERT INTO order_lines (order_id, sku) VALUES ($1, $2)`)
	if err != nil {
		return err
	}
	defer st.Close() // also closed automatically at Commit/Rollback

	for _, sku := range skus {
		if _, err := st.ExecContext(ctx, orderID, sku); err != nil {
			return fmt.Errorf("insert %s: %w", sku, err)
		}
	}
	return tx.Commit()
}
go
package prepared

import (
	"database/sql/driver"
	"sync"
	"testing"

	"academy/database-sql-pgx/internal/fakedb"
)

func priceFake() *fakedb.DB {
	return fakedb.New(func(kind, q string, _ []any) fakedb.Response {
		return fakedb.Response{Columns: []string{"price_cents"}, Rows: [][]driver.Value{{int64(1999)}}}
	})
}

// A driver without QueryerContext forces database/sql to prepare every query.
func TestImplicitPreparePerQuery(t *testing.T) {
	fake := priceFake()
	fake.NoQueryer = true
	db := fake.Open()
	for range 3 {
		if err := db.QueryRowContext(t.Context(), "SELECT 1").Scan(new(int64)); err != nil {
			t.Fatal(err)
		}
	}
	if fake.Count("prepare") != 3 || fake.Count("close-stmt") != 3 {
		t.Fatalf("calls %v", fake.Kinds())
	}
}

// A DB-level Stmt is prepared once per connection it is used on.
func TestStmtReprepareOnNewConnection(t *testing.T) {
	fake := priceFake()
	db := fake.Open()
	p, err := NewPriceLookup(t.Context(), db) // prepared on connection 1
	if err != nil {
		t.Fatal(err)
	}
	defer p.Close()

	// Two concurrent callers while connection 1 is held force a second connection.
	held, _ := db.Conn(t.Context())
	var wg sync.WaitGroup
	for range 2 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if _, err := p.Price(t.Context(), "A1"); err != nil {
				t.Error(err)
			}
		}()
	}
	wg.Wait()
	held.Close()
	if fake.Opens() < 2 || fake.Count("prepare") < 2 {
		t.Fatalf("opens=%d prepares=%d", fake.Opens(), fake.Count("prepare"))
	}
	t.Logf("connections=%d prepares=%d", fake.Opens(), fake.Count("prepare"))
}

func TestTxStmt(t *testing.T) {
	fake := fakedb.New(func(string, string, []any) fakedb.Response { return fakedb.Response{Affected: 1} })
	if err := InsertLines(t.Context(), fake.Open(), 7, []string{"A1", "B2", "C3"}); err != nil {
		t.Fatal(err)
	}
	if fake.Count("prepare") != 1 || fake.Count("exec") != 3 || fake.Count("commit") != 1 {
		t.Fatalf("calls %v", fake.Kinds())
	}
}

حالت‌های cache دستور در pgx: QueryExecMode مهم ​

به زبان ساده: pgx اولین بار که اتصال یک query را می‌بیند آن را آماده می‌کند، از hash متن SQL نام می‌سازد و دوباره استفاده می‌کند. query تکراری یک رفت‌وبرگشت و اطلاعات نوع کامل دارد؛ ولی فرض می‌شود شکل دستور ثابت است و اتصال در اختیار شما می‌ماند. پنج حالت، این بده‌بستان را تغییر می‌دهند.

بدفهمی رایج: «خاموش کردن cache یعنی pgx مقدارها را در متن SQL می‌گذارد.» فقط پروتکل ساده (Simple protocol) درون‌یابی کلاینت انجام می‌دهد؛ QueryExecModeExec همچنان پارامترها را جدا می‌فرستد، فقط statement نام‌دار نمی‌سازد.

تعریف: طبق conn.go در v5.8.0:

حالت (default_query_exec_mode=)رفت‌وبرگشتstatement نام‌دارخطر / محدودیت
QueryExecModeCacheStatement (cache_statement، پیش‌فرض)1 پس از اولین باربله، stmtcache_<sha256 prefix>"If the database schema is modified or the search_path is changed after a statement is cached then the first execution of a previously cached query may fail"
QueryExecModeCacheDescribe (cache_describe)1 پس از اولین بارنه؛ description را cache می‌کندهمان محدودیت تغییر schema
QueryExecModeDescribeExec (describe_exec)2نه؛ statement بی‌نام"may cause problems with connection poolers that switch the underlying connection between round trips"
QueryExecModeExec (exec)1نهاستنباط نوع از مقدار Go؛ قالب text؛ رد نوع مبهم مثل map[string]string
QueryExecModeSimpleProtocol (simple_protocol)1نهدرون‌یابی در کلاینت؛ []byte از نوع bytea؛ رفع تزریق در batchهای simple protocol در 5.12.0

statement_cache_capacity و description_cache_capacity هر دو پیش‌فرض 512 دارند و اندازهٔ cacheهای LRU هر اتصال را تعیین می‌کنند. انتخاب برای یک query هم ممکن است: حالت را آرگومان اول بدهید، مثل pool.Query(ctx, sql, pgx.QueryExecModeExec, args...).

conn#1 first  Query("SELECT ... $1", 7)   Parse "stmtcache_9f2c..." + Describe, then Bind/Execute   2 round trips
conn#1 second Query("SELECT ... $1", 8)   Bind/Execute stmtcache_9f2c...                            1 round trip
ALTER TABLE orders ADD COLUMN note text   (SELECT * now returns one more column)
conn#1 third  Query(...)                  ERROR: cached plan must not change result type -> pgx drops the entry; next call re-prepares

سناریوی واقعی: SELECT * بلافاصله بعد از migration روی هر اتصال یک‌بار شکست می‌خورد؛ ستون‌ها را صریح بنویسید. سرویس پشت PgBouncer 1.18 خطای prepared statement "stmtcache_..." does not exist می‌گیرد؛ به exec بروید. ابزار گزارش queryهای یک‌بارمصرف زیادی دارد و cache را پر می‌کند؛ ظرفیت را کم کنید یا exec بگذارید.

راه‌حل / روش استفاده: اتصال مستقیم به PostgreSQL با پیش‌فرض مناسب است. پشت transaction pooler بدون رهگیری prepared statement، exec یا در pgx ≥ 5.12.0، simple_protocol بگذارید. در query برنامه هرگز SELECT * ننویسید. تست pgxnative از DSN مقدارهای default_query_exec_mode=exec&statement_cache_capacity=128 را parse و هر دو را بررسی می‌کند.

تراکنش‌ها: BeginTx، سطح جداسازی، Commit/Rollback و الگوی defer Rollback حیاتی ​

به زبان ساده: BeginTx یک اتصال رزرو و تراکنش (Transaction) را روی آن شروع می‌کند. تمام دستورها باید از *sql.Tx برگشتی بگذرند؛ Commit تغییرها را ثبت و اتصال را پس می‌دهد. بلافاصله بعد از BeginTx، defer tx.Rollback() بگذارید تا هر خروج زودهنگام، خطا یا panic کار را برگرداند.

بدفهمی رایج: «db.ExecContext داخل تابع Transaction، جزو همان Transaction است.» راهنمای go.dev: "take care not to call the non-transaction sql.DB methods directly, too, as those will execute outside the transaction, giving your code an inconsistent view of the state of the database or even causing deadlocks". اشتباه دیگر اجرای BEGIN با db.ExecContext است. همان راهنما می‌گوید "Do not use transaction-related SQL statements such as BEGIN and COMMIT directly"، چون دستور بعدی شاید روی اتصال دیگری اجرا شود.

تعریف: از Go 1.8، BeginTx(ctx, *sql.TxOptions{Isolation, ReadOnly}) داریم. "The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled." همچنین "If a non-default isolation level is used that the driver doesn't support, an error will be returned." سطح جداسازی (Isolation level) یکی از LevelDefault، LevelReadUncommitted، LevelReadCommitted، LevelWriteCommitted، LevelRepeatableRead، LevelSnapshot، LevelSerializable و LevelLinearizable است. driverهای PostgreSQL چهار سطح ANSI را نگاشت می‌کنند؛ PostgreSQL، Read Uncommitted را Read Committed می‌گیرد. تضمین هر سطح در Isolation Levels است. پس از Commit یا Rollback هر متد sql.ErrTxDone با متن "sql: transaction has already been committed or rolled back" می‌دهد. در pgx بومی، pgx.TxOptions{IsoLevel: pgx.Serializable, AccessMode: pgx.ReadOnly, DeferrableMode: pgx.Deferrable} داریم؛ Rollback، "is safe to call even if the tx is already closed". tx.Begin داخل Transaction یک نقطهٔ ذخیره (Savepoint) یا شبه‌Transaction تو‌در‌تو می‌سازد و pgx.BeginFunc/BeginTxFunc کل الگو را می‌پوشانند.

     G1 (Transfer)                                   PostgreSQL session on conn#4
1    tx, _ := db.BeginTx(ctx, nil)                   BEGIN
2    defer tx.Rollback()
3    tx.ExecContext(debit)                           UPDATE accounts ... id=1
4    tx.ExecContext(credit) -> error                 UPDATE accounts ... id=2  (fails)
5    return err  -> deferred Rollback                ROLLBACK   (debit undone)
     --- success path ---
5'   tx.Commit()                                     COMMIT
6'   deferred Rollback -> sql.ErrTxDone, no SQL      conn#4 back in the pool

سناریوی واقعی: انتقال میان کیف‌پول‌ها؛ ساخت سفارش با اقلام و یک سطر outbox؛ «رزرو موجودی، بعد پرداخت» که پرداخت HTTP است و باید بیرون Transaction باشد، ببینید Outbox Pattern. گزارش فقط‌خواندنی با LevelRepeatableRead, ReadOnly: true هم همهٔ queryها را روی یک snapshot می‌بیند.

گزینهdatabase/sqlpgx بومیدستور PostgreSQL
سطح پیش‌فرضnil یا LevelDefaultpgx.TxOptions{}BEGIN؛ پیش‌فرض سرور، معمولاً Read Committed
Repeatable ReadLevelRepeatableReadpgx.RepeatableReadBEGIN ISOLATION LEVEL REPEATABLE READ
SerializableLevelSerializablepgx.SerializableBEGIN ISOLATION LEVEL SERIALIZABLE
فقط خواندنReadOnly: trueAccessMode: pgx.ReadOnlyREAD ONLY
تعویق‌پذیرموجود نیستDeferrableMode: pgx.DeferrableDEFERRABLE برای serializable فقط‌خواندنی
Savepointtx.ExecContext("SAVEPOINT s1")tx.Begin(ctx)SAVEPOINT
MySQL InnoDBTxOptions.IsolationنامربوطSET TRANSACTION ISOLATION LEVEL ...؛ سطح پیش‌فرض در Isolation Levels

راه‌حل / روش استفاده: الگو را یک‌بار در helper بگذارید و همه‌جا استفاده کنید. txn.WithTx آغاز می‌کند، rollback را defer می‌کند، تابع شما را اجرا و commit می‌کند. تست‌ها ترتیب commit، خطا و panic و رسیدن LevelSerializable به driver را می‌سنجند.

go
// Package txn wraps database/sql transactions: one helper with the
// defer-Rollback pattern, and one that retries the whole transaction on
// SQLSTATE 40001 (serialization failure) and 40P01 (deadlock).
package txn

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"math/rand/v2"
	"time"

	"github.com/jackc/pgx/v5/pgconn"
)

// WithTx runs fn inside one transaction: Commit when fn returns nil,
// Rollback on an error or a panic.
func WithTx(ctx context.Context, db *sql.DB, opts *sql.TxOptions, fn func(*sql.Tx) error) error {
	tx, err := db.BeginTx(ctx, opts)
	if err != nil {
		return fmt.Errorf("begin: %w", err)
	}
	// Runs on every exit, including a panic in fn; after Commit it returns
	// sql.ErrTxDone without talking to the server.
	defer func() { _ = tx.Rollback() }()

	if err := fn(tx); err != nil {
		return err
	}
	if err := tx.Commit(); err != nil {
		return fmt.Errorf("commit: %w", err)
	}
	return nil
}

// Retryable reports whether the whole transaction may be run again.
func Retryable(err error) bool {
	var pg *pgconn.PgError
	return errors.As(err, &pg) && (pg.Code == "40001" || pg.Code == "40P01")
}

// Serializable is the option set for transactions that rely on SSI.
var Serializable = &sql.TxOptions{Isolation: sql.LevelSerializable}

// WithRetry runs WithTx up to attempts times while the error is retryable,
// sleeping with jittered exponential backoff, and stops when ctx is done.
// fn must be safe to run more than once: no side effects outside the transaction.
func WithRetry(ctx context.Context, db *sql.DB, opts *sql.TxOptions, attempts int,
	fn func(*sql.Tx) error) error {
	var err error
	for i := range attempts {
		if err = WithTx(ctx, db, opts, fn); err == nil || !Retryable(err) {
			return err
		}
		backoff := time.Duration(1<<i) * 10 * time.Millisecond
		backoff += rand.N(backoff) // full jitter on top of the base
		t := time.NewTimer(backoff)
		select {
		case <-ctx.Done():
			t.Stop()
			return errors.Join(err, ctx.Err())
		case <-t.C:
		}
	}
	return fmt.Errorf("after %d attempts: %w", attempts, err)
}
BeginTx(ctx, opts)pins one connectiondefer tx.Rollback()tx.ExecContext ...tx.Commit()COMMITconn backto the poolROLLBACKerror, panic, or ctx canceledSQLSTATE 40001 / 40P01roll back, back off, run the whole fn againretry loop (bounded attempts, ctx budget)deferred Rollback after a successful Commit is a no-op: it returns sql.ErrTxDoneall statements must use tx, not db: db.ExecContext inside the function runs outside the transactiona Commit that times out has an unknown outcome: read back or use an idempotency key

تلاش مجدد تراکنش پس از serialization failure با کد 40001 مهم ​

به زبان ساده: در Repeatable Read و Serializable، PostgreSQL ممکن است تراکنش (Transaction) را لغو کند تا نمای ناسازگار ندهد. این باگ نیست؛ قرارداد همین است. کل Transaction را از اول و با تعداد تلاش محدود اجرا کنید.

بدفهمی رایج: «فقط دستور شکست‌خورده را دوباره بزن.» مستند PostgreSQL می‌گوید برنامه "should abort the current transaction and retry the whole transaction from the beginning". تکرار یک دستور در Transaction لغوشده، 25P02 in_failed_sql_transaction می‌دهد. «هر خطایی را retry کن» هم غلط است: نقض یکتایی 23505 برای کلید داده‌شده از کلاینت هر بار همان شکست را دارد. استثنا کلیدی است که داخل Transaction از داده‌ها به دست می‌آید. مستند دربارهٔ Serializable می‌گوید "it is possible to see unique constraint violations caused by conflicts with overlapping Serializable transactions even after explicitly checking that the key isn't present"؛ مثل کلیدی بر اساس بیشینهٔ فعلی. تکرار کامل داده را دوباره می‌خواند و شاید کلید آزاد انتخاب کند.

تعریف: 40001 serialization_failure با متن "could not serialize access due to concurrent update" در Repeatable Read یا "due to read/write dependencies among transactions" در Serializable و 40P01 deadlock_detected کدهای قابل retry از class 40 هستند. "Applications using this level must be prepared to retry transactions due to serialization failures." تابع باید اجرای دوباره را تحمل کند: داخل آن email، HTTP call یا send روی channel نباشد.

     T1 (Serializable)                       T2 (Serializable)
1    BEGIN; SELECT sum(...) WHERE doctor=7    BEGIN; SELECT sum(...) WHERE doctor=7
2    UPDATE ... SET on_call=false (Alice)    UPDATE ... SET on_call=false (Bob)
3    COMMIT  -> ok
4                                            COMMIT -> ERROR 40001 (read/write dependencies)
5                                            WithRetry: backoff 10-20 ms, run fn again
6                                            BEGIN; SELECT sees Alice off -> refuses -> COMMIT ok

سناریوی واقعی: برنامهٔ شیفت پزشکان و write skew، رزرو صندلی و بررسی موجودی زیر Serializable؛ deadlock هنگام migration میان دو batch job که سطرها را با ترتیب متفاوت می‌نویسند؛ 40P01 را با retry و ترتیب یکسان اصلاح کنید، ببینید Deadlocks. در CockroachDB هم مستند می‌گوید "By default, CockroachDB executes all transactions at SERIALIZABLE isolation" و خطاهای 40001 با متن "restart transaction" باید در کلاینت retry شوند.

خطاSQLSTATEتکرار Transaction؟چرا
شکست serialization40001بله، با backoffقرارداد RR/Serializable
تشخیص deadlock40P01بله؛ ترتیب lock را هم اصلاح کنیدیک قربانی انتخاب شده
نقض یکتایی، کلید از کلاینت23505نهورودی یکسان، نتیجه یکسان
نقض یکتایی، کلید مشتق‌شده در tx از نوع Serializable23505بله، تکرار کامل و محدودTransactionهای هم‌پوشان؛ retry دوباره می‌خواند
lock در دسترس نیست55P03شاید، پس از backofflock_timeout یا NOWAIT
query لغوشده57014فقط با بودجهٔ کل باقی‌ماندهstatement_timeout یا cancel
شکست اتصال08006فقط اگر نتیجهٔ commit معلوم باشدCOMMIT گم‌شده شاید موفق بوده
context.Canceledنامربوطنهصدازننده رفته است

راه‌حل / روش استفاده: txn.WithRetry فقط Retryable(err) یعنی 40001 و 40P01 را با backoff نمایی و jitter تکرار می‌کند و با پایان ctx می‌ایستد. تست دو commit اول را با 40001 دست‌ساز شکست می‌دهد و سه اجرای تابع را می‌سنجد؛ 23505 فقط یک‌بار اجرا می‌شود. تست دوم context متعلق به BeginTx را لغو و poll می‌کند تا database/sql از goroutine پس‌زمینه rollback کند.

go
package txn

import (
	"context"
	"database/sql"
	"errors"
	"slices"
	"strings"
	"sync/atomic"
	"testing"
	"time"

	"academy/database-sql-pgx/internal/fakedb"
	"github.com/jackc/pgx/v5/pgconn"
)

func TestCommitAndRollback(t *testing.T) {
	fake := fakedb.New(nil)
	db := fake.Open()
	if err := WithTx(t.Context(), db, nil, func(tx *sql.Tx) error {
		_, err := tx.ExecContext(t.Context(), "INSERT INTO t VALUES (1)")
		return err
	}); err != nil {
		t.Fatal(err)
	}
	boom := errors.New("boom")
	if err := WithTx(t.Context(), db, nil, func(*sql.Tx) error { return boom }); !errors.Is(err, boom) {
		t.Fatal(err)
	}
	want := []string{"connect", "begin", "exec", "commit", "begin", "rollback"}
	if got := fake.Kinds(); !slices.Equal(got, want) {
		t.Fatalf("got %v", got)
	}
}

func TestRollbackOnPanic(t *testing.T) {
	fake := fakedb.New(nil)
	func() {
		defer func() { _ = recover() }()
		_ = WithTx(t.Context(), fake.Open(), nil, func(*sql.Tx) error { panic("bug") })
	}()
	if fake.Count("rollback") != 1 {
		t.Fatalf("calls %v", fake.Kinds())
	}
}

func TestIsolationLevelReachesDriver(t *testing.T) {
	fake := fakedb.New(nil)
	_ = WithTx(t.Context(), fake.Open(), Serializable, func(*sql.Tx) error { return nil })
	if q := fake.Calls()[1].Query; !strings.Contains(q, "isolation=Serializable") {
		t.Fatal(q)
	}
}

func TestRetryOnSerializationFailure(t *testing.T) {
	var commits atomic.Int32
	fake := fakedb.New(func(kind, q string, _ []any) fakedb.Response {
		if kind == "commit" && commits.Add(1) < 3 { // fail the first two commits
			return fakedb.Response{Err: &pgconn.PgError{Code: "40001",
				Message: "could not serialize access due to read/write dependencies among transactions"}}
		}
		return fakedb.Response{}
	})
	var runs int
	err := WithRetry(t.Context(), fake.Open(), Serializable, 5, func(*sql.Tx) error { runs++; return nil })
	if err != nil || runs != 3 {
		t.Fatalf("err=%v runs=%d", err, runs)
	}
}

func TestNoRetryOnUniqueViolation(t *testing.T) {
	fake := fakedb.New(nil)
	var runs int
	err := WithRetry(t.Context(), fake.Open(), nil, 5, func(*sql.Tx) error {
		runs++
		return &pgconn.PgError{Code: "23505"}
	})
	if err == nil || runs != 1 {
		t.Fatalf("err=%v runs=%d", err, runs)
	}
}

// database/sql rolls back by itself when the BeginTx context ends; it happens
// in a background goroutine, so the test polls.
func TestContextCancelRollsBack(t *testing.T) {
	fake := fakedb.New(nil)
	db := fake.Open()
	ctx, cancel := context.WithCancel(t.Context())
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		t.Fatal(err)
	}
	cancel()
	deadline := time.Now().Add(time.Second)
	for fake.Count("rollback") == 0 && time.Now().Before(deadline) {
		time.Sleep(5 * time.Millisecond)
	}
	if fake.Count("rollback") != 1 {
		t.Fatalf("calls %v", fake.Kinds())
	}
	if err := tx.Commit(); err == nil {
		t.Fatal("Commit after cancel must fail")
	}
}

لغو: رفتار context و درخواست cancel در pgx مهم ​

به زبان ساده: ctx درخواست را به هر query بدهید. با پایان آن، database/sql انتظار را قطع می‌کند، rows را می‌بندد و Transaction را rollback می‌کند. driver تعیین می‌کند در سرور چه شود: pgx به‌صورت پیش‌فرض اتصال را قطع می‌کند یا با پیکربندی از PostgreSQL می‌خواهد دستور را لغو کند.

بدفهمی رایج: «با انقضای ctx، query در سرور می‌ایستد.» فقط اگر driver درخواست لغو (Cancel request) بفرستد. ناظر context پیش‌فرض pgx v5، "handles canceled contexts by setting a deadline on a net.Conn"؛ فراخوانی Go برمی‌گردد و اتصال بسته می‌شود، ولی سرور بعداً متوجه socket بسته می‌شود. CancelRequestContextWatcherHandler، "handles canceled contexts by sending a cancel request to the server". جزئیات و آزمایش در context است.

تعریف: یادداشت Go 1.8 دربارهٔ متدهای Context: "connections are closed and returned to the connection pool when the request is done; enables canceling in-progress queries should the driver support that; and allows the database pool to cancel waiting for the next available connection." درخواست cancel اتصال جداگانه‌ای است که PID و کلید محرمانهٔ backend را می‌فرستد؛ PostgreSQL در نشست اصلی ERROR: canceling statement due to user request (SQLSTATE 57014) می‌دهد.

t=0     handler ctx (300 ms budget) -> db.QueryContext(ctx, slowReport)
t=300   ctx.Done()
        database/sql: closes the Rows / rolls back the Tx, stops waiting
        pgx default:    net.Conn deadline -> read fails -> "timeout: context deadline exceeded"; conn discarded
        pgx CancelRequest handler: new TCP conn -> CancelRequest(pid, key) -> server: 57014; conn reusable
        lib/pq:         sends a cancel request and marks the connection bad
t=300+  server-side: statement_timeout is still the backstop if neither reached it

سناریوی واقعی: تب dashboard وسط گزارش 20 ثانیه‌ای بسته می‌شود؛ gateway پنج‌ثانیه‌ای جلوی query سی‌ثانیه‌ای قرار دارد؛ shutdown، context ریشه را لغو می‌کند و نباید Transaction نیمه‌کاره بماند، پس rollback می‌شود.

Driverهنگام لغو ctxاتصال پس از آن
pgx v5 پیش‌فرض (DeadlineContextWatcherHandler)deadline روی socketبسته
pgx v5 با CancelRequestContextWatcherHandlerCancelRequest به سروراگر cancel برسد نگه داشته می‌شود
lib/pqدرخواست cancel با sendCancelRequest در watchCancelعلامت bad؛ "so it does not get reused"
go-sql-driver/mysqlبستن اتصال؛ بدون KILL QUERYبسته
هر driver هنگام انتظار ظرفیت pooldatabase/sql انتظار را قطع می‌کندنامربوط

راه‌حل / روش استفاده: همیشه QueryContext؛ statement_timeout را پشتیبان سمت سرور نگه دارید (Timeoutها) و اگر دستورهای طولانی رایج‌اند، handler درخواست cancel را از pgconn.Config.BuildContextWatcherHandler تنظیم کنید.

pgx بومی: API بومی pgx v5، pgx.Conn و pgxpool.Pool حیاتی ​

به زبان ساده: pgx بدون database/sql هم کار می‌کند. pgx.Conn یک اتصال است و استفادهٔ هم‌زمان از آن امن نیست؛ pgxpool.Pool مخزن اتصال (Connection pool) امن برای اشتراک است. متدها شبیه database/sql هستند ولی همه‌جا ctx می‌گیرند و قابلیت‌های PostgreSQL را نشان می‌دهند.

بدفهمی رایج: «pgx.Connect یک pool می‌دهد.» مستند: "*pgx.Conn represents a single connection to the database and is not concurrency safe. Use package github.com/jackc/pgx/v5/pgxpool for a concurrency safe connection pool." اشتراک یک *pgx.Conn بین goroutineها با "conn busy" شکست می‌خورد.

تعریف: سازنده‌ها pgxpool.New(ctx, dsn) و NewWithConfig(ctx, cfg) هستند. عملیات شامل pool.Query، QueryRow، Exec، Begin/BeginTx، SendBatch، CopyFrom، Acquire برای رزرو یک *pgxpool.Conn و Release پس از کار، Ping، Stat و Close است. *pgxpool.Pool، *pgx.Conn و pgx.Tx این مجموعه‌متدها را مشترک دارند؛ interfaceی مثل Querier زیر به repository اجازه می‌دهد روی هر سه کار کند. لایهٔ زیرین pgconn، "a lower level PostgreSQL driver roughly at the level of libpq" است.

1  pool, _ := pgxpool.New(ctx, dsn)          no connection yet
2  rows, _ := pool.Query(ctx, q, args...)    Acquire -> conn#1 (dial) -> query
3  pgx.CollectRows(rows, ...)                reads all, closes rows -> conn#1 released
4  tx, _ := pool.Begin(ctx)                  conn#1 acquired for the whole tx
5  tx.Commit(ctx)                            released

سناریوی واقعی: سرویس فقط PostgreSQL که واردسازی COPY و ابطال cache با LISTEN می‌خواهد؛ sqlc کد pgx/v5 با نوع‌های pgtype تولید می‌کند؛ codebase ترکیبی که goose در آن *sql.DB می‌خواهد و از همان pool با stdlib.OpenDBFromPool(pool) تأمین می‌شود.

قابلیتdatabase/sql + pgx stdlibpgx بومی
pool*sql.DB*pgxpool.Pool
جمع‌آوری در structScan دستی یا sqlx/scanyCollectRows + RowToStructByName
آرگومان نام‌دارنهpgx.NamedArgs، pgx.StrictNamedArgs
batchنهSendBatch
COPYفقط از RawCopyFrom
LISTEN/NOTIFYفقط از RawWaitForNotification
array، range، jsonbاز pgtype.Map.SQLScanner؛ مستقیم در Go 1.27 با pgx ≥ 5.11بومی
hook ردگیریdriver پوشاننده مثل otelsqlConnConfig.Tracer

راه‌حل / روش استفاده: در سرویس جدیدی که فقط PostgreSQL دارد مستقیم از pgxpool استفاده کنید؛ فقط جایی که کتابخانه‌ای الزام دارد *sql.DB عرضه کنید.

go
package pgxnative

import (
	"context"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
)

// Querier is satisfied by *pgxpool.Pool, *pgx.Conn and pgx.Tx.
type Querier interface {
	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
	SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults
	CopyFrom(ctx context.Context, table pgx.Identifier, cols []string, src pgx.CopyFromSource) (int64, error)
}

// Order maps columns by name; the db tag overrides the field name.
type Order struct {
	ID         int64      `db:"id"`
	CustomerID int64      `db:"customer_id"`
	Status     string     `db:"status"`
	TotalCents int64      `db:"total_cents"`
	ShippedAt  *time.Time `db:"shipped_at"` // NULL -> nil
}

// OpenOrders uses named arguments and collects rows straight into structs.
// CollectRows closes rows and returns rows.Err() for you.
func OpenOrders(ctx context.Context, q Querier, customerID int64) ([]Order, error) {
	rows, err := q.Query(ctx, `
SELECT id, customer_id, status, total_cents, shipped_at
FROM orders WHERE customer_id = @customer AND status = @status ORDER BY id`,
		pgx.NamedArgs{"customer": customerID, "status": "open"})
	if err != nil {
		return nil, err
	}
	return pgx.CollectRows(rows, pgx.RowToStructByName[Order])
}

// MarkShipped updates a set of rows with one array parameter.
func MarkShipped(ctx context.Context, q Querier, ids []int64) (int64, error) {
	tag, err := q.Exec(ctx,
		`UPDATE orders SET status = 'shipped', shipped_at = now() WHERE id = ANY($1)`, ids)
	return tag.RowsAffected(), err
}

// CountByStatus sends N small queries in one network round trip.
func CountByStatus(ctx context.Context, q Querier, statuses []string) (map[string]int64, error) {
	b := &pgx.Batch{}
	out := make(map[string]int64, len(statuses))
	for _, s := range statuses {
		b.Queue(`SELECT count(*) FROM orders WHERE status = $1`, s).QueryRow(func(r pgx.Row) error {
			var n int64
			err := r.Scan(&n)
			out[s] = n
			return err
		})
	}
	// Close reads every result and returns the first error.
	return out, q.SendBatch(ctx, b).Close()
}

// NewOrder is one row of an import.
type NewOrder struct {
	CustomerID int64
	Email      string
	TotalCents int64
}

// ImportColumns are the columns Import copies. COPY fills omitted columns with
// their defaults, so every NOT NULL column without a default in schema.sql must
// be listed here (schema_test.go checks it).
var ImportColumns = []string{"customer_id", "email", "total_cents"}

// Import loads many rows with the COPY protocol: one statement, streamed.
func Import(ctx context.Context, q Querier, orders []NewOrder) (int64, error) {
	return q.CopyFrom(ctx, pgx.Identifier{"orders"}, ImportColumns,
		pgx.CopyFromSlice(len(orders), func(i int) ([]any, error) {
			return []any{orders[i].CustomerID, orders[i].Email, orders[i].TotalCents}, nil
		}))
}

جمع‌آوری سطرها: CollectRows، RowToStructByName و named args مهم ​

به زبان ساده: به‌جای نوشتن حلقهٔ Next/Scan/Err/Close، سطرها و تابع نگاشت را به pgx.CollectRows بدهید. pgx.RowToStructByName[T] ستون‌ها را با نام یا tag db به فیلد struct وصل می‌کند. آرگومان نام‌دار (Named argument) مثل @customer، query طولانی را خواناتر می‌کند.

بدفهمی رایج: «RowToStructByName ستون اضافه یا گمشده را نادیده می‌گیرد.» شرط آن "the same number of named public fields as row has fields" است. نبود ستون خطا می‌دهد؛ خروجی واقعی تست cannot find field customer_id in returned row است. برای struct با فیلد اضافه RowToStructByNameLax و برای کنار گذاشتن یک فیلد db:"-" بگذارید.

تعریف: CollectRows[T](rows, fn RowToFunc[T]) ([]T, error) پیمایش می‌کند، برای هر سطر fn را صدا می‌زند، rows را می‌بندد و rows.Err() را برمی‌گرداند. نتیجهٔ بدون سطر slice خالی است. CollectOneRow برای نتیجهٔ خالی ErrNoRows می‌دهد و CollectExactlyOneRow علاوه بر آن ErrTooManyRows دارد. ForEachRow callback اجرا می‌کند. تطبیق نام به بزرگی حروف حساس نیست و snake_case را پشتیبانی می‌کند. NamedArgs، "will replace every '@' named placeholder with a '$' ordinal placeholder"؛ نام باید با حرف یا underscore شروع شود. StrictNamedArgs همچنین وجود همهٔ نام‌ها و نبود نام اضافه را می‌سنجد. متن داخل quote تغییر نمی‌کند.

SQL in:  ... WHERE customer_id = @customer AND status = @status AND note <> '@x'
args:    pgx.NamedArgs{"customer": 7, "status": "open"}
SQL out: ... WHERE customer_id = $1 AND status = $2 AND note <> '@x'   args [7 "open"]
rows -> CollectRows(rows, RowToStructByName[Order]) -> []Order{...}, rows closed

سناریوی واقعی: endpoint فهرست با بیش از 10 ستون که Scan موقعیتی آن با هر ستون تازه خراب می‌شد؛ query گزارش با یک پارامتر در سه جا که @from فقط یک‌بار در map می‌آید؛ struct دارای فیلد محاسبه‌شده با tag db:"-".

تابعسطر مورد انتظارنگاشتزمان خطا
CollectRows(rows, RowTo[int32])0..nتک‌ستونخطای scan
CollectRows(rows, RowToStructByName[T])0..nنام / tag dbستون یا فیلد گمشده
CollectRows(rows, RowToStructByNameLax[T])0..nنام؛ struct می‌تواند فیلد بیشتر داشته باشدستون ناشناخته
CollectRows(rows, RowToStructByPos[T])0..nموقعیتعدم تطابق تعداد
CollectOneRowاولین سطرهر نگاشتErrNoRows
CollectExactlyOneRowدقیقاً 1هر نگاشتErrNoRows، ErrTooManyRows

راه‌حل / روش استفاده: OpenOrders بالا از NamedArgs و RowToStructByName استفاده می‌کند. تست، pgx.Rows جعلی حداقلی را به CollectRows واقعی می‌دهد، نگاشت NULL به pointer nil و خطای ستون گمشده را می‌سنجد. تست دیگر مستقیم NamedArgs.RewriteQuery را اجرا می‌کند.

go
package pgxnative

import (
	"context"
	"errors"
	"reflect"
	"testing"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
)

// fakeRows is a minimal pgx.Rows so CollectRows/RowToStructByName run for real.
type fakeRows struct {
	cols []string
	data [][]any
	i    int
}

func (r *fakeRows) Close()                        {}
func (r *fakeRows) Err() error                    { return nil }
func (r *fakeRows) CommandTag() pgconn.CommandTag { return pgconn.NewCommandTag("SELECT 2") }
func (r *fakeRows) FieldDescriptions() []pgconn.FieldDescription {
	fd := make([]pgconn.FieldDescription, len(r.cols))
	for i, c := range r.cols {
		fd[i].Name = c
	}
	return fd
}
func (r *fakeRows) Next() bool             { r.i++; return r.i <= len(r.data) }
func (r *fakeRows) Values() ([]any, error) { return r.data[r.i-1], nil }
func (r *fakeRows) RawValues() [][]byte    { return nil }
func (r *fakeRows) Conn() *pgx.Conn        { return nil }
func (r *fakeRows) Scan(dest ...any) error {
	for i, d := range dest {
		v := r.data[r.i-1][i]
		dv := reflect.ValueOf(d).Elem()
		if v == nil {
			dv.SetZero()
			continue
		}
		if dv.Kind() == reflect.Pointer {
			p := reflect.New(dv.Type().Elem())
			p.Elem().Set(reflect.ValueOf(v))
			dv.Set(p)
			continue
		}
		dv.Set(reflect.ValueOf(v))
	}
	return nil
}

type fakeQ struct {
	Querier // unimplemented methods panic if called
	sql     string
	args    []any
	rows    *fakeRows
}

func (f *fakeQ) Query(_ context.Context, sql string, args ...any) (pgx.Rows, error) {
	f.sql, f.args = sql, args
	return f.rows, nil
}

func TestCollectRowsByName(t *testing.T) {
	shipped := time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC)
	q := &fakeQ{rows: &fakeRows{
		cols: []string{"id", "customer_id", "status", "total_cents", "shipped_at"},
		data: [][]any{{int64(1), int64(7), "open", int64(900), nil}, {int64(2), int64(7), "open", int64(50), shipped}},
	}}
	got, err := OpenOrders(t.Context(), q, 7)
	if err != nil {
		t.Fatal(err)
	}
	if len(got) != 2 || got[0].ShippedAt != nil || !got[1].ShippedAt.Equal(shipped) || got[1].TotalCents != 50 {
		t.Fatalf("%+v", got)
	}
	if _, ok := q.args[0].(pgx.NamedArgs); !ok {
		t.Fatal("named args should be the first argument")
	}
}

func TestRowToStructByNameRejectsMissingColumn(t *testing.T) {
	q := &fakeQ{rows: &fakeRows{cols: []string{"id", "status"}, data: [][]any{{int64(1), "open"}}}}
	_, err := OpenOrders(t.Context(), q, 7)
	if err == nil {
		t.Fatal("struct fields without a column must be an error")
	}
	t.Log(err)
	var pg *pgconn.PgError
	if errors.As(err, &pg) {
		t.Fatal("this is a client-side mapping error, not a server error")
	}
}

دسته و بارگذاری انبوه: batch، CopyFrom، COPY، unnest و bulk insert مهم ​

به زبان ساده: دستورهای کوچک فراوان، رفت‌وبرگشت شبکهٔ فراوان دارند. آن‌ها را دسته‌ای (Batch) با pgx.Batch بفرستید، سطرها را از پروتکل COPY با CopyFrom وارد کنید یا array بدهید تا PostgreSQL با unnest و = ANY($1) بازشان کند.

بدفهمی رایج: «batch فقط N دستور مستقل است که با هم فرستاده می‌شوند.» مستند SendBatch: "All queries are run in an implicit transaction unless explicit transaction control statements are executed"؛ شکست یکی، بقیه را هم برمی‌گرداند. همچنین "Depending on the QueryExecMode, all queries may be prepared before any are executed"؛ پس ساخت جدول و استفاده از آن در همان batch شاید شکست بخورد. pgx 5.12+، Batch.BeginTx را برای آغاز Transaction واقعی به‌عنوان query اول batch اضافه می‌کند. باور غلط دیگر این است که VALUES چندسطری بی‌نهایت مقیاس می‌گیرد. شمارندهٔ پارامتر Bind از نوع Int16 است؛ سقف هر دستور 65535 پارامتر است و pgconn برای بیشتر از آن extended protocol limited to %v parameters می‌دهد که %v همان math.MaxUint16 است.

تعریف: Batch.Queue(sql, args...) یک QueuedQuery می‌دهد که callbackهای Query، QueryRow یا Exec آن هنگام رسیدن نتیجه اجرا می‌شوند. SendBatch، BatchResults می‌دهد و Close آن همهٔ نتیجه‌ها را می‌خواند و اولین خطا را برمی‌گرداند. CopyFrom(ctx, pgx.Identifier{"t"}, cols, src) از COPY FROM STDIN در قالب binary استفاده می‌کند؛ منبع‌ها CopyFromRows، CopyFromSlice و CopyFromFunc هستند. مستند: "CopyFrom can be faster than an insert with as few as 5 rows." راهنمای populate در PostgreSQL: "Use COPY to load all the rows in one command, instead of using a series of INSERT commands."

1000 order lines to insert
A) loop of ExecContext INSERT            1000 statements, 1000 round trips (or 1000 Bind/Execute in a tx)
B) multi-row VALUES ($1,$2,$3),...       1 statement per 21845 rows (3 cols x 21845 = 65535 params)
C) INSERT ... SELECT * FROM unnest($1::bigint[], $2::text[], $3::bigint[])   1 statement, 3 params, any size
D) CopyFrom                              1 COPY, streamed, fastest; no ON CONFLICT, no RETURNING

سناریوی واقعی: واردسازی شبانهٔ 2 میلیون سطر، با COPY به جدول موقت میانی و سپس INSERT ... ON CONFLICT؛ dashboard با 12 count کوچک در هر بازدید که یک batch می‌شود؛ job همگام‌سازی با upsert برای 5,000 سطر، با unnest و ON CONFLICT DO UPDATE.

روشرفت‌وبرگشتON CONFLICT / RETURNINGاز database/sqlمحدودیت
حلقهٔ INSERTnبلهبلهتأخیر × n
VALUES چندسطری⌈n·cols/65535⌉بلهبله65535 پارامتر؛ متن تازه برای هر اندازه
arrayهای unnest1بلهبله؛ pgx stdlib، slice می‌فرستدحافظهٔ arrayها
pgx.Batch1بلهنهTransaction ضمنی؛ همه یا هیچ
CopyFrom1 جریاننه؛ از جدول میانی استفاده کنیدفقط Rawtrigger و constraint همچنان اجرا می‌شوند

راه‌حل / روش استفاده: Import و CountByStatus در pgx بومی، CopyFrom و batch را نشان می‌دهند. COPY ستون‌های حذف‌شده را با پیش‌فرض پر می‌کند؛ پس هر ستون NOT NULL بدون پیش‌فرض باید در فهرست باشد. ImportColumns شامل customer_id, email, total_cents است و تست با parse کردن schema آزمایشگاه آن را می‌سنجد. snippet bulk نسخه‌های database/sql را دارد و تست ثابت می‌کند 50,000 سطر سه‌ستونی دقیقاً سه دستور می‌شوند و اولی به ($65533, $65534, $65535) ختم می‌شود.

go
// Package bulk fixes the N+1 query and shows two bulk-insert shapes that work
// through database/sql: = ANY($1) / unnest with array parameters, and chunked
// multi-row VALUES that respect PostgreSQL's 65535-parameter limit.
package bulk

import (
	"context"
	"database/sql"
	"fmt"
	"strings"
)

// Line is one order line.
type Line struct {
	OrderID int64
	SKU     string
	Qty     int64
}

// LinesNPlus1 issues one query per order: 1 + N round trips for a page of N orders.
func LinesNPlus1(ctx context.Context, db *sql.DB, orderIDs []int64) (map[int64][]Line, error) {
	out := map[int64][]Line{}
	for _, id := range orderIDs {
		rows, err := db.QueryContext(ctx, `SELECT order_id, sku, qty FROM order_lines WHERE order_id = $1`, id)
		if err != nil {
			return nil, err
		}
		if err := collect(rows, out); err != nil {
			return nil, err
		}
	}
	return out, nil
}

// LinesBatched issues one query for the whole page. With pgx's stdlib driver
// a []int64 argument is sent as a PostgreSQL bigint[].
func LinesBatched(ctx context.Context, db *sql.DB, orderIDs []int64) (map[int64][]Line, error) {
	rows, err := db.QueryContext(ctx,
		`SELECT order_id, sku, qty FROM order_lines WHERE order_id = ANY($1) ORDER BY order_id, sku`, orderIDs)
	if err != nil {
		return nil, err
	}
	out := map[int64][]Line{}
	return out, collect(rows, out)
}

func collect(rows *sql.Rows, out map[int64][]Line) error {
	defer rows.Close()
	for rows.Next() {
		var l Line
		if err := rows.Scan(&l.OrderID, &l.SKU, &l.Qty); err != nil {
			return err
		}
		out[l.OrderID] = append(out[l.OrderID], l)
	}
	return rows.Err()
}

// InsertUnnest inserts any number of lines with three array parameters: the
// statement text never changes, so it is prepared and cached once.
func InsertUnnest(ctx context.Context, db *sql.DB, lines []Line) (int64, error) {
	ids := make([]int64, len(lines))
	skus := make([]string, len(lines))
	qtys := make([]int64, len(lines))
	for i, l := range lines {
		ids[i], skus[i], qtys[i] = l.OrderID, l.SKU, l.Qty
	}
	res, err := db.ExecContext(ctx, `INSERT INTO order_lines (order_id, sku, qty)
SELECT * FROM unnest($1::bigint[], $2::text[], $3::bigint[])`, ids, skus, qtys)
	if err != nil {
		return 0, err
	}
	return res.RowsAffected()
}

// MaxParams is the Bind message limit: the parameter count is an Int16 (65535).
const MaxParams = 65535

// Chunk is one INSERT statement with its arguments.
type Chunk struct {
	SQL  string
	Args []any
}

// ValuesChunks builds INSERT ... VALUES ($1,$2,$3),($4,...) statements, each
// below MaxParams parameters.
func ValuesChunks(table string, cols []string, rows [][]any) []Chunk {
	perChunk := MaxParams / len(cols)
	var out []Chunk
	for start := 0; start < len(rows); start += perChunk {
		end := min(start+perChunk, len(rows))
		var b strings.Builder
		fmt.Fprintf(&b, "INSERT INTO %s (%s) VALUES ", table, strings.Join(cols, ", "))
		args := make([]any, 0, (end-start)*len(cols))
		for i, r := range rows[start:end] {
			if i > 0 {
				b.WriteString(", ")
			}
			b.WriteByte('(')
			for j, v := range r {
				if j > 0 {
					b.WriteString(", ")
				}
				args = append(args, v)
				fmt.Fprintf(&b, "$%d", len(args))
			}
			b.WriteByte(')')
		}
		out = append(out, Chunk{SQL: b.String(), Args: args})
	}
	return out
}

LISTEN/NOTIFY تکمیلی ​

به زبان ساده: PostgreSQL می‌تواند اعلان (Notification) کوچکی به همهٔ نشست‌هایی بفرستد که LISTEN channel اجرا کرده‌اند. سرویس Go یک اتصال نگه می‌دارد، روی آن منتظر می‌ماند و مثلاً cache را باطل یا worker را بیدار می‌کند.

بدفهمی رایج: «NOTIFY صف پیام است.» نه ماندگاری دارد نه بازپخش؛ listener قطع‌شده پیام‌ها را از دست می‌دهد. payload در پیش‌فرض "must be shorter than 8000 bytes" و "if a NOTIFY is executed inside a transaction, the notify events are not delivered until and unless the transaction is committed."

تعریف: در pgx ابتدا conn.Exec(ctx, "listen channelname") و سپس conn.WaitForNotification(ctx)؛ این متد "blocks until a notification is received or the context is canceled" و *pgconn.Notification{PID, Channel, Payload} می‌دهد. ارسال با NOTIFY channel, 'payload' یا pg_notify(text, text) است؛ دومی "is much easier to use than the NOTIFY command if you need to work with non-constant channel names and payloads". LISTEN حالت نشست است و هرگز از transaction pooling در PgBouncer کار نمی‌کند؛ جدول قابلیت آن "LISTEN ... Never" می‌گوید.

listener (pool.Acquire, held)          writer tx
1  LISTEN orders_changed
2  WaitForNotification(ctx) ...        BEGIN; UPDATE orders ...; SELECT pg_notify('orders_changed','42')
3                                      COMMIT
4  <- Notification{Channel:"orders_changed", Payload:"42"}
5  invalidate cache key order:42; wait again

سناریوی واقعی: ابطال cache میان instanceها؛ بیدار کردن worker به‌جای polling ثانیه‌ای، البته بعد از reconnect برای کارهای ازدست‌رفته همچنان poll کنید؛ اعلان بارگذاری دوبارهٔ config.

راه‌حل / روش استفاده: Listen یک اتصال pool را می‌گیرد و نگه می‌دارد، نام channel را با pgx.Identifier پاک‌سازی می‌کند و روی WaitForNotification حلقه می‌زند. در خطا برمی‌گردد تا صدازننده reconnect و حالت را دوباره بخواند. پیش از پس دادن اتصال با context تازه UNLISTEN * می‌زند؛ چون "A session's listen registrations are automatically cleared when the session ends" ولی نشست pooled تمام نشده و بدون پاک‌سازی، قرض‌گیرندهٔ بعدی همچنان اعلان می‌گیرد. اگر UNLISTEN شکست بخورد، با Hijack اتصال از pool خارج و بسته می‌شود. دو تست با اتصال جعلی حلقه را اجرا و ترتیب LISTEN "orders_changed" و UNLISTEN * را بررسی می‌کنند، حتی وقتی ctx صدازننده از قبل لغو شده باشد.

go
package pgxnative

import (
	"context"
	"errors"
	"slices"
	"testing"

	"github.com/jackc/pgx/v5/pgconn"
)

type fakeListener struct {
	sqls  []string
	notes []*pgconn.Notification
	ctxOK []bool // whether the ctx passed to Exec was still alive
}

func (f *fakeListener) Exec(ctx context.Context, sql string, _ ...any) (pgconn.CommandTag, error) {
	f.sqls = append(f.sqls, sql)
	f.ctxOK = append(f.ctxOK, ctx.Err() == nil)
	return pgconn.CommandTag{}, nil
}

func (f *fakeListener) WaitForNotification(ctx context.Context) (*pgconn.Notification, error) {
	if len(f.notes) == 0 {
		<-ctx.Done()
		return nil, ctx.Err()
	}
	n := f.notes[0]
	f.notes = f.notes[1:]
	return n, nil
}

// Round 1: the LISTEN registration must not survive into the next user of a pooled connection.
func TestListenUnlistensOnHandlerError(t *testing.T) {
	f := &fakeListener{notes: []*pgconn.Notification{{Channel: "orders_changed", Payload: "42"}}}
	boom := errors.New("handler failed")
	err := listenLoop(t.Context(), f, "orders_changed", func(*pgconn.Notification) error { return boom })
	if !errors.Is(err, boom) {
		t.Fatal(err)
	}
	if !slices.Equal(f.sqls, []string{`LISTEN "orders_changed"`, "UNLISTEN *"}) {
		t.Fatalf("statements %q", f.sqls)
	}
}

func TestListenUnlistensWithFreshContextOnCancel(t *testing.T) {
	f := &fakeListener{}
	ctx, cancel := context.WithCancel(t.Context())
	cancel()
	_ = listenLoop(ctx, f, "orders_changed", func(*pgconn.Notification) error { return nil })
	if len(f.sqls) != 2 || f.sqls[1] != "UNLISTEN *" || !f.ctxOK[1] {
		t.Fatalf("statements %q ctx alive %v", f.sqls, f.ctxOK)
	}
}
go
package pgxnative

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/jackc/pgx/v5/stdlib"
)

// Listen holds one pool connection for the whole subscription: LISTEN is
// session state, so it cannot go through a transaction-mode pooler. On exit the
// registration is removed (UNLISTEN *) or, if that fails, the connection is
// destroyed instead of being returned to the pool.
// Notifications are delivered only after the sending transaction commits.
func Listen(ctx context.Context, pool *pgxpool.Pool, channel string,
	handle func(*pgconn.Notification) error) error {
	conn, err := pool.Acquire(ctx)
	if err != nil {
		return err
	}

	err = listenLoop(ctx, pooled{conn}, channel, handle)
	if errors.Is(err, errUnlisten) {
		// The session may still be registered: never hand it to another caller.
		_ = conn.Hijack().Close(context.WithoutCancel(ctx))
		return err
	}
	conn.Release()
	return err
}

var errUnlisten = errors.New("unlisten failed")

type listener interface {
	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
	WaitForNotification(ctx context.Context) (*pgconn.Notification, error)
}

type pooled struct{ c *pgxpool.Conn }

func (p pooled) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
	return p.c.Exec(ctx, sql, args...)
}

func (p pooled) WaitForNotification(ctx context.Context) (*pgconn.Notification, error) {
	return p.c.Conn().WaitForNotification(ctx)
}

// listenLoop runs LISTEN, delivers notifications until ctx ends or handle fails,
// and always runs UNLISTEN * on a fresh context: LISTEN registrations live until
// UNLISTEN or the end of the session, and a pooled session outlives this call.
func listenLoop(ctx context.Context, c listener, channel string, handle func(*pgconn.Notification) error) (err error) {
	if _, err := c.Exec(ctx, "LISTEN "+pgx.Identifier{channel}.Sanitize()); err != nil {
		return fmt.Errorf("listen: %w", err)
	}
	defer func() {
		uctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
		defer cancel()
		if _, uerr := c.Exec(uctx, "UNLISTEN *"); uerr != nil {
			err = errors.Join(err, errUnlisten, uerr)
		}
	}()
	for {
		n, err := c.WaitForNotification(ctx)
		if err != nil {
			return err
		}
		if err := handle(n); err != nil {
			return err
		}
	}
}

// Notify sends a payload (under 8000 bytes by default) after the tx commits.
func Notify(ctx context.Context, tx pgx.Tx, channel, payload string) error {
	_, err := tx.Exec(ctx, `SELECT pg_notify($1, $2)`, channel, payload)
	return err
}

// AsSQLDB exposes the same pgxpool to libraries that need *sql.DB
// (goose, otelsql-wrapped code, sqlx). Pool limits stay on pgxpool.
func AsSQLDB(pool *pgxpool.Pool) *sql.DB { return stdlib.OpenDBFromPool(pool) }

// WithPgxConn reaches the *pgx.Conn under a database/sql connection, for
// pgx-only features such as CopyFrom.
func WithPgxConn(ctx context.Context, db *sql.DB, fn func(*pgx.Conn) error) error {
	c, err := db.Conn(ctx)
	if err != nil {
		return err
	}
	defer c.Close()
	return c.Raw(func(dc any) error { return fn(dc.(*stdlib.Conn).Conn()) })
}

نوع‌ها: pgtype، نوع اختصاصی و AfterConnect تکمیلی ​

به زبان ساده: pgx با pgtype میان مقدارهای Go و نوع‌های PostgreSQL نگاشت می‌کند. نوع‌های رایج مثل عدد صحیح، متن، timestamptz، uuid، jsonb، array، numeric و inet آماده‌اند؛ enum، domain و نوع مرکب (Composite type) اختصاصی را یک‌بار برای هر اتصال ثبت می‌کنید.

بدفهمی رایج: «برای پول، scan کردن numeric در float64 مناسب است.» دقت از دست می‌رود؛ pgtype.Numeric، adapter اعشاری مثل pgx-shopspring-decimal یا سنتِ integer بگیرید.

تعریف: "pgx uses the pgtype package to converting Go values to and from PostgreSQL values ... User defined data types such as enums, domains, and composite types may require type registration." conn.LoadType(ctx, "order_status") نوع را از catalog می‌خواند و conn.TypeMap().RegisterType(t) ثبتش می‌کند. ثبت متعلق به هر اتصال است؛ بنابراین در pgxpool.Config.AfterConnect قرار می‌گیرد که "is called after a connection is established, but before it is added to the pool". برای database/sql، pgtype.Map.SQLScanner مقدارهای pgtype را با sql.Scanner سازگار می‌کند.

PostgreSQLGo در pgx بومیاز database/sql
text، varcharstring، *string، pgtype.Textstring، sql.NullString
bigintint64، pgtype.Int8int64، sql.NullInt64
numericpgtype.Numeric و adapterهای decimalstring
timestamptztime.Time، pgtype.Timestamptztime.Time
uuid[16]byte، pgtype.UUID و adapterهای uuidstring
jsonbهر مقدار قابل marshal به JSON[]byte
bigint[][]int64pgtype.Map.SQLScanner(&a)
inet / cidrnetip.Addr / netip.Prefixstring
enumstring پس از LoadTypestring

راه‌حل / روش استفاده: نوع اختصاصی را در AfterConnect ثبت کنید؛ snippet پیکربندی pgxpool این کار را برای enum با نام order_status می‌کند. پول را سنت integer یا numeric همراه نوع decimal نگه دارید. نوع باید پیش از شروع pool وجود داشته باشد، وگرنه هر اتصال تازه در AfterConnect شکست می‌خورد. schema آزمایشگاه آن را می‌سازد و تست می‌سنجد هر نام LoadedTypes در schema.sql یک CREATE TYPE داشته باشد.

پیکربندی pgxpool: MaxConns، health check، AfterConnect و رشتهٔ اتصال/DSN حیاتی ​

به زبان ساده: pgxpool تنظیمات را از رشتهٔ اتصال (Connection string)، به‌شکل URL یا key=value، و از pgxpool.Config می‌گیرد که پیش از ساخت pool قابل ویرایش است. مهم‌ترین‌ها ظرفیت، عمر اتصال، فاصلهٔ بررسی اتصال‌های بیکار و hook آماده‌سازی اتصال تازه‌اند.

بدفهمی رایج: «ظرفیت پیش‌فرض pool برابر 4 است.» توضیح ParseConfig می‌گوید "pool_max_conns: integer greater than 0 (default 4)"، ولی توضیح فیلد و کد می‌گویند "The default is the greater of 4 or runtime.NumCPU()"؛ تست روی ماشین 12 هسته‌ای مقدار 12 چاپ کرد. در container با سهم CPU محدود هم شاید شمار هستهٔ میزبان باشد؛ صریح تنظیم کنید.

تعریف: DSN به‌شکل postgres://user:pass@host:5432/db?sslmode=verify-full&pool_max_conns=20 یا host=db user=app dbname=orders pool_max_conns=20 است. pgconn پارامترهای استاندارد libpq یعنی sslmode، connect_timeout، application_name، target_session_attrs و options را می‌فهمد. pgx، default_query_exec_mode، statement_cache_capacity و description_cache_capacity را اضافه می‌کند و pgxpool کلیدهای جدول را. کلید ناشناخته به‌عنوان پارامتر زمان اجرا به سرور می‌رود؛ به همین روش statement_timeout=5s در RuntimeParams پیش‌فرض نشست می‌شود.

تنظیمکلید DSNپیش‌فرضمعنی
MaxConnspool_max_connsmax(4, NumCPU)سقف قطعی
MinConnspool_min_conns0حداقل اتصال باز
MinIdleConnspool_min_idle_conns0حداقل idle؛ برای tail latency، "superior to MinConns"
MaxConnLifetimepool_max_conn_lifetime1 hبستن پس از این سن
MaxConnLifetimeJitterpool_max_conn_lifetime_jitter0پخش کردن زمان بسته شدن‌ها
MaxConnIdleTimepool_max_conn_idle_time30 minبستن اتصال بیکار در health check
HealthCheckPeriodpool_health_check_period1 minبررسی پس‌زمینهٔ idleها
PingTimeoutpool_ping_timeout از 5.11+0 = بدون سقفمحدودیت Ping هنگام گرفتن اتصال
ShouldPingفقط کدping پس از idle > 1 sبررسی زنده بودن هنگام acquire
AfterConnectفقط کدnilتنظیم هر اتصال: نوع‌ها و SET
PrepareConn / AfterRelease / BeforeCloseفقط کدnilhookهای گرفتن و پس دادن؛ BeforeAcquire منسوخ است
ConnConfig.ConnectTimeoutconnect_timeoutنداردسقف dial و startup
ConnConfig.Tracerفقط کدnilردگیری query؛ مشاهده‌پذیری
1  cfg, _ := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))   DSN keys parsed, unknown keys -> RuntimeParams
2  cfg.MaxConns = 20; cfg.AfterConnect = registerTypes          code overrides
3  pool, _ := pgxpool.NewWithConfig(ctx, cfg)                  returns at once, starts health check goroutine
4  first Acquire -> dial -> startup(params incl. statement_timeout) -> AfterConnect -> in pool
5  every HealthCheckPeriod: close idle > MaxConnIdleTime, age > MaxConnLifetime(+jitter), refill MinConns

سناریوی واقعی: pod با 2 vCPU روی node با 64 هسته، پیش‌فرض 64 اتصال می‌گیرد؛ MinIdleConns: 2 هزینهٔ dial را از اولین درخواست پس از شب آرام حذف می‌کند؛ MaxConnLifetimeJitter نمی‌گذارد هر 50 اتصال در یک ثانیه پس از deploy دوباره وصل شوند؛ AfterConnect یک enum ثبت می‌کند تا RowToStructByName بتواند scan کند.

راه‌حل / روش استفاده: DSN را parse کنید و بعد همهٔ فیلدهای pool را در کد تنظیم کنید تا بازبینی مقدارها یک‌جا باشد. NewPool یک‌بار ping می‌کند تا startup سریع شکست بخورد.

go
// Package pgxnative uses pgx v5's own API: pgxpool configuration, typed row
// collection, named arguments, batches, COPY, LISTEN/NOTIFY and the bridge to
// database/sql. Only the parts that need no server are tested here.
package pgxnative

import (
	"context"
	"fmt"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

// LoadedTypes are the PostgreSQL types AfterConnect registers on every connection.
// They must exist before the pool starts: schema.sql creates them (schema_test.go checks it),
// and a missing type makes every new connection fail.
var LoadedTypes = []string{"order_status"}

// PoolConfig parses a DSN (URL or key=value) and applies production defaults.
// Settings given in the DSN, such as pool_max_conns, are parsed first; the
// fields set here override them, so keep one source of truth per knob.
func PoolConfig(dsn string) (*pgxpool.Config, error) {
	cfg, err := pgxpool.ParseConfig(dsn)
	if err != nil {
		return nil, fmt.Errorf("parse dsn: %w", err)
	}
	cfg.MaxConns = 20                        // default: max(4, runtime.NumCPU())
	cfg.MinIdleConns = 2                     // warm connections for tail latency
	cfg.MaxConnLifetime = 30 * time.Minute   // default 1h
	cfg.MaxConnLifetimeJitter = time.Minute  // spread reconnects
	cfg.MaxConnIdleTime = 5 * time.Minute    // default 30m
	cfg.HealthCheckPeriod = 30 * time.Second // default 1m
	cfg.ConnConfig.ConnectTimeout = 5 * time.Second

	// Server-side backstops, sent as startup parameters on every new connection.
	rp := cfg.ConnConfig.RuntimeParams
	rp["application_name"] = "orders-api"
	rp["statement_timeout"] = "5s"
	rp["lock_timeout"] = "2s"
	rp["idle_in_transaction_session_timeout"] = "30s"

	// AfterConnect runs once per new physical connection, before it joins the pool.
	cfg.AfterConnect = func(ctx context.Context, c *pgx.Conn) error {
		t, err := c.LoadType(ctx, LoadedTypes[0]) // the order_status enum from schema.sql
		if err != nil {
			return fmt.Errorf("load type %s (run the migrations first): %w", LoadedTypes[0], err)
		}
		c.TypeMap().RegisterType(t)
		return nil
	}
	return cfg, nil
}

// ForTransactionPooler switches off named prepared statements for a pooler
// in transaction mode that cannot track them (PgBouncer before 1.21, or with
// max_prepared_statements = 0). QueryExecModeExec still sends parameters
// separately (no client-side interpolation) but cannot infer some types,
// for example a map[string]string has to be passed as json text.
// PgBouncer also rejects startup parameters it does not track unless they are
// listed in ignore_startup_parameters, so the timeouts move to ALTER ROLE ... SET.
func ForTransactionPooler(cfg *pgxpool.Config) {
	cfg.ConnConfig.DefaultQueryExecMode = pgx.QueryExecModeExec
	for _, k := range []string{"statement_timeout", "lock_timeout", "idle_in_transaction_session_timeout"} {
		delete(cfg.ConnConfig.RuntimeParams, k)
	}
	cfg.AfterConnect = nil // keep connection setup out of the pooled session
}

// NewPool builds the pool and checks it once: pgxpool.New does not connect.
func NewPool(ctx context.Context, cfg *pgxpool.Config) (*pgxpool.Pool, error) {
	pool, err := pgxpool.NewWithConfig(ctx, cfg)
	if err != nil {
		return nil, err
	}
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
	if err := pool.Ping(ctx); err != nil {
		pool.Close()
		return nil, fmt.Errorf("ping: %w", err)
	}
	return pool, nil
}
go
package pgxnative

import (
	"context"
	"runtime"
	"testing"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

// Port 1 on loopback refuses connections: nothing here needs PostgreSQL.
const dsn = "postgres://app:secret@127.0.0.1:1/orders?sslmode=disable"

func TestDSNParameters(t *testing.T) {
	cfg, err := pgxpool.ParseConfig(dsn +
		"&pool_max_conns=10&pool_max_conn_idle_time=2m&default_query_exec_mode=exec&statement_cache_capacity=128")
	if err != nil {
		t.Fatal(err)
	}
	if cfg.MaxConns != 10 || cfg.MaxConnIdleTime != 2*time.Minute ||
		cfg.ConnConfig.DefaultQueryExecMode != pgx.QueryExecModeExec ||
		cfg.ConnConfig.StatementCacheCapacity != 128 {
		t.Fatalf("parsed %+v", cfg)
	}
}

func TestDefaults(t *testing.T) {
	cfg, err := pgxpool.ParseConfig(dsn)
	if err != nil {
		t.Fatal(err)
	}
	want := int32(max(4, runtime.NumCPU()))
	if cfg.MaxConns != want || cfg.MaxConnLifetime != time.Hour ||
		cfg.MaxConnIdleTime != 30*time.Minute || cfg.HealthCheckPeriod != time.Minute ||
		cfg.ConnConfig.DefaultQueryExecMode != pgx.QueryExecModeCacheStatement ||
		cfg.ConnConfig.StatementCacheCapacity != 512 {
		t.Fatalf("defaults %+v", cfg)
	}
	t.Logf("MaxConns default on this machine: %d", cfg.MaxConns)
}

func TestPoolConfigSetsBackstops(t *testing.T) {
	cfg, err := PoolConfig(dsn)
	if err != nil {
		t.Fatal(err)
	}
	if cfg.ConnConfig.RuntimeParams["statement_timeout"] != "5s" || cfg.MaxConns != 20 || cfg.AfterConnect == nil {
		t.Fatalf("%+v", cfg.ConnConfig.RuntimeParams)
	}
	ForTransactionPooler(cfg)
	if cfg.ConnConfig.DefaultQueryExecMode != pgx.QueryExecModeExec {
		t.Fatal("exec mode not set")
	}
	if _, ok := cfg.ConnConfig.RuntimeParams["statement_timeout"]; ok {
		t.Fatal("PgBouncer would reject statement_timeout as a startup parameter")
	}
}

func TestPoolIsLazy(t *testing.T) {
	cfg, _ := pgxpool.ParseConfig(dsn)
	pool, err := pgxpool.NewWithConfig(t.Context(), cfg) // returns without connecting
	if err != nil {
		t.Fatalf("New should not dial: %v", err)
	}
	defer pool.Close()
	ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
	defer cancel()
	if err := pool.Ping(ctx); err == nil {
		t.Fatal("Ping must fail: nothing listens on port 1")
	} else {
		t.Log(err)
	}
}

func TestNamedArgsRewrite(t *testing.T) {
	sql, args, err := pgx.NamedArgs{"customer": int64(7), "status": "open"}.RewriteQuery(t.Context(), nil,
		"SELECT 1 FROM orders WHERE customer_id = @customer AND status = @status AND note <> '@x'", nil)
	if err != nil {
		t.Fatal(err)
	}
	if sql != "SELECT 1 FROM orders WHERE customer_id = $1 AND status = $2 AND note <> '@x'" || len(args) != 2 {
		t.Fatalf("%q %v", sql, args)
	}
}

Timeoutها: statement_timeout، lock_timeout و همراهانشان حیاتی ​

به زبان ساده: ctx مدت انتظار Go را محدود می‌کند؛ محدودیت زمانی (Timeout) خود PostgreSQL مدت کار سرور و نگهداری قفل (Lock) را محدود می‌کند، حتی وقتی کلاینت رفته یا driver لغو نکرده باشد. هر دو را داشته باشید.

بدفهمی رایج: «ctx من مهلت 2 ثانیه‌ای دارد، پس هیچ دستور بیشتر از 2 ثانیه اجرا نمی‌شود.» handler پیش‌فرض pgx اتصال را می‌بندد ولی backend تا تلاش بعدی برای ارتباط با کلاینت کار می‌کند. statement_timeout در خود سرور متوقفش می‌کند. حتی با آن، lock_timeout مهم است: migration منتظر lock، تمام queryهای پشت سرش را هم مسدود می‌کند.

تعریف طبق مستند PostgreSQL: statement_timeout: "Abort any statement that takes more than the specified amount of time ... A value of zero (the default) disables the timeout." lock_timeout: "Abort any statement that waits longer than the specified amount of time while attempting to acquire a lock". idle_in_transaction_session_timeout: "Terminate any session that has been idle ... within an open transaction for longer than the specified amount of time"؛ Transaction باز همچنین "prevents vacuuming away recently-dead tuples". transaction_timeout در نسخه‌های جدیدتر PostgreSQL کل Transaction را محدود می‌کند. دربارهٔ idle_session_timeout هشدار هست: "Be wary of enforcing this timeout on connections made through connection-pooling software". مقدار بدون واحد در همه میلی‌ثانیه است. می‌توان در سطح role با ALTER ROLE app SET statement_timeout = '5s'، اتصال با RuntimeParams یا DSN شامل options=-c statement_timeout=5s، یا Transaction با SET LOCAL تنظیم کرد.

1  BEGIN;
2  SET LOCAL lock_timeout = '2s'; SET LOCAL statement_timeout = '30s';   only this transaction
3  ALTER TABLE orders ADD COLUMN note text;   waits for ACCESS EXCLUSIVE lock behind a long SELECT
4  ... 2 s later: ERROR: canceling statement due to lock timeout (SQLSTATE 55P03)
5  ROLLBACK;   queued application queries resume instead of piling up behind the ALTER

سناریوی واقعی: گزارش مهارنشده‌ای که یک ساعت پس از انصراف کلاینت HTTP ادامه دارد؛ deploy با ALTER TABLE منتظر lock که API را منجمد می‌کند و با lock_timeout و retry اصلاح می‌شود (Schema Migrations)؛ باگی که اتصال را داخل BEGIN رها کرده و lock سطر را نگه داشته تا idle_in_transaction_session_timeout نشست را بکشد.

لایهتنظیممحافظت در برابرخطا
Godeadline در ctx هر فراخوانیانتظار بی‌پایان pool یا querycontext deadline exceeded
dial در pgxconnect_timeout / ConnectTimeoutمیزبان دور از دسترسdial timeout
PostgreSQLstatement_timeoutدستور طولانی57014 "canceling statement due to statement timeout"
PostgreSQLlock_timeoutانتظار lock55P03 "canceling statement due to lock timeout"
PostgreSQLidle_in_transaction_session_timeoutTransaction بازِ رهاشدهپایان نشست
PostgreSQLtransaction_timeoutکل Transaction طولانیپایان نشست
PgBouncerquery_timeout، server_idle_timeoutسقف‌های poolerقطع کلاینت

راه‌حل / روش استفاده: statement_timeout در سطح role کمی بالاتر از طولانی‌ترین query مجاز API؛ SET LOCAL برای job طولانی شناخته‌شده؛ lock_timeout در هر migration؛ و idle_in_transaction_session_timeout همیشه فعال. PoolConfig سه مورد اول را در پارامترهای زمان اجرا می‌گذارد.

خطاها: بررسی خطا، pgconn.PgError و SQLSTATE حیاتی ​

به زبان ساده: هر خطای PostgreSQL یک کد پنج‌کاراکتری SQLSTATE دارد و اغلب نام constraint، جدول و ستون را هم می‌دهد. با errors.As آن را در *pgconn.PgError بخوانید؛ متن پیام ممکن است ترجمه یا بازنویسی شود و معیار تصمیم نیست.

بدفهمی رایج: «err.Error() شامل duplicate key است، پس strings.Contains کافی است.» پیام به lc_messages و نسخهٔ سرور وابسته است؛ کدها پایدارند و در Appendix A آمده‌اند. تبدیل مستقیم err.(*pgconn.PgError) هم برای خطای wrapشده شکست می‌خورد. ویکی pgx: "errors.Is() and errors.As() should be used instead of directly testing an error for equality or attempting a type assertion."

تعریف: pgconn.PgError فیلدهای Severity، Code، Message، Detail، Hint، Position، SchemaName، TableName، ColumnName، DataTypeName، ConstraintName، File، Line و Routine دارد. Error() قالب Severity + ": " + Message + " (SQLSTATE " + Code + ")" می‌سازد. pgconn.Timeout(err) برای خطاهای "caused within pgconn by a context.DeadlineExceeded or an implementer of net.Error where Timeout() is true" درست است. pgconn.SafeToRetry(err) فقط اگر خطا "before sending any data to the server" رخ داده باشد درست است. ثابت‌های کد در github.com/jackc/pgerrcode هستند.

1  _, err := pool.Exec(ctx, `INSERT INTO users (email) VALUES ($1)`, "a@example.test")
2  err: fmt.Errorf("signup: %w", *pgconn.PgError{Code:"23505", ConstraintName:"users_email_key"})
3  var pg *pgconn.PgError; errors.As(err, &pg)  -> true
4  pg.Code == "23505" && pg.ConstraintName == "users_email_key"  -> return ErrEmailTaken  -> HTTP 409

سناریوی واقعی: ثبت‌نام به‌جای pre-check مستعد race از unique constraint، پاسخ 409 «email گرفته شده» می‌سازد؛ نقض FK با 23503 روی order_lines.product_id به 422 تبدیل می‌شود؛ هشدار 53300 با نام too_many_connections جدا از خطای query ثبت می‌شود.

SQLSTATEنامعلت معمولواکنش Go
23505unique_violationکلید تکراری409 یا ON CONFLICT
23503foreign_key_violationوالد ناموجود / فرزند موجود422
23502not_null_violationمقدار جاافتادهباگ یا 422
23514check_violationCHECK (balance >= 0)422 / خطای کسب‌وکار
40001serialization_failureتعارض RR/Serializableretry کل tx
40P01deadlock_detectedچرخهٔ lockretry و اصلاح ترتیب
55P03lock_not_availablelock_timeout، NOWAITbackoff
57014query_canceledstatement_timeout، درخواست cancelمدیریت timeout
25P02in_failed_sql_transactionدستور پس از خطا در txباگ؛ اول rollback
26000invalid_sql_statement_nameprepared statement ناموجود پشت poolerPgBouncer
42P05duplicate_prepared_statementآماده‌سازی دوبارهٔ یک نام در نشستpooler یا PREPARE دستی
53300too_many_connectionsرسیدن به max_connectionspool کوچک‌تر یا pooler
57P01admin_shutdownrestart / failover سرورreconnect و retry کار idempotent
08006connection_failureشبکهretry فقط اگر امن باشد
42601 / 42P01 / 42703syntax_error / undefined_table / undefined_columnSQL غلط یا migration جاافتادهباگ

راه‌حل / روش استفاده: برای هر سرویس یک دسته‌بند بسازید؛ repository از آن خطای دامنه می‌سازد و helper Transaction دربارهٔ retry تصمیم می‌گیرد. تست، مقدارهای PgError را دستی می‌سازد؛ دسته‌بند را اثبات می‌کند، نه رفتار سرور را.

go
// Package errs turns driver errors into decisions: not found, conflict,
// retry, timeout. It inspects *pgconn.PgError by SQLSTATE, never by message.
package errs

import (
	"context"
	"database/sql"
	"errors"

	"github.com/jackc/pgx/v5/pgconn"
)

// SQLSTATE codes used below (PostgreSQL Appendix A).
const (
	UniqueViolation      = "23505"
	ForeignKeyViolation  = "23503"
	CheckViolation       = "23514"
	SerializationFailure = "40001"
	DeadlockDetected     = "40P01"
	QueryCanceled        = "57014" // statement_timeout or a cancel request
	LockNotAvailable     = "55P03" // lock_timeout or NOWAIT
	TooManyConnections   = "53300"
	AdminShutdown        = "57P01"
)

// Kind is what the caller should do about an error.
type Kind int

const (
	KindNone        Kind = iota
	KindNotFound         // map to 404
	KindConflict         // unique violation: 409
	KindInvalid          // FK or CHECK violation: 422
	KindRetry            // serialization failure or deadlock: retry the whole transaction
	KindTimeout          // our deadline or statement_timeout/lock_timeout
	KindCanceled         // the caller went away: log at INFO, do not retry
	KindUnavailable      // server overloaded or restarting: back off
	KindOther
)

// Classify inspects err with errors.Is / errors.As, so wrapping with %w is fine.
func Classify(err error) Kind {
	if err == nil {
		return KindNone
	}
	if errors.Is(err, sql.ErrNoRows) { // pgx.ErrNoRows wraps sql.ErrNoRows since pgx v5.7.0
		return KindNotFound
	}
	if errors.Is(err, context.Canceled) {
		return KindCanceled
	}
	if errors.Is(err, context.DeadlineExceeded) || pgconn.Timeout(err) {
		return KindTimeout
	}
	var pg *pgconn.PgError
	if errors.As(err, &pg) {
		switch pg.Code {
		case UniqueViolation:
			return KindConflict
		case ForeignKeyViolation, CheckViolation:
			return KindInvalid
		case SerializationFailure, DeadlockDetected:
			return KindRetry
		case QueryCanceled, LockNotAvailable:
			return KindTimeout
		case TooManyConnections, AdminShutdown:
			return KindUnavailable
		}
		if len(pg.Code) == 2+3 && pg.Code[:2] == "08" { // class 08: connection exception
			return KindUnavailable
		}
	}
	return KindOther
}

// ErrEmailTaken is a domain error derived from a specific constraint name.
var ErrEmailTaken = errors.New("email already registered")

// Domain maps a unique violation on users_email_key to ErrEmailTaken.
func Domain(err error) error {
	var pg *pgconn.PgError
	if errors.As(err, &pg) && pg.Code == UniqueViolation && pg.ConstraintName == "users_email_key" {
		return ErrEmailTaken
	}
	return err
}
go
package errs

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"testing"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
)

// These PgErrors are built by hand: the test proves the classifier, not the server.
func pgErr(code string) error {
	return fmt.Errorf("insert order: %w", &pgconn.PgError{Severity: "ERROR", Code: code, Message: "test"})
}

func TestClassify(t *testing.T) {
	cases := []struct {
		name string
		err  error
		want Kind
	}{
		{"nil", nil, KindNone},
		{"sql.ErrNoRows", fmt.Errorf("get: %w", sql.ErrNoRows), KindNotFound},
		{"pgx.ErrNoRows", pgx.ErrNoRows, KindNotFound},
		{"unique", pgErr("23505"), KindConflict},
		{"fk", pgErr("23503"), KindInvalid},
		{"serialization", pgErr("40001"), KindRetry},
		{"deadlock", pgErr("40P01"), KindRetry},
		{"statement_timeout", pgErr("57014"), KindTimeout},
		{"lock_timeout", pgErr("55P03"), KindTimeout},
		{"too many connections", pgErr("53300"), KindUnavailable},
		{"connection failure", pgErr("08006"), KindUnavailable},
		{"ctx deadline", fmt.Errorf("query: %w", context.DeadlineExceeded), KindTimeout},
		{"ctx canceled", context.Canceled, KindCanceled},
		{"syntax", pgErr("42601"), KindOther},
	}
	for _, c := range cases {
		if got := Classify(c.err); got != c.want {
			t.Errorf("%s: got %d want %d", c.name, got, c.want)
		}
	}
}

func TestPgErrorText(t *testing.T) {
	e := &pgconn.PgError{Severity: "ERROR", Code: "40001",
		Message: "could not serialize access due to concurrent update"}
	if got := e.Error(); got != "ERROR: could not serialize access due to concurrent update (SQLSTATE 40001)" {
		t.Fatal(got)
	}
}

func TestPgxErrNoRowsIsSQLErrNoRows(t *testing.T) {
	if !errors.Is(pgx.ErrNoRows, sql.ErrNoRows) {
		t.Fatal("pgx.ErrNoRows should wrap sql.ErrNoRows")
	}
}

func TestDomainConstraint(t *testing.T) {
	err := fmt.Errorf("signup: %w", &pgconn.PgError{Code: "23505", ConstraintName: "users_email_key"})
	if !errors.Is(Domain(err), ErrEmailTaken) {
		t.Fatal("want ErrEmailTaken")
	}
}

حالت transaction در PgBouncer و prepared statement مهم ​

به زبان ساده: PgBouncer در حالت transaction فقط به‌اندازهٔ عمر یک تراکنش (Transaction) اتصال سرور می‌دهد. هر چیزی که متعلق به نشست (Session) است، مثل prepared statement نام‌دار، SET، LISTEN، advisory lock و temp table، در Transaction بعدی شاید نباشد یا روی اتصال دیگری باشد. cache پیش‌فرض pgx دقیقاً چنین حالت نشستی است.

بدفهمی رایج: «PgBouncer اصلاً prepared statement پشتیبانی نمی‌کند.» پیش از 1.21 درست بود. PgBouncer 1.21.0 در ۱۶ اکتبر ۲۰۲۳ با عنوان "The one with prepared statements"، "support for protocol-level named prepared statements" را اضافه کرد که با max_prepared_statements غیرصفر فعال می‌شود. نسخهٔ 1.24.0 پیش‌فرض را 200 کرد. مستند خود pgx در doc.go که می‌گوید "Prepared statements are incompatible with PgBouncer" قدیمی‌تر است؛ برای pooler قدیمی، managed pooler بدون رهگیری و PREPARE در سطح SQL که PgBouncer دست‌نخورده عبور می‌دهد همچنان برداشت امنی است.

تعریف: حالت‌های PgBouncer شامل session با "This mode supports all PostgreSQL features"، transaction با "A server connection is assigned to a client only during a transaction" و "This mode breaks a few session-based features of PostgreSQL" و statement هستند. با max_prepared_statements > 0، PgBouncer "gives each unique query string an internal name with the format PGBOUNCER_{unique_id}" و "transparently prepares the statement before executing it" روی هر اتصال سروری که کلاینت به آن برسد. مقدار تنظیم، اندازهٔ LRU برای هر اتصال سرور است. محدودیت مستند: اگر migration نوع نتیجهٔ دستور را تغییر دهد، تا RECONNECT کلاینت‌ها ERROR: cached plan must not change result type می‌گیرند.

pool_mode=transaction, max_prepared_statements=0, pgx default cache_statement
1  tx1 on server A: Parse stmtcache_9f2c... ; Bind/Execute      ok
2  tx2 on server B: Bind stmtcache_9f2c...                      ERROR: prepared statement "stmtcache_9f2c..." does not exist (26000)
3  or tx3 on server A from another client that cached the same SQL earlier: ERROR 42P05 duplicate_prepared_statement

سناریوی واقعی: سرویس جمعه از اتصال مستقیم به managed pooler می‌رود و deploy دوشنبه خراب می‌شود؛ میزبان PostgreSQL هم endpoint مستقیم و هم pooled می‌دهد و pooled در حالت transaction است؛ ابطال cache مبتنی بر LISTEN باید مستقیم وصل شود و pooler را دور بزند.

چیدمانDefaultQueryExecMode در pgxکار می‌کند؟نکته
مستقیم به PostgreSQLcache_statement پیش‌فرضبلهسریع‌ترین
PgBouncer در حالت sessioncache_statementبلهصرفه‌جویی کمتر از pooling
PgBouncer ≥ 1.21 در حالت transaction با max_prepared_statements > 0cache_statementبله، طبق مستند PgBouncerدر مستند pgx نیست؛ تست کنید؛ پس از migration تغییر نوع، RECONNECT
PgBouncer transaction بدون رهگیری statementexec یا simple_protocolبلهexec پارامتر را جدا نگه می‌دارد
هر transaction poolerنامربوطLISTEN، SET و advisory lock نشستی: هرگزاتصال مستقیم برای آن‌ها

راه‌حل / روش استفاده: ForTransactionPooler در snippet config، QueryExecModeExec را انتخاب و پارامترهای startup مربوط به timeout را حذف می‌کند. دلیل: "By default, PgBouncer allows only parameters it can keep track of in startup packets ... All other parameters will raise an error"، مگر در ignore_startup_parameters باشند. بنابراین statement_timeout و همراهان را با ALTER ROLE ... SET تنظیم کنید. تنظیم ماندگار دیگر مثل SET search_path هم باید در پیش‌فرض role یا database باشد، نه AfterConnect؛ پشت pooler، «اتصال» شما همان نشست سرور نیست.

Go service (pgx)tx 1: Parse stmtcache_1then Bind/Executetx 2: Bind stmtcache_1(cached, no Parse)PgBouncerpool_mode =transactionserver conn Ahas stmtcache_1server conn Bno such statement: 26000fixesPgBouncer 1.21+: max_prepared_statements > 0 (default 200 since 1.24) re-prepares on Bor pgx DefaultQueryExecMode = QueryExecModeExec / QueryExecModeSimpleProtocolor session pooling; LISTEN and SET never work in transaction pooling

الگوی repository: یک interface برای هر aggregate حیاتی ​

به زبان ساده: مخزن (Repository) تنها جایی است که SQL یک تجمیع (Aggregate)، مثل سفارش و اقلامش، را می‌شناسد. بقیهٔ کد شیء دامنه می‌خواهد و برای ذخیره پس می‌دهد. interface را در محل مصرف تعریف کنید؛ یکی برای هر Aggregate و با نوع‌های دامنه در امضاها.

بدفهمی رایج: «برای هر جدول repository با FindAll/Update عمومی بسازیم.» schema به لایه‌های بالا نشت می‌کند و ذخیرهٔ ناقص Aggregate، مثل اقلام بدون سفارش، ممکن می‌شود. «repository باید Transaction را کاملاً پنهان کند» هم غلط است؛ مرز Transaction را use case تعیین می‌کند، نه repository. دید DDD در Repositories آمده است.

تعریف: interface به‌نام Orders با Get(ctx, id) (*Order, error) و Save(ctx, *Order) error؛ پیاده‌سازی SQLOrders روی interface DBTX شامل ExecContext، QueryContext و QueryRowContext که *sql.DB، *sql.Tx و *sql.Conn همگی دارند. خطاهای driver به ErrNotFound/ErrConflict تبدیل می‌شوند. هم‌زمانی خوش‌بینانه (Optimistic concurrency) با ستون version باعث می‌شود ذخیرهٔ هم‌زمان ErrConflict بدهد، نه lost update.

handler -> Service.Cancel(ctx, 7)
             InTx: Orders.Get(ctx,7)     SELECT order; SELECT lines        (2 queries, not 1+N)
                   o.Status = cancelled
                   Orders.Save(ctx,o)    UPDATE ... WHERE id=7 AND version=4  -> 0 rows => ErrConflict
                   Outbox.Append(...)    INSERT INTO outbox
             COMMIT

سناریوی واقعی: جایگزینی پیاده‌سازی PostgreSQL با fake حافظه‌ای برای تست سرویس در Mocking with Interfaces & DI؛ handler REST که ErrNotFound را 404 و ErrConflict را 409 می‌کند در A REST API in Go؛ Aggregate سفارش که اقلام آن همیشه با هم جایگزین می‌شوند و هیچ مسیر کد یک قلم را تنها ذخیره نمی‌کند.

تصمیم طراحیپیشنهادپرهیز
دانه‌بندییک repository برای هر ریشهٔ Aggregateیکی برای هر جدول
امضانوع دامنه و ctx اول*sql.Rows، map[string]any، sql.NullString
خطاErrNotFound، ErrConflictsql.ErrNoRows، *pgconn.PgError خام
محل interfaceبستهٔ مصرف‌کنندهکنار پیاده‌سازی «برای احتیاط»
کنترل هم‌زمانیستون version یا SELECT ... FOR UPDATEآخرین نوشتن برنده باشد
queryستون صریح و بارگیری دسته‌ای فرزندانSELECT * و query برای هر فرزند

راه‌حل / روش استفاده: snippet repository، دامنه، سرویس و interfaceها را در یک فایل و پیاده‌سازی PostgreSQL را در فایل دیگر دارد.

go
// Package repository shows the repository pattern on database/sql: one
// interface per aggregate, a PostgreSQL implementation that works on a pool
// or a transaction, and two ways to share one transaction across
// repositories: a transaction carried in the context, or an explicit unit of work.
package repository

import (
	"context"
	"errors"
	"strconv"
)

// Order is the aggregate root; Lines belong to it and are saved with it.
type Order struct {
	ID         int64
	CustomerID int64
	Status     string
	Lines      []Line
	Version    int // optimistic concurrency
}

// Line is part of the Order aggregate, never loaded or saved on its own.
type Line struct {
	SKU string
	Qty int
}

var (
	ErrNotFound = errors.New("not found")
	ErrConflict = errors.New("concurrent update")
)

// Orders is the repository for the Order aggregate: domain types in and out,
// no *sql.Rows, no SQL, no driver errors in the signature.
type Orders interface {
	Get(ctx context.Context, id int64) (*Order, error)
	Save(ctx context.Context, o *Order) error
}

// Outbox records events in the same transaction as the state change.
type Outbox interface {
	Append(ctx context.Context, topic string, payload []byte) error
}

// TxRunner runs fn so that every repository call made with the ctx it
// receives joins one transaction.
type TxRunner interface {
	InTx(ctx context.Context, fn func(ctx context.Context) error) error
}

// Service is application logic; it sees only interfaces, so tests use fakes.
type Service struct {
	Tx     TxRunner
	Orders Orders
	Outbox Outbox
}

// Cancel changes the status and records an event, atomically.
func (s Service) Cancel(ctx context.Context, id int64) error {
	return s.Tx.InTx(ctx, func(ctx context.Context) error {
		o, err := s.Orders.Get(ctx, id)
		if err != nil {
			return err
		}
		if o.Status == "shipped" {
			return errors.New("cannot cancel a shipped order")
		}
		o.Status = "cancelled"
		if err := s.Orders.Save(ctx, o); err != nil {
			return err
		}
		return s.Outbox.Append(ctx, "order.cancelled", []byte(`{"id":`+strconv.FormatInt(o.ID, 10)+`}`))
	})
}
go
package repository

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
)

// DBTX is satisfied by *sql.DB, *sql.Tx and *sql.Conn (sqlc generates the same idea).
type DBTX interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

type txKey struct{}

// conn returns the transaction carried in ctx, or the fallback (pool or tx).
func conn(ctx context.Context, fallback DBTX) DBTX {
	if tx, ok := ctx.Value(txKey{}).(*sql.Tx); ok {
		return tx
	}
	return fallback
}

// TxManager implements TxRunner by putting the *sql.Tx into the context.
type TxManager struct{ DB *sql.DB }

// InTx joins an existing transaction or starts one, with the defer-Rollback pattern.
func (m TxManager) InTx(ctx context.Context, fn func(ctx context.Context) error) error {
	if _, ok := ctx.Value(txKey{}).(*sql.Tx); ok {
		return fn(ctx) // already inside: join, do not nest
	}
	tx, err := m.DB.BeginTx(ctx, nil)
	if err != nil {
		return fmt.Errorf("begin: %w", err)
	}
	defer tx.Rollback()
	if err := fn(context.WithValue(ctx, txKey{}, tx)); err != nil {
		return err
	}
	return tx.Commit()
}

// SQLOrders is the PostgreSQL implementation of Orders.
type SQLOrders struct{ db DBTX }

// NewSQLOrders works on a pool (then ctx may carry a tx) or directly on a tx.
func NewSQLOrders(db DBTX) *SQLOrders { return &SQLOrders{db: db} }

// Get loads the root and its lines in two queries (not one per line).
func (r *SQLOrders) Get(ctx context.Context, id int64) (*Order, error) {
	q := conn(ctx, r.db)
	o := &Order{ID: id}
	err := q.QueryRowContext(ctx,
		`SELECT customer_id, status, version FROM orders WHERE id = $1`, id,
	).Scan(&o.CustomerID, &o.Status, &o.Version)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, ErrNotFound
	}
	if err != nil {
		return nil, fmt.Errorf("load order %d: %w", id, err)
	}
	rows, err := q.QueryContext(ctx,
		`SELECT sku, qty FROM order_lines WHERE order_id = $1 ORDER BY sku`, id)
	if err != nil {
		return nil, fmt.Errorf("load lines: %w", err)
	}
	defer rows.Close()
	for rows.Next() {
		var l Line
		if err := rows.Scan(&l.SKU, &l.Qty); err != nil {
			return nil, err
		}
		o.Lines = append(o.Lines, l)
	}
	return o, rows.Err()
}

// Save writes the whole aggregate; the version check rejects lost updates.
func (r *SQLOrders) Save(ctx context.Context, o *Order) error {
	q := conn(ctx, r.db)
	res, err := q.ExecContext(ctx,
		`UPDATE orders SET status = $1, version = version + 1 WHERE id = $2 AND version = $3`,
		o.Status, o.ID, o.Version)
	if err != nil {
		return fmt.Errorf("save order %d: %w", o.ID, err)
	}
	if n, _ := res.RowsAffected(); n == 0 {
		return ErrConflict
	}
	o.Version++
	if _, err := q.ExecContext(ctx, `DELETE FROM order_lines WHERE order_id = $1`, o.ID); err != nil {
		return err
	}
	for _, l := range o.Lines {
		if _, err := q.ExecContext(ctx,
			`INSERT INTO order_lines (order_id, sku, qty) VALUES ($1, $2, $3)`, o.ID, l.SKU, l.Qty); err != nil {
			return err
		}
	}
	return nil
}

// SQLOutbox appends to an outbox table that a relay publishes from.
type SQLOutbox struct{ db DBTX }

// NewSQLOutbox works like NewSQLOrders.
func NewSQLOutbox(db DBTX) *SQLOutbox { return &SQLOutbox{db: db} }

// Append inserts one event row.
func (o *SQLOutbox) Append(ctx context.Context, topic string, payload []byte) error {
	_, err := conn(ctx, o.db).ExecContext(ctx,
		`INSERT INTO outbox (topic, payload) VALUES ($1, $2)`, topic, payload)
	return err
}

// UnitOfWork is the explicit alternative: fn receives repositories bound to one tx.
type UnitOfWork struct{ DB *sql.DB }

// Repos are the repositories available inside one unit of work.
type Repos struct {
	Orders Orders
	Outbox Outbox
}

// Do begins a transaction, hands tx-bound repositories to fn, commits on nil.
func (u UnitOfWork) Do(ctx context.Context, fn func(Repos) error) error {
	tx, err := u.DB.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()
	if err := fn(Repos{Orders: NewSQLOrders(tx), Outbox: NewSQLOutbox(tx)}); err != nil {
		return err
	}
	return tx.Commit()
}

اشتراک تراکنش: انتشار tx با context یا UnitOfWork مهم ​

به زبان ساده: use case اغلب دو repository مثل orders و outbox را تغییر می‌دهد که باید با هم commit شوند. یا *sql.Tx را در context حمل کنید تا همه بردارند، یا repositoryهای از قبل متصل به تراکنش (Transaction) را بدهید؛ این روش واحد کار (Unit of work) است.

بدفهمی رایج: «هر متد repository، Transaction خودش را شروع کند.» آن‌وقت Save و Append جدا commit می‌شوند و crash میانشان event را گم می‌کند. دام مقابل، نگهداری Transaction در struct مشترک repository است؛ repository میان goroutineها مشترک است و فیلد tx درخواست‌ها را قاطی می‌کند.

تعریف: در انتشار با context، TxManager.InTx یک tx شروع می‌کند، با کلید unexported می‌گذارد و repository با conn(ctx, fallback) آن را انتخاب می‌کند. فراخوانی‌های تودرتوی InTx به همان tx می‌پیوندند. در Unit of work، UnitOfWork.Do(ctx, func(Repos) error) برای طول فراخوانی NewSQLOrders(tx) و NewSQLOutbox(tx) می‌سازد. کد تولیدی sqlc راه دوم را می‌رود؛ مستند: "the WithTx method allows a Queries instance to be associated with a transaction". روش context ضمنی است: تابع بیرون InTx بی‌صدا بدون Transaction اجرا می‌شود. Unit of work صریح است ولی امضاها را تغییر می‌دهد.

TxManager.InTx(ctx, fn)        BEGIN on conn#1; ctx' = ctx + tx
  Orders.Get(ctx')             conn(ctx') = tx  -> conn#1
  Orders.Save(ctx')            tx -> conn#1
  Outbox.Append(ctx')          tx -> conn#1
COMMIT on conn#1               all-or-nothing; the test asserts every call ran on conn#1

سناریوی واقعی: سفارش و outbox در یک commit که بعداً relay می‌شود (Outbox Pattern)؛ متد سرویس هم مستقل و هم در use case بزرگ‌تر صدا زده می‌شود و context به tx می‌پیوندد؛ batch job کنترل صریح می‌خواهد و Unit of work می‌گیرد.

روشمسیر txمزیتعیب
Tx در contextcontext.WithValue(ctx, txKey{}, tx)امضا ثابت؛ فراخوانی تودرتو می‌پیونددضمنی؛ اجرای بدون tx آسان
Unit of workDo(ctx, func(Repos) error)صریح و روشن در زمان کامپایلکد اتصال بیشتر؛ ساخت repository در هر فراخوانی
WithTx در sqlcq.WithTx(tx) query متصل می‌دهدتولیدشده و صریحیک Queries برای هر tx
پارامتر DBTXSave(ctx, q DBTX, o)بسیار صریحنوع persistence در کد سرویس

راه‌حل / روش استفاده: برای هر سرویس یک روش انتخاب کنید. تست‌ها ثابت می‌کنند روش context، begin, query, query, exec, exec, exec, exec, commit را روی یک اتصال اجرا می‌کند، تعارض نسخه rollback می‌دهد و Unit of work فقط یک commit دارد.

go
package repository

import (
	"context"
	"database/sql/driver"
	"errors"
	"slices"
	"strings"
	"testing"

	"academy/database-sql-pgx/internal/fakedb"
)

// In-memory fakes: the service test needs no SQL at all.
type memOrders struct{ m map[int64]*Order }

func (r *memOrders) Get(_ context.Context, id int64) (*Order, error) {
	o, ok := r.m[id]
	if !ok {
		return nil, ErrNotFound
	}
	c := *o
	return &c, nil
}
func (r *memOrders) Save(_ context.Context, o *Order) error { r.m[o.ID] = o; return nil }

type memOutbox struct{ topics []string }

func (o *memOutbox) Append(_ context.Context, topic string, _ []byte) error {
	o.topics = append(o.topics, topic)
	return nil
}

type noTx struct{}

func (noTx) InTx(ctx context.Context, fn func(context.Context) error) error { return fn(ctx) }

func TestServiceWithFakes(t *testing.T) {
	orders := &memOrders{m: map[int64]*Order{7: {ID: 7, Status: "open"}}}
	out := &memOutbox{}
	s := Service{Tx: noTx{}, Orders: orders, Outbox: out}
	if err := s.Cancel(t.Context(), 7); err != nil {
		t.Fatal(err)
	}
	if orders.m[7].Status != "cancelled" || !slices.Equal(out.topics, []string{"order.cancelled"}) {
		t.Fatalf("%+v %v", orders.m[7], out.topics)
	}
	if err := s.Cancel(t.Context(), 99); !errors.Is(err, ErrNotFound) {
		t.Fatal(err)
	}
}

func orderFake(affected int64) *fakedb.DB {
	return fakedb.New(func(kind, q string, _ []any) fakedb.Response {
		switch {
		case strings.HasPrefix(q, "SELECT customer_id"):
			return fakedb.Response{Columns: []string{"customer_id", "status", "version"},
				Rows: [][]driver.Value{{int64(3), "open", int64(4)}}}
		case strings.HasPrefix(q, "SELECT sku"):
			return fakedb.Response{Columns: []string{"sku", "qty"},
				Rows: [][]driver.Value{{"A1", int64(2)}}}
		case strings.HasPrefix(q, "UPDATE orders"):
			return fakedb.Response{Affected: affected}
		}
		return fakedb.Response{Affected: 1}
	})
}

// Every statement of the use case runs on one connection between BEGIN and COMMIT.
func TestTxInContextSharesOneTransaction(t *testing.T) {
	fake := orderFake(1)
	db := fake.Open()
	s := Service{Tx: TxManager{DB: db}, Orders: NewSQLOrders(db), Outbox: NewSQLOutbox(db)}
	if err := s.Cancel(t.Context(), 7); err != nil {
		t.Fatal(err)
	}
	calls := fake.Calls()
	var kinds []string
	for _, c := range calls[1:] {
		if c.Conn != calls[1].Conn {
			t.Fatalf("statement on another connection: %+v", c)
		}
		kinds = append(kinds, c.Kind)
	}
	want := []string{"begin", "query", "query", "exec", "exec", "exec", "exec", "commit"}
	if !slices.Equal(kinds, want) {
		t.Fatalf("got %v", kinds)
	}
}

func TestVersionConflictRollsBack(t *testing.T) {
	fake := orderFake(0) // UPDATE matched no row: someone else saved first
	db := fake.Open()
	s := Service{Tx: TxManager{DB: db}, Orders: NewSQLOrders(db), Outbox: NewSQLOutbox(db)}
	if err := s.Cancel(t.Context(), 7); !errors.Is(err, ErrConflict) {
		t.Fatal(err)
	}
	if fake.Count("rollback") != 1 || fake.Count("commit") != 0 {
		t.Fatalf("calls %v", fake.Kinds())
	}
}

func TestUnitOfWork(t *testing.T) {
	fake := orderFake(1)
	err := UnitOfWork{DB: fake.Open()}.Do(t.Context(), func(r Repos) error {
		o, err := r.Orders.Get(t.Context(), 7)
		if err != nil {
			return err
		}
		o.Status = "paid"
		if err := r.Orders.Save(t.Context(), o); err != nil {
			return err
		}
		return r.Outbox.Append(t.Context(), "order.paid", nil)
	})
	if err != nil || fake.Count("commit") != 1 {
		t.Fatalf("err=%v calls=%v", err, fake.Kinds())
	}
}

query نوع‌دار با sqlc، builderهای squirrel/goqu و بده‌بستان GORM/ent/bun مهم ​

به زبان ساده: SQL را دستی بنویسید، از فایل SQL کد Go نوع‌دار بسازید (sqlc)، با زنجیرهٔ متدهای Go SQL بسازید (squirrel، goqu)، یا با نگاشت شیء-رابطه‌ای (ORM) مثل GORM، ent و bun ساختارها را به جدول وصل کنید. هرچه به گزینهٔ آخر نزدیک شوید، SQL کمتری می‌نویسید و کمتر هم می‌بینید.

بدفهمی رایج: «Go هم ORMی مثل Eloquent لازم دارد.» تیم‌های بسیاری آگاهانه استفاده نمی‌کنند؛ sqlc ایمنی نوع می‌دهد و SQL مرجع حقیقت می‌ماند. builder هم جادویی تزریق را متوقف نمی‌کند؛ فقط تا وقتی مقدار از API placeholder بگذرد، نه Expr با قالب‌بندی رشته.

تعریف: sqlc می‌گوید "sqlc generates type-safe code from SQL"؛ query را می‌نویسید، sqlc را اجرا می‌کنید و متد تولیدی را صدا می‌زنید. sql_package: "pgx/v5" کد pgx می‌دهد و emit_pointers_for_null_types برای ستون NULL از pointer استفاده می‌کند. squirrel یک "fluent SQL generator for Go" است و اکنون "complete" یعنی فقط bug fix. goqu، "an expressive SQL builder and executor" است. GORM با association و hook، "The fantastic ORM library for Golang"؛ ent با schema در کد Go و API پیمایش graph، "a simple, yet powerful entity framework for Go"؛ bun هم "Lightweight, SQL-first Golang ORM for PostgreSQL, MySQL, MSSQL, SQLite, and Oracle".

sqlc flow
1  query.sql:  -- name: GetOrder :one
               SELECT id, status FROM orders WHERE id = $1;
2  sqlc generate  -> db/query.sql.go: func (q *Queries) GetOrder(ctx, id int64) (Order, error)
3  repository: o, err := q.GetOrder(ctx, id)   compile error if the column or type changes

سناریوی واقعی: سرویس پرداخت با sqlc و pgx که هر query آن به‌صورت SQL بازبینی می‌شود؛ پنل مدیریتی با GORM برای سرعت CRUD؛ endpoint جست‌وجو با فیلتر اختیاری که squirrel می‌سازد؛ schema در ent با GraphQL تولیدی.

ابزارسبکایمنی نوعدیدن SQLبده‌بستان
دستی + database/sql/pgxرشتهٔ SQLزمان اجرا با Scanکاملکد تکراری؛ CollectRows کمک می‌کند
sqlcSQL → Go تولیدیزمان کامپایلکاملquery پویا دشوار
squirrel / goquBuilderنسبیبا ToSql()فیلتر پویا آسان؛ یک DSL دیگر
sqlx / scanyhelper scanزمان اجراکاملکوچک و بدون codegen
bunORM با محور SQLنسبیبیشتر اوقاتسبک‌تر از GORM
GORMORM کاملزمان اجرا، reflectionپیش‌فرض پنهانCRUD سریع؛ N+1 و query غیرمنتظره در ORM Pitfalls
entORM با schema در کدزمان کامپایل، تولیدیپنهانAPI قوی graph؛ codegen سنگین

راه‌حل / روش استفاده: پیش‌فرض معقول سرویس PostgreSQL، sqlc برای query ثابت، builder برای چند جست‌وجوی پویا و pgx.CollectRows برای باقی است. ORM را جایی بگیرید که سرعت CRUD مهم‌تر از کنترل SQL است.

Migrationها: golang-migrate، goose، atlas و tern تکمیلی ​

به زبان ساده: تغییر طرح‌واره (Schema migration) در فایل‌های نسخه‌دار است؛ ابزار آن‌ها را به‌ترتیب اجرا و در جدول ثبت می‌کند. ابزار را هنگام deploy اجرا کنید، نه در زمان‌های تصادفی startup برنامه.

بدفهمی رایج: «هر instance هنگام startup، migration بزند.» ده pod برای یک ALTER TABLE مسابقه می‌دهند و lock لازم دارند. بیشتر ابزارها advisory lock می‌گیرند، ولی migration طولانی همچنان rollout را مسدود می‌کند. آن را مرحلهٔ جداگانهٔ deploy کنید. روش بدون قطعی، expand/contract و CREATE INDEX CONCURRENTLY در Schema Migrations است.

تعریف: golang-migrate، "Database migrations written in Go"، هم CLI و هم کتابخانه است؛ فایل‌های SQL رفت و برگشت و پایگاه‌ها و منبع‌های متعدد دارد. goose، "a database migration tool. Both a CLI and a library"، migration SQL یا تابع Go با annotationهای -- +goose Up/Down دارد و روی *sql.DB کار می‌کند. Atlas، "a language-independent tool for managing and migrating database schemas"، workflow اعلانی دارد؛ atlas schema apply وضعیت مطلوب و فعلی را diff می‌کند و migration نسخه‌دار هم دارد. tern از نویسندهٔ pgx، "a standalone migration tool for PostgreSQL" با migration SQL و تابع Go و درون‌یابی متغیر داده است.

ابزارقالبdiff اعلانیAPI در Goنکته
golang-migrateNNN_name.up.sql / .down.sqlنهبلهپایگاه‌های متعدد؛ حالت "dirty" پس از شکست
gooseSQL با -- +goose Up یا تابع Goنهبله، *sql.DBقابل embed با embed.FS
Atlasschema با HCL یا SQL و پوشهٔ نسخه‌داربلهمحور CLIlint و diff در CI
ternSQL با template و migration در Goنهبله، بستهٔ migrate و pgxفقط PostgreSQL
sqlcخواندن پوشهٔ schemaنامربوطنامربوطschema: را به پوشهٔ migration بدهید
deploy pipeline
1  build image
2  run: goose -dir migrations postgres "$DATABASE_URL" up    (SET lock_timeout inside each file)
3  roll out new pods (code works with old and new schema: expand step)
4  later release: contract (drop old column)

N+1 در Go مهم ​

به زبان ساده: گرفتن یک فهرست و سپس یک query برای هر عضو، 1 + N رفت‌وبرگشت دارد. در Go پنهان نیست؛ query داخل حلقه می‌بینید. فرزندهای تمام والدها را با یک query بگیرید.

بدفهمی رایج: «N+1 مشکل ORM است؛ SQL دستی من ندارد.» متد repository داخل حلقه، یعنی for _, o := range orders { repo.Lines(ctx, o.ID) }، همان باگ است. با رفت‌وبرگشت 1 میلی‌ثانیه‌ای، صفحهٔ 100 سفارش فقط 100 میلی‌ثانیه منتظر شبکه می‌ماند.

تعریف: راه‌حل WHERE order_id = ANY($1) با slice شناسه‌هاست؛ pgx آن را bigint[] می‌فرستد. گزینه‌های دیگر JOIN و گروه‌بندی در Go، json_agg در SQL، یا Batch در pgx برای queryهای متفاوت‌اند. تست bulk فراخوانی driver را می‌شمارد: برای 10 سفارش، N+1 ده query و حالت دسته‌ای یک query دارد؛ کل []int64 یک آرگومان است.

N+1:      SELECT ... FROM orders LIMIT 100                 1
          SELECT ... FROM order_lines WHERE order_id = $1  x100
batched:  SELECT ... FROM orders LIMIT 100                 1
          SELECT ... FROM order_lines WHERE order_id = ANY($1)  1   ($1 = 100 ids)
راه‌حلتعداد queryزمان استفاده
= ANY($1) با idها2پیش‌فرض
JOIN و گروه‌بندی در Go1مجموعهٔ فرزند کوچک
json_agg / array_agg1read model و API با JSON تودرتو
pgx.Batch1 رفت‌وبرگشتquery متفاوت برای هر والد
dataloader در GraphQL1 در هر سطحresolverهای GraphQL؛ GraphQL in Go
go
package bulk

import (
	"database/sql/driver"
	"strings"
	"testing"

	"academy/database-sql-pgx/internal/fakedb"
)

func linesFake() *fakedb.DB {
	return fakedb.New(func(kind, q string, args []any) fakedb.Response {
		cols := []string{"order_id", "sku", "qty"}
		if kind == "exec" {
			return fakedb.Response{Affected: int64(len(args[0].([]int64)))}
		}
		return fakedb.Response{Columns: cols, Rows: [][]driver.Value{{int64(1), "A1", int64(2)}}}
	})
}

func TestNPlus1VersusBatched(t *testing.T) {
	ids := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	slow := linesFake()
	if _, err := LinesNPlus1(t.Context(), slow.Open(), ids); err != nil {
		t.Fatal(err)
	}
	fast := linesFake()
	if _, err := LinesBatched(t.Context(), fast.Open(), ids); err != nil {
		t.Fatal(err)
	}
	if slow.Count("query") != 10 || fast.Count("query") != 1 {
		t.Fatalf("n+1=%d batched=%d", slow.Count("query"), fast.Count("query"))
	}
	if _, ok := fast.Calls()[1].Args[0].([]int64); !ok {
		t.Fatal("the slice should reach the driver as one argument")
	}
}

func TestInsertUnnestIsOneStatement(t *testing.T) {
	fake := linesFake()
	n, err := InsertUnnest(t.Context(), fake.Open(), []Line{{1, "A1", 2}, {1, "B2", 1}, {2, "A1", 5}})
	if err != nil || n != 3 || fake.Count("exec") != 1 || len(fake.Calls()[1].Args) != 3 {
		t.Fatalf("n=%d err=%v calls=%v", n, err, fake.Kinds())
	}
}

func TestValuesChunksRespectParamLimit(t *testing.T) {
	rows := make([][]any, 50_000)
	for i := range rows {
		rows[i] = []any{int64(i), "sku", int64(1)}
	}
	chunks := ValuesChunks("order_lines", []string{"order_id", "sku", "qty"}, rows)
	if len(chunks) != 3 {
		t.Fatalf("chunks=%d", len(chunks))
	}
	total := 0
	for _, c := range chunks {
		if len(c.Args) > MaxParams {
			t.Fatalf("chunk with %d params", len(c.Args))
		}
		total += len(c.Args)
	}
	if total != 150_000 || !strings.HasSuffix(chunks[0].SQL, "($65533, $65534, $65535)") {
		t.Fatalf("total=%d tail=%q", total, chunks[0].SQL[len(chunks[0].SQL)-30:])
	}
}

تست: fake driver، pgx mock، DB واقعی و dockertest/testcontainers مهم ​

به زبان ساده: سرویس را با repository جعلی حافظه‌ای تست کنید؛ repository را با PostgreSQL واقعی. فقط سرور می‌گوید SQL، constraint و isolation واقعاً درست کار می‌کنند. mock driver برای حالت‌های محدود است.

بدفهمی رایج: «تست sqlmock/pgxmock درستی SQL را ثابت می‌کند.» فقط ثابت می‌کند رشتهٔ مورد انتظار ارسال شده و کد نتیجهٔ از پیش نوشته‌شده را مدیریت کرده است. غلط املایی ستون هم قبول می‌شود. pgxmock، "has one and only purpose - to simulate pgx behavior in tests, without needing a real database connection"؛ برای مسیر خطایی بگیرید که ایجاد واقعی‌اش دشوار است.

تعریف و گزینه‌ها:

لایهابزارچه چیزی ثابت می‌شودهزینه
منطق سرویسfake حافظه‌ای پیاده‌کنندهٔ interface repositoryقانون کسب‌وکار و فراخوانی مرز txمیلی‌ثانیه
رفتار database/sqldriver جعلی کوچک؛ internal/fakedb این صفحهpool، rows و ترتیب txمیلی‌ثانیه
تعامل با drivergo-sqlmock و pgx mock یعنی pgxmockمتن SQL و آرگومان مورد انتظار؛ مسیر خطامیلی‌ثانیه؛ شکننده
SQL در repositoryDB واقعی: ماژول postgres در testcontainers-go، ory/dockertest یا container سرویس CISQL، constraint، isolation و migrationچند ثانیه برای هر بسته
جداسازی تست‌هاrollback هر تست یا template database برای هر بستهنداشتن نشت بین تست‌هاکم
TestMain: start one container (testcontainers / dockertest pointer), run migrations once
each test: tx := pool.Begin(ctx); repo := NewSQLOrders(tx); ...; tx.Rollback(ctx)
CI:       services: postgres:18 in the pipeline instead of a container from the test

سناریوی واقعی: تست repository که نبود هدف ON CONFLICT را فقط روی سرور واقعی پیدا کرد؛ مجموعه‌تست ناپایدار با پایگاه مستقل هر بسته که از template مهاجرت‌یافته clone شده اصلاح می‌شود؛ go test -race برای سرویس با fake زیر یک ثانیه تمام می‌شود.

راه‌حل / روش استفاده: تست fake driver و fake repository در go test ./... پیش‌فرض بماند. تست DB واقعی را پشت build tag یا متغیر محیط بگذارید تا در CI با container اجرا شود. container خارج از قواعد آزمایشگاه این صفحه است؛ snippetها به fake محدودند.

مشاهده‌پذیری: otelsql، pgx tracer و آمار pool تکمیلی ​

به زبان ساده: از لایهٔ داده سه چیز برای مشاهده‌پذیری (Observability) می‌خواهید: span یا log هر query با مدت آن، gaugeهای pool شامل در حال استفاده و idle و انتظار، و شمار خطا بر اساس SQLSTATE.

بدفهمی رایج: «همهٔ queryها را با آرگومان log کن.» آرگومان دادهٔ شخصی و secret دارد؛ متن SQL، مدت، شمار سطر و کد خطا را log کنید و برای باقی sampling یا threshold بگذارید.

تعریف: otelsql برای database/sql، "is an OpenTelemetry instrumentation for Golang database/sql" که با پوشاندن driver، "instruments traces and metrics". در pgx، ConnConfig.Tracer یک pgx.QueryTracer می‌گیرد؛ TraceQueryStart، ctx می‌دهد که به TraceQueryEnd می‌رسد. BatchTracer، CopyFromTracer، PrepareTracer و ConnectTracer هم هستند. multitracer چند tracer را ترکیب می‌کند، tracelog logger را سازگار می‌کند و otelpgx ابزار OpenTelemetry برای pgx است؛ README آن حداقل Go 1.25 می‌خواهد. آمار از db.Stats() و pool.Stat() با AcquiredConns، IdleConns، EmptyAcquireCount، AcquireDuration و CanceledAcquireCount می‌آید.

TraceQueryStart(ctx, conn, {SQL, Args})  -> ctx' with start time (and a span in otelpgx)
... query runs ...
TraceQueryEnd(ctx', conn, {CommandTag, Err}) -> duration, rows, SQLSTATE -> log / span / histogram
سیگنالمنبعزمان هشدار
p99 زمان queryTracer / histogram در otelsqlبیش از بودجه
تعداد انتظار pool / زمان acquiredb.Stats().WaitCount، pool.Stat().EmptyAcquireCountروند افزایشی
در حال استفاده == سقفInUse، AcquiredConnsبه‌صورت پایدار
خطا بر اساس SQLSTATEدسته‌بند و counterجهش 40001 و هر 53300
Transaction طولانیpg_stat_activity با state = 'idle in transaction'عمر بیش از چند ثانیه
go
// Package observe adds query timing to pgx through its QueryTracer hook
// (ConnConfig.Tracer) and exports pool gauges. Production setups usually use
// otelpgx (pgx) or otelsql (database/sql) for OpenTelemetry spans and metrics;
// this shows the hook they plug into.
package observe

import (
	"context"
	"log/slog"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

// SlowQueries logs failed queries and queries slower than Threshold.
type SlowQueries struct {
	Log       *slog.Logger
	Threshold time.Duration
}

type startKey struct{}

type started struct {
	sql string
	at  time.Time
}

var _ pgx.QueryTracer = (*SlowQueries)(nil)

// TraceQueryStart stores the start time in the returned context.
func (t *SlowQueries) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context {
	return context.WithValue(ctx, startKey{}, started{sql: d.SQL, at: time.Now()})
}

// TraceQueryEnd logs SQL text (never the arguments: they may hold personal data).
func (t *SlowQueries) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryEndData) {
	s, ok := ctx.Value(startKey{}).(started)
	if !ok {
		return
	}
	took := time.Since(s.at)
	switch {
	case d.Err != nil:
		t.Log.ErrorContext(ctx, "query failed", "sql", s.sql, "took", took, "err", d.Err)
	case took >= t.Threshold:
		t.Log.WarnContext(ctx, "slow query", "sql", s.sql, "took", took, "rows", d.CommandTag.RowsAffected())
	}
}

// Install sets the tracer on a pool config before the pool is created.
func Install(cfg *pgxpool.Config, t pgx.QueryTracer) { cfg.ConnConfig.Tracer = t }

// PoolGauges reads pgxpool.Stat for a metrics exporter.
func PoolGauges(p *pgxpool.Pool) map[string]int64 {
	s := p.Stat()
	return map[string]int64{
		"total":            int64(s.TotalConns()),
		"acquired":         int64(s.AcquiredConns()),
		"idle":             int64(s.IdleConns()),
		"max":              int64(s.MaxConns()),
		"empty_acquire":    s.EmptyAcquireCount(), // had to wait: pool too small or queries too slow
		"acquire_ms_total": s.AcquireDuration().Milliseconds(),
		"canceled_acquire": s.CanceledAcquireCount(),
	}
}

سازوکار (Mechanics) ​

درون pool در database/sql مهم ​

sql.DB فهرست freeConn []*driverConn را با ترتیب "free connections ordered by returnedAt oldest to newest"، مجموعهٔ درخواست‌های منتظر connRequests، numOpen، سقف‌ها و شمارنده‌های Stats() نگه می‌دارد. OpenDB یک goroutine به‌نام connectionOpener راه می‌اندازد. با تعیین lifetime یا idle time، goroutine پاک‌کننده هم شروع می‌شود و اتصال منقضی را می‌بندد: "Expired connections may be closed lazily before reuse".

db.conn(ctx, strategy):
1  ctx already done?                     -> return ctx.Err()
2  free connection available (cachedOrNewConn)?
       take the newest; if expired -> close, try again; resetSession if the driver needs it
3  maxOpen reached?                      -> register a request, wait on it or ctx.Done()  (WaitCount++)
4  else numOpen++, dial via connector    -> new driverConn
release (putConn): hand to a waiting request first, else append to freeConn if under maxIdle, else close (MaxIdleClosed++)
driver.ErrBadConn on a fresh call        -> retry (maxBadConnRetries = 2), then once with a forced new connection

*sql.Tx و *sql.Conn اتصال را تا پایان عمرشان از چرخه بیرون می‌برند؛ *sql.Rows تا Close یا EOF نگهش می‌دارد. context در BeginTx یک goroutine به‌نام awaitDone دارد که با پایان context، Transaction را rollback می‌کند؛ به همین دلیل تست rollback، poll می‌کند.

درون pgx و pgxpool تکمیلی ​

pgxpool روی github.com/jackc/puddle/v2 ساخته شده است. هر resource یک *pgx.Conn روی pgconn.PgConn است که با I/O غیرمسدودکننده پروتکل frontend/backend را حرف می‌زند. در Query با حالت پیش‌فرض، SQL در cache از نوع LRU اتصال جست‌وجو می‌شود؛ نام "stmtcache_" + hex(sha256(sql)[:24]) است. نبود ورودی باعث Parse/Describe و سپس Bind/Execute/Sync می‌شود؛ نتیجه با pgtype.Map همان اتصال decode می‌شود. در خطا ورودی cache باطل می‌شود. در Conn.exec یعنی مسیر Exec، دستور بدون آرگومان مستقل از mode با simple protocol می‌رود. حالت pipeline با یک Sync برای چند دستور زیربنای SendBatch است.

متن دقیق خطاها حیاتی ​

متنمنبع
sql: no rows in result setsql.ErrNoRows
sql: transaction has already been committed or rolled backsql.ErrTxDone
sql: connection is already closedsql.ErrConnDone
sql: Scan error on column index 0, name "phone": converting NULL to string is unsupportedRows.Scan؛ خروجی واقعی
no rows in result setpgx.ErrNoRows که sql.ErrNoRows را wrap می‌کند
too many rows in result setpgx.ErrTooManyRows
tx is closedpgx.ErrTxClosed
commit unexpectedly resulted in rollbackpgx.ErrTxCommitRollback
conn busypgconn؛ دو goroutine از یک *pgx.Conn استفاده کرده‌اند
cannot find field customer_id in returned rowRowToStructByName؛ خروجی واقعی
extended protocol limited to 65535 parameterspgconn؛ %v = math.MaxUint16
failed to connect to ... dial error: dial tcp 127.0.0.1:1: connect: connection refusedPing در pgxpool؛ خروجی واقعی
ERROR: could not serialize access due to concurrent update (SQLSTATE 40001)PostgreSQL، Repeatable Read
ERROR: could not serialize access due to read/write dependencies among transactions (SQLSTATE 40001)PostgreSQL، Serializable
ERROR: current transaction is aborted, commands ignored until end of transaction block (SQLSTATE 25P02)دستور پس از خطا داخل tx
ERROR: cached plan must not change result typeprepared statement پس از تغییر schema

حل مسئله‌های کلاسیک (Solutions) ​

باگنشانهاصلاحهزینه
sql.Open برای هر درخواستبازوبسته شدن اتصال، 53300یک pool در mainندارد
نبود PingContext در startupشکست اولین درخواست پس از deploy بدPing با timeoutیک فراخوانی
MaxOpenConns نامحدوداضافه‌بار سرور در اوجبودجه برای هر instanceکمی صف
Rows بسته‌نشدهاتمام ظرفیت pool و رشد WaitCountdefer rows.Close()ندارد
نادیده گرفتن rows.Err()نتیجهٔ بریدهبررسی پس از حلقهندارد
SQL با چسباندن رشتهتزریقplaceholder و allow-listندارد
دستور بیرون txنوشتن ناقص، deadlockهمه‌جا tx و helperانضباط
نبود rollback در خطاlock تا timeout می‌ماندdefer tx.Rollback()ندارد
retry یک دستور25P02تکرار کل Transaction برای 40001/40P01تابع idempotent
HTTP داخل txTransaction و lock طولانیoutbox و فراخوانی پس از commitجدول اضافه
SELECT * و cache دستورخطا پس از migrationفهرست صریح ستون‌هاتایپ بیشتر
cache پشت transaction pooler26000 / 42P05QueryExecModeExec یا رهگیری PgBouncer ≥ 1.21کمی planning بیشتر
N+1تأخیر متناسب با اندازهٔ صفحه= ANY($1) و batchندارد
تطبیق متن خطاشکست با ارتقا یا زبانerrors.As و SQLSTATEندارد

repository که برای هر متد Transaction پنهان داشت ​

شروع Transaction مستقل در هر متد، رایج‌ترین علت گم شدن event یا سطر audit است. مرز را با TxManager.InTx یا Unit of work به use case ببرید؛ اشتراک تراکنش را ببینید. repository فقط همان چیزی را به کار می‌گیرد که به آن داده‌اید.

Transaction طولانی ​

go
// Bug: the transaction (and its row locks) lives for the whole HTTP call.
err := txn.WithTx(ctx, db, nil, func(tx *sql.Tx) error {
	if _, err := tx.ExecContext(ctx, `UPDATE stock SET qty = qty - 1 WHERE sku = $1`, sku); err != nil {
		return err
	}
	return payments.Charge(ctx, amount) // 2 s on a bad day, locks held all along
})

// Fix: reserve and record the intent in one short transaction, charge outside,
// confirm in a second short transaction (or let a worker drive it from an outbox row).

اتمام ظرفیت pool با اتصال‌های تودرتو ​

تابعی که Tx نگه داشته و درونش helper مبتنی بر db صدا می‌زند، هم‌زمان دو اتصال لازم دارد. با MaxOpenConns(n) و n درخواست هم‌زمان با همین رفتار، هر n درخواست یک اتصال دارند و تا پایان ctx منتظر دومی می‌مانند. این همان deadlock هشدار داده‌شده در go.dev است. tx یا ctx حامل آن را به پایین بدهید.

انتخاب (Choosing) ​

وضعیتانتخابروش مکملدلیل
سرویس تازه فقط با PostgreSQLpgx v5 بومی و pgxpoolsqlc با sql_package: pgx/v5سریع‌ترین و تمام قابلیت‌ها
کتابخانه یا کد چندپایگاهیdatabase/sql + pgx stdlibاگر pgx هم لازم است OpenDBFromPoolقابل حمل؛ انتظار ابزارها *sql.DB است
کد موجود lib/pqحفظ و مهاجرت هنگام تغییرنام driver را pgx کنید و NULL/array را تست کنیدجایگزینی کم‌خطر
MySQLgo-sql-driver/mysqlparseTime=true و placeholder ?driver مرسوم
خواندن کوچک فراوان در هر صفحهpgx.Batch یا = ANY($1)حذف N+1غلبهٔ هزینهٔ رفت‌وبرگشت
بارگذاری انبوهCopyFromجدول میانی و INSERT ... ON CONFLICTسرعت در مرتبه‌ای بالاتر
upsert چند هزار سطرarrayهای unnestON CONFLICT DO UPDATEیک دستور با متن ثابت
انتقال پول و موجودیBeginTx و SELECT ... FOR UPDATE یا SerializableWithRetry برای 40001درستی در اولویت
گزارش فقط‌خواندنیLevelRepeatableRead, ReadOnlyreplica اگر lag پذیرفتنی استیک snapshot
پشت PgBouncer transactionQueryExecModeExec یا رهگیری PgBouncer ≥ 1.21اتصال مستقیم LISTENحالت نشست باقی نمی‌ماند
ابطال cache بین instanceهاLISTEN/NOTIFYبازخوانی پس از reconnectبدون broker
CRUD ثابت و query گزارشsqlcbuilder برای فیلتر پویانوع‌دار و SQL آشکار
پنل مدیریتGORM یا bunمراقبت از N+1سرعت توسعه
تست سرویسrepository جعلیDB واقعی برای تست repositoryسریع و با ادعای دقیق

در معماری: از یک فرایند تا سیستم توزیع‌شده ​

Monolith: یک فرایند، یک پایگاه داده ​

یک pgxpool.Pool یا *sql.DB در main ساخته، ping و متناسب با بودجهٔ پایگاه اندازه‌گذاری می‌شود و از constructor به repository می‌رسد. use caseها یک TxManager دارند و pipeline استقرار migration را اجرا می‌کند. مثال: API سفارش در POST /orders، InTx → Orders.Save + Outbox.Append را در یک تراکنش (Transaction) با بودجهٔ ctx برابر 2 ثانیه اجرا می‌کند؛ role دارای statement_timeout = 5s و pool دارای MaxConns = 20 است.

Monolith ماژولار و چند پایگاه داده ​

هر ماژول مالک جدول‌ها و repositoryهای خودش است؛ ماژول دیگر API در Go را صدا می‌زند، نه جدول را. تا وقتی دو ماژول در یک پایگاه‌اند، می‌توانند یک pool و یک تراکنش (Transaction) مشترک داشته باشند؛ tx در context این را آسان می‌کند و همان‌جا خطر هم دارد چون وابستگی را پنهان می‌کند. با دو پایگاه، مثلاً سفارش در PostgreSQL و تحلیل در پایگاه دیگر، دو pool دارید و Transaction مشترک ندارید. outbox پایگاه سفارش و یک consumer تغییر را به سمت دیگر می‌برند. نام pool را از پایگاه بگیرید، مثل ordersDB و billingDB، تا اشتباه پاس داده نشود.

Microservices ​

هر سرویس پایگاه و pool خودش را دارد؛ فقط API call و event از مرز عبور می‌کنند. تغییر چندسرویسی یک saga است: سرویس سفارش orders و outbox را با هم commit می‌کند، relay رویداد order.created را منتشر می‌کند و سرویس پرداخت با جدول processed_messages و کلید unique که با 23505 بررسی می‌شود، idempotent مصرف می‌کند و حالت و outbox خودش را commit می‌کند. اندازهٔ pool مسئلهٔ کل ناوگان است: 30 سرویس × 4 pod × 20 اتصال = 2,400، بسیار بالاتر از محدودهٔ راحت یک PostgreSQL. این‌جا PgBouncer، RDS Proxy و pgcat وارد می‌شوند و محدودیت prepared statement و LISTEN را همراه می‌آورند.

دادهٔ توزیع‌شده: replica، cache، پایگاه shardشده و چند منطقه ​

نسخهٔ خواندنی (Read replica) یک pool دیگر به‌نام replicaPool با target_session_attrs و default_transaction_read_only است. خواندنی که باید نوشتن خود کاربر را ببیند، یعنی read-your-writes، به primary می‌رود یا منتظر LSN در replica می‌ماند. failover میزبان primary را عوض می‌کند؛ MaxConnLifetime همراه target_session_attrs=read-write در DSN چندمیزبانی به pool کمک می‌کند میزبان تازه را پیدا کند. Transaction در حال اجرا با 57P01 یا 08006 شکست می‌خورد و نتیجه‌اش نامعلوم است؛ نوشتن‌ها کلید idempotency می‌خواهند. SQL توزیع‌شده مثل CockroachDB پروتکل PostgreSQL دارد؛ README در pgx می‌گوید "is tested against the latest version of CockroachDB". مستند CockroachDB پیش‌فرض همهٔ Transactionها را SERIALIZABLE می‌داند؛ پس 40001 عادی و helper retry الزامی است. shard کردن بر اساس tenant یعنی یک pool برای هر shard و router انتخاب‌کننده بر اساس tenant id؛ Transaction میان shardها وجود ندارد.

مسیر رشد: 1×، 10×، 100× ​

بارچه تغییر می‌کندروش لایهٔ داده در Go
1×؛ یک instanceپیش‌فرض‌ها باگ را پنهان می‌کنندیک pool، Ping، هر چهار تنظیم، defer rows.Close()، helper tx و دسته‌بند SQLSTATE
10×؛ چند instanceبودجهٔ اتصال و query کند مهم می‌شودظرفیت = بودجه ÷ instance، statement_timeout، metric pool، batch/ANY و COPY برای import
100×؛ ناوگان، replica و poolerاتصال سرور و failover غالب می‌شوندPgBouncer transaction با حالت exec یا رهگیری 1.21+، pool replica، retry بودجه‌دار و outbox برای هر اثر میان‌سرویسی

آزمایشگاه (Lab) ​

1. اجرای تست‌ها؛ واقعی ​

cd docs/snippets/go/database-sql-pgx/go
gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ok  academy/database-sql-pgx/after       1.982s
# ok  academy/database-sql-pgx/before      1.923s
# ok  academy/database-sql-pgx/bulk        1.905s
# ok  academy/database-sql-pgx/errs        1.855s
# ?   academy/database-sql-pgx/internal/fakedb  [no test files]
# ok  academy/database-sql-pgx/nulls       1.846s
# ok  academy/database-sql-pgx/observe     1.690s
# ok  academy/database-sql-pgx/pgxnative   1.679s
# ok  academy/database-sql-pgx/pool        1.733s
# ok  academy/database-sql-pgx/prepared    1.625s
# ok  academy/database-sql-pgx/repository  1.795s
# ok  academy/database-sql-pgx/txn         1.859s

2. مشاهدهٔ پیش‌فرض‌ها و تنبلی؛ واقعی ​

go test -count=1 -v -run 'TestDefaults|TestPoolIsLazy|TestScanNullIntoStringFails|TestStmtReprepareOnNewConnection' ./pgxnative ./nulls ./prepared
# config_test.go:41: MaxConns default on this machine: 12
# config_test.go:70: failed to connect to `user=app database=orders`: 127.0.0.1:1 (127.0.0.1): dial error: dial tcp 127.0.0.1:1: connect: connection refused
# nulls_test.go:47: sql: Scan error on column index 0, name "phone": converting NULL to string is unsupported
# prepared_test.go:59: connections=3 prepares=3

pgxpool.NewWithConfig برای پورتی که هیچ listener نداشت بدون خطا برگشت؛ فقط Ping شکست خورد. یک Stmt در سطح DB که روی سه اتصال اجرا شد، سه بار prepare شد.

3. Schema آزمایش‌های سرور ​

schema کنار کد در pgxnative/schema.sql است و با نام Schema داخل بسته embed می‌شود تا تست بتواند با کد مقایسه کند: فهرست ستون Import هر ستون NOT NULL بدون پیش‌فرض را پوشش می‌دهد و enum به‌نام order_status که AfterConnect بار می‌کند این‌جا ساخته می‌شود. پیش از شروع pool ساخته‌شده با PoolConfig آن را اعمال کنید.

sql
-- Lab schema for the database-sql-pgx snippets (run before starting the service:
-- pgxpool's AfterConnect loads the order_status type on every new connection).
CREATE TYPE order_status AS ENUM ('open', 'paid', 'shipped', 'cancelled');
CREATE TABLE accounts (id bigint PRIMARY KEY, balance bigint NOT NULL CHECK (balance >= 0));
CREATE TABLE users (
  id    bigserial PRIMARY KEY,
  email text NOT NULL,
  CONSTRAINT users_email_key UNIQUE (email)
);
CREATE TABLE orders (
  id          bigserial PRIMARY KEY,
  customer_id bigint NOT NULL,
  email       text NOT NULL,
  note        text,
  status      order_status NOT NULL DEFAULT 'open',
  total_cents bigint NOT NULL,
  shipped_at  timestamptz,
  version     int NOT NULL DEFAULT 1
);
CREATE TABLE order_lines (
  order_id bigint NOT NULL REFERENCES orders (id),
  sku      text NOT NULL,
  qty      bigint NOT NULL,
  PRIMARY KEY (order_id, sku)
);
CREATE TABLE outbox (
  id         bigserial PRIMARY KEY,
  topic      text NOT NULL,
  payload    bytea,
  created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO accounts VALUES (1, 1000), (2, 0);

پشتیبان‌های سمت سرور در سطح role برای کاربر برنامه؛ پشت PgBouncer transaction pooling این تنها محل نگهداری timeoutهاست، ببینید PgBouncer:

sql
ALTER ROLE app SET statement_timeout = '5s';
ALTER ROLE app SET lock_timeout = '2s';
ALTER ROLE app SET idle_in_transaction_session_timeout = '30s';
go
package pgxnative

import (
	"regexp"
	"slices"
	"strings"
	"testing"
)

// requiredColumns returns the NOT NULL columns without a DEFAULT of one table in schema.sql.
func requiredColumns(t *testing.T, table string) []string {
	t.Helper()
	m := regexp.MustCompile(`(?s)CREATE TABLE ` + table + ` \((.*?)\n\);`).FindStringSubmatch(Schema)
	if m == nil {
		t.Fatalf("table %s not in schema.sql", table)
	}
	var out []string
	for _, line := range strings.Split(m[1], "\n") {
		f := strings.Fields(strings.TrimSuffix(strings.TrimSpace(line), ","))
		if len(f) < 2 || strings.ToUpper(f[0]) == "PRIMARY" {
			continue
		}
		l := strings.ToUpper(line)
		if strings.Contains(l, "NOT NULL") && !strings.Contains(l, "DEFAULT") && !strings.Contains(l, "SERIAL") {
			out = append(out, f[0])
		}
	}
	return out
}

// Round 1: COPY fails for NOT NULL columns it omits that have no default.
func TestImportCoversRequiredColumns(t *testing.T) {
	for _, c := range requiredColumns(t, "orders") {
		if !slices.Contains(ImportColumns, c) {
			t.Errorf("Import omits required column %q", c)
		}
	}
}

// Round 1: AfterConnect loads these types; the schema must create them.
func TestSchemaCreatesLoadedTypes(t *testing.T) {
	for _, typ := range LoadedTypes {
		if !strings.Contains(Schema, "CREATE TYPE "+typ+" ") {
			t.Errorf("schema.sql does not create type %s used by AfterConnect", typ)
		}
	}
}

4. شکست serialization واقعی؛ خروجی مورد انتظار، اجرا نشده ​

دو نشست psql روی schema بالا:

     session A                                          session B
1    BEGIN ISOLATION LEVEL REPEATABLE READ;             BEGIN ISOLATION LEVEL REPEATABLE READ;
2    SELECT balance FROM accounts WHERE id = 1;  -- 1000
3                                                       SELECT balance FROM accounts WHERE id = 1;  -- 1000
4    UPDATE accounts SET balance = balance - 100 WHERE id = 1;
5    COMMIT;
6                                                       UPDATE accounts SET balance = balance - 100 WHERE id = 1;
7                                                       -- ERROR:  could not serialize access due to concurrent update
8                                                       ROLLBACK;   -- txn.WithRetry would now run B again and succeed

5. statement_timeout و cancel؛ خروجی مورد انتظار، اجرا نشده ​

go: pool.Exec(ctx /* 300 ms */, "SELECT pg_sleep(10)")
# default pgx handler:  timeout: context deadline exceeded   (connection discarded)
psql: SELECT pid, state, query FROM pg_stat_activity WHERE query LIKE '%pg_sleep%';
# row still present until the backend notices the closed socket
go: pool.Exec(context.Background(), "SELECT pg_sleep(10)")   with role statement_timeout = 5s
# ERROR: canceling statement due to statement timeout (SQLSTATE 57014) after 5 s

6. حالت transaction در PgBouncer؛ خروجی مورد انتظار، اجرا نشده ​

با pool_mode = transaction، max_prepared_statements = 0 و default_pool_size = 2 در PgBouncer، همان pool.Query پارامتردار را از 20 goroutine با پیش‌فرض pgx اجرا کنید. انتظار خطای گاه‌به‌گاه prepared statement "stmtcache_..." does not exist (SQLSTATE 26000) یا 42P05 داریم. با افزودن default_query_exec_mode=exec به DSN خطاها حذف می‌شوند. در PgBouncer 1.21+ مقدار max_prepared_statements = 200 بگذارید و گزینهٔ DSN را بردارید؛ طبق مستند PgBouncer حالت پیش‌فرض دوباره کار می‌کند.

7. LISTEN/NOTIFY؛ خروجی مورد انتظار، اجرا نشده ​

go:   Listen(ctx, pool, "orders_changed", func(n *pgconn.Notification) error { fmt.Println(n.Channel, n.Payload); return nil })
psql: BEGIN; SELECT pg_notify('orders_changed', '42');    -- nothing printed yet
psql: COMMIT;                                             -- go prints: orders_changed 42

برای توسعه‌دهندگان PHP/Laravel ​

در PHP-FPM هر درخواست فرایندی با اتصال PDO خودش یا اتصال persistent برای هر worker دارد؛ pool داخل فرایند برای اندازه‌گذاری ندارید. در Go، *sql.DB میان هزاران goroutine یک فرایند مشترک است؛ اندازهٔ pool، rows بسته‌نشده و Transaction طولانی مسئولیت شماست، نه pm.max_children در FPM. Eloquent یک ORM از نوع Active Record با lazy loading است و به همین دلیل N+1 و with() مطرح می‌شوند؛ کد Go معمولاً SQL می‌نویسد یا با sqlc تولید می‌کند. DB::transaction در Laravel 13 خودکار commit یا rollback می‌کند و "accepts an optional second argument which defines the number of times a transaction should be retried when a deadlock occurs". معادل Go، txn.WithRetry است که شما SQLSTATE قابل retry را تعیین می‌کنید؛ 40001 در کنار 40P01. Laravel 13 همچنین «Pooled PostgreSQL Connections» را مستند کرده: اتصال pooled برای transaction pooler و مشخصات direct چون "some schema operations, migrations, and maintenance commands require a direct database connection". همان جداسازی pool مستقیم برای migration و LISTEN در Go است.

php
// Laravel: closure-based transaction, retried up to 3 times on deadlock.
DB::transaction(function () use ($from, $to, $cents) {
    DB::update('UPDATE accounts SET balance = balance - ? WHERE id = ?', [$cents, $from]);
    DB::update('UPDATE accounts SET balance = balance + ? WHERE id = ?', [$cents, $to]);
}, attempts: 3);
Laravel / PHPGo
DB::connection() با PDOsql.Open / pgxpool.New برای pool تنبل و Ping
یک اتصال برای هر worker در FPMیک pool در هر فرایند، SetMaxOpenConns / MaxConns
binding با ? و prepare شبیه‌سازی‌شدهٔ PDOplaceholder با $1 و cache دستور pgx
DB::transaction(fn, attempts)txn.WithTx / WithRetry
مدل Eloquent و with()repository و sqlc، = ANY($1)
QueryException و errorInfo[0] یعنی SQLSTATEerrors.As(err, &pgErr)؛ pgErr.Code
php artisan migrategoose، golang-migrate، Atlas، tern
اتصال pgsql با pooled و directDSN از pooler برای query؛ DSN مستقیم برای migration و LISTEN
DB::listen برای log querypgx.QueryTracer، otelsql

بدفهمی‌های رایج ​

باورواقعیت
sql.Open اتصال را بررسی می‌کندشاید اصلاً وصل نشود؛ PingContext بزنید
برای هر درخواست یک *sql.DBpool است؛ یک‌بار در هر فرایند
اتصال نامحدود سریع‌ترین استسرور overload می‌شود؛ MaxOpenConns/MaxConns تنظیم کنید
اندازهٔ پیش‌فرض pgxpool برابر 4 استmax(4, runtime.NumCPU())
false از Next یعنی موفقیتrows.Err() را بررسی کنید
rows.Close() اختیاری استخروج زودهنگام بدون آن اتصال نشت می‌دهد
database/sql، ? را به $1 تبدیل می‌کندsyntax جای‌نگهدار متعلق به driver است
db.Prepare یک‌بار آماده می‌کندروی هر اتصال مورد استفاده یک‌بار
خاموشی cache در pgx یعنی درون‌یابیفقط simple protocol درون‌یابی دارد
defer tx.Rollback()، commit را برمی‌گرداندپس از Commit کاری نمی‌کند و ErrTxDone می‌دهد
db.ExecContext در تابع tx جزو tx استروی اتصال دیگر و بیرون Transaction اجرا می‌شود
در 40001 فقط دستور شکست‌خورده را تکرار کنکل Transaction را تکرار کنید
لغو ctx، query سرور را متوقف می‌کندوابسته به driver؛ پیش‌فرض pgx اتصال را می‌بندد
PgBouncer هرگز از prepared statement پشتیبانی نمی‌کنداز 1.21+ نوع protocol-level را با max_prepared_statements > 0 رهگیری می‌کند
تست sqlmock درستی SQL را ثابت می‌کندفقط پایگاه واقعی می‌تواند
duplicate key را در پیام پیدا کنSQLSTATE 23505 و نام constraint را بسنجید

برگهٔ تقلب (Cheat sheet) ​

موضوعبه خاطر بسپارید
باز کردنیک‌بار در main؛ PingContext با timeout؛ وگرنه تنبل
poolSetMaxOpenConns، SetMaxIdleConns با پیش‌فرض 2، SetConnMaxLifetime، SetConnMaxIdleTime
pgxpoolMaxConns پیش‌فرض max(4, NumCPU)؛ MinIdleConns؛ عمر 1 h؛ idle برابر 30 min؛ health check برابر 1 min
queryQueryContext → defer rows.Close() → Next/Scan → rows.Err()
تک‌سطرQueryRowContext(...).Scan؛ sql.ErrNoRows → not found دامنه
NULLpointer، sql.Null[T] از 1.22 یا sql.NullString؛ هرگز string ساده
placeholderPostgreSQL با $1، MySQL با ?؛ identifier از allow-list یا pgx.Identifier
preparepgx خودکار cache می‌کند، 512 در هر اتصال؛ Stmt متعلق به هر اتصال است
حالت اجراپیش‌فرض cache_statement؛ پشت transaction pooler از exec
TransactionBeginTx → defer tx.Rollback() → کار فقط با tx → Commit
retry40001 و 40P01: تکرار کل تابع با backoff؛ 23505 فقط اگر کلید داخل tx از نوع Serializable مشتق شده باشد
timeoutctx هر فراخوانی و statement_timeout، lock_timeout، idle_in_transaction_session_timeout
خطاerrors.As(err, &*pgconn.PgError)؛ تصمیم بر اساس Code
انبوهCopyFrom > array با unnest > VALUES چندسطری با 65535 پارامتر > حلقه
N+1= ANY($1) با slice یا pgx.Batch
repositoryinterface برای هر Aggregate، نوع دامنه و ستون version
tx مشترکTx در ctx با InTx یا Unit of work؛ مرز در use case
تستfake برای سرویس، PostgreSQL واقعی برای repository

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — sql.Open("pgx", dsn) چه می‌کند و چطور رمز اشتباه را هنگام startup پیدا می‌کنید؟ حیاتی ​

پاسخ

پاسخ: driver ثبت‌شده را پیدا و شیء pool از نوع *sql.DB را برمی‌گرداند؛ "may just validate its arguments without creating a connection". بلافاصله db.PingContext(ctx) با timeout بزنید؛ اتصال می‌سازد و احراز هویت می‌کند تا DSN یا رمز غلط deploy را شکست دهد، نه اولین درخواست را.

۲ — با SetMaxOpenConns(10) و پایگاه بیکار، درخواست‌ها context deadline exceeded می‌گیرند؛ اول چه چیزی را می‌بینید؟ حیاتی ​

پاسخ

پاسخ: db.Stats()؛ اگر InUse برابر 10 و WaitCount رو به رشد است، اتصال‌ها نگه داشته شده‌اند، نه مشغول اجرای کار. علت معمول *sql.Rows بسته‌نشده در خروج زودهنگام، Transaction طولانی مثل HTTP در Tx، یا استفادهٔ تودرتو از db هنگام نگه داشتن Tx است. پیش از بالا بردن سقف، نگهدارندهٔ اتصال را اصلاح کنید.

۳ — چرا پس از حلقهٔ for rows.Next() باید rows.Err() را بخوانید؟ حیاتی ​

پاسخ

پاسخ: Next هم در پایان نتیجه و هم هنگام خطای خواندن سطر بعد false می‌دهد؛ "Rows.Err should be consulted to distinguish between the two cases". بدون آن قطع اتصال میان جریان، نتیجهٔ کوتاه‌تر به نظر می‌رسد.

۴ — الگوی defer-Rollback چیست و چرا Rollback معوق پس از Commit موفق بی‌خطر است؟ حیاتی ​

پاسخ

پاسخ: tx, err := db.BeginTx(ctx, nil)؛ defer tx.Rollback()؛ تمام کار روی tx؛ و return tx.Commit(). هر خروج زودهنگام یا panic باعث rollback می‌شود. بعد از Commit، Tx تمام شده و Rollback بدون ارسال چیزی به سرور sql.ErrTxDone می‌دهد؛ تست بعد نشان می‌دهد driver آن را نمی‌بیند.

۵ — Transaction با SQLSTATE 40001 شکست می‌خورد؛ کد چه کند و تابع چه ویژگی‌ای داشته باشد؟ حیاتی ​

پاسخ

پاسخ: rollback کنید و کل Transaction را از BeginTx با backoff و تعداد تلاش محدود، تا وقتی ctx صدازننده اجازه می‌دهد، دوباره اجرا کنید. تابع باید اجرای دوباره را تحمل کند؛ اثر بیرونی مثل email، HTTP call و channel send داخلش نباشد. این قصدها را در سطر outbox ثبت کنید.

۶ — ستون nullable به‌نام phone را چگونه scan می‌کنید و اگر مقصد string باشد چه می‌شود؟ مهم ​

پاسخ

پاسخ: در *string با nil برای NULL، در sql.Null[string] از Go 1.22 یا در sql.NullString. خواندن NULL در string معمولی با converting NULL to string is unsupported شکست می‌خورد.

۷ — db.PrepareContext در pool با 20 اتصال واقعاً چه می‌کند؟ مهم ​

پاسخ

پاسخ: روی یک اتصال آماده می‌کند و *sql.Stmt می‌دهد که هر بار روی اتصال دیگری اجرا شود "will prepare itself on the new connection automatically"؛ پس تا 20 prepare سمت سرور داریم. با pgx معمولاً این مرحله را نمی‌خواهید چون cache دستور آن از قبل روی هر اتصال آماده و بازاستفاده می‌کند.

۸ — سرویس pgx پشت PgBouncer transaction رفته و prepared statement "stmtcache_..." does not exist می‌دهد؛ علت و اصلاح چیست؟ مهم ​

پاسخ

پاسخ: حالت پیش‌فرض cache_statement در pgx، statement نام‌دار را در یک نشست می‌سازد؛ Transaction بعدی ممکن است روی اتصال سرور دیگری بیفتد. default_query_exec_mode=exec یا در pgx ≥ 5.12.0، simple_protocol بگذارید؛ یا PgBouncer 1.21+ را با max_prepared_statements > 0 اجرا کنید تا statement را روی هر اتصال مورد استفاده دوباره آماده کند.

۹ — نقض یکتایی روی users.email را بدون تطبیق متن پیام چگونه به 409 تبدیل می‌کنید؟ مهم ​

پاسخ

پاسخ: var pg *pgconn.PgError; if errors.As(err, &pg) && pg.Code == "23505" && pg.ConstraintName == "users_email_key" { return ErrEmailTaken }. errors.As از wrap با %w عبور می‌کند و کد و نام constraint میان زبان‌ها و نسخه‌ها پایدارند.

۱۰ — دو repository باید در یک Transaction بنویسند؛ دو روش اشتراک و یک خطر هرکدام چیست؟ مهم ​

پاسخ

پاسخ: حمل *sql.Tx در context؛ InTx می‌گذارد و repository برمی‌دارد. ضمنی است و فراخوانی بیرون InTx بی‌صدا بدون Transaction اجرا می‌شود. Unit of work، repositoryهای متصل به tx را به تابع می‌دهد؛ صریح است ولی کد اتصال بیشتری دارد و هر بار repository می‌سازد. در هر دو، مالک مرز use case است، هرگز repository نیست.

۱۱ — چه وقت CopyFrom برای درج 10,000 سطر ابزار اشتباهی است؟ تکمیلی ​

پاسخ

پاسخ: وقتی ON CONFLICT برای upsert یا RETURNING لازم دارید که COPY پشتیبانی نمی‌کند، یا به database/sql بدون Raw محدودید. از INSERT ... SELECT * FROM unnest($1::bigint[], ...) همراه ON CONFLICT یا COPY به جدول میانی و سپس یک INSERT ... ON CONFLICT استفاده کنید.

۱۲ — با پیش‌فرض pgx، لغو ctx یک query در حال اجرا در سرور چه اثری دارد و چه پشتیبانی اضافه می‌کنید؟ تکمیلی ​

پاسخ

پاسخ: DeadlineContextWatcherHandler پیش‌فرض روی socket مهلت می‌گذارد؛ فراخوانی Go برمی‌گردد و اتصال دور انداخته می‌شود، ولی backend تا تشخیص بسته شدن اتصال ادامه می‌دهد. برای ارسال cancel، CancelRequestContextWatcherHandler را تنظیم کنید و statement_timeout در سطح role را به‌عنوان پشتیبان سمت سرور نگه دارید.

واژه‌نامه (Glossary) ​

اصطلاحمعنی
database/sqlبستهٔ استاندارد Go برای pool، Transaction و رابط driver پایگاه‌های SQL
*sql.DBpool امن برای هم‌زمانی؛ یک‌بار برای هر پایگاه باز کنید
تنبلی sql.Open (sql.Open lazy)sql.Open/OpenDB شاید وصل نشوند؛ Ping یا اولین query اتصال می‌سازد
PingContextامکان ساخت و استفاده از اتصال را می‌سنجد
SetMaxOpenConnsسقف اتصال باز؛ پیش‌فرض نامحدود
SetMaxIdleConnsاتصال‌های بیکار نگه‌داشته‌شده؛ پیش‌فرض 2
SetConnMaxLifetimeبیشینهٔ عمر اتصال پیش از بستن
SetConnMaxIdleTimeبیشینهٔ بیکاری اتصال پیش از بستن؛ Go 1.15
DBStatsشمارنده‌های db.Stats()؛ باز، مشغول، بیکار و انتظار
راه‌انداز (Driver)بستهٔ پیاده‌کنندهٔ database/sql/driver برای یک پایگاه
pgx stdlibadapter به‌نام github.com/jackc/pgx/v5/stdlib که با "pgx" ثبت می‌شود
lib/pqdriver قدیمی pure-Go برای PostgreSQL؛ مدت طولانی در حالت نگهداری
go-sql-driver/mysqldriver مربوط به MySQL برای database/sql
QueryContext / QueryRowContext / ExecContextquery، query تک‌سطر و exec آگاه از context
*sql.Rowsمکان‌نمای نتیجه؛ Next، Scan، Err، Close
sql.ErrNoRowsخطای Row.Scan وقتی هیچ سطر برنگشته
مدیریت NULL (NULL handling)نمایش NULL در Go با pointer یا نوع‌های Null
sql.NullStringرشتهٔ nullable نوع‌دار با پرچم Valid
sql.Null[T]wrapper جنریک nullable از Go 1.22
جای‌نگهدار (Placeholder)نشان پارامتر SQL؛ $1 در PostgreSQL و ? در MySQL
تزریق SQL (SQL injection)تفسیر ورودی کاربر به‌عنوان SQL به‌علت چسباندن به متن
دستور آماده (Prepared statement)دستور parseشدهٔ سرور در یک نشست که با پارامتر اجرا می‌شود
*sql.Stmthandle در database/sql که روی هر اتصال مورد استفاده خودش را prepare می‌کند
آماده‌سازی ضمنی هر اتصال (Implicit per-connection prepare)prepare هر دستور توسط database/sql وقتی driver، QueryerContext ندارد
حافظهٔ دستور (Statement cache)LRU هر اتصال pgx برای prepared statement؛ stmtcache_... با 512 ورودی
QueryExecModeتنظیم pgx شامل cache_statement، cache_describe، describe_exec، exec و simple_protocol
پروتکل ساده (Simple protocol)پروتکل query در PostgreSQL با مقدارهای درون‌یابی‌شده در یک رشته
پروتکل توسعه‌یافته (Extended protocol)پیام‌های Parse/Bind/Execute با پارامتر جدا
تراکنش (Transaction)گروه دستورها روی یک اتصال که با هم commit یا rollback می‌شوند
BeginTxشروع Transaction با TxOptions برای isolation و فقط‌خواندنی
سطح جداسازی (Isolation level)تضمین دید Transactionهای هم‌زمان؛ مثل LevelSerializable
Commit/Rollbackپایان Transaction با نگه داشتن یا دور ریختن تغییرها
الگوی Rollback معوق (Defer Rollback pattern)defer tx.Rollback() بلافاصله پس از BeginTx؛ بی‌خطر پس از Commit
sql.ErrTxDoneخطای Tx که قبلاً commit یا rollback شده
نقطهٔ ذخیره (Savepoint)نقطهٔ نام‌دار داخل Transaction؛ ابزار Begin تودرتوی pgx
شکست سریالی‌سازی (Serialization failure)SQLSTATE 40001؛ Transaction باید تکرار شود
بن‌بست (Deadlock)SQLSTATE 40P01؛ چرخهٔ lock و لغو یکی از Transactionها
رفتار لغو context (Context cancellation behaviour)واکنش database/sql و driver به پایان ctx
درخواست لغو (Cancel request)پیام پروتکل PostgreSQL برای درخواست توقف دستور جاری backend
API بومی pgx v5 (pgx v5 native API)استفادهٔ مستقیم از pgx بدون database/sql
pgx.Connیک اتصال pgx؛ برای استفادهٔ هم‌زمان امن نیست
pgxpool.Poolpool امن pgx برای هم‌زمانی
pgxpool.Configتنظیم MaxConns، عمرها، health check و hookها
MaxConnsسقف ظرفیت pgxpool؛ پیش‌فرض max(4, NumCPU)
بررسی سلامت (Health check)بررسی پس‌زمینهٔ اتصال‌های idle در pgxpool با HealthCheckPeriod
AfterConnecthook در pgxpool که برای هر اتصال تازه یک‌بار اجرا می‌شود
رشتهٔ اتصال (Connection string / DSN)URL یا متن key=value با میزبان، کاربر، پایگاه و گزینه‌ها
CollectRowshelper جنریک pgx برای جمع‌آوری سطرها در slice
RowToStructByNameنگاشت سطر pgx با تطبیق نام ستون و فیلد struct
آرگومان نام‌دار (Named args)pgx.NamedArgs، placeholderهای @name را به $n بازنویسی می‌کند
دسته (Batch)pgx.Batch؛ چند دستور در یک رفت‌وبرگشت
CopyFromبارگذاری انبوه pgx از پروتکل COPY
COPYفرمان و پروتکل بارگذاری/خروجی انبوه PostgreSQL
unnestتابع PostgreSQL برای باز کردن array به سطر؛ ابزار درج انبوه
درج انبوه (Bulk insert)درج سطرهای فراوان با دستورهای کم
LISTEN/NOTIFYانتشار/اشتراک PostgreSQL میان نشست‌ها؛ تحویل هنگام commit
pgtypeبستهٔ pgx برای نگاشت نوع PostgreSQL به Go
محدودیت زمانی (Timeouts)deadline کلاینت در ctx و سقف سرور با statement_timeout و lock_timeout
statement_timeoutسقف مدت دستور در PostgreSQL با کد 57014
lock_timeoutسقف انتظار lock در PostgreSQL با کد 55P03
idle_in_transaction_session_timeoutخاتمهٔ نشست بیکار در Transaction باز
بررسی خطا (Error inspection)دسته‌بندی خطا با errors.Is/errors.As
pgconn.PgErrorنوع خطای pgx حامل SQLSTATE، پیام و constraint سرور
SQLSTATEکد خطای استاندارد پنج‌کاراکتری
PgBouncerpooler سبک اتصال PostgreSQL
اشتراک اتصال در سطح تراکنش (Transaction pooling)قرض دادن اتصال سرور فقط برای یک Transaction
max_prepared_statementsتنظیم PgBouncer 1.21+ برای رهگیری prepared statement سطح پروتکل
الگوی مخزن (Repository pattern)رابط persistence برای هر Aggregate که SQL را از دامنه پنهان می‌کند
رابط هر تجمیع (Interface per aggregate)یک interface repository برای هر ریشهٔ Aggregate، تعریف‌شده در مصرف‌کننده
DBTXinterface مشترک *sql.DB، *sql.Tx و *sql.Conn
انتشار تراکنش (Tx propagation)اشتراک یک Transaction میان repositoryها با context یا Unit of work
واحد کار (Unit of work)شیئی که تابع را با repositoryهای متصل به یک Transaction اجرا می‌کند
هم‌زمانی خوش‌بینانه (Optimistic concurrency)بررسی ستون version در UPDATE ... WHERE version = $n
صندوق خروجی (Outbox)جدول eventهایی که در Transaction همان تغییر حالت نوشته می‌شوند
sqlcمولد کد Go نوع‌دار از queryهای SQL
squirrel / goquابزار ساخت query SQL در Go
GORM / ent / bunORMهای Go؛ به‌ترتیب کامل، schema در کد و SQL-first
تغییر طرح‌واره (Migrations)تغییر نسخه‌دار schema که به‌ترتیب اعمال می‌شود
golang-migrate / goose / Atlas / ternابزارهای migration اکوسیستم Go
N+1یک query برای فهرست و یکی برای هر عضو
pgx mockpgxmock؛ mock پیاده‌کنندهٔ interfaceهای pgx
sqlmockgo-sqlmock؛ driver جعلی database/sql
driver جعلی (Fake driver)driver کوچک database/sql در تست که فراخوانی‌ها را ثبت می‌کند
تست پایگاه واقعی (Real DB test)تست repository روی PostgreSQL واقعی؛ container یا سرویس CI
testcontainers / dockertestکتابخانه‌های راه‌اندازی container پایگاه برای تست
مشاهده‌پذیری (Observability)trace، metric و log لایهٔ داده
otelsqlپوشش OpenTelemetry برای database/sql
tracer در pgx (pgx tracer)pgx.QueryTracer و همراهان روی ConnConfig.Tracer
otelpgxtracer مبتنی بر OpenTelemetry برای pgx

منابع ​

ساخته‌شده توسط Morteza Negahi