DDIA·واژه‌هاTERMS

نقشه راهRoadmap/ واژه‌نامهGlossary/ فصل ۳Chapter 3

۳3مدل‌های داده و زبان‌های کوئریData models and query languages

۲۱ واژه از فصل ۳ — هر کدام با یک مثال روزمره، یک نمودار و تلهٔ رایج.21 terms from chapter 3, each with an everyday example, a diagram and the usual trap.

این رابطه چند تا چند است؟How many of each does this relationship allow?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

توی خانواده، هر بچه یک مادر دارد، ولی یک مادر می‌تواند چند بچه داشته باشد. حالا کوچه را نگاه کن: هر بچه می‌تواند با چند بچهٔ دیگر دوست باشد و آن‌ها هم با چند نفر. اسم این «چند تا چند بودن» کاردینالیتی است، و تعیین می‌کند داده را چطور بچینی.In a family each child has one mother, while one mother can have several children. Now look at the street: each child can be friends with several others, and they with several more. The name for this how-many-on-each-side is cardinality, and it decides how you arrange the data.

تشبیه و تصویر ذهنیThe analogy

سه شکل اصلی هست: یک‌به‌یک، مثل هر نفر و شناسنامه‌اش؛ یک‌به‌چند، مثل مادر و بچه‌هایش؛ و چندبه‌چند، مثل دوستی. تفاوت وقتی مهم می‌شود که بخواهی داده را بچینی. رابطهٔ یک‌به‌چند را می‌شود با یک ستون در سمت «چند» نگه داشت. رابطهٔ چندبه‌چند به یک جای سوم نیاز دارد، چون هیچ‌کدام طرف مالک دیگری نیست و نمی‌شود گفت کدام شناسه را کجا نوشت.There are three basic shapes: one-to-one, like a person and their birth certificate; one-to-many, like a mother and her children; and many-to-many, like friendship. The difference matters when you arrange the data. A one-to-many relationship fits in a single column on the many side. A many-to-many needs a third place, because neither side owns the other and there is no obvious spot to write the id.

یک‌به‌چندOne-to-manyیک مادر، چند بچهone mother, many childrenکلید خارجی سمت چندforeign key on the many sideدر سند: تودرتو، اگر کم استin a document: embed, if fewچندبه‌چندMany-to-manyدوستی، دو طرفهfriendship, both waysجدول واسط لازم استneeds a join tableدر سند: سخت و تکراریin a document: awkward, duplicated
کاردینالیتی می‌گوید هر طرف چند چیز می‌تواند داشته باشد؛ همین تصمیم می‌گیرد کجا کلید بگذاری.Cardinality says how many each side may hold; that decision places the key.

و بعدش، فنیAnd now, technically

کاردینالیتی در مدل‌سازی یعنی تعداد چیزهایی که در دو طرف یک رابطه می‌توانند بنشینند: یک‌به‌یک، یک‌به‌چند و چندبه‌چند. در مدل رابطه‌ای، یک‌به‌چند با کلید خارجی در سمت چند حل می‌شود و چندبه‌چند با جدول واسط. در مدل سندی تفاوت مهم‌تر بین one-to-few و one-to-many است: اگر تعداد واقعاً کوچک و محدود بماند، تودرتو کردن سند خوب است؛ اگر بی‌مرز رشد کند، سند را از سقف می‌گذراند. این کلمه معنای دومی هم دارد: تعداد مقادیر متمایز یک ستون، که تعیین می‌کند ایندکس چقدر گزینش‌پذیر است و بهینه‌ساز چه تخمینی برای تعداد ردیف‌ها بزند.In modelling, cardinality is how many things can sit on each side of a relationship: one-to-one, one-to-many, many-to-many. In the relational model, one-to-many is solved with a foreign key on the many side and many-to-many with a join table. In a document model the important line is between one-to-few and one-to-many: if the count stays genuinely small and bounded, embedding is right; if it grows without limit, it pushes the document past its size cap. The same word has a second job: the number of distinct values in a column, which decides how selective an index is and what row estimate the optimizer makes.

1:Nکلید خارجی در سمت «چند» می‌نشیندthe foreign key sits on the many side
N:Mجدول واسط، یا آرایه‌ای از شناسه‌هاa join table, or an array of ids

تلهٔ رایجThe usual trap

فکر کردن که یک‌به‌چند همیشه کم می‌ماند. آرایه‌ای که امروز سه عضو دارد، دو سال بعد سه هزار عضو دارد و سند را از سقف می‌گذراند. کاردینالیتی را برای فردا تخمین بزن، نه برای امروز.Assuming one-to-many stays few. An array with three members today has three thousand in two years and pushes the document past its limit. Estimate cardinality for next year, not for today.

CQRS

تفکیک خواندن و نوشتن فصل ۳Chapter 3 · دیدن در متنsee in context

چرا خواندن و نوشتن باید یک شکل باشند؟Why should reads and writes share one shape?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

کتابخانهٔ محله را تصور کن. کتابدار هر امانت را در دفتر ثبت می‌کند: یک خط، تاریخ، شمارهٔ کتاب. اما روی دیوار یک نمودار هست: «پرحواننده‌ترین کتاب‌های این ماه». آن نمودار را هیچ‌کس موقع ثبت امانت نگاه نمی‌کند و هیچ امانتی هم داخلش نوشته نمی‌شود. هر شب از روی همان دفتر، نمودار از نو ساخته می‌شود. دفتر برای نوشتن ساخته شده و نمودار برای یک نگاه، و هر دو از یک واقعیت می‌آیند.Picture the neighbourhood library. The librarian records every loan in a ledger: one line, the date, the book number. On the wall there is a chart: most borrowed books this month. Nobody looks at the chart while writing a loan down, and no loan is ever written into the chart. Every evening the chart is rebuilt from the ledger. The ledger is built for writing, the chart for one glance, and both come from the same fact.

تشبیه و تصویر ذهنیThe analogy

این جدایی سه چیز به تو می‌دهد. اول، هر طرف شکل خودش را دارد: دفتر می‌تواند کثیف و پرجزئیات باشد، نمودار می‌تواند درشت و خوانا. دوم، هر طرف جدا بزرگ می‌شود؛ اگر همه فقط نمودار را نگاه کنند، می‌توانی نمودار را روی چند برگ بزرگ کنی بدون اینکه به دفتر دست بزنی. سوم، نمودار همیشه کمی عقب است؛ همان وقتی که کتابدار تازه یک امانت را ثبت کرده و نمودار هنوز خبر ندارد. این عقب‌ماندگی رایگان نیست، ولی معمولاً قابل اندازه‌گیری است. اگر نمودار تازهٔ دیگری بخواهی، لازم نیست دفتر را عوض کنی؛ فقط یک نمودار دیگر از همان دفتر می‌سازی.That separation gives you three things. Each side gets its own shape: the ledger can be messy and detailed, the chart can be large and plain. Each side grows on its own; if everyone only stares at the chart, you can draw it on a bigger board without touching the ledger. And the chart is always a little behind, exactly when the librarian has just recorded a loan the chart knows nothing about. That lag is not free, but it is usually measurable. If you want a second chart, you do not rewrite the ledger, you build another chart from it.

فرمانCommandاعتبارسنجیvalidatedمدل نوشتنWrite modelمنبع حقیقتsystem of recordجریان رویدادEvent streamترتیبیorderedمدل خواندنRead modelبرای هر پرسشper query
فرمان به مدل نوشتن می‌رسد، به‌صورت رویداد بیرون می‌آید و مدل خواندن را می‌سازد.A command lands on the write model, leaves as an event, and builds the read model.

و بعدش، فنیAnd now, technically

در CQRS دو مسیر جدا می‌سازی. مسیر نوشتن با command کار می‌کند: درخواست می‌آید، مدل نوشتن قواعد را چک می‌کند، تغییر را ثبت می‌کند و بعد رویداد را روی یک جریان می‌گذارد. مسیر خواندن به همان جریان گوش می‌دهد و نتیجه را به شکلی می‌چیند که یک صفحهٔ خاص با یک پرسش بخواندش. مدل نوشتن منبع حقیقت است و مدل خواندن دادهٔ مشتق‌شده؛ یعنی می‌شود مدل خواندن را پاک کرد و از اول ساخت. هر طرف جدا بزرگ می‌شود: خواندن سنگین، نوشتن سبک. بهایش سه چیز است: تأخیر، چون مدل خواندن کمی عقب می‌ماند؛ دو مدل که باید با هم سازگار بمانند؛ و یک جریان که خودش باید پایدار و مرتب باشد. برای CQRS لازم نیست رویدادمحور باشی؛ با یک WAL یا CDC هم همان جریان را داری.In CQRS you keep two paths. The write path takes commands: a request arrives, the write model checks the rules, records the change, and then puts an event on a stream. The read path listens to that stream and arranges the result into the shape one particular screen wants. The write model is the system of record and the read model is derived data, which means you can drop a read model and rebuild it. Each side scales on its own: reads heavy, writes light. The bill has three lines: lag, because the read model runs slightly behind; two models that must stay in agreement; and a stream that itself has to be durable and ordered. CQRS does not require event sourcing; a WAL or CDC gives you the same stream.

2 مسیردو مسیر جدا، یک منبع حقیقتtwo paths, one source of truth
1 رویدادهر تغییر یک رویداد، چند مصرف‌کنندهone event per change, several consumers
ms–sتأخیر معمول رسیدن نوشتن به مدل خواندنtypical lag from a write to a readable model

چرا یک مدل برای هر دو کار جواب نمی‌دهدWhy one model cannot serve both jobs

مسیر نوشتن و مسیر خواندن دو خواستهٔ متفاوت دارند. نوشتن باید قواعد را چک کند، چند رکورد را با هم ببیند و مطمئن شود چیزی متناقض ذخیره نمی‌شود؛ برای این کار به قفل، تراکنش و یک مدل کوچک و دقیق نیاز دارد. خواندن باید یک صفحه را در یک رفت‌وبرگشت پر کند: مرتب، از پیش جوین‌شده، با شکل همان صفحه. اگر هر دو را روی یک مدل سوار کنی، یا نوشتن برای ایندکس‌هایی پول می‌دهد که هرگز خوانده نمی‌شوند، یا خواندن هر بار چند join سنگین را تکرار می‌کند. هیچ‌کدام از این دو حالت غلط نیست؛ فقط یکی از آنها همیشه گران است.The write path and the read path want different things. Writing has to check rules, look at several rows at once and make sure nothing contradictory is stored, which asks for locks, transactions and a small precise model. Reading has to fill one screen in one round trip: sorted, pre-joined, in that screen's shape. Put both on one model and either writes pay for indexes nobody reads, or reads repeat the same heavy joins on every request. Neither state is wrong; one of them is simply always expensive.

تأخیر را جدی بگیرTake the lag seriously

مدل خواندن همیشه کمی عقب‌تر از مدل نوشتن است و این عقب‌ماندگی روی صفحهٔ کاربر دیده می‌شود. کاربر سفارشی ثبت می‌کند، همان لحظه فهرست سفارش‌ها را باز می‌کند و سفارشش را نمی‌بیند. راه‌حل‌ها ساده‌اند ولی باید انتخاب شوند: بعد از فرمان، شناسهٔ سفارش را برگردان و همان یک قلم را نشان بده؛ یا تا رسیدن مدل خواندن، همان صفحه را از مدل نوشتن بخوان؛ یا دکمهٔ ثبت را تا تأیید غیرفعال نگه دار. مهم این است که عقب‌ماندگی را اندازه بگیری و به کاربر نگویی «فوری است» وقتی نیست.A read model always sits slightly behind the write model, and that gap shows up on the user's screen. The user places an order, opens the order list right away, and does not see it. The fixes are simple but must be chosen: return the order id after the command and render that one row yourself; or read that single screen from the write model until the read model catches up; or keep the submit button disabled until the acknowledgement arrives. The point is to measure the lag and stop telling users something is instant when it is not.

CQRS در برابر رویدادمحوریCQRS versus event sourcing

CQRSCQRSرویدادمحوریEvent sourcing
منبع حقیقتSource of truthمدل نوشتنthe write modelزنجیرهٔ رویدادهاthe event log
چه چیزی را جدا می‌کندWhat it separatesخواندن از نوشتنreads from writesوضعیت از تاریخstate from history
لازم و ملزوم؟Do they need each other?بدون رویداد هم می‌شودworks without eventsمعمولاً با برون‌فکنی می‌آیدusually arrives with projections

تلهٔ رایجThe usual trap

دو نوشتن موازی به دو جا: هم به مدل نوشتن، هم مستقیم به مدل خواندن. تا وقتی همه‌چیز آرام است درست کار می‌کند؛ روزی که یکی از این دو شکست بخورد، دو مدل برای همیشه با هم اختلاف پیدا می‌کنند و هیچ‌کس نمی‌داند کدام درست است. تنها یک نویسنده برای هر داده داشته باش و بقیه را از جریان بساز.Writing twice, in parallel: once to the write model, once straight into the read model. It works fine while everything is calm; the day one of those two writes fails, the models drift apart for good and nobody knows which one is right. Keep one writer per fact and build the rest from the stream.

به جدول می‌گویی چه می‌خواهی؛ خودش راه را پیدا می‌کند؟You tell the table what you want. Does it find the way?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

به آشپز می‌گویی «دو پرس کباب، یکی بدون پیاز، هر دو با هم». او خودش تصمیم می‌گیرد کدام سیخ اول روی آتش برود و کدام بشقاب زودتر آماده شود. تو نتیجه را گفتی، نه ترتیب کارها؛ دیتافریم هم همین است: خواسته را می‌نویسی، مسیر حساب را خودش می‌چیند.You tell the cook “two kebabs, one without onion, both together”. She decides which skewer hits the fire first and which plate is ready sooner. You stated the result, not the order of steps. A dataframe is the same: you write the wish, it works out the route.

تشبیه و تصویر ذهنیThe analogy

آشپزخانه را بزرگ‌تر کن: سه آشپز، دو اجاق، یک سینک. حالا همان سفارش تبدیل می‌شود به یک برنامه: کدام آشپز سیخ بزند، کدام اجاق اول روشن شود، سالاد چه‌وقت آماده شود. تو این برنامه را نمی‌نویسی، و همین باعث می‌شود هر شب که سفارش عوض شود، آشپزخانه خودش را وفق بدهد. ولی بهایش را هم می‌دهی: وقتی غذا دیر می‌رسد، از بیرون نمی‌بینی کدام آشپز مقصر است، و اگر فقط یک پرس بخواهی، این همه هماهنگی خرجِ اضافه است.Grow that kitchen: three cooks, two stoves, one sink. Now the same order becomes a schedule — which cook skewers, which stove lights first, when the salad is ready. You do not write that schedule, and that is exactly why the kitchen can rearrange itself when tonight's orders change. The bill arrives too: when the food is late you cannot see which cook is at fault, and for a single portion all that coordination is pure overhead.

و بعدش، فنیAnd now, technically

دیتافریم یک انتزاع جدولی است: ستون‌های نام‌دار با نوع، و عملیاتی مثل filter، select، join و groupBy که به‌جای حلقه‌نویسی، ترکیبشان می‌کنی. تفاوتش با یک لیست معمولی این است که بیشتر موتورها اول یک نقشهٔ منطقی از کار می‌سازند، آن را بازنویسی و بهینه می‌کنند و تازه بعد اجرا می‌کنند؛ به همین دلیل می‌توانند ستون‌های بی‌مصرف را کنار بگذارند و فیلتر را تا نزدیک‌ترین نقطهٔ خواندن پایین ببرند. اجرا اغلب ستونی است: برای میانگین یک ستون، همان ستون خوانده می‌شود، نه همهٔ ردیف‌ها. ارزیابی معمولاً تنبل است، یعنی تا وقتی نتیجه‌ای نخواهی هیچ محاسبه‌ای انجام نمی‌شود. هزینه‌اش جایی ظاهر می‌شود که join یا groupBy داده را بین ماشین‌ها جابه‌جا کند؛ آن مرحله، که shuffle نام دارد، گران‌ترین بخش کار است. برای خواندن یا به‌روزرسانی یک رکورد، یا برای تراکنش، دیتافریم ابزار درستی نیست.A dataframe is a table abstraction: named, typed columns plus operations such as filter, select, join and groupBy that you compose instead of writing loops. What separates it from a plain list is that most engines first build a logical plan, rewrite and optimise it, and only then execute — which lets them drop unused columns and push filters down to the closest possible read. Execution is often columnar: an average over one column reads that column, not every row. Evaluation is usually lazy, so nothing is computed until you ask for a result. The cost shows up wherever a join or groupBy has to move data between machines; that stage, the shuffle, is the expensive part. For reading or updating one record, or for transactions, a dataframe is the wrong tool.

