الـ Normalization والـ ERD: تقسّم البيانات صح من أول يوم
مشاكل الجدول الواحد (زي الـ sheet): الـ update anomaly، والـ lists جُوّه عمود، و LIKE اللي بيلاقي حاجات غلط. الـ normal forms الأولى والتانية والتالتة بكلام بسيط، وأنواع العلاقات 1:1 و 1:N و M:N بجدول وسيط، والـ ERD. وإمتى الـ denormalization صح: زي نسخ السعر وقت الشراء. ونقل sheet قديم لجداول بـ INSERT … SELECT و unnest.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك. أغلب المشاريع بتبدأ بـ sheet: جدول واحد فيه كل حاجة. وده بيبان سهل، لحد ما البيانات تكبر. جدول orders flat: بيانات العميل متكررة في كل order. والكورسات اللي اشتراها مكتوبة كلها في عمود واحد بـ commas. وهنعمل حاجتين عاديين جدًّا: مُنى غيّرت رقمها، والـ update اتعمل على order واحد، وبعدين ندوّر مين اشترى sql. نشغّل.
-- جدول واحد فيه كل حاجة، زي sheet
DROP TABLE IF EXISTS orders_flat CASCADE;
CREATE TABLE orders_flat (
order_id int,
customer_email text,
customer_phone text,
items text, -- 'node,sql'
total int
);
INSERT INTO orders_flat VALUES
(1, '[email protected]', '0100', 'node,sql', 450),
(2, '[email protected]', '0100', 'redis', 150),
(3, '[email protected]', '0122', 'node', 200);
-- مُنى غيّرت رقمها… في order واحد بس
UPDATE orders_flat SET customer_phone = '0111' WHERE order_id = 2;
SELECT DISTINCT customer_email, customer_phone FROM orders_flat ORDER BY 1;
-- مين اشترى كورس sql؟
SELECT order_id FROM orders_flat WHERE items LIKE '%sql%';
INSERT INTO orders_flat VALUES (4, '[email protected]', '0155', 'mysql', 100);
SELECT order_id FROM orders_flat WHERE items LIKE '%sql%';المخرجات
$ psql -f schema.sql DROP TABLE CREATE TABLE INSERT 0 3 UPDATE 1 customer_email | customer_phone ----------------+---------------- [email protected] | 0100 [email protected] | 0111 [email protected] | 0122 (3 rows) order_id ---------- 1 (1 row) INSERT 0 1 order_id ---------- 1 4 (2 rows)
مُنى بقى ليها رقمين مختلفين في نفس الـ database، ومحدش يعرف أنهي الصح. ده اسمه update anomaly. والسؤال عن sql لقى الـ order الأول، وبعد ما سارة اشترت mysql، لقاها كمان، لأن LIKE بتدوّر على حروف، مش على كورس. وكمان: مش هتعرف تعمل foreign key على كورس جُوّه string، ولا index، ولا تعدّ مبيعات كل كورس بسهولة.
الـ normalization: إنك تقسم البيانات علشان كل معلومة تتخزن في مكان واحد بس. الأولى: كل خانة فيها قيمة واحدة، مفيش lists بـ commas. التانية: كل عمود معتمد على الـ key كله، مش جزء منه. التالتة: كل عمود معتمد على الـ key، مش على عمود تاني. يعني إيميل العميل مالوش علاقة بالـ order، ده معلومة عن العميل، فمكانه جدول العميل. والقاعدة المختصرة: كل حاجة ليها هوية، ليها جدول.
والعلاقات بين الجداول ليها تلات أنواع، وبنرسمها في رسمة اسمها ERD. واحد لكتير: عميل ليه orders كتير، فالـ order فيه customer_id. كتير لكتير: الـ order فيه كورسات كتير، والكورس في orders كتير، فلازم جدول في النص: order_items. وواحد لواحد: مستخدم وملفه الشخصي. التصميم المتقسم. customers و products و orders. و order_items جدول في النص، والـ primary key بتاعه العمودين مع بعض. وأهم سطر هنا: unit_price_cents. ده نسخة من السعر وقت الشراء. ده denormalization مقصود: لو بكرة السعر اتغيّر، الفاتورة القديمة لازم تفضل بسعرها القديم. وبعدين بنغيّر رقم مُنى في مكان واحد، وسعر node، ونرجّع الصورة الكاملة بـ JOINs. نشغّل.
DROP TABLE IF EXISTS order_items, orders, products, customers CASCADE;
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE,
phone text
);
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
slug text NOT NULL UNIQUE,
price_cents int NOT NULL CHECK (price_cents >= 0)
);
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers (id),
created_at timestamptz NOT NULL DEFAULT now()
);
-- many-to-many: order فيه منتجات كتير، والمنتج في orders كتير
CREATE TABLE order_items (
order_id bigint NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
product_id bigint NOT NULL REFERENCES products (id),
unit_price_cents int NOT NULL, -- نسخة من السعر وقت الشراء!
PRIMARY KEY (order_id, product_id)
);
INSERT INTO customers (email, phone) VALUES ('[email protected]', '0100'), ('[email protected]', '0122');
INSERT INTO products (slug, price_cents) VALUES ('node', 20000), ('sql', 25000), ('redis', 15000);
INSERT INTO orders (customer_id) VALUES (1), (1), (2);
INSERT INTO order_items VALUES (1, 1, 20000), (1, 2, 25000), (2, 3, 15000), (3, 1, 20000);
-- رقم مُنى بيتغيّر في مكان واحد
UPDATE customers SET phone = '0111' WHERE email = '[email protected]';
-- والسعر بيتغيّر، والـ orders القديمة ما بتتأثرش
UPDATE products SET price_cents = 30000 WHERE slug = 'node';
SELECT o.id AS order_id, c.email, c.phone, p.slug, oi.unit_price_cents, p.price_cents AS today_price
FROM orders o
JOIN customers c ON c.id = o.customer_id
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
ORDER BY o.id, p.slug;المخرجات
$ psql -f schema.sql
DROP TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 2
INSERT 0 3
INSERT 0 3
INSERT 0 4
UPDATE 1
UPDATE 1
order_id | email | phone | slug | unit_price_cents | today_price
----------+------------+-------+-------+------------------+-------------
1 | [email protected] | 0111 | node | 20000 | 30000
1 | [email protected] | 0111 | sql | 25000 | 25000
2 | [email protected] | 0111 | redis | 15000 | 15000
3 | [email protected] | 0122 | node | 20000 | 30000
(4 rows)رقم مُنى الجديد باين في الـ orders بتاعتها كلها، لأنه متخزن مرة واحدة. وسعر node النهارده تلتمية جنيه، بس الـ orders القديمة فاكرة إنها اتباعت بمِيتين. الـ JOINs دي هنشرحها بالتفصيل الدرس الجاي. والقاعدة: ابدأ normalized، و denormalize بقصد ولسبب واضح: تاريخ لازم يتحفَظ، أو counter علشان السرعة. التحدي: حوّل الـ sheet لجداول. فريق المحتوى عنده sheet: كورس، وإيميل المعلم واسمه، و tags بـ commas. هتصمم أربع جداول: teachers و courses و tags، و course_tags في النص. وتنقل البيانات بـ INSERT SELECT، من غير ما تكتب قيمة واحدة بإيدك، لأن الـ sheet الحقيقي فيه آلاف الصفوف. الـ unnest و string_to_array هيقسموا الـ tags. التفاصيل في الكومنت.
صمم teachers و courses و tags و course_tags، وانقل catalog_sheet بـ INSERT … SELECT (DISTINCT للمعلمين والـ tags، و unnest(string_to_array(tags, ','))).
الحل. الجداول الأربعة بالـ constraints. teachers بـ SELECT DISTINCT. courses بـ JOIN على الإيميل علشان ناخد الـ id. tags بـ DISTINCT unnest. و course_tags: CROSS JOIN LATERAL بيفك كل صف لصفوف بعدد الـ tags، وبعدين JOIN على الاسم. نشغّل.
-- ده الـ sheet القديم اللي فريق المحتوى كان شغال عليه
DROP TABLE IF EXISTS catalog_sheet, course_tags, tags, courses, teachers CASCADE;
CREATE TABLE catalog_sheet (course text, teacher_email text, teacher_name text, tags text);
INSERT INTO catalog_sheet VALUES
('node', '[email protected]', 'مُنى', 'backend,js'),
('express', '[email protected]', 'مُنى', 'backend,js,http'),
('sql', '[email protected]', 'عمر', 'backend,db');
CREATE TABLE teachers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE,
name text NOT NULL
);
CREATE TABLE courses (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
slug text NOT NULL UNIQUE,
teacher_id bigint NOT NULL REFERENCES teachers (id)
);
CREATE TABLE tags (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL UNIQUE
);
CREATE TABLE course_tags (
course_id bigint NOT NULL REFERENCES courses (id) ON DELETE CASCADE,
tag_id bigint NOT NULL REFERENCES tags (id) ON DELETE CASCADE,
PRIMARY KEY (course_id, tag_id)
);
INSERT INTO teachers (email, name)
SELECT DISTINCT teacher_email, teacher_name FROM catalog_sheet;
INSERT INTO courses (slug, teacher_id)
SELECT s.course, t.id FROM catalog_sheet s JOIN teachers t ON t.email = s.teacher_email;
INSERT INTO tags (name)
SELECT DISTINCT unnest(string_to_array(tags, ',')) FROM catalog_sheet;
INSERT INTO course_tags (course_id, tag_id)
SELECT c.id, t.id
FROM catalog_sheet s
CROSS JOIN LATERAL unnest(string_to_array(s.tags, ',')) AS x(tag)
JOIN courses c ON c.slug = s.course
JOIN tags t ON t.name = x.tag;
SELECT (SELECT count(*) FROM teachers) AS teachers, (SELECT count(*) FROM tags) AS tags;
SELECT t.name, count(*) FROM course_tags ct JOIN tags t ON t.id = ct.tag_id
GROUP BY t.name ORDER BY count(*) DESC, t.name;المخرجات
$ psql -f schema.sql
DROP TABLE
CREATE TABLE
INSERT 0 3
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 2
INSERT 0 3
INSERT 0 4
INSERT 0 7
teachers | tags
----------+------
2 | 4
(1 row)
name | count
---------+-------
backend | 3
js | 2
db | 1
http | 1
(4 rows)اتنين معلمين، وأربع tags، و backend في تلات كورسات، و js في اتنين. الدرس الجاي: الـ JOINs والتجميع بالتفصيل.
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