ماندگاری داده در طراحی: Repository، نگاشت و مرزها (Data Persistence in Design)
"Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." — Rob Mee و Edward Hieatt، Repository، کاتالوگ Patterns of Enterprise Application Architecture، martinfowler.com
خلاصه (Summary): ماندگاری (Persistence) اول یک مسئلهٔ طراحی است و بعد مسئلهٔ دیتابیس: باید تصمیم بگیرید کدام objectها از ذخیرهسازی خبر دارند، مالک تراکنش کیست، چه مقدار از گراف objectها بارگذاری شود و کدام سرویس به کدام جدول دست میزند. ابزارها (Eloquent، GORM، sqlc، Doctrine) فقط همین تصمیمها را اجرا میکنند. تمرکز (Focus): بیخبری از ذخیرهسازی (Persistence ignorance)، ناهمخوانی شیءگرا-رابطهای (Impedance mismatch)، Active Record در برابر Data Mapper و Table و Row Data Gateway، Repository و aggregate، Specification و Query Object، Unit of Work، Identity Map، بارگذاری تنبل و مشتاق (Lazy و Eager)، DTO و read model، نگاشت value object و ستون JSON، قفل خوشبینانه (Optimistic locking)، حذف نرم (Soft delete) و ممیزی (Auditing)، تست، و مرزهای ماندگاری از مونولیت تا میکروسرویس، در Go و Laravel. هدف یادگیری (Learning goal): برای یک فیچر انتخاب کنید SQL کجا بنشیند، مرز تراکنش کجاست، آیا repository ارزشش را دارد یا نه، و همان aggregate به نام Order چه شکلی دارد: بهصورت مدل Eloquent، بهصورت object ساده پشت repository، و بهصورت ردیف در دیتابیس یک سرویس دیگر.
این صفحه «نگاه طراحی» به ماندگاری است. موتورها، طراحی schema، migration و تلههای کارایی ORM را درس نمیدهد؛ آنها مال مسیر Databases هستند و هر جا لازم باشد لینک شدهاند: ORM Pitfalls (N+1، lazy loading، عملیات انبوه)، Schema Design (فرمهای نرمال، کلیدها، JSONB)، Zero-Downtime Schema Migrations، ACID & Transactions، Isolation Levels، Optimistic vs Pessimistic Locking و Connection Pooling. فصلهای همسایهٔ طراحی: Dependency Inversion توضیح میدهد چرا interface مربوط به repository کنار domain مینشیند، Single Responsibility میگوید چرا god model بوی بد طراحی است، Designing for Concurrency و Distribution of Components میگویند وقتی ماندگاری از مرز thread و شبکه رد میشود چه میشود. جزئیات تاکتیکی DDD در Repositories، Aggregates & Factories، Entities & Value Objects و Anemic vs Rich Models است؛ مالکیت داده در سطح سرویس در Data Ownership in Microservices.
نقشهٔ صفحه
| دنبال چه میگردید | بروید به |
|---|---|
| کل فصل در چند جدول | همهچیز در یک دقیقه |
| چرا ماندگاری طراحی لازم دارد | چرا وجود دارد |
| Fowler، Evans، بحث ORM | از کجا آمده |
| objectهای دامنهای که از ذخیرهسازی خبر ندارند | Persistence ignorance |
| چرا object و جدول جور نمیشوند | Impedance mismatch |
| Eloquent و مدلهای سبک Rails | Active Record |
| Doctrine، mapperهای دستی، adapterهای sqlc | Data Mapper، Gatewayها |
| رابط شبیه collection برای aggregateها | Repository، مرز Aggregate |
| متدهای جستجو، Specification، Query Object | پرسوجو از طریق repository |
| «Eloquent را داخل repository بپیچم؟» | Repository روی Eloquent |
| چه کسی تراکنش را باز و بسته میکند | Unit of Work |
| یک ردیف، یک object؛ cache جلوی آن | Identity Map و caching |
| الان بارگذاری کنم یا بعداً | Lazy در برابر Eager |
| صفحه و گزارش بدون aggregate | DTO و read model |
| پول، enum، آدرس، ستون JSON | نگاشت value object |
| Lost update در لایهٔ object | Optimistic locking |
deleted_at و «چه کسی چه چیزی را عوض کرد» | Soft delete و ممیزی |
| fake، دیتابیس واقعی، تست با rollback | تست ماندگاری |
| مقایسهٔ Eloquent، GORM، sqlc، ent، Doctrine | نگاه هر زبان و فریمورک |
| dirty checking، SQL تولیدشده، knobها | سازوکار |
کد: Order در Go و Laravel | Go، Laravel |
| مسئلههای کلاسیک با راهحل | حل مسئلههای کلاسیک |
| کدام الگو برای کدام وضعیت | انتخاب |
| از مونولیت تا میکروسرویس، strangler، همگامسازی داده | در معماری |
| اجرای تستها و خراب کردن عمدی | آزمایشگاه |
| باورهای غلط، چکیده، خودآزمایی، واژهنامه | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
واژگان. هر سطر در بخش مفهومها باز میشود.
| اصطلاح | به زبان ساده | مثال کوچک | بدون آن چه خراب میشود |
|---|---|---|---|
| Persistence ignorance | object دامنه نمیداند کجا و چطور ذخیره میشود | Order::place() نه SQL دارد نه save() | قواعد بدون دیتابیس تست نمیشوند |
| Impedance mismatch | object و جدول داده را متفاوت مدل میکنند | Order لیست خط دارد؛ جدول برای هر خط یک ردیف تخت دارد | کد نگاشت بزرگ میشود و به دامنه نشت میکند |
| Active Record | یک object یک ردیف را میپیچد و خودش را ذخیره میکند | $order->save() در Eloquent | قاعده، SQL و فریمورک در یک class |
| Data Mapper | لایهای جدا داده را بین object و جدول جابهجا میکند | EntityManager در Doctrine، mapper دستی | اول کار کد بیشتر، class بیشتر |
| Table / Row Data Gateway | یک object SQL یک جدول یا یک ردیف را نگه میدارد | OrderTable::find($id) | SQL تکراری در همهجا |
| Repository | نمای شبیه collection روی ذخیرهسازی یک aggregate | orders.Get(ctx, id) | کد پرسوجو در سراسر برنامه پخش میشود |
| Aggregate | خوشهای از objectها که یکجا ذخیره و قفل میشوند | Order و ردیفهای OrderLine | invariant نیمهذخیره، قفلهای بزرگ |
| Specification / Query Object | بیان قابلاستفادهٔ مجدد از «کدام objectها» | OverdueOrders | انفجار متدهای finder |
| Unit of Work | تغییرها را دنبال و یکجا commit میکند | یک DB::transaction برای هر use case | نوشتن ناقص، commitهای ریز |
| Identity Map | در یک تراکنش کسبوکاری هر ردیف یک object | دو بار find(7) همان نمونه را برمیگرداند | دو کپی ویرایش میشوند و یکی بیصدا گم میشود |
| Lazy / Eager loading | دادههای مرتبط در اولین استفاده یا از قبل بارگذاری میشوند | $order->lines در برابر with('lines') | N+1 یا join غولآسا |
| DTO / read model | شکل فقطداده برای یک صفحه یا پاسخ | OrderSummary | برای نمایش لیست aggregate بارگذاری میشود |
| Optimistic lock | شمارهٔ نسخه ویرایش همزمان را تشخیص میدهد | UPDATE ... WHERE version = ? | lost update بدون هیچ خطا |
| Soft delete | بهجای حذف، ردیف را علامت میزنیم | deleted_at | ردیفهای شبح در queryها |
| Database per service | هر سرویس جدولهای خودش را دارد و کسی دیگر نمیخواند | دیتابیس orders در برابر billing | schema مشترکی که کسی جرئت تغییرش را ندارد |
چهار راه برای گذاشتن object کنار جدول (کاتالوگ Fowler؛ جزئیات در Active Record):
| الگو | چه کسی SQL میداند | قاعدهٔ کسبوکار کجاست | ابزار معمول | وقتی بهترین است |
|---|---|---|---|---|
| Active Record | خود object دامنه | همان class که SQL دارد | Eloquent، Rails Active Record | قاعدهها سادهاند و جدول و object شبیهاند |
| Data Mapper | یک mapper جدا | class دامنهٔ خالص | Doctrine، Hibernate، mapper دستی | دامنهٔ غنی، schema و مدل متفاوت |
| Table Data Gateway | یک gateway برای هر جدول | جای دیگر (transaction script) | کلاسهای OrderTable، struct با نام Queries در sqlc | بیشتر query، کم قاعده |
| Row Data Gateway | یک object برای هر ردیف | جای دیگر | کلاسهای ردیف تولیدشده | ردیفها بهصورت object تایپدار بدون قاعده |
هر ایده در ابزارهای شما کجاست.
| سطح | Go | Laravel |
|---|---|---|
| نگاشت ردیف | rows.Scan، structهای sqlc، مدلهای GORM | مدلهای Eloquent، ردیفهای stdClass از query builder |
| Repository | interface در package دامنه، adapter کنار driver | interface در namespace دامنه، adapter مبتنی بر Eloquent در Infrastructure |
| Unit of Work | db.BeginTx با closure؛ gorm.DB.Transaction | DB::transaction(fn) |
| Identity Map | داخلی نیست؛ اگر خواستید map بهازای هر request | داخلی نیست (Doctrine دارد، Eloquent ندارد) |
| Lazy loading | نادر؛ خودتان Preload یا query دوم میزنید | پیشفرض برای relationها؛ Model::preventLazyLoading() |
| نگاشت مقدار | sql.Scanner و driver.Valuer | cast، CastsAttributes، enum cast |
| Soft delete | gorm.DeletedAt در GORM؛ یا deleted_at IS NULL دستی | trait به نام SoftDeletes |
| Optimistic lock | WHERE version = $n و RowsAffected | where('version', $n)->update(...) تعداد ردیفهای تغییرکرده را برمیگرداند |
چرا وجود دارد
object کسبوکار در حافظه زندگی میکند، با reference به هم وصل است و قاعده دارد. ذخیرهسازی روی دیسک است، با کلید به هم وصل است و ردیف دارد. باید چیزی ترجمه کند و این ترجمه هزینه دارد: Fowler در مقالهٔ ۲۰۱۲ دربارهٔ ORM میگوید مسئلهٔ نگاشت شیء/رابطهای "is hard" است چون دارید بین "two quite different representations of data" همگامسازی میکنید، با تغییر از هر دو طرف و چند نفر که همزمان ویرایش میکنند. طراحی تعیین میکند این ترجمه کجا بنشیند و چقدر از بقیهٔ کد اجازه دارد آن را ببیند.
| ماندگاری پخششده در کد | ماندگاری پشت یک مرز |
|---|---|
| کمترین class، سریعترین فیچر اول | class و نام بیشتر، یک لایهٔ نگاشت |
| هر لایه هر جدول را query میکند | فقط repository و read model به جدولها دست میزنند |
| قاعده فقط با دیتابیس تست میشود | قاعده با object ساده تست میشود |
| تغییر schema به controller، job و view میخورد | تغییر schema فقط یک adapter را لمس میکند |
| تراکنش هر جا کسی یادش بود باز میشود | یک use case، یک تراکنش |
| خطر: god model، N+1، جدول مشترک | خطر: تشریفات، repositoryِ توخالی، لایهٔ زودهنگام |
نیمهٔ چپ Active Record است: use case مستقیم یک مدل را صدا میزند که فیلد، قاعده و save() را با هم دارد و خودش SQL اجرا میکند. نیمهٔ راست Data Mapper با repository است: use case از repository یک Order خالص میگیرد و فقط mapper با دیتابیس حرف میزند. هیچکدام «درست مطلق» نیست؛ بخشهای بعد میگویند کدام کی برنده است.
تمثیلی که در کل صفحه تکرار میکنیم: میز امانت کتابخانه. میتوانید خودتان بین قفسهها بگردید و کتاب را بردارید (Active Record: object ردیف خودش را میآورد و سر جایش میگذارد) یا از کتابدار بخواهید «کتاب دربارهٔ فلان» (Repository: به زبان کتاب حرف میزنید، نه کد قفسه). کتابهای مرجع که از ساختمان بیرون نمیروند مثل aggregate هستند، نسخههای امانتگرفتهشده که با یک برگه ثبت میشوند مثل Unit of Work، و فهرست ماهانهٔ امانتها که مدیر میخواند مثل read model. کتابخانهٔ دوم که فهرست خودش را دارد یک سرویس دیگر است: از او میپرسید، وارد قفسههایش نمیشوید.
سه بدفهمی رایج، همین ابتدا
- «Repository یعنی پوششی دور ORM.» repository یک collection رو به دامنه است: متدهایی با نام زبان کسبوکار که aggregate برمیگردانند. اگر هر متد Eloquent را یکبهیک بپیچید یک لایه اضافه کردهاید و چیزی کم نکردهاید (ببینید Repository روی Eloquent).
- «Active Record ضدالگوست.» الگویی است با قیمت مشخص. برای یک فیچر CRUD با قاعدهٔ کم، ارزانترین انتخاب درست است؛ قیمتش وقتی پیدا میشود که قاعدهها زیاد شوند و تستها دیتابیس بخواهند.
- «اگر دیتابیس را پشت interface قایم کنم راحت دیتابیس عوض میکنم.» adapter را عوض میکنید، اما تراکنش، قفل، index، پشتیبانی JSON و معنای consistency نشت میکنند. هدف صادقانه قابلیت تست و یک نقطهٔ تغییر است، نه عوضکردن رایگان دیتابیس.
از کجا آمده
Fowler و همکارانش، کاتالوگ PoEAA. کتاب Patterns of Enterprise Application Architecture واژگانی را داد که این فصل استفاده میکند. ما خلاصهٔ یکپاراگرافی هر مدخل را در martinfowler.com خواندیم (همه با تاریخ ۵ مارس ۲۰۰۳ در سایت)، نه فصلهای کتاب را؛ پس فقط از همان مدخلها نقل میکنیم. 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." 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." Table Data Gateway: "An object that acts as a gateway to a database table. One instance handles all the rows in the table." Row Data Gateway: "An object that acts as a gateway to a single record in a data source. There is one instance per row." 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." Identity Map: "Ensures that each object gets loaded only once by keeping every loaded object in a map." Lazy Load: "An object that doesn't contain all of the data you need but knows how to get it." Query Object: "An object that represents a database query." Repository (نوشتهٔ Hieatt و Mee) همان نقلقول ابتدای صفحه است و Optimistic Offline Lock نوشتهٔ David Rice است.
"With Data Mapper the in-memory objects needn't know even that there's a database present; they need no SQL interface code, and certainly no knowledge of the database schema." — Martin Fowler، Data Mapper، کاتالوگ PoEAA
این جمله تعریف چیزی است که بعدها persistence ignorance نامیده شد. خود این عبارت اصطلاح جامعهٔ برنامهنویسان است و ما تعریف اولیهای برای نقل پیدا نکردیم؛ پس در این صفحه دقیقاً یعنی همین جمله.
Evans، ۲۰۰۳ (خلاصهشده در DDD Reference سال ۲۰۱۵). Eric Evans aggregate و repository را در یک داستان گذاشت: مرز aggregate تراکنش و توزیع را "govern" میکند و repository راه دسترسی به آنهاست.
"For each type of aggregate that needs global access, create a service that can provide the illusion of an in-memory collection of all objects of that aggregate's root type." — Eric Evans، Domain-Driven Design Reference (2015)، Repositories
"Provide repositories only for aggregate roots that actually need direct access." — Eric Evans، Domain-Driven Design Reference (2015)، Repositories
Evans شکستی را هم نام میبرد که repository جلویش را میگیرد: queryهای بیقید "instantiate a few specific objects from the interior of an aggregate, blindsiding the aggregate root" و در نتیجه "entities and value objects become mere data containers."
Evans و Fowler، مقالهٔ Specifications. این مقاله "the statement of how to match a candidate" را از "the candidate object that it is matched against" جدا میکند و سه روش پیادهسازی میدهد: hard-coded، parameterized و composite.
Fowler، «OrmHate»، ۲۰۱۲. دفاع صادقانه از ORM: مسئلهٔ نگاشت سخت است، "you can't just rely on transactions"، و جایگزینها یا "solve the problem differently (and better), or avoid the problem" هستند و هر دو "significant flaws" دارند. بهترین متن واحد برای فهمیدن چرایی این فصل.
Ambler و impedance mismatch. مقالهٔ نگاشت Scott Ambler در یک خط میگوید: "Classes implement both behavior and data whereas relational database tables just implement data." مقالهٔ Wikipedia دربارهٔ این ناهمخوانی منبع ثانویه برای فهرستهای بلندتر تفاوتهاست.
ابزارها. حرف خود Laravel متواضعانه است: "Eloquent, an object-relational mapper (ORM)" که در آن "each database table has a corresponding 'Model'". نامگذاری آن به Active Record طبقهبندی خود ما بر پایهٔ تعریف Fowler است (مستندات 13.x این اصطلاح را به کار نمیبرند). Doctrine هم entity، EntityManager، Unit of Work و Identity Map را مستند کرده؛ نامگذاری آن به Data Mapper نیز طبقهبندی ماست. فرهنگ Go راه سومی رفت: SQL بنویس، کد تایپدار تولید کن. sqlc میگوید "generates fully type-safe idiomatic Go code from SQL".
مفهومها، یکییکی
هر بلوک همین ترتیب را دارد: به زبان ساده، بدفهمی معمول، تعریف دقیق، timeline، سناریوی واقعی، چه کسی این را فراهم میکند، و راهحل در SQL و Go و Laravel.
بیخبری از ذخیرهسازی (Persistence ignorance) حیاتی
به زبان ساده: objectهایی که قاعدهٔ کسبوکار را نگه میدارند، دیتابیس، ORM و فریمورک را import نمیکنند. فقط دادهاند و رفتار.
بدفهمی رایج: «بیخبری یعنی مدل دامنه نباید هیچ شباهتی به جدولها داشته باشد.» نه. یعنی نوع دامنه کد ذخیرهسازی ندارد؛ شکلها میتوانند نزدیک باشند. محک این است که class چه چیزی import میکند، نه شبیه چه چیزی است.
تعریف: object دامنه وقتی persistence-ignorant است که بتوان آن را بدون driver دیتابیس، ORM و فریمورک در مسیر import کامپایل، ساخت و در تست اجرا کرد. نگرانیهای ذخیرهسازی (نام جدول، نوع ستون، save()، relation بهشکل query builder) در adapter مینشینند.
Test an overtime rule (Go) Test an overtime rule (Active Record, Laravel)
1 o, _ := domain.NewOrder("o1", "c1", "USD") $order = Order::factory()->create(); -- INSERT
2 o.AddLine("sku", 2, 500) $order->lines()->create([...]); -- INSERT
3 err := o.Place() $order->place(); -- SELECT count, UPDATE
4 -- no I/O, microseconds -- needs a database, milliseconds, RefreshDatabaseسناریوی واقعی: سفارشی که بدون خط ثبت نمیشود؛ وامی که از سقف نمیگذرد؛ رزروی که نباید همپوشانی داشته باشد؛ کیف پولی که هرگز منفی نمیشود. هر کدام قاعدهای است که ارزش هزار بار تست دارد، و این را فقط وقتی انجام میدهید که هر تست چند میکروثانیه باشد.
| کجا | هزینهٔ این بیخبری | چه میخرد |
|---|---|---|
| Go | سازندهٔ Rehydrate و interface برای repository | تست دامنه با go test بدون driver |
| Laravel | یک class ساده PHP کنار مدل Eloquent، بهعلاوهٔ نگاشت | unit test با PHPUnit\Framework\TestCase بدون بالا آوردن app |
| هر دو | کد نگاشت، دو نمایش از داده | یک نقطه برای تغییر ذخیرهسازی |
// Domain package imports: context, errors, fmt. Nothing else.
o, _ := domain.NewOrder("o-1", "c-1", "USD")
_ = o.AddLine("sku-1", 2, 500)
err := o.Place() // pure rule check// Domain class: no `use Illuminate\...` line at all.
$order = new Order('o-1', 'c-1', 'USD');
$order->addLine('sku-1', 2, 500);
$order->place();راه درست: برای هر bounded context جدا تصمیم بگیرید. ماژولی که فقط میخواند چیزی از این لازم ندارد؛ موتور قیمتگذاری با چهل قاعده همهٔ آن را میخواهد. با قاعدهٔ Dependency Inversion ترکیبش کنید: interface مربوط به repository مال دامنه است و adapter به آن وابسته میشود.
ناهمخوانی شیءگرا-رابطهای (Impedance mismatch) حیاتی
به زبان ساده: object و جدول دو شکل متفاوت از یک واقعیتاند؛ پس هر ORM، mapper و query دستی یک مترجم است و مترجمها چیزی گم یا کج میکنند.
بدفهمی رایج: «ناهمخوانی مشکل شیءگراییِ است؛ در زبان تابعی ORM لازم نمیشد.» Fowler عکسش را میگوید: "there is really nothing to do with objects here"؛ این یک مسئلهٔ نگاشت درونحافظه/رابطهای برای هر ساختار درونحافظه است.
تعریف: مجموعهای از تفاوتهای ساختاری و معنایی بین مدل object در حافظه و schema رابطهای. پنج تفاوتی که در طراحی مهماند:
| تفاوت | Object | جدول | چه خراب میشود | نگاشت رایج | Go / Laravel |
|---|---|---|---|---|---|
| هویت (Identity) | دو reference یکیاند (==) یا برابر از نظر مقدار | هویت همان primary key است؛ دو ردیف با مقدار برابر دو ردیفاند | دو کپی از یک ردیف با ویرایشهای واگرا | Identity Map، برابری کلید، value object بدون هویت | Go ids را مقایسه میکند؛ Doctrine Identity Map دارد؛ Eloquent برای هر query نمونهٔ تازه میدهد |
| وراثت (Inheritance) | زیرکلاس، چندریختی | وراثت ندارد | کدام class در کدام جدول است | Single Table Inheritance، Class Table Inheritance، Concrete Table Inheritance | نه Eloquent نه GORM وراثت class را نگاشت نمیکنند (polymorphic relationهای Eloquent دربارهٔ associationاند نه زیرکلاس)؛ ترکیب و ستون type را ترجیح دهید |
| انجمنها (Associations) | فیلد reference، collection، دوطرفه | کلید خارجی، یکجهته، جدول واسط | چرخه، مالکیت نامشخص | Foreign Key Mapping، Association Table Mapping | hasMany/belongsToMany در Eloquent؛ tag در GORM؛ sqlc join را به خودتان میسپارد |
| ریزدانگی (Granularity) | classهای کوچک زیاد (Money، Address) | چند جدول پهن | یک object چند ستون، یا چند object یک ستون | Embedded Value، Serialized LOB (JSON) | cast، Scanner/Valuer، ستون JSON |
| پیمایش (Navigation) | reference را یک گام یک گام دنبال میکنید | مجموعهٔ ردیفها را یکجا join میکنید | N+1: برای هر گام یک query | Eager loading، query صریح، read model | with()، Preload، join در sqlc |
| رفتار (Behaviour) | متد | فقط داده | getTotalTax() به ستون نگاشت میشود | رفتار در object، ورودیها ذخیره شوند | در دامنه محاسبه کنید، حقیقتها را ذخیره کنید |
| نوع و null | نوع غنی، enum | نوع ستون، NULL | تبدیل بیصدا | نوع سفارشی | Valuer و enum cast |
کاتالوگ Fowler نگاشتهای وراثت را نام میبرد: Single Table Inheritance "Represents an inheritance hierarchy of classes as a single table that has columns for all the fields of the various classes"؛ Class Table Inheritance یک جدول برای هر class؛ Concrete Table Inheritance یک جدول برای هر class غیرانتزاعی. Embedded Value و Serialized LOB ریزدانگی را حل میکنند؛ Foreign Key Mapping و Association Table Mapping انجمنها را. فقط خلاصهٔ کاتالوگ را خواندیم.
Navigation: print 3 orders with their lines
1 SELECT * FROM orders WHERE customer_id = 'c1' LIMIT 3; -- 1 query
2 SELECT * FROM order_lines WHERE order_id = 'o1'; -- lazy load, order 1
3 SELECT * FROM order_lines WHERE order_id = 'o2'; -- lazy load, order 2
4 SELECT * FROM order_lines WHERE order_id = 'o3'; -- lazy load, order 3 => 1 + N
5 SELECT * FROM order_lines WHERE order_id IN ('o1','o2','o3'); -- eager load: 2 queries totalسناریوی واقعی: سلسلهمراتب Payment (کارت، انتقال بانکی، کیف پول) در یک جدول با ستون type و یازده ستون nullable؛ object Address پخششده روی چهار ستون؛ ارجاع دوطرفهٔ Customer <-> Order که serialize به JSON را بینهایت بازگشتی میکند.
چه کسی فراهم میکند: هیچ ابزاری ناهمخوانی را حذف نمیکند؛ فقط انتخاب میکنند کجا درد کند. mapperهای سبک Doctrine و Hibernate بیشترش را پنهان میکنند و در عوض باید قواعدشان را یاد بگیرید؛ Eloquent حالتهای ساده را پنهان و بقیه را از طریق relation و cast عیان میکند؛ sqlc همهچیز را عیان میکند و نیمهٔ خستهکننده را تولید میکند.
راه درست:
-- Single Table Inheritance for payments: one table, a discriminator, nullable columns.
CREATE TABLE payments (
id bigint PRIMARY KEY,
order_id text NOT NULL,
type text NOT NULL CHECK (type IN ('card', 'bank', 'wallet')),
card_last4 char(4), -- only for type = 'card'
iban text, -- only for type = 'bank'
wallet_id text, -- only for type = 'wallet'
amount_cents bigint NOT NULL
);// Go: the domain keeps one interface; the adapter switches on the discriminator.
type Payment interface{ Amount() domain.Money }
func fromRow(r paymentRow) (Payment, error) {
switch r.Type {
case "card":
return CardPayment{Last4: r.CardLast4.String, Cents: r.AmountCents}, nil
case "bank":
return BankPayment{IBAN: r.IBAN.String, Cents: r.AmountCents}, nil
}
return nil, fmt.Errorf("unknown payment type %q", r.Type)
}// Laravel: composition beats Eloquent inheritance. The type column picks the strategy object.
$payment = match ($record->type) {
'card' => new CardPayment($record->card_last4, $record->amount_cents),
'bank' => new BankPayment($record->iban, $record->amount_cents),
default => throw new \UnexpectedValueException("Unknown payment type {$record->type}"),
};طرف طراحی schema (فرم نرمال، کلید، JSONB) در Schema Design است.
Active Record حیاتی
به زبان ساده: یک object برابر یک ردیف. ستونها فیلدهایشاند، جدولش را میشناسد و روی خودش save() صدا میزند. Eloquent چیزی است که بیشتر برنامهنویسهای PHP این الگو را با آن میشناسند.
بدفهمی رایج: «Active Record یعنی مدل anemic یا باید چاق باشد.» هیچکدام لازم نیست. الگو میگوید object دسترسی به داده را حمل میکند و میتواند منطق دامنه هم اضافه کند (به تعبیر Fowler). مشکل خودِ الگو نیست؛ رشد بیحد یک class است.
تعریف: Fowler: "An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data." نیروهایش: نوشتنش سریع است، خواندنش آسان است، دامنه و schema با هم تکامل مییابند؛ وقتی مدل object به schema نزدیک باشد بهترین عملکرد را دارد.
Eloquent: place an order
1 $order = Order::findOrFail($id); -- SELECT * FROM orders WHERE id = ? AND deleted_at IS NULL
2 $order->status = OrderStatus::Placed; -- in memory, marks `status` dirty
3 $order->save(); -- UPDATE orders SET status = ?, updated_at = ? WHERE id = ?
4 -- no version check, no transaction unless you opened oneسناریوی واقعی: پنل مدیریت دستهبندیها؛ وبلاگ؛ جدول تنظیمات؛ API ای که جدول و resource یکیاند. و شش ماه اول تقریباً هر محصول Laravel.
| نقطهٔ قوت | هزینه |
|---|---|
| کمترین کد تا فیچر کارا | class سه دلیل تغییر دارد (قاعده، SQL، فریمورک) |
| relation، cast، scope و event همراهش است | قاعده فقط با دیتابیس یا mock سنگین تست میشود |
| ابزار عالی و جامعهٔ بزرگ | شکل جدول به شکل API نشت میکند |
| معلوم است کجا را نگاه کنید | هر لایه میتواند save() را در هر تراکنشی صدا بزند |
چه کسی فراهم میکند: Eloquent (Laravel 13)، Active Record در Rails، و GORM وقتی مدلها را بهجای object دامنه به کار ببرید. معرفی Laravel: "each database table has a corresponding 'Model' that is used to interact with that table".
راه درست: برای بخشهای CRUD نگهش دارید و وقتی قاعدهها زیاد شدند بیرونشان بکشید (classهای Action، domain service یا یک class ساده دامنه). ارجاع: Single Responsibility و Code Smells & Refactoring (large class، divergent change). مثال کامل AR در بخش Laravel است.
Data Mapper حیاتی
به زبان ساده: واسطهای که هم object را میشناسد هم جدول را، تا هیچکدام دیگری را نشناسد.
بدفهمی رایج: «Data Mapper یعنی ORM سنگینتر.» Data Mapper یک نقش است، نه محصول: OrderMapper دستی، EntityManager در Doctrine و adapter مبتنی بر sqlc همه این نقش را بازی میکنند. ویژگی تعیینکننده این است که object دامنه هیچ کد ذخیرهسازی ندارد.
تعریف: Fowler: "A layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself." وجودش برای این است که schema شیء و schema رابطهای از هم دور میشوند (collection، وراثت) و وقتی object schema را بشناسد "changes in one tend to ripple to the other".
Data Mapper: place an order
1 use case -> orders.Get(ctx, "o-1") -- repository
2 mapper -> SELECT ... FROM orders; SELECT ... FROM order_lines -- two queries
3 mapper -> domain.Rehydrate(...) -- builds the pure aggregate
4 domain -> o.Place() -- rules, no I/O
5 use case -> orders.Save(ctx, o)
6 mapper -> UPDATE orders ... WHERE version = $n; DELETE/INSERT lines -- one transactionسناریوی واقعی: بیمهنامهای با چهل قاعده و schema قدیمی که کسی جرئت دستزدنش را ندارد؛ دامنهای که یک جدول پشت دو aggregate است؛ سرویسی که مدل دامنهاش باید از سه migration دیتابیس جان سالم به در ببرد.
چه کسی فراهم میکند: Doctrine ORM (Unit of Work، Identity Map، entityها بهصورت class ساده، طبق مستنداتش)، Hibernate در دنیای Java، mapperهای دستی، و در Go هر adapter repository روی database/sql، sqlc یا مدلهای GORM که فقط داخل adapter استفاده شوند.
| نقطهٔ قوت | هزینه |
|---|---|
| تست دامنه دیتابیس نمیخواهد | دو مدل که باید همگام بمانند (دامنه و ذخیرهسازی) |
| schema بدون دستزدن به قاعدهها عوض میشود | فایل و نام بیشتر |
| قواعد بارگذاری aggregate یکجاست | برای CRUD بهراحتی بیشازحد ساخته میشود |
راه درست: adapterهای Go در after/sqlcrepo و after/gormrepo و adapter لاراول EloquentOrderRepository را در بخشهای Go و Laravel ببینید. توجه کنید adapter خودش از مدلهای Eloquent استفاده میکند: Data Mapper و Eloquent میتوانند با هم زندگی کنند، با این تفاوت که Eloquent به «مدل ذخیرهسازی» تنزل پیدا میکند.
Table Data Gateway و Row Data Gateway مهم
به زبان ساده: بهجای object ای برای هر ردیف که همهکاره است، SQL را برای هر جدول یکجا نگه دارید (Table Data Gateway) یا به هر ردیف یک دستگیرهٔ تایپدار بدهید بدون قاعده (Row Data Gateway).
بدفهمی رایج: «gateway همان repository است.» repository دربارهٔ aggregate به زبان دامنه حرف میزند و ممکن است چند جدول را بپوشاند؛ gateway دربارهٔ یک جدول یا ردیف به زبان جدول.
تعریف: Fowler: Table Data Gateway "holds all the SQL for accessing a single table or view: selects, inserts, updates, and deletes. Other code calls its methods for all interaction with the database." Row Data Gateway "objects that look exactly like the record in your record structure but can be accessed with the regular mechanisms of your programming language."
Table Data Gateway
1 orders := OrderTable{db}
2 row, err := orders.Find(ctx, "o-1") -- SELECT ... FROM orders WHERE id = $1
3 err = orders.UpdateStatus(ctx, "o-1", "placed") -- UPDATE orders SET status = $2 ...
4 -- rules live in a service that calls these methodsسناریوی واقعی: job گزارشگیری؛ transaction script («ده هزار ردیف import کن»)؛ سرویسی که تقریباً همهٔ منطقش SQL است. در Go، نوع Queries که sqlc تولید میکند یک Table Data Gateway برای کل schema است (دقیقتر: یک gateway با متدهای تایپدار و struct برای ردیفها).
| الگو | واحد | قاعده دارد؟ | نمونه در Go | نمونه در Laravel |
|---|---|---|---|---|
| Table Data Gateway | یک object برای هر جدول | نه | Queries در sqlc | class دور DB::table('orders') |
| Row Data Gateway | یک object برای هر ردیف | نه | structهای ردیف در sqlc | ردیف stdClass از query builder |
| Active Record | یک object برای هر ردیف | بله | مدل GORM با متد | مدل Eloquent |
راه درست: وقتی منطق بیشتر SQL مجموعهای است از آنها استفاده کنید و قاعدهها را در یک service بگذارید. به یک کیسهٔ find/save نگویید repository؛ Repository را ببینید.
Repository حیاتی
به زبان ساده: repository «قفسهٔ کتاب» یک نوع object کسبوکار است: aggregate را مثل collection درونحافظه به آن اضافه میکنید، از آن میگیرید و حذف میکنید، و پشت صحنه ذخیرهسازی را خودش انجام میدهد.
بدفهمی رایج: «برای هر جدول یک repository» یا «هر repository باید findAll و find و save و delete برای همهچیز داشته باشد.» Evans میگوید repository برای ریشهٔ aggregateهایی است که به دسترسی مستقیم نیاز دارند و متدهایش با "criteria meaningful to domain experts" انتخاب میکنند.
تعریف: مدخل Hieatt و Mee: "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." repository (۱) به زبان دامنه تعریف میشود، (۲) aggregate کامل برمیگرداند، (۳) فناوری query را پنهان میکند، (۴) تنها در به جدولهای aggregate است.
Repository, in use
1 orders := repo (interface domain.Repository)
2 o, err := orders.Get(ctx, id) -- ErrNotFound if missing
3 o.Place() -- domain rule
4 err = orders.Save(ctx, o) -- ErrConflict if version changed
5 -- the use case never sees SQL, a table, an ORM type or a transaction handleسناریوی واقعی: OrderRepository، AccountRepository، BookingRepository: هرکدام یک aggregate را بارگذاری و ذخیره میکند و invariantها و راهبرد قفل آن را میشناسد.
| انتخاب طراحی در repository | خوب | بد |
|---|---|---|
| جای interface | در package دامنه (DIP) | در package زیرساخت کنار ORM |
| نوع بازگشتی | aggregate (*domain.Order) | مدل ORM، query builder، *sql.Rows |
| نام متدها | ByCustomerOverdue، NextToShip | FindBy(field, value) |
| دانهبندی | یکی برای هر ریشهٔ aggregate | یکی برای هر جدول |
| خطاها | خطای دامنه (ErrNotFound، ErrConflict) | خطای خام driver |
| حس collection | Add، Get، Save | Insert، Update، Select |
چه کسی فراهم میکند: هیچ چیز در Eloquent یا GORM؛ این طراحیای است که خودتان مینویسید. interfaceهای Go و PHP در snippetها مرجعاند.
راه درست:
// Go: the port, defined in the domain package.
type Repository interface {
Add(ctx context.Context, o *Order) error
Get(ctx context.Context, id OrderID) (*Order, error)
Save(ctx context.Context, o *Order) error
}// Laravel: the port, in the domain namespace.
interface OrderRepository
{
public function add(Order $order): void;
public function get(string $id): Order; // throws OrderNotFound
public function save(Order $order): void; // throws ConcurrencyConflict
}برای قواعد تاکتیکی DDD هم Repositories را ببینید.
مرز Aggregate: یک repository برای هر aggregate حیاتی
به زبان ساده: چیزهایی که باید همیشه با هم سازگار باشند (سفارش و خطوطش) با هم بارگذاری، تغییر و ذخیره میشوند؛ هر چیز دیگر با id ارجاع داده میشود.
بدفهمی رایج: «aggregate یعنی class مجموعه یا جدول با فرزندانش.» Fowler: "DDD Aggregates are sometimes confused with collection classes... DDD aggregates are domain concepts (order, clinic visit, playlist)".
تعریف: Fowler: "A DDD aggregate is a cluster of domain objects that can be treated as a single unit... Aggregates are the basic element of transfer of data storage - you request to load or save whole aggregates. Transactions should not cross aggregate boundaries." Evans: "Within an aggregate boundary, apply consistency rules synchronously. Across boundaries, handle updates asynchronously."
Why the boundary matters
1 T1: load Order o-1 (root + 3 lines), AddLine, Save -- version 4 -> 5
2 T2: load Order o-1, Place, Save -- expected version 4, finds 5: ErrConflict
3 T3: load Customer c-1 to change the address -- different aggregate, no conflict with T1/T2
4 Rule: o-1's lines never change except through Order, so one version number guards the whole clusterسناریوی واقعی: سبد خرید با آیتمها، پلیلیست با ترکها، رزرو با مهمانها. مثال نقض: بارگذاری Customer همراه ۲۰٬۰۰۰ سفارشش بهعنوان یک aggregate؛ aggregate بیشازحد بزرگ است، سفارشها را با customer_id ارجاع دهید.
| پرسش | درون aggregate | بین aggregateها |
|---|---|---|
| سازگاری | فوری، یک تراکنش | در نهایت (event، outbox) |
| ارجاعها | object | id |
| قفل | یک ستون version روی ریشه | یکی برای هر aggregate |
| Repository | مال ریشه | جدا |
| باگ معمول | aggregate بزرگ: رقابت، بارگذاری کند | aggregate کوچک: invariant شکسته |
چه کسی فراهم میکند: انضباط طراحی. نه Eloquent نه GORM آن را اعمال نمیکنند؛ relationها عبور تصادفی از مرزها را آسان میکنند.
راه درست: aggregate Order در snippetها Lines() را کپی برمیگرداند و فقط AddLine را در دسترس میگذارد؛ repository خطوط را داخل همان تراکنشِ بهروزرسانی ریشه بازنویسی میکند. بیشتر: Aggregates & Factories.
پرسوجو از طریق repository: finder، Specification، Query Object مهم
به زبان ساده: میخواهید بگویید «همهٔ سفارشهای معوق این مشتری، جدیدترین اول، صفحهٔ ۳». یا برای هر پرسش یک متد مینویسید، یا یک object میدهید که پرسش را توصیف کند.
بدفهمی رایج: «Specification جای SQL را میگیرد.» توصیف میکند کدام objectها واجدند؛ باز هم چیزی باید آن را به SQL تبدیل کند یا در حافظه ارزیابی کند.
تعریف: سه تکنیک.
| تکنیک | چیست | منبع | مناسب برای | هزینه |
|---|---|---|---|---|
| متدهای Finder | یک متد نامدار برای هر پرسش | Evans: criteria meaningful to domain experts | چند query پایدار | انفجار متد، پارامتر boolean |
| Specification | object ای که میگوید candidate جور است یا نه؛ با AND و OR و NOT ترکیب میشود | Evans و Fowler، Specifications | محمولهای کسبوکار قابلاستفادهٔ مجدد؛ اعتبارسنجی و انتخاب | دو backend (SQL و درونحافظه) ممکن است واگرا شوند |
| Query Object | object ای که یک query را نمایندگی میکند و از نام class و فیلد ساخته میشود | Fowler: "An object that represents a database query" | فیلترهای ad-hoc که کاربر میسازد | کد interpreter؛ یک mini-ORM |
Evans و Fowler ایده را جداکردن "how to match a candidate" از "the candidate object that it is matched against" میدانند و سه راهبرد پیادهسازی میدهند: Hard Coded، Parameterized و Composite Specification. Composite "uses an interpreter ... to cut a very agreeable middle path."
Finder-method explosion vs one specification
1 ordersRepo.Overdue(customer) ordersRepo.Matching(Overdue().And(ForCustomer(c)))
2 ordersRepo.OverdueNewestFirst(customer) ordersRepo.Matching(spec, Page(3, 20), Newest())
3 ordersRepo.OverdueByRegion(customer, region) -- one method, composable predicates
4 ordersRepo.OverdueByRegionUnpaid(...) -- 4 methods and growingسناریوی واقعی: UI فیلتر ادمین با دوازده فیلتر اختیاری؛ قاعدهٔ «این مشتری میتواند این را بخرد؟» که هم برای اعتبارسنجی هم برای فهرست مشتریان واجد استفاده میشود؛ job شبانه که «سفارشهای راکد ۳۰ روزه» را انتخاب میکند.
// A small specification for the SQL adapter: it renders a WHERE fragment and arguments.
type Spec interface{ SQL(argN int) (frag string, args []any) }
type ForCustomer string
func (s ForCustomer) SQL(n int) (string, []any) {
return fmt.Sprintf("customer_id = $%d", n), []any{string(s)}
}
type And []Spec
func (a And) SQL(n int) (string, []any) {
var parts []string
var args []any
for _, s := range a {
f, ar := s.SQL(n + len(args))
parts, args = append(parts, f), append(args, ar...)
}
return "(" + strings.Join(parts, " AND ") + ")", args
}// Laravel: a specification as a scope-like object applied to the persistence model's builder.
interface OrderSpecification
{
public function apply(\Illuminate\Database\Eloquent\Builder $query): void;
}
final class OverdueFor implements OrderSpecification
{
public function __construct(private string $customerId) {}
public function apply(\Illuminate\Database\Eloquent\Builder $query): void
{
$query->where('customer_id', $this->customerId)
->where('status', 'placed')
->where('due_at', '<', now());
}
}راه درست: با متدهای finder نامدار شروع کنید؛ وقتی دیدید همان محمولها در چند جا ترکیب میشوند به Specification بروید؛ هرگز API مربوط به specification را بازنویسی ظاهری query builder نکنید (این همان repository نشتی است، حل مسئلههای کلاسیک). ارزیابی درونحافظه و SQL را با همان تستهای contract بسنجید (ببینید تست).
بحث «Repository روی Eloquent» مهم
به زبان ساده: Eloquent خودش شبیه repository است (Order::where(...)->get())، پس باید پشت یکی دیگر پنهانش کرد؟
بدفهمی رایج: «همیشه بپیچ» و «هرگز نپیچ» هر دو شعارند. پرسش این است که wrapper چیزی را که بقیهٔ کد به آن وابسته است عوض میکند یا نه.
تعریف: بحث یک هستهٔ پایدار دارد.
| موضع | استدلال | قویترین وقتی |
|---|---|---|
| نپیچ | Eloquent خودش لایهٔ دسترسی به داده است؛ wrapper یکبهیک کد اضافه میکند و ارزشی ندارد؛ relation و scope و with() را از دست میدهید | CRUD، ادمین، محتوا، تیم کوچک |
| بهازای aggregate بپیچ | قاعدهها تستپذیر و persistence-ignorant میمانند؛ قفل، نگاشت و تراکنش یکجاست | قاعدهٔ غنی، محصول بلندمدت، چند bounded context |
| فقط قسمتهای دردسرساز را بپیچ | Query object یا Action برای ۱۰ query پیچیده؛ جاهای دیگر مدل | بیشتر اپهای واقعی Laravel |
When the wrapper pays for itself
1 Rule changes: "orders over 1000 need approval" -> edit Order::place(), no SQL touched
2 Storage changes: split lines into a second database -> edit EloquentOrderRepository only
3 Test: 400 rule tests in 0.2 s with the fake -> no RefreshDatabase
4 Counter-case: a settings table with 3 columns -> the wrapper is pure ceremonyسناریوی واقعی (ارزش): قیمتگذاری، صورتحساب، رزرو، دفتر کل؛ هر جا باگ قاعده پول خرج دارد. سناریوی واقعی (تشریفات): UserRepository::find و ::all و ::create و ::update و ::delete که همه به Eloquent فوروارد میکنند، بهعلاوهٔ interface و binding، برای یک صفحهٔ CRUD.
| پرسش | اگر بله | اگر نه |
|---|---|---|
| قاعدههایی هست که تست سریع میخواهند؟ | Repository و دامنهٔ ساده | مستقیم Eloquent |
| شکل ذخیرهسازی با شکل object فرق دارد؟ | Mapper داخل repository | مدل Eloquent همان object است |
| بیش از یک راه برای بارگذاری این چیز هست؟ | Repository با متدهای نامدار | scopeهای ساده |
| ماژولهای دیگر هم از این داده استفاده میکنند؟ | facade یا repository بهعنوان قرارداد عمومی | مدل داخلی |
راه درست: آزمایشگاه هر دو را از روی یک تست پیاده میکند تا هزینه را حس کنید. ببینید Anemic vs Rich Models.
Unit of Work و تراکنش بهعنوان مرز طراحی حیاتی
به زبان ساده: یک کار کسبوکاری، یک تراکنش: یا همهٔ تغییرها ذخیره میشوند یا هیچکدام. Unit of Work چیزی است که میداند چه چیزی عوض شده و یکجا commit میکند.
بدفهمی رایج: «save() اتمیک است پس امنم.» هر save() یک statement است؛ use case ای که دو چیز را ذخیره میکند یک تراکنش دور هر دو میخواهد. کاتالوگ Fowler اضافه میکند بدون آن "lots of very small database calls" میگیرید.
تعریف: Fowler: "Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems." دو شکل وجود دارد:
| شکل | چطور | نمونه |
|---|---|---|
| Unit of Work ردیاب | ORM objectها را زیر نظر دارد، تغییرها را حساب میکند و آخر flush میکند | EntityManager::flush() در Doctrine؛ GORM ردیابی ندارد (فراخوانی صریح) |
| تراکنش محدودهدار | تراکنش را باز میکنید، use case را اجرا میکنید، commit میکنید | DB::transaction(fn)، BeginTx و closure در Go |
Scoped Unit of Work in the use case
1 uow.Do(ctx, func(ctx, orders) error { -- BEGIN
2 o := orders.Get(ctx, id) -- SELECT (inside the tx)
3 o.Place() -- in memory
4 orders.Save(ctx, o) -- UPDATE ... WHERE version = $n
5 }) -- COMMIT, or ROLLBACK if the closure returned an error
6 -- publish events AFTER commit, or write them to an outbox row in the same transactionسناریوی واقعی: ثبت سفارش و رزرو موجودی؛ انتقال پول (دو حساب، یک تراکنش، ترتیب قفل مهم است)؛ ساخت کاربر و ارسال ایمیل خوشآمد (ایمیل داخل تراکنش نیست: بعد از commit یا در outbox).
| پرسش طراحی | پاسخ پیشنهادی |
|---|---|
| چه کسی تراکنش را باز میکند؟ | use case (لایهٔ application)، نه repository، نه controller |
| چقدر باز میماند؟ | به اندازهٔ یک request؛ هرگز در زمان فکرکردن کاربر یا فراخوانی راه دور |
| چه چیزی داخلش است؟ | خواندن و نوشتن یک دیتابیس؛ بدون HTTP و ایمیل |
| repositoryها چطور به آن میپیوندند؟ | دستگیرهٔ تراکنش را میگیرند (Go: Queries.WithTx؛ Laravel: DB::transaction محیطی) |
| دو aggregate چه؟ | معمولاً دو تراکنش و یک event؛ ببینید Saga |
// Go: the use case owns the boundary; the adapter binds repositories to the transaction.
func (u UoW) Do(ctx context.Context, fn func(context.Context, domain.Repository) error) error {
tx, err := u.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
if err := fn(ctx, New(u.Q.WithTx(tx))); err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}// Laravel: the use case wraps the work. The repository's own DB::transaction nests inside.
DB::transaction(function () use ($orderId): void {
$order = $this->orders->get($orderId);
$order->place();
$this->orders->save($order);
});مستندات sqlc سازوکار Go را توضیح میدهد: "In the code generated by sqlc, the WithTx method allows a Queries instance to be associated with a transaction." جزئیات isolation، قفل و deadlock در ACID & Transactions و Isolation Levels است. DB::transaction در Laravel آرگومان attempts هم میگیرد تا هنگام deadlock دوباره تلاش کند.
Identity Map و caching مهم
به زبان ساده: اگر در یک عملیات ردیف ۷ را دو بار بارگذاری کنید، باید همان object را بگیرید، نه دو کپی که میتوانند از هم جدا شوند.
بدفهمی رایج: «Identity Map یک cache است.» یک نقشهٔ مخصوص هر تراکنش کسبوکاری است و هدف اولش درستی است؛ سرعت اثر جانبی است. cache از تراکنش بیشتر عمر میکند و مشکل invalidation دارد؛ identity map با تراکنش دور انداخته میشود.
تعریف: Fowler: "Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them." مستندات Doctrine: "Doctrine keeps a map of each entity and ids that have been retrieved per PHP request and keeps returning you the same instances." Eloquent و GORM این کار را نمیکنند؛ هر query شیء تازه برمیگرداند.
Without and with an identity map
1 a := repo.Get(7); b := repo.Get(7) -- two objects, same row
2 a.Rename("X"); b.Rename("Y") -- both dirty
3 save(a); save(b) -- last write wins, "X" lost, no error
--- with an identity map ---
4 a := uow.Get(7); b := uow.Get(7) -- a == b (same instance)
5 a.Rename("X"); b.Rename("Y") -- one object, final state "Y", saved onceسناریوی واقعی: مسیرهایی که همان سفارش را در controller و دوباره در listener بارگذاری میکنند؛ job دستهای که همان مشتری را از چند ردیف لمس میکند.
| لایه | محدوده | Invalidation | کجا |
|---|---|---|---|
| Identity Map | یک unit of work | با آن میمیرد | Doctrine؛ در Go دستی برای هر request |
| memo در سطح request | یک request | با آن میمیرد | map[OrderID]*Order داخل UoW |
| cache برنامه | process یا مشترک | صریح و سخت | Cache::remember، Redis |
| cache دیتابیس | موتور | موتور | buffer pool |
راه درست: در Laravel یک مدل را در لایههای مختلف دوباره بارگذاری نکنید؛ object را پایین بفرستید. در Go اگر دو repository ممکن است همان aggregate را بارگذاری کنند، یک map کوچک داخل unit of work نگه دارید. برای cache جلوی repository، read model را cache کنید (ببینید DTO و read model) و با event باطل کنید؛ هرگز aggregate قابلنوشتن را بین requestها cache نکنید. طراحی cache: Storage & Data Scaling.
بارگذاری تنبل در برابر مشتاق بهعنوان تصمیم طراحی حیاتی
به زبان ساده: وقتی سفارش را بارگذاری میکنید، خطوطش، مشتری، و سفارشهای دیگر مشتری هم بیایند؟ Lazy میگوید «فقط وقتی کسی نگاه کرد»، Eager میگوید «همین حالا و یکجا».
بدفهمی رایج: «Lazy loading یک قابلیت کارایی است.» Lazy Load در تعبیر Fowler برای جلوگیری از بارگذاری "a huge number of related objects" است وقتی فقط چندتا لازماند؛ هزینهاش یک query پنهان در اولین دسترسی است که در حلقه به N+1 تبدیل میشود.
تعریف: Lazy Load: "An object that doesn't contain all of the data you need but knows how to get it." Fowler چهار نوع میشمارد: lazy initialization، virtual proxy، value holder و ghost. Eager loading دادههای مرتبط را از قبل میآورد.
| راهبرد | کی بارگذاری میکند | query برای ۵۰ سفارش و خطوط | خطر |
|---|---|---|---|
| Lazy | اولین دسترسی به هر relation | 1 + 50 | N+1، I/O پنهان، دسترسی بعد از بستهشدن اتصال |
Eager (with، Preload، WithX در ent) | همراه والد | 2 | بارگذاری بیشازحد اگر استفاده نشود |
| Join | در یک statement | 1 | تکثیر ردیف، نتیجهٔ بزرگ |
| Read model | query مخصوص | 1 | چیز دیگری برای نگهداری |
Aggregate design rule
1 Aggregate (Order + lines): always loaded whole -- eager by design, small, bounded
2 Reference to another aggregate (Customer): by id only -- never lazy-navigate across the boundary
3 Collections that can grow without bound (events, audit): -- not part of the aggregate; separate queryسناریوی واقعی: لیست ۲۰۰ سفارش که قالب $order->customer->name و count($order->lines) را چاپ میکند: lazy ۴۰۱ query، eager ۳ query. تشخیص و راهحل کامل در ORM Pitfalls است.
چه کسی فراهم میکند: Eloquent relationها را پیشفرض lazy بارگذاری میکند؛ Model::preventLazyLoading() lazy load تصادفی را به exception تبدیل میکند و مستندات Laravel فعالکردنش بیرون از production را نشان میدهد (Model::preventLazyLoading(! $this->app->isProduction())). GORM نیاز به Preload دارد؛ ent از edgeهای eager استفاده میکند (به سبک WithPets()) و نتیجه را از Edges میخواند. Go با sqlc اصلاً lazy loading ندارد: relationها query جداگانهایاند که خودتان مینویسید.
راه درست: در طراحی برای هر association تصمیم بگیرید: درون aggregate یعنی همراه ریشه eager؛ بین aggregateها یعنی ارجاع با id و read model برای نمایش.
DTO و read model (CQRS سبک) حیاتی
به زبان ساده: صفحه برای پنجاه سفارش «id، وضعیت، جمع، تعداد خطوط» میخواهد. پنجاه aggregate بارگذاری نکنید؛ یک query بزنید که دقیقاً همین فیلدها را برگرداند.
بدفهمی رایج: «CQRS یعنی دو دیتابیس، event و eventual consistency.» آن یک شکل سنگین است. Fowler هشدار میدهد "for most systems CQRS adds risky complexity". شکل سبک فقط یک مسیر query جدا است که از همان دیتابیس DTO برمیگرداند.
تعریف: Data Transfer Object "an object that carries data between processes in order to reduce the number of method calls" (کاتالوگ Fowler) است و معمولاً یک assembler میسازدش. در اینجا به هر شکل فقطدادهای هم میگوییم که برای صفحه یا API برمیگردد. read model مدل سمت query است: شکلش مال صفحه است، نه aggregate. CQRS: "you can use a different model to update information than the model you use to read information."
Command side vs query side
1 POST /orders/o-1/place -> use case -> repository.Get -> Order.Place -> repository.Save -- aggregate, rules, version
2 GET /customers/c-1/orders -> OrderSummaryQuery.forCustomer -> one GROUP BY query -- DTOs, no rules
3 Both read the same tables; the query side never constructs an Orderسناریوی واقعی: صفحههای لیست، داشبورد، خروجی گرفتن، نتایج جستجو، endpointهای مجموعه در API؛ هر چیزی که کاربر بیشتر از نوشتن میخواند.
| سطح | چه میکنید | Consistency | هزینه |
|---|---|---|---|
| سبک | query با DTO روی همان جدولها | فوری | تقریباً هیچ |
| متوسط | SQL view یا materialized view | به اندازهٔ تازگی refresh | jobهای refresh |
| سنگین | store جدا که با event تغذیه میشود (ببینید CQRS و event sourcing) | در نهایت | projector، بازسازی، پایش |
-- The read model query used by sqlc and the Laravel query builder.
SELECT o.id, o.status, o.currency,
COALESCE(SUM(l.qty * l.unit_cents), 0)::bigint AS total_cents,
COUNT(l.position)::int AS line_count
FROM orders o
LEFT JOIN order_lines l ON l.order_id = o.id
WHERE o.customer_id = $1 AND o.deleted_at IS NULL
GROUP BY o.id
ORDER BY o.created_at DESC
LIMIT $2;راه درست: readmodel.Reader در Go و OrderSummaryQuery در Laravel همین الگو هستند: port جدا، دادهی ساده، بدون رفتار. صفحهبندی چنین لیستهایی: Pagination.
نگاشت value object، enum و ستون JSON مهم
به زبان ساده: Money، Address و Status نوعهای کوچک و معنادارند. دیتابیس عدد، رشته و JSON ذخیره میکند. برای عبور از مرز قاعدهای لازم دارید و نوع باید در هر دو سمت مقدار بد را رد کند.
بدفهمی رایج: «پول را float ذخیره کن و بعد فرمت کن» یا «ستون JSON اجازهٔ مدلنکردن است.» پول یعنی مبلغ صحیح بهعلاوهٔ واحد پول؛ ستون JSON انتخابی آگاهانه برای دادهای است که فیلدبهفیلد query نمیشود.
تعریف: راهبردهای نگاشت (نامهای Fowler: Embedded Value، Serialized LOB):
| مقدار | راهبرد ستون | Go | Laravel |
|---|---|---|---|
Money | دو ستون (total_cents، currency) | فیلدهای struct در adapter؛ Money دامنه در mapper ساخته میشود | CastsAttributes روی دو ستون (MoneyCast) |
Address | یک ستون JSONB یا چند ستون | نوعی که driver.Valuer و sql.Scanner را پیاده میکند | AsArrayObject یا cast سفارشی Address |
enum Status | text بهعلاوهٔ CHECK یا نوع enum بومی | نوعی با Scan که مقدار ناشناخته را رد میکند | cast روی enum پشتیباندار (OrderStatus::class) |
| tag / تنظیمات | jsonb | []byte یا json.RawMessage یا Valuer تایپدار | AsArrayObject، AsCollection، cast از نوع array |
| شناسه | text/uuid/bigint | نوع نامدار OrderID | id تایپدار در دامنه، رشته در مدل |
Crossing the boundary
1 write: domain.Address{...} --Value()--> []byte JSON --driver--> jsonb column
2 read: jsonb column --driver--> []byte or string --Scan()--> domain.Address
3 bad data: status = 'shipped' in the table --Scan()--> error "unknown value", not a silent defaultسناریوی واقعی: ناسازگاری ارز که در خود نوع گرفته میشود؛ ستون status که با دست به مقداری ویرایش شده که کد نمیشناسد؛ blob JSON که شکلش بین دو release عوض شده.
// Go: Valuer writes, Scanner reads. Unknown enum values fail loudly on read.
func (a Address) Value() (driver.Value, error) { return json.Marshal(a) }
func (a *Address) Scan(src any) error {
switch v := src.(type) {
case []byte:
return json.Unmarshal(v, a)
case string:
return json.Unmarshal([]byte(v), a)
case nil:
*a = Address{}
return nil
default:
return fmt.Errorf("address: cannot scan %T", src)
}
}// Laravel: casts() declares the mapping; CastsAttributes handles multi-column values.
protected function casts(): array
{
return [
'status' => OrderStatus::class, // backed enum
'options' => AsArrayObject::class, // JSON column as an object
'total' => MoneyCast::class, // two columns -> Money
];
}interfaceهای Valuer و Scanner در database/sql/driver و database/sql مستند شدهاند؛ castهای Laravel در Eloquent: Mutators & Casting. sqlc هم میتواند نوع Go یک ستون را override کند (راهنمای overrides). GORM همان جفت Scanner/Valuer را برای نوعهای سفارشی مستند کرده. طراحی ستون JSON: Schema Design.
Optimistic locking بهعنوان دغدغهٔ طراحی حیاتی
به زبان ساده: دو نفر یک سفارش را باز میکنند و هر دو ذخیره میزنند. بدون بررسی، دومی بیصدا کار اولی را پاک میکند. شمارهٔ نسخه باعث میشود ذخیرهٔ دوم بهجای آن خطا بدهد.
بدفهمی رایج: «ORM من این را خودش انجام میدهد.» Doctrine و بسیاری از ORMها فیلد نسخه دارند، اما Eloquent قفل خوشبینانهٔ داخلی ندارد و هستهٔ GORM هم ندارد؛ WHERE version = ? را خودتان مینویسید.
تعریف: Optimistic Offline Lock از Rice "prevents conflicts between concurrent business transactions by detecting a conflict and rolling back the transaction." یک تراکنش کسبوکاری معمولاً چند request را میپوشاند، پس تراکنش دیتابیس بهتنهایی از آن محافظت نمیکند. تصمیم طراحی این است که مالک version کیست: ریشهٔ aggregate. مکانیک دیتابیسی در Optimistic vs Pessimistic Locking است.
Two editors, one aggregate (version column)
1 A: Get(o-1) -> version 3 B: Get(o-1) -> version 3
2 A: Place(); Save: UPDATE ... SET version = 4 WHERE id = 'o-1' AND version = 3 -> 1 row
3 B: Place(); Save: UPDATE ... WHERE version = 3 -> 0 rows
4 B: ErrConflict -> reload and retry, or tell the userسناریوی واقعی: دو ادمین که یک محصول را ویرایش میکنند؛ دکمهٔ «پرداخت» که دو بار کلیک میشود؛ یک worker و یک کاربر که همزمان یک رزرو را بهروز میکنند. برای شمارندهٔ داغ مناسب نیست: بهجایش UPDATE x = x + 1 اتمیک بزنید.
| تکنیک | چه چیزی را تشخیص میدهد | هزینه | کی |
|---|---|---|---|
ستون version و WHERE version = ? | هر نوشتن همزمان روی aggregate | مسیر retry | ویرایشهایی که چند request را میپوشانند، تعارض کم |
مقایسهٔ updated_at | نوشتن همزمان (خشن، به دقت ساعت) | شکننده | فرمهای CRUD سریع |
SELECT ... FOR UPDATE | با منتظر نگهداشتن جلوگیری میکند | قفل نگهداشته، deadlock | تراکنش کوتاه با تعارض زیاد |
بهروزرسانی اتمیک (balance = balance - ?) | لازم نیست | هیچ | شمارنده، موجودی |
UPDATE orders
SET status = $2, version = version + 1, updated_at = now()
WHERE id = $1 AND version = $3 AND deleted_at IS NULL;
-- rows affected = 0 => someone else changed it (or it is gone): return a conflict, never "ok"n, err := q.UpdateOrderVersioned(ctx, db.UpdateOrderVersionedParams{ID: id, Status: s, Version: v})
if err == nil && n == 0 {
err = domain.ErrConflict // the repository translates "0 rows" into a domain error
}$affected = OrderRecord::query()
->where('id', $order->id)
->where('version', $order->version())
->update(['status' => $order->status()->value, 'version' => $order->version() + 1]);
if ($affected === 0) {
throw ConcurrencyConflict::forOrder($order->id);
}راه درست: تست contract در آزمایشگاه شامل «نویسندهٔ دوم conflict میگیرد» است. رفتار رو به کاربر (reload و merge یا پرسیدن دوباره) را در use case تعیین کنید، نه در repository.
Soft delete و ممیزی (Auditing) بهعنوان دغدغهٔ مقطعی مهم
به زبان ساده: «حذف» اغلب یعنی «پنهان کن ولی برای حسابداری نگه دار»؛ و یک نفر حتماً میپرسد چه کسی چه چیزی را کی عوض کرد.
بدفهمی رایج: «soft delete فقط یک boolean روی هر جدول است و مسئله حل شد.» حالا هر query، هر unique index، هر کلید خارجی و هر گزارش باید از آن خبر داشته باشد و داده هرگز نمیرود (قوانین حریم خصوصی شاید حذف واقعی بخواهند).
تعریف: هر دو مقطعیاند: برای aggregateهای زیادی صدق میکنند و نباید در هر use case تکرار شوند.
| دغدغه | سازوکار معمول | تلهها |
|---|---|---|
| Soft delete | timestamp به نام deleted_at | قیدهای unique (email دوباره استفاده میشود)، join که فیلتر را فراموش میکند، cascade |
| ممیزی: چه کسی/کی | created_by، updated_by، timestamp | jobهای پسزمینه کاربر ندارند |
| ممیزی: چه چیزی | جدول تاریخچهٔ append-only، لاگ event یا trigger دیتابیس | حجم، نگهداری PII |
| لاگ event بهعنوان حقیقت | Event sourcing | معماری متفاوت؛ ببینید event sourcing |
Soft delete in practice
1 DELETE /orders/o-1 -> UPDATE orders SET deleted_at = now() WHERE id = 'o-1'
2 list orders -> WHERE deleted_at IS NULL (global scope in Eloquent, GORM adds it for gorm.DeletedAt)
3 create order with same key -> unique index must be partial: UNIQUE (code) WHERE deleted_at IS NULL
4 GDPR erasure -> real DELETE or anonymise; soft delete is not erasureسناریوی واقعی: سفارش لغوشدهای که برای حسابداری میماند؛ کاربر «حذفشده» که صورتحسابهایش باید بماند؛ ادمینی که میپرسد «کی قیمت را روز جمعه عوض کرد؟».
چه کسی فراهم میکند: trait به نام SoftDeletes در Laravel با trashed()، withTrashed()، restore() و forceDelete()؛ GORM: "If your model includes a gorm.DeletedAt field ... When calling Delete, the record WON'T be removed from the database"؛ sqlc و database/sql چیزی نمیدهند: deleted_at IS NULL را در هر query خودتان بنویسید (مثل queryهای snippet). ممیزی در Eloquent میتواند از model event و observer استفاده کند (ShouldHandleEventsAfterCommit برای اجرا بعد از commit هست)، اما update() انبوهی را که مدل را دور میزند از دست میدهد.
CREATE UNIQUE INDEX orders_code_live ON orders (code) WHERE deleted_at IS NULL; -- PostgreSQL partial unique index
CREATE TABLE order_audit (
id bigserial PRIMARY KEY,
order_id text NOT NULL,
actor text NOT NULL,
action text NOT NULL,
changed_at timestamptz NOT NULL DEFAULT now(),
diff jsonb NOT NULL
);راه درست: soft delete را ویژگی repository کنید (هر متد خواندن آن را فیلتر کند)، ردیف ممیزی را داخل همان تراکنش تغییر بنویسید و زمان نگهداری را از ابتدا تعیین کنید. زاویهٔ امنیتی: Security by Design و Database Security.
تست ماندگاری: fake، دیتابیس واقعی، تست تراکنشی حیاتی
به زبان ساده: قاعدهها را با object ساده تست کنید، adapter را با دیتابیس واقعی، و ثابت کنید fake همان رفتار واقعی را دارد با همان تستها.
بدفهمی رایج: «در تستها بهجای دیتابیس واقعی از SQLite درونحافظه استفاده کن.» موتور دیگری است: نوع، قفل، JSON، قید و لهجهٔ SQL متفاوت. رفتار SQLite را میسنجد، نه فرضهای شما را.
تعریف: هرم تست برای ماندگاری.
| تست | موضوع | سرعت | چه میگیرد |
|---|---|---|---|
| unit test دامنه | قاعدههای Order، بدون I/O | میکروثانیه | باگ قاعده |
| تست use case با fake درونحافظه | PlaceOrder با memrepo | میکروثانیه | باگ orchestration، رفتار rollback |
| تست contract برای repository | fake و adapter واقعی یک مجموعه را اجرا میکنند | میلیثانیه | واگرایی fake، باگ نگاشت، بررسی version |
| تست adapter روی موتور واقعی | SQL، قید، index، JSON | میلیثانیه برای هر تست | SQL غلط، نوع غلط |
| end-to-end از HTTP | کل برش | کندتر | سیمکشی |
The contract suite
1 contract.Run(t, newRepo) -- one list of behaviours
2 memrepo.New() passes -> the fake mirrors the contract
3 sqlcrepo.New(db.New(tx)) passes -> the SQL adapter satisfies it (inside a rolled-back transaction)
4 gormrepo.New(gormDB) passes -> same port, different tool
5 Change a rule in the contract, all three fail togetherسناریوی واقعی: fake ای که دو نویسنده را بیصدا میپذیرفت در حالی که production conflict برمیگرداند؛ migration ای که ستون NOT NULL اضافه کرد و فقط تستهای دیتابیس واقعی را شکست؛ مجموعهای که یازده دقیقه طول میکشید چون هر تست جدولها را truncate میکرد.
| تکنیک ایزولهسازی | چطور | نکته |
|---|---|---|
| تراکنش برای هر تست، rollback در پایان | قبل از تست Begin، در cleanup Rollback | سریع؛ رفتار commit را نمیشود تست کرد؛ تست Go در snippetها همین کار را میکند |
| truncate / refresh بین تستها | RefreshDatabase در Laravel («will take care of this for you») | ساده؛ کندتر |
| schema تازه برای هر package | container برای هر suite | کندترین، ایزولهترین |
// Go: run the same contract against the fake and, if DATABASE_URL is set, PostgreSQL.
func TestContract(t *testing.T) {
contract.Run(t, func(*testing.T) domain.Repository { return memrepo.New() })
}// Laravel: one trait of checks, two test classes (fake: plain PHPUnit; real: RefreshDatabase).
final class InMemoryOrderRepositoryTest extends TestCase { use OrderRepositoryContract; }
final class EloquentOrderRepositoryTest extends TestCase { use OrderRepositoryContract, RefreshDatabase; }راه درست: fakeها را ساده نگه دارید (حالت را مثل دیتابیس داخل و خارج کپی کنند، همان مقدار خطا)، contract را یکجا نگه دارید و مجموعهٔ موتور واقعی را در CI با همان موتور و نسخهٔ production اجرا کنید. سمت پیامرسانی: Testing Messaging.
نگاه هر زبان و فریمورک
ستون «الگوی نزدیک» طبقهبندی خود ماست (از تعریف Fowler)؛ مستندات هر ابزار قابلیتها را توصیف میکنند، نه نام الگو را.
| ابزار | الگوی نزدیک | Unit of Work | Identity Map | Lazy loading | Optimistic lock | Soft delete | منبع |
|---|---|---|---|---|---|---|---|
| Eloquent (Laravel 13) | Active Record | ردیابی ندارد؛ save() برای هر مدل، DB::transaction را خودتان میپیچید | ندارد | پیشفرض برای relation؛ preventLazyLoading() | داخلی نیست؛ where('version', $n) بنویسید | trait به نام SoftDeletes | مستندات Laravel |
| Doctrine ORM (PHP) | Data Mapper | بله، EntityManager، flush() | بله، "per PHP request" | در صفحههای خواندهشده پوشش داده نشده | در صفحههای خواندهشده پوشش داده نشده | در صفحههای خواندهشده پوشش داده نشده | مستندات Doctrine |
| GORM (Go) | شبیه Active Record (مدلها tag دارند؛ خودتان تصمیم میگیرید بپیچید یا نه) | db.Transaction(func(tx *gorm.DB) error)؛ نوشتنها در تراکنش ضمنی اجرا میشوند | ندارد | ندارد؛ Preload برای eager | در هسته نیست؛ Where("version = ?") | gorm.DeletedAt | مستندات GORM |
| sqlc (Go) | Table Data Gateway روی SQL تولیدشده | Queries.WithTx(tx) | ندارد | هیچ: هر query را خودتان مینویسید | WHERE version دستی با :execrows | deleted_at IS NULL دستی | مستندات sqlc |
| ent (Go) | گراف entity تولیدشده با client | صفحهٔ transactions دارد (بهتفصیل نخواندیم) | ندارد | edgeهای eager به شکل WithX() | در بخش خواندهشده نیست | در بخش خواندهشده نیست | مستندات ent |
database/sql و pgx (Go) | gateway خام | BeginTx، *sql.Tx | ندارد | هیچ | دستی | دستی | مستندات database/sql |
Query builder (DB::table) | Table Data Gateway، ردیفها stdClass | DB::transaction | ندارد | هیچ | دستی | دستی | مستندات Laravel |
| PostgreSQL، MySQL/InnoDB، SQL Server، Oracle | موتور ذخیرهسازی زیر همهٔ اینها | تراکنش، قفل، MVCC | n/a | n/a | ستون version خودتان | n/a | ببینید Databases |
| SQLite، MongoDB، Redis، CockroachDB | storeهای دیگری که adapter ممکن است هدف بگیرد | متفاوت (تراکنش چندسندی در MongoDB، serializable در CockroachDB) | n/a | n/a | MongoDB: فیلد version دستی | n/a | ببینید Databases |
مستندات GORM میگوید عملیات نوشتن "run inside a transaction to ensure data consistency, you can disable it during initialization". متد Save همهٔ فیلدها را مینویسد که منبع معمول lost update وقتی دو نویسنده همان رکورد را بارگذاری میکنند. مستندات ent دربارهٔ eager loading میگوید: "ent supports querying entities with their associations (through their edges)".
سازوکار (Mechanics)
Dirty checking و SQL ای که تولید میشود حیاتی
اینکه ابزار چطور تصمیم میگیرد چه چیزی بنویسد شکل خرابشدنش را تعیین میکند.
| ابزار | از کجا میداند چه عوض شده | SQL هنگام ذخیره | شکل خرابی |
|---|---|---|---|
| Eloquent | attributeها را با مقدار اصلی مقایسه میکند (isDirty()) | UPDATE ... SET ستونهای تغییرکرده | دو نویسنده روی ستونهای متفاوت هر دو موفق میشوند؛ ستون یکسان: آخری برنده |
| Doctrine | Unit of Work هنگام بارگذاری snapshot میگیرد و در flush() تفاضل میگیرد | یک دسته در یک تراکنش | unit of work بزرگ کند و پرمصرف حافظه است |
GORM Save | ردیابی ندارد؛ همهٔ فیلدها را مینویسد | UPDATE ... SET همهٔ ستونها | تغییر همزمان هر ستون را بازنویسی میکند |
GORM Updates با map یا struct | فقط فیلدهای دادهشده (برای struct غیرصفرها) | UPDATE ... SET همانها | با struct، مقدارهای صفر بیصدا نادیده گرفته میشوند |
| sqlc | شما statement را انتخاب میکنید | دقیقاً SQL شما | فراموشکردن یک ستون در UPDATE دستی |
| Repository با version | کل aggregate، یک version | UPDATE ... WHERE version و بازنویسی فرزندان | فرزندان حتی اگر تغییر نکردهاند بازنویسی میشوند (delete و insert) |
Same two edits, three tools (two admins, order o-1, status vs notes)
1 A: load o-1 (status=draft, notes='') B: load o-1 (status=draft, notes='')
2 A: status = placed; save B: notes = 'gift'; save
3 Eloquent save(): A writes status, B writes notes -> both survive (different columns), no version
4 GORM Save(&o): A writes all, B writes all -> B overwrites status back to draft
5 Version column: A ok (v1->v2), B conflict -> B reloads and retriesمکانیک تراکنش در لایهٔ object مهم
| دغدغه | Go (database/sql) | Laravel |
|---|---|---|
| Pool | sql.DB "a database handle representing a pool of zero or more underlying connections" و برای استفادهٔ همزمان امن است | یک اتصال برای هر request/worker؛ ببینید Connection Pooling |
| شروع | db.BeginTx(ctx, &sql.TxOptions{Isolation:..., ReadOnly:...}) | DB::transaction(fn, attempts) یا beginTransaction() |
| Commit/rollback | tx.Commit() / tx.Rollback()؛ بعد از هرکدام sql.ErrTxDone | خودکار با برگشت closure یا exception |
| Context | ctx query را لغو میکند و تراکنش باز را rollback میکند | timeout در سطح request، نه context |
| Retry | خودتان مینویسید (40001، 40P01) | آرگومان attempts:، در بخش «Handling Deadlocks» مستند است |
| تو در تو | همان *sql.Tx را پایین بدهید؛ nesting وجود ندارد | DB::transaction درون DB::transaction را Laravel بهصورت سطح تو در تو دنبال میکند (در صفحههای خواندهشده توضیح داده نشده؛ روی driver خودتان تست کنید) |
| بعد از commit | بعد از Commit() publisher را صدا میزنید | ShouldHandleEventsAfterCommit روی observer؛ ردیف outbox برای پیامها |
خطاهایی که repository نگاشت میکند مهم
| منبع | خطای خام | معنای دامنه | Retry؟ |
|---|---|---|---|
database/sql | sql.ErrNoRows | ErrNotFound | نه |
| Eloquent | ModelNotFoundException از findOrFail | OrderNotFound | نه |
| PostgreSQL | SQLSTATE 23505 unique_violation | AlreadyExists / تکراری بودن کسبوکاری | نه |
| PostgreSQL | SQLSTATE 23503 foreign_key_violation | ارجاع به aggregate ای که نیست | نه |
| PostgreSQL | SQLSTATE 40001 serialization_failure | کل unit of work را دوباره اجرا کنید | بله |
| PostgreSQL | SQLSTATE 40P01 deadlock_detected | کل unit of work را دوباره اجرا کنید | بله |
| MySQL/InnoDB | 1062 کلید تکراری، 1213 deadlock، 1205 lock wait timeout | مثل بالا | 1213 و 1205: بله |
| بررسی version | 0 ردیف تغییر کرد | ErrConflict / ConcurrencyConflict | بعد از reload |
کار repository این است که خطای موتور را به خطای دامنه ترجمه کند تا use caseها هرگز pgconn یا Illuminate\Database\QueryException را import نکنند. قواعد retry در Error & Exception Handling and Fault Tolerance و Deadlocks است.
knobهایی که رفتار ماندگاری را عوض میکنند تکمیلی
| Knob | ابزار | اثر |
|---|---|---|
Model::preventLazyLoading(! $this->app->isProduction()) | Eloquent | بیرون از production روی lazy load استثنا میدهد |
Model::preventSilentlyDiscardingAttributes() | Eloquent | وقتی attribute غیر fillable دور ریخته شود استثنا میدهد (در فهرست مستندات هست) |
DB::transaction($cb, attempts: 3) | Laravel | هنگام deadlock دوباره تلاش میکند |
SkipDefaultTransaction: true | gorm.Config در GORM | تراکنش ضمنی هر نوشتن را غیرفعال میکند ("30%+ performance improvement" طبق مستندات GORM) |
db.SetMaxOpenConns، SetMaxIdleConns | database/sql | اندازهٔ pool؛ ببینید Connection Pooling |
emit_interface، sql_package | sqlc.yaml در sqlc | interface به نام Querier تولید میکند، database/sql یا pgx را انتخاب میکند |
| Overrides | sqlc | نوع ستون را به نوع Go شما نگاشت میکند |
Go
قبل
یک Active Record که در Go با دست نوشته شده: Order ستونها، SQL و قاعدهٔ ثبت را میشناسد. کامپایل میشود و کار میکند. هزینهها: قاعده بدون *sql.DB اجرا نمیشود، caller نمیتواند تراکنش را انتخاب کند و نوع شبیه جدول شکل گرفته است.
// Package before is Active Record written by hand in Go: the Order type
// knows its table, its SQL and its business rules, all in one place.
package before
import (
"context"
"database/sql"
"errors"
)
// Order mirrors the orders table column by column.
type Order struct {
ID string
CustomerID string
Status string
TotalCents int64
Lines []Line
}
// Line mirrors the order_lines table.
type Line struct {
SKU string
Qty int
UnitCents int64
}
// Find loads one order and its lines.
func Find(ctx context.Context, db *sql.DB, id string) (*Order, error) {
o := &Order{ID: id}
err := db.QueryRowContext(ctx,
`SELECT customer_id, status, total_cents FROM orders WHERE id = $1`, id).
Scan(&o.CustomerID, &o.Status, &o.TotalCents)
if err != nil {
return nil, err
}
rows, err := db.QueryContext(ctx,
`SELECT sku, qty, unit_cents FROM order_lines WHERE order_id = $1 ORDER BY position`, id)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var l Line
if err := rows.Scan(&l.SKU, &l.Qty, &l.UnitCents); err != nil {
return nil, err
}
o.Lines = append(o.Lines, l)
}
return o, rows.Err()
}
// Place applies a business rule and writes to the database in the same
// method. The rule cannot be tested without a database, the SQL cannot be
// reused without the rule, and nothing says which transaction this runs in.
func (o *Order) Place(ctx context.Context, db *sql.DB) error {
if len(o.Lines) == 0 {
return errors.New("an order needs at least one line")
}
o.TotalCents = 0
for _, l := range o.Lines {
o.TotalCents += int64(l.Qty) * l.UnitCents
}
o.Status = "placed"
_, err := db.ExecContext(ctx,
`UPDATE orders SET status = $2, total_cents = $3 WHERE id = $1`,
o.ID, o.Status, o.TotalCents)
return err
}بعد
همان رفتار بهصورت aggregate پشت یک port. اول دامنه: هیچ import ای جز context، errors و fmt ندارد.
// Package domain holds the Order aggregate. It imports no database,
// no framework and no JSON package: this is persistence ignorance.
package domain
import (
"context"
"errors"
"fmt"
)
// OrderID is the identity of an order, assigned by the application.
type OrderID string
// Status is the order lifecycle.
type Status string
// The allowed statuses.
const (
Draft Status = "draft"
Placed Status = "placed"
Cancelled Status = "cancelled"
)
// Money is a value object: an amount in minor units plus a currency.
type Money struct {
Cents int64
Currency string
}
// Add returns the sum of two amounts in the same currency.
func (m Money) Add(o Money) (Money, error) {
if m.Currency != o.Currency {
return Money{}, fmt.Errorf("currency mismatch: %s vs %s", m.Currency, o.Currency)
}
return Money{Cents: m.Cents + o.Cents, Currency: m.Currency}, nil
}
// Line is one entry of an order. It has no identity outside its order.
type Line struct {
SKU string
Qty int
UnitCents int64
}
// Order is the aggregate root. Lines are reachable only through it.
type Order struct {
id OrderID
customerID string
currency string
status Status
lines []Line
version int64
}
// NewOrder starts a draft order. Version 0 means "never stored".
func NewOrder(id OrderID, customerID, currency string) (*Order, error) {
if id == "" || customerID == "" {
return nil, errors.New("id and customer are required")
}
return &Order{id: id, customerID: customerID, currency: currency, status: Draft}, nil
}
// Rehydrate rebuilds an order from stored state. Only repositories call it.
// It skips the business rules on purpose: stored data was valid when written.
func Rehydrate(id OrderID, customerID, currency string, status Status, lines []Line, version int64) *Order {
return &Order{id: id, customerID: customerID, currency: currency, status: status,
lines: append([]Line(nil), lines...), version: version}
}
// ID returns the identity.
func (o *Order) ID() OrderID { return o.id }
// CustomerID returns the owning customer.
func (o *Order) CustomerID() string { return o.customerID }
// Currency returns the order currency.
func (o *Order) Currency() string { return o.currency }
// Status returns the lifecycle state.
func (o *Order) Status() Status { return o.status }
// Version returns the version this object was loaded or last saved at.
func (o *Order) Version() int64 { return o.version }
// Lines returns a copy so callers cannot bypass the root.
func (o *Order) Lines() []Line { return append([]Line(nil), o.lines...) }
// AcceptVersion is called by a repository after a successful write.
func (o *Order) AcceptVersion(v int64) { o.version = v }
// AddLine adds a line while the order is a draft.
func (o *Order) AddLine(sku string, qty int, unitCents int64) error {
if o.status != Draft {
return fmt.Errorf("cannot change a %s order", o.status)
}
if qty <= 0 || unitCents < 0 {
return errors.New("quantity must be positive and price non-negative")
}
o.lines = append(o.lines, Line{SKU: sku, Qty: qty, UnitCents: unitCents})
return nil
}
// Place moves a draft order to placed. An order needs at least one line.
func (o *Order) Place() error {
if o.status != Draft {
return fmt.Errorf("cannot place a %s order", o.status)
}
if len(o.lines) == 0 {
return errors.New("an order needs at least one line")
}
o.status = Placed
return nil
}
// Total sums the lines.
func (o *Order) Total() Money {
var cents int64
for _, l := range o.lines {
cents += int64(l.Qty) * l.UnitCents
}
return Money{Cents: cents, Currency: o.currency}
}
// Errors every repository implementation must return.
var (
ErrNotFound = errors.New("order not found")
ErrConflict = errors.New("order was changed by someone else")
)
// Repository is the collection-like port of the Order aggregate. It is
// defined next to the domain; adapters implement it elsewhere.
type Repository interface {
// Add stores a new order (version 0). It sets the version to 1.
Add(ctx context.Context, o *Order) error
// Get loads the whole aggregate or returns ErrNotFound.
Get(ctx context.Context, id OrderID) (*Order, error)
// Save writes changes if the stored version still equals o.Version();
// otherwise it returns ErrConflict.
Save(ctx context.Context, o *Order) error
}use case مالک مرز تراکنش (UnitOfWork) است و فقط با port حرف میزند.
// Package app holds use cases. It owns the transaction boundary.
package app
import (
"context"
"academy/data-persistence-design/after/domain"
)
// UnitOfWork runs fn in one transaction. Everything fn does through the
// repository it receives commits together or not at all.
type UnitOfWork interface {
Do(ctx context.Context, fn func(ctx context.Context, orders domain.Repository) error) error
}
// PlaceOrder is one use case: load, call the domain, save, in one unit of work.
type PlaceOrder struct {
UoW UnitOfWork
}
// Handle places the order with the given id.
func (p PlaceOrder) Handle(ctx context.Context, id domain.OrderID) error {
return p.UoW.Do(ctx, func(ctx context.Context, orders domain.Repository) error {
o, err := orders.Get(ctx, id)
if err != nil {
return err
}
if err := o.Place(); err != nil {
return err
}
return orders.Save(ctx, o)
})
}adapter مبتنی بر SQL. queryها در query.sql هستند، کد تایپدار به شکل خروجی sqlc نوشته شده (sqlc را اینجا اجرا نکردیم؛ هدر فایل همین را میگوید) و repository ردیفها را به aggregate نگاشت میکند.
-- PostgreSQL. The aggregate is two tables: the root row and its lines.
CREATE TABLE IF NOT EXISTS orders (
id text PRIMARY KEY,
customer_id text NOT NULL,
currency char(3) NOT NULL,
status text NOT NULL CHECK (status IN ('draft', 'placed', 'cancelled')),
version bigint NOT NULL DEFAULT 1,
deleted_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS order_lines (
order_id text NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
position int NOT NULL,
sku text NOT NULL,
qty int NOT NULL CHECK (qty > 0),
unit_cents bigint NOT NULL CHECK (unit_cents >= 0),
PRIMARY KEY (order_id, position)
);
CREATE INDEX IF NOT EXISTS orders_customer_idx ON orders (customer_id) WHERE deleted_at IS NULL;-- name: GetOrder :one
SELECT id, customer_id, currency, status, version
FROM orders
WHERE id = $1 AND deleted_at IS NULL;
-- name: ListLines :many
SELECT order_id, position, sku, qty, unit_cents
FROM order_lines
WHERE order_id = $1
ORDER BY position;
-- name: InsertOrder :exec
INSERT INTO orders (id, customer_id, currency, status)
VALUES ($1, $2, $3, $4);
-- name: InsertLine :exec
INSERT INTO order_lines (order_id, position, sku, qty, unit_cents)
VALUES ($1, $2, $3, $4, $5);
-- name: DeleteLines :exec
DELETE FROM order_lines WHERE order_id = $1;
-- Optimistic lock: the WHERE clause carries the version the caller read.
-- :execrows returns the affected row count; 0 means someone else won.
-- name: UpdateOrderVersioned :execrows
UPDATE orders
SET status = $2, version = version + 1, updated_at = now()
WHERE id = $1 AND version = $3 AND deleted_at IS NULL;
-- Read model: no aggregate, no lines, one row per order.
-- name: ListOrderSummaries :many
SELECT o.id, o.status, o.currency,
COALESCE(SUM(l.qty * l.unit_cents), 0)::bigint AS total_cents,
COUNT(l.position)::int AS line_count
FROM orders o
LEFT JOIN order_lines l ON l.order_id = o.id
WHERE o.customer_id = $1 AND o.deleted_at IS NULL
GROUP BY o.id
ORDER BY o.created_at DESC
LIMIT $2;version: "2"
sql:
- engine: "postgresql"
schema: "schema.sql"
queries: "query.sql"
gen:
go:
package: "db"
out: "db"
sql_package: "database/sql"// Code in the shape that `sqlc generate` produces (sqlc was not run for this
// page; regenerate with the sqlc.yaml next to it and compare).
package db
import (
"context"
"database/sql"
)
// DBTX is satisfied by both *sql.DB and *sql.Tx.
type DBTX interface {
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
PrepareContext(context.Context, string) (*sql.Stmt, error)
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
QueryRowContext(context.Context, string, ...interface{}) *sql.Row
}
// New wraps a connection or a transaction.
func New(db DBTX) *Queries { return &Queries{db: db} }
// Queries holds one method per named query.
type Queries struct {
db DBTX
}
// WithTx returns Queries bound to a transaction.
func (q *Queries) WithTx(tx *sql.Tx) *Queries { return &Queries{db: tx} }package db
import "context"
const getOrder = `SELECT id, customer_id, currency, status, version
FROM orders
WHERE id = $1 AND deleted_at IS NULL`
// GetOrder returns the root row.
func (q *Queries) GetOrder(ctx context.Context, id string) (Order, error) {
row := q.db.QueryRowContext(ctx, getOrder, id)
var i Order
err := row.Scan(&i.ID, &i.CustomerID, &i.Currency, &i.Status, &i.Version)
return i, err
}
const listLines = `SELECT order_id, position, sku, qty, unit_cents
FROM order_lines
WHERE order_id = $1
ORDER BY position`
// ListLines returns the lines of one order.
func (q *Queries) ListLines(ctx context.Context, orderID string) ([]OrderLine, error) {
rows, err := q.db.QueryContext(ctx, listLines, orderID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []OrderLine
for rows.Next() {
var i OrderLine
if err := rows.Scan(&i.OrderID, &i.Position, &i.Sku, &i.Qty, &i.UnitCents); err != nil {
return nil, err
}
items = append(items, i)
}
return items, rows.Err()
}
const insertOrder = `INSERT INTO orders (id, customer_id, currency, status)
VALUES ($1, $2, $3, $4)`
// InsertOrderParams are the arguments of InsertOrder.
type InsertOrderParams struct {
ID string
CustomerID string
Currency string
Status string
}
// InsertOrder inserts the root row.
func (q *Queries) InsertOrder(ctx context.Context, arg InsertOrderParams) error {
_, err := q.db.ExecContext(ctx, insertOrder, arg.ID, arg.CustomerID, arg.Currency, arg.Status)
return err
}
const insertLine = `INSERT INTO order_lines (order_id, position, sku, qty, unit_cents)
VALUES ($1, $2, $3, $4, $5)`
// InsertLineParams are the arguments of InsertLine.
type InsertLineParams struct {
OrderID string
Position int32
Sku string
Qty int32
UnitCents int64
}
// InsertLine inserts one line.
func (q *Queries) InsertLine(ctx context.Context, arg InsertLineParams) error {
_, err := q.db.ExecContext(ctx, insertLine, arg.OrderID, arg.Position, arg.Sku, arg.Qty, arg.UnitCents)
return err
}
const deleteLines = `DELETE FROM order_lines WHERE order_id = $1`
// DeleteLines removes every line of one order.
func (q *Queries) DeleteLines(ctx context.Context, orderID string) error {
_, err := q.db.ExecContext(ctx, deleteLines, orderID)
return err
}
const updateOrderVersioned = `UPDATE orders
SET status = $2, version = version + 1, updated_at = now()
WHERE id = $1 AND version = $3 AND deleted_at IS NULL`
// UpdateOrderVersionedParams are the arguments of UpdateOrderVersioned.
type UpdateOrderVersionedParams struct {
ID string
Status string
Version int64
}
// UpdateOrderVersioned returns the number of rows changed (0 or 1).
func (q *Queries) UpdateOrderVersioned(ctx context.Context, arg UpdateOrderVersionedParams) (int64, error) {
result, err := q.db.ExecContext(ctx, updateOrderVersioned, arg.ID, arg.Status, arg.Version)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
const listOrderSummaries = `SELECT o.id, o.status, o.currency,
COALESCE(SUM(l.qty * l.unit_cents), 0)::bigint AS total_cents,
COUNT(l.position)::int AS line_count
FROM orders o
LEFT JOIN order_lines l ON l.order_id = o.id
WHERE o.customer_id = $1 AND o.deleted_at IS NULL
GROUP BY o.id
ORDER BY o.created_at DESC
LIMIT $2`
// ListOrderSummariesParams are the arguments of ListOrderSummaries.
type ListOrderSummariesParams struct {
CustomerID string
Limit int32
}
// ListOrderSummariesRow is one row of the read model.
type ListOrderSummariesRow struct {
ID string
Status string
Currency string
TotalCents int64
LineCount int32
}
// ListOrderSummaries returns one row per order, newest first.
func (q *Queries) ListOrderSummaries(ctx context.Context, arg ListOrderSummariesParams) ([]ListOrderSummariesRow, error) {
rows, err := q.db.QueryContext(ctx, listOrderSummaries, arg.CustomerID, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListOrderSummariesRow
for rows.Next() {
var i ListOrderSummariesRow
if err := rows.Scan(&i.ID, &i.Status, &i.Currency, &i.TotalCents, &i.LineCount); err != nil {
return nil, err
}
items = append(items, i)
}
return items, rows.Err()
}// Package sqlcrepo is the SQL adapter of domain.Repository: it maps the
// aggregate to two tables with queries written in SQL and typed by sqlc.
package sqlcrepo
import (
"context"
"database/sql"
"errors"
"academy/data-persistence-design/after/app"
"academy/data-persistence-design/after/domain"
"academy/data-persistence-design/after/readmodel"
"academy/data-persistence-design/after/sqlcrepo/db"
)
// Repo implements domain.Repository and readmodel.Reader.
type Repo struct{ q *db.Queries }
var (
_ domain.Repository = (*Repo)(nil)
_ readmodel.Reader = (*Repo)(nil)
)
// New builds a repository on a connection or on a transaction.
func New(q *db.Queries) *Repo { return &Repo{q: q} }
// Add inserts the root and its lines.
func (r *Repo) Add(ctx context.Context, o *domain.Order) error {
err := r.q.InsertOrder(ctx, db.InsertOrderParams{
ID: string(o.ID()), CustomerID: o.CustomerID(), Currency: o.Currency(), Status: string(o.Status()),
})
if err != nil {
return err
}
if err := r.writeLines(ctx, o); err != nil {
return err
}
o.AcceptVersion(1)
return nil
}
// Get loads the root and its lines, then rebuilds the aggregate.
func (r *Repo) Get(ctx context.Context, id domain.OrderID) (*domain.Order, error) {
row, err := r.q.GetOrder(ctx, string(id))
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrNotFound
}
if err != nil {
return nil, err
}
rows, err := r.q.ListLines(ctx, row.ID)
if err != nil {
return nil, err
}
lines := make([]domain.Line, 0, len(rows))
for _, l := range rows {
lines = append(lines, domain.Line{SKU: l.Sku, Qty: int(l.Qty), UnitCents: l.UnitCents})
}
return domain.Rehydrate(domain.OrderID(row.ID), row.CustomerID, row.Currency,
domain.Status(row.Status), lines, row.Version), nil
}
// Save is an optimistic write: zero affected rows means a newer version exists.
func (r *Repo) Save(ctx context.Context, o *domain.Order) error {
n, err := r.q.UpdateOrderVersioned(ctx, db.UpdateOrderVersionedParams{
ID: string(o.ID()), Status: string(o.Status()), Version: o.Version(),
})
if err != nil {
return err
}
if n == 0 {
return domain.ErrConflict
}
if err := r.q.DeleteLines(ctx, string(o.ID())); err != nil {
return err
}
if err := r.writeLines(ctx, o); err != nil {
return err
}
o.AcceptVersion(o.Version() + 1)
return nil
}
func (r *Repo) writeLines(ctx context.Context, o *domain.Order) error {
for i, l := range o.Lines() {
err := r.q.InsertLine(ctx, db.InsertLineParams{
OrderID: string(o.ID()), Position: int32(i), Sku: l.SKU, Qty: int32(l.Qty), UnitCents: l.UnitCents,
})
if err != nil {
return err
}
}
return nil
}
// ForCustomer is the read side: it never builds an aggregate.
func (r *Repo) ForCustomer(ctx context.Context, customerID string, limit int) ([]readmodel.OrderSummary, error) {
rows, err := r.q.ListOrderSummaries(ctx, db.ListOrderSummariesParams{CustomerID: customerID, Limit: int32(limit)})
if err != nil {
return nil, err
}
out := make([]readmodel.OrderSummary, 0, len(rows))
for _, s := range rows {
out = append(out, readmodel.OrderSummary{
ID: s.ID, Status: s.Status, Currency: s.Currency, TotalCents: s.TotalCents, LineCount: int(s.LineCount),
})
}
return out, nil
}
// UoW opens a database transaction per unit of work and hands the use case a
// repository bound to it.
type UoW struct {
DB *sql.DB
Q *db.Queries
}
var _ app.UnitOfWork = UoW{}
// Do implements app.UnitOfWork.
func (u UoW) Do(ctx context.Context, fn func(context.Context, domain.Repository) error) error {
tx, err := u.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
if err := fn(ctx, New(u.Q.WithTx(tx))); err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}همان port با GORM. مقایسه کنید بررسی version، eager loading و soft delete وقتی ابزار یک ORM است چه شکلی میشوند.
// Package gormrepo is the same adapter written with GORM. Compare it with
// package sqlcrepo: the port (domain.Repository) is identical.
package gormrepo
import (
"context"
"errors"
"gorm.io/gorm"
"academy/data-persistence-design/after/domain"
)
// orderRow and lineRow are persistence models. They carry GORM tags, the
// domain type does not.
type orderRow struct {
ID string `gorm:"primaryKey"`
CustomerID string
Currency string
Status string
Version int64
DeletedAt gorm.DeletedAt // soft delete: Delete sets it, queries skip it
Lines []lineRow `gorm:"foreignKey:OrderID;references:ID"`
}
func (orderRow) TableName() string { return "orders" }
type lineRow struct {
OrderID string `gorm:"primaryKey"`
Position int `gorm:"primaryKey;autoIncrement:false"`
SKU string
Qty int
UnitCents int64
}
func (lineRow) TableName() string { return "order_lines" }
// Repo implements domain.Repository on top of *gorm.DB.
type Repo struct{ db *gorm.DB }
var _ domain.Repository = (*Repo)(nil)
// New builds a repository. Pass a transaction handle to join a transaction.
func New(db *gorm.DB) *Repo { return &Repo{db: db} }
// Add inserts the root and its lines in one call (GORM saves associations).
func (r *Repo) Add(ctx context.Context, o *domain.Order) error {
row := toRow(o)
row.Version = 1
if err := r.db.WithContext(ctx).Create(&row).Error; err != nil {
return err
}
o.AcceptVersion(1)
return nil
}
// Get uses Preload, an explicit eager load of the aggregate's lines.
func (r *Repo) Get(ctx context.Context, id domain.OrderID) (*domain.Order, error) {
var row orderRow
err := r.db.WithContext(ctx).Preload("Lines", func(tx *gorm.DB) *gorm.DB {
return tx.Order("position")
}).First(&row, "id = ?", string(id)).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, domain.ErrNotFound
}
if err != nil {
return nil, err
}
lines := make([]domain.Line, 0, len(row.Lines))
for _, l := range row.Lines {
lines = append(lines, domain.Line{SKU: l.SKU, Qty: l.Qty, UnitCents: l.UnitCents})
}
return domain.Rehydrate(domain.OrderID(row.ID), row.CustomerID, row.Currency,
domain.Status(row.Status), lines, row.Version), nil
}
// Save does the optimistic check by hand: GORM has no version column feature
// in core, so the WHERE clause and RowsAffected are ours.
func (r *Repo) Save(ctx context.Context, o *domain.Order) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
res := tx.Model(&orderRow{}).
Where("id = ? AND version = ?", string(o.ID()), o.Version()).
Updates(map[string]any{"status": string(o.Status()), "version": o.Version() + 1})
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return domain.ErrConflict
}
if err := tx.Where("order_id = ?", string(o.ID())).Delete(&lineRow{}).Error; err != nil {
return err
}
if lines := toRow(o).Lines; len(lines) > 0 {
if err := tx.Create(&lines).Error; err != nil {
return err
}
}
o.AcceptVersion(o.Version() + 1)
return nil
})
}
func toRow(o *domain.Order) orderRow {
row := orderRow{ID: string(o.ID()), CustomerID: o.CustomerID(), Currency: o.Currency(),
Status: string(o.Status()), Version: o.Version()}
for i, l := range o.Lines() {
row.Lines = append(row.Lines, lineRow{OrderID: row.ID, Position: i, SKU: l.SKU, Qty: l.Qty, UnitCents: l.UnitCents})
}
return row
}سمت خواندن DTO برمیگرداند و هرگز aggregate نمیسازد.
// Package readmodel holds query-side shapes. They are plain data: no
// behaviour, no invariants, no link to the aggregate.
package readmodel
import "context"
// OrderSummary is the DTO a list screen or an API response needs.
type OrderSummary struct {
ID string `json:"id"`
Status string `json:"status"`
Currency string `json:"currency"`
TotalCents int64 `json:"total_cents"`
LineCount int `json:"line_count"`
}
// Reader is the query port. It is separate from domain.Repository on purpose.
type Reader interface {
ForCustomer(ctx context.Context, customerID string, limit int) ([]OrderSummary, error)
}نگاشت مقدار از مرز database/sql.
// Package valuer shows how a value object, an enum and a JSON column cross
// the database/sql boundary: driver.Valuer writes, sql.Scanner reads.
package valuer
import (
"database/sql/driver"
"encoding/json"
"fmt"
)
// Address is a value object stored in one jsonb column.
type Address struct {
Street string `json:"street"`
City string `json:"city"`
Postal string `json:"postal"`
}
// Value implements driver.Valuer.
func (a Address) Value() (driver.Value, error) { return json.Marshal(a) }
// Scan implements sql.Scanner.
func (a *Address) Scan(src any) error {
switch v := src.(type) {
case []byte:
return json.Unmarshal(v, a)
case string:
return json.Unmarshal([]byte(v), a)
case nil:
*a = Address{}
return nil
default:
return fmt.Errorf("address: cannot scan %T", src)
}
}
// Status is a closed enum that refuses unknown database values.
type Status string
// The allowed statuses.
const (
Draft Status = "draft"
Placed Status = "placed"
)
// Value implements driver.Valuer and rejects invalid values before the write.
func (s Status) Value() (driver.Value, error) {
if s != Draft && s != Placed {
return nil, fmt.Errorf("status: invalid value %q", string(s))
}
return string(s), nil
}
// Scan implements sql.Scanner and rejects invalid values after the read.
func (s *Status) Scan(src any) error {
var raw string
switch v := src.(type) {
case string:
raw = v
case []byte:
raw = string(v)
default:
return fmt.Errorf("status: cannot scan %T", src)
}
if st := Status(raw); st == Draft || st == Placed {
*s = st
return nil
}
return fmt.Errorf("status: unknown value %q in database", raw)
}fake درونحافظه، با همان بررسی version و rollback مبتنی بر snapshot.
// Package memrepo is the in-memory fake of domain.Repository, used by fast tests.
package memrepo
import (
"context"
"sync"
"academy/data-persistence-design/after/app"
"academy/data-persistence-design/after/domain"
)
type stored struct {
customerID, currency string
status domain.Status
lines []domain.Line
version int64
}
// Repo keeps copies, never the caller's pointer, like a real database would.
type Repo struct {
mu sync.Mutex
rows map[domain.OrderID]stored
}
// New returns an empty fake.
func New() *Repo { return &Repo{rows: map[domain.OrderID]stored{}} }
// Add implements domain.Repository.
func (r *Repo) Add(_ context.Context, o *domain.Order) error {
r.mu.Lock()
defer r.mu.Unlock()
r.rows[o.ID()] = stored{o.CustomerID(), o.Currency(), o.Status(), o.Lines(), 1}
o.AcceptVersion(1)
return nil
}
// Get implements domain.Repository.
func (r *Repo) Get(_ context.Context, id domain.OrderID) (*domain.Order, error) {
r.mu.Lock()
defer r.mu.Unlock()
s, ok := r.rows[id]
if !ok {
return nil, domain.ErrNotFound
}
return domain.Rehydrate(id, s.customerID, s.currency, s.status, s.lines, s.version), nil
}
// Save implements domain.Repository with the same version check as SQL.
func (r *Repo) Save(_ context.Context, o *domain.Order) error {
r.mu.Lock()
defer r.mu.Unlock()
s, ok := r.rows[o.ID()]
if !ok {
return domain.ErrNotFound
}
if s.version != o.Version() {
return domain.ErrConflict
}
s.status, s.lines, s.version = o.Status(), o.Lines(), s.version+1
r.rows[o.ID()] = s
o.AcceptVersion(s.version)
return nil
}
// UoW is a fake unit of work: it snapshots the rows and restores them on error.
type UoW struct{ Repo *Repo }
var _ app.UnitOfWork = UoW{}
// Do implements app.UnitOfWork.
func (u UoW) Do(ctx context.Context, fn func(context.Context, domain.Repository) error) error {
u.Repo.mu.Lock()
snapshot := make(map[domain.OrderID]stored, len(u.Repo.rows))
for k, v := range u.Repo.rows {
snapshot[k] = v
}
u.Repo.mu.Unlock()
if err := fn(ctx, u.Repo); err != nil {
u.Repo.mu.Lock()
u.Repo.rows = snapshot
u.Repo.mu.Unlock()
return err
}
return nil
}قراردادی که هر پیادهسازی باید بگذراند، و اینکه چطور به fake و PostgreSQL وصل میشود.
// Package contract is a test suite every domain.Repository must pass. The
// in-memory fake and the SQL adapters run the same checks, so the fake
// cannot drift from the real thing.
package contract
import (
"context"
"errors"
"testing"
"academy/data-persistence-design/after/domain"
)
// Run executes the contract against repositories made by newRepo.
func Run(t *testing.T, newRepo func(t *testing.T) domain.Repository) {
ctx := context.Background()
t.Run("round trip keeps the whole aggregate", func(t *testing.T) {
repo := newRepo(t)
o, _ := domain.NewOrder("o-1", "c-1", "USD")
_ = o.AddLine("sku-1", 2, 500)
_ = o.AddLine("sku-2", 1, 250)
if err := repo.Add(ctx, o); err != nil {
t.Fatal(err)
}
got, err := repo.Get(ctx, "o-1")
if err != nil {
t.Fatal(err)
}
if got.Total().Cents != 1250 || len(got.Lines()) != 2 || got.Version() != 1 {
t.Fatalf("unexpected aggregate: total=%d lines=%d version=%d",
got.Total().Cents, len(got.Lines()), got.Version())
}
})
t.Run("missing order is ErrNotFound", func(t *testing.T) {
if _, err := newRepo(t).Get(ctx, "nope"); !errors.Is(err, domain.ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound", err)
}
})
t.Run("second writer gets ErrConflict", func(t *testing.T) {
repo := newRepo(t)
o, _ := domain.NewOrder("o-2", "c-1", "USD")
_ = o.AddLine("sku-1", 1, 100)
_ = repo.Add(ctx, o)
a, _ := repo.Get(ctx, "o-2")
b, _ := repo.Get(ctx, "o-2")
_ = a.Place()
_ = b.Place()
if err := repo.Save(ctx, a); err != nil {
t.Fatal(err)
}
if err := repo.Save(ctx, b); !errors.Is(err, domain.ErrConflict) {
t.Fatalf("err = %v, want ErrConflict", err)
}
})
}package sqlcrepo_test
import (
"database/sql"
"os"
"testing"
_ "github.com/jackc/pgx/v5/stdlib"
"academy/data-persistence-design/after/contract"
"academy/data-persistence-design/after/domain"
"academy/data-persistence-design/after/sqlcrepo"
"academy/data-persistence-design/after/sqlcrepo/db"
_ "embed"
)
//go:embed schema.sql
var schema string
// TestContract runs the shared contract against PostgreSQL. Every subtest runs
// inside one transaction that is rolled back, so nothing is left behind.
// Run: DATABASE_URL=postgres://... go test ./after/sqlcrepo
func TestContract(t *testing.T) {
url := os.Getenv("DATABASE_URL")
if url == "" {
t.Skip("DATABASE_URL not set")
}
conn, err := sql.Open("pgx", url)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
contract.Run(t, func(t *testing.T) domain.Repository {
tx, err := conn.Begin()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = tx.Rollback() })
if _, err := tx.Exec(schema); err != nil {
t.Fatal(err)
}
return sqlcrepo.New(db.New(tx))
})
}زاویهٔ Go
pool همان اتصال است. sql.DB یک pool است و برای استفادهٔ همزمان امن؛ پس repositoryها یک *sql.DB یا DBTX نگه میدارند، نه یک اتصال تکی. تراکنش یک اتصال را قفل میکند و برای همین دستگیرهٔ تراکنش باید پایین فرستاده شود (WithTx در sqlc، tx *gorm.DB در GORM) و از یک متغیر سراسری خوانده نشود.
DBTX درزی است که همهچیز را وصل میکند. interface تولیدشدهٔ DBTX در sqlc هم با *sql.DB و هم با *sql.Tx سازگار است. به همین دلیل یک repository میتواند با همان کد هم مستقل و هم داخل unit of work کار کند.
sqlc، GORM، ent: سه پاسخ به یک پرسش.
| پرسش | sqlc | GORM | ent |
|---|---|---|---|
| SQL کجاست؟ | در فایلهای .sql که شما مینویسید | کتابخانه از زنجیرهٔ متدها تولیدش میکند | کتابخانه از گراف schema تولیدش میکند |
| نوع مدل چیست؟ | struct تولیدشده برای هر query/جدول | struct خودتان با tag | entityهای تولیدشده |
| بررسی زمان کامپایل | queryها هنگام generate با schema بررسی میشوند | کم؛ خطا در زمان اجرا | قوی: predicateهای تایپدار |
| Eager loading | join یا query دوم را مینویسید | Preload | edgeهای WithX |
| نوعهای مقدار | override در sqlc.yaml | Scanner/Valuer | نوع فیلد و نوعهای Go سفارشی |
| بهترین برای | سرویس query-محور که SQL دیدنی میخواهد | CRUD سریع، مدلهای کوچک زیاد | دامنههای گرافی |
| ایزولهسازی دامنه | ردیف را به دامنه نگاشت میکنید | مدل را به دامنه نگاشت میکنید، یا مدل را دامنه میگیرید | entity را به دامنه نگاشت میکنید یا خودش را به کار میبرید |
توصیف خود sqlc: "You write SQL queries, you run sqlc to generate Go code that presents type-safe interfaces to those queries, you write application code that calls the methods sqlc generated." فرهنگ interfaceهای کوچک در Go یعنی port مربوط به repository دو سه متد است، همانجا که مصرف میشود تعریف میشود (Dependency Inversion) و adapter یک struct در package خودش است.
Laravel
قبل
Active Record به سبک Laravel: مدل enum خودش را cast میکند، relation را دارد، قاعدهاش را اجرا میکند و خودش را ذخیره میکند، و controller relationها را lazy پیمایش میکند.
<?php
declare(strict_types=1);
namespace App\Models;
use App\Enums\OrderStatus;
use App\Casts\MoneyCast;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
/**
* Active Record: one object = one row of `orders`. The model knows its table,
* its casts, its relations, its business rules AND how to save itself.
* For a CRUD-ish aggregate this is the shortest path; the cost shows up when
* rules grow and tests need the database.
*/
class Order extends Model
{
use SoftDeletes;
public $incrementing = false;
protected $keyType = 'string';
protected $guarded = [];
protected function casts(): array
{
return [
'status' => OrderStatus::class, // enum <-> string column
'total' => MoneyCast::class, // value object <-> two columns
'version' => 'integer',
];
}
public function lines(): HasMany
{
return $this->hasMany(OrderLine::class)->orderBy('position');
}
/** Business rule and persistence in one method. */
public function place(): void
{
if ($this->lines()->count() === 0) {
throw new \DomainException('An order needs at least one line.');
}
DB::transaction(function (): void {
$this->status = OrderStatus::Placed;
$this->save(); // UPDATE orders SET ... (whole dirty set)
});
}
}<?php
declare(strict_types=1);
namespace App\Casts;
use App\Domain\Money;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
/**
* Maps two columns (total_cents, currency) to one value object.
*
* @implements CastsAttributes<Money, Money>
*/
class MoneyCast implements CastsAttributes
{
public function get(Model $model, string $key, mixed $value, array $attributes): Money
{
return new Money((int) $attributes['total_cents'], (string) $attributes['currency']);
}
public function set(Model $model, string $key, mixed $value, array $attributes): array
{
if (! $value instanceof Money) {
throw new InvalidArgumentException('The given value is not a Money instance.');
}
return ['total_cents' => $value->cents, 'currency' => $value->currency];
}
}<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
class OrderController
{
/**
* The classic Active Record trap: the view model IS the table row, and
* `$order->lines` inside the loop lazy-loads one query per order (N+1).
*/
public function index(string $customerId): JsonResponse
{
$orders = Order::query()->where('customer_id', $customerId)->latest()->limit(50)->get();
return response()->json($orders->map(fn (Order $o) => [
'id' => $o->id,
'status' => $o->status->value,
'lines' => $o->lines->count(), // lazy load per row
]));
}
public function place(string $id): JsonResponse
{
Order::query()->findOrFail($id)->place();
return response()->json(['ok' => true]);
}
}بعد
aggregate یک class ساده PHP است. Eloquent به مدل ذخیرهسازی تنزل مییابد که فقط repository به آن دست میزند. migration ستون version و soft delete را دارد.
<?php
declare(strict_types=1);
namespace App\Domain;
/**
* The Order aggregate root. Plain PHP: no Eloquent, no facade, no framework
* import. That is persistence ignorance, and it is why this class can be
* tested with `new Order(...)` and nothing else.
*/
final class Order
{
/** @var list<array{sku: string, qty: int, unitCents: int}> */
private array $lines = [];
private int $version = 0;
public function __construct(
public readonly string $id,
public readonly string $customerId,
public readonly string $currency,
private OrderStatus $status = OrderStatus::Draft,
) {
}
/**
* Rebuild from stored state. Only repositories call this.
*
* @param list<array{sku: string, qty: int, unitCents: int}> $lines
*/
public static function rehydrate(
string $id,
string $customerId,
string $currency,
OrderStatus $status,
array $lines,
int $version,
): self {
$order = new self($id, $customerId, $currency, $status);
$order->lines = $lines;
$order->version = $version;
return $order;
}
public function status(): OrderStatus
{
return $this->status;
}
public function version(): int
{
return $this->version;
}
/** @return list<array{sku: string, qty: int, unitCents: int}> */
public function lines(): array
{
return $this->lines;
}
public function acceptVersion(int $version): void
{
$this->version = $version;
}
public function addLine(string $sku, int $qty, int $unitCents): void
{
if ($this->status !== OrderStatus::Draft) {
throw new \DomainException("Cannot change a {$this->status->value} order.");
}
if ($qty <= 0 || $unitCents < 0) {
throw new \DomainException('Quantity must be positive and price non-negative.');
}
$this->lines[] = ['sku' => $sku, 'qty' => $qty, 'unitCents' => $unitCents];
}
public function place(): void
{
if ($this->status !== OrderStatus::Draft) {
throw new \DomainException("Cannot place a {$this->status->value} order.");
}
if ($this->lines === []) {
throw new \DomainException('An order needs at least one line.');
}
$this->status = OrderStatus::Placed;
}
public function total(): Money
{
$cents = 0;
foreach ($this->lines as $line) {
$cents += $line['qty'] * $line['unitCents'];
}
return new Money($cents, $this->currency);
}
}<?php
declare(strict_types=1);
namespace App\Domain;
/** Value object: immutable, compared by value, no identity. */
final readonly class Money
{
public function __construct(public int $cents, public string $currency)
{
}
public function add(self $other): self
{
if ($other->currency !== $this->currency) {
throw new \DomainException("Currency mismatch: {$this->currency} vs {$other->currency}");
}
return new self($this->cents + $other->cents, $this->currency);
}
}<?php
declare(strict_types=1);
namespace App\Domain;
enum OrderStatus: string
{
case Draft = 'draft';
case Placed = 'placed';
case Cancelled = 'cancelled';
}<?php
declare(strict_types=1);
namespace App\Domain;
/** Collection-like port of the Order aggregate. Lives with the domain. */
interface OrderRepository
{
/** Store a new order (version 0); sets version 1. */
public function add(Order $order): void;
/** @throws OrderNotFound */
public function get(string $id): Order;
/**
* Write changes if the stored version still equals $order->version().
*
* @throws ConcurrencyConflict
*/
public function save(Order $order): void;
}<?php
declare(strict_types=1);
namespace App\Domain;
final class OrderNotFound extends \RuntimeException
{
public static function withId(string $id): self
{
return new self("Order {$id} not found.");
}
}<?php
declare(strict_types=1);
namespace App\Domain;
final class ConcurrencyConflict extends \RuntimeException
{
public static function forOrder(string $id): self
{
return new self("Order {$id} was changed by someone else.");
}
}<?php
declare(strict_types=1);
namespace App\Infrastructure;
use App\Domain\OrderStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Persistence model: an Eloquent class used ONLY inside the repository.
* Nothing outside Infrastructure imports it.
*/
class OrderRecord extends Model
{
use SoftDeletes;
protected $table = 'orders';
public $incrementing = false;
protected $keyType = 'string';
protected $guarded = [];
protected function casts(): array
{
return ['status' => OrderStatus::class, 'version' => 'integer'];
}
public function lines(): HasMany
{
return $this->hasMany(OrderLineRecord::class, 'order_id')->orderBy('position');
}
}<?php
declare(strict_types=1);
namespace App\Infrastructure;
use Illuminate\Database\Eloquent\Model;
class OrderLineRecord extends Model
{
protected $table = 'order_lines';
public $incrementing = false;
public $timestamps = false;
protected $guarded = [];
}<?php
declare(strict_types=1);
namespace App\Infrastructure;
use App\Domain\ConcurrencyConflict;
use App\Domain\Order;
use App\Domain\OrderNotFound;
use App\Domain\OrderRepository;
use Illuminate\Support\Facades\DB;
final class EloquentOrderRepository implements OrderRepository
{
public function add(Order $order): void
{
DB::transaction(function () use ($order): void {
OrderRecord::query()->create([
'id' => $order->id,
'customer_id' => $order->customerId,
'currency' => $order->currency,
'status' => $order->status(),
'version' => 1,
]);
$this->writeLines($order);
});
$order->acceptVersion(1);
}
public function get(string $id): Order
{
// with('lines') is an explicit eager load: two queries, never N+1.
$record = OrderRecord::query()->with('lines')->find($id);
if ($record === null) {
throw OrderNotFound::withId($id);
}
return Order::rehydrate(
$record->id,
$record->customer_id,
$record->currency,
$record->status,
$record->lines->map(fn (OrderLineRecord $l) => [
'sku' => $l->sku, 'qty' => (int) $l->qty, 'unitCents' => (int) $l->unit_cents,
])->all(),
$record->version,
);
}
/**
* Optimistic write. Eloquent has no built-in version column, so the check
* is ours: the UPDATE only matches when the version is still the one we read.
*/
public function save(Order $order): void
{
DB::transaction(function () use ($order): void {
$affected = OrderRecord::query()
->where('id', $order->id)
->where('version', $order->version())
->update(['status' => $order->status()->value, 'version' => $order->version() + 1]);
if ($affected === 0) {
throw ConcurrencyConflict::forOrder($order->id);
}
OrderLineRecord::query()->where('order_id', $order->id)->delete();
$this->writeLines($order);
});
$order->acceptVersion($order->version() + 1);
}
private function writeLines(Order $order): void
{
$rows = [];
foreach ($order->lines() as $position => $line) {
$rows[] = [
'order_id' => $order->id,
'position' => $position,
'sku' => $line['sku'],
'qty' => $line['qty'],
'unit_cents' => $line['unitCents'],
];
}
if ($rows !== []) {
OrderLineRecord::query()->insert($rows); // one multi-row INSERT
}
}
}<?php
declare(strict_types=1);
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('orders', function (Blueprint $table): void {
$table->string('id')->primary();
$table->string('customer_id')->index();
$table->char('currency', 3);
$table->string('status');
$table->unsignedBigInteger('version')->default(1); // optimistic lock
$table->softDeletes();
$table->timestamps();
});
Schema::create('order_lines', function (Blueprint $table): void {
$table->string('order_id');
$table->unsignedInteger('position');
$table->string('sku');
$table->unsignedInteger('qty');
$table->unsignedBigInteger('unit_cents');
$table->primary(['order_id', 'position']);
$table->foreign('order_id')->references('id')->on('orders')->cascadeOnDelete();
});
}
public function down(): void
{
Schema::dropIfExists('order_lines');
Schema::dropIfExists('orders');
}
};use case مالک تراکنش است، query مبتنی بر DTO صفحهٔ لیست را سرو میکند و provider تنها جایی است که adapter را نام میبرد.
<?php
declare(strict_types=1);
namespace App\Application;
use App\Domain\OrderRepository;
use Illuminate\Support\Facades\DB;
/** One use case = one transaction. The transaction boundary is chosen here. */
final class PlaceOrder
{
public function __construct(private readonly OrderRepository $orders)
{
}
public function handle(string $orderId): void
{
DB::transaction(function () use ($orderId): void {
$order = $this->orders->get($orderId);
$order->place();
$this->orders->save($order);
}, attempts: 1); // a ConcurrencyConflict is a business retry, not a deadlock retry
}
}<?php
declare(strict_types=1);
namespace App\Application;
/** Read model / DTO: data only, shaped for one screen or one API response. */
final readonly class OrderSummary
{
public function __construct(
public string $id,
public string $status,
public string $currency,
public int $totalCents,
public int $lineCount,
) {
}
}<?php
declare(strict_types=1);
namespace App\Application;
use Illuminate\Support\Facades\DB;
/** Query side: no aggregate, no Eloquent models, one grouped SQL statement. */
final class OrderSummaryQuery
{
/** @return list<OrderSummary> */
public function forCustomer(string $customerId, int $limit = 50): array
{
return DB::table('orders as o')
->leftJoin('order_lines as l', 'l.order_id', '=', 'o.id')
->where('o.customer_id', $customerId)
->whereNull('o.deleted_at')
->groupBy('o.id', 'o.status', 'o.currency', 'o.created_at')
->orderByDesc('o.created_at')
->limit($limit)
->selectRaw('o.id, o.status, o.currency, COALESCE(SUM(l.qty * l.unit_cents), 0) AS total_cents, COUNT(l.position) AS line_count')
->get()
->map(fn (object $r) => new OrderSummary(
$r->id, $r->status, $r->currency, (int) $r->total_cents, (int) $r->line_count,
))
->all();
}
}<?php
declare(strict_types=1);
namespace App\Providers;
use App\Domain\OrderRepository;
use App\Infrastructure\EloquentOrderRepository;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;
final class PersistenceServiceProvider extends ServiceProvider
{
public array $bindings = [
// The composition root: the only place that names the adapter.
OrderRepository::class => EloquentOrderRepository::class,
];
public function boot(): void
{
// Fail loudly in development when a relation is lazy loaded (N+1).
Model::preventLazyLoading(! $this->app->isProduction());
}
}تستها: aggregate خالص، fake، و یک contract که هم روی fake و هم روی دیتابیس واقعی اجرا میشود.
<?php
declare(strict_types=1);
namespace Tests\Unit;
use App\Domain\Order;
use App\Domain\OrderStatus;
use PHPUnit\Framework\TestCase;
/** The aggregate needs nothing but `new`. */
final class OrderTest extends TestCase
{
public function test_an_empty_order_cannot_be_placed(): void
{
$this->expectException(\DomainException::class);
(new Order('o-1', 'c-1', 'USD'))->place();
}
public function test_a_placed_order_is_frozen(): void
{
$order = new Order('o-1', 'c-1', 'USD');
$order->addLine('sku-1', 1, 100);
$order->place();
$this->assertSame(OrderStatus::Placed, $order->status());
$this->expectException(\DomainException::class);
$order->addLine('sku-2', 1, 100);
}
}<?php
declare(strict_types=1);
namespace Tests\Fakes;
use App\Domain\ConcurrencyConflict;
use App\Domain\Order;
use App\Domain\OrderNotFound;
use App\Domain\OrderRepository;
/** Fake for fast unit tests. It copies state in and out like a database. */
final class InMemoryOrderRepository implements OrderRepository
{
/** @var array<string, array{customerId: string, currency: string, status: \App\Domain\OrderStatus, lines: array, version: int}> */
private array $rows = [];
public function add(Order $order): void
{
$this->rows[$order->id] = $this->snapshot($order, 1);
$order->acceptVersion(1);
}
public function get(string $id): Order
{
$r = $this->rows[$id] ?? throw OrderNotFound::withId($id);
return Order::rehydrate($id, $r['customerId'], $r['currency'], $r['status'], $r['lines'], $r['version']);
}
public function save(Order $order): void
{
$stored = $this->rows[$order->id] ?? throw OrderNotFound::withId($order->id);
if ($stored['version'] !== $order->version()) {
throw ConcurrencyConflict::forOrder($order->id);
}
$this->rows[$order->id] = $this->snapshot($order, $stored['version'] + 1);
$order->acceptVersion($stored['version'] + 1);
}
private function snapshot(Order $o, int $version): array
{
return ['customerId' => $o->customerId, 'currency' => $o->currency,
'status' => $o->status(), 'lines' => $o->lines(), 'version' => $version];
}
}<?php
declare(strict_types=1);
namespace Tests\Contracts;
use App\Domain\ConcurrencyConflict;
use App\Domain\Order;
use App\Domain\OrderNotFound;
use App\Domain\OrderRepository;
/** Shared checks: the fake and the Eloquent adapter must both pass them. */
trait OrderRepositoryContract
{
abstract protected function repository(): OrderRepository;
public function test_round_trip_keeps_the_whole_aggregate(): void
{
$repo = $this->repository();
$order = new Order('o-1', 'c-1', 'USD');
$order->addLine('sku-1', 2, 500);
$order->addLine('sku-2', 1, 250);
$repo->add($order);
$loaded = $repo->get('o-1');
$this->assertSame(1250, $loaded->total()->cents);
$this->assertCount(2, $loaded->lines());
$this->assertSame(1, $loaded->version());
}
public function test_missing_order_throws(): void
{
$this->expectException(OrderNotFound::class);
$this->repository()->get('nope');
}
public function test_second_writer_gets_a_conflict(): void
{
$repo = $this->repository();
$order = new Order('o-2', 'c-1', 'USD');
$order->addLine('sku-1', 1, 100);
$repo->add($order);
$a = $repo->get('o-2');
$b = $repo->get('o-2');
$a->place();
$b->place();
$repo->save($a);
$this->expectException(ConcurrencyConflict::class);
$repo->save($b);
}
}<?php
declare(strict_types=1);
namespace Tests\Unit;
use App\Domain\OrderRepository;
use PHPUnit\Framework\TestCase;
use Tests\Contracts\OrderRepositoryContract;
use Tests\Fakes\InMemoryOrderRepository;
/** Plain PHPUnit: no framework boot, no database, milliseconds. */
final class InMemoryOrderRepositoryTest extends TestCase
{
use OrderRepositoryContract;
protected function repository(): OrderRepository
{
return new InMemoryOrderRepository();
}
}<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Domain\OrderRepository;
use App\Infrastructure\EloquentOrderRepository;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\Contracts\OrderRepositoryContract;
use Tests\TestCase;
/** Real database: the same contract, run against Eloquent and the migration. */
final class EloquentOrderRepositoryTest extends TestCase
{
use OrderRepositoryContract;
use RefreshDatabase;
protected function repository(): OrderRepository
{
return new EloquentOrderRepository();
}
}روی ماشین نویسنده PHP نصب نیست؛ این فایلها بازبینی شدهاند، اجرا نه. اولین php artisan test را بخشی از آزمایشگاه بدانید.
زاویهٔ Laravel
Eloquent ذاتاً Active Record است. توصیف Laravel: "each database table has a corresponding 'Model' that is used to interact with that table." مدل object ردیف جدول است، relationها متدهاییاند که builder برمیگردانند و save() attributeهای dirty را مینویسد.
castها لایهٔ نگاشتی هستند که از قبل دارید. متد casts() ستونها را به نوعهای PHP نگاشت میکند؛ enumهای پشتیباندار هدف cast درجهیکاند؛ کلاسهای CastsAttributes چند ستون را به یک value object نگاشت میکنند (get و set مقدار $attributes را میگیرند و MoneyCast به همین ترتیب دو ستون را میخواند)؛ AsArrayObject و castهای مشابه ستون JSON را نگاشت میکنند.
Lazy loading پیشفرض است و میتوانید ممنوعش کنید. محافظ مستند Laravel: Model::preventLazyLoading(! $this->app->isProduction()) را در boot یک service provider صدا بزنید تا در توسعه و CI هنگام lazy load یک relation استثنا بیاید و production به کارش ادامه دهد.
Event و observer منطق ماندگاری پنهاناند. eventهای مدل از save() و delete() فایر میشوند؛ مستندات Laravel میگوید در mass update از طریق Eloquent eventهای saving، saved، updating و updated "will not be fired"، پس کد ممیزی در observer میتواند نوشتنهای انبوه را از دست بدهد؛ ShouldHandleEventsAfterCommit روی observer اجرا را تا commit به تعویق میاندازد.
تراکنشها. DB::transaction(fn) با برگشت commit و با exception rollback میکند؛ آرگومان دوم اختیاری تعداد تلاشها هنگام deadlock است. قفلهای pessimistic (sharedLock()، lockForUpdate()) روی query builder مستندند و "it is recommended to wrap pessimistic locks within a transaction".
تست. RefreshDatabase ("will take care of this for you") دیتابیس را بین تستها بازنشانی میکند. برای تست سریع دامنه اصلاً Laravel را بالا نیاورید: از PHPUnit\Framework\TestCase ارث ببرید.
چیزهایی که Laravel نمیدهد: قفل خوشبینانه، identity map، unit of work ای که aggregateها را ردیابی کند، یا repository. هرکدام یک تصمیم است، نه قابلیت گمشده.
حل مسئلههای کلاسیک
| مسئله | راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|---|
| God model (Active Record با ۴۰ متد) | class دامنه یا Action استخراج کنید | قاعدهها را بیرون ببرید، مدل را مدل ذخیرهسازی نگه دارید | قاعدهها تستپذیر | نگاشت یا دو class |
| N+1 از lazy loading | Eager یا read model | with()، Preload، query با join | ۱ تا ۲ query | بارگذاری بیشازحد در استفادهٔ نابجا |
| Repository نشتی | فقط aggregate و خطای دامنه برگردانید | هیچ query builder در امضا نباشد | ذخیرهسازی قابلتعویض | کد repository بزرگتر میشود |
| Repository برای هر جدول | یکی برای هر ریشهٔ aggregate | جدولها را بر اساس invariant گروه کنید | portهای کمتر و معنادار | طراحی aggregate لازم است |
save() تغییر همزمان را بازنویسی میکند | ستون version | WHERE version = ?، ۰ ردیف یعنی conflict | lost update تشخیص داده میشود | مسیر retry |
| تراکنش در پنج جا باز میشود | Unit of Work در use case | یک closure، یک دستگیره | اتمیکبودن دیده میشود | پایینفرستادن دستگیره |
| تستهای کند که برای قاعده دیتابیس میخواهند | دامنهٔ persistence-ignorant و fake | new Order()، memrepo | میلیثانیه | تست contract برای صادق نگهداشتن fake |
| صفحهٔ لیست که aggregate بارگذاری میکند | read model با DTO | یک query گروهبندیشده | سریع و کوچک | شکل دومی که باید نگه داشت |
| دو سرویس یک جدول را به اشتراک دارند | مالکیت داده | API یا event، schema خودی | deployهای مستقل | eventual consistency |
| ردیفهای soft-delete نشت میکنند | فیلتر در repository | deleted_at IS NULL همهجا، unique index جزئی | یک قاعده | انضباط |
God model
مدل relation، scope، قاعده، accessor، اعلان و toArray شبیه HTTP دارد. بر اساس دلیل تغییر بشکنید (SRP): مدل ذخیرهسازی را نگه دارید، قاعدهها را به aggregate یا Action ببرید، نمایش را به API resource ببرید و اثرهای جانبی را به listenerهایی که بعد از commit فایر میشوند.
Repository نشتی
نشانهها: متدی Builder، *gorm.DB یا *sql.Rows برمیگرداند؛ callerها ->where() اضافه میکنند؛ findBy(array $criteria) نام ستون میگیرد.
// Leaky: the caller now depends on Eloquent and on column names.
public function query(): \Illuminate\Database\Eloquent\Builder;
// Honest: the question is in domain language, the answer is an aggregate.
/** @return list<Order> */
public function overdueFor(string $customerId, \DateTimeImmutable $now): array;N+1 و خویشاوندانش
تشخیص: Model::preventLazyLoading() در توسعه، شمارش query در تستها، pg_stat_statements در production (Database Observability). رفع در طراحی: aggregateها کامل بارگذاری میشوند، نمایش بین aggregateها از read model میآید. مکانیک و عملیات انبوه: ORM Pitfalls.
ذخیرهٔ کل aggregate در هر تغییر
repository ای که در هر save همهٔ خطوط را حذف و دوباره درج میکند درست است اما اسرافکار. اگر aggregateها بزرگاند، در repository تفاضل بگیرید (جدید درج، تغییرکرده بهروز، حذفشده پاک) یا اندازهٔ aggregate را بازنگری کنید. snippet وضوح را ترجیح داده است: خطوط کوچک و محدودند.
-- Diff-style write for large aggregates: only what changed.
INSERT INTO order_lines (order_id, position, sku, qty, unit_cents)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (order_id, position) DO UPDATE
SET sku = EXCLUDED.sku, qty = EXCLUDED.qty, unit_cents = EXCLUDED.unit_cents;
DELETE FROM order_lines WHERE order_id = $1 AND position >= $2; -- trim removed tailانتخاب: کدام طراحی ماندگاری
| وضعیت | پیشنهاد | تکنیک اضافه | دلیل |
|---|---|---|---|
| پنل ادمین CRUD، محتوا، تنظیمات | مستقیم Eloquent Active Record | preventLazyLoading، Form Request | ارزانترین انتخاب درست |
| قاعدهٔ غنی، پول، رزرو، دفتر کل | Aggregate و repository | ستون version، تست contract | قاعدهها تستپذیر، همزمانی صریح |
| سرویس Go پر از query | sqlc و repository نازک | queryهای read model، WithTx | SQL دیدنی و تایپدار |
| CRUD سریع در Go با جدولهای کوچک زیاد | مدلهای GORM | Preload، version دستی | کمترین boilerplate |
| گزارش، export، داشبورد | Read model / SQL view | DTO، صفحهبندی | بدون aggregate و قاعده |
| schema قدیمی که نمیشود عوضش کرد | Data Mapper با anti-corruption | تست نگاشت | دامنه تمیز میماند |
| چند تیم روی یک codebase | repository یا facade برای هر ماژول | schema برای هر ماژول، یک نویسنده برای هر جدول | مالکیت |
| میکروسرویس | Database per service | outbox، event، read model خودی | تغییر مستقل |
| import/export انبوه | Table Data Gateway / SQL مجموعهای | COPY، batch | object ردیفبهردیف کند است |
| نمونهٔ اولیه | هرچه سریعتر است، دور بیندازید | هیچ | برای ناشناخته طراحی نکنید |
Decision walk
1 Are there domain rules worth fast tests? no -> Active Record, stop
2 yes -> Is the storage shape close to the object? yes -> Active Record + Action classes, revisit later
3 no -> Aggregate + repository (Data Mapper)
4 Do screens read data the aggregates do not shape? yes -> add DTO read models
5 Will another team or service use this data? yes -> public contract (API/events), private tablesدر معماری: از یک پروسه تا سیستم توزیعشده
همان یک پرسش در هر اندازه تکرار میشود: این داده مال کیست و چه کسی اجازهٔ تغییرش را دارد؟
Monolith (مونولیت): یک پروسه، یک دیتابیس
چطور دیده میشود: مدلها و queryها داخل یک اپ؛ هر کدی به هر جدولی میرسد. خرابی پخش است: controllerها، jobها و viewها همه Order::where(...) صدا میزنند.
سادهترین استفادهٔ درست: Active Record برای بخشهای CRUD؛ برای یکی دو aggregate با قاعدهٔ واقعی، repository و class ساده دامنه؛ یک DB::transaction برای هر use case؛ read model برای صفحههای لیست.
مثال روزمره (ساده): وبلاگ یا اپ ادمین. Post::with('author')->paginate()، StorePostRequest، action به نام PublishPost. repository ندارد؛ اضافهکردنش تشریفات است.
مثال production (پیچیده): checkout یک فروشگاه. PlaceOrder aggregate Order را بارگذاری میکند، قواعد قیمت را اعمال میکند، با بررسی version ذخیره میکند و در همان تراکنش یک ردیف OrderPlaced در جدول outbox مینویسد (Outbox)؛ یک relay بعد از commit منتشرش میکند. صفحهٔ فهرست سفارشها از OrderSummaryQuery میآید.
Modular monolith و چند دیتابیس
چطور دیده میشود: هر ماژول جدولهایش را دارد (یک schema برای هر ماژول) و یک facade عمومی میدهد؛ ماژولهای دیگر facade را صدا میزنند، نه جدول را. طراحی ماندگاری به طراحی ماژول تبدیل میشود (Modular Monolith).
-- PostgreSQL: one schema and one role per module; others get read-only access to a view at most.
CREATE SCHEMA orders; CREATE SCHEMA billing;
CREATE ROLE orders_app LOGIN; CREATE ROLE billing_app LOGIN;
GRANT USAGE, CREATE ON SCHEMA orders TO orders_app;
GRANT USAGE, CREATE ON SCHEMA billing TO billing_app;
-- billing_app has no privileges on schema orders: it must call the Orders facade. Cross-module read, modular monolith
1 Billing needs the order total
2 billing -> OrdersFacade.totalFor(orderId) -- public interface, returns a DTO
3 OrdersFacade -> OrderSummaryQuery -- reads orders.* tables, inside the Orders module
4 billing never joins orders.order_lines directlyمثال روزمره: ماژولهای Catalog، Orders و Billing در یک اپ Laravel، هرکدام با service provider و CODEOWNERS. مثال production: همان تقسیم، با اتصال دیتابیس دوم برای ماژول Billing (credential جدا، DB::connection('billing')) تا تقسیم قبل از وجود هر سرویسی واقعی باشد.
Microservices (میکروسرویس): ماندگاری با مرز شبکه
چه میماند: repositoryها و aggregateها، بدون تغییر. چه میشکند: join بین سرویسها، تراکنش بین سرویسها، و «فقط جدولشان را بخوان». قاعدهٔ Richardson: "Keep each microservice's persistent data private to that service and accessible only via its API"، با سه سطح ایزولهسازی (private tables، schema per service، database server per service). صفحهٔ Integration Database از Fowler توضیح میدهد چرا جایگزین آسیب میزند: schema مشترک "has to unify what should be separate BoundedContexts".
Place an order across three services
1 Client -> Orders: POST /orders -- Orders: aggregate saved, version 1, outbox row OrderPlaced (one transaction)
2 Relay -> broker: OrderPlaced -- after commit, at-least-once
3 Billing consumes OrderPlaced (inbox: dedupe by event id) -- creates its invoice in its own DB
4 Billing -> broker: InvoiceCreated
5 Orders consumes InvoiceCreated -- updates Order.status in its own aggregate
6 Reporting consumes all three -- its own denormalised read model, rebuildableهمگامسازی داده و read model. سرویسی که دادهی دیگری را لازم دارد، کپیای نگه میدارد که مال خودش است، با event یا change data capture تغذیه میشود و آن را read model ای میداند که ممکن است کهنه باشد. پردازش idempotent: Idempotent Consumer & Inbox؛ هماهنگی: Saga.
مهاجرت strangler برای طراحی ماندگاری. Strangler Fig از Fowler: جایگزینی تدریجی سیستم قدیمی تا "investment and returns occur gradually and visibly". روی داده:
| گام | کار | قاعدهٔ داده |
|---|---|---|
| 1 | یک facade جلوی ماژول در همان مونولیت بگذارید | دیگران خواندن جدولهایش را متوقف میکنند |
| 2 | جدولهای ماژول را به schema خودش و بعد دیتابیس خودش ببرید | یک نویسنده برای هر جدول |
| 3 | ترافیک جدید را به سرویس جدید بفرستید؛ کد قدیمی facade را صدا میزند | خواندن دوگانه، نوشتن واحد |
| 4 | در دورهٔ گذار داده را دوطرفه همگام کنید (event، CDC یا dual write پشت flag) | برای هر فیلد یک منبع حقیقت انتخاب کنید |
| 5 | جدولهای قدیمی را بازنشسته کنید | backfill، راستیآزمایی، حذف |
Anti-corruption layer. وقتی سرویس جدید باید مدل قدیمی را بخواند، در مرز ترجمه کنید. Evans: "As a downstream client, create an isolating layer to provide your system with functionality of the upstream system in terms of your own domain model." در زبان ماندگاری، schema قدیمی mapper مخصوص خودش را میگیرد و دامنهٔ جدید هرگز نوعهایش را import نمیکند.
مثال روزمره: Orders رویداد OrderPlaced را منتشر میکند؛ Notifications کپی خودش به نام order_contacts را نگه میدارد. مثال production: جداکردن Billing از یک مونولیت: اول facade، بعد schema، dual-write پشت flag، یک ماه مقایسهٔ صورتحسابها، بعد سوییچ خواندن و حذف جدولهای قدیمی.
دادههای توزیعشده: replica، cache و CQRS
کجا میشکند. replicaها عقب میافتند، پس repository ای که درست بعد از نوشتن از replica بخواند داده کهنه میگیرد (Replication)؛ cache جلوی aggregateها کهنه میشود و تعارض version را پنهان میکند؛ repository ای که دو دیتابیس را میپوشاند تراکنش ندارد.
| وضعیت | قاعده |
|---|---|
| خواندن درست بعد از نوشتن | از primary بخوانید (یا توکن consistency پاس بدهید) برای request بعدی |
| Repository روی replica | فقط برای read model؛ aggregateها از primary بارگذاری میشوند چون بررسی version باید حقیقت را ببیند |
| Cache جلوی خواندنها | read model را cache کنید، با event باطل کنید، TTL را شبکهٔ ایمنی بگیرید |
| دو دیتابیس در یک use case | دو تراکنش و outbox/saga؛ هرگز two-phase commit پنهان (distributed SQL) |
| store شاردشده | id مربوط به aggregate باید shard key را شامل شود یا القا کند |
| چندمنطقهای | یک منطقهٔ نویسنده برای هر aggregate؛ تعارض با version یا CRDT حل میشود |
Replica lag and the repository
1 T0 Orders: Save(o-1) on primary, version 5
2 T1 user reloads the page; the query goes to a replica
3 T2 replica still at version 4 -> the page shows the old status
4 T3 user clicks Place again; Get(o-1) from the REPLICA returns version 4; Save with WHERE version = 4 -> 0 rows on the primary
5 Lesson: aggregates load from the primary, read models may use replicasمسیر مقیاسپذیری: 1×، 10×، 100×
| مقیاس | طراحی ماندگاری | عمل |
|---|---|---|
| 1× (یک تیم، یک اپ) | مدلهای Eloquent/GORM مستقیم؛ repository فقط برای aggregate پرقاعده | preventLazyLoading، یک تراکنش برای هر use case |
| 10× (چند تیم، یک repo) | Modular monolith؛ schema برای هر ماژول؛ repository و facade | تست contract، CODEOWNERS روی جدولها، read model برای لیستها |
| 100× (تیمها و سرویسهای زیاد) | Database per service؛ event، outbox، inbox؛ read model بهصورت کپیهای خودی | idempotency، eventهای نسخهدار، ابزار replay و بازسازی |
| فراتر | sharding، store برای هر tenant، polyglot persistence | id مربوط به aggregate شارد را حمل میکند؛ ببینید Multi-Tenancy و Billion-Row Tables |
آزمایشگاه: یک Order به سه شکل
تستهای Go را اجرا میکنید، بعد Active Record و Repository را از نظر هزینهٔ تغییر، هزینهٔ تست و همزمانی مقایسه میکنید. هر چیز در Go آفلاین اجرا میشود، جز اجرای اختیاری PostgreSQL؛ گامهای PHP خروجی مورد انتظارند، نه اجراشده (روی ماشین نویسنده PHP نیست).
آمادهسازی.
cd docs/snippets/design/data-persistence-design/go
gofmt -l . # no output
go vet ./... # no output
go test ./...گام ۱: تستهای خالص و fake را اجرا کنید.
go test -v ./after/domain ./after/memrepo ./after/app ./after/valuer
# --- PASS: TestPlaceNeedsLines
# --- PASS: TestPlacedOrderIsFrozen
# --- PASS: TestMoneyAddRejectsMixedCurrencies
# --- PASS: TestContract/round_trip_keeps_the_whole_aggregate
# --- PASS: TestContract/missing_order_is_ErrNotFound
# --- PASS: TestContract/second_writer_gets_ErrConflict
# --- PASS: TestPlaceOrderCommitsOnSuccess
# --- PASS: TestPlaceOrderRollsBackOnError
# --- PASS: TestAddressRoundTrip
# --- PASS: TestStatusRejectsUnknownگام ۲: بسنجید دامنه چه چیزی import میکند.
go list -f '{{join .Imports " "}}' ./after/domain
# context errors fmt
go list -f '{{join .Imports " "}}' ./before
# context database/sql errorsaggregate هیچ package دیتابیسی import نمیکند؛ Active Record بدون آن ساخته نمیشود.
گام ۳: بررسی version را بشکنید. در memrepo/repo.go بلوک if s.version != o.Version() را حذف کنید. انتظار: TestContract/second_writer_gets_ErrConflict با err = <nil>, want ErrConflict شکست میخورد. این lost update در شکل object است. بلوک را برگردانید.
گام ۴: یک فیلد اضافه کنید و فایلها را بشمارید. Notes string را به سفارش اضافه کنید. انتظار برای طراحی repository: domain/order.go، schema.sql، query.sql، db/query.sql.go، repo.go. برای Active Record: struct، SELECT و UPDATE در before/order.go. کدام ارزانتر است به تعداد قاعدهها و جدولها بستگی دارد؛ repository وقتی دامنه زیاد و ذخیرهسازی کم تغییر میکند برنده است، Active Record وقتی هر دو با هم تغییر میکنند.
| معیار | Active Record (before) | Repository (after) |
|---|---|---|
package های لازم برای تست Place() | database/sql و یک دیتابیس | هیچ (go test ساده) |
| تراکنش کجا انتخاب میشود | داخل متد مدل | در use case (UnitOfWork) |
| کنترل همزمانی | هیچ | بررسی version، با contract تست میشود |
| فایل برای اضافهکردن یک ستون | 1 | 5 |
| فایل برای عوضکردن موتور ذخیرهسازی | همهٔ callerها | 1 adapter |
| read model برای صفحهٔ لیست | بارگذاری مدلها | query با DTO در ForCustomer |
گام ۵: adapter را عوض کنید. gormrepo.New(gormDB) همان domain.Repository را پیاده میکند. در یک تست با contract وصلش کنید (dialector GORM برای دیتابیس شما لازم است؛ ماژول بدون آن هم کامپایل میشود):
// contract.Run(t, func(t *testing.T) domain.Repository { return gormrepo.New(openGorm(t)) })گام ۶: روی PostgreSQL اجرا کنید (اختیاری).
createdb academy_dpd
DATABASE_URL="postgres://localhost/academy_dpd?sslmode=disable" go test -v ./after/sqlcrepo
# --- PASS: TestContract/round_trip_keeps_the_whole_aggregate
# --- PASS: TestContract/missing_order_is_ErrNotFound
# --- PASS: TestContract/second_writer_gets_ErrConflictهر subtest schema را میسازد و داخل تراکنشی اجرا میشود که rollback میشود؛ پس دیتابیس خالی میماند. این گام را روی ماشین نویسنده نتوانستیم اجرا کنیم (PostgreSQL در دسترس نبود)؛ بدون DATABASE_URL تست SKIP چاپ میکند.
گام ۷ (Laravel). فایلهای after/ را (با namespaceهای نوشتهشده) در یک اپ Laravel 13 کپی کنید، migration را اجرا کنید، provider را bind کنید و تستها را اجرا کنید.
php artisan migrate
php artisan test --filter=OrderTest # pure: no database
php artisan test --filter=InMemoryOrderRepositoryTest # fake: no database
php artisan test --filter=EloquentOrderRepositoryTest # real DB, RefreshDatabase
# expected: all green; the three contract tests run twice (fake and Eloquent)گام ۸ (Laravel): N+1 را حس کنید. اکشن before/OrderController::index را برای مشتریای با ۵۰ سفارش و با Model::preventLazyLoading() فعال صدا بزنید. انتظار: استثنا که در اولین دور حلقه relation به نام lines را نام میبرد. $o->lines->count() را قبل از حلقه به $o->loadCount('lines') تغییر دهید یا از OrderSummaryQuery استفاده کنید. انتظار: ۱ query.
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| «Repository پوششی دور ORM است.» | collection ای از aggregateها به زبان دامنه است؛ پوشش یکبهیک چیزی اضافه نمیکند |
| «Active Record ضدالگوست.» | ارزانترین الگوی درست برای فیچرهای CRUD است |
| «با repository راحت دیتابیس عوض میکنم.» | تراکنش، قفل و قابلیتهای SQL نشت میکنند؛ برد واقعی قابلیت تست و یک نقطهٔ تغییر است |
| «برای هر جدول یک repository.» | برای هر ریشهٔ aggregate که دسترسی مستقیم میخواهد |
| «Lazy loading قابلیت کارایی است.» | هزینه را عقب میاندازد و N+1 را پنهان میکند؛ در طراحی برای هر association تصمیم بگیرید |
«save() اتمیک است پس امن است.» | یک statement اتمیک است؛ use case یک تراکنش دور همهٔ نوشتنهایش میخواهد |
| «تست با SQLite درونحافظه معادل production است.» | موتور، نوعها، قفل و JSON متفاوتاند؛ برای adapter موتور واقعی |
| «Identity map یک cache است.» | ابزار درستی در محدودهٔ تراکنش است و با unit of work دور انداخته میشود |
| «CQRS یعنی دیتابیس جدا و event.» | شکل سبکش یک query با DTO روی همان جدولهاست |
| «Soft delete یعنی حریم خصوصی رعایت شد.» | داده soft-delete شده هنوز هست؛ پاکسازی واقعی حذف واقعی یا ناشناسسازی میخواهد |
| «Eloquent قفل خوشبینانه دارد.» | ندارد؛ ستون version و WHERE version = ? اضافه کنید |
| «سرویسها اگر جدولهای متفاوت بخوانند میتوانند دیتابیس مشترک داشته باشند.» | دسترسی مشترک deploy و schema را به هم گره میزند؛ هر سرویس جدولهایش را دارد و API یا event عرضه میکند |
چکیده
| موضوع | یادتان باشد |
|---|---|
| Persistence ignorance | دامنه چیزی از ذخیرهسازی import نمیکند؛ قاعده را با new تست کنید |
| Mismatch | هویت، وراثت، انجمنها، ریزدانگی، پیمایش |
| Active Record | object ردیف که خودش را ذخیره میکند؛ برای CRUD عالی |
| Data Mapper | mapper جدا؛ object دامنه کد ذخیرهسازی ندارد |
| Gatewayها | Table: SQL یک جدول؛ Row: دستگیرهٔ تایپدار برای ردیف؛ هیچکدام قاعده ندارند |
| Repository | collection ای از aggregateها به زبان دامنه؛ یکی برای هر ریشه |
| Aggregate | کامل بارگذاری و ذخیره شود؛ بقیه با id؛ یک تراکنش |
| Querying | اول متدهای finder؛ Specification برای محمولهای قابلاستفادهٔ مجدد |
| Unit of Work | یک use case، یک تراکنش، در لایهٔ application باز میشود |
| Identity Map | هر ردیف یک object در هر unit of work؛ cache نیست |
| Loading | درون aggregate eager؛ بین aggregateها با id یا read model |
| Read model | query جداگانه با DTO؛ برای لیست هرگز aggregate نسازید |
| نگاشت مقدار | Scanner/Valuer در Go؛ cast در Laravel؛ مقدار ناشناخته را رد کنید |
| Optimistic lock | WHERE version = ?؛ ۰ ردیف یعنی conflict |
| Soft delete | در repository فیلتر کنید؛ unique index جزئی؛ پاکسازی نیست |
| تست | دامنه خالص، fake برای use case، contract روی موتور واقعی |
| سرویسها | Database per service؛ جدول مشترک نه؛ event و read model |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — همکارتان میگوید «Eloquent خودش repository است، لازم نیست یکی اضافه کنیم.» کی درست میگوید و کی غلط؟ حیاتی
پاسخ
پاسخ: برای فیچرهای شبیه CRUD با قاعدهٔ کم درست است. وقتی قاعدهها تست سریع میخواهند، شکل ذخیرهسازی با شکل object فرق دارد، یا ماژولهای دیگر قرارداد پایدار میخواهند، غلط است. ببینید Repository روی Eloquent.
۲ — پنج ناهمخوانی بین object و جدول را نام ببرید و برای هرکدام یک قابلیت ابزار. مهم
پاسخ
پاسخ: هویت (Identity Map، برابری کلید)، وراثت (Single/Class/Concrete Table Inheritance)، انجمنها (نگاشت کلید خارجی و جدول واسط، relation)، ریزدانگی (cast، Scanner/Valuer، embedded value، JSON)، پیمایش (eager loading، read model). ببینید Impedance mismatch.
۳ — چرا interface مربوط به repository باید در package دامنه باشد نه کنار ORM؟ مهم
پاسخ
پاسخ: Dependency Inversion: دامنه تعیین میکند چه میخواهد و adapter به آن وابسته میشود. وگرنه دامنه زیرساخت را import میکند و persistence ignorance را از دست میدهد. ببینید Dependency Inversion.
۴ — دو کاربر یک سفارش را ویرایش میکنند. با UPDATE ... WHERE version = ? توضیح دهید هرکدام چه میبینند. حیاتی
پاسخ
پاسخ: ذخیرهٔ اول یک ردیف را عوض میکند و version را بالا میبرد. دومی صفر ردیف را match میکند، repository conflict برمیگرداند و use case دوباره بارگذاری میکند یا از کاربر میپرسد. ببینید Optimistic locking.
۵ — تراکنش «ثبت سفارش» از کجا شروع شود و چرا نه در repository؟ حیاتی
پاسخ
پاسخ: در use case، چون فقط آن میداند کدام فراخوانیهای repository یک کار کسبوکاریاند. تراکنش در سطح repository هر فراخوانی را جداگانه commit میکند. ببینید Unit of Work.
۶ — endpoint لیست ۲ ثانیه طول میکشد و ۴۰۱ query اجرا میکند. راهحل طراحی چیست، فراتر از اضافهکردن with()؟ حیاتی
پاسخ
پاسخ: read model (query با DTO) تا لیست aggregate نسازد؛ eager loading وصله است و query مخصوص طراحی. ببینید DTO و read model و ORM Pitfalls.
۷ — چه چیزی درون aggregate است و چه چیزی با id ارجاع داده میشود؟ حیاتی
پاسخ
پاسخ: چیزهایی که باید در یک تراکنش با هم سازگار باشند (سفارش و خطوطش) دروناند؛ aggregateهای دیگر (مشتری) با id ارجاع داده میشوند و از repository خودشان میآیند. ببینید مرز Aggregate.
۸ — چرا SQLite درونحافظه جایگزین بدی برای PostgreSQL در تست repository است؟ مهم
پاسخ
پاسخ: نوعها، قیدها، JSON، قفل و لهجهٔ SQL متفاوتاند؛ تست رفتار SQLite را میسنجد. برای adapter موتور واقعی و برای use case یک fake، با یک contract برای هر دو. ببینید تست ماندگاری.
۹ — سرویس A دادهای را میخواهد که مال سرویس B است. دو راه قابلقبول و یک راه ممنوع را بگویید. حیاتی
پاسخ
پاسخ: قابلقبول: صدا زدن API سرویس B؛ نگهداشتن کپی خودی که با event یا CDC سرویس B تغذیه میشود. ممنوع: خواندن مستقیم جدولهای B (دیتابیس مشترک). ببینید میکروسرویس.
۱۰ — Model::preventLazyLoading(! $this->app->isProduction()) چه میکند و چرا آن شرط هست؟ مهم
پاسخ
پاسخ: هنگام lazy load یک relation استثنا میدهد تا N+1 در توسعه و CI پیدا شود؛ در production برنامه به کارش ادامه میدهد. ببینید Lazy در برابر Eager.
۱۱ — چرا aggregateها باید از primary بارگذاری شوند، نه replica؟ مهم
پاسخ
پاسخ: replica ممکن است عقب باشد، پس version خواندهشده از آن کهنه است و نوشتن مبتنی بر version شکست میخورد، یا بدتر، تصمیمها روی حالت قدیمی گرفته میشوند. read modelها میتوانند از replica بخوانند. ببینید دادههای توزیعشده.
واژهنامه
| اصطلاح | معنا |
|---|---|
| بیخبری از ذخیرهسازی (Persistence ignorance) | objectهای دامنه هیچ کد یا import مربوط به ذخیرهسازی ندارند |
| ناهمخوانی شیءگرا-رابطهای (Impedance mismatch) | شکاف ساختاری بین مدل object و schema رابطهای |
| هویت (Identity) | چه چیزی دو چیز را یکی میکند: کلید (جدول) یا reference/مقدار (object) |
| ریزدانگی (Granularity) | مدل object داده را نسبت به ستونها چقدر ریز میشکند |
| پیمایش (Navigation) | دنبالکردن reference یکبهیک در برابر join مجموعهها |
| Active Record | object ای که ردیف را میپیچد، دسترسی به داده دارد و منطق دامنه اضافه میکند |
| Data Mapper | لایهای که داده را بین object و جدول جابهجا میکند و هر دو را مستقل نگه میدارد |
| Table Data Gateway | یک object که همهٔ SQL یک جدول را دارد |
| Row Data Gateway | یک object برای هر ردیف، دستگیرهٔ تایپدار بدون قاعده |
| Repository | رابط شبیه collection روی aggregateهای ذخیرهشدهٔ یک نوع |
| Aggregate | خوشهای از objectها که برای سازگاری و ذخیره یک واحد حساب میشوند |
| ریشهٔ aggregate (Aggregate root) | تنها عضوی که objectهای بیرون میتوانند به آن ارجاع دهند |
| Specification | object ای که میگوید candidate با یک معیار جور است یا نه |
| Query Object | object ای که یک query دیتابیس را نمایندگی میکند |
| Unit of Work | تغییرهای یک کار کسبوکاری را دنبال و یکجا commit میکند |
| Identity Map | نقشهٔ مخصوص هر تراکنش که تضمین میکند هر ردیف یک object باشد |
| Lazy Load | object ای که میداند دادهی کمشدهاش را هنگام اولین استفاده بیاورد |
| بارگذاری مشتاق (Eager loading) | آوردن داده مرتبط از قبل همراه والد |
| N+1 | یک query برای والد و یکی برای هر فرزند |
| DTO | Data Transfer Object: شکل فقطدادهای که از مرز عبور میکند |
| Read model | شکل سمت query که برای یک صفحه یا پاسخ ساخته شده |
| CQRS | استفاده از مدل متفاوت برای نوشتن و خواندن |
| Value object | object تغییرناپذیر که با مقدار مقایسه میشود و هویت ندارد |
| Embedded Value | ذخیرهٔ value object در ستونهای جدول مالکش |
| Serialized LOB | ذخیرهٔ یک گراف object بهصورت یک ستون serialize شده (JSON) |
| Single Table Inheritance | یک سلسلهمراتب در یک جدول با ستون تمایز |
| Class Table Inheritance | یک جدول برای هر class در سلسلهمراتب |
sql.Scanner | interface در Go برای خواندن مقدار دیتابیس به یک نوع |
driver.Valuer | interface در Go برای تبدیل یک نوع به مقدار دیتابیس |
| Cast | تبدیل اعلامشدهٔ Eloquent بین ستون و نوع PHP |
| قفل خوشبینانه (Optimistic locking) | تشخیص ویرایش همزمان با version و شکستدادن نوشتن دیرتر |
| Soft delete | علامتزدن ردیف بهجای حذف آن |
| ردپای ممیزی (Audit trail) | سابقهٔ اینکه چه کسی چه چیزی را کی عوض کرده |
| مدل ذخیرهسازی (Persistence model) | class شکلگرفته بر اساس ذخیرهسازی (مدل Eloquent، struct GORM) که داخل adapter میماند |
| تست contract (Contract test) | مجموعه تستی که هر پیادهسازی یک port باید بگذراند |
| تست تراکنشی (Transactional test) | تستی که در تراکنشی اجرا میشود که در پایان rollback میشود |
| Database per service | هر سرویس store داده خودش را دارد و فقط با API آن دسترسی داده میشود |
| Integration database | یک schema مشترک بین چند برنامه |
| Strangler Fig | جایگزینی تدریجی سیستم قدیمی از لبهها |
| Anti-corruption layer | لایهٔ ترجمه که دامنه را از مدل بیگانه محافظت میکند |
| Outbox | جدولی که در همان تراکنش تغییر حالت نوشته میشود و بعد به broker فرستاده میشود |
| Change data capture (CDC) | جریانکردن تغییرهای commit شدهٔ ردیفها از لاگ دیتابیس |
| Dirty checking | تشخیص اینکه کدام فیلدهای object بارگذاریشده تغییر کردهاند |
منابع
- Martin Fowler et al., Patterns of Enterprise Application Architecture catalog: Repository (Edward Hieatt, Rob Mee), Data Mapper, Active Record, Table Data Gateway, Row Data Gateway, Unit of Work, Identity Map, Lazy Load, Query Object, Data Transfer Object, Single Table Inheritance, Class Table Inheritance, Embedded Value, Serialized LOB, Foreign Key Mapping, Optimistic Offline Lock (David Rice). فقط خلاصهٔ کاتالوگ خوانده شد؛ فصلهای کتاب را نخواندیم.
- Martin Fowler, OrmHate, 8 May 2012; DDD Aggregate, 23 April 2013; CQRS; Integration Database, 25 May 2004; Strangler Fig, 22 August 2024.
- Eric Evans, Domain-Driven Design Reference (2015): Aggregates, Repositories, Anticorruption Layer.
- Eric Evans and Martin Fowler, Specifications.
- Scott Ambler, Mapping Objects to Relational Databases; Wikipedia, Object-relational impedance mismatch (منبع ثانویه).
- Chris Richardson, Database per service, CQRS, Aggregate.
- Laravel 13: Eloquent, Mutators & Casting, Relationships, Database, Query Builder, Database Testing.
- Doctrine ORM: Working with objects, Architecture.
- Go: database/sql, database/sql/driver, Executing transactions.
- sqlc: docs, Using transactions, Query annotations, Overrides.
- GORM: Guides, Models, Preload, Transactions, Delete (soft delete), Update, Data types.
- ent: Getting started, Eager loading, Transactions.
- فصلهای مرتبط: ORM Pitfalls, Optimistic vs Pessimistic Locking, Repositories, Aggregates & Factories, Data Ownership in Microservices, Outbox.