1 columnبرای یک aggregate، فقط ستون لازم خوانده می‌شود، نه کل ردیفan aggregate reads the column it needs, not every row
1 shuffleهر groupBy یا join بین ماشین‌ها یک جابه‌جایی گران می‌خواهدevery cross-machine groupBy or join pays for one shuffle
0 rowsتا نتیجه نخواهی، هیچ ردیفی پردازش نمی‌شودuntil you ask for a result, no rows are processed

تلهٔ رایجThe usual trap

جمع کردن نتیجه در حافظهٔ برنامه. یک دیتافریم برای یک گزارش بزرگ می‌سازی، بعد کل خروجی را به یک لیست تبدیل می‌کنی و همهٔ ردیف‌ها می‌روند روی رم همان ماشینی که کدت آن‌جاست. تا وقتی داده کوچک است کسی نمی‌فهمد؛ روزی که جدول بزرگ شود، برنامه با خطای کمبود حافظه از کار می‌افتد، در حالی که خودِ محاسبه کاملاً پخش‌شده بود.Collecting the result into the application's memory. You build a dataframe for a big report and then convert the whole output to a list, which drags every row onto the one machine running your code. Nothing happens while the data is small; the day the table grows the process dies of memory pressure even though the computation itself was fully distributed.

گفتنِ «چه می‌خواهم» کجا از گفتنِ «چطور» بهتر است؟When is saying what you want better than saying how?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

برنج‌پز را روی «پخته» می‌گذاری و می‌روی سراغ کارهای دیگر. خودش زمان و حرارت را انتخاب می‌کند. تو فقط نتیجه را خواستی، نه دمای لحظه‌به‌لحظه را؛ کوئری اعلانی هم همین است.You set the rice cooker to “cooked” and go do something else. It picks the time and the heat on its own. You asked for the result, not the temperature minute by minute; a declarative query is the same.

تشبیه و تصویر ذهنیThe analogy

کیک سفارش می‌دهی: «شکلاتی، برای ده نفر، تا عصر». قنادی آرد و فر و زمان پخت را خودش انتخاب می‌کند و اگر آردش تمام شود، بی‌آنکه چیزی بپرسی، با نسبت دیگری جبران می‌کند. این همان قدرت اعلانی است: خواسته‌ات به شرایط روز وابسته نیست و لازم نیست هر بار از نو بنویسی‌اش. بهایش را هم می‌دهی؛ نمی‌دانی با چه فر و چه آردی پخته می‌شود و اگر قنادی تصمیمش را عوض کند، کیکت هم عوض می‌شود. اگر باید دقیقاً همان کیک همیشگی باشد، مجبوری دستور گام‌به‌گام بدهی و خودت مسئول نتیجه باشی.You order a cake: “chocolate, for ten, by this evening”. The baker chooses the flour, the oven and the baking time, and if he runs out of one flour he substitutes without asking. That is the power of declarative: your request does not depend on today's conditions and you never rewrite it. You pay for it too — you do not know which oven or which flour, and if the baker changes his mind your cake changes with him. If it has to be exactly the usual cake, you must hand over step-by-step instructions and own the result.

و بعدش، فنیAnd now, technically

زبان اعلانی می‌گوید نتیجه چه شکلی باشد، نه با چه ترتیبی ساخته شود. در SQL می‌نویسی «این ردیف‌ها را با آن‌ها وصل کن و بر اساس ماه جمع بزن»؛ انتخاب ایندکس، ترتیب join و میزان موازی‌کاری به عهدهٔ بهینه‌ساز است. همین جدایی سه چیز می‌دهد: سیستم می‌تواند پرس‌وجو را بازنویسی و سریع‌تر کند، می‌تواند آن را بین چند هسته یا چند ماشین پخش کند، و می‌توانی ساختار ذخیره‌سازی را زیر پایت عوض کنی بی‌آنکه کوئری‌ها را دست بزنی. مرز اعلانی و دستوری هم مطلق نیست: SQL در عمل اعلانی است ولی hint و CTEهای دستی هم دارد، و در وب، CSS اعلانی است در برابر جاوااسکریپتی که DOM را گام‌به‌گام تغییر می‌دهد. چیزی که اعلانی بودن تضمین نمی‌کند سرعت است؛ اگر آمار بهینه‌ساز کهنه باشد، همان کوئری اعلانی هم می‌تواند بدترین نقشه را انتخاب کند.A declarative language says what the result should look like, not in what order to build it. In SQL you write “join these rows to those and sum by month”; the index choice, the join order and the degree of parallelism belong to the optimiser. That separation buys three things: the system can rewrite the query and make it faster, it can spread it across cores or machines, and you can change the storage layout under your feet without touching the queries. The border is not absolute — SQL is declarative in practice yet carries hints and hand-written CTEs, and on the web CSS is declarative next to JavaScript that mutates the DOM step by step. What declarativeness does not guarantee is speed: with stale statistics the same declarative query can pick the worst plan available.

1 queryیک متن، چند نقشهٔ اجرای ممکنone statement, several possible execution plans
N coresهمان کوئری را می‌توان بین چند هسته پخش کردthe same query can be spread across cores

تلهٔ رایجThe usual trap

ستون ایندکس‌شده را داخل تابع می‌گذاری، مثلاً date(created_at) = امروز، و بعد می‌گویی «اعلانی است، خودش بهینه می‌کند». بهینه‌ساز نمی‌تواند از ایندکس ستون خام استفاده کند و نقشه به پیمایش کامل جدول می‌افتد. اعلانی بودن یعنی سیستم آزاد است راه را عوض کند، نه این‌که حتماً راه خوب را پیدا می‌کند.Wrapping an indexed column in a function — date(created_at) = today — and then trusting that “it is declarative, it will optimise itself”. The planner cannot use the plain column's index and the plan falls back to a full table scan. Declarative means the system is free to choose another route, not that it is guaranteed to find the good one.

denormalization

نرمال‌زدایی فصل ۳Chapter 3 · دیدن در متنsee in context

چرا همان اسم را دو جا نوشته‌ای؟Why is the same name written in two places?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

توی کیف پولت، شمارهٔ مطب دکتر را روی یک کارت کوچک نوشته‌ای و همان شماره را روی جلد دفترچهٔ بیمه هم نوشته‌ای. وقتی می‌خواهی نوبت بگیری، هر کدام در دسترس باشد کافی است؛ لازم نیست دنبال پرونده بگردی. اما وقتی مطب شماره‌اش را عوض کرد، حالا دو جا باید عوض شود؛ اگر یکی جا بماند، یک روز اشتباه زنگ می‌زنی. نرمال‌زدایی همین است: یک واقعیت، چند نسخه، تا خواندن ساده شود.In your wallet, the clinic's number is written on a small card, and the same number is on the cover of your insurance booklet. When you call to book, whichever one is in reach is enough; you never dig through a file. But when the clinic changes its number, two places have to change, and if one is missed you dial a stranger one day. That is denormalization: one fact, several copies, so reading stays simple.

تشبیه و تصویر ذهنیThe analogy

کارخانه‌ای را تصور کن که سفارش‌ها را در یک دفتر مرکزی ثبت می‌کند. وقتی جنس بار می‌خورد، اسم مشتری را روی برچسب بسته و روی برگهٔ حمل هم می‌نویسند تا راننده در نیمه‌شب لازم نباشد به دفتر مرکزی زنگ بزند. این دو نسخه خواندن را ارزان می‌کنند و در ازایش یک تعهد می‌سازند: هر بار نام مشتری عوض شود، هر دو نسخه باید عوض شوند. اگر نسخه‌ها با هم اختلاف پیدا کنند، دیگر معلوم نیست کدام درست است؛ پس باید بدانی کدام یکی اصل است و بقیه فقط کپی. نرمال‌زدایی همیشه یک نسخهٔ اصل می‌خواهد، وگرنه دو حقیقت داری که هیچ‌کدام برنده نیست.Picture a factory that records orders in a central ledger. When goods are loaded, the customer name goes on the parcel label and on the shipping sheet too, so the driver does not have to call the office at midnight. Those two copies make reading cheap and create a promise: every time the name changes, both copies change. If the copies ever disagree, nobody can tell which is right, so you had better know which one is the original and which are copies. Denormalization always needs one original; otherwise you have two truths and no winner.

نرمال‌شدهNormalizedهر واقعیت، یک جاeach fact, one placeخواندن: joinread: a joinنوشتن: یک نقطهwrite: one spotنرمال‌زدایی‌شدهDenormalizedهمان واقعیت، چند نسخهsame fact, several copiesخواندن: بدون joinread: no joinنوشتن: همهٔ نسخه‌هاwrite: every copy
نرمال‌زدایی خواندن را ارزان و نوشتن را گران می‌کند؛ بهایش هماهنگ نگه داشتن نسخه‌هاست.Denormalization makes reads cheap and writes expensive; the price is keeping the copies in step.

و بعدش، فنیAnd now, technically

نرمال‌زدایی یعنی عمداً یک واقعیت را در بیش از یک جا نگه داری یا نتیجهٔ یک join را از پیش حساب کنی تا هنگام خواندن لازم نباشد دوباره به دستش بیاوری. سه شکل رایج دارد: ستون تکراری مثل اسم مشتری روی فاکتور، سند تودرتو مثل آدرس داخل سفارش، و جدول جمع‌بندی‌شده مثل تعداد سفارش هر مشتری. هر سه یک الگو دارند: خواندن ارزان می‌شود، نوشتن گران. هر تغییر باید همهٔ نسخه‌ها را به‌روز کند، و اگر یکی جا بماند داده متناقض می‌شود. یک نشانهٔ خوب این است که بتوانی بگویی هر نسخه از کجا ساخته می‌شود؛ اگر نمی‌توانی، آن نسخه یک منبع حقیقت دوم است، نه یک کپی. برای همین در عمل یک نویسنده برای هر داده می‌گذاری و کپی‌ها را از یک جریان می‌سازی، نه با دو نوشتن موازی. نرمال‌زدایی وقتی درست است که خواندن گلوگاه واقعی باشد، نه وقتی حدس می‌زنی شاید بشود.Denormalization means deliberately keeping a fact in more than one place, or precomputing the result of a join, so a read does not have to fetch it again. It comes in three common shapes: a duplicated column such as the customer name on an invoice, an embedded document such as the address inside an order, and an aggregate table such as the order count per customer. All three follow one pattern: reads get cheap, writes get expensive. Every change must update every copy, and a missed copy means contradictory data. A good test is being able to say where each copy is built from; if you cannot, that copy is a second source of truth rather than a copy. That is why in practice you keep one writer per fact and build the copies from a stream instead of writing to them in parallel. Denormalization is right when reads are the measured bottleneck, not when you suspect they might be.

2 نسخهکمترین حالت: یک نسخهٔ اضافه که باید هماهنگ بماندthe minimum: one extra copy that has to stay in sync
1 منبعباید بدانی کدام نسخه اصل استyou must know which copy is the original
N نوشتنهر تغییر روی همهٔ نسخه‌ها می‌نشیندevery change lands on every copy

کجا ارزشش را داردWhere it pays

وقتی خواندن چند صد برابر نوشتن است، نرمال‌زدایی معمولاً برنده است: یک صفحهٔ محصول که هزار بار در دقیقه باز می‌شود، نباید هر بار پنج جدول را جوین کند. جایی هم لازم می‌شود که join اصلاً ممکن نیست: دو سرویس جدا که دیتابیس مشترک ندارند، یا یک پایگاه سندی که زبان join ندارد. دستهٔ سوم، گزارش‌های سنگین است که اگر هر بار از نو حساب شوند، هم کندند هم بقیه را کند می‌کنند. در هر سه حالت، سود باید با عدد نشان داده شود، نه با حس.When reads outnumber writes by hundreds to one, denormalization usually wins: a product page hit a thousand times a minute should not join five tables on every request. It is also required where a join is impossible at all: two separate services with no shared database, or a document store whose language has no joins. The third case is heavy reports that are slow on their own and slow everything else down while they run. In all three, the gain should be shown with a number rather than a feeling.

نسخه‌ها چطور از هم می‌افتندHow the copies drift apart

پرتکرارترین راه، دو نوشتن جداگانه است: کد اول جدول اصلی را می‌نویسد، بعد نسخهٔ دوم را. اگر بین این دو خرابی رخ دهد یا یکی از دو نوشتن شکست بخورد، دو نسخه جدا می‌مانند و هیچ خطایی بالا نمی‌آید. راه دوم، بازپخش دوباره یا از دست رفتن یک پیام است که یک کپی را یک قدم عقب می‌گذارد. راه سوم، پر کردن دوبارهٔ یک نسخه از یک نسخهٔ کهنه است. علاج هر سه یکی است: یک مسیر نوشتن، اعمال تکرارپذیر، و یک شغل آشتی که دوره‌ای اختلاف‌ها را پیدا کند.The most common route is two separate writes: the code writes the main table, then the second copy. A crash between them, or one failed write, leaves the copies apart and raises no error. The second route is a replay or a lost message that leaves one copy a step behind. The third is a backfill that rebuilds a copy from a copy that was already stale. The cure is the same for all three: a single write path, repeatable applies, and a reconciliation job that periodically finds the differences.

تلهٔ رایجThe usual trap

نرمال‌زدایی را قبل از اندازه‌گیری انجام دادن. از یک join ساده می‌ترسی، داده را در سه جا کپی می‌کنی، و بعد سه ماه با باگ‌های اختلاف نسخه‌ها می‌جنگی؛ در حالی که یک ایندکس درست همان join را ارزان می‌کرد.Denormalizing before measuring. You fear one simple join, copy the data into three places, and spend the next three months fighting drift bugs, when a correct index would have made that join cheap.

همه‌چیزِ یک چیز، در یک جا.Everything about one thing, in one place.

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

پوشهٔ پزشکی‌ات را باز می‌کنی. داخلش همه چیز با هم است: آزمایش‌ها، نسخه‌ها، عکس رادیولوژی، همه به ترتیب تاریخ. برای فهمیدن وضعیت یک بیمار لازم نیست به سه بایگانی مختلف زنگ بزنی؛ یک پوشه برمی‌داری و کارت راه می‌افتد. اما اگر بخواهی بدانی این بیمار با کدام دکترها در ارتباط بوده، باید پوشه‌های زیادی را ورق بزنی. مدل سندی همان پوشه است: یک چیز، همهٔ جزئیاتش، در یک جا.You open your medical folder. Everything is together inside: test results, prescriptions, the X-ray, all in date order. To understand one patient you do not call three separate archives; you pick up one folder and you are done. But if you want to know which doctors this patient has seen, you have to leaf through a lot of folders. The document model is that folder: one thing, all of its detail, in one place.

تشبیه و تصویر ذهنیThe analogy

هر سند مثل یک برگهٔ کامل است که فقط با نگاه کردن به خودش معنا پیدا می‌کند؛ لازم نیست چیزی را از جای دیگر قرض بگیری. این خودبسندگی دو هدیه دارد: خواندن یک صفحه یک رفت‌وبرگشت می‌شود، و سند را می‌شود روی هر ماشینی گذاشت بدون نگرانی از نصفه بودنش. بهایش جایی ظاهر می‌شود که چیزها به هم وصل‌اند، نه تودرتو. وقتی یک دکتر در صد پوشه تکرار شده، عوض کردن نامش یعنی صد سند را پیدا کنی و صد جا را به‌روز کنی، و اگر یکی جا بماند دیگر معلوم نیست کدام درست است. برای همین سندها برای درخت ساخته شده‌اند، نه برای گراف.Each document is a complete sheet that makes sense on its own; you never have to borrow meaning from somewhere else. That self-containment buys two things: reading one screen becomes one round trip, and a document can sit on any machine without worrying that half of it is elsewhere. The price shows up where things are linked rather than nested. When one doctor's name is repeated across a hundred folders, changing it means finding all hundred and updating each, and one miss leaves you unsure which version is true. Document stores are built for trees, not for graphs.

مدل سندیDocument modelیک سند، همهٔ جزئیاتone document, all detailsخواندن: یک رفت‌وبرگشتread: one round tripچندبه‌چند: سختmany-to-many: awkwardمدل رابطه‌ایRelational modelجدول‌ها، ارجاع با کلیدtables, keys as referencesخواندن: joinread: a joinهر رابطه‌ای، راحتany relationship, easily
سند برای درختی ساخته شده که با هم خوانده می‌شود؛ جدول برای رابطه‌ای که هر شکلی به خود می‌گیرد.A document suits a tree read all at once; a table suits relationships of any shape.

و بعدش، فنیAnd now, technically

