الـ Transactions بـ node-postgres: كله أو ولا حاجة
ليه خطوتين منفصلين بيعملوا بيانات بايزة لو التانية وقعت. الـ ACID في جملة. Pool مقابل Client، وأشهر bug: BEGIN على pool.query بيروح لـ connection مختلفة. withTransaction بـ pool.connect و BEGIN و COMMIT و ROLLBACK و release في finally. الـ SAVEPOINT لجزء اختياري، و pool.on("error")، وإن bigint و count بيرجعوا strings.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك في قسم Postgres في التشغيل. أشهر مسال في الدنيا: تحويل فلوس من حساب لحساب. خطوتين: تزوّد عند ده، وتخصم من ده. لو الخطوة التانية وقعت؟ يبقى الفلوس اتعملت من الهوا. db dot js فيه pool بيوصل لـ Postgres، وجدول accounts فيه CHECK إن الرصيد ما يبقاش سالب، و function بتطبع الأرصدة. و main dot js بيحوّل من عمر لمُنى تمنمية جنيه، وعمر معاه خمسمية بس. نشغّل.
import { pool, setup, balances } from "./db.js";
await setup();
// ❌ من غير transaction: خطوتين منفصلين
async function transfer(from, to, amount) {
await pool.query("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [amount, to]);
await pool.query("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [amount, from]);
}
try {
await transfer(2, 1, 800); // عمر معاه 500 بس
} catch (err) {
console.log("error:", err.message);
}
console.log(await balances());
await pool.end();المخرجات
$ node main.js error: new row for relation "accounts" violates check constraint "accounts_balance_check" مُنى=1800 عمر=500 | المجموع=2300
الخصم وقع بسبب الـ CHECK، بس الإضافة كانت حصلت خلاص: مُنى بقت ألف وتمنمية، وعمر لسه خمسمية. يعني تمنمية جنيه اتخلقوا من العدم. الحل: transaction. مجموعة خطوات، يا تتم كلها، يا ولا واحدة منها، وده أول حرف في كلمة ACID: Atomicity. أول محاولة، واللي هتلاقيها في code كتير على الإنترنت: BEGIN و COMMIT و ROLLBACK، بس بـ pool dot query. وهنشغّل عشر تحويلات مع بعض، زي server عليه requests كتير في نفس الوقت، ونصهم المفروض يفشلوا، لأن عمر معاه خمسمية بس. نشغّل.
import { pool, setup, balances } from "./db.js";
await setup();
// ❌ BEGIN على الـ pool: كل query ممكن تروح لـ connection مختلفة
async function transfer(from, to, amount) {
await pool.query("BEGIN");
try {
await pool.query("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [amount, to]);
await pool.query("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [amount, from]);
await pool.query("COMMIT");
} catch (err) {
await pool.query("ROLLBACK");
throw err;
}
}
// 10 transfers مع بعض، زي server عليه requests كتير: نصهم هيفشل (عمر معاه 500 بس)
const jobs = Array.from({ length: 10 }, (_, i) => (i % 2 ? transfer(1, 2, 10) : transfer(2, 1, 800)));
const results = await Promise.allSettled(jobs);
console.log(results.map((r) => (r.status === "fulfilled" ? "✓" : "✗")).join(""));
console.log(await balances());
await pool.end();المخرجات
$ node main.js ✗✓✗✓✗✓✗✓✗✓ مُنى=1770 عمر=510 | المجموع=2280
المجموع مش ألف وخمسمية، يعني فلوس اتخلقت أو اختفت، مع إن فيه BEGIN و ROLLBACK! ولو شغّلته تاني هتلاقي أرقام مختلفة كل مرة، وده أسوأ نوع bugs. السبب: الـ pool فيه connections كتير، وكل pool dot query بتاخد أي connection فاضية. فالـ BEGIN راحت على connection، والـ UPDATE راح على connection تانية مالهاش transaction خالص، والـ ROLLBACK راح على تالتة. الـ transaction في Postgres مربوطة بالـ connection. ودي من أخطر الـ bugs في Node، لأنها بتشتغل صح لما تجرّب request واحد لوحدك. الحل الصح: withTransaction. pool dot connect بياخد client واحد. BEGIN، وبعدين الـ function بتاعتك بتاخد نفس الـ client. COMMIT لو كله تمام، و ROLLBACK لو حصل أي error، وترمي الـ error تاني. و release في finally، دايمًا. لو نسيته، الـ connection عمرها ما ترجع للـ pool، وبعد عشر مرات الـ pool يخلص والـ app يعلّق.
نشغّل نفس العشر تحويلات.
import { pool, setup, balances } from "./db.js";
import { withTransaction } from "./tx.js";
await setup();
function transfer(from, to, amount) {
return withTransaction(async (c) => {
await c.query("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [amount, to]);
await c.query("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [amount, from]);
await c.query("INSERT INTO transfers (from_id, to_id, amount) VALUES ($1, $2, $3)", [from, to, amount]);
});
}
const jobs = Array.from({ length: 10 }, (_, i) => (i % 2 ? transfer(1, 2, 10) : transfer(2, 1, 800)));
const results = await Promise.allSettled(jobs);
console.log(results.map((r) => (r.status === "fulfilled" ? "✓" : "✗")).join(""));
console.log(await balances());
const { rows } = await pool.query("SELECT count(*) FROM transfers");
console.log("transfers:", rows[0].count, typeof rows[0].count);
await pool.end();المخرجات
$ node main.js ✗✓✗✓✗✓✗✓✗✓ مُنى=950 عمر=550 | المجموع=1500 transfers: 5 string
الخمسة اللي بتحوّل تمنمية من عمر فشلوا، والخمسة التانيين نجحوا. مُنى تسعمية وخمسين، وعمر خمسمية وخمسين، والمجموع ألف وخمسمية بالزبط، ومفيش فلوس اتخلقت. والـ transfers خمسة بس. وخد بالك من آخر سطر: count رجع string! pg بيرجّع bigint و numeric كـ strings، علشان JavaScript ما تقدرش تمسك كل الأرقام دي بدقة. يا تعمل cast في الـ SQL لـ int، يا تحوّل بنفسك. حاجة كمان: الـ SAVEPOINT. جُوّه transaction، ممكن تحط علامة، ولو خطوة اختيارية وقعت ترجع للعلامة بس، والـ transaction تكمّل. وده مهم، لأن في Postgres لو أي query جُوّه transaction وقعت، الـ transaction كلها بتبقى aborted، وأي query بعدها بترفض، لحد ما تعمل ROLLBACK أو ترجع لـ savepoint. التحدي: checkout كله أو ولا حاجة. order وخصم رصيد في transaction واحدة. الكوبون اختياري، وبيتسجّل في جدول مش موجود، فهيقع، ولازم ترجع لـ savepoint وتكمّل. و order أكبر من الرصيد لازم يترجع كله. الأرقام المتوقعة في الكومنت.
checkout(accountId, items, coupon) جُوّه withTransaction: INSERT order و UPDATE balance، والكوبون بـ SAVEPOINT و ROLLBACK TO SAVEPOINT لو وقع.
الحل. الإجمالي بـ reduce. INSERT بـ RETURNING id. الخصم. والكوبون: SAVEPOINT، و try، ولو وقع ROLLBACK TO SAVEPOINT، والـ transaction تكمّل عادي. و Number للـ id. نشغّل.
import { pool, setup, balances } from "./db.js";
import { withTransaction } from "./tx.js";
await setup();
await pool.query("CREATE TABLE IF NOT EXISTS orders (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, account_id bigint, total bigint)");
function checkout(accountId, items, coupon) {
return withTransaction(async (c) => {
const total = items.reduce((s, i) => s + i.price, 0);
const { rows } = await c.query(
"INSERT INTO orders (account_id, total) VALUES ($1, $2) RETURNING id",
[accountId, total],
);
await c.query("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [total, accountId]);
if (coupon) {
await c.query("SAVEPOINT coupon");
try {
await c.query("INSERT INTO coupons_used (code) VALUES ($1)", [coupon]);
} catch {
await c.query("ROLLBACK TO SAVEPOINT coupon");
}
}
return { orderId: Number(rows[0].id), total };
});
}
console.log(await checkout(1, [{ price: 300 }, { price: 200 }], "WELCOME"));
try {
await checkout(2, [{ price: 900 }]);
} catch (err) {
console.log("error:", err.message);
}
console.log(await balances());
const { rows } = await pool.query("SELECT count(*)::int AS n FROM orders");
console.log("orders:", rows[0].n);
await pool.end();المخرجات
$ node main.js
{ orderId: 1, total: 500 }
error: new row for relation "accounts" violates check constraint "accounts_balance_check"
مُنى=500 عمر=500 | المجموع=1000
orders: 1الأول نجح بخمسمية رغم إن الكوبون وقع. التاني وقع بالـ CHECK، والـ order بتاعه اترجع. الأرصدة: خمسمية وخمسمية. و order واحد بس. الدرس الجاي: لما transactions كتير تشتغل مع بعض: الـ MVCC ومستويات الـ isolation.
import { pool } from "./db.js";
// كل الـ queries على نفس الـ client، وأي error = ROLLBACK، والـ client يرجع للـ pool دايمًا
export async function withTransaction(fn) {
const client = await pool.connect();
try {
await client.query("BEGIN");
const result = await fn(client);
await client.query("COMMIT");
return result;
} catch (err) {
await client.query("ROLLBACK");
throw err;
} finally {
client.release();
}
}03 / دروس المسار (122)
- 01أهلًا بيك: يعني إيه backend، والكورس ده ماشي إزاي
- 02الملفات والفولدرات والـ terminal: تتحرك على جهازك زي المبرمجين
- 03Node وأول برنامج: تشغّل وتقرا رسالة الخطأ
- 04القيم والمتغيرات والأنواع: const و let و typeof
- 05القرارات والتكرار: if و === والـ truthy والـ loops
- 06الـ functions: parameters و return والـ arrow functions والـ scope
- 07الـ objects والـ arrays: destructuring و spread و map و filter و reduce
- 08JSON والنصوص والتواريخ: اللغة اللي الـ backend بيتكلم بيها
- 09الـ callbacks والـ closures وأول لمسة async: setTimeout
- 10الـ classes والـ errors: throw و try/catch و stack trace
- 11git: تحفَظ كل خطوة وترجعلها، وما تسرّبش أسرارك
- 12ESM و CommonJS و package exports: Node بيلاقي الـ modules إزاي
- 13الـ Promises و async/await: sequential و parallel والأخطاء والإلغاء
- 14الـ event loop والـ microtasks: Node بيعمل كل حاجة بـ thread واحد إزاي
- 15الـ Streams والـ Backpressure: ملفات أكبر من الـ memory
- 16الـ File System والـ paths: قراية وكتابة صح، ومن غير path traversal
- 17الـ Buffers والبيانات الـ binary: الـ bytes من جُوّه
- 18Crypto APIs والأسرار: random و hash و HMAC و AES-GCM
- 19الـ Worker Threads: شغل CPU تقيل من غير ما توقف الـ server
- 20الـ Errors على مستوى الـ process: operational و programmer و crash-only
- 21الـ Node test runner والـ debugging: tests من غير مكتبات
- 22HTTP من جُوّه: الـ methods والـ status codes والـ headers
- 23Express والـ Routing: الـ params والـ query والترتيب والـ Router
- 24Express 5: إيه اللي اتغيّر، وإزاي تنقل مشروع قديم
- 25الـ Middleware ودورة حياة الـ request جُوّه Express
- 26Validation للمدخلات بـ Zod: ما تصدّقش أي حاجة جاية من برة
- 27تصنيف الأخطاء و Problem Details: شكل واحد لكل الـ errors
- 28الـ CORS والـ Cookies: المتصفح بيحمي المستخدم إزاي
- 29رفع الملفات وحدود الحجم: multer من غير ثغرات
- 30الـ Realtime: Server-Sent Events و WebSockets
- 31OpenAPI والـ API Versioning: عقد مكتوب، وتغيير من غير ما تكسر حد
- 32PostgreSQL: الـ DDL وأنواع البيانات الصح لكل عمود
- 33الـ Constraints: PK و FK و UNIQUE و CHECK — الـ database بتحمي نفسها
- 34الـ Normalization والـ ERD: تقسّم البيانات صح من أول يوم
- 35الـ JOINs والتجميع: INNER و LEFT و GROUP BY و HAVING و window functions
- 36JSONB في PostgreSQL: إمتى تستخدمه، وإزاي تسأله وتعمله index
- 37الـ Indexes من جُوّه: B-tree و GIN و BRIN
- 38Partial و Covering indexes: indexes أصغر وأسرع
- 39الـ Pagination بالـ Keyset: ليه OFFSET بيبطّأ وبيكرر
- 40Full Text Search في Postgres: بحث بالكلمات، بالعربي والإنجليزي
- 41EXPLAIN ANALYZE والـ Planner: اقرا الـ plan وصلّح الـ query
- 42الـ Transactions بـ node-postgres: كله أو ولا حاجةانت هنا
- 43الـ MVCC ومستويات الـ Isolation: transactions كتير في نفس الوقت
- 44الـ Locks والـ Deadlocks: مين مستني مين
- 45SKIP LOCKED و Job Leasing: Postgres كـ job queue
- 46Row Level Security والـ Multi-tenancy: كل عميل يشوف بياناته بس
- 47Migrations من غير downtime: expand و backfill و contract
- 48الـ Replication والـ Read Replicas: نسخ حية من الـ database
- 49الـ Connection Pooling و PgBouncer: connections أقل، requests أكتر
- 50الـ Partitioning والـ VACUUM والمراقبة: Postgres على المدى الطويل
- 51Redis وأنواع البيانات: strings و hashes و lists و sets و sorted sets
- 52Cache-aside والـ TTL: Redis قدام الـ database
- 53الـ Cache invalidation والـ Stampede: لما الـ key الشهير يموت
- 54Lua والـ Atomicity في Redis: كام أمر كأنهم أمر واحد
- 55الـ Rate Limiting في Redis: fixed window و sliding window و token bucket
- 56الـ Sessions في Redis: تسجيل دخول تقدر تلغيه في أي وقت
- 57Redis Streams والـ Consumer Groups: log بيتوزع على workers
- 58Pub/Sub و BullMQ: إشارات بين الـ instances، وطوابير شغل محترمة
- 59Redis لما يقع: الـ persistence (RDB و AOF) والـ replication
- 60Redis في الإنتاج: الـ ACLs والـ Cluster والمراقبة
- 61تخزين الـ Passwords بـ Argon2id: صح من أول مرة
- 62Session Fixation والـ Rotation: id جديد مع كل صلاحية جديدة
- 63الـ Cookie Flags والـ CSRF: المتصفح بيبعت الـ cookie، فلازم تتأكد مين اللي طلب
- 64الـ XSS والـ Content Security Policy: ما تخليش النص يتحوّل لـ code
- 65الـ OAuth و OpenID Connect و PKCE: login بـ Google من غير ما تشوف الـ password
- 66التأكد من الـ JWT صح: التوقيع والـ claims والـ scopes
- 67الـ BOLA و BFLA: الـ token السليم مش معناه إن الطلب مسموح
- 68الـ RBAC و ABAC والملكية: policy واحدة بدل ifs متفرقة
- 69الـ MFA والـ recovery: التاني factor اللي بجد
- 70الـ Passkeys و WebAuthn: login من غير password وضد الـ phishing
- 71الـ Threat Modeling بـ STRIDE: فكّر زي المهاجم قبل ما تكتب code
- 72الـ SQL Injection والـ Parameterization: الـ data ما تبقاش code
- 73الـ SSRF والـ Egress: ما تخليش الـ server بتاعك يزور الشبكة الداخلية
- 74الـ Security Headers والـ TLS: كل response يقول للـ browser يحمي المستخدم إزاي
- 75توقيع الـ Webhooks والـ Replay: الـ webhook ده جاي فعلًا من Stripe؟
- 76تغيير الأسرار والـ HMAC: إزاي تغيّر مفتاح من غير ما كل حاجة تقع
- 77سلسلة التوريد والـ SBOM: إنت واثق في ألف package ما تعرفهمش؟
- 78الـ Audit والـ Privacy Logs: سجّل مين عمل إيه، من غير ما تسجّل الأسرار
- 79اختبار الأمان و OWASP ASVS: الأمن جُوّه الـ CI، مش audit آخر السنة
- 80الـ Prototype Pollution والـ Resource DoS: request واحد يخلّي الكل admin أو يوقّع الـ server
- 81الـ SLI والـ SLO والـ Error Budget: إمتى تصحّي الـ on-call وإمتى تسيبه نايم
- 82الـ Event Loop Delay والـ ELU: لما Node نفسه يتخنق
- 83الـ Worker Threads والـ CPU Profiling: الشغل التقيل بره الـ event loop، والوقت راح فين
- 84الـ Memory والـ GC والـ Leaks: الـ process اللي بيكبر لحد ما يقع
- 85الـ N+1 Queries والـ DataLoader: صفحة واحدة بمِيّتين query
- 86الـ HTTP Caching والـ Compression: أسرع request هو اللي ما بيوصلش
- 87الـ Load Testing والـ Soak Testing: الـ server بيستحمل قد إيه بجد
- 88الـ Concurrency Limits والـ Bulkheads: dependency بطيئة ما توقعش الـ app كله
- 89الـ Timeouts والـ Retries والـ Circuit Breakers: إزاي تتعامل مع dependency بطيئة أو واقعة
- 90OpenTelemetry والـ Distributed Tracing: الـ request راح فين وضاع وقته فين
- 91Docker Layers والـ Build Context: ليه الـ build بياخد دقيقة وفيه الـ .env بتاعك
- 92Multi-stage Builds و Non-root: image صغيرة ومن غير root
- 93Docker Compose والـ Networks: الـ services بتلاقي بعض إزاي
- 94Docker Volumes: الـ data بتتحفَظ فين
- 95Healthcheck و Restart و Resource Limits: running مش معناها شغّال
- 96BuildKit والـ Build Secrets: الـ token ما يدخلش الـ image
- 97Reverse Proxy و TLS: اللي واقف قدام الـ app
- 98Multi-arch Images والـ Native Modules: اشتغلت عندي
- 99CI/CD و Rollback و Canary: الـ deploy يبقى ممل
- 100Kubernetes من الأول: Pods و Deployments و Services و Probes
- 101Modular Monolith و DDD: حدود واضحة من غير network
- 102Transactional Outbox و Inbox: الـ event ما يضيعش وما يتنفذش مرتين
- 103Sagas: عملية واحدة على تلات services من غير transaction واحدة
- 104CQRS و Event Sourcing: الـ events هي الحقيقة
- 105الـ Queues والـ Brokers: BullMQ و RabbitMQ و Kafka و SQS
- 106Realtime على أكتر من instance: Redis pub/sub و presence و resume
- 107الـ Object Storage والـ Media: presigned URLs و uploads مباشرة
- 108التكامل مع الـ Email والـ Search: retries و webhooks و indexes
- 109GraphQL و gRPC في الإنتاج: contracts و DataLoader و limits و deadlines
- 110Kafka على أكتر من zone و region: الـ replication والـ ISR والـ acks والـ MirrorMaker والـ failover
- 111TypeScript و runtime boundaries: الـ types بتختفي، والـ schemas لأ
- 112ORM ولا SQL: query builders و repositories و migrations و transactions
- 113الـ Serverless من جُوّه: cold starts و freeze و timeouts و connections
- 114الـ Testing Pyramid: unit و integration و e2e على Postgres حقيقية
- 115Contract Testing و Property-Based Testing بـ fast-check
- 116الـ Payments: idempotency و webhooks و refunds و reconciliation
- 117الـ Timezones والـ Internationalization: UTC و DST والـ locales والـ plurals والفلوس
- 118الـ Privacy والـ Data Retention: consent و export و erasure و crypto shredding
- 119الـ ADRs والـ Feature Flags: القرارات المكتوبة والـ rollout من غير deploy
- 120Multi-region active-active: حل الـ conflicts بـ HLC و CRDTs
- 121Readiness و Liveness و Startup Probes: الـ pod جاهز ولا عايش؟
- 122Incident Runbooks: من الـ alert للـ postmortem