دامهای ORM: N+1، lazy loading و عملیات bulk
"When accessing Eloquent relationships as properties, the related models are "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the "N + 1" query problem." — Laravel 13.x documentation, Eloquent: Relationships, "Eager Loading"
خلاصه: ORM رابطهها را به property و نوشتن را به فراخوانی متد تبدیل میکند و هر کدام SQL را پنهان میکند؛ دامها یعنی statement هایی که نمیدانستید فرستاده میشوند، ردیفهایی که نمیدانستید بارگذاری میشوند، و قاعدههایی (event، transaction، timestamp) که یک فراخوانی bulk بیصدا نادیده میگیرد. تمرکز: N+1 و eager loading، هزینهٔ hydration، تفاوت chunk و chunkById و lazy و cursor، نوشتن bulk (insert و upsert و update)، مرز transaction، Active Record در برابر Data Mapper، raw SQL و injection، SQL بدِ تولیدشده، و تفاوت Eloquent، GORM، pgx، sqlx، sqlc، Ent، Bun و Doctrine. هدف یادگیری: بتوانید SQL ای را که یک فراخوانی ORM میفرستد بخوانید، تعداد statement و حافظهٔ یک مسیر کد را پیشبینی کنید، و برای هر عملیات ابزار درست (model، query builder یا raw SQL) را انتخاب کنید.
این صفحه مرجع کامل اشتباهاتی است که با نگاشت شیء-رابطهای (Object-Relational Mapper یا ORM) در production رخ میدهد: ناهمخوانی شیء-رابطهای (Impedance Mismatch) که ریشهٔ آنهاست، پنجرهٔ پرسشهای N+1، eager loading در همهٔ شکلهایش (with، load، loadMissing، withCount، withSum، nested eager loading، و Preload و Joins در GORM)، محافظهای lazy loading (preventLazyLoading، shouldBeStrict)، انتخاب ستون و هزینهٔ hydration، چهار راه پیمایش جدول بزرگ (chunk، chunkById، lazy، cursor)، نوشتن bulk (insert، upsert، insertOrIgnore، mass update در برابر save تکردیفی) و eventهایی که رد میکنند، transaction ضمنی، نبود identity map، دامهای caching، raw SQL و injection، SQL بد، soft delete، رابطههای polymorphic، timestamp و time zone، optimistic locking، migration های تولیدشده توسط ORM، و راه خواندن و تست آنچه ORM میفرستد. مباحث همسایه را دوباره درس نمیدهد: transaction در ACID & Transactions، anomalyها در Isolation Levels، مصالحهٔ offset و keyset در Pagination، ستون version در Optimistic vs Pessimistic Locking، خواندن plan در Query Planning، طراحی index در Indexing، cursor سمت سرور در Cursors & Streaming، اندازهٔ pool در Connection Pooling، ایمنی migration در Zero-Downtime Schema Migrations و injection در عمق در Database Security.
نقشهٔ صفحه
| اگر دنبال این هستید | به این بخش بروید |
|---|---|
| جدولی که در یک دقیقه حفظ شود | همهچیز در یک دقیقه |
| چرا ORM ها هزینه را پنهان میکنند و مصالحه چیست | چرا دامهای ORM وجود دارند |
| واژگان Fowler: Active Record، Data Mapper، Identity Map، Unit of Work، Lazy Load، Repository | واژگان از کجا آمدهاند |
| یک دام با timeline و راهحل در SQL و Go و Laravel | دامها، یکییکی |
| Eloquent، GORM، pgx/sqlx/sqlc/Ent/Bun و Doctrine/Hibernate/SQLAlchemy/Rails/Django | رفتار هر ORM |
| خواندن SQL، تنظیمات، پیامهای خطا | سازوکار |
| راهحل کامل: N+1، import، پیمایش، گزارش، تست | حل مسئلههای کلاسیک |
| کدام ابزار برای کدام عملیات | انتخاب ابزار |
| مونولیت، میکروسرویس، replica و مقیاس | در معماری |
| بازتولید N+1 و جاافتادن ردیف در chunk | آزمایشگاه |
| باورهای غلط، یادسپار و واژهها | بدفهمیها، یادسپار، واژهنامه |
همهچیز در یک دقیقه
دامها. هر ردیف در بخش دامها باز میشود.
| Pitfall | In plain words | Tiny example | The fix |
|---|---|---|---|
| N+1 / lazy loading | One query for the list, then one more per row | 25 books, $book->author in a loop = 26 queries | with('author'), Preload, a JOIN, withCount |
| Over-fetching and hydration cost | You load whole objects when the page needs two columns | Author::all() to print names | select(['id','name']), DTOs, pluck |
| Offset chunking while updating | The loop shifts the pages under itself | chunk() + update on the filtered column skips rows | chunkById, lazyById, keyset |
| Row-by-row writes | N statements, N round trips, N commits | save() in a loop of 10,000 | insert, upsert, one transaction, COPY |
| Bulk call skips behaviour | No events, no observers, no casts, no updated_at | Book::where(...)->update([...]) | Know the list; touch timestamps yourself |
| Implicit transaction | One write = one hidden transaction; a loop of writes is not atomic | 500 save() calls, crash at 300, 300 rows committed | DB::transaction, db.Transaction |
| No identity map | The same row loaded twice is two objects | Book::find(1) twice gives two instances; edits diverge | Pass the object, or use a Data Mapper ORM |
| Raw SQL concatenation | A string you built is a string an attacker can build | whereRaw("name = '$name'") | Bindings, ?, $1, whitelist identifiers |
| Bad generated SQL | The ORM is faithful, not clever | 5,000-element IN, 40-branch OR chain, whereHas on a large table | Temp table, ANY(array), join, rewrite |
| Soft deletes | "Deleted" rows still exist, still count, still collide | Unique email blocks re-signup | Partial unique index, deleted_at in indexes |
| Polymorphic relations | One column holds an id of different tables | commentable_id has no foreign key | Separate tables or accept and test the gap |
| Timestamps and time zones | Dates are strings with hidden zone rules | now() stored in app zone, read in another | Store UTC, timestamptz, one source of truth |
| ORM-generated migrations | The diff tool does not know your traffic | Rename column = drop + add | Review --pretend SQL, expand/contract |
loaderها. هر روش خواندن رابطه یا ردیف چه هزینهای دارد.
| Method | Queries | Memory | Eager loading | Safe while updating filter columns |
|---|---|---|---|---|
Lazy property access ($a->books) | 1 + N | small per step | no | n/a |
with('books') / Preload("Books") | 2 | whole result set | yes | n/a |
Joins("Author") / JOIN FETCH | 1 | whole set, repeated parent columns | yes | n/a |
get() / Find | 1 | whole result set | optional | n/a |
chunk(n) | 1 per page, OFFSET | n models | yes | no |
chunkById(n) | 1 per page, WHERE id > | n models | yes | yes |
lazy(n) / lazyById(n) | like chunk / chunkById | n models, flat iterator | yes | lazyById yes |
cursor() | 1 | 1 model, but the driver may buffer | no | depends on the driver |
نویسندههای bulk. هر کدام چه چیزی را رد میکند.
| Call | Statements | Model events | Casts, mutators | created_at / updated_at | Atomic |
|---|---|---|---|---|---|
$model->save() per row | N | fired | applied | set | each statement alone |
Model::where(...)->update([...]) | 1 | not fired | not applied | not touched | yes (one statement) |
Model::insert($rows) | 1 per batch | not fired | not applied | not set | per statement |
Model::upsert($rows, ...) | 1 per batch | not fired | not applied | updated_at set on update | per statement |
insertOrIgnore($rows) | 1 per batch | not fired | not applied | not set | per statement, hides errors |
DB::table(...)->... | 1 | no model at all | none | not set | per statement |
GORM Create(&slice) | 1 per batch | hooks run | applied | set (autoCreateTime) | wrapped in a transaction |
pgx CopyFrom | 1 COPY | none | none | none | whole load or nothing |
چرا دامهای ORM وجود دارند
دیتابیس رابطهای مجموعههایی از ردیف را نگه میدارد و به پرسشهای مجموعهای جواب میدهد. اپلیکیشن گرافهایی از شیء نگه میدارد و هر بار یک ارجاع را دنبال میکند. ORM بین این دو ترجمه میکند و هزینه و غافلگیری در همین ترجمه پنهان است. مصالحه همیشه یکی است:
| Side | You gain | You pay |
|---|---|---|
| Hide SQL behind objects (ORM) | Less code, rich model behaviour, portability, fewer typos | Statement count, memory and locks are no longer visible in the code |
| Write the SQL yourself (query builder, raw SQL, sqlc) | Exact statements, exact columns, one-pass reports | More code, hand-written mapping, you own the injection discipline |
| Load everything eagerly | Few round trips | Big result sets, repeated parent columns in joins, wasted memory |
| Load lazily | Small steps, simple code | A round trip per access, latency that grows with the data |
تصویری از زندگی روزمره. یک انبار. اگر برای هر جعبه یک پیک بفرستید، ۳۰۰ جعبه یعنی ۳۰۰ سفر. اگر یک لیست برداشت (pick list) بدهید، انبار یک پالت بار میکند و یک بار برمیگردد. lazy loading پیکی است که هر بار نام جعبهٔ بعدی را بگویید دوباره میآید؛ eager loading همان لیست برداشت است؛ bulk insert همان پالت. مدیر انبار (دیتابیس) با هر دو راحت است، اما زمان تحویل شما (latency) نه.
سه بدفهمی رایج، از همان ابتدا
- «
$book->authorخواندن یک property است، پس رایگان است.» شبیه دسترسی به حافظه است، اما بار اول یک round trip شبکهای است. - «ORM کند است.» معمولاً ORM وفادار است: دقیقاً همان statement هایی را فرستاده که کد شما خواسته، یکی در هر دور حلقه. هزینه در الگوی دسترسی است، نه در کتابخانه.
- «متدهای bulk فقط
save()سریعترند.» عملیات متفاوتیاند: هیچ model ای بارگذاری نمیشود، پس event، cast، mutator، observer و timestamp خودکار اجرا نمیشود.
ناهمخوانی شیء-رابطهای (Impedance Mismatch) تکمیلی
به زبان ساده: شیءها به هم اشاره میکنند و مجموعه نگه میدارند؛ جدولها ردیفهای تخت دارند و با کلید به هم مربوط میشوند. تبدیل این دو به هم یک مسئلهٔ ترجمه است، نه کپی.
سوءبرداشت رایج: «ORM ناهمخوانی را از بین میبرد.» فقط مدیریتش میکند؛ تفاوتها میمانند و به شکل N+1، مشکل identity، رفتار null و اصطکاک migration بیرون میزنند.
تعریف: مجموعهٔ تفاوتهای مفهومی بین گراف شیء در حافظه و schema رابطهای: هویت (ارجاع شیء در برابر primary key)، رابطهها (اشارهگر و مجموعه در برابر کلید خارجی و join)، وراثت (سلسلهمراتب کلاس در برابر جدول)، دانهبندی (یک شیء غنی در برابر چند ردیف)، پیمایش (دنبال کردن اشارهگر در برابر JOIN) و نوع داده (نوع زبان در برابر نوع ستون، NULL، time zone). Martin Fowler در bliki اش میگوید: "The object/relational mapping problem is hard. Essentially what you are doing is synchronizing between two quite different representations of data, one in the relational database, and the other in-memory." و اضافه میکند که به حق باید «مسئلهٔ نگاشت in-memory/relational» نامیده شود.
| Mismatch | Object side | Relational side | Where it bites |
|---|---|---|---|
| Identity | Two references can be the same or different objects | One primary key per row | No identity map in Eloquent: two instances of one row |
| Relationships | $author->books follows a pointer | books.author_id joined by a query | N+1 |
| Inheritance | class Admin extends User | Single table, table per class, or joined tables | Wide nullable tables, hard queries |
| Granularity | One Address value object | Several columns, or a table | Embedded vs related models |
| Navigation | Walk the graph | Ask a set question | Loops instead of joins |
| Types | DateTimeImmutable, enums | timestamptz, smallint, text | Time zones, casting, enums as strings |
| Writes | Mutate in memory, save later | Statement per change, transaction boundary | Silent partial writes |
واژگان از کجا آمدهاند
بیشتر واژههای این حوزه (Active Record، Data Mapper، Identity Map، Unit of Work، Lazy Load، Repository) از فهرست الگوهای Martin Fowler برای اپلیکیشنهای سازمانی میآیند. تعریفهای یکخطی زیر عین عبارت فهرست خود اوست:
| Pattern | Fowler's definition (verbatim) | What it means in practice |
|---|---|---|
| Active Record | "An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data." | Eloquent, Rails, Django models: the object saves itself |
| Data Mapper | "A layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself." | Doctrine, Hibernate, SQLAlchemy ORM, Ent: entities are plain, a mapper persists them |
| Identity Map | "Ensures that each object gets loaded only once by keeping every loaded object in a map." | Doctrine EntityManager, Hibernate session: the same row yields the same instance |
| Unit of Work | "Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems." | Doctrine flush(), Hibernate flush: changes are collected, then written together |
| Lazy Load | "An object that doesn't contain all of the data you need but knows how to get it." | Eloquent relation properties, Hibernate proxies |
| Repository | "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." | A class with find, add, remove that hides the query code |
خود اصطلاح «N+1» را به منبع اولیهاش ردیابی نکردهام؛ مستندات Laravel آن را نام میبرد و میشمارد و من همان واژه را به کار میبرم. دربارهٔ «impedance mismatch» هم به توصیف Fowler از مسئله ارجاع میدهم، نه به یک ابداع. مستندات Laravel 13.x هزینه را برای فهرست ۲۵ کتاب میشمارد: "one query for the original book, and 25 additional queries to retrieve the author of each book" و نشان میدهد یک with('author') یعنی "only two queries will be executed". GORM همان راهحل را مستند کرده است: "GORM allows eager loading relations in other SQL with Preload" و "Preload loads the association data in a separate query, Join Preload will loads association data using left join". کتابخانههای Go lazy loading ندارند که خاموش شود؛ پس N+1 در Go همیشه query ای است که خودتان داخل حلقه نوشتهاید.
دامها، یکییکی
همهٔ مثالها از این schema استفاده میکنند که آزمایشگاه میسازد: authors(id, name)، books(id, author_id, sku unique, title, price_cents, in_stock, published_at, created_at, updated_at, deleted_at) و comments(id, commentable_type, commentable_id, body). فایلهای snippet با نام Models.php، Lab.php، Bulk.php و Migration.php سمت Laravel را دارند؛ سمت Go در پکیجهای before، after، gorm، pgx و chunk است.
N+1 و lazy loading حیاتی
به زبان ساده: یک فهرست میخواهید، بعد برای هر آیتم فهرست یک سؤال دیگر از دیتابیس میپرسید. برای ۲۵ آیتم میشود ۲۶ سؤال به جای ۲.
سوءبرداشت رایج: «N+1 فقط با هزاران ردیف مهم است.» هر query اضافه یک round trip شبکه، یک parse و یک جستجوی plan هزینه دارد؛ ۲۵ ردیف با ۲ میلیثانیه برای هر سفر همین حالا ۵۰ میلیثانیه اضافه میکند و با ۲۰۰ ردیف در صفحه و دیتابیس شلوغ به اصلیترین latency تبدیل میشود. و این باور که «دیتابیس سریع است پس مهم نیست»: دیتابیس بیکار است و اپلیکیشن شما منتظر سفر بعدی.
تعریف: الگوی دسترسی ای که در آن کد یک query برای N ردیف والد میزند و بعد به ازای هر والد یک query برای ردیف یا مجموعهٔ مرتبط، یعنی 1 + N statement. بارگذاری تنبل (lazy loading) سازوکار آن است: رابطه در اولین خواندن property بارگذاری میشود.
App (foreach authors) PostgreSQL
1 SELECT * FROM authors -- 5 rows
2 $a1->books -> SELECT * FROM books WHERE author_id = 1
3 $a2->books -> SELECT * FROM books WHERE author_id = 2
4 $a3->books -> SELECT * FROM books WHERE author_id = 3
5 $a4->books -> SELECT * FROM books WHERE author_id = 4
6 $a5->books -> SELECT * FROM books WHERE author_id = 5
-- 6 statements, 6 round trips. With 500 authors: 501.سناریوهای واقعی: فهرست ادمین که نام مشتری هر سفارش را چاپ میکند (1 + 50)؛ قالب Blade که $author->books->count() را صدا میزند (پنهان در view)؛ resource ای در API که author و publisher را شامل میشود (1 + 2N)؛ resolver هر فیلد در GraphQL (N+1 کلاسیکی که DataLoader دستهبندیاش میکند)؛ handler ای در Go که GetAuthor(ctx, id) را در حلقه صدا میزند؛ serializer ای که رابطهای را میخواند که controller هرگز بارگذاری نکرده.
| Where | How the N+1 arises | Visible in code? |
|---|---|---|
| Eloquent | Reading a relation property that is not loaded | No: looks like a field |
| GORM | A db.Where(...).Find(...) inside a for loop; GORM has no lazy loading | Yes: a query call in a loop |
database/sql, pgx, sqlx | Same: a query call in a loop | Yes |
| Doctrine | Touching a lazy proxy or collection | No |
| Hibernate / JPA | Lazy @OneToMany or @ManyToOne(fetch=LAZY) | No |
| SQLAlchemy | Default lazy="select" | No |
| Rails ActiveRecord | Association without includes | No |
| Django | Foreign key access without select_related / prefetch_related | No |
راهحل.
-- the two statements eager loading sends
SELECT id, name FROM authors;
SELECT id, author_id, title FROM books WHERE author_id IN (1, 2, 3, 4, 5);
-- or one statement with a join (parent columns repeat on every book row)
SELECT a.id, a.name, b.id AS book_id, b.title
FROM authors a LEFT JOIN books b ON b.author_id = a.id;
-- or counting in SQL
SELECT a.id, a.name, count(b.id) AS books_count
FROM authors a LEFT JOIN books b ON b.author_id = a.id GROUP BY a.id;Go: تابع LoadBooksByAuthor یک WHERE author_id = ANY(...) میفرستد؛ کد در پکیج after است.
// Package after loads and writes books in a fixed number of statements,
// no matter how many authors or rows there are.
package after
import (
"context"
"database/sql"
"fmt"
"strconv"
"strings"
)
type Book struct {
AuthorID int64
Title string
}
// LoadBooksByAuthor fetches the books of all the given authors in one query and
// groups them in memory. The ids are formatted as a comma-separated text value and
// turned into an array by string_to_array, so the driver needs no array support.
// Only integers are formatted here, so there is nothing to escape.
func LoadBooksByAuthor(ctx context.Context, db *sql.DB, authorIDs []int64) (map[int64][]string, error) {
grouped := make(map[int64][]string, len(authorIDs))
if len(authorIDs) == 0 {
return grouped, nil
}
parts := make([]string, len(authorIDs))
for i, id := range authorIDs {
parts[i] = strconv.FormatInt(id, 10)
}
rows, err := db.QueryContext(ctx,
`SELECT author_id, title FROM books
WHERE author_id = ANY(string_to_array($1, ',')::bigint[])
ORDER BY id`,
strings.Join(parts, ","))
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var authorID int64
var title string
if err := rows.Scan(&authorID, &title); err != nil {
return nil, err
}
grouped[authorID] = append(grouped[authorID], title)
}
return grouped, rows.Err()
}
// InsertBooks writes all books in one transaction using multi-row INSERT
// statements. Postgres allows at most 65535 bind parameters per statement, and
// each row uses two, so the rows go in batches of 1000 (2000 parameters).
func InsertBooks(ctx context.Context, db *sql.DB, books []Book) (err error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() {
if err != nil {
_ = tx.Rollback()
return
}
err = tx.Commit()
}()
const batchSize = 1000
for start := 0; start < len(books); start += batchSize {
end := min(start+batchSize, len(books))
if err = insertBatch(ctx, tx, books[start:end]); err != nil {
return err
}
}
return nil
}
func insertBatch(ctx context.Context, tx *sql.Tx, books []Book) error {
var sb strings.Builder
sb.WriteString(`INSERT INTO books (author_id, title) VALUES `)
args := make([]any, 0, len(books)*2)
for i, b := range books {
if i > 0 {
sb.WriteString(", ")
}
fmt.Fprintf(&sb, "($%d, $%d)", 2*i+1, 2*i+2)
args = append(args, b.AuthorID, b.Title)
}
_, err := tx.ExecContext(ctx, sb.String(), args...)
return err
}پکیج «before» همان کار را غلط انجام میدهد: برای هر نویسنده یک query، دستی نوشته شده.
// Package before shows the habits an ORM hides, written by hand with
// database/sql: one query per parent row, and one statement per inserted row.
package before
import (
"context"
"database/sql"
)
type Book struct {
AuthorID int64
Title string
}
// AuthorTitles returns the book titles for every author.
// It runs one query for the authors and then one more per author: 1 + N round trips.
func AuthorTitles(ctx context.Context, db *sql.DB) (map[string][]string, error) {
rows, err := db.QueryContext(ctx, `SELECT id, name FROM authors ORDER BY id`)
if err != nil {
return nil, err
}
defer rows.Close()
result := make(map[string][]string)
for rows.Next() {
var id int64
var name string
if err := rows.Scan(&id, &name); err != nil {
return nil, err
}
titles, err := titlesFor(ctx, db, id) // one extra query per author
if err != nil {
return nil, err
}
result[name] = titles
}
return result, rows.Err()
}
func titlesFor(ctx context.Context, db *sql.DB, authorID int64) ([]string, error) {
rows, err := db.QueryContext(ctx, `SELECT title FROM books WHERE author_id = $1`, authorID)
if err != nil {
return nil, err
}
defer rows.Close()
var titles []string
for rows.Next() {
var title string
if err := rows.Scan(&title); err != nil {
return nil, err
}
titles = append(titles, title)
}
return titles, rows.Err()
}
// SaveBooks inserts one row per statement. Outside an explicit transaction each
// Exec commits on its own, so 10,000 rows mean 10,000 commits and round trips.
func SaveBooks(ctx context.Context, db *sql.DB, books []Book) error {
for _, b := range books {
if _, err := db.ExecContext(ctx,
`INSERT INTO books (author_id, title) VALUES ($1, $2)`, b.AuthorID, b.Title); err != nil {
return err
}
}
return nil
}نسخهٔ «before» در Eloquent همان N+1 بهعلاوهٔ عادتهایی است که پشت آن میآیند:
<?php
// Before: the habits that turn ORM code into N+1 queries, row-by-row writes,
// and chunks that skip rows.
namespace App\Http\Controllers;
use App\Models\Author;
use App\Models\Book;
final class AuthorIndexController
{
// N+1: one query for the authors, then one more per author when the loop
// reads $author->books. A Blade template written the same way,
// @foreach ($authors as $author) {{ $author->books->count() }} @endforeach
// hides the same cost.
public function index(): array
{
$rows = [];
foreach (Author::all() as $author) {
$rows[] = [
'name' => $author->name,
'books' => $author->books->count(),
];
}
return $rows;
}
}
final class BookImporter
{
// 10,000 rows mean 10,000 INSERT statements. Each save() is its own
// statement, and nothing groups them into one transaction.
public function import(array $rows): void
{
foreach ($rows as $row) {
$book = new Book();
$book->author_id = $row['author_id'];
$book->sku = $row['sku'];
$book->title = $row['title'];
$book->price_cents = $row['price_cents'];
$book->save();
}
}
// chunk() pages with OFFSET. Each update removes the row from the
// "in_stock = true" filter, so the next page skips rows that were never visited.
public function markOutOfStock(): void
{
Book::where('in_stock', true)->chunk(200, function ($books) {
$books->each->update(['in_stock' => false]);
});
}
}Laravel: with query دوم را اجرا میکند و withCount عدد را داخل SQL حساب میکند.
<?php
// After: select what the view needs, count in SQL, write in batches, and
// page by id when the rows you page over are also the rows you update.
namespace App\Http\Controllers;
use App\Models\Author;
use App\Models\Book;
final class AuthorIndexController
{
// withCount() adds a books_count column computed by one subquery, so the view
// never touches the books table. Only the columns it needs are selected.
// Include the id when you select columns, or the relation cannot be matched.
public function index(): array
{
return Author::query()
->select(['id', 'name'])
->withCount('books')
->orderBy('id')
->get()
->map(fn (Author $author) => [
'name' => $author->name,
'books' => $author->books_count,
])
->all();
}
// When the list needs the related rows themselves, eager load them in one
// extra query: with('books:id,author_id,title') instead of a loop of queries.
public function withTitles(): array
{
return Author::query()
->select(['id', 'name'])
->with('books:id,author_id,title')
->orderBy('id')
->get()
->all();
}
}
final class BookImporter
{
// upsert() sends each batch as one INSERT ... ON CONFLICT statement.
// uniqueBy names the unique index that decides "already exists".
public function import(array $rows): void
{
foreach (array_chunk($rows, 500) as $batch) {
Book::upsert(
$batch,
uniqueBy: ['sku'],
update: ['title', 'price_cents'],
);
}
}
// lazyById() pages by primary key, so rows that leave the filter after the
// update do not shift the next page.
public function markOutOfStock(): void
{
Book::where('in_stock', true)
->lazyById(200, column: 'id')
->each->update(['in_stock' => false]);
}
}Eager loading: with، load، loadMissing، withCount، withSum حیاتی
به زبان ساده: از قبل به ORM بگویید چه دادههای مرتبطی لازم دارید تا همه را در تعداد ثابتی query بیاورد.
سوءبرداشت رایج: «eager loading همیشه سریعتر است.» round trip را با حافظه و هزینهٔ ساخت و تطبیق نتیجه معاوضه میکند. eager load کردن یک میلیون والد با همهٔ رابطهها میتواند از N+1 ای که جایش آمده کندتر باشد. و: «with یک JOIN میسازد.» در Eloquent نمیسازد؛ یک query دوم با WHERE fk IN (...) میزند و نتیجه را در PHP به هم وصل میکند.
تعریف: بارگذاری پیشاپیش (eager loading) یعنی بارگذاری model های مرتبط از قبل، با یک query برای هر رابطه، به جای بارگذاری در اولین خواندن property.
| Eloquent call | When | What it sends |
|---|---|---|
Author::with('books')->get() | Before the parents are fetched | Parent query, then books WHERE author_id IN (...) |
$authors->load('books') | After you already have the models | Same second query, on the existing collection |
$author->loadMissing('books') | You are unsure if it is loaded | Loads only relations not yet present |
Author::withCount('books') | You need only a number | A correlated subquery; adds books_count |
Author::withSum('books', 'price_cents') | A sum, min, max, avg or exists | Adds books_sum_price_cents; also withMin, withMax, withAvg, withExists |
with('books:id,author_id,title') | You need only some columns | Narrow select; keep the key and foreign key |
with(['books' => fn ($q) => $q->where('in_stock', true)]) | You need a constrained relation | Extra WHERE on the second query |
Author::withWhereHas('books', fn ($q) => ...) | Filter parents by children and load the matches | EXISTS filter plus eager load |
Model::automaticallyEagerLoadRelationships() | You want the framework to batch for you | Loads the relation for all siblings on first access |
protected $with = ['author'] | A relation is always needed | Eager loads on every query; without('author') opts out |
مستندات Laravel میگوید وقتی ستونهای یک رابطه را محدود میکنید باید ستونهای id و کلید خارجی را نگه دارید، وگرنه وصل کردن فرزندها به والدها شکست میخورد. همان صفحه withSum، withMin، withMax، withAvg و withExists را همخانوادهٔ withCount مستند میکند و میگوید نتیجه در attribute ای به شکل {relation}_{function}_{column} مینشیند.
Eloquent Author::with('books:id,author_id,title')->get()
1 select * from authors
2 select id, author_id, title from books where books.author_id in (1, 2, 3, 4, 5)
3 -- PHP groups the books by author_id and sets each author's relationNested eager loading با نقطه نوشته میشود: Author::with('books.comments.user') به ازای هر سطح یک query اضافه میزند و with('books.comments:id,commentable_id,body') برگ را باریک میکند. عمق، تعداد ردیف را ضرب میکند: 100 نویسنده × 20 کتاب × 30 نظر یعنی 60,000 model نظر در حافظه. Model::automaticallyEagerLoadRelationships() (مستندات Laravel، «Automatic Eager Loading») رابطه را وقتی یکی از model های همان مجموعه آن را میخواند برای همه بارگذاری میکند و حلقهٔ تودرتوی بالا را بدون نوشتن with به یک query در هر سطح میرساند؛ باز هم همهٔ ستونها را میآورد.
GORM:
// two queries: users, then orders WHERE user_id IN (...)
db.Preload("Orders").Find(&users)
// nested and constrained
db.Preload("Orders.OrderItems.Product").Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
// one query with LEFT JOIN (belongs-to and has-one)
db.Joins("Company").Joins("Manager").Find(&users)
// every association (only one level)
db.Preload(clause.Associations).Find(&users)سه شکل Go ORM کنار هم در snippet ای به نام gorm است که با یک callback تعداد query ها را میشمارد و SQL را با ToSQL چاپ میکند:
// Command gorm reproduces an N+1 with GORM, counts the queries, and fixes it
// with Preload and Joins. It needs a PostgreSQL database with the authors and
// books tables from the lab; it exits early when DATABASE_URL is not set.
package main
import (
"fmt"
"os"
"sync/atomic"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type Author struct {
ID uint
Name string
Books []Book
}
type Book struct {
ID uint
AuthorID uint
Title string
Author Author
}
func main() {
dsn := os.Getenv("DATABASE_URL")
if dsn == "" {
fmt.Println("set DATABASE_URL, for example postgres://postgres:pg@localhost:5432/lab")
return
}
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Println("open:", err)
return
}
// A callback after every query makes the statement count measurable.
var queries atomic.Int64
err = db.Callback().Query().After("gorm:query").Register("lab:count", func(*gorm.DB) {
queries.Add(1)
})
if err != nil {
fmt.Println("callback:", err)
return
}
measure := func(name string, run func() error) {
queries.Store(0)
if err := run(); err != nil {
fmt.Println(name, "error:", err)
return
}
fmt.Printf("%-12s %d queries\n", name, queries.Load())
}
measure("n+1", func() error { return nPlusOne(db) })
measure("preload", func() error { return preload(db) })
measure("joins", func() error { return joins(db) })
// ToSQL renders the statement without running it, so the SQL can be read.
sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
return tx.Joins("Author").Find(&[]Book{})
})
fmt.Println(sql)
}
// nPlusOne is the classic mistake: one query for the authors and one per author.
func nPlusOne(db *gorm.DB) error {
var authors []Author
if err := db.Find(&authors).Error; err != nil {
return err
}
for i := range authors {
err := db.Where("author_id = ?", authors[i].ID).Find(&authors[i].Books).Error
if err != nil {
return err
}
}
return nil
}
// preload runs two queries: authors, then books WHERE author_id IN (...).
func preload(db *gorm.DB) error {
var authors []Author
return db.Preload("Books").Find(&authors).Error
}
// joins runs one query with a LEFT JOIN. It suits belongs-to and has-one
// associations; a has-many association is loaded with Preload instead.
func joins(db *gorm.DB) error {
var books []Book
return db.Joins("Author").Find(&books).Error
}سناریوهای واقعی: داشبورد مشتریها با تعداد سفارش (withCount)؛ فهرست فاکتور با آیتمها و مالیات (with تودرتو)؛ فید با نویسنده و آخرین نظر (with با قید بهعلاوهٔ Joins)؛ خروجی export که فقط id و email میخواهد.
Preload یا join؟
| Approach | Queries | Duplicates parent columns | Good for | Limit |
|---|---|---|---|---|
Separate query (with, Preload, selectinload) | 1 per relation | no | has-many, deep graphs | IN list grows with parents |
JOIN (Joins, joinedload, JOIN FETCH) | 1 | yes | belongs-to, has-one, filters on the child | has-many multiplies rows, breaks LIMIT on the parent |
Subquery count (withCount) | 1 | no | numbers only | one correlated subquery per count |
سختگیری: preventLazyLoading و shouldBeStrict مهم
به زبان ساده: برنامه را در توسعه بلند و واضح خراب کنید وقتی lazy loading میکند، تا یک with() فراموششده به جای صفحهٔ کند، یک تست قرمز باشد.
سوءبرداشت رایج: «روشن کردنش در production برنامه را امنتر میکند.» صفحههایی را که امروز کار میکنند به exception تبدیل میکند. بیرون از production روشنش کنید، یا در production فقط log کنید.
تعریف: Model::preventLazyLoading() باعث میشود lazy loading خطای Illuminate\Database\LazyLoadingViolationException بدهد. Model::handleLazyLoadingViolationUsing(fn) به جای throw، handler شما را صدا میزند. Model::shouldBeStrict() سه بررسی را با هم روشن میکند: preventLazyLoading، preventSilentlyDiscardingAttributes و preventAccessingMissingAttributes (از سورس Model.php در 13.x خواندهام؛ صفحهٔ مستندات اولی و دومی را جدا توصیف میکند و از shouldBeStrict اسمی نمیبرد).
<?php
namespace App\Providers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;
final class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// Turns on lazy-loading, silently-discarded-attribute and missing-attribute
// checks. Enabled outside production so mistakes fail in development.
Model::shouldBeStrict(! $this->app->isProduction());
}
}| Check | Throws when | Exception |
|---|---|---|
preventLazyLoading | A relation is lazy loaded | LazyLoadingViolationException |
preventSilentlyDiscardingAttributes | fill() / create() gets a key not in $fillable | MassAssignmentException |
preventAccessingMissingAttributes | You read an attribute that was not selected or does not exist | MissingAttributeException |
| Environment | Recommended setting | Why |
|---|---|---|
| Local, CI | shouldBeStrict() | N+1 becomes a red test |
| Staging | shouldBeStrict() with real data volume | Sees the shapes production sees |
| Production | preventLazyLoading() with handleLazyLoadingViolationUsing logging | Visibility without outages |
در Go چیزی برای جلوگیری وجود ندارد؛ معادلش شمارندهٔ query در تستهاست (بخش تست) و مرور کد: هر فراخوانی query داخل for.
انتخاب ستون و هزینهٔ hydration مهم
به زبان ساده: هر ردیفی که بارگذاری میکنید به شیئی با همهٔ ستونها، cast ها و رابطههایش تبدیل میشود. صفحهای که فقط یک نام لازم دارد هزینهٔ کل ردیف را میدهد.
سوءبرداشت رایج: «هزینه همان SQL است.» در جدولهای عریض هزینه اغلب در PHP یا Go است: خواندن بایتها، ساخت شیءها، اجرای cast و mutator، و حافظهای که اشغال میکنند.
تعریف: hydration یعنی تبدیل ردیفهای نتیجه به model (تخصیص حافظه، مقداردهی attribute ها، اعمال cast، نگه داشتن مقدار اصلی برای dirty checking). هزینه با ردیف × ستون × قابلیتها (cast، accessor، observer) رشد میکند.
| Read shape | Cost | Use when |
|---|---|---|
Book::all() | All columns, one model per row, dirty tracking | Rarely |
Book::select(['id','title'])->get() | Fewer bytes, still models | You need models but few columns |
DB::table('books')->get() | stdClass rows, no casts, no events | Read-only lists |
Book::pluck('title', 'id') | An array, no models | Dropdowns, id lists |
Book::toBase()->get() | Query builder rows from an Eloquent query | Keep scopes, skip hydration |
Book::query()->value('title') / exists() / count() | One scalar | Presence and counts |
GORM Select("id", "title").Find(&dtos) into a small struct | Fewer columns, no model | Read-only lists |
sqlc generated row struct | Exactly the selected columns | Typed reads |
Peak memory, 100,000 books, 12 columns (illustrative ratios, measure your own)
1 Book::all() -> hundreds of MB of PHP objects
2 Book::select(['id','title']) -> a fraction of that
3 DB::table('books')->pluck('title')-> a flat array of strings
4 cursor() / lazy() / chunkById -> constant: one page or one model at a timeسناریوهای واقعی: export CSV ای که User::all() را بارگذاری میکند و حافظه تمام میشود (Allowed memory size of 134217728 bytes exhausted)؛ APIای که فقط id و name برمیگرداند ولی 40 ستون از جمله یک blob از نوع jsonb را select میکند؛ صفحهٔ فهرستی که ستون TEXT حاوی HTML رندرشده را بارگذاری میکند. انتخاب ستون همچنین به PostgreSQL اجازه میدهد از index-only scan استفاده کند (بخش Indexing) و مقدارهای TOAST را نخواند.
-- the wide read
SELECT * FROM books WHERE author_id = 7;
-- the narrow read that an index on (author_id) INCLUDE (title) can answer
SELECT id, title FROM books WHERE author_id = 7;پیمایش جدول بزرگ: chunk، chunkById، lazy، cursor حیاتی
به زبان ساده: وقتی جدول برای یکجا بارگذاری بزرگ است آن را برشبرش میخوانید. اینکه برش بعدی را چطور انتخاب کنید تعیین میکند ردیفی را از دست میدهید یا نه.
سوءبرداشت رایج: «chunk پیشفرض امن برای بهروزرسانی دستهای است.» فقط وقتی امن است که حلقه ردیفهای منطبق با filter را عوض نکند. مستندات خود Laravel هشدار میدهد که استفاده از chunk روی ستونی که همزمان بهروز میکنید "could lead to unexpected and inconsistent results".
تعریف: chunk(n, fn) برای k = 0, n, 2n, ... اجرا میکند ORDER BY id LIMIT n OFFSET k؛ chunkById(n, fn) اجرا میکند WHERE id > last ORDER BY id LIMIT n؛ lazy(n) همان chunk است که در یک LazyCollection تخت شده؛ lazyById(n) همان chunkById تختشده؛ و cursor() یک query میزند و با generator در PHP هر بار یک model میدهد. (در سورس 13.x، chunk با forPage یعنی offset/limit صفحهبندی میکند.)
chunk(2) with an update that removes rows from the filter (WHERE in_stock = true, rows 1..6)
1 page 1: OFFSET 0 LIMIT 2 -> rows 1, 2 update -> in_stock = false
2 page 2: OFFSET 2 LIMIT 2 -> rows 5, 6 (rows 3, 4 moved to offsets 0 and 1)
3 page 3: OFFSET 4 LIMIT 2 -> (empty)
-- rows 3 and 4 were never visited, no error.
chunkById(2): WHERE id > last
1 page 1: id > 0 LIMIT 2 -> rows 1, 2 update
2 page 2: id > 2 LIMIT 2 -> rows 3, 4 update
3 page 3: id > 4 LIMIT 2 -> rows 5, 6 update
4 page 4: id > 6 LIMIT 2 -> empty, done| Method | Paging | Memory | Eager loading | Safe when updating the filter | Notes |
|---|---|---|---|---|---|
chunk | OFFSET | n models | yes | no | Offset also gets slower deep into the table |
chunkById | WHERE id > | n models | yes | yes | Needs a unique, ordered key; adds its own where, so group your own conditions in a closure |
lazy | OFFSET | n models, iterator | yes | no | chunk with a flat API |
lazyById | WHERE id > | n models, iterator | yes | yes | lazyByIdDesc for descending |
cursor | one query | 1 model | no | depends | The Laravel docs say it "cannot eager load relationships"; PDO may still buffer all rows, so it "will still eventually run out of memory" |
each | chunk | n models | yes | no | each(fn) on the builder is chunk-then-foreach |
GORM FindInBatches | keyset by primary key | n structs | Preload works | yes | Pages by primary key |
database/sql Rows | one query | 1 row | n/a | depends | Needs a transaction or cursor for stable reads; see Cursors & Streaming |
سناریوهای واقعی: تغییر in_stock = false برای کاتالوگ یک تأمینکننده (مثال بالا)؛ ایندکس دوبارهٔ سندها در موتور جستوجو؛ ارسال اعلان به هر کاربری که فاکتور باز دارد؛ حذف ردیفهای soft-delete شدهٔ قدیمیتر از یک سال.
معادل Go هر دو شکل را نشان میدهد و آزمایش دوم آزمایشگاه است:
// Package chunk contrasts offset paging with keyset paging while the loop
// changes the rows it is reading, the Go version of chunk vs chunkById.
package chunk
import (
"context"
"database/sql"
)
// OffsetSweep marks books out of stock page by page using OFFSET. Every update
// removes the row from the in_stock = true filter, so the next OFFSET skips
// rows that were never visited. It is the shape of Eloquent's chunk().
func OffsetSweep(ctx context.Context, db *sql.DB, size int) (int, error) {
visited := 0
for offset := 0; ; offset += size {
ids, err := pageByOffset(ctx, db, size, offset)
if err != nil {
return visited, err
}
if len(ids) == 0 {
return visited, nil
}
for _, id := range ids {
if _, err := db.ExecContext(ctx, `UPDATE books SET in_stock = false WHERE id = $1`, id); err != nil {
return visited, err
}
visited++
}
}
}
func pageByOffset(ctx context.Context, db *sql.DB, size, offset int) ([]int64, error) {
return scanIDs(ctx, db,
`SELECT id FROM books WHERE in_stock ORDER BY id LIMIT $1 OFFSET $2`, size, offset)
}
// KeysetSweep does the same work with WHERE id > last. The position is a key
// value, not a row count, so rows leaving the filter cannot shift the page.
// It is the shape of Eloquent's chunkById().
func KeysetSweep(ctx context.Context, db *sql.DB, size int) (int, error) {
visited := 0
var last int64
for {
ids, err := scanIDs(ctx, db,
`SELECT id FROM books WHERE in_stock AND id > $1 ORDER BY id LIMIT $2`, last, size)
if err != nil {
return visited, err
}
if len(ids) == 0 {
return visited, nil
}
for _, id := range ids {
if _, err := db.ExecContext(ctx, `UPDATE books SET in_stock = false WHERE id = $1`, id); err != nil {
return visited, err
}
visited++
}
last = ids[len(ids)-1]
}
}
func scanIDs(ctx context.Context, db *sql.DB, query string, args ...any) ([]int64, error) {
rows, err := db.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
}
return ids, rows.Err()
}-- offset page k (what chunk sends)
SELECT * FROM books WHERE in_stock = true ORDER BY id LIMIT 200 OFFSET 400;
-- keyset page (what chunkById sends); needs an index on id (the primary key is enough)
SELECT * FROM books WHERE in_stock = true AND id > 612 ORDER BY id LIMIT 200;برای مدل هزینهٔ offset در برابر keyset به Pagination: Offset vs Keyset نگاه کنید. دربارهٔ cursor() و بافر شدن ردیفها در PDO به Cursors & Streaming: در PostgreSQL نتیجهٔ pdo_pgsql بهطور پیشفرض کامل fetch میشود، پس cursor() حافظهٔ شیءهای model را کم میکند نه حافظهٔ driver را.
نوشتن bulk: insert، upsert، insertOrIgnore، mass update حیاتی
به زبان ساده: به جای statement های زیاد، ردیفهای زیاد را در یک statement بفرستید. بسیار سریعتر است و رفتار هر ردیف را که شاید به آن تکیه داشتید رد میکند.
سوءبرداشت رایج: «upsert یک save() بهتر است.» مستقیم SQL مینویسد: هیچ model ای بارگذاری نمیشود، پس event، observer، cast و mutator اجرا نمیشوند و روی ستونهای conflict یک unique index لازم دارد.
تعریف: نوشتن bulk یعنی یک statement که روی ردیفهای زیاد اثر میگذارد (INSERT ... VALUES (...), (...)، INSERT ... ON CONFLICT، UPDATE ... WHERE، COPY). mass update یعنی یک UPDATE از راه query builder؛ per-row save هر model را بارگذاری میکند، تغییر میدهد و مینویسد.
Importing 10,000 rows
Row-by-row save() Batched
1 10,000 INSERT statements 20 INSERT statements of 500 rows
2 10,000 round trips 20 round trips
3 10,000 implicit transactions (commits) 1 explicit transaction (1 commit)
4 10,000 WAL flushes (fsync each) 1 WAL flush
5 ~ tens of seconds ~ hundreds of milliseconds| Operation | Eloquent | GORM | pgx / SQL | Events skipped |
|---|---|---|---|---|
| Insert many | Book::insert($rows) | db.Create(&slice) (single statement; hooks still run) / CreateInBatches(rows, 100) | multi-row VALUES, unnest, CopyFrom | Eloquent: yes; GORM: no |
| Insert, ignore duplicates | insertOrIgnore($rows) | Clauses(clause.OnConflict{DoNothing: true}) | ON CONFLICT DO NOTHING | Eloquent: yes |
| Insert or update | Book::upsert($rows, ['sku'], ['title']) | Clauses(clause.OnConflict{UpdateAll: true}) | ON CONFLICT (sku) DO UPDATE / MySQL ON DUPLICATE KEY UPDATE | Eloquent: yes |
| Update many | Book::where(...)->update([...]) | db.Model(&Book{}).Where(...).Updates(...) | UPDATE ... WHERE | Eloquent: yes |
| Delete many | Book::where(...)->delete() | db.Where(...).Delete(&Book{}) | DELETE ... WHERE | Eloquent: yes |
| Bulk load | insertUsing, raw COPY | CopyFrom via pgx | COPY books FROM STDIN | n/a |
| Per-row | $book->save() | db.Save(&book) | UPDATE ... WHERE id | no |
insertOrIgnore احتیاط میخواهد. مستندات Laravel میگوید "will ignore errors while inserting records"، خطای کلید تکراری نادیده گرفته میشود و "other types of errors may also be ignored depending on the database engine"، و strict mode در MySQL را دور میزند. در PostgreSQL به ON CONFLICT DO NOTHING تبدیل میشود که فقط تعارض unique را نادیده میگیرد. مستندات Laravel upsert را "a single, atomic operation" توصیف میکند؛ همهٔ دیتابیسها بهجز SQL Server روی ستونهای conflict به primary یا unique index نیاز دارند و MySQL و MariaDB آرگومان را نادیده میگیرند و از کلیدهای خودشان استفاده میکنند.
سقف پارامتر. پروتکل PostgreSQL در یک statement حداکثر 65,535 bind parameter حمل میکند (شمارندهٔ 16 بیتی)، prepared statement در MySQL هم سقف 65,535 placeholder دارد (خطای 1390: "Prepared statement contains too many placeholders") و SQLITE_MAX_VARIABLE_NUMBER در SQLite از نسخهٔ 3.32 پیشفرض 32,766 است. insert چندردیفی ردیف × ستون پارامتر مصرف میکند، پس batch کنید: 1,000 ردیف سهستونه یعنی 3,000 پارامتر. unnest با آرایه (snippet ای به نام pgx) تعداد پارامتر را برابر تعداد ستونها نگه میدارد.
// Command pgx shows the no-ORM patterns: one query for many parents, a
// pgx.Batch for many statements in one round trip, a multi-row upsert, and
// COPY for bulk loads. It exits early when DATABASE_URL is not set.
package main
import (
"context"
"fmt"
"os"
"github.com/jackc/pgx/v5"
)
type Book struct {
ID int64 `db:"id"`
AuthorID int64 `db:"author_id"`
Title string `db:"title"`
}
func main() {
dsn := os.Getenv("DATABASE_URL")
if dsn == "" {
fmt.Println("set DATABASE_URL, for example postgres://postgres:pg@localhost:5432/lab")
return
}
ctx := context.Background()
conn, err := pgx.Connect(ctx, dsn)
if err != nil {
fmt.Println("connect:", err)
return
}
defer conn.Close(ctx)
books, err := BooksByAuthors(ctx, conn, []int64{1, 2, 3})
if err != nil {
fmt.Println("query:", err)
return
}
fmt.Println("books:", len(books))
}
// BooksByAuthors fetches the books of many authors in one statement. pgx
// encodes a []int64 as a PostgreSQL array, so ANY($1) needs no string tricks.
func BooksByAuthors(ctx context.Context, conn *pgx.Conn, ids []int64) ([]Book, error) {
rows, err := conn.Query(ctx,
`SELECT id, author_id, title FROM books WHERE author_id = ANY($1) ORDER BY id`, ids)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, pgx.RowToStructByName[Book])
}
// RenameMany queues many UPDATE statements and sends them in one round trip.
// Statements still run one by one on the server; only the network trips shrink.
func RenameMany(ctx context.Context, conn *pgx.Conn, titles map[int64]string) error {
batch := &pgx.Batch{}
for id, title := range titles {
batch.Queue(`UPDATE books SET title = $1 WHERE id = $2`, title, id)
}
results := conn.SendBatch(ctx, batch)
defer results.Close()
for range titles {
if _, err := results.Exec(); err != nil {
return err
}
}
return results.Close()
}
// UpsertBooks writes many rows with one statement using unnest, so the number
// of bind parameters stays at three however many rows there are.
func UpsertBooks(ctx context.Context, conn *pgx.Conn, skus []string, authorIDs []int64, titles []string) error {
_, err := conn.Exec(ctx,
`INSERT INTO books (sku, author_id, title)
SELECT * FROM unnest($1::text[], $2::bigint[], $3::text[])
ON CONFLICT (sku) DO UPDATE SET title = EXCLUDED.title`,
skus, authorIDs, titles)
return err
}
// CopyBooks loads rows through the COPY protocol, the fastest path in pgx.
// COPY has no ON CONFLICT: a duplicate key fails the whole load.
func CopyBooks(ctx context.Context, conn *pgx.Conn, rows [][]any) (int64, error) {
return conn.CopyFrom(ctx,
pgx.Identifier{"books"},
[]string{"sku", "author_id", "title"},
pgx.CopyFromRows(rows))
}<?php
// Bulk writes and what they skip: events, casts, mutators, timestamps.
namespace App\Services;
use App\Models\Book;
use Illuminate\Support\Facades\DB;
final class BulkWrites
{
/**
* Mass update: one UPDATE statement. The saving/saved/updating/updated
* model events do not fire and no model is loaded. updated_at is NOT touched
* unless you set it yourself.
*/
public function discount(int $authorId): int
{
return Book::where('author_id', $authorId)->update([
'price_cents' => DB::raw('price_cents * 9 / 10'),
'updated_at' => now(),
]);
}
/** Per-row save: N SELECT-then-UPDATE round trips, events fire, one wrapper transaction. */
public function discountEach(int $authorId): void
{
DB::transaction(function () use ($authorId) {
Book::where('author_id', $authorId)->each(function (Book $book) {
$book->price_cents = intdiv($book->price_cents * 9, 10);
$book->save();
});
});
}
/**
* insert(): one multi-row INSERT, no events, no timestamps, no casts.
* Batch to stay under the driver's bind-parameter limit (65535 for
* PostgreSQL and MySQL prepared statements).
*/
public function insertMany(array $rows): void
{
$now = now();
foreach (array_chunk($rows, 1000) as $batch) {
Book::insert(array_map(fn ($r) => $r + ['created_at' => $now, 'updated_at' => $now], $batch));
}
}
/** insertOrIgnore() swallows duplicate-key errors, and on MySQL other errors too. */
public function insertIgnoring(array $rows): int
{
return DB::table('books')->insertOrIgnore($rows);
}
/** upsert(): INSERT ... ON CONFLICT DO UPDATE (PostgreSQL) / ON DUPLICATE KEY UPDATE (MySQL). */
public function sync(array $rows): int
{
return Book::upsert($rows, uniqueBy: ['sku'], update: ['title', 'price_cents']);
}
/** A large IN list: whereIntegerInRaw inlines integers instead of binding them. */
public function find(array $ids)
{
return Book::whereIntegerInRaw('id', $ids)->get();
}
/** Raw SQL done safely: values travel as bindings, never inside the string. */
public function search(string $term): array
{
return DB::select('SELECT id, title FROM books WHERE title ILIKE ? LIMIT 20', ["%{$term}%"]);
}
/** Silent-save: keeps events off for one model, for importers that must not notify. */
public function importOne(array $attributes): Book
{
$book = new Book($attributes);
$book->saveQuietly();
return $book;
}
}mass update در برابر per-row save:
Mass update | Per-row save() | |
|---|---|---|
| Statements | 1 | 1 SELECT + N UPDATE |
| Events and observers | not fired | fired |
| Casts, mutators | not applied | applied |
updated_at | not touched | set |
Dirty tracking (isDirty, wasChanged) | no model | works |
| Lock duration | one statement, may lock many rows at once | short per row |
| Race with another writer | one atomic SET x = x * 0.9 | read-modify-write: lost update |
مستندات Laravel میگوید: "When issuing a mass update via Eloquent, the saving, saved, updating, and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update." همین برای mass delete و insert و upsert و insertOrIgnore هم صادق است. اگر یک observer، cache را باطل میکند، ردیف audit مینویسد یا index جستوجو را بهروز میکند، مسیر bulk از آن میگذرد: کار را خودتان dispatch کنید، یا وقتی رفتار مهمتر از سرعت است از راه model و در chunk (chunkById بهعلاوهٔ save) بنویسید. saveQuietly() و Model::withoutEvents(fn) برعکساند: مسیر model را اجرا میکنند ولی eventها را بیصدا میکنند.
-- one atomic statement, no race
UPDATE books SET price_cents = price_cents * 9 / 10, updated_at = now() WHERE author_id = 7;
-- upsert, PostgreSQL
INSERT INTO books (sku, author_id, title, price_cents)
VALUES ('a-1', 7, 'Dune', 900), ('a-2', 7, 'Emma', 700)
ON CONFLICT (sku) DO UPDATE SET title = EXCLUDED.title, price_cents = EXCLUDED.price_cents;transaction ضمنی و مرز transaction حیاتی
به زبان ساده: هر statement در یک transaction اجرا میشود. اگر خودتان باز نکرده باشید، دیتابیس برای هر statement یکی باز و commit میکند؛ حلقهٔ 300 تا save() یعنی 300 commit جدا.
سوءبرداشت رایج: «متد سرویس من یک واحد کار است، پس یک transaction است.» بدون DB::transaction یا db.BeginTx به تعداد statement ها transaction است و crash در میانه نیمی از کار را commit شده میگذارد.
تعریف: مرز تراکنش (transaction) جفت BEGIN و COMMIT دور statement هایی است که باید با هم موفق شوند. ORM هم ممکن است مرز خودش را بیفزاید: GORM هر create و update و delete را بهطور پیشفرض داخل transaction میبرد. مستنداتش میگوید "write (create/update/delete) operations run inside a transaction to ensure data consistency" و با SkipDefaultTransaction: true میتوانید خاموشش کنید برای "about 30%+ performance improvement". Laravel چنین نمیکند: save() بیرون از DB::transaction یک statement با autocommit است. فقط فراخوانیای که مستنداتش بگوید خودش را میپیچد، مثل deleteOrFail که مستندات میگوید در exception rollback میکند.
No explicit transaction With DB::transaction
1 INSERT book 1 -> autocommit, durable BEGIN
2 INSERT book 2 -> autocommit, durable INSERT book 1; INSERT book 2; INSERT book 3
3 process crashes process crashes -> ROLLBACK, nothing stored
4 INSERT book 3 -> never runs (or) COMMIT: all three durable
-- 2 of 3 books exist, no error shownسه پیامد برای طراحی. اتمیک بودن یک batch مرز صریح میخواهد؛ مبانی ACID در ACID & Transactions است. طول transaction: transaction ای دور حلقهای که API HTTP هم صدا میزند قفل و connection را در تمام آن مدت نگه میدارد (بخش Connection Pooling)؛ مرز را فقط دور کار دیتابیس بگذارید. side effect ها (ایمیل، queue) باید بعد از commit اجرا شوند: در Laravel با DB::afterCommit، job صف با afterCommit یا ShouldDispatchAfterCommit روی eventها؛ در Go بعد از برگشتن tx.Commit(). فراخوانیهای تودرتوی DB::transaction از savepoint استفاده میکنند؛ attempts بنبست یا خطای serialization را دوباره تلاش میکند، بخش Deadlocks.
BEGIN;
INSERT INTO books (author_id, sku, title) VALUES (1, 'x-1', 'A'), (1, 'x-2', 'B');
UPDATE authors SET books_count = books_count + 2 WHERE id = 1;
COMMIT;// Go: one boundary around related writes; GORM
err := db.Transaction(func(tx *gorm.DB) error {
if err := tx.Create(&books).Error; err != nil {
return err // rolls back
}
return tx.Model(&author).Update("books_count", gorm.Expr("books_count + ?", len(books))).Error
})DB::transaction(function () use ($rows, $authorId) {
Book::insert($rows);
Author::whereKey($authorId)->increment('books_count', count($rows));
}, attempts: 3);نبود Identity Map در Eloquent مهم
به زبان ساده: از Eloquent دوبار همان ردیف را بخواهید، دو شیء متفاوت (نبود Identity Map) میگیرید. یکی را تغییر دهید، دیگری خبردار نمیشود.
سوءبرداشت رایج: «find(1) هر بار همان شیء را برمیگرداند، مثل cache جلسه.» این قابلیت Data Mapper است (Doctrine، Hibernate). Eloquent، GORM و Rails برای هر query نمونهٔ تازه میسازند.
تعریف: identity map هر entity بارگذاریشده را در هر unit of work فقط یک بار، با کلید primary key نگه میدارد تا بارگذاری دوم همان نمونه را برگرداند. Fowler: "Ensures that each object gets loaded only once by keeping every loaded object in a map."
Eloquent Doctrine EntityManager
1 $a = Book::find(1); // SELECT $a = $em->find(Book::class, 1); // SELECT
2 $b = Book::find(1); // SELECT again $b = $em->find(Book::class, 1); // from the map
3 $a->title = 'X'; $a->save(); $a->setTitle('X');
4 $b->title $b->getTitle() // 'X': same object
-- 'old title': $b is stale $em->flush(); // one UPDATEسناریوهای واقعی: دو سرویس در یک request هر کدام کاربر را بارگذاری میکنند و فیلد متفاوتی را ویرایش میکنند و save() دوم اولی را بازنویسی میکند (با dirty tracking پیشفرض فقط attribute های تغییرکرده نوشته میشوند و معمولاً امن است؛ ذخیرهٔ کل ردیف مثل Save در GORM اینطور نیست)؛ تستی که دو نمونه را با === مقایسه میکند و میافتد؛ کدی که برای «داده تازه» model را داخل حلقه دوباره بارگذاری میکند و query ها را دوبرابر میکند. راهحلها: به جای id خود شیء را پایین بدهید؛ وقتی وضعیت فعلی دیتابیس را میخواهید $book->refresh() بزنید؛ برای نمونهٔ تازه fresh()؛ یا وقتی دامنه غنی است به ORM از نوع Data Mapper بروید.
| ORM | Identity map | Unit of Work | Dirty tracking |
|---|---|---|---|
| Eloquent | no | no (explicit save) | per model (isDirty) |
| GORM | no | no | Save writes all fields; Updates writes given fields |
| Doctrine ORM | yes (EntityManager) | yes (flush) | automatic, by snapshot comparison |
| Hibernate / JPA | yes (session) | yes (flush) | automatic |
| SQLAlchemy ORM | yes (Session) | yes | automatic |
| Rails ActiveRecord | per-request query cache only | no | per model |
| Django | no | no | save() writes all fields unless update_fields |
| Ent | no | no | explicit builders |
دامهای caching مهم
به زبان ساده: cache جلوی ORM خواندن را سریع میکند و ارائهٔ شیء کهنه یا غلط را آسان.
سوءبرداشت رایج: «Cache::remember روی یک model رایگان است.» یک عکس لحظهای را serialize میکند: نوشتنهای بعدی آن را عوض نمیکند، شیء cache شده lazy load ها را پنهان میکند (بعد از unserialize ممکن است رابطه نباشد) و cache hit از event ها و scope هایی که فکر میکردید اعمال میشوند رد میشود.
تعریف: جاهایی که cache کنار ORM خراب میشود: cache کردن model های hydrate شده به جای آرایه، باطلسازی نشدن بعد از نوشتن bulk (که event نمیفرستد، پس باطلسازی مبتنی بر event اجرا نمیشود)، cache stampede روی کلید داغ، cache کردن نتیجهٔ هر کاربر زیر کلید سراسری، و race مرحلهٔ بررسی-سپس-نوشتن در read-through cache. query cache داخل یک request (cache هر request در Rails، second-level cache در Hibernate) چیز دیگری است و در Eloquent بهطور پیشفرض نیست.
| Pitfall | Why it happens | Fix |
|---|---|---|
| Cached model carries an unloaded relation | Lazy load after unserialize runs a query or throws under strictness | Cache arrays or DTOs, not models |
| Bulk update leaves cache stale | update() fires no updated event, so the observer that clears the cache does not run | Invalidate in the same code path, or version the key |
| Stampede | Many requests miss together and all query | Cache::lock, remember with jitter, stale-while-revalidate |
| Write-then-read from a replica | The cache fills from a stale replica | Read primary after write, see Replication |
| Cache written before commit | Reader sees data that is rolled back | Write the cache in DB::afterCommit |
| Cache inside the transaction | Lost update through the cache | Delete the key after commit, do not rewrite it; see Isolation Levels |
// version the key so a bulk update invalidates without events
$version = Cache::get('books:version:'.$authorId, 1);
$titles = Cache::remember("books:{$authorId}:v{$version}", 300, fn () =>
Book::where('author_id', $authorId)->pluck('title', 'id')->all());
DB::transaction(function () use ($authorId) {
Book::where('author_id', $authorId)->update(['in_stock' => false]);
DB::afterCommit(fn () => Cache::increment('books:version:'.$authorId));
});Query builder در برابر raw SQL و SQL injection حیاتی
به زبان ساده: ORM فقط از مقدارهایی که خودش bind میکند محافظت میکند. هر چه خودتان به رشته بچسبانید، محافظتش با شماست.
سوءبرداشت رایج: «ORM دارم، پس SQL injection ندارم.» where('name', $x) مقدار $x را bind میکند؛ whereRaw("name = '$x'")، orderBy($request->sort)، DB::unprepared($sql) و selectRaw با مقدار درونیابیشده نه. مستندات Laravel میگوید query builder "uses PDO parameter binding to protect your application against SQL injection attacks"، "PDO does not support binding column names" و "Laravel cannot guarantee that any query using raw expressions is protected against SQL injection vulnerabilities".
تعریف: مقدار وقتی امن است که بهصورت پارامتر bind شده (?، $1، :name) برسد و متن SQL ثابت باشد. شناسهها (نام ستون و جدول، جهت ORDER BY، در بعضی driverها LIMIT) bind نمیشوند و باید از یک whitelist بیایند.
Request: GET /books?sort=title;DROP TABLE books--
1 Book::orderBy($request->query('sort')) -> ORDER BY "title;DROP TABLE books--" (quoted by Laravel; fails, safe)
2 Book::orderByRaw($request->query('sort')) -> ORDER BY title;DROP TABLE books-- (injection)
3 DB::select("... WHERE id = $id") -> id = 1 OR 1=1 (injection)
4 DB::select('... WHERE id = ?', [$id]) -> id = $1 bound as text '1 OR 1=1' (safe, returns nothing)| Technique | Safe? | Note |
|---|---|---|
where('col', $value) | yes | Binding |
whereRaw('lower(name) = ?', [$v]) | yes | Binding in raw |
whereRaw("lower(name) = '$v'") | no | Concatenation |
orderBy($col) with user input | no | Whitelist the column |
DB::unprepared($sql) | no | The docs: "never allow user controlled values" |
whereIntegerInRaw('id', $ids) | yes if the values are cast to int | Inlines integers on purpose to save memory |
GORM Where("name = ?", v) | yes | Binding |
GORM Where("name = '" + v + "'") | no | Concatenation |
database/sql $1 / ? | yes | Server-side or driver-side binding |
| sqlc generated functions | yes | Parameters are arguments |
جایی که raw SQL ابزار درست است: گزارش با window function، CTE بازگشتی، FOR UPDATE SKIP LOCKED، COPY، join تنظیمشده با دست. برای filter های پویا از query builder (ترکیبپذیر است)، برای رفتار یک entity از model و برای query های ثابت تحلیلی از raw SQL (یا sqlc) استفاده کنید. بحث injection در عمق، با prepared statement و نقشها، در Database Security است.
-- the dynamic part: validated column, bound value
SELECT id, title FROM books WHERE title ILIKE $1 ORDER BY created_at DESC LIMIT 20;var allowed = map[string]string{"title": "title", "created": "created_at"}
func list(ctx context.Context, db *sql.DB, term, sort string) (*sql.Rows, error) {
col, ok := allowed[sort]
if !ok {
col = "created_at"
}
// col comes from the whitelist; term travels as a parameter.
return db.QueryContext(ctx, "SELECT id, title FROM books WHERE title ILIKE $1 ORDER BY "+col+" DESC LIMIT 20", "%"+term+"%")
}$column = in_array($request->query('sort'), ['title', 'created_at'], true) ? $request->query('sort') : 'created_at';
Book::where('title', 'ilike', '%'.$request->query('q').'%')->orderBy($column, 'desc')->limit(20)->get();SQL بد تولیدشده توسط ORM: زنجیرهٔ OR، IN بزرگ، subquery همبسته مهم
به زبان ساده: ORM همان SQL ای را مینویسد که شما توصیف کردید، نه آنچه planner دوست دارد. بعضی PHP یا Go کاملاً طبیعی statement کند یا شکننده تولید میکند.
سوءبرداشت رایج: «اگر کد تمیز است SQL هم خوب است.» شکلهای زیر در کد تمیزند و در SQL گران.
تعریف: شکلهایی از query (مثل OR chain، یعنی زنجیرهٔ طولانی OR) که ORM ها آسان تولید میکنند و دیتابیسها بد از پسشان برمیآیند.
| Shape | Produced by | Problem | Fix |
|---|---|---|---|
IN with thousands of ids | whereIn('id', $ids) after a big pluck | Long parse, parameter limit (65,535), a plan per distinct list length | Join on a temp table, = ANY($1) with one array, whereIntegerInRaw, chunk the ids |
Long OR chain | A loop adding orWhere | PostgreSQL can combine with BitmapOr; MySQL may fall to a scan; plan time grows | IN, UNION ALL, a join on VALUES |
OR across columns | where('a', 1)->orWhere('b', 1) | One index cannot serve both | Two queries UNIONed, or an index per column and rely on bitmap-or |
whereHas | Nested EXISTS | Correlated subquery per parent; slow on big tables | join with distinct, or whereIn on a subquery, check the plan |
count(*) for pagination | paginate() | Counts the whole filtered set on every page | simplePaginate, cursorPaginate, cached or estimated count; see Pagination |
OFFSET deep pages | paginate(), chunk | Reads and discards offset rows | Keyset |
SELECT * | default | Wide rows, no index-only scan | Select columns |
LIKE '%x%' | where('name', 'like', "%$x%") | Cannot use a B-tree | pg_trgm GIN or full-text; see Full-Text Search |
| Function on an indexed column | whereRaw('lower(email) = ?'), whereDate('created_at', $d) | Index not used | Expression index, range predicate |
| N sorts | orderBy on a computed alias | Sort in memory | Index matching the order |
| Casting mismatch | Binding a string against an int column | Implicit cast defeats index | Cast in the application |
| Prepared-statement plan flip | PDO::ATTR_EMULATE_PREPARES off, generic plan | PostgreSQL may choose a generic plan after five executions | plan_cache_mode, see Query Planning |
-- IN with thousands of values
SELECT * FROM books WHERE id IN (1, 2, 3, /* ... 5,000 ... */ 5000);
-- one array parameter, one plan
SELECT * FROM books WHERE id = ANY($1::bigint[]);
-- the join form for huge lists
CREATE TEMP TABLE wanted (id bigint PRIMARY KEY);
-- COPY ids in, then:
SELECT b.* FROM books b JOIN wanted w ON w.id = b.id;SQL تولیدشده خواندنی است. در Eloquent: ->toRawSql(). مستندات Laravel برای همین هدف dumpRawSql و ddRawSql را دارد. پیش از پذیرفتن کد، statement را بخوانید و EXPLAIN (ANALYZE, BUFFERS) اجرا کنید؛ بخش سازوکار و Query Planning.
Pagination تکمیلی
به زبان ساده: paginate() راحت است و هر صفحه یک COUNT(*) بهعلاوهٔ پویش OFFSET هزینه دارد.
سوءبرداشت رایج: «pagination یک قابلیت UI است.» انتخاب شکل query با منحنی هزینه است؛ صفحهٔ 5,000 صد هزار ردیف را میخواند و دور میریزد.
تعریف: Laravel سه ابزار دارد: paginate (شمارهٔ صفحه، count میزند)، simplePaginate (قبلی/بعدی، بدون count) و cursorPaginate (keyset). GORM و sqlc صفحهبندی نمیکنند: LIMIT/OFFSET یا شرط keyset را خودتان مینویسید. مدل کامل هزینه، مقایسهٔ row-value و cursor مات در Pagination: Offset vs Keyset است؛ این صفحه فقط هشدار میدهد که chunk همان offset paging با callback است.
paginate(25) on 40 million rows, page 4000
1 SELECT count(*) FROM books WHERE in_stock -- full filtered scan
2 SELECT * FROM books WHERE in_stock ORDER BY id LIMIT 25 OFFSET 99975 -- reads 100,000 rows
cursorPaginate(25): WHERE (id) > (?) ORDER BY id LIMIT 26 -- reads 26 rowsSoft delete و index مهم
به زبان ساده: حذف نرم (soft delete) به جای حذف ردیف، آن را «حذفشده» علامت میزند. ردیف هنوز جا میگیرد، هنوز در هر index هست و هنوز مقدارهای unique را اشغال میکند.
سوءبرداشت رایج: «soft delete یک DELETE امن است.» هر query را عوض میکند (یک WHERE deleted_at IS NULL پنهان)، کلید خارجیها را زنده نگه میدارد، constraint یکتایی را میشکند و نیاز پاکسازی داده را برآورده نمیکند.
تعریف: SoftDeletes در Eloquent ستون deleted_at را پر میکند و یک global scope میافزاید؛ GORM برای model هایی با فیلد gorm.DeletedAt همین کار را میکند ("If your model includes a gorm.DeletedAt field (which is included in gorm.Model), it will get soft delete ability automatically!") و رکوردهای soft-delete شده هنگام query نادیده گرفته میشوند.
| Issue | Why | Fix |
|---|---|---|
| Unique collision | email unique index includes deleted rows | PostgreSQL partial unique index WHERE deleted_at IS NULL; MySQL: unique on (email, deleted_at) or a generated column |
| Slow queries | The hidden predicate is not in your index | Include deleted_at IS NULL in a partial index on hot paths |
| Table bloat | Deleted rows never leave | Purge job with chunkById + forceDelete; archive; partition by date |
| Foreign keys | A child references a soft-deleted parent | Cascade soft delete in the model, or hard delete children |
Raw queries and JOINs | Global scope applies only to model queries | Add the predicate to every raw query and to joins |
| Counts | withCount counts deleted children unless scoped | withCount(['books' => fn ($q) => ...]); the relation's scope applies |
unique validation | Rule sees deleted rows | Rule::unique(...)->withoutTrashed() |
| Privacy | Data is retained | Hard delete or anonymise on request |
-- PostgreSQL: free the email when a user is soft deleted
CREATE UNIQUE INDEX users_email_active ON users (email) WHERE deleted_at IS NULL;
-- keep hot queries on the live subset small
CREATE INDEX books_author_live ON books (author_id) WHERE deleted_at IS NULL;type Book struct {
ID uint
Title string
DeletedAt gorm.DeletedAt `gorm:"index"` // soft delete, indexed
}
// db.Delete(&book) sets deleted_at; db.Unscoped().Delete(&book) removes the row.رابطههای polymorphic و از دست رفتن کلید خارجی مهم
به زبان ساده: یک ستون (commentable_id) id ای دارد که میتواند به جدولهای مختلف تعلق داشته باشد و ستون دیگر (commentable_type) میگوید کدام. دیتابیس نمیتواند وجود id را بررسی کند.
سوءبرداشت رایج: «رابطهٔ polymorphic یک کلید خارجی معمولی با نوع است.» کلید خارجی به یک جدول اشاره میکند؛ این یکی به چند جدول، پس constraint ممکن نیست و ردیف یتیم پیدا میشود.
تعریف: ستونهای morphTo، morphMany و morphs() در Eloquent؛ polymorphic: true در Rails؛ در Doctrine با وراثت نگاشت میشود.
comments(commentable_type, commentable_id)
1 ('book', 7) -> books.id = 7
2 ('author', 7) -> authors.id = 7
3 DELETE FROM books WHERE id = 7; -- no FK: comment ('book', 7) now points at nothing
4 $comment->commentable -- null; or N+1 across two tables when listed| Problem | Effect | Fix |
|---|---|---|
| No foreign key | Orphan rows after delete | Delete in model events or a job; a periodic orphan query; or avoid polymorphism |
| Class name in the type column | Renaming a class breaks data | Relation::enforceMorphMap(['book' => Book::class]) |
| Eager loading across types | One query per type | morphWith for nested relations; accept one query per type |
| Index | (commentable_type, commentable_id) is needed | morphs() creates the composite index |
| Query for all comments of authors and books | Hard in SQL | Separate relations, or a supertype table |
جایگزینهایی که یکپارچگی را نگه میدارند: یک جدول برای هر والد (book_comments، author_comments)، یک ستون nullable برای هر والد با CHECK (num_nonnulls(book_id, author_id) = 1)، یا یک جدول supertype به نام commentables که هر دو والد به آن ارجاع میدهند. مصالحهها در Schema Design آمده است.
CREATE TABLE comments (
id bigserial PRIMARY KEY,
book_id bigint REFERENCES books(id) ON DELETE CASCADE,
author_id bigint REFERENCES authors(id) ON DELETE CASCADE,
body text NOT NULL,
CHECK (num_nonnulls(book_id, author_id) = 1)
);Timestamp و time zone مهم
به زبان ساده: created_at همان چیزی است که ساعت اپلیکیشن گفت، در هر zone ای که اپلیکیشن و دیتابیس روی آن توافق دارند، و ممکن است یکی نباشند.
سوءبرداشت رایج: «timestamp یک لحظه را نگه میدارد.» در PostgreSQL نوع timestamp یک ساعت دیواری بدون zone است؛ timestamptz یک لحظه است (داخلاً UTC). DATETIME در MySQL zone ندارد؛ TIMESTAMP به UTC تبدیل میکند و سقفش سال 2038 است.
تعریف: Eloquent در save()، touch()، create() و upsert (فقط در بهروزرسانی) مقدار created_at/updated_at را با now() در time zone اپلیکیشن (config('app.timezone')، پیشفرض UTC) میگذارد؛ insert bulk و mass update آنها را دست نمیزنند. GORM با autoCreateTime/autoUpdateTime و NowFunc مقدار CreatedAt/UpdatedAt را میگذارد.
| Pitfall | Example | Fix |
|---|---|---|
| Local time stored | App zone Asia/Tehran, a second service in UTC reads the same column | Store UTC, convert at the edge |
timestamp without time zone | PostgreSQL timestamp loses the offset | timestamptz (Laravel timestampTz) |
Bulk write leaves updated_at | update() or insert() skips timestamps | Set them in the statement ('updated_at' => now()) |
| Clock skew | Two app servers differ by seconds | Use the database's now() for ordering, or a sequence |
now() inside a transaction | PostgreSQL now() is the transaction start time | clock_timestamp() if you need wall time |
| Daylight saving | Add 24 hours vs "same wall time tomorrow" | Do date math in UTC |
whereDate('created_at', $d) | Function on the column kills the index | whereBetween('created_at', [$start, $end]) |
| Casts | 'immutable_datetime' vs datetime | Prefer immutable casts, avoid in-place ->addDay() mutation |
SHOW timezone; -- PostgreSQL session zone
SELECT now(), clock_timestamp(), current_setting('TimeZone');
ALTER TABLE books ALTER COLUMN published_at TYPE timestamptz USING published_at AT TIME ZONE 'UTC';Optimistic locking در ORM ها مهم
به زبان ساده: در قفل خوشبینانه (optimistic locking) به ردیف یک شمارهٔ نسخه اضافه کنید؛ بهروزرسانی فقط وقتی موفق میشود که نسخه هنوز همان باشد که خواندهاید.
سوءبرداشت رایج: «ORM جلوی بازنویسی همزمان را میگیرد.» Eloquent و GORM نمیگیرند مگر خودتان ستون version بیفزایید؛ save() attribute های تغییرکرده را مینویسد و آخرین نویسنده برنده میشود. سازوکار، حلقهٔ retry و زمان ترجیح FOR UPDATE در Optimistic vs Pessimistic Locking است.
| ORM | Built-in version check | How |
|---|---|---|
| Hibernate / JPA | yes | @Version; OptimisticLockException |
| Doctrine ORM | yes | #[Version] or LockMode::OPTIMISTIC; OptimisticLockException |
| Rails | yes | lock_version column; StaleObjectError |
| Django | no (third-party) | F() expressions, select_for_update |
| Eloquent | no | where('version', $v)->update([... 'version' => $v + 1]) and check affected rows |
| GORM | plugin | gorm.io/plugin/optimisticlock Version field; or manual Where("version = ?") and RowsAffected |
| Ent | no | Hand-written predicate, UpdateOne(...).Where(...) |
UPDATE books SET title = $1, version = version + 1 WHERE id = $2 AND version = $3;
-- rows affected = 0 -> someone else changed it: reload and retry or tell the user$updated = Book::whereKey($id)->where('version', $version)
->update(['title' => $title, 'version' => $version + 1]);
if ($updated === 0) { throw new ConflictHttpException('Book was changed by someone else'); }migration های تولیدشده توسط ORM حیاتی
به زبان ساده: ابزارهایی که model ها را با دیتابیس مقایسه میکنند و migration مینویسند نمیدانند جدول شما 800 گیگابایت است.
سوءبرداشت رایج: «migration خودکار امن است چون مکانیکی است.» مکانیکی است، نه آگاه از production: rename را با drop و add انجام میدهد، NOT NULL با default را روی موتورهای قدیمیتر کل جدول را بازنویسی میکند، index را بدون CONCURRENTLY میسازد و قفل ACCESS EXCLUSIVE میگیرد.
تعریف: ابزارهای diff روی schema (migrations:diff در Doctrine، makemigrations در Django، --autogenerate در Alembic، Atlas، AutoMigrate در GORM، Schema.Create در Ent، schema dump در Rails) schema مطلوب و واقعی را مقایسه میکنند و DDL تولید میکنند.
| Danger | What the diff emits | Production-safe version |
|---|---|---|
| Rename column | DROP COLUMN + ADD COLUMN (data lost) | RENAME COLUMN, or expand/contract with dual writes |
New NOT NULL column | ADD COLUMN ... NOT NULL DEFAULT | Add nullable, backfill in batches, then SET NOT NULL via a validated CHECK |
| New index | CREATE INDEX | CREATE INDEX CONCURRENTLY (PostgreSQL), online DDL (MySQL) |
| New foreign key | ADD FOREIGN KEY | NOT VALID then VALIDATE CONSTRAINT |
| Change column type | ALTER COLUMN TYPE | New column, backfill, switch, drop |
AutoMigrate at startup (GORM) | Runs DDL on every deploy, from every pod | Run migrations as a separate job; never from the web process |
| Down migrations | Not tested | Forward-only fixes |
| Foreign key without index (PostgreSQL) | Missing index on the referencing column | Add it; deletes on the parent scan the child |
عادت Laravel: php artisan migrate --pretend SQL را چاپ میکند؛ بخوانیدش. AutoMigrate در GORM هرگز ستونهای بلااستفاده را حذف نمیکند و این drift را پنهان میکند. جزئیات expand/contract، سطح قفل و backfill در Zero-Downtime Schema Migrations است.
رفتار هر ORM
Active Record در برابر Data Mapper و بحث repository مهم
به زبان ساده: در Active Record خود شیء model میداند چطور ذخیره شود. در Data Mapper شیء ساده است و شیء دیگری ذخیرهاش میکند.
سوءبرداشت رایج: «Data Mapper تمیزتر است، پس بهتر است.» کد و مفهوم بیشتری میخواهد (unit of work، identity map، ترتیب flush، entity جداشده). برای اپلیکیشنهای CRUD محور، Active Record سریعتر ساخته میشود؛ Data Mapper وقتی میارزد که مدل دامنه غنی است و نباید از دیتابیس خبر داشته باشد.
تعریف: عبارت Fowler در جدول واژگان است. Active Record: Eloquent، ActiveRecord در Rails، ORM در Django. Data Mapper: Doctrine ORM، Hibernate، SQLAlchemy ORM، Entity Framework، Ent (builder تولیدشده، struct ساده). هیچکدام همان query builder نیست که فقط SQL میسازد.
| Question | Active Record | Data Mapper |
|---|---|---|
| Where does persistence live | On the model | In a mapper / entity manager |
| Domain object knows SQL | Yes (inherits Model) | No |
| Identity map, unit of work | No | Yes |
| Testing the domain without a database | Hard | Easy |
| Boilerplate | Low | Higher |
| Surprise | Hidden queries on property access | Hidden queries on flush() and lazy proxies |
| Typical pitfall | N+1, bulk bypasses events | Flush order, stale entities after clear(), proxy initialisation |
| Fits | CRUD apps, admin tools, startups | Rich domains, long-lived systems, DDD |
بحث repository همان پرسش یک سطح بالاتر است. تعریف Fowler میگوید repository "mediates between the domain and data mapping layers using a collection-like interface". دلیل موافق: یک جا برای کد query، درزی برای تست، و رابط پایدار وقتی ORM عوض میشود. دلیل مخالف، که در جامعهٔ Laravel رایج است: با Eloquent، repository ای که Model::find را میپیچد لایهای است بیانتزاع تازه، نوعهای Eloquent را از طریق مقدار برگشتی لو میدهد و بدون اینکه برای هر use case یک متد اضافه شود نمیتواند انتخابهای with() را بیان کند. میانهٔ عملی: برای هر use case یک repository (یا query object) که دادههای ساده برمیگرداند و eager loading را داخل خودش اعلام میکند، تا view نتواند N+1 بسازد.
هر ORM و کتابخانه واقعاً چه میکند
| Product | Model | Relation loading | N+1 guard | Bulk | Notes |
|---|---|---|---|---|---|
| Eloquent (Laravel 13) | Active Record | Lazy by default; with, load, withCount | preventLazyLoading, shouldBeStrict, automaticallyEagerLoadRelationships | insert, upsert, insertOrIgnore, mass update | No identity map; chunk APIs |
| GORM | Active-Record-style over structs | No lazy loading; Preload, Joins | none: a query in a loop is the bug | Create(&slice), CreateInBatches, Clauses(OnConflict), FindInBatches | Default transaction per write; hooks; soft delete via DeletedAt |
database/sql + pgx | None | You write every query | none | pgx.Batch, CopyFrom, unnest | Full control; rows.Close() discipline |
| sqlx | Thin: struct scanning and named parameters | You write every query | none | NamedExec with a slice, sqlx.In | Select, Get, StructScan; no relations |
| sqlc | Code generation from SQL | You write the join or the IN | none; N+1 only if you call a generated function in a loop | :copyfrom, :batchexec (pgx), sqlc.slice (MySQL, SQLite) | Compile-time type checking of SQL against the schema |
| Ent | Data-Mapper-style, generated graph API | WithPosts()-style eager loading, separate queries | none, but loading is explicit | CreateBulk, OnConflict | Schema as Go code, code generation |
| Bun | Query builder + models | Relation("Author") joins for has-one and uses separate queries for has-many | none | NewInsert().Model(&slice), On("CONFLICT"), bun.In | bundebug query hook prints SQL |
| Doctrine ORM (PHP) | Data Mapper | Lazy proxies, EXTRA_LAZY, JOIN FETCH in DQL | none built in; $em->getUnitOfWork() inspectable | DQL UPDATE/DELETE, batch with flush()+clear() | Identity map, unit of work, #[Version] |
| Hibernate / JPA | Data Mapper | Lazy by default for collections; @EntityGraph, JOIN FETCH, @BatchSize | LazyInitializationException after close | JDBC batching (hibernate.jdbc.batch_size) | Second-level cache |
| SQLAlchemy | Data Mapper + Core | selectinload, joinedload, lazy="raise" | lazy="raise" | insert().values([...]), bulk_insert_mappings | Identity map in Session |
| Rails ActiveRecord | Active Record | includes, preload, eager_load | strict_loading, bullet gem | insert_all, upsert_all, update_all | lock_version optimistic locking |
| Django ORM | Active Record | select_related, prefetch_related | none built in | bulk_create, bulk_update, update() | QuerySet is lazy until iterated |
GORM، sqlx، pgx، sqlc، Ent و Bun در Go، در عمل:
// sqlc: write SQL, get typed Go. queries.sql
// -- name: BooksByAuthors :many
// SELECT id, author_id, title FROM books WHERE author_id = ANY($1::bigint[]);
// -- name: InsertBooks :copyfrom
// INSERT INTO books (sku, author_id, title) VALUES ($1, $2, $3);
//
// generated (shape):
// func (q *Queries) BooksByAuthors(ctx context.Context, ids []int64) ([]Book, error)// sqlx: scan into structs, expand IN lists
query, args, _ := sqlx.In("SELECT id, title FROM books WHERE author_id IN (?)", ids)
query = db.Rebind(query)
var books []Book
err := db.SelectContext(ctx, &books, query, args...)// Ent: explicit eager loading, one extra query per edge
authors, err := client.Author.Query().WithBooks().All(ctx)
// Bun: has-one by JOIN
err = db.NewSelect().Model(&books).Relation("Author").Scan(ctx)// Doctrine: DQL with JOIN FETCH avoids the proxy N+1
$authors = $em->createQuery('SELECT a, b FROM App\Entity\Author a JOIN a.books b')->getResult();مستندات sqlc ابزار را در یک خط توصیف میکند: "sqlc generates fully type-safe idiomatic Go code from SQL." توصیف GORM از Preload و Joins همان است که بالا آمد. قابلیتهایی که برای Ent، Bun، Doctrine، Hibernate، SQLAlchemy، Rails و Django میآورم از مستنداتشان است (صفحههای Ent و Bun و Doctrine ذخیره شده؛ بقیه از حافظه از مستندات عمومی است، پس نام دقیق متدها را در نسخهٔ خودتان بررسی کنید).
سازوکار (Mechanics)
خواندن SQL ای که ORM میفرستد حیاتی
چیزی را که نمیبینید نمیتوانید درست کنید. هر ORM راهی برای چاپ SQL دارد؛ پیش و پس از هر تغییر کارایی از آن استفاده کنید.
| Tool | What it shows | How |
|---|---|---|
Eloquent toSql() / toRawSql() | The statement, with ? or with bindings filled in | Book::where(...)->toRawSql() |
Eloquent dumpRawSql() / ddRawSql() | Same, printed in the request | Chain on the builder |
DB::listen | Every statement after it runs: $query->sql, $query->bindings, $query->time (ms), $query->toRawSql() | In a service provider |
DB::enableQueryLog() / DB::getQueryLog() | An in-memory list | Tests and tinker |
DB::pretend(fn) | The statements a closure would run, without running them | php artisan migrate --pretend |
| Laravel Telescope, Debugbar, Pulse | Per-request query list, duplicates, slow queries | Install in non-production |
GORM db.Debug() | Logs each statement with duration and rows | db.Debug().Find(&x) |
GORM db.ToSQL(fn) and DryRun: true | SQL without executing | tx.Statement.SQL.String() |
| GORM logger | logger.Default.LogMode(logger.Info), SlowThreshold | gorm.Config{Logger: ...} |
pgx tracelog / QueryTracer | Statements with arguments and timing | pgx.ConnConfig.Tracer |
database/sql db.Stats() | Pool counters | OpenConnections, WaitCount; see Connection Pooling |
PostgreSQL log_min_duration_statement | Slow statements in the server log | ALTER SYSTEM SET log_min_duration_statement = '200ms' |
pg_stat_statements | Calls, mean time and rows per normalised statement | A statement with calls in the millions and tiny mean_exec_time is an N+1 |
auto_explain | Plans of slow statements in the log | auto_explain.log_min_duration |
MySQL slow query log, performance_schema | Same | long_query_time |
EXPLAIN (ANALYZE, BUFFERS) | The plan; see Query Planning | Paste the toRawSql() output |
// AppServiceProvider::boot, non-production: flag repeated statements
$seen = [];
DB::listen(function (QueryExecuted $q) use (&$seen) {
$seen[$q->sql] = ($seen[$q->sql] ?? 0) + 1;
if ($seen[$q->sql] === 10) {
logger()->warning('possible N+1', ['sql' => $q->sql, 'sample' => $q->toRawSql()]);
}
});نشانهٔ N+1 در pg_stat_statements یک statement نرمالشده (... WHERE author_id = $1) با calls بسیار زیاد و mean_exec_time ناچیز است، کنار statement والد که بسیار کمتر صدا زده شده.
تنظیمات (Knobs) مهم
| Knob | Product | Effect |
|---|---|---|
Model::preventLazyLoading($bool) | Laravel | Throw on lazy load |
Model::shouldBeStrict($bool) | Laravel | Three checks at once |
Model::preventSilentlyDiscardingAttributes() | Laravel | Throw instead of dropping unfillable attributes |
Model::preventAccessingMissingAttributes() | Laravel | Throw on unselected attributes |
Model::automaticallyEagerLoadRelationships() | Laravel | Batch lazy loads of siblings |
Model::handleLazyLoadingViolationUsing(fn) | Laravel | Log instead of throw |
protected $with, $withCount | Laravel | Always eager load |
$fillable, $guarded, Model::unguard() | Laravel | Mass-assignment policy |
PDO::ATTR_EMULATE_PREPARES | PHP PDO | Client-side vs server-side prepare |
SkipDefaultTransaction | GORM | Remove the per-write transaction |
PrepareStmt | GORM | Cache prepared statements per connection |
DryRun, Logger, NowFunc | GORM | Debugging and clock control |
CreateBatchSize | GORM | Default batch for Create(&slice) |
SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime | database/sql | Pool limits; a loop of N queries holds one connection |
jdbc.batch_size, fetch_size | Hibernate | Statement batching, streaming |
plan_cache_mode, max_prepared_transactions, statement_timeout, idle_in_transaction_session_timeout | PostgreSQL | Plan reuse, timeouts for runaway ORM loops |
max_allowed_packet, max_prepared_stmt_count | MySQL | Limits for giant INSERTs |
پیامهای خطایی که میبینید حیاتی
| Message | Product | Meaning | Fix |
|---|---|---|---|
Attempted to lazy load [books] on model [App\Models\Author] but lazy loading is disabled. (LazyLoadingViolationException) | Laravel | preventLazyLoading caught a lazy load | Add with |
The attribute [x] either does not exist or was not retrieved for model [...] (MissingAttributeException) | Laravel | You narrowed select and read a missing column | Select it |
Add [x] to fillable property to allow mass assignment on [...] (MassAssignmentException) | Laravel | create($request->all()) with an unfillable key | $fillable |
Allowed memory size of ... bytes exhausted | PHP | all() or eager loading too much | chunkById, lazy, select columns |
SQLSTATE 23505 duplicate key value violates unique constraint / MySQL 1062 | PostgreSQL / MySQL | Unique violation; soft-deleted row counts | Partial unique index; upsert |
| SQLSTATE 40001 / 40P01 / MySQL 1213 | PostgreSQL / MySQL | Serialization failure or deadlock | Retry the whole transaction; see Deadlocks |
number of parameters must be between 0 and 65535 (pgx: extended protocol limited to 65535 parameters) | PostgreSQL / pgx | Multi-row insert too big | Batch, unnest, COPY |
MySQL 1390 Prepared statement contains too many placeholders | MySQL | Same | Batch |
WHERE conditions required (gorm.ErrMissingWhereClause) | GORM | Delete/Update with no condition | Add a condition |
record not found (gorm.ErrRecordNotFound) | GORM | First, Take, Last found nothing | Check with errors.Is |
sql: Rows are closed, pool exhaustion context deadline exceeded | database/sql | Forgot rows.Close() or a long loop holds connections | defer rows.Close(); see Connection Pooling |
LazyInitializationException | Hibernate | Touched a lazy proxy after the session closed | JOIN FETCH, DTOs |
حل مسئلههای کلاسیک
N+1 در endpoint فهرست
| Solution | How | Advantage | Cost / limit |
|---|---|---|---|
with / Preload / selectinload | Second query with IN | Simple, works for has-many | Result set in memory; big IN |
withCount / withSum | Subquery per aggregate | No child rows loaded | One subquery per aggregate |
JOIN | One statement | One round trip | Duplicates parent columns; breaks LIMIT on parent |
| DTO query (raw / sqlc) | You write the exact shape | Minimal data | More code |
preventLazyLoading in CI | Fail on lazy load | Catches regressions | Only paths that tests execute |
| DataLoader (GraphQL) | Batch per request tick | Fixes resolver N+1 | Needs a batching layer |
| Denormalised counter column | books_count maintained on write | Reads become free | Write complexity, drift |
کد: بخش N+1 و eager loading.
import فایل با 1,000,000 ردیف
| Solution | How | Advantage | Cost / limit |
|---|---|---|---|
Per-row save() | Loop | Events and validation | Hours; one commit per row |
Batched insert / upsert in one transaction | 500-1,000 rows per statement | 50 to 500 times faster | No events; validation is yours |
Staging table + INSERT ... SELECT | Load raw, transform in SQL | Set-based, restartable | Extra table |
COPY (pgx CopyFrom) | Wire protocol bulk | Fastest | No ON CONFLICT; whole load fails on one bad row |
| Queue per chunk | One job per 1,000 rows | Parallel, retryable | Idempotency required; see Idempotent Consumer |
public function import(string $path): void
{
$batch = [];
foreach ($this->rows($path) as $row) { // generator: constant memory
$batch[] = $row + ['updated_at' => now(), 'created_at' => now()];
if (count($batch) === 1000) {
Book::upsert($batch, uniqueBy: ['sku'], update: ['title', 'price_cents', 'updated_at']);
$batch = [];
}
}
if ($batch) { Book::upsert($batch, ['sku'], ['title', 'price_cents', 'updated_at']); }
}پیمایشی که همان چیزی را بهروز میکند که میخواند
در Laravel از chunkById یا lazyById، در Go از FindInBatches یا حلقهٔ keyset دستی (پکیج chunk)، یا وقتی منطق تکردیفی لازم نیست از یک UPDATE ... WHERE مجموعهای استفاده کنید. برای جدولی با صدها میلیون ردیف هر batch را محدود کنید و بین آنها commit کنید تا قفل طولانی و bloat نداشته باشید؛ بخش Working with Billion-Row Tables.
-- batch of 5,000 per statement, repeat until 0 rows
UPDATE books SET in_stock = false
WHERE id IN (SELECT id FROM books WHERE in_stock AND author_id = 7 ORDER BY id LIMIT 5000 FOR UPDATE SKIP LOCKED);query های گزارش
گزارشی که پنج جدول را join میکند و یک میلیون ردیف را aggregate میکند مسئلهٔ SQL است. آن را به صورت SQL بنویسید (selectRaw/groupBy در query builder، DB::select یا sqlc)، plan را بخوانید و ردیفهای ساده برگردانید. اگر سنگین است روی replica یا در materialized view اجرا کنید؛ بخش OLTP vs OLAP و Replication.
SELECT a.id, a.name, count(b.id) AS books, sum(b.price_cents) AS value
FROM authors a LEFT JOIN books b ON b.author_id = a.id AND b.deleted_at IS NULL
GROUP BY a.id, a.name ORDER BY value DESC NULLS LAST LIMIT 50;تست: دیتابیس واقعی یا mock
به زبان ساده: ORM ای که mock شده فقط ثابت میکند کد شما mock را صدا میزند. فقط دیتابیس واقعی SQL را ثابت میکند.
سوءبرداشت رایج: «mock کردن repository تستها را سریع و به همان اندازه خوب میکند.» mock نمیتواند N+1، join غلط، نقض unique، رفتار NULL، collation یا migration را بگیرد.
| Approach | Catches | Misses | Speed |
|---|---|---|---|
| Mocks / fakes of the ORM | Control flow | Everything about SQL | Fastest |
| SQLite in memory (Laravel default for tests) | Basic logic | PostgreSQL-specific features: ON CONFLICT, jsonb, partial indexes, timestamptz, locking | Fast |
| Real PostgreSQL / MySQL in a container (Testcontainers, Docker Compose) | SQL, constraints, migrations, plans | Production-scale data | Seconds to start |
Transaction rollback per test (RefreshDatabase, DatabaseTransactions; Go: BEGIN/ROLLBACK) | Isolation between tests | Code that commits or uses multiple connections | Fast |
| Query-count assertions | N+1 regressions | Slow single queries | Fast |
EXPLAIN in CI on key queries | Missing index regressions | Data-dependent plans | Medium |
قاعدههایی که جواب میدهند: migration ها را روی همان موتوری اجرا کنید که deploy میکنید؛ یک seed کوچک واقعگرایانه نگه دارید؛ برای endpoint های فهرست تعداد query را assert کنید؛ shouldBeStrict را در bootstrap تست روشن کنید؛ پاکسازی transaction-per-test را ترجیح دهید؛ و قابلیتهای همزمانی را روی سرور واقعی تست کنید (بخش آزمایشگاه isolation).
public function test_author_index_uses_two_queries(): void
{
Author::factory()->count(20)->hasBooks(3)->create();
DB::enableQueryLog();
$this->getJson('/authors')->assertOk();
$this->assertLessThanOrEqual(3, count(DB::getQueryLog()));
}func countingDB(t *testing.T, db *gorm.DB) *atomic.Int64 {
var n atomic.Int64
_ = db.Callback().Query().After("gorm:query").Register("test:count", func(*gorm.DB) { n.Add(1) })
return &n
}انتخاب ابزار
| Operation | Recommended tool | Extra technique | Reason |
|---|---|---|---|
| Single-entity create/update with rules | Model (save, GORM Save) | Observers, validation, transaction | Behaviour lives on the model |
| List with relations | with / Preload | Select columns, preventLazyLoading | Fixed query count |
| Counts and sums of children | withCount, withSum | Cached counter if hot | No child rows loaded |
| Filter parents by children | whereHas or JOIN | Check the plan | EXISTS vs join choice depends on data |
| Dynamic search filters | Query builder | Bindings, whitelisted columns | Composable and safe |
| Reports and analytics | Raw SQL / sqlc | EXPLAIN, replica, materialised view | The planner needs the whole shape |
| Walk a big table with updates | chunkById, lazyById, keyset | Commit per batch | No skipped rows |
| Read-only pass over a big table | lazy or cursor | select columns | Constant memory |
| Bulk import | Batched upsert in one transaction, or COPY | Staging table | Statement count |
| Bulk change needing events | chunkById + save | Queue the heavy part | Events are the reason |
| Money, stock, balances | Atomic UPDATE, FOR UPDATE, version column | Idempotency keys | Not read-modify-write; see Isolation Levels |
| Hot path in Go | pgx or sqlc | Prepared statements | Exact SQL, typed rows |
| Rich domain in PHP or Java | Data Mapper (Doctrine, Hibernate) | Repository per aggregate | Identity map and unit of work |
در معماری: از یک پردازه تا سیستم توزیعشده
مونولیت (Monolith): یک پردازه، یک دیتابیس
یک مونولیت Eloquent با strict mode روشن در CI سادهترین تنظیم درست است. هر endpoint فهرست with اش را اعلام میکند؛ یک feature test تعداد query را assert میکند؛ chunkById کارهای دستهای را انجام میدهد؛ DB::transaction دور هر use case است. مثال: فروشگاهی با orders، order_items و customers. فهرست سفارشها Order::with('customer:id,name')->withCount('items')->cursorPaginate(25) را بارگذاری میکند: دو query در هر صفحه، حافظهٔ ثابت و بدون lazy loading.
مونولیت ماژولار و چند دیتابیس
وقتی ماژولها مالک جدولهای خودشان هستند، رابطهای که از ماژول عبور کند نقض مرز است. رابطههای Eloquent بین ماژولها (مثلاً Order با belongsTo(Customer::class) از ماژول دیگر) schema ها را به هم گره میزنند و اگر جدولها در دیتابیسهای جدا باشند with غیرممکن میشود (Eloquent میتواند connection جدا برای هر model داشته باشد اما JOIN بین دیتابیسها وجود ندارد). رابطه را با یک id و فراخوانی read model عوض کنید: ماژول سفارشها از ماژول مشتریها customersByIds($ids) را یکجا میخواهد که همان eager loading دستی است. هر ماژول migration های خودش و DB::transaction خودش را دارد (مرز یک connection).
میکروسرویس (Microservices): ORM از مرز شبکه رد نمیشود
رابطه نمیتواند از مرز سرویس عبور کند: ORM نمیتواند orders (سرویس A) را با customers (سرویس B) join کند. N+1 از SQL به HTTP میرود: حلقهای که برای هر سفارش GET /customers/{id} میزند همان پنجره است، با latency دهها میلیثانیه و حالتهای خرابی. با endpoint دستهای (GET /customers?ids=1,2,3)، یک read model محلی که با eventها تغذیه میشود (بخش Outbox) یا aggregation در gateway حل کنید. هر سرویس ORM و DB::transaction خودش را دارد؛ اتمیک بودن بین سرویسها saga میخواهد (بخش Saga) چون هیچ transaction ORM ای بین سرویسها پخش نمیشود. عملیات bulk داخل سرویس هم باید eventهایی را منتشر کند که ORM دور زده: mass update هیچ event ای نمیفرستد، پس cache یا index جستوجوی پاییندست هرگز خبردار نمیشود؛ یک ردیف outbox را در همان transaction بنویسید.
Order service (Eloquent) Event consumers
1 BEGIN
2 UPDATE books SET in_stock = false WHERE author_id = 7 -- mass update: no model event
3 INSERT INTO outbox (type, payload) VALUES ('author.out_of_stock', '{"author":7}')
4 COMMIT
5 relay publishes 'author.out_of_stock' --------------> search index and cache updateداده توزیعشده: replica، cache و SQL توزیعشده
Read replica ها (Replication & Failover) خواندن بعد از نوشتن پنهان ORM را به باگ تبدیل میکنند: save() سپس redirect سپس find() ممکن است replica عقبمانده را بخواند. گزینهٔ sticky در connection در Laravel خواندن را در همان request بعد از نوشتن روی primary نگه میدارد؛ در Go با transaction یا pool صریح مسیر بدهید. cache دور ORM (بخش دامهای caching) و نوشتنهای bulk که event نمیفرستند ورودیهای کهنه به جا میگذارند. روی SQL توزیعشده (CockroachDB، Spanner، YugabyteDB) یک N+1 هزینهٔ round trip بین منطقهای دارد و transaction ممکن است با 40001 تکرار شود: ORM باید کل واحد کار را دوباره تلاش کند (بخش Distributed SQL). سطح isolation پیشفرض بین محصولات فرق دارد (CockroachDB: Serializable، PostgreSQL و Oracle: Read Committed، InnoDB: Repeatable Read) و همین تعیین میکند read-modify-write از راه ORM چه چیزی را از دست میدهد؛ بخش Isolation Levels.
مسیر مقیاسپذیری: ۱×، ۱۰×، ۱۰۰×
| Load | ORM-level concern | What to do |
|---|---|---|
| 1× (a few hundred rows per list) | N+1 is invisible | Turn on strict mode and query-count tests now, because this is when the habit is formed |
| 10× | N+1 shows in p95; paginate() counts get slow; chunk jobs take minutes | with everywhere, cursorPaginate, chunkById, indexes on foreign keys, pg_stat_statements in review |
| 100× | Hydration cost, connection pool pressure, bulk write contention, replica lag | DTO or sqlc for hot reads, batched writes with outbox, read replicas with read-your-writes routing, partition big tables, move reports to OLAP; see Storage & Data Scaling |
آزمایشگاه (Lab)
به دو terminal نیازی نیست؛ یک shell و یک psql. خروجی مورد انتظار در comment هاست.
آمادهسازی.
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
docker exec -it pg psql -U postgres -c 'CREATE DATABASE lab'
export DATABASE_URL=postgres://postgres:pg@localhost:5432/lab-- psql -U postgres -d lab
CREATE TABLE authors (id bigserial PRIMARY KEY, name text NOT NULL);
CREATE TABLE books (
id bigserial PRIMARY KEY,
author_id bigint NOT NULL REFERENCES authors(id),
sku text UNIQUE,
title text NOT NULL,
price_cents int NOT NULL DEFAULT 0,
in_stock boolean NOT NULL DEFAULT true
);
CREATE INDEX books_author_id ON books (author_id);
INSERT INTO authors (name) SELECT 'author ' || g FROM generate_series(1, 200) g;
INSERT INTO books (author_id, sku, title)
SELECT (g % 200) + 1, 'sku-' || g, 'book ' || g FROM generate_series(1, 5000) g;آزمایش 1: با GORM یک N+1 بسازید، بشمارید و درستش کنید.
1 cd docs/snippets/database/orm-pitfalls/go && go run ./gorm
2 n+1 201 queries
3 preload 2 queries
4 joins 1 queries
5 SELECT "books"."id", ... "Author"."name" AS "Author__name" FROM "books" LEFT JOIN "authors" "Author" ON ...
-- the counts are from the 200 authors above; with 20 authors the first line says 21آزمایش 2: با Eloquent یک N+1 بسازید، بشمارید و درستش کنید. model ها و migration را از snippet ها اضافه کنید (php artisan migrate)، 200 نویسنده و 5,000 کتاب بسازید و در php artisan tinker اجرا کنید:
فایلهای آزمایشگاه به ترتیب: model ها، migration و کلاس کمکی Lab.
<?php
// Models and migration used by the lab: authors have many books, books have
// many comments through a polymorphic relation, and books are soft deleted.
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
final class Author extends Model
{
use HasFactory;
protected $fillable = ['name'];
public function books(): HasMany
{
return $this->hasMany(Book::class);
}
}
final class Book extends Model
{
use HasFactory;
use SoftDeletes;
protected $fillable = ['author_id', 'sku', 'title', 'price_cents', 'in_stock'];
protected $casts = ['in_stock' => 'boolean', 'published_at' => 'immutable_datetime'];
public function author(): BelongsTo
{
return $this->belongsTo(Author::class);
}
public function comments(): MorphMany
{
return $this->morphMany(Comment::class, 'commentable');
}
}
final class Comment extends Model
{
protected $fillable = ['commentable_type', 'commentable_id', 'body'];
// commentable_id can point at books or authors, so the database cannot
// declare a foreign key for it. Register Relation::enforceMorphMap(
// ['book' => Book::class, 'author' => Author::class]) in a service provider
// so commentable_type stores short stable names instead of class names.
}<?php
// Migration for the lab. Read the SQL an ORM migration will run before you
// ship it: php artisan migrate --pretend
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('authors', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Schema::create('books', function (Blueprint $table) {
$table->id();
// foreignId()->constrained() creates the FK and, on MySQL, an index.
// PostgreSQL does NOT index the referencing column: add it yourself.
$table->foreignId('author_id')->constrained();
$table->string('sku')->unique();
$table->string('title');
$table->unsignedInteger('price_cents')->default(0);
$table->boolean('in_stock')->default(true);
$table->timestampTz('published_at')->nullable();
$table->timestamps();
$table->softDeletes();
$table->index('author_id');
// Serves the chunkById sweep: WHERE in_stock = true AND id > ? ORDER BY id.
// The unique sku index still counts soft-deleted rows; see the page.
$table->index(['in_stock', 'id']);
});
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->morphs('commentable'); // commentable_type + commentable_id + index, no FK
$table->text('body');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('comments');
Schema::dropIfExists('books');
Schema::dropIfExists('authors');
}
};<?php
// Lab helpers: count the queries a piece of code sends, produce an N+1, fix it,
// and compare chunk() with chunkById(). Run it from `php artisan tinker` or a
// console command against the lab database.
namespace App\Lab;
use App\Models\Author;
use App\Models\Book;
use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
final class Lab
{
/**
* Runs $work and returns how many SQL statements it sent.
* DB::listen fires for every statement on the default connection.
*/
public static function countQueries(Closure $work): int
{
$count = 0;
DB::listen(function (QueryExecuted $query) use (&$count) {
$count++;
// $query->toRawSql() is the statement with its bindings filled in.
// $query->time is the execution time in milliseconds.
});
$work();
return $count;
}
public static function nPlusOne(): int
{
return self::countQueries(function () {
foreach (Author::all() as $author) {
$author->books->count(); // lazy load: one query per author
}
});
}
public static function fixed(): int
{
return self::countQueries(function () {
// with() = 1 query for authors + 1 query for all their books.
foreach (Author::with('books:id,author_id,title')->get() as $author) {
$author->books->count();
}
});
}
public static function countedInSql(): int
{
return self::countQueries(function () {
// withCount() = 1 query. withSum('books', 'price_cents') works the same way.
foreach (Author::withCount('books')->get() as $author) {
$author->books_count;
}
});
}
/** Throws instead of lazy loading, so a missed with() fails in tests. */
public static function strict(): void
{
Model::preventLazyLoading();
Model::handleLazyLoadingViolationUsing(function (Model $model, string $relation) {
logger()->warning('lazy loading', ['model' => $model::class, 'relation' => $relation]);
});
}
/** The SQL Eloquent will send, without running it. */
public static function readTheSql(): string
{
return Author::query()
->withCount('books')
->whereHas('books', fn ($q) => $q->where('in_stock', true))
->toRawSql();
}
/**
* Visits every in-stock book and flips it out of stock. Returns how many
* rows the loop saw. With chunk() the answer is about half the table.
*/
public static function chunkVisited(): int
{
$seen = 0;
Book::where('in_stock', true)->chunk(100, function ($books) use (&$seen) {
foreach ($books as $book) {
$book->update(['in_stock' => false]);
$seen++;
}
});
return $seen;
}
/** Same work with chunkById(): pages by id, so every row is visited once. */
public static function chunkByIdVisited(): int
{
$seen = 0;
Book::where('in_stock', true)->chunkById(100, function ($books) use (&$seen) {
foreach ($books as $book) {
$book->update(['in_stock' => false]);
$seen++;
}
});
return $seen;
}
}1 >>> App\Lab\Lab::nPlusOne()
2 => 201
3 >>> App\Lab\Lab::fixed()
4 => 2
5 >>> App\Lab\Lab::countedInSql()
6 => 1
7 >>> App\Lab\Lab::readTheSql()
8 => "select \"authors\".*, (select count(*) from \"books\" where ...) as \"books_count\" from \"authors\" where exists (...)"آزمایش 3: chunk ردیفها را جا میاندازد و chunkById نه. با UPDATE books SET in_stock = true; بازنشانی کنید و بعد:
1 >>> App\Lab\Lab::chunkVisited()
2 => 2500 // not 5000: half the rows were skipped, no error
3 SELECT count(*) FROM books WHERE in_stock; -- 2500 rows still true
4 UPDATE books SET in_stock = true;
5 >>> App\Lab\Lab::chunkByIdVisited()
6 => 5000
7 SELECT count(*) FROM books WHERE in_stock; -- 0معادلهای Go اینها هستند: chunk.OffsetSweep(ctx, db, 100) (کمتر از 5,000 ردیف را میبیند) و chunk.KeysetSweep(ctx, db, 100) (5,000 را میبیند).
آزمایش 4: N+1 را از سمت سرور پیدا کنید.
CREATE EXTENSION IF NOT EXISTS pg_stat_statements; -- needs shared_preload_libraries
SELECT calls, round(mean_exec_time::numeric, 3) AS ms, query
FROM pg_stat_statements WHERE query ILIKE '%FROM books WHERE author_id%' ORDER BY calls DESC LIMIT 3;
-- one statement with calls = 200 per page view and ms near 0.05: that is the N+1آزمایش 5: bulk در برابر تکردیفی. در tinker، زمان foreach (range(1, 5000) as $i) Book::create([...]) را با Book::insert($rows) در batch های 1,000 تایی مقایسه کنید: در یک container محلی ثانیهها در برابر دهها میلیثانیه انتظار داشته باشید.
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| «N+1 فقط در مقیاس بالا مهم است.» | از همان نسخهٔ اول یک مالیات latency متناسب با ردیفهای هر صفحه است؛ فقط در مقیاس دیده میشود |
| «Eager loading یعنی JOIN.» | در Eloquent و Preload در GORM یک query دوم با IN است؛ شکل join همان Joins است |
| «Eager loading همیشه سریعتر است.» | round trip را با حافظه معاوضه میکند؛ فقط آنچه رندر میکنید بارگذاری کنید و ستونها را انتخاب کنید |
«chunk برای بهروزرسانی دستهای امن است.» | وقتی update شرط filter را عوض کند ردیفها را جا میاندازد؛ از chunkById استفاده کنید |
«cursor() میتواند eager load کند و حافظه نمیخورد.» | eager load نمیکند و driver PDO ممکن است همهٔ ردیفها را بافر کند |
«upsert یک save() بهتر است.» | event، cast، mutator و observer را رد میکند و unique index میخواهد |
| «mass update، eventهای model را فرا میخواند.» | mass update و insert و upsert و delete هیچ event ای نمیفرستند |
| «متد من یک transaction است.» | فقط اگر DB::transaction یا BeginTx نوشته باشید؛ وگرنه هر statement جدا commit میشود |
«find(1) دو بار همان شیء را میدهد.» | در Eloquent، GORM و Rails نه؛ فقط ORM های Data Mapper identity map دارند |
| «ORM جلوی SQL injection را میگیرد.» | فقط برای مقدارهای bind شده؛ رشتههای raw و شناسهها با خودتان است |
| «soft delete فقط یک delete است.» | ردیف در جدولها، index ها، constraint های unique و backup ها میماند |
| «رابطهٔ polymorphic کلید خارجی دارد.» | نمیتواند؛ ردیف یتیم ممکن است |
«timestamp یک لحظه را نگه میدارد.» | timestamptz نگه میدارد؛ timestamp یک ساعت دیواری است |
| «mock کردن ORM، query را تست میکند.» | فراخوانی را تست میکند؛ فقط دیتابیس واقعی SQL را تست میکند |
| «migration های خودکار امناند.» | مکانیکیاند: rename داده را حذف میکند، index قفل میگیرد، NOT NULL بازنویسی میکند |
| «repository باعث میشود ORM قابل تعویض باشد.» | نوعهای Eloquent معمولاً بیرون میزنند؛ فایدهاش یک درز و جای کد query است |
یادسپار (Cheat sheet)
| موضوع | چه چیزی را به خاطر بسپارید |
|---|---|
| N+1 | 1 query برای والدها + 1 به ازای هر والد؛ با with، Preload، join یا withCount درست میشود |
| loaderهای Eloquent | with، load، loadMissing، withCount، withSum، with('a.b') تودرتو، with('a:id,name') ستونهای کلید را نگه میدارد |
| سختگیری | Model::shouldBeStrict(! app()->isProduction())؛ preventLazyLoading، handleLazyLoadingViolationUsing |
| GORM | Preload، Joins (belongs-to/has-one)، Preload(clause.Associations)، Debug()، ToSQL، FindInBatches، CreateInBatches، transaction پیشفرض برای هر نوشتن |
| Hydration | ستون را انتخاب کنید، pluck، toBase، DTO؛ model حافظه و CPU میخورد |
| جدول بزرگ | chunkById / lazyById وقتی بهروز میکنید؛ lazy فقطخواندنی؛ cursor eager load نمیکند؛ offset جا میاندازد |
| Bulk | insert (بدون event)، upsert (unique index)، insertOrIgnore (خطا را پنهان میکند)، mass update (بدون event و بدون updated_at) |
| سقفها | 65,535 bind parameter (PostgreSQL، MySQL)؛ batch های 500 تا 1,000 ردیفی؛ unnest یا COPY |
| Transaction | پیشفرض autocommit؛ هر use case را در DB::transaction بپیچید؛ side effect بعد از commit |
| Identity | Eloquent و GORM: identity map ندارند؛ Doctrine، Hibernate، SQLAlchemy: دارند |
| Raw SQL | مقدار را bind کنید؛ شناسه را whitelist کنید؛ whereIntegerInRaw برای فهرست عدد صحیح |
| SQL بد | IN بزرگ ← ANY(array)/join؛ زنجیرهٔ OR ← IN/UNION؛ whereHas ← plan را ببینید؛ LIKE '%x%' ← trigram |
| Soft delete | partial unique index با WHERE deleted_at IS NULL؛ job پاکسازی |
| Polymorphic | بدون FK؛ enforceMorphMap؛ جدولهای جدا با CHECK را بسنجید |
| زمان | timestamptz، ذخیره به UTC، نوشتن bulk timestamp نمیگذارد |
| Optimistic lock | ستون version و WHERE version = ?؛ تعداد ردیفهای اثرگرفته را بررسی کنید |
| خواندن SQL | toRawSql، DB::listen، Debug()، pg_stat_statements، EXPLAIN (ANALYZE, BUFFERS) |
| تست | موتور واقعی، assert تعداد query، strict mode در bootstrap تست |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — یک view در Blade برای 50 نویسنده $author->books->count() چاپ میکند. چند query اجرا میشود و دو راهحل بگویید. حیاتی
پاسخ
پاسخ: 51 تا: یکی برای نویسندهها و یکی برای هر نویسنده. با Author::withCount('books') (و خواندن books_count) یا with('books') درست میشود؛ مسیر کد را با Model::preventLazyLoading() نگهبانی کنید. بخش N+1 و eager loading.
۲ — آیا Author::with('books') یک JOIN اجرا میکند؟ حیاتی
پاسخ
پاسخ: نه. query دوم ... FROM books WHERE author_id IN (...) را میزند و ردیفها را در PHP گروه میکند. join همان Joins در GORM یا JOIN FETCH در Doctrine است. بخش Preload یا join.
۳ — رابطه را با with('books:title') باریک میکنید و وصل کردن شکست میخورد. چرا؟ مهم
پاسخ
پاسخ: رابطه برای تطبیق کتاب با نویسنده به ستون کلید و کلید خارجی نیاز دارد؛ id و author_id را هم select کنید: with('books:id,author_id,title').
۴ — jobی با Book::where('in_stock', true)->chunk(200, ...) مقدار in_stock = false را میگذارد و تمام میشود در حالی که ردیفهایی هنوز true اند. چه شد و چه چیزی را عوض میکنید؟ مهم
پاسخ
پاسخ: chunk با OFFSET صفحهبندی میکند؛ هر update ردیفها را از filter بیرون برد و offset های بعدی ردیفهای ندیده را جا انداختند. از chunkById یا lazyById استفاده کنید که با WHERE id > last صفحه میزنند. بخش chunking.
۵ — Book::where(...)->update([...]) نسبت به بارگذاری و ذخیرهٔ هر model چه چیزی را رد میکند؟ مهم
پاسخ
پاسخ: eventهای model (saving، saved، updating، updated) و observer ها، cast و mutator، و updated_at خودکار؛ یک statement اتمیک SQL است. بخش نوشتن bulk.
۶ — چرا insertOrIgnore میتواند خطرناک باشد؟ مهم
پاسخ
پاسخ: خطای کلید تکراری و بسته به موتور خطاهای دیگر را نادیده میگیرد؛ مستندات Laravel یادآور میشود strict mode در MySQL را دور میزند. ردیف ردشده از ردیف درجشده تشخیص داده نمیشود. upsert را ترجیح دهید یا تعداد اثرگرفته را بررسی کنید.
۷ — import 10,000 ردیفی در ردیف 6,000 crash میکند. با حلقهٔ save() و بدون transaction چند ردیف ذخیره شده و چطور همهیاهیچاش میکنید؟ حیاتی
پاسخ
پاسخ: حدود 6,000: هر save() autocommit میشود. batch را در DB::transaction (یا BeginTx در Go) بپیچید تا crash همه چیز را برگرداند، و با upsert یا INSERT چندردیفی batch کنید. بخش transaction.
۸ — چرا Book::find(1) دوبار در Eloquent دو شیء میدهد و در Doctrine یکی؟ تکمیلی
پاسخ
پاسخ: EntityManager در Doctrine Identity Map و Unit of Work را پیاده میکند؛ Eloquent Active Record است و هیچکدام را ندارد. بخش identity map و Active Record در برابر Data Mapper.
۹ — کدامها injection پذیرند: where('name', $x)، whereRaw("name = '$x'")، orderBy($col) با ورودی کاربر، whereRaw('name = ?', [$x])؟ حیاتی
پاسخ
پاسخ: دومی و سومی. مقدارِ bind شده با ? امن است؛ concatenation نه، و نام ستون bind نمیشود پس whitelist کنید. بخش raw SQL.
۱۰ — چرا unique index روی users.email ثبتنام دوبارهٔ حساب soft-delete شده را میشکند و در PostgreSQL چه درستش میکند؟ مهم
پاسخ
پاسخ: index هنوز ردیف soft-delete شده را دارد. با partial unique index با WHERE deleted_at IS NULL عوضش کنید. بخش soft delete.
۱۱ — N+1 را از سمت دیتابیس چطور تشخیص میدهید؟ حیاتی
پاسخ
پاسخ: pg_stat_statements یک statement نرمالشده (... WHERE author_id = $1) با calls بسیار بالا و میانگین زمان ناچیز نشان میدهد. در اپلیکیشن: DB::listen، db.Debug() یا assert تعداد query. بخش خواندن SQL.
۱۲ — چرا mock کردن ORM جایگزین بدی برای دیتابیس واقعی در تست است؟ مهم
پاسخ
پاسخ: mock فراخوانیها را بررسی میکند نه SQL را: N+1، نقض constraint، رفتار NULL و collation، قابلیتهای خاص موتور و migration ها را نمیبیند. موتور واقعی و assert تعداد query به کار ببرید. بخش تست.
واژهنامه
| اصطلاح | معنی |
|---|---|
| ORM | نگاشت شیء-رابطهای (Object-Relational Mapper): کتابخانهای که جدول و ردیف را به کلاس و شیء نگاشت میکند |
| Impedance mismatch | ناهمخوانی مفهومی گراف شیء با schema رابطهای (هویت، رابطه، وراثت، نوع) |
| N+1 | یک query برای N والد بهعلاوهٔ N query برای رابطههایشان |
| Lazy loading | بارگذاری تنبل (Lazy loading): آوردن رابطه در اولین خواندن property |
| Eager loading | بارگذاری پیشاپیش (Eager loading): آوردن رابطهها از قبل در تعداد ثابتی query |
with / load / loadMissing | Eloquent: eager load پیش از query / روی model های موجود / فقط اگر بارگذاری نشده باشد |
withCount / withSum | Eloquent: افزودن attribute تجمیعی با subquery (books_count، books_sum_price_cents) |
| Nested eager loading | with('a.b.c'): یک query برای هر سطح |
preventLazyLoading | محافظ Eloquent که در lazy load خطای LazyLoadingViolationException میدهد |
shouldBeStrict | کلید Eloquent برای preventLazyLoading، preventSilentlyDiscardingAttributes و preventAccessingMissingAttributes |
automaticallyEagerLoadRelationships | گزینهٔ Eloquent که lazy load های model های همخانواده را دستهای میکند |
| Hydration | تبدیل ردیفهای نتیجه به شیء model |
| DTO | شیء انتقال داده (Data Transfer Object): struct ساده و کوچک برای یک خواندن |
chunk | پیمایش Eloquent با LIMIT/OFFSET؛ اگر حلقه filter را عوض کند ردیف جا میاندازد |
chunkById / lazyById | پیمایش با WHERE id > last؛ هنگام بهروزرسانی امن است |
lazy | chunk که در یک LazyCollection تخت شده |
cursor | یک query و هر بار یک model با generator؛ eager load نمیکند |
| Keyset paging | WHERE key > last ORDER BY key LIMIT n؛ موقعیت با مقدار، نه با شمارش |
insert | insert چندردیفی Eloquent؛ بدون event و بدون timestamp |
upsert | درج یا بهروزرسانی در یک statement؛ unique index روی ستونهای کلید میخواهد |
insertOrIgnore | درجی که خطای تکراری (و شاید خطاهای دیگر) را نادیده میگیرد |
| Mass update | Model::where(...)->update(...): یک UPDATE بدون eventهای model |
| Model events | saving، saved، creating، updating و مانند آن که عملیات model میفرستد |
| Observer | کلاسی که به eventهای model گوش میدهد |
saveQuietly / withoutEvents | ذخیره یا اجرا بدون فرستادن eventهای model |
| Implicit transaction | transaction ضمنی: آنچه دیتابیس یا ORM دور یک statement یا نوشتن باز میکند |
DB::transaction | مرز transaction صریح Laravel با attempts برای تلاش دوباره |
SkipDefaultTransaction | تنظیم GORM که transaction هر نوشتن را برمیدارد |
| Identity Map | برای هر ردیف در هر جلسه فقط یک شیء نگه میدارد |
| Unit of Work | تغییرها را جمع میکند و در flush() مینویسد |
| Active Record | خود شیء model ذخیره میشود (Eloquent، Rails، Django) |
| Data Mapper | mapper جدا شیءهای ساده را ذخیره میکند (Doctrine، Hibernate، SQLAlchemy) |
| Repository | رابط مجموعهمانند روی لایهٔ نگاشت |
| Query builder | API روان که SQL میسازد بیآنکه رفتار دامنه را hydrate کند |
| Raw SQL | SQL ای که خودتان مینویسید؛ مقدار را bind و شناسه را whitelist کنید |
| SQL injection | تبدیل شدن ورودی نامعتبر به متن SQL |
whereIntegerInRaw | Eloquent: فهرست عدد صحیح را به جای bind مستقیم در SQL میگذارد |
ANY(array) | شرط PostgreSQL که یک پارامتر آرایه میگیرد |
| Soft delete | علامت زدن deleted_at به جای حذف ردیف |
| Partial index | indexی با WHERE؛ برای محدود کردن یکتایی به ردیفهای زنده |
| Polymorphic relation | رابطهای که id بیگانهاش ممکن است به چند جدول اشاره کند، بدون FK |
enforceMorphMap | Eloquent: به جای نام کلاس، نام کوتاه را در ستون نوع morph ذخیره میکند |
timestamptz | نوع timestamp در PostgreSQL که یک لحظه را نگه میدارد |
| Optimistic locking | قفل خوشبینانه: ستون version که در WHERE بهروزرسانی بررسی میشود |
AutoMigrate | همگامسازی schema در GORM؛ ابزار migration امن برای production نیست |
toRawSql | Eloquent: SQL با bindingهای جایگزینشده |
DB::listen | hook ای در Eloquent که برای هر statement اجراشده صدا زده میشود |
Debug / ToSQL / DryRun | راههای GORM برای دیدن SQL یا اجرا نکردن آن |
Preload / Joins | GORM: eager loading با query جدا / بارگذاری با LEFT JOIN |
pgx | driver و جعبهابزار PostgreSQL برای Go؛ CopyFrom، Batch، CollectRows |
sqlx | افزونههای Go روی database/sql: scan به struct، پارامتر نامدار، In |
sqlc | تولید Go با نوعهای امن از روی SQL |
| Ent | فریمورک entity در Go با API گراف تولیدشده و edge های eager-loading |
| Bun | ORM مبتنی بر SQL برای Go روی database/sql |
| Doctrine | ORM از نوع Data Mapper در PHP با identity map، unit of work و DQL |
pg_stat_statements | افزونهٔ PostgreSQL برای شمارش و زمان هر statement |
| Testcontainers | کتابخانهای که container دیتابیس واقعی را برای تست بالا میآورد |
منابع
- Laravel 13.x, Eloquent: Relationships: Eager Loading, Preventing Lazy Loading, Automatic Eager Loading
- Laravel 13.x, Eloquent: Strictness, Chunking Results, Cursors, Mass Updates, Upserts, Muting Events
- Laravel 13.x: Query Builder, Database (
DB::listen) - Laravel 13.x source:
Eloquent/Model.php,Concerns/BuildsQueries.php - GORM: Preloading, Transactions, Create, Hooks, Delete
- Martin Fowler, Patterns of Enterprise Application Architecture catalogue: Active Record, Data Mapper, Identity Map, Unit of Work, Lazy Load, Repository; bliki: OrmHate
- sqlc: Documentation; Ent: Eager Loading; Bun: Relations; Doctrine ORM: Working with Objects
- pgx v5:
pgx; Go:database/sql - PostgreSQL: 9.26.3 ANY/SOME (array)