در مدل سندی، واحد ذخیره یک سند JSON یا BSON است: درختی تودرتو از اشیاء و آرایه‌ها که با یک کلید یکتا خوانده می‌شود. خواندن یک سند یک عملیات است، نه یک join؛ به همین دلیل locality خوبی دارد و همهٔ چیزی که یک صفحه لازم دارد کنار هم روی دیسک می‌نشیند. چیزی که ندارد، رابطهٔ چندبه‌چند است. اگر دو سند به هم ارجاع بدهند، پایگاه داده آن ارجاع را دنبال نمی‌کند؛ برنامه باید دوباره بپرسد و همین‌جا N+1 ساخته می‌شود. بیشتر این پایگاه‌ها سقف اندازه برای یک سند دارند، از چند مگابایت تا چند ده مگابایت، و آرایه‌ای که بی‌مرز رشد کند دیر یا زود به آن سقف می‌خورد. ایندکس روی فیلدهای داخل سند ممکن است، ولی قید بین سندها معمولاً ممکن نیست.In a document model the unit of storage is one JSON or BSON document: a nested tree of objects and arrays read by a unique key. Reading a document is one operation rather than a join, which gives good locality: everything a screen needs sits together on disk. What it does not give you is many-to-many. If two documents reference each other, the store does not follow the reference; the application has to ask again, and that is where N+1 comes from. Most of these stores cap document size somewhere between a few megabytes and a few tens of megabytes, and an unbounded array hits that cap sooner or later. Indexes on fields inside a document are possible; constraints across documents usually are not.

1 سندهمهٔ دادهٔ یک صفحه در یک خواندن می‌آیدone read brings everything for one screen
۱۶ مگابایتسقف رایج اندازهٔ سند در بعضی از این پایگاه‌هاa common per-document size cap in some of these stores
0 joinبین سندها join نیست؛ کار برنامه استno cross-document join; that is the app's job

درخت خوب است، گراف بدTrees fit, graphs do not

اگر داده‌ات ذاتاً یک درخت است، سند بهترین انتخاب است: یک سفارش با اقلامش، یک پروفایل با آدرس‌هایش، یک پست با کامنت‌هایش. همهٔ اینها با هم خوانده می‌شوند و با هم نوشته می‌شوند، پس کنار هم بودنشان منطقی است. مشکل از جایی شروع می‌شود که چیزی دو والد دارد: یک برچسب که به هزار محصول می‌خورد، یا یک کاربر که در چند سازمان عضو است. آن‌وقت یا باید نسخه‌ها را تکرار کنی یا شناسه نگه داری و در کد جوین کنی؛ دومی همان کاری است که پایگاه رابطه‌ای مجانی انجام می‌دهد.If your data is naturally a tree, a document is the right home: an order with its lines, a profile with its addresses, a post with its comments. All of it is read together and written together, so keeping it together makes sense. Trouble starts when something has two parents: a tag that applies to a thousand products, or a user who belongs to several organisations. Then you either duplicate the copies or store ids and join in code, and the second is exactly what a relational database does for free.

سقف اندازه و آرایهٔ بی‌مرزSize limits and the unbounded array

تودرتو کردن فقط تا وقتی راحت است که تعداد اعضا کوچک و محدود بماند. آرایهٔ کامنت‌های یک پست محبوب را در نظر بگیر: امروز ده عضو دارد و سال بعد صد هزار. هر نوشتن تازه کل سند را جابه‌جا می‌کند، سند از سقف می‌گذرد، و خواندن یک کامنت یعنی آوردن صد هزار کامنت. راه‌حل معمول این است که آرایهٔ بی‌مرز را به یک مجموعهٔ جدا و یک ارجاع کوچک تبدیل کنی؛ یعنی بخشی از سند را از دست می‌دهی و همان locality را قربانی می‌کنی.Embedding stays comfortable only while the member count is small and bounded. Consider the comments array on a popular post: ten members today, a hundred thousand next year. Every new write moves the whole document, the document crosses the size limit, and reading one comment means fetching a hundred thousand. The usual fix is to turn the unbounded array into a separate collection plus a small reference, which means giving up part of the document and sacrificing exactly the locality you wanted.

تلهٔ رایجThe usual trap

استفاده از یک پایگاه سندی به‌عنوان پایگاه رابطه‌ای: هر چیز یک سند جدا با شناسه، و بعد حلقه‌ای در کد که برای هر ردیف یک پرسش می‌زند. نتیجه همان join است، فقط چند صد بار کندتر و بدون هیچ تضمینی.Using a document store as if it were relational: everything becomes its own document with an id, and then a loop in code fires one query per row. You end up with the join you were avoiding, a few hundred times slower and with no guarantees at all.

event sourcing

رویدادمحوری فصل ۳Chapter 3 · دیدن در متنsee in context

اگر فقط اتفاق‌ها را نگه داری، وضعیت کجاست؟If you only keep what happened, where is the state?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

دفتر حساب خانه‌ات را در نظر بگیر. تو در آن نمی‌نویسی «موجودی: صدهزار تومان». می‌نویسی «حقوق واریز شد»، «اجاره دادم»، «نان خریدم». موجودی را هیچ‌جا ننوشته‌ای، ولی هر وقت بخواهی، دفتر را از اول جمع می‌زنی و موجودی همان لحظه به دست می‌آید. اگر هم اشتباهی رخ داده باشد، می‌بینی کجا بوده. رویدادمحوری همین دفتر است، نه عکسی از موجودی.Think of the household account book. You do not write down the balance; you write down what happened: salary in, rent paid, bread bought. The balance is written nowhere, yet whenever you want it you add the book up from the first page and it appears. If something went wrong, you can see where. Event sourcing is that book, not a photograph of the balance.

تشبیه و تصویر ذهنیThe analogy

این دفتر یک هدیهٔ بزرگ دارد: هر سؤالی که دیروز نمی‌پرسیدی، امروز از همان صفحات جواب می‌گیرد. «پارسال چقدر خرج شیرینی شد؟» را می‌شود از نو جمع زد، چون خط‌ها را پاک نکرده‌ای. اما همین دفتر یک هزینه هم دارد: برای گفتن موجودی الان باید نهصد خط را جمع بزنی. پس هر چند صفحه یک جمع می‌نویسی و از آنجا ادامه می‌دهی؛ این همان snapshot است. اگر هم بخواهی معنی یک خط قدیمی را عوض کنی، کل تاریخچه به هم می‌ریزد، چون خط‌ها دیگر قابل بازنویسی نیستند.That ledger has one great gift: any question you did not ask yesterday can be answered today from the same pages. What did we spend on sweets last year? Add it up again, because you never erased a line. It also has a cost: telling the balance right now means adding nine hundred lines. So every few pages you write a running total and continue from there, and that is a snapshot. And if you want to change what an old line meant, the whole history collapses, because the lines cannot be rewritten.

سفارش ثبت شدOrder placedرویداد ۱event 1پرداخت شدPayment takenرویداد ۲event 2ارسال شدShippedرویداد ۳event 3بازپخشReplayساخت وضعیتrebuild state
رویدادها به ترتیب می‌نشینند و وضعیت، حاصل جمع زدن آن‌ها تا همین لحظه است.Events stack up in order, and the state is their sum up to this moment.

و بعدش، فنیAnd now, technically

در رویدادمحوری، منبع حقیقت یک لاگ فقط-افزودنی از رویدادهاست: هر رویداد یک واقعیت گذشته است، با نامی در زمان گذشته و شکلی که دیگر عوض نمی‌شود. وضعیت فعلی چیزی نیست که ذخیره شود؛ حاصل جمع زدن رویدادها از ابتدا تا همین نقطه است. چون جمع زدن از صفر گران می‌شود، هر چند هزار رویداد یک snapshot می‌گیری و بازپخش را از آنجا ادامه می‌دهی. پرسش‌های خواندن از روی نمای ساخته‌شده جواب می‌گیرند، نه از روی خود لاگ. رویداد با فرمان یکی نیست: فرمان ممکن است رد شود، رویداد چیزی است که اتفاق افتاده. چون فقط افزودن است، نوشتن ارزان و ترتیبی می‌شود و همین آن را برای جریان دادن به چند مصرف‌کننده مناسب می‌کند. تعداد رویدادها مدام بالا می‌رود، پس آرشیو کردن بخش‌های قدیمی بخشی از طراحی است، نه یک بهینه‌سازی بعدی. رویدادمحوری با معماری رویدادمحور هم فرق دارد؛ دومی دربارهٔ اعلان بین سرویس‌هاست.In event sourcing the source of truth is an append-only log of events: each event is a fact about the past, named in the past tense, in a shape that no longer changes. The current state is not stored; it is the fold of all events from the start up to now. Because folding from zero gets expensive, you take a snapshot every few thousand events and replay from there. Read queries are answered from a projection, not from the log itself. An event is not a command: a command can be rejected, an event is something that already happened. Because it only appends, writing is cheap and sequential, which is what makes the log a good feed for several consumers. The event count keeps climbing, so archiving old segments is part of the design rather than a later optimisation. Event sourcing is also not event-driven architecture; the latter is about notifications between services.

append-onlyرویدادها فقط اضافه می‌شوند و بازنویسی ندارندevents are only appended, never rewritten
1 snapshotهر چند هزار رویداد، یک عکس برای کوتاه کردن بازپخشone snapshot every few thousand events to shorten replay
O(n)ساختن وضعیت از n رویداد، وقتی snapshot نداریbuilding state from n events with no snapshot

فرمان با رویداد فرق داردA command is not an event

این تفاوت کوچک به نظر می‌رسد و بیشتر خرابی‌ها از همین‌جا می‌آید. فرمان یک درخواست است: «این سفارش را ثبت کن». ممکن است رد شود، چون موجودی نیست یا کاربر اجازه ندارد. رویداد یک گزارش است: «سفارش ۴۲ ثبت شد». این یکی دیگر رد نمی‌شود؛ اتفاق افتاده. اگر این دو را قاطی کنی، لاگت پر از نیت‌هایی می‌شود که هیچ‌وقت عملی نشدند و بازپخش، وضعیتی می‌سازد که هرگز وجود نداشته. قاعدهٔ ساده: چیزی که ممکن است شکست بخورد را هرگز رویداد ننام.The distinction looks small and most of the damage comes from missing it. A command is a request: place this order. It can be refused, because stock is gone or the user lacks permission. An event is a report: order 42 was placed. That one cannot be refused; it happened. Mix the two and your log fills with intentions that never became true, so a replay builds a state that never existed. The simple rule: never call something an event if it can fail.

طرح‌وارهٔ رویداد برای همیشه می‌ماندThe event schema stays forever

در یک جدول معمولی، وقتی ستونی را عوض می‌کنی، دادهٔ قدیمی را مهاجرت می‌دهی و تمام. در رویدادمحوری، هر رویدادی که تا امروز نوشته شده باید فردا هم قابل خواندن باشد، چون بازپخش از همان‌ها شروع می‌شود. این یعنی نسخه‌بندی و کد ارتقا از نسخهٔ قدیم به جدید بخشی از سیستم است، نه یک کار یک‌باره. حذف هم سخت می‌شود: اگر کسی بخواهد داده‌اش پاک شود، نمی‌توانی وسط یک زنجیرهٔ به‌هم‌پیوسته سوراخ کنی؛ باید کلید رمز را دور بیندازی یا تاریخچه را از نو بنویسی.In an ordinary table, changing a column means migrating the old rows once and moving on. In event sourcing, every event written so far must still be readable tomorrow, because replay starts from them. That makes versioning and upcasting part of the system rather than a one-off task. Deletion gets hard too: if someone asks for their data to be erased, you cannot punch a hole in an unbroken chain; you either throw away an encryption key or rewrite the history.

تلهٔ رایجThe usual trap

معنی یک رویداد قدیمی را عوض کردن، یا شکلش را بدون نسخه‌بندی تغییر دادن. همه‌چیز تا روز بازپخش درست کار می‌کند؛ آن روز، تاریخچه دو معنی دارد و وضعیت بازسازی‌شده با وضعیتی که کاربر دیده فرق می‌کند.Changing what an old event means, or changing its shape without versioning. Everything works until the day you replay; on that day the history means two things, and the rebuilt state disagrees with the state users saw.

این دو نفر چطور به هم وصل می‌شوند؟How are these two people connected?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

می‌خواهی بدانی دوستت از چه طریقی با یک آدم مشهور آشناست. ذهنت فهرست اسم نمی‌سازد؛ از خودت شروع می‌کنی، به دوستت می‌روی، بعد به هم‌کلاسی او، بعد به آن آدم. هر پرش یک رابطه است. اگر همین سؤال را از یک دفترچهٔ اسم‌های مرتب بپرسی، باید هزار بار بگردی. مدل گرافی همان نقشهٔ پرش‌هاست: نقطه‌ها آدم‌ها هستند و خط‌ها آشنایی‌ها.You want to know how your friend is connected to someone famous. Your head does not build a list of names; it starts at you, goes to your friend, then to their classmate, then to the famous person. Every hop is a relationship. Ask the same question of an alphabetised address book and you will search a thousand times. A graph model is that map of hops: the dots are people, the lines are who knows whom.

تشبیه و تصویر ذهنیThe analogy

نقشهٔ مترو را در نظر بگیر. ایستگاه‌ها نقطه‌اند و خط‌ها یال؛ سؤال «چند ایستگاه تا اینجا؟» با دنبال کردن خط‌ها جواب می‌گیرد، نه با خواندن جدولی از همهٔ ایستگاه‌ها. این نقشه برای پیدا کردن مسیر عالی است و برای چیز دیگری بد: اگر بپرسی «امسال چند بلیت فروخته شد؟»، باید همهٔ ایستگاه‌ها را جدا بشماری و نقشه کمکی نمی‌کند. بدتر، نقشه را نمی‌شود وسطش برید و نصفش را به شهر دیگری داد؛ هر مسیری که از نیمه بگذرد، دو تکه را به هم می‌چسباند.Take a metro map. Stations are dots, lines are edges, and the question how many stops to here is answered by following the lines, not by reading a table of every station. The map is excellent for finding a route and bad for anything else: ask how many tickets were sold this year and you must count at every station, with the map no help at all. Worse, you cannot cut the map in half and hand one half to another city; any route through the middle would stitch two pieces together.

مدل گرافیGraph modelنقطه و یال، هر دو با ویژگیvertices and edges, both with fieldsپرسش: دنبال مسیرthe question: find a pathهر پرش یک اشاره‌گرeach hop is a pointerمدل رابطه‌ایRelational modelجدول و کلید خارجیtables and foreign keysپرسش: join در هر سطحeach level is a joinجمع‌بندی: راحتaggregation: easy
گراف مسیر را ارزان می‌کند؛ جدول جمع‌بندی و رابطه‌های ساده را.A graph makes paths cheap; a table makes aggregation and simple relations cheap.

و بعدش، فنیAnd now, technically

در مدل گرافی، داده دو نوع موجودیت دارد: vertex یعنی نقطه، و edge یعنی یال، و هر دو می‌توانند ویژگی داشته باشند. یک خانوادهٔ رایج property graph است با برچسب و کلید-مقدار روی هر دو طرف؛ خانوادهٔ دیگر triple store است که هر واقعیت را به شکل subject و predicate و object نگه می‌دارد و با SPARQL پرسیده می‌شود. چیزی که گراف را سریع می‌کند index-free adjacency است: هر گره اشاره‌گر مستقیم به یال‌هایش دارد، پس هر پرش یک پیمایش اشاره‌گر است نه یک index lookup. ایندکس فقط برای پیدا کردن گرهٔ شروع لازم است. در SQL هم می‌شود با recursive CTE گراف پیمود، ولی هر سطح یک join می‌شود. هزینهٔ اصلی توزیع است: هر پرش ممکن است به shard دیگری برود.A graph model has two kinds of entity: vertices and edges, and both can carry properties. The common family is the property graph, with labels and key-value pairs on both ends; the other is the triple store, which keeps each fact as subject, predicate and object and is queried with SPARQL. What makes traversal fast is index-free adjacency: each vertex holds direct pointers to its edges, so a hop is a pointer chase rather than an index lookup. Indexes are only needed to find the starting vertex. SQL can traverse a graph with a recursive CTE, but every level becomes another join. The real cost is distribution: a hop may cross into another shard.

1 hopهر پرش یک اشاره‌گر، نه یک index lookupeach hop is a pointer, not an index lookup
O(degree)هزینهٔ هر گره به تعداد یال‌هایش بستگی داردper-vertex cost grows with the number of its edges
3+ پرشپرسشی که گراف را توجیه می‌کند معمولاً چندپرشی استthe queries that justify a graph are multi-hop

چرا گراف سخت تقسیم می‌شودWhy graphs are hard to partition

در یک سیستم توزیع‌شده، هر پرسش خوب آن است که به یک ماشین برسد. گراف این قرار را نمی‌پذیرد: یک پیمایش سه‌پرشی به‌طور طبیعی از چند نقطه شروع می‌شود و به همسایه‌های همسایه‌ها می‌رسد، و اگر آن همسایه‌ها روی ماشین‌های مختلف باشند، هر پرش یک رفت‌وبرگشت شبکه می‌شود. راه‌های دور زدنش دو تاست: همهٔ گراف را روی یک ماشین نگه دار، یا گراف را طوری تقسیم کن که یال‌های زیاد داخل یک تکه بمانند. هیچ‌کدام رایگان نیست و به همین دلیل خیلی از پایگاه‌های گرافی در عمل کوچک می‌مانند.In a distributed system, a good query reaches one machine. A graph refuses that deal: a three-hop traversal naturally starts at a few points and reaches the neighbours of neighbours, and if those neighbours live on different machines every hop becomes a network round trip. There are two ways around it: keep the whole graph on one machine, or partition it so that most edges stay inside a piece. Neither is free, which is why many graph databases stay small in practice.

کِی گراف را انتخاب نکنWhen not to reach for a graph

اگر پرسش‌هایت یک یا دو پرش دارند، یک join معمولی همان کار را می‌کند و لازم نیست زبان و ابزار تازه یاد بگیری. اگر بار اصلی‌ات جمع‌بندی است — فروش ماهانه، میانگین سبد، شمارش — پایگاه رابطه‌ای یا ستونی خیلی بهتر است، چون گراف برای شمردن همهٔ گره‌ها ساخته نشده. گراف را وقتی بردار که پرسش‌های واقعی‌ات شکل «از اینجا به کجا می‌شود رسید» دارند و عمقشان از دو سه پرش بیشتر می‌شود؛ همان‌جاست که هزینهٔ joinهای تودرتو واقعاً دیده می‌شود.If your queries are one or two hops deep, an ordinary join does the job and you do not need a new language and tool. If your main load is aggregation — monthly sales, average basket, counts — a relational or column store is far better, because a graph was not built for counting every vertex. Reach for a graph when the real questions look like where can I get to from here, at a depth beyond two or three hops; that is where the cost of nested joins actually shows.

تلهٔ رایجThe usual trap

مدل کردن همه‌چیز به شکل گراف و بعد کشف این‌که بیشتر پرسش‌ها یک join ساده بودند. بدتر از آن، پیمایش بدون سقف عمق روی گره‌ای با میلیون‌ها یال: یک پرسش، کل حافظه را می‌خورد و به بقیه هم جواب نمی‌دهد.Modelling everything as a graph and then discovering that most queries were a simple join. Worse is an unbounded traversal from a vertex with millions of edges: one query eats all the memory and stops answering anyone else.

impedance mismatch

ناهم‌خوانی امپدانس فصل ۳Chapter 3 · دیدن در متنsee in context

وقتی دو دنیا شکل هم را ندارند، چه چیزی می‌شکند؟What breaks when two worlds are not shaped alike?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

فرم اداری پر می‌کنی. توی ذهنت آدرس یک چیز است: «خانهٔ مادربزرگ، کوچهٔ سوم، درِ آبی». فرم سه خانه دارد: خیابان، پلاک، واحد. مجبوری آدرس را تکه‌تکه کنی و هر تکه را در خانهٔ خودش بگذاری. ناهم‌خوانی امپدانس همین است: دنیای تو تکه نشده، دنیای فرم تکه است.You fill in an official form. In your head the address is one thing: “grandmother's house, third alley, blue door”. The form has three boxes: street, number, unit. You have to cut the address apart and drop each piece into its own box. That is the impedance mismatch: your world is not divided, the form's world is.

تشبیه و تصویر ذهنیThe analogy

حالا همان فرم را برای هزار نفر پر کن. یکی دو شماره تلفن دارد، یکی هیچ، سومی سال بعد شمارهٔ تازه اضافه می‌کند. در فرم کاغذی برای «شمارهٔ دوم» یک ستون باز می‌کنی که برای بیشتر آدم‌ها خالی می‌ماند؛ در دنیای شیءها، هر شیء هر تعداد شماره که بخواهد دارد. این تفاوت کوچک نیست: هر بار شیء را در جدول می‌ریزی باید تصمیم بگیری کدام تکه ستون شود و کدام ردیف، و هر بار از جدول می‌خوانی باید تکه‌ها را سر هم کنی. اگر این رفت‌وبرگشت را درست انجام ندهی، همان چیزی را می‌سازی که فکر می‌کردی از آن فرار کرده‌ای: یک لایهٔ ترجمهٔ کند و پر از حالت خاص.Now fill that form for a thousand people. One has two phone numbers, one has none, a third adds a new number next year. On paper you open a “second number” column that stays empty for most people; in the object world every object simply holds as many numbers as it has. That difference is not small: every time you pour an object into a table you must decide which part becomes a column and which becomes a row, and every time you read it back you must put the pieces together again. Get that round trip wrong and you rebuild the thing you thought you were escaping: a slow translation layer full of special cases.

شیء در برنامهObject in codeتودرتو و ارجاع‌دارnested, by referenceیک هویت برای همهone identity throughoutذخیرهٔ یک شیءsave one objectردیف در جدولRow in a tableتخت، با کلید خارجیflat, with foreign keysهر ردیف جداeach row stands aloneیک دستور، هزار ردیفone statement, many rows
هر رفت‌وبرگشت بین شیء و ردیف یک ترجمه است، و هر ترجمه هزینه‌ای دارد که باید جایی پرداخت شود.Every round trip between object and row is a translation, and every translation gets paid for somewhere.

و بعدش، فنیAnd now, technically

مدل رابطه‌ای داده را در جدول‌های تخت با کلید خارجی می‌چیند و مجموعه‌ای فکر می‌کند؛ کد برنامه داده را در شیءهایی با ارجاع، تودرتویی و وراثت نگه می‌دارد و یکی‌یکی. ناهم‌خوانی از همین‌جا می‌آید و سه چهره دارد: ساختار (درخت در برابر جدول)، هویت (یک شیء که چند ردیف دارد) و دانهٔ به‌روزرسانی (ذخیرهٔ یک شیء در برابر یک دستور SQL روی هزار ردیف). هزینه‌اش هم سه جاست: کد نگاشت که باید نوشته و نگه‌داری شود، رفت‌وبرگشت‌های اضافه مثل خواندن تنبل، و معنایی که در ترجمه گم می‌شود، مثل ترتیب یا شیءهای تکراری. مدل سندی این شکاف را برای دادهٔ درختی کم می‌کند و برای دادهٔ شبکه‌ای بدترش می‌کند؛ هیچ مدلی هر دو طرف را راضی نمی‌کند.The relational model puts data into flat tables joined by foreign keys and thinks in sets; application code holds data in objects with references, nesting and inheritance, and thinks one at a time. The mismatch starts there and has three faces: structure (a tree versus a table), identity (one object spread over several rows), and update granularity (saving one object versus one SQL statement over a thousand rows). The cost lands in three places: mapping code that must be written and maintained, extra round trips such as lazy loading, and meaning lost in translation, like ordering or duplicate objects. A document model narrows the gap for tree-shaped data and widens it for network-shaped data; no model pleases both sides.

1 objectیک شیء معمولاً چند ردیف در چند جدول می‌شودone object usually becomes several rows in several tables
2 modelsدنیای شیء و دنیای جدول، دو مدل متفاوتthe object world and the table world, two different models

تلهٔ رایجThe usual trap

فکر کردن این‌که ORM شکاف را برمی‌دارد. ORM ترجمه را خودکار می‌کند، حذفش نمی‌کند؛ همان تصمیم‌های «ستون یا ردیف» را جایی پنهان می‌گیرد و بعد در قالب خواندن تنبل و N+1 صورت‌حساب می‌دهد. شکاف وقتی واقعاً کوچک می‌شود که مدل داده‌ات را با کوئری‌هایی که واقعاً می‌زنی تطبیق بدهی، نه با کدی که می‌نویسی.Believing an ORM removes the gap. It automates the translation, it does not delete it: the same “column or row” decisions still get made, only now they are hidden and the bill arrives as lazy loading and N+1. The gap actually narrows when you match the data model to the queries you really run, not to the code you write.

دو جدول، یک سؤال: این ردیف به آن ردیف چه ربطی دارد؟Two tables, one question: which row belongs with which?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

دو دفتر داری: یکی سفارش‌ها با شمارهٔ مشتری و کالا، یکی مشتری‌ها با شماره و آدرس. برای فرستادن هر بسته باید سفارش را به آدرس صاحبش وصل کنی. همین است: تطبیق دو دفتر روی شمارهٔ مشتری. اگر شماره در دفتر مشتری‌ها نبود، بسته بی‌آدرس می‌ماند.You keep two notebooks: one with orders (customer number, item) and one with customers (number, address). To post each parcel you must attach the order to its owner's address. That is all a join is: matching two notebooks on the customer number. If a number is missing from the customer book, the parcel has nowhere to go.

تشبیه و تصویر ذهنیThe analogy

کتابخانه‌ای را تصور کن که دو فهرست دارد: برگهٔ امانت‌ها و کارت کتاب‌ها. برای اینکه بدانی کدام کتاب بیشتر امانت رفته، باید هر برگهٔ امانت را به کارت همان کتاب وصل کنی. وقتی هر دو فهرست کوچک‌اند، ورق زدن و پیدا کردن تکی کار چند دقیقه است. وقتی میلیون‌ها برگه داری، کسی برگه‌به‌برگه نمی‌گردد: اول هر دو فهرست را بر اساس همان شماره مرتب می‌کنی (یا تقسیم می‌کنی روی سبدهای هشی) و بعد دو فهرست مرتب را کنار هم راه می‌بری. اینجا معلوم می‌شود چرا پیوند گران است: هزینه‌اش در جست‌وجو نیست، در مرتب‌کردن و جابه‌جا کردنِ داده است.Picture a library with two lists: loan slips and book cards. To learn which book is borrowed most, you must attach every slip to that book's card. With two small lists you can flip through and match by hand in minutes. With millions of slips nobody works leaf by leaf: you first sort both lists by the same number — or spread them across hash buckets — and then walk the two sorted lists side by side. That is where the cost of a join shows up: not in the search, but in sorting and moving data.

دو جدولTwo tablesسفارش و مشتریorders, customersتطبیق روی کلیدMatch on keyشمارهٔ مشتریcustomer idیک نتیجهOne resultردیف‌های کاملcombined rows
پیوند دو ورودی را روی یک کلید مشترک تطبیق می‌دهد و یک خروجی می‌سازد؛ کارِ سخت، هم‌جاکردنِ دو طرف است.A join matches two inputs on a shared key and produces one output; the hard part is co-locating both sides.

و بعدش، فنیAnd now, technically

پیوند ردیف‌های دو مجموعه را بر اساس یک شرط مشترک ترکیب می‌کند: در SQL با JOIN و در داده‌های توزیع‌شده با هم‌جاکردن دو طرف روی کلید پیوند. سه الگوریتم فیزیکی رایج است. حلقهٔ تودرتو، که برای هر ردیف یک طرف طرف دیگر را می‌گردد؛ ساده است و برای مجموعه‌های کوچک کافی. پیوند هشی، که هر دو طرف را روی تعداد ثابتی سبد تقسیم می‌کند و هر سبد را جدا پیوند می‌زند؛ برای مجموعه‌های بزرگ و بدون ترتیب مناسب است. پیوند مرتب‌سازی-ادغام، که هر دو طرف را روی کلید مرتب می‌کند و بعد مثل دو لیست مرتب جلو می‌رود؛ وقتی خروجی هم باید مرتب باشد ارزان‌تر تمام می‌شود. در پردازش توزیع‌شده، هر سه الگوریتم به یک چیز نیاز دارند: ردیف‌های هم‌کلید باید روی یک ماشین باشند، و همین یعنی shuffle. اگر یکی از دو طرف کوچک باشد، به‌جای shuffle می‌شود آن را به همه فرستاد (broadcast join) و شبکه را نجات داد.A join combines rows of two sets on a shared condition: in SQL with JOIN, in distributed data by co-locating both sides on the join key. Three physical algorithms dominate. Nested loop, which scans the other side for every row; simple, fine for small sets. Hash join, which partitions both sides into a fixed number of buckets and joins each bucket separately; good for large unordered sets. Sort-merge join, which sorts both sides on the key and walks them together; cheaper when the output must be sorted anyway. In distributed processing all three need the same thing: rows with the same key must sit on the same machine, and that means a shuffle. If one side is small, it can be broadcast to every worker instead, saving the shuffle.

1 keyبدون کلید مشترک، پیوند یا ممکن نیست یا باید همه را جابه‌جا کندwithout a common key a join either fails or moves everything
N × Mحجم نتیجه به تعداد تطبیق‌ها بستگی دارد، نه به تعداد ردیف‌هاthe result scales with matches, not with row counts

چرا پیوند گران‌ترین عملگر استWhy join is the expensive operator

در یک پرس‌وجوی تحلیلی، بیشتر زمان معمولاً به پیوند می‌رود و بیشتر خرابی‌ها هم از همان‌جا می‌آید. دلیل اول، حرکت داده است: برای اینکه ردیف‌های هم‌کلید کنار هم برسند، باید یا هر دو طرف مرتب شوند یا روی شبکه shuffle شوند، و این کار به اندازهٔ دادهٔ هر دو جدول هزینه دارد، نه به اندازهٔ نتیجه. دلیل دوم، کجی است: اگر یک کلید مشترک بسیار پرتکرار باشد، همان یک سبد چند برابر بقیه بزرگ می‌شود و یک ماشین همه را انجام می‌دهد. دلیل سوم، تکرار است: اگر کلید پیوند یکتا نباشد، هر ردیف سمت چپ با چند ردیف سمت راست جفت می‌شود و نتیجه از انتظار بزرگ‌تر می‌شود؛ گاهی چند برابر.In an analytical query most of the time usually goes to the join, and most of the failures come from there. First, data movement: for rows of the same key to meet, both sides must be sorted or shuffled across the network, and that costs the size of both tables, not the size of the result. Second, skew: if one join key is very frequent, that single bucket grows to several times the others and one machine does all the work. Third, duplication: if the join key is not unique, each left row pairs with several right rows and the result is larger than expected — sometimes many times larger.

تلهٔ رایجThe usual trap

پیوند زدن روی کلیدی که یکتا نیست و بعد تعجب کردن از اینکه تعداد ردیف‌ها چند برابر شد. یک کلید پیوند که در یک طرف تکراری است، مثل ضرب‌کردن دو مجموعه است، نه اضافه کردنشان؛ و اگر بعد از پیوند جمع بزنی، عدد چند بار حساب شده است.Joining on a non-unique key and then being surprised that the row count multiplied. A duplicated key on one side multiplies the sets rather than adding them; if you sum after the join, several values have been counted more than once.

keyset pagination

صفحه‌بندی کلیدمحور فصل ۳Chapter 3 · دیدن در متنsee in context

صفحهٔ بعد از کجا شروع می‌شود، بی‌آنکه چیزی بشماری؟Where does the next page start, without counting anything?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

شب کتاب می‌خوانی و خوابت می‌برد. جای خودت را با یک لنگه کاغذ علامت می‌زنی، نه با شمردن صفحه‌های خوانده‌شده. فردا شب از همان علامت ادامه می‌دهی. صفحه‌بندی کلیدمحور همین است: جای شروع را از «آخرین چیزی که دیدم» می‌گیری، نه از تعداد.You read at night until you fall asleep. You mark your place with a scrap of paper, not by counting the pages you have read. Tomorrow you continue from the mark. Keyset pagination is that: you start from the last thing you saw, not from a count.

تشبیه و تصویر ذهنیThe analogy

صف نانوایی را تصور کن. تو می‌گویی «نفر بعد از آن آقای کلاه‌دار»، نه «نفر بیستم». اگر کسی از صف برود یا یکی تازه بایستد، «نفر بیستم» عوض می‌شود و ممکن است یک نفر را دو بار ببینی یا یکی را کامل جا بگذاری؛ ولی «بعد از آقای کلاه‌دار» سر جایش می‌ماند. بهایش این است که همیشه باید یک نشانهٔ مشخص بلد باشی و ترتیب صف هم باید پایدار بماند.Picture the queue at a bakery. You say “the person after the man in the hat”, not “the twentieth person”. If somebody leaves or joins, “the twentieth” shifts and you may see one person twice or skip one entirely, while “after the man in the hat” stays put. The price is that you must always carry a specific marker, and the order of the queue has to stay stable.

صفحه‌بندی offsetOffset pagingردیف‌ها را می‌شماردcounts rows firstصفحهٔ n گران‌ترpage n costs moreمرزها جابه‌جا می‌شوندboundaries shiftکلیدمحورKeyset pagingاز آخرین کلیدfrom the last keyهمهٔ صفحه‌ها هم‌قیمتevery page costs alikeکلید یکتا لازم استneeds a unique key
offset ردیف‌ها را می‌شمارد و دور می‌ریزد؛ کلیدمحور فقط از آخرین کلید جلو می‌رود.Offset counts past rows and throws them away; keyset simply steps forward from the last key.

و بعدش، فنیAnd now, technically

در صفحه‌بندی کلیدمحور، مرتب‌سازی روی یک کلید یکتا انجام می‌شود، معمولاً (زمان، شناسه)، و صفحهٔ بعد با شرطی مثل WHERE (created_at, id) > (آخرین مقدار دیده‌شده) و ORDER BY همان کلید و LIMIT ۲۰ گرفته می‌شود. با ایندکس مناسب، این فقط یک پیمایش بازه‌ای کوچک است، پس هزینهٔ هر صفحه تقریباً ثابت می‌ماند. در صفحه‌بندی offset، دیتابیس باید به اندازهٔ OFFSET ردیف را رد کند و تازه بعد دورشان بریزد؛ صفحهٔ هزارم یعنی خواندن هزار صفحهٔ قبلی. مشکل بدتر هم دارد: اگر بین دو درخواست ردیفی درج یا حذف شود، مرزها جابه‌جا می‌شوند و کاربر ردیفی را دو بار می‌بیند یا اصلاً نمی‌بیند. کلید مرتب‌سازی باید یکتا باشد، وگرنه بین دو صفحه با مقدار تکراری بعضی ردیف‌ها گم می‌شوند؛ به همین دلیل شناسه را به‌عنوان تای‌بریکر اضافه می‌کنند. در عوض، پرش به «صفحهٔ ۵۷» دیگر مستقیم نیست و برای هر ترتیب دلخواه به ایندکس مناسب نیاز داری.Keyset pagination sorts on a unique key, usually (time, id), and asks for the next page with a predicate such as WHERE (created_at, id) > (last seen), ORDER BY the same key and LIMIT 20. With the right index that is one small range scan, so each page costs roughly the same. Offset pagination instead makes the database walk past OFFSET rows and throw them away; page one thousand means reading the previous thousand pages first. Worse, if a row is inserted or deleted between two requests the boundaries shift and the reader sees one row twice or misses it entirely. The sort key must be unique, or rows with equal values slip between pages, which is why the id is appended as a tie-breaker. In exchange you can no longer jump straight to “page 57”, and every sort order you offer needs a matching index.

OFFSET 10000دیتابیس همچنان ۱۰۰۲۰ ردیف را رد می‌کندthe database still walks past 10,020 rows
O(1)هزینهٔ هر صفحه، مستقل از شمارهٔ صفحهeach page costs the same regardless of its number
2 colsکلید مرتب‌سازی باید یکتا شود: زمان به‌همراه شناسهthe sort key must be unique: time plus id

تلهٔ رایجThe usual trap

مرتب‌سازی روی ستونی که یکتا نیست. با created_at تنها، دو رکورد هم‌زمان می‌توانند بین دو صفحه بیفتند و یکی از آن‌ها هیچ‌وقت دیده نشود. اگر شناسه را به کلید اضافه نکنی، این باگ فقط وقتی پیدا می‌شود که حجم نوشتن بالا برود یا کاربر واقعاً صفحه‌به‌صفحه جلو برود — و آن‌وقت ردیف گم‌شده در گزارش‌ها هم گم است.Sorting on a column that is not unique. With created_at alone, two rows written in the same instant can fall between pages and one of them is never seen. Without the id in the key, the bug only appears once write volume rises or a user actually pages forward — and by then the missing row is missing from the reports too.

چرا خواندن چیزهایی که کنار هم‌اند ارزان‌تر است؟Why is reading things that sit together cheaper?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

آشپزخانه‌ات را چیده‌ای: نمک و فلفل کنار اجاق، قابلمه‌ها زیر اجاق. وقتی غذا می‌پزی، دستت یک بار دراز می‌شود، نه ده بار. اگر نمک در انبار باشد، برای هر غذا یک راه‌روی کامل می‌روی. محلی‌بودن در دیتابیس هم همین است: چیزهایی که با هم لازم می‌شوند، کنار هم بنشینند.Your kitchen is arranged: salt and pepper by the stove, pots underneath it. When you cook, your hand reaches once and comes back. If the salt lived in the basement you would walk a corridor for every dish. Locality in a database is the same: things needed together sit together.

تشبیه و تصویر ذهنیThe analogy

انبار یک فروشگاه اینترنتی را تصور کن. اگر همهٔ کالاهای یک سفارش در یک قفسه باشند، انباردار یک بار می‌رود و برمی‌گردد؛ اگر هر کالا در گوشه‌ای باشد، برای همان سفارش ده راه‌رو را می‌پیماید. حالا انبار را برای یک نوع سفارش بچین و ببین چه می‌شود: سفارش‌های بعدی که ترکیب دیگری دارند، دوباره پخش می‌شوند. محلی‌بودن همیشه یک انتخاب است؛ آن را برای کوئری‌ای می‌چینی که مهم‌تر است و کوئری بعدی را گران‌تر می‌کنی.Picture the warehouse of an online shop. If everything in one order sits on one shelf, the picker walks once; if the items are scattered, the same order costs ten aisles. Now arrange the warehouse for one kind of order and watch what happens: the next orders, with different mixes, are scattered again. Locality is always a choice — you arrange it for the query that matters most and make the next one more expensive.

و بعدش، فنیAnd now, technically

دیسک و SSD داده را بلوک‌بلوک می‌خوانند، نه بایت‌به‌بایت؛ پس هر خواندن یک هزینهٔ ثابت دارد و خواندن دنباله‌ای آن هزینه را روی دادهٔ بیشتری پخش می‌کند. محلی‌بودن یعنی چیدمان داده با الگوی دسترسی جور باشد. مدل سندی کل یک سند را پیوسته نگه می‌دارد، پس «این سند را بیاور» یک خواندن است. ذخیره‌سازی ستونی مقادیر یک ستون را پیوسته می‌چیند، پس میانگین روی یک ستون با خواندن یک ناحیهٔ پیوسته حساب می‌شود. ایندکس خوشه‌ای ردیف‌ها را به ترتیب کلید روی دیسک می‌نشاند، پس پیمایش بازه‌ای دنباله‌ای است. هزینه‌اش این است که یک چیدمان برای یک الگو خوب است و برای الگوی دیگر بد؛ و اگر کلید مرتب‌سازی با زمان جلو برود، همهٔ نوشتن‌های امروز به یک نقطه می‌رسند و آن نقطه داغ می‌شود.Disks and SSDs read in blocks, not bytes, so every read carries a fixed cost and a sequential read spreads that cost over more data. Locality means the layout matches the access pattern. A document model keeps a whole document contiguous, so “fetch this document” is one read. Column storage keeps one column's values contiguous, so an average over that column is one contiguous region. A clustered index lays rows on disk in key order, so a range scan stays sequential. The price is that a layout suits one pattern and punishes another; and if the sort key advances with time, every write today lands at one point and that point goes hot.

4–16 KBبلوکی که دیسک در یک خواندن می‌آوردthe block a disk fetches in one read
1 readسند پیوسته یعنی آوردنش یک خواندن استa contiguous document costs one read
1 columnدر چیدمان ستونی، یک ستون یک ناحیهٔ پیوسته استin column layout, one column is one contiguous region

تلهٔ رایجThe usual trap

چیدن داده برای یک کوئری و فراموش کردن بقیه. سند کاربر را کامل و پیوسته ذخیره می‌کنی تا پروفایلش سریع بیاید، بعد گزارش «همهٔ سفارش‌های امروز» باید هزار سند را باز کند و هر کدام را جدا بخواند. محلی‌بودن رایگان نیست؛ همان چیدمانی که یک مسیر را کوتاه می‌کند، مسیر دیگر را طولانی می‌کند.Arranging data for one query and forgetting the rest. You store each user's document whole and contiguous so the profile loads fast, then the “all orders today” report has to open a thousand documents and read each one on its own. Locality is not free: the layout that shortens one path lengthens another.

materialized view

نمای مادی‌شده فصل ۳Chapter 3 · دیدن در متنsee in context

چرا جوابی را که می‌شود حساب کرد، ذخیره می‌کنی؟Why store an answer you could compute?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

روی در یخچال یک کاغذ چسبانده‌ای: «شیر تمام شد، نان هست». این کاغذ خودش داده نیست؛ از نگاه کردن به یخچال ساخته شده. هر وقت چیزی می‌خری یا مصرف می‌کنی، کاغذ را هم عوض می‌کنی تا با داخل یخچال یکی بماند. اگر یک هفته به آن دست نزنی، دیگر راست نمی‌گوید. نمای مادی‌شده همان کاغذ است: جوابی که یک بار حساب شده و ذخیره شده.There is a note stuck to the fridge door: out of milk, still have bread. The note is not the data; it was made by looking inside the fridge. Every time you shop or cook you update the note too, so it still matches what is inside. Leave it alone for a week and it starts lying. That note is a materialized view: an answer computed once and kept.

تشبیه و تصویر ذهنیThe analogy

کاغذ یخچال از باز کردن در و شمردن قوطی‌ها سریع‌تر است و همین برنده شدن است. اما سه حالت دارد: هر بار که چیزی عوض می‌شود کاغذ را هم عوض می‌کنی، که نوشتن را گران می‌کند؛ یا هر شب یک بار از نو می‌نویسی، که تا فردا صبح کاغذ کهنه است؛ یا تا کسی نپرسیده دست نمی‌زنی و لحظهٔ پرسیدن تازه‌اش می‌کنی، که آن لحظه را کند می‌کند. انتخاب بین این سه، همان انتخاب بین هزینهٔ نوشتن و کهنگی است، و باید بر اساس اینکه کدام سؤال چقدر کهنه می‌تواند باشد گرفته شود.The fridge note beats opening the door and counting cartons, and that is the whole win. But it comes in three modes: update the note whenever something changes, which makes the writing expensive; rewrite it once a night, which leaves it stale until morning; or leave it alone until someone asks and refresh it at the moment of asking, which makes that moment slow. Choosing among the three is choosing between write cost and staleness, and the choice belongs to how stale each question is allowed to be.

تغییر در جدولBase table changesنوشتنa writeبه‌روزرسانی نماRefresh the viewافزایشی یا کاملincremental or fullنتیجهٔ ذخیره‌شدهStored resultمثل یک جدولlike a tableخواندن سریعFast readیک lookupone lookup
نتیجهٔ پرسش یک بار حساب و ذخیره می‌شود؛ بعد هر تغییر باید دوباره به آن برسد.The result is computed once and stored; after that every change has to reach it.

و بعدش، فنیAnd now, technically

نمای مادی‌شده نتیجهٔ یک پرسش است که به شکل داده ذخیره شده، نه به شکل متن پرسش. برخلاف view معمولی که هر بار خواندن اجرا می‌شود، اینجا نتیجه از پیش حساب شده و خواندن فقط یک lookup است. نگهداری‌اش سه راه دارد: به‌روزرسانی افزایشی هنگام نوشتن با trigger یا CDC یا جریان رویداد، بازسازی کامل دوره‌ای، و بازسازی تنبل هنگام خواندن. هر سه یک معامله‌اند: خواندن ارزان، نوشتن یا فضای بیشتر. مزیت پنهانش این است که روی نتیجه می‌شود ایندکس گذاشت و یک پرسش چندجدولی سنگین را به یک جست‌وجوی ساده تبدیل کرد. کهنگی را هم باید اندازه گرفت؛ هر نما یک عدد عقب‌ماندگی دارد و اگر آن را ندانی، روزی کاربر جواب قدیمی می‌بیند و فکر می‌کند سیستم خراب است. در سیستم تقسیم‌شده، نما معمولاً باید کنار داده‌ای باشد که پرسش از آن می‌آید، وگرنه خودش یک fan-out می‌شود.A materialized view is the result of a query stored as data rather than as query text. Unlike an ordinary view, which runs on every read, the result is already computed and reading it is just a lookup. There are three ways to maintain it: incremental update on write through triggers, CDC or an event stream; full refresh on a schedule; and lazy refresh at read time. All three strike the same bargain: cheap reads for more write work or more space. A hidden benefit is that you can index the result, turning an expensive multi-table query into a simple lookup. Staleness has to be measured too: every view has a lag number, and if you do not know it, one day a user sees a stale answer and concludes the system is broken. In a partitioned system the view usually has to sit next to the data it summarises, or it becomes a fan-out of its own.

0 joinدر زمان خواندن، join دوباره اجرا نمی‌شودno join runs at read time
ms–minپنجرهٔ کهنگی که باید صریح انتخاب شودthe staleness window you have to choose openly
×Nهر نما یک نسخهٔ اضافه از داده استeach view is one more copy of the data

نما، کش و ایندکس یک خانواده‌اندViews, caches and indexes are one family

هر سه یک کار می‌کنند: چیزی را از دادهٔ اصلی می‌سازند تا خواندن ارزان شود. ایندکس ترتیب را ذخیره می‌کند، کش نتیجه را در حافظه نگه می‌دارد، نمای مادی‌شده نتیجه را به شکل یک جدول نگه می‌دارد. هر سه دادۀ مشتق‌شده‌اند، یعنی از دادهٔ اصلی ساخته می‌شوند و در صورت شک به آن قابل بازگشت‌اند. همین ویژگی دو قاعده به تو می‌دهد: می‌شود پاکشان کرد و از نو ساخت، و هر کدام هزینه‌ای روی نوشتن می‌گذارند. اگر هزینهٔ نوشتن را نادیده بگیری، با ده نما یک سیستم نوشتنی را به زانو درمی‌آوری.All three do the same job: build something from the base data so reads get cheap. An index stores order, a cache keeps a result in memory, a materialized view keeps a result as a table. All three are derived data: built from the base, and recoverable from it when in doubt. That gives two rules. You can drop them and rebuild them, and each one charges a tax on writes. Ignore the tax and ten views will bring a write-heavy system to its knees.

کهنگی را چطور مدیریت کنیHow to manage the staleness

اول تصمیم بگیر که هر پرسش چقدر می‌تواند کهنه باشد؛ عدد را بنویس، چون «تقریباً تازه» معیار نیست. دوم عقب‌ماندگی را اندازه بگیر و همان را به کاربر نشان بده؛ یک برچسب «تا پنج دقیقه پیش» از یک عدد دروغ بهتر است. سوم، بازسازی کامل را با احتیاط انجام بده: یک بازسازی سنگین روی جدول بزرگ، هم دیسک را پر می‌کند هم ترافیک خواندن را می‌خورد. چهارم، زنجیرهٔ نما روی نما را کوتاه نگه دار؛ هر پله تأخیر و حالت خرابی تازه‌ای اضافه می‌کند.First decide how stale each question may be, and write the number down, because nearly fresh is not a criterion. Second, measure the lag and show it: a label reading as of five minutes ago beats a lie. Third, be careful with full rebuilds, because a heavy refresh over a large table eats disk and read traffic at the same time. Fourth, keep chains of views over views short; every extra step adds latency and a new way to be wrong.

view در برابر نمای مادی‌شدهView versus materialized view

viewViewنمای مادی‌شدهMaterialized view
چه ذخیره می‌شودWhat is storedمتن پرسشthe query textنتیجهٔ پرسشthe query result
هر خواندنEach readپرسش دوباره اجرا می‌شودthe query runs againفقط یک lookupjust a lookup
تازگیFreshnessهمیشه تازهalways freshبه اندازهٔ پنجرهٔ به‌روزرسانیas fresh as the refresh window

تلهٔ رایجThe usual trap

بازسازی کامل نما بعد از هر نوشتن. کار روی دادهٔ کم درست جواب می‌دهد و در تولید به یک جدول قفل‌شده و صفی از نوشتن‌های منتظر تبدیل می‌شود. به‌روزرسانی باید افزایشی باشد، یا کلاً از مسیر نوشتن بیرون بماند.Refreshing the whole view after every write. It looks fine on small data and turns into a locked table with a queue of waiting writes in production. Maintenance should be incremental, or it should not be on the write path at all.

یک کوئری برای فهرست، و بعد یکی برای هر ردیف؟One query for the list, then one for every row?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

فهرست خرید ده قلمی داری. به‌جای یک بار رفتن به سوپرمارکت، برای هر قلم جداگانه برمی‌گردی خانه و دوباره راه می‌افتی. ده قلم، یازده سفر. برنامه‌ات هم همان را می‌کند: یک کوئری برای فهرست، و یکی برای هر ردیف.You have a ten-item shopping list. Instead of one trip to the shop, you walk back home after each item and set out again. Ten items, eleven trips. Your code does the same: one query for the list, one more for each row.

تشبیه و تصویر ذهنیThe analogy

حالا حساب واقعی را ببین. هر سفر فقط مسیر نیست؛ پارک کردن، صف صندوق و پرداخت هم هست. برای همین صد سفر کوچک تقریباً به اندازهٔ صد سفر کامل خرج دارد، حتی اگر هر بار فقط یک قلم بخری. در دیتابیس هم همان هزینهٔ ثابت هر رفت‌وبرگشت است که کار را خراب می‌کند، نه حجم داده. با پنج ردیف روی لپ‌تاپ خودت هیچ‌چیز نیست؛ با پانصد ردیف و پنجاه درخواست در ثانیه، همان الگو کل صف را می‌بندد.Now the real arithmetic. A trip is not just the walk: parking, the queue and paying are in it too. So a hundred small trips cost about as much as a hundred full ones even when each buys a single item. In a database the fixed cost of each round trip is what hurts, not the volume of data. With five rows on your laptop nothing shows; with five hundred rows and fifty requests a second the same pattern closes the queue.

11۱۰ ردیف10 rows101۱۰۰ ردیف100 rows1001۱۰۰۰ ردیف1000 rows
تعداد کوئری‌ها با تعداد ردیف‌ها بالا می‌رود: ده ردیف یازده کوئری، هزار ردیف هزار و یک کوئری.Queries grow with rows: ten rows mean eleven queries, a thousand rows mean a thousand and one.

و بعدش، فنیAnd now, technically

N+1 وقتی می‌آید که اول یک کوئری برای گرفتن فهرست بزنی و بعد برای هر عضو فهرست یک کوئری جدا بزنی. رایج‌ترین راه رسیدنش خواندن تنبل در ORM است: فهرست سفارش‌ها را می‌گیری، بعد در حلقه به customer هر سفارش دست می‌زنی و هر دست‌زدن یک رفت‌وبرگشت تازه می‌سازد. هزینه خطی است: N ردیف یعنی N+1 کوئری، و هر کوئری هزینهٔ ثابت خودش را دارد، از رفت‌وبرگشت شبکه تا تجزیه و برنامه‌ریزی. راه‌حل‌ها دو دسته‌اند: همه را در یک کوئری بگیر (join یا خواندن حریص)، یا دسته‌ای بگیر و شناسه‌ها را با IN بفرست تا دو کوئری کافی باشد. این الگو با صفحه‌بندی هم بدتر می‌شود، چون تعداد ردیف‌ها را کسی در کد نمی‌بیند و دادهٔ محیط توسعه کوچک می‌ماند.N+1 appears when you first run one query for a list and then one separate query for each member of it. The usual route is lazy loading in an ORM: you load the orders, touch each order's customer inside a loop, and every touch becomes a fresh round trip. The cost is linear — N rows means N+1 queries — and every query pays its own fixed price, from the network round trip to parsing and planning. The fixes come in two shapes: fetch everything in one query (a join, or eager loading), or fetch in batches and send the ids with IN so two queries suffice. Pagination makes it worse, because nobody in the code sees how many rows are involved and the development data stays small.

1 + Nیک کوئری فهرست، N کوئری برای جزئیاتone list query, N detail queries
101 queriesبرای ۱۰۰ ردیف، صد و یک رفت‌وبرگشتfor 100 rows, a hundred and one round trips
2 queriesبا IN، همان کار معمولاً به دو کوئری می‌رسدwith IN the same work usually drops to two

تلهٔ رایجThe usual trap

این باگ در محیط توسعه دیده نمی‌شود، چون همه چیز محلی و چند میلی‌ثانیه‌ای است. تنها راه مطمئن، شمردن تعداد کوئری‌ها در هر درخواست است، نه اندازه‌گیری زمان کل. اگر شمارنده نداشته باشی، N+1 همیشه اول در تولید و در بدترین ساعت پیدا می‌شود.The bug is invisible in development, where everything is local and a few milliseconds away. The only reliable check is counting queries per request, not timing the endpoint. Without that counter, N+1 is always discovered in production, at the worst hour.

normalization

نرمال‌سازی فصل ۳Chapter 3 · دیدن در متنsee in context همچنینalso in فصل ۴ch 4

هر واقعیت را چند بار نگه می‌داری؟How many times do you keep the same fact?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

قبل از مهمانی، فهرست مهمان‌ها را روی یک کاغذ می‌نویسی: اسم، شماره، و غذایی که می‌خورد. حالا اگر همان اسم را روی کارت دعوت، روی فهرست خرید و روی دفتر حساب هم بنویسی، سه نسخه داری. یکی از مهمان‌ها زنگ می‌زند و می‌گوید گوشت نمی‌خورد؛ باید سه جا را عوض کنی، و اگر یکی جا بماند، شب مهمانی یک بشقاب اشتباه سر میز می‌رود. نرمال‌سازی یعنی همان یک کاغذ، و بقیه فقط به آن نگاه کنند.Before a dinner party you write the guest list on one sheet: name, number, and what they eat. Now copy that name onto the invitation cards, the shopping list and the expense notebook, and you have three copies. One guest calls to say they no longer eat meat, so three places must change, and a missed one puts the wrong plate on the table. Normalization means keeping the one sheet and letting everything else look at it.

تشبیه و تصویر ذهنیThe analogy

وقتی هر واقعیت یک جا نوشته شده باشد، عوض کردنش یک حرکت است و جا ماندن تقریباً غیرممکن. این آرامش را با یک هزینه می‌خری: برای جواب دادن به هر سؤال باید چند کاغذ را کنار هم بگذاری. «چند نفر گوشت نمی‌خورند؟» جوابش روی همان یک کاغذ است، ولی «برای هر مهمان چه خریدی کردیم و چقدر شد؟» باید فهرست خرید را با فهرست مهمان‌ها جفت کنی. هر چه بیشتر نرمال کنی، نوشتن امن‌تر و خواندن پرزحمت‌تر می‌شود؛ همین است که نرمال‌سازی یک تصمیم است، نه یک قانون اخلاقی.When each fact is written in one place, changing it is a single move and leaving it behind is nearly impossible. You buy that calm with a cost: answering any question means putting several sheets side by side. How many guests avoid meat is on the one sheet, but what did we buy for each guest and what did it cost means pairing the shopping list with the guest list. The more you normalise, the safer writing gets and the more work reading becomes, which is why normalization is a decision rather than a moral law.

۱NF · مقدار اتمی1NF · atomic values۲NF · وابستگی کامل به کلید2NF · no partial dependency۳NF · بدون وابستگی گذرا3NF · no transitive dependencyBCNF · تعیین‌کننده = کلیدBCNF · determinant is a key
هر پله یک نوع تکرار را برمی‌دارد؛ نتیجه: هر واقعیت یک جا و خواندن با join.Each rung removes one kind of duplication; the result is one home per fact and reads that join.

و بعدش، فنیAnd now, technically

نرمال‌سازی تجزیهٔ یک طرح‌واره به جدول‌هایی است که در هر کدام یک واقعیت زندگی می‌کند، تا تغییر یک مقدار فقط یک جا بنشیند. معیارش وابستگی تابعی است: اگر دانستن A همیشه B را مشخص کند، B جای دیگری نباید تکرار شود. سه شکل اول هر کدام یک نوع تکرار را برمی‌دارند: ۱NF مقدار اتمی می‌خواهد، ۲NF وابستگی جزئی به بخشی از کلید مرکب را رد می‌کند، ۳NF وابستگی گذرا را، و BCNF سخت‌گیرتر است و هر عامل تعیین‌کننده را کلید می‌خواهد. نتیجه‌اش حذف ناهنجاری‌های به‌روزرسانی و درج و حذف است، و بهایش این است که خواندن باید جدول‌ها را دوباره به هم وصل کند. به همین دلیل نرمال‌سازی پیش‌فرض دادهٔ تراکنشی است و نرمال‌زدایی یک استثنای آگاهانه.Normalization decomposes a schema into tables where each fact lives in one place, so that changing a value writes in one place only. The test is functional dependency: if knowing A always determines B, then B must not be repeated elsewhere. The first three forms each remove one kind of duplication: 1NF wants atomic values, 2NF rejects a dependency on part of a composite key, 3NF rejects transitive dependency, and BCNF is stricter still, requiring every determinant to be a key. The gain is the disappearance of update, insert and delete anomalies; the price is that reads must join the tables back together. That is why normalization is the default for transactional data and denormalization is a deliberate exception.

1 بارهر واقعیت یک بار نوشته می‌شودeach fact is written once
0 نسخههیچ نسخهٔ دومی برای هماهنگ کردن نمی‌ماندno second copy is left to reconcile
joinبهایش: خواندن باید جدول‌ها را وصل کندthe price: reads must join the tables

این سه اسم عجیب از کجا می‌آیندWhere those odd names come from

نرمال‌سازی برای درمان سه درد ساخته شد، و هر شکل یکی از آن‌ها را می‌گیرد. درد اول به‌روزرسانی است: شمارهٔ تلفن یک مشتری در پنج فاکتور تکرار شده و تو یکی را عوض می‌کنی. درد دوم درج است: نمی‌توانی یک مشتری تازه ثبت کنی تا وقتی فاکتوری هم برایش نساخته باشی، چون همه چیز در یک ردیف است. درد سوم حذف است: آخرین فاکتور را پاک می‌کنی و ناخواسته اطلاعات مشتری هم با آن می‌رود. هر سه یک ریشه دارند: چند واقعیت در یک جا نشسته‌اند.Normalization was built to cure three pains, and each form takes one of them. The first is the update pain: a customer phone number is repeated across five invoices and you correct one. The second is the insert pain: you cannot add a new customer until you also invent an invoice, because everything lives in one row. The third is the delete pain: you remove the last invoice and the customer's details go with it. All three share one root: several facts sitting in one place.

چه چیزی را گران می‌کندWhat it makes expensive

نرمال‌سازی جدول‌ها را زیاد می‌کند و خواندن را به join وابسته می‌کند، پس بهینه‌ساز باید برای هر پرسش تصمیم بگیرد جدول‌ها را به چه ترتیبی وصل کند. بیشتر این هزینه در عمل دیده نمی‌شود، چون join روی کلید و با ایندکس ارزان است. جایی که واقعاً گران می‌شود، پرسش‌های تحلیلی است که ده‌ها جدول را به هم می‌بافند و هر بار میلیون‌ها ردیف را جابه‌جا می‌کنند؛ همان‌جاست که آدم‌ها به جدول جمع‌بندی یا انبار داده پناه می‌برند. تفاوت را بگذار بین بار تراکنشی و بار تحلیلی، نه بین خوب و بد.Normalization multiplies tables and makes reads depend on joins, so the optimizer must decide a join order for every query. In practice most of that cost is invisible, because a join on a key with an index is cheap. It truly becomes expensive in analytical queries that weave dozens of tables and move millions of rows each time, which is exactly where people reach for aggregate tables or a warehouse. Make the distinction between transactional and analytical load, not between good and bad.

نرمال‌شده در برابر نرمال‌زدایی‌شدهNormalized versus denormalized

نرمال‌شدهNormalizedنرمال‌زدایی‌شدهDenormalized
هر واقعیتEach factیک جاone placeچند جاseveral places
خواندنReadjoin لازم داردneeds a joinبدون joinno join
نوشتنWriteیک نقطهone spotهمهٔ نسخه‌هاevery copy
خطر اصلیMain riskjoin کندslow joinsنسخهٔ ناهماهنگcopies that drift

تلهٔ رایجThe usual trap

گفتن «ما نرمال هستیم» در حالی که جمع‌ها و مبالغ مشتق‌شده در جدول ذخیره می‌شوند. همان لحظه که یک مبلغ ذخیره شد، یک نسخهٔ دوم ساخته‌ای و باید مثل هر نسخهٔ دیگری نگهداری‌اش کنی؛ وگرنه روزی مجموع فاکتورها با ستون جمع فرق می‌کند.Declaring the schema normalized while totals and derived amounts are stored in a column. The moment that amount is written you have a second copy, and it needs the same care as any other copy; otherwise the sum of the lines and the stored total disagree one day.

لایه‌ای که جدول را شیء نشان می‌دهد؛ چه چیزی را پنهان می‌کند؟A layer that makes tables look like objects. What does it hide?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

در مطب دکتر، مترجم بین تو و دکتر می‌نشیند. تو می‌گویی «سرم درد می‌کند»، او به دکتر می‌گوید. کارت راه می‌افتد و خودت لازم نیست اصطلاح پزشکی بلد باشی؛ ولی اگر مترجم جمله‌ات را کوتاه کند، تا آخر ویزیت نمی‌فهمی چه گفته شده. ORM هم همان مترجم است، بین شیءهای تو و جدول‌های دیتابیس.At the doctor's office an interpreter sits between you and the doctor. You say “my head hurts”, she says it in the doctor's language. It works, and you never need the medical vocabulary yourself; but if she shortens your sentence you never find out what was said. An ORM is that interpreter, between your objects and the database tables.

تشبیه و تصویر ذهنیThe analogy

مترجم خوب فقط ترجمه نمی‌کند؛ تصمیم هم می‌گیرد. وقتی می‌گویی «برای این ده بیمار نسخه بنویس»، او می‌تواند یک بار با دکتر حرف بزند یا ده بار برای هر بیمار برگردد. اگر برگردد، تو از بیرون فقط می‌بینی کار طول کشید، نه این‌که ده بار در باز شد. مترجم می‌تواند جمله‌ات را بهتر بگوید یا بدتر؛ چون تو زبان دکتر را نمی‌دانی، تفاوت را نمی‌فهمی. تنها راهش این است که گاهی پرونده را خودت بخوانی: نقشهٔ اجرای کوئری را ببینی و بفهمی مترجم چه گفته.A good interpreter does more than translate; she decides things. When you say “write prescriptions for these ten patients”, she can talk to the doctor once or come back ten times, one patient at a time. If she comes back each time, from the outside you only see that it took long, not that the door opened ten times. She can also phrase you better or worse, and since you do not speak the doctor's language you cannot tell the difference. The only cure is to read the file yourself now and then: look at the execution plan and see what the interpreter actually said.

و بعدش، فنیAnd now, technically

ORM کلاس‌ها را به جدول، ویژگی‌ها را به ستون و ارجاع‌ها را به کلید خارجی نگاشت می‌کند. سه چیز اضافه بر نگاشت می‌دهد: نگاشت هویت (هر ردیف در طول یک تراکنش فقط یک شیء است)، واحد کار (تغییرها جمع می‌شوند و در پایان یک تراکنش نوشته می‌شوند) و خواندن تنبل برای رابطه‌ها. سودش کم‌شدن کد تکراری، ایمنی نوع و اعتبارسنجی در یک جاست. هزینه‌اش این است که SQL تولیدشده را نمی‌بینی: ستون‌هایی که لازم نداری خوانده می‌شوند، هر تغییر یک دستور جدا می‌شود و رابطه‌ها می‌توانند به N+1 برسند. برای CRUD ساده خوب است؛ برای گزارش‌های سنگین و کوئری‌های داغ، SQL دستی تقریباً همیشه برنده است.An ORM maps classes to tables, attributes to columns and references to foreign keys. It adds three things beyond the mapping: an identity map (one row is one object for the life of a transaction), a unit of work (changes accumulate and are written at commit) and lazy loading of relations. The gain is less boilerplate, type safety and validation in one place. The price is that you do not see the generated SQL: columns you do not need get read, each change becomes its own statement, and relations can quietly become N+1. It is good for simple CRUD; for heavy reports and hot queries, hand-written SQL almost always wins.

1 save()یک فراخوانی می‌تواند چند دستور SQL بسازدone call can become several statements
0 SQLکدی که SQL نمی‌نویسد، نقشهٔ اجرا را هم نمی‌بیندcode that writes no SQL never sees a plan

ORM در برابر SQL دستیORM versus hand-written SQL

ORMORMSQL دستیHand-written SQL
کارهای سادهSimple CRUDکوتاه و خواناshort and readableتکراری، ولی شفافrepetitive but explicit
گزارش سنگینHeavy reportممکن است SQL بد بسازدmay generate a poor statementکامل در دست خودتentirely in your hands
دیدن هزینهSeeing the costباید لاگ کوئری را روشن کنیyou must turn on query loggingهمان چیزی است که نوشتیit is what you wrote
تغییر مدلModel changeمهاجرت خودکار، با ریسکautomated migration, with riskدستی و کندتر، ولی دقیقmanual and slower, but exact

تلهٔ رایجThe usual trap

اعتماد به این‌که SQL تولیدشده همان است که خودت می‌نوشتی. یک accessor در حلقه، یک رابطهٔ تنبل داخل سریالایزر، و یک درخواست ساده به هشتاد کوئری تبدیل می‌شود؛ همه‌اش هم در کد بی‌گناه به نظر می‌رسد. تا وقتی تعداد کوئری‌ها را نشماری، ORM هزینه‌اش را بی‌صدا می‌گیرد.Trusting that the generated SQL is what you would have written. One accessor inside a loop, one lazy relation inside a serializer, and a simple request becomes eighty queries, all of it looking innocent in the code. Until you count queries, the ORM charges you silently.

همان رویدادها، چند جواب مختلف.The same events, several different answers.

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

از مهمانی یک نوار فیلم داری. برای مادرت آن را به آلبوم عکس کوتاه تبدیل می‌کنی؛ برای صاحبخانه فقط یک فهرست «چند نفر آمدند» می‌سازی. نوار یکی است و دست نمی‌خورد، ولی هر کس نسخهٔ خودش را می‌بیند. هر نسخه با یک قاعدهٔ ساده از همان نوار ساخته می‌شود و اگر خراب شود، دوباره از نوار ساخته می‌شود. برون‌فکنی همین تبدیل است: یک قاعده، یک نسخهٔ خوانا از رویدادها.You have one film of the party. For your mother you turn it into a short photo album; for the landlord you make a list of how many people came. The film is one and untouched, yet each person sees their own version. Each version comes from the same film through a simple rule, and if it is ruined it is built again from the film. A projection is that conversion: one rule, one readable version of the events.

تشبیه و تصویر ذهنیThe analogy

این تبدیل باید همیشه یک جواب بدهد. اگر قاعده‌ات این باشد که «هر بار عکس را با تاریخ امروز برچسب بزن»، دو بار ساختن یک آلبوم دو جواب می‌دهد و دیگر نمی‌شود فهمید کدام درست است. برای همین قاعده را طوری می‌نویسی که فقط به خود نوار نگاه کند: تاریخ عکس، از خود عکس. آن‌وقت می‌توانی آلبوم را پاک کنی و از اول بسازی و مطمئن باشی همانی است که بود. چند نسخه هم می‌شود ساخت: آلبوم برای مادر، فهرست برای صاحبخانه، هر کدام با قاعدهٔ خودش و هر کدام چند قدم عقب‌تر از نوار.That conversion has to give the same answer every time. If your rule is stamp each photo with today's date, building the album twice gives two different answers and nobody can tell which is right. So you write the rule to look only at the film: the date comes from the photo itself. Then you can throw the album away and rebuild it, sure that it will be what it was. You can also keep several versions: the album for your mother, the list for the landlord, each with its own rule and each a few steps behind the film.

زنجیرهٔ رویدادEvent logترتیب ثابتfixed orderبرون‌فکنProjectorتابع معینpure functionنمای خواناRead modelجدول یا ایندکسtable or indexپرسش کاربرQueryارزانcheap
همان رویدادها با یک قاعدهٔ معین به یک نمای قابل پرسش تبدیل می‌شوند.The same events become a queryable view through one defined rule.

و بعدش، فنیAnd now, technically

برون‌فکنی یک تابع معین از زنجیرهٔ رویداد به وضعیت نمای خواناست. یک projector رویدادها را به ترتیب می‌خواند، هر رویداد را روی وضعیت اعمال می‌کند و offset خودش را جلو می‌برد؛ چون ورودی و تابع هر دو معین‌اند، بازپخش از صفر دقیقاً همان وضعیت را می‌سازد. برای همین قاعده نباید به زمان حال، تصادف یا سرویس بیرونی نگاه کند. اعمال دوبارهٔ یک رویداد هم باید بی‌اثر باشد، چون تحویل دست‌کم‌یک‌بار است و تکرار پیش می‌آید. ثبت offset باید در همان تراکنشی باشد که وضعیت را می‌نویسد، وگرنه یک خرابی وسط کار یا رویداد را دوبار اعمال می‌کند یا جا می‌اندازد. یک زنجیره می‌تواند چند projector داشته باشد که هر کدام از نقطهٔ خودش می‌خواند؛ ترتیب رویدادها به ازای هر کلید حفظ می‌شود و همین برای درستی جمع کافی است. در جبر رابطه‌ای، projection معنای دیگری دارد: انتخاب ستون‌ها.A projection is a pure function from the event log to a read model state. A projector reads events in order, applies each one to the state, and advances its own offset; because both the input and the function are fixed, a replay from zero produces exactly the same state. That is why the rule must not look at the clock, at randomness, or at an external service. Applying an event twice must also be a no-op, because delivery is at-least-once and duplicates happen. The offset must be committed in the same transaction that writes the state, or a crash midway either applies an event twice or skips it. One log can feed several projectors, each reading from its own point; event order is preserved per key, which is enough for a sum to come out right. In relational algebra, projection means something else: choosing columns.

1 تابعبرون‌فکنی یک تابع معین است، نه یک اثر جانبیa projection is a pure function, not a side effect
idempotentاعمال دوبارهٔ یک رویداد نباید چیزی را عوض کندre-applying an event must change nothing
1 offsetهر projector می‌داند تا کجای زنجیره رسیدهeach projector knows how far it has read

چرا باید معین باشدWhy it has to be deterministic

ارزش اصلی برون‌فکنی در این است که می‌شود پاکش کرد و از نو ساخت؛ و این وعده فقط وقتی راست است که قاعده معین باشد. اگر موقع ساختن، ساعت یا تصادف یا پاسخ یک سرویس بیرونی را دخالت بدهی، همان زنجیره دو وضعیت مختلف تولید می‌کند. آن‌وقت دیگر نمی‌دانی یک باگ از داده آمده یا از لحظه‌ای که بازپخش کردی، و نمی‌توانی نمای تازه‌ای کنار نمای قدیم بسازی و مقایسه کنی. قاعدهٔ معین یک هدیهٔ کوچک هم دارد: می‌شود کل برون‌فکنی را روی چند رویداد تست کرد، بدون هیچ پایگاه داده‌ای.The real value of a projection is that it can be thrown away and rebuilt, and that promise only holds if the rule is fixed. If you let the clock, random numbers or an external response inside, the same log produces two different states. Then you cannot tell whether a bug came from the data or from the moment you replayed, and you cannot build a new projection beside the old one and compare. A deterministic rule has one small gift too: the whole projector can be unit-tested against a handful of events, with no database at all.

چند برون‌فکنی از یک زنجیرهSeveral projections from one log

یک زنجیره می‌تواند چند نمای مختلف را تغذیه کند: یکی فهرست سفارش‌ها برای پشتیبانی، یکی شمارش روزانه برای داشبورد، یکی ایندکس جست‌وجو. هر کدام offset خودش را دارد و عقب‌ماندگی خودش را، پس یکی می‌تواند سالم باشد و دیگری گیر کرده باشد. همین جدایی بزرگ‌ترین سود این طرح است: افزودن یک نمای تازه یعنی یک بازپخش، نه یک مهاجرت روی دادهٔ زنده. تنها چیزی که باید مراقبش باشی این است که زنجیره به‌اندازهٔ کافی نگه داشته شود؛ اگر لاگ فشرده و کوتاه شود، بازپخش از صفر ممکن نیست.One log can feed several different views: an order list for support, a daily count for a dashboard, a search index. Each has its own offset and its own lag, so one can be healthy while another is stuck. That separation is the biggest win of the design: adding a new view is a replay, not a migration over live data. The one thing to watch is that the log is kept long enough; if it is compacted and truncated, replaying from zero is no longer possible.

تلهٔ رایجThe usual trap

وابسته بودن projector به ساعت یا تصادف یا شناسهٔ تازه. یک بار درست کار می‌کند و بار دوم نه؛ و آن روز که مجبور شوی بازپخش کنی، نمی‌فهمی کدام وضعیت درست است چون هیچ‌کدام قابل تکرار نیستند.A projector that depends on the clock, on randomness or on freshly generated ids. It works once and not twice, and on the day you must replay you cannot tell which state is right, because neither one can be reproduced.

query optimizer

بهینه‌ساز کوئری فصل ۳Chapter 3 · دیدن در متنsee in context

چه کسی تصمیم می‌گیرد کوئری‌ات واقعاً چطور اجرا شود؟Who decides how your query actually runs?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

سفارش می‌دهی و راننده برای رسیدن به خانه‌ات چند راه دارد: بزرگراه، خیابان اصلی، کوچه‌های پشت بازار. ساعت شش بزرگراه می‌گیرد، پس کوچه را انتخاب می‌کند. بهینه‌ساز کوئری همان راننده است: پیش از حرکت، راه را از روی نقشه و ساعت انتخاب می‌کند.You order something and the driver has several ways to your door: the motorway, the main street, the alleys behind the bazaar. At six the motorway jams, so he takes the alleys. The query optimizer is that driver: before moving, it picks a route from the map and the clock.

تشبیه و تصویر ذهنیThe analogy

آن راننده نقشه‌ای دارد که ممکن است قدیمی باشد. فکر می‌کند کوچهٔ سوم کوتاه‌تر است، چون سال پیش کوتاه‌تر بود؛ یا فکر می‌کند خیابان اصلی خلوت است، چون دیروز ظهر رفته. تصمیمش همیشه بهترین نیست، ولی تصمیم گرفتنش هم وقت می‌گیرد: اگر برای هر سفر یک ساعت نقشه بخواند، همان تأخیر بدتر از مسیر اشتباه است. برای همین بین «فکر کن» و «برو» تعادل می‌گذارد، و تو هم می‌توانی مسیر را ببینی و اگر پرت بود، نقشه را به‌روز کنی.That driver carries a map that may be out of date. He thinks the third alley is shorter because it was last year, or that the main street is empty because it was at noon yesterday. His choice is not always the best, and choosing also takes time: if he studied the map for an hour before every trip, the delay would cost more than the wrong route. So he balances thinking against driving, and you can look at the route he chose and update the map when it is wrong.

تجزیهParseبه نقشهٔ منطقیto a logical planبازنویسیRewriteفیلتر پایینpush down filtersتخمین هزینهCost itاز روی آمارfrom statisticsاجراExecuteارزان‌ترین نقشهthe cheapest plan
یک کوئری، چند نقشهٔ ممکن؛ آمار جدول‌ها تعیین می‌کند کدام‌شان اجرا شود.One query, several possible plans; table statistics decide which one runs.

و بعدش، فنیAnd now, technically

کوئری اول تجزیه می‌شود و به یک نقشهٔ منطقی تبدیل می‌شود: کدام جدول، کدام فیلتر، کدام join. بعد قواعد ساده‌ای روی آن اجرا می‌شود: فیلتر را تا نزدیک‌ترین نقطهٔ خواندن پایین می‌برند، ستون‌های بی‌مصرف را حذف می‌کنند، ترتیب join را عوض می‌کنند. بعد نوبت تخمین است: از آمار جدول‌ها تعداد ردیف‌های هر مرحله را حدس می‌زند و هزینهٔ هر نقشهٔ فیزیکی را می‌شمارد؛ ارزان‌ترین را انتخاب می‌کند و اجرا آغاز می‌شود. همهٔ این‌ها به آمار وابسته است، و آمار همان جایی است که کهنه می‌شود. اگر تخمین تعداد ردیف‌ها ده برابر خطا برود، ممکن است به‌جای hash join یک nested loop انتخاب شود و همان کوئری از میلی‌ثانیه به دقیقه برود. برای همین دیدن نقشهٔ اجرا، پیش از هر بهینه‌سازی، اولین قدم است.A query is first parsed into a logical plan: which tables, which filters, which joins. Simple rules then rewrite it — filters pushed down towards the read, unused columns pruned, join order changed. Next comes estimation: from table statistics it guesses the row count at each step and prices every physical plan, picks the cheapest and starts executing. All of it depends on those statistics, and statistics are the part that goes stale. If the row estimate is off by ten times, the plan may pick a nested loop where a hash join belonged and the same query goes from milliseconds to minutes. That is why reading the execution plan is the first step of optimisation, not the last.

N!تعداد ترتیب‌های ممکن join با N جدول؛ پیدا کردن بهترین، خودش یک مسئله استthe possible join orders for N tables; finding the best is a problem of its own
1 planاز بین چند نامزد، فقط یکی اجرا می‌شودof several candidates, exactly one runs
1 estimateهمهٔ هزینه‌ها روی یک تخمین از تعداد ردیف‌ها سوارندevery cost rides on one estimate of the row count

تلهٔ رایجThe usual trap

حدس زدن به‌جای خواندن نقشه. آدم‌ها ایندکس اضافه می‌کنند و امیدوارند سریع شود، در حالی که نقشه نشان می‌دهد مشکل جای دیگری است: تخمین بد تعداد ردیف‌ها، یا فیلتری که به موقع پایین نرفته. بدون دیدن نقشهٔ واقعی، هر بهینه‌سازی یک شرط‌بندی است — و ایندکس اضافه خودش روی هر نوشتن هزینه دارد.Guessing instead of reading the plan. People add an index and hope for speed while the plan shows the problem elsewhere: a bad row estimate, or a filter that never got pushed down. Without the real plan every optimisation is a bet — and the extra index charges you on every write.

relational model

مدل رابطه‌ای فصل ۳Chapter 3 · دیدن در متنsee in context

چرا جدول‌ها هنوز همه‌جا هستند؟Why are tables still everywhere?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

دفتر حساب مغازه‌ات را باز می‌کنی: یک صفحه برای مشتری‌ها، یک صفحه برای فاکتورها، یک صفحه برای کالاها. اسم مشتری را فقط یک بار نوشته‌ای؛ روی فاکتور فقط شمارهٔ مشتری را زده‌ای. هر وقت بخواهی بدانی این ماه چه فروختی، فاکتورها را با کالاها جفت می‌کنی. همین سه صفحه با یک قاعدهٔ ساده، جواب هزار سؤال مختلف را می‌دهند، بدون اینکه چیزی را از قبل برای آن سؤال چیده باشی.You open the shop's account book: one page for customers, one for invoices, one for goods. The customer name is written once; the invoice carries only the customer number. Whenever you want to know what sold this month, you pair invoices with goods. Those three pages, with one simple rule, answer a thousand different questions without having been arranged for any of them in advance.

تشبیه و تصویر ذهنیThe analogy

چیزی که این دفتر را قوی می‌کند این است که رابطه‌ها با مقدار ساخته می‌شوند، نه با اشاره‌گر. روی فاکتور نوشته‌ای «۴۲»؛ هر مشتری که شماره‌اش ۴۲ است همان است، چه کارت را جابه‌جا کنی چه نه. بهایش این است که هر سؤال باید شماره‌ها را تطبیق بدهد و ارزان نیست، ولی در عوض هیچ‌وقت نمی‌شود اشاره‌گری به جای اشتباه اشاره کند. دومین هدیه‌اش این است که شکل صفحه را از قبل نمی‌چینی: سؤالی که سال بعد پیش می‌آید را هم همان جدول‌ها جواب می‌دهند.What makes that book strong is that relationships are made by value, not by pointer. The invoice says 42, and whichever customer has number 42 is the one, whether or not you moved the card. The cost is that every question has to match numbers, which is not free, but in exchange no pointer can ever point at the wrong thing. The second gift is that you do not pre-arrange the page: a question that shows up next year is still answered by the same tables.

مدل رابطه‌ایRelational modelجدول، سطر، ستونtables, rows, columnsرابطه با کلید خارجیrelationships by foreign keyپرسش: هر شکلی، با joinany question, through joinsمدل سندیDocument modelسند خودبسندهa self-contained documentرابطه با تودرتوییrelationships by nestingپرسش: شکل صفحه از قبلthe screen shape comes first
جدول‌ها را برای هر پرسشی می‌شود جوین کرد؛ سندها برای پرسشی که از قبل می‌شناسی ساخته شده‌اند.Tables can be joined for any question; documents are shaped for the question you already know.

و بعدش، فنیAnd now, technically

مدل رابطه‌ای داده را به‌صورت رابطه می‌بیند: مجموعه‌ای از تاپل‌ها، بدون ترتیب و بدون تکرار، با کلیدهایی که سطرها را مشخص می‌کنند و کلید خارجی که به سطر جدول دیگر اشاره می‌کند. اشاره‌گری در کار نیست؛ join با تطبیق مقدار انجام می‌شود و همین است که آن را از مدل سلسله‌مراتبی قدیمی جدا می‌کند. طرح‌واره هنگام نوشتن اعمال می‌شود: نوع، قید و کلید یکتا. SQL اعلامی است؛ می‌گویی چه می‌خواهی و بهینه‌ساز تصمیم می‌گیرد با hash join یا merge join یا nested loop جواب بدهد. نکتهٔ ظریف این است که مدل رابطه‌ای با SQL یکی نیست: مدل دربارهٔ مجموعه‌هاست، SQL تکرار و ترتیب و NULL را قبول می‌کند، و بسیاری از شکایت‌ها از SQL است نه از مدل.The relational model treats data as relations: sets of tuples with no order and no duplicates, with keys that identify rows and foreign keys that point at rows in another table. There are no pointers; a join matches values, which is exactly what separates it from the old hierarchical model. The schema is enforced on write: types, constraints, unique keys. SQL is declarative: you say what you want and the optimizer decides whether to answer with a hash join, a merge join or a nested loop. The subtle point is that the relational model is not SQL: the model is about sets, SQL permits duplicates and order and NULL, and much of the complaining is about SQL rather than the model.

0 اشاره‌گررابطه با مقدار ساخته می‌شود، نه با آدرسrelationships are made by value, not by address
SQLزبان اعلامی: چه می‌خواهی، نه چطورdeclarative: what you want, not how
ACIDهمان موتور، تراکنش و ایزولهthe same engine gives transactions too

چرا جدول‌ها هنوز برنده‌اندWhy tables still win

بیشتر سیستم‌ها یک ویژگی مشترک دارند: در زمان طراحی نمی‌دانی چه سؤالی خواهند پرسید. مدل رابطه‌ای برای همین ساخته شد. جدول‌ها را نرمال نگه می‌داری، سؤال را بعداً می‌نویسی، و بهینه‌ساز تصمیم می‌گیرد چطور جوابش بدهد. سه چیز دیگر هم روی همین سوار است: قیدها که جلوی دادهٔ متناقض را می‌گیرند، تراکنش‌ها که چند تغییر را با هم امن می‌کنند، و یک زبان مشترک که هر ابزاری آن را می‌فهمد. هیچ‌کدام از این‌ها هیجان‌انگیز نیست و همه‌شان گران ساخته می‌شوند.Most systems share one property: at design time you do not know what will be asked. The relational model was built for that. You keep the tables normalized, write the question later, and the optimizer works out how to answer it. Three other things ride on the same idea: constraints that block contradictory data, transactions that make several changes safe together, and one shared language that every tool understands. None of it is exciting, and all of it is expensive to rebuild.

مدل رابطه‌ای با SQL یکی نیستThe model is not SQL

این تفاوت بیشتر از یک نکتهٔ دانشگاهی است. مدل دربارهٔ مجموعه‌هاست: ترتیب معنا ندارد و تکرار وجود ندارد. SQL ولی چندتایی‌ها را قبول می‌کند، ORDER BY دارد و NULL را با منطق سه‌مقداری اداره می‌کند. خیلی از انتقادهایی که به «مدل رابطه‌ای» می‌شود در واقع به رفتار SQL است: مقایسه با NULL که همیشه ناشناخته برمی‌گردد، یا پرسشی که با تکرار یک ردیف دو برابر جواب می‌دهد. وقتی این دو را قاطی کنی، بحث دربارهٔ ابزار را با بحث دربارهٔ ایده اشتباه می‌گیری.That distinction is more than academic. The model is about sets: order is meaningless and duplicates do not exist. SQL, however, accepts bags, has ORDER BY, and handles NULL with three-valued logic. Much of the criticism aimed at the relational model is really aimed at SQL's behaviour: comparison with NULL returning unknown, or a query that doubles a row because the bag contained a duplicate. Mix the two up and you are arguing about a tool while thinking you are arguing about an idea.

رابطه‌ای در برابر سندیRelational versus document

رابطه‌ایRelationalسندیDocument
طرح‌وارهSchemaهنگام نوشتنon writeهنگام خواندنon read
چندبه‌چندMany-to-manyطبیعیnaturalکار برنامهthe app's job
تغییر شکلReshapingمهاجرتa migrationتحمل در کدtolerated in code
ایندکسIndexروی هر ستونon any columnروی فیلد سندon document fields

تلهٔ رایجThe usual trap

گفتن «رابطه‌ای کند است» وقتی مشکل جای دیگری است. بیشتر کندی‌های واقعی از ایندکس نبودن، پرسشی که در حلقه اجرا می‌شود، یا بازگرداندن ستون‌های اضافی می‌آید؛ مدل رابطه‌ای هیچ‌کدام را تحمیل نمی‌کند.Saying relational is slow when the problem is elsewhere. Most real slowdowns come from a missing index, a query run inside a loop, or returning more columns than anyone reads; the model itself imposes none of that.

schema-on-read

طرح‌واره هنگام خواندن فصل ۳Chapter 3 · دیدن در متنsee in context

قاعده را کِی چک می‌کنی: موقع نوشتن یا خواندن؟When do you enforce the rules: on write, or on read?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

یک کشو پر از رسید داری. موقع گذاشتن رسید داخل کشو، هیچ‌کس چیزی چک نمی‌کند؛ هر رسیدی به هر شکلی می‌رود داخل. اما روزی که می‌خواهی مالیات را حساب کنی، تازه می‌بینی بعضی رسیدها تاریخ شمسی دارند، بعضی میلادی، و یکی اصلاً تاریخ ندارد. آن روز باید بنشینی و قاعده بگذاری. طرح‌واره هنگام خواندن همین است: کشوی بی‌قاعده، و حسابی که موقع جمع زدن سخت می‌شود.You keep a drawer full of receipts. Nothing is checked as a receipt goes in; every shape is allowed. Then tax season arrives and you discover that some receipts carry a Persian date, some a Gregorian one, and one carries none at all. That day you sit down and write a rule. Schema-on-read is that drawer: no rules going in, and an accountant to fix it on the way out.

تشبیه و تصویر ذهنیThe analogy

دفعهٔ بعد دو راه داری. می‌توانی دم کشو یک نگهبان بگذاری که هر رسید را قبل از ورود نگاه کند: تاریخ داشته باشد، مبلغ داشته باشد، وگرنه برود بیرون. این همان طرح‌واره هنگام نوشتن است؛ ورودی تمیز می‌شود ولی هر رسید عجیب رد می‌شود. یا می‌توانی نگهبان را برداری و قبول کنی که هر بار حساب کردن، اول باید رسیدها را مرتب کنی. هیچ‌کدام مجانی نیست: اولی انعطاف را می‌گیرد، دومی اطمینان را. و هیچ‌وقت واقعاً بی‌طرح‌واره نیستی؛ فقط طرح‌واره از دم کشو به دست حساب‌دار منتقل می‌شود.Next time you have two options. You can put a guard at the drawer who checks every receipt before it goes in: it must have a date and a total, or it goes back out. That is schema-on-write; the input is clean and every odd receipt is refused. Or you can remove the guard and accept that every calculation starts with tidying the receipts. Neither is free: the first gives up flexibility, the second gives up certainty. And you are never truly schemaless; the schema simply moves from the drawer to the accountant.

هنگام نوشتنOn writeنوع و ستون، قبل از درجtype and columns before insertدادهٔ بد پس زده می‌شودbad data is refusedتغییر شکل: مهاجرتreshaping: a migrationهنگام خواندنOn readشکل، موقع تفسیرthe shape comes at parse timeدادهٔ بد تا خواندن می‌ماندbad data waits until readتغییر شکل: تحمل در کدreshaping: tolerated in code
هر دو یک طرح‌واره دارند؛ تفاوت در لحظهٔ چک کردن و در این است که نبودش را کجا حس می‌کنی.Both have a schema; the difference is when it is checked and where its absence is felt.

و بعدش، فنیAnd now, technically

طرح‌واره هنگام نوشتن یعنی ساختار و نوع داده پیش از درج اعمال می‌شود؛ پایگاه داده دادهٔ بدشکل را رد می‌کند و بهینه‌ساز می‌تواند روی همان ساختار حساب کند. طرح‌واره هنگام خواندن یعنی داده هر شکلی ذخیره می‌شود و ساختار موقع تفسیر اعمال می‌شود؛ این حالت در پایگاه‌های سندی، دریاچه‌های داده و لاگ‌ها رایج است. کتاب این را به تایپ ایستا و پویا تشبیه می‌کند: در حالت اول خطا را زود می‌گیری، در حالت دوم انعطاف بیشتری داری و خطا را دیر. اما «بی‌طرح‌واره» افسانه است: خواننده همیشه یک طرح‌وارهٔ ضمنی در کدش دارد، فقط جایی مکتوب نیست که بشود نسخه‌بندی‌اش کرد. در عمل بیشتر سیستم‌ها ترکیبی‌اند: یک اعتبارسنجی سبک روی نوشتن، و تفسیر کامل روی خواندن؛ همان ترکیبی که در مرز یک API سالم دیده می‌شود. رجیستری طرح‌واره تلاش می‌کند هر دو را داشته باشد: اعتبارسنجی موقع نوشتن، با قاعدهٔ سازگاری رو به جلو.Schema-on-write means structure and types are enforced before insert; the store refuses malformed data and the optimizer can rely on the structure. Schema-on-read means data of any shape is stored and structure is applied when it is interpreted, which is common in document stores, data lakes and logs. The usual comparison is static versus dynamic typing: the first catches mistakes early, the second is more flexible and catches them late. But schemaless is a myth: the reader always carries an implicit schema, it just is not written anywhere you can version it. In practice most systems are mixed: light validation on write and full interpretation on read, which is exactly what a healthy API boundary looks like. A schema registry tries to have both, validating on write under a forward-compatibility rule.

2 حالتیا موقع نوشتن چک می‌شود یا موقع خواندنchecked either on write or on read
0 رددر حالت خواندن، پایگاه داده دادهٔ بد را رد نمی‌کندon read, the store rejects nothing
1 طرح‌وارهحتی بدون اجبار، یک طرح‌واره در کد خواننده هستeven unenforced, a schema lives in the reader

طرح‌واره جایی نمی‌رود، جابه‌جا می‌شودThe schema does not leave, it moves

وقتی پایگاه داده چیزی را اعتبارسنجی نمی‌کند، آن کار به کد خواننده منتقل می‌شود و معمولاً چند بار تکرار می‌شود. هر سرویس و هر اسکریپت تحلیلی نسخهٔ خودش از «این فیلد یعنی چه» را دارد، و این نسخه‌ها بی‌آنکه بدانی از هم جدا می‌شوند. نتیجه‌اش دو پرسش است که روی یک داده دو جواب متفاوت می‌دهند. راه‌حل، برگرداندن طرح‌واره به یک نقطه است: یک رجیستری، یک قرارداد مکتوب، یا یک لایهٔ اعتبارسنجی در مرز ورود. تفاوتش با طرح‌واره هنگام نوشتن این است که سخت‌گیری را از پایگاه داده به لبه منتقل می‌کند، نه اینکه حذفش کند.When the store does not validate, that job moves into reader code and is usually duplicated. Every service and every analysis script carries its own version of what this field means, and those versions drift apart without anyone noticing. The result is two queries giving two answers over one data set. The fix is to put the schema back in one place: a registry, a written contract, or a validation layer at the boundary. What separates it from schema-on-write is that the strictness moves to the edge instead of disappearing.

کِی خواندن را انتخاب کنWhen to choose read

طرح‌واره هنگام خواندن وقتی برنده است که منابع داده واقعاً ناهمگون باشند: چند اپلیکیشن که هر کدام شکل خودش را می‌نویسد، یک فید بیرونی که شکلش را تو انتخاب نمی‌کنی، یا رویدادهایی که سال‌ها معنی‌شان عوض می‌شود. آنجا اجبار کردن یک شکل، داده را از دست می‌دهد. اما برای پول، موجودی و هر چیزی که قید دارد، خواندن را انتخاب نکن؛ چون خطا تا لحظهٔ گزارش کشف نمی‌شود و آن‌وقت گران است. معیار ساده: اگر می‌شود دادهٔ بد را دور ریخت، انعطاف بخواه؛ اگر نمی‌شود، اجبار.Schema-on-read wins when the sources really are heterogeneous: several applications each writing its own shape, an external feed whose shape you do not control, or events whose meaning shifts over years. Enforcing one shape there loses data. But for money, stock and anything with an invariant, do not choose read, because the error is discovered at reporting time and by then it is expensive. The simple test: if you can afford to discard bad data, buy flexibility; if you cannot, enforce.

تلهٔ رایجThe usual trap

تلقی کردن «بی‌طرح‌واره» به‌عنوان اجازهٔ جمع کردن هر چیزی. سه ماه بعد، یک فیلد نصفه عدد دارد و نصفه رشته، و اولین گزارش مالی به دو جواب می‌رسد؛ آن روز کشف می‌کنی طرح‌واره‌ای که نداشتی، در واقع در ده جای کدت پخش شده بود.Reading schemaless as permission to collect garbage. Three months later one field is half numbers and half strings, the first financial report gives two answers, and you discover that the schema you did not have was in fact spread across ten places in your code.

star schema

طرح ستاره‌ای فصل ۳Chapter 3 · دیدن در متنsee in context

چرا در انبار داده یک جدول بزرگ و چند جدول کوچک؟Why one big table and a ring of small ones?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

دفتر خرج خانه‌ات را باز کن: هر خط می‌گوید «نان، پانزده هزار، از نانوایی سر کوچه». آدرس و اسم نانوایی را هر بار نمی‌نویسی؛ یک بار در دفترچهٔ تلفن نوشته‌ای و در دفتر خرج فقط به آن اشاره می‌کنی. طرح ستاره‌ای همین است: یک دفتر رویداد، و چند دفترچهٔ کوچک برای توضیح.Open the notebook where you track household spending. Each line says “bread, fifteen thousand, from the bakery at the corner”. You do not write the bakery's address every time; you wrote it once in the phone book and the notebook only points at it. That is a star schema: one book of events, a few small books that explain them.

تشبیه و تصویر ذهنیThe analogy

اگر آدرس کامل را روی هر خط بنویسی، دفتر دو برابر می‌شود و روزی که نانوایی جابه‌جا شود باید چهارصد خط را اصلاح کنی. اگر جدا نگه داری، یک خط اصلاح می‌شود، ولی هر بار که بخواهی بدانی «این ماه چقدر خرج نان کردم و در کدام محله»، باید دو دفتر را کنار هم باز کنی. تازه یک تصمیم سخت‌تر هم هست: اگر نانوایی عوض شود، خط‌های قدیمی باید آدرس قدیم را نگه دارند یا به آدرس تازه اشاره کنند؟ طرح ستاره‌ای همین تعادل را با تو می‌بندد: نوشتن ارزان و بدون تکرار، در برابر خواندنی که یک اشارهٔ اضافه می‌خواهد.Write the full address on every line and the notebook doubles, and the day the bakery moves you have four hundred lines to fix. Keep it separate and you fix one line, but every time you want to know “how much did I spend on bread this month, and in which neighbourhood” you must open both books side by side. There is a harder decision too: when the bakery moves, should the old lines keep the old address or point at the new one? A star schema strikes that bargain: cheap writes without repetition, in exchange for a read that pays one extra hop.

ستاره‌ایStarابعاد تختflat dimensionsjoin کمترfewer joinsتکرار عمدیdeliberate repetitionدانه‌برفیSnowflakeابعاد نرمالnormalised dimensionsjoin بیشترmore joinsتکرار کمترless repetition
طرح ستاره‌ای ابعاد را تخت نگه می‌دارد؛ دانه‌برفی همان ابعاد را باز هم می‌شکند.A star keeps dimensions flat; a snowflake splits those dimensions again.

و بعدش، فنیAnd now, technically

در طرح ستاره‌ای یک جدول واقعیت در مرکز است: هر ردیف یک رویداد در یک دانهٔ مشخص، مثلاً یک قلم فروش، همراه با چند اندازهٔ عددی و چند کلید خارجی. اطرافش جدول‌های بُعد هستند: مشتری، کالا، زمان، شعبه، هر کدام با ویژگی‌های توصیفی. ابعاد عمداً نرمال‌نشده‌اند تا گزارش یک join کمتر بخواهد؛ اگر ابعاد را هم به جدول‌های کوچک‌تر بشکنی، شکل دانه‌برفی می‌شود. پیش از هر چیز باید دانه را اعلام کنی: هر ردیف واقعیت دقیقاً چه چیزی است؟ اگر دانه دو معنا داشته باشد، جمع‌زدن‌ها دو برابر می‌شوند. تبدیل رویدادهای تودرتو، مثل یک سبد خرید JSON، به جدول واقعیت و ابعاد را shredding می‌نامند؛ همان کاری که مدل سندی را به مدل رابطه‌ای می‌آورد.In a star schema one fact table sits in the middle: each row is one event at a declared grain, say one sale line, carrying a few numeric measures and a few foreign keys. Around it sit dimension tables — customer, product, time, store — each with descriptive attributes. Dimensions are deliberately left denormalised so a report needs fewer joins; break them into smaller tables and you get a snowflake. Before any of that you must declare the grain: what exactly is one fact row? If the grain means two things at once, every sum doubles. Turning nested events, such as a JSON basket, into fact rows plus dimension rows is called shredding, and it is how a document model is brought into a relational one.

1 factیک جدول مرکزی، معمولاً بزرگ‌ترین جدول انبارone central table, usually the largest in the warehouse
N dimsچند جدول کوچک اطراف، هر کدام یک بُعدa few small tables around it, one per dimension
2–3 joinsبرای یک گزارش معمول همین قدر join کافی استa typical report needs about this many joins

تلهٔ رایجThe usual trap

اعلام نکردن دانه. جدول واقعیت را از دو منبع می‌سازی، بعد دو جدول را join می‌کنی و گزارش دو برابر می‌شود، چون هر ردیف واقعیت یک معنا نداشته. دانه را قبل از پر کردن جدول بنویس و بعد از آن، هر join را با همان دانه بسنج.Not declaring the grain. You build the fact table from two sources, join it to a second table and the report doubles, because a fact row never had one meaning. Write the grain down before you load the table, and check every later join against it.