@ai-content-space/loopx 0.2.9 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +10 -6
  2. package/README.zh-CN.md +10 -6
  3. package/docs/loopx/design/loopx-skill-suite-v1-design.md +12 -0
  4. package/docs/loopx/plans/2026-06-15-support-lens-skills-migration.md +1153 -0
  5. package/package.json +6 -1
  6. package/plugins/loopx/.codex-plugin/plugin.json +1 -1
  7. package/plugins/loopx/skills/api-designer/SKILL.md +232 -0
  8. package/plugins/loopx/skills/api-designer/references/error-handling.md +541 -0
  9. package/plugins/loopx/skills/api-designer/references/openapi.md +824 -0
  10. package/plugins/loopx/skills/api-designer/references/pagination.md +494 -0
  11. package/plugins/loopx/skills/api-designer/references/rest-patterns.md +335 -0
  12. package/plugins/loopx/skills/api-designer/references/versioning.md +391 -0
  13. package/plugins/loopx/skills/architecture-designer/SKILL.md +117 -0
  14. package/plugins/loopx/skills/architecture-designer/references/adr-template.md +116 -0
  15. package/plugins/loopx/skills/architecture-designer/references/architecture-patterns.md +346 -0
  16. package/plugins/loopx/skills/architecture-designer/references/database-selection.md +102 -0
  17. package/plugins/loopx/skills/architecture-designer/references/nfr-checklist.md +212 -0
  18. package/plugins/loopx/skills/architecture-designer/references/system-design.md +313 -0
  19. package/plugins/loopx/skills/clarify/SKILL.md +1 -1
  20. package/plugins/loopx/skills/cli-developer/SKILL.md +124 -0
  21. package/plugins/loopx/skills/cli-developer/references/design-patterns.md +221 -0
  22. package/plugins/loopx/skills/cli-developer/references/go-cli.md +540 -0
  23. package/plugins/loopx/skills/cli-developer/references/node-cli.md +383 -0
  24. package/plugins/loopx/skills/cli-developer/references/python-cli.md +422 -0
  25. package/plugins/loopx/skills/cli-developer/references/ux-patterns.md +448 -0
  26. package/plugins/loopx/skills/debug/SKILL.md +1 -1
  27. package/plugins/loopx/skills/doc-readability/SKILL.md +1 -1
  28. package/plugins/loopx/skills/exec/SKILL.md +1 -1
  29. package/plugins/loopx/skills/final-review/SKILL.md +1 -1
  30. package/plugins/loopx/skills/finish/SKILL.md +1 -1
  31. package/plugins/loopx/skills/fix-review/SKILL.md +1 -1
  32. package/plugins/loopx/skills/go-style/SKILL.md +1 -1
  33. package/plugins/loopx/skills/kratos/SKILL.md +2 -1
  34. package/plugins/loopx/skills/plan-to-exec/SKILL.md +1 -1
  35. package/plugins/loopx/skills/refactor-plan/SKILL.md +1 -1
  36. package/plugins/loopx/skills/requirement-analyzer/SKILL.md +161 -0
  37. package/plugins/loopx/skills/requirement-analyzer/references/example-reports.md +170 -0
  38. package/plugins/loopx/skills/requirement-analyzer/references/prd-gap-checklist.md +167 -0
  39. package/plugins/loopx/skills/requirement-analyzer/references/readiness-rubric.md +70 -0
  40. package/plugins/loopx/skills/requirement-analyzer/references/report-template.md +83 -0
  41. package/plugins/loopx/skills/review/SKILL.md +1 -1
  42. package/plugins/loopx/skills/spec/SKILL.md +1 -1
  43. package/plugins/loopx/skills/sql-style/SKILL.md +108 -0
  44. package/plugins/loopx/skills/sql-style/references/database-design.md +402 -0
  45. package/plugins/loopx/skills/sql-style/references/dialect-differences.md +419 -0
  46. package/plugins/loopx/skills/sql-style/references/optimization.md +384 -0
  47. package/plugins/loopx/skills/sql-style/references/query-patterns.md +285 -0
  48. package/plugins/loopx/skills/sql-style/references/window-functions.md +328 -0
  49. package/plugins/loopx/skills/subagent-exec/SKILL.md +1 -1
  50. package/plugins/loopx/skills/tdd/SKILL.md +1 -1
  51. package/plugins/loopx/skills/verify/SKILL.md +1 -1
  52. package/scripts/verify-skills.mjs +0 -2
  53. package/skills/RESOLVER.md +8 -1
  54. package/skills/api-designer/SKILL.md +232 -0
  55. package/skills/api-designer/references/error-handling.md +541 -0
  56. package/skills/api-designer/references/openapi.md +824 -0
  57. package/skills/api-designer/references/pagination.md +494 -0
  58. package/skills/api-designer/references/rest-patterns.md +335 -0
  59. package/skills/api-designer/references/versioning.md +391 -0
  60. package/skills/architecture-designer/SKILL.md +117 -0
  61. package/skills/architecture-designer/references/adr-template.md +116 -0
  62. package/skills/architecture-designer/references/architecture-patterns.md +346 -0
  63. package/skills/architecture-designer/references/database-selection.md +102 -0
  64. package/skills/architecture-designer/references/nfr-checklist.md +212 -0
  65. package/skills/architecture-designer/references/system-design.md +313 -0
  66. package/skills/clarify/SKILL.md +1 -1
  67. package/skills/cli-developer/SKILL.md +124 -0
  68. package/skills/cli-developer/references/design-patterns.md +221 -0
  69. package/skills/cli-developer/references/go-cli.md +540 -0
  70. package/skills/cli-developer/references/node-cli.md +383 -0
  71. package/skills/cli-developer/references/python-cli.md +422 -0
  72. package/skills/cli-developer/references/ux-patterns.md +448 -0
  73. package/skills/debug/SKILL.md +1 -1
  74. package/skills/doc-readability/SKILL.md +1 -1
  75. package/skills/exec/SKILL.md +1 -1
  76. package/skills/final-review/SKILL.md +1 -1
  77. package/skills/finish/SKILL.md +1 -1
  78. package/skills/fix-review/SKILL.md +1 -1
  79. package/skills/go-style/SKILL.md +1 -1
  80. package/skills/kratos/SKILL.md +2 -1
  81. package/skills/plan-to-exec/SKILL.md +1 -1
  82. package/skills/refactor-plan/SKILL.md +1 -1
  83. package/skills/requirement-analyzer/SKILL.md +161 -0
  84. package/skills/requirement-analyzer/references/example-reports.md +170 -0
  85. package/skills/requirement-analyzer/references/prd-gap-checklist.md +167 -0
  86. package/skills/requirement-analyzer/references/readiness-rubric.md +70 -0
  87. package/skills/requirement-analyzer/references/report-template.md +83 -0
  88. package/skills/review/SKILL.md +1 -1
  89. package/skills/spec/SKILL.md +1 -1
  90. package/skills/sql-style/SKILL.md +108 -0
  91. package/skills/sql-style/references/database-design.md +402 -0
  92. package/skills/sql-style/references/dialect-differences.md +419 -0
  93. package/skills/sql-style/references/optimization.md +384 -0
  94. package/skills/sql-style/references/query-patterns.md +285 -0
  95. package/skills/sql-style/references/window-functions.md +328 -0
  96. package/skills/subagent-exec/SKILL.md +1 -1
  97. package/skills/tdd/SKILL.md +1 -1
  98. package/skills/verify/SKILL.md +1 -1
  99. package/src/install-discovery.mjs +5 -0
@@ -0,0 +1,108 @@
1
+ ---
2
+ name: sql-style
3
+ description: "Applies loopx SQL and database-change discipline for queries, schemas, indexes, migrations, dialects, and performance-sensitive data access. Not for replacing clarify, spec, implementation planning, code review, or workflow state transitions."
4
+ when_to_use: "sql-style, SQL, database schema, migration, index, query optimization, EXPLAIN, PostgreSQL, MySQL, SQLite, 数据库, 索引"
5
+ license: MIT
6
+ metadata:
7
+ version: "0.2.10"
8
+ forked_from: https://github.com/Jeffallan/claude-skills/tree/main/skills/sql-pro
9
+ maintained_by: loopx
10
+ ---
11
+
12
+ # SQL Style
13
+
14
+ ## Purpose
15
+
16
+ `sql-style` is the shared loopx SQL/database support lens. It fuses useful upstream `sql-pro` guidance with loopx workflow discipline.
17
+
18
+ Do not delete or flatten useful SQL/database guidance from other skills just because `sql-style` exists. Instead, make related skills call `sql-style` when SQL, database schema, migration, indexing, or query-performance discipline is relevant.
19
+
20
+ Use it directly for SQL, schema, index, migration, and database performance work. Use it from `spec`, `exec`, `review`, or `final-review` when work touches persistent data or performance-sensitive data access.
21
+
22
+ This skill does not replace `spec`. If data ownership, product semantics, migration compatibility, permission boundaries, or rollback decisions are unresolved, route those decisions through `clarify` or `spec`.
23
+
24
+ ## When To Use
25
+
26
+ - Designing or reviewing database schemas
27
+ - Writing or optimizing SQL queries
28
+ - Adding or changing indexes
29
+ - Writing migrations, backfills, or data cleanup
30
+ - Reviewing ORM-generated SQL or repository data access
31
+ - Investigating slow queries with `EXPLAIN` or query plans
32
+ - Handling dialect-specific behavior in PostgreSQL, MySQL, SQLite, or SQL Server
33
+
34
+ ## Schema And Migration Discipline
35
+
36
+ - Preserve existing schema conventions unless they are clearly broken.
37
+ - Define primary keys, foreign keys, uniqueness, nullability, and defaults intentionally.
38
+ - Treat nullability as product behavior, not a storage afterthought.
39
+ - Include rollback or forward-fix strategy for migrations that can fail mid-flight.
40
+ - Make repeated migration or backfill runs safe when the deployment process may retry.
41
+ - For large tables, plan lock behavior, batching, indexes, and online migration constraints.
42
+ - Keep application compatibility in mind during rolling deploys.
43
+ - For MySQL tables in Kratos projects, preserve the existing loopx rule: `CREATE TABLE` statements should include table comments, and persisted columns should include column comments where the project convention requires them.
44
+
45
+ ## Query Discipline
46
+
47
+ - Prefer set-based operations over row-by-row loops.
48
+ - Avoid `SELECT *` in production queries unless the repository has an explicit reason.
49
+ - Filter early and return only required columns.
50
+ - Handle `NULL` explicitly in predicates, joins, ordering, and uniqueness assumptions.
51
+ - Prefer `EXISTS` over `COUNT(*)` for existence checks when only existence matters.
52
+ - Make ordering deterministic for paginated or user-visible results.
53
+ - Use transactions deliberately. State the isolation assumptions when correctness depends on them.
54
+ - Keep query intent readable with names, structure, or short comments for non-obvious logic.
55
+
56
+ ## Index Discipline
57
+
58
+ - Add indexes for demonstrated access paths, constraints, or clearly required query patterns.
59
+ - Consider column order, selectivity, covering behavior, and write amplification.
60
+ - Avoid redundant indexes unless the dialect or workload justifies them.
61
+ - Verify the intended query uses the index with the project's database tooling when practical.
62
+ - Document why a non-obvious index exists.
63
+
64
+ ## Performance Verification
65
+
66
+ - Use project-specific performance targets when they exist.
67
+ - If no target exists, state the measured baseline and proposed improvement without inventing an SLO.
68
+ - Analyze execution plans before claiming an optimization works.
69
+ - Test against production-like data volume when data size can change the plan.
70
+ - Record before/after evidence for meaningful optimizations.
71
+
72
+ Example commands:
73
+
74
+ ```bash
75
+ EXPLAIN ANALYZE <query>;
76
+ go test ./...
77
+ npm test
78
+ pytest
79
+ ```
80
+
81
+ ## Dialect Discipline
82
+
83
+ - Check dialect-specific behavior for upserts, JSON fields, generated columns, partial indexes, expression indexes, collations, time zones, and locking.
84
+ - Do not assume PostgreSQL behavior applies to MySQL or SQLite.
85
+ - Keep ORM abstractions honest by inspecting generated SQL when performance or correctness depends on it.
86
+
87
+ ## Reference Guide
88
+
89
+ Load detailed guidance from the preserved upstream references when the task needs it:
90
+
91
+ | Topic | Reference | Load When |
92
+ |-------|-----------|-----------|
93
+ | Query Patterns | `references/query-patterns.md` | JOINs, CTEs, subqueries, recursive queries |
94
+ | Window Functions | `references/window-functions.md` | ROW_NUMBER, RANK, LAG/LEAD, analytics |
95
+ | Optimization | `references/optimization.md` | EXPLAIN plans, indexes, statistics, tuning |
96
+ | Database Design | `references/database-design.md` | Normalization, keys, constraints, schemas |
97
+ | Dialect Differences | `references/dialect-differences.md` | PostgreSQL, MySQL, SQLite, or SQL Server behavior |
98
+
99
+ ## Review Checklist
100
+
101
+ - Are schema semantics explicit: keys, uniqueness, nullability, defaults?
102
+ - Is migration order safe for rolling deploys and retries?
103
+ - Could repeated runs corrupt data or duplicate work?
104
+ - Do queries avoid unnecessary columns, rows, and row-by-row loops?
105
+ - Are `NULL` and ordering semantics intentional?
106
+ - Are indexes justified by access paths and verified when practical?
107
+ - Are dialect-specific assumptions documented?
108
+ - Is performance evidence fresh before any performance claim?
@@ -0,0 +1,402 @@
1
+ # Database Design
2
+
3
+ ## Normalization Levels
4
+
5
+ ```sql
6
+ -- 1NF: Atomic values, no repeating groups
7
+ -- Bad: Non-atomic phone column
8
+ CREATE TABLE customers_bad (
9
+ customer_id INT PRIMARY KEY,
10
+ name VARCHAR(100),
11
+ phones VARCHAR(500) -- "555-1234,555-5678,555-9012"
12
+ );
13
+
14
+ -- Good: Atomic values
15
+ CREATE TABLE customers (
16
+ customer_id SERIAL PRIMARY KEY,
17
+ name VARCHAR(100) NOT NULL
18
+ );
19
+
20
+ CREATE TABLE customer_phones (
21
+ phone_id SERIAL PRIMARY KEY,
22
+ customer_id INT NOT NULL REFERENCES customers(customer_id),
23
+ phone_number VARCHAR(20) NOT NULL,
24
+ phone_type VARCHAR(20) CHECK (phone_type IN ('mobile', 'home', 'work'))
25
+ );
26
+
27
+ -- 2NF: No partial dependencies (all non-key attributes depend on entire key)
28
+ -- Bad: Partial dependency on composite key
29
+ CREATE TABLE order_items_bad (
30
+ order_id INT,
31
+ product_id INT,
32
+ product_name VARCHAR(100), -- Depends only on product_id
33
+ product_price DECIMAL(10,2), -- Depends only on product_id
34
+ quantity INT,
35
+ PRIMARY KEY (order_id, product_id)
36
+ );
37
+
38
+ -- Good: Separate product attributes
39
+ CREATE TABLE products (
40
+ product_id SERIAL PRIMARY KEY,
41
+ product_name VARCHAR(100) NOT NULL,
42
+ product_price DECIMAL(10,2) NOT NULL CHECK (product_price >= 0)
43
+ );
44
+
45
+ CREATE TABLE order_items (
46
+ order_id INT,
47
+ product_id INT,
48
+ quantity INT NOT NULL CHECK (quantity > 0),
49
+ unit_price DECIMAL(10,2) NOT NULL, -- Snapshot at order time
50
+ PRIMARY KEY (order_id, product_id),
51
+ FOREIGN KEY (order_id) REFERENCES orders(order_id),
52
+ FOREIGN KEY (product_id) REFERENCES products(product_id)
53
+ );
54
+
55
+ -- 3NF: No transitive dependencies
56
+ -- Bad: City/State depends on ZIP
57
+ CREATE TABLE addresses_bad (
58
+ address_id INT PRIMARY KEY,
59
+ street VARCHAR(200),
60
+ city VARCHAR(100),
61
+ state VARCHAR(2),
62
+ zip_code VARCHAR(10)
63
+ );
64
+
65
+ -- Good: Separate ZIP code reference
66
+ CREATE TABLE zip_codes (
67
+ zip_code VARCHAR(10) PRIMARY KEY,
68
+ city VARCHAR(100) NOT NULL,
69
+ state VARCHAR(2) NOT NULL,
70
+ county VARCHAR(100)
71
+ );
72
+
73
+ CREATE TABLE addresses (
74
+ address_id SERIAL PRIMARY KEY,
75
+ street VARCHAR(200) NOT NULL,
76
+ zip_code VARCHAR(10) NOT NULL REFERENCES zip_codes(zip_code)
77
+ );
78
+ ```
79
+
80
+ ## Primary and Foreign Keys
81
+
82
+ ```sql
83
+ -- Natural vs Surrogate keys
84
+ -- Natural key (business meaning)
85
+ CREATE TABLE countries (
86
+ country_code CHAR(2) PRIMARY KEY, -- ISO 3166-1 alpha-2
87
+ country_name VARCHAR(100) NOT NULL
88
+ );
89
+
90
+ -- Surrogate key (technical, no business meaning)
91
+ CREATE TABLE customers (
92
+ customer_id SERIAL PRIMARY KEY, -- Auto-incrementing surrogate
93
+ email VARCHAR(255) NOT NULL UNIQUE, -- Natural candidate key
94
+ name VARCHAR(100) NOT NULL,
95
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
96
+ );
97
+
98
+ -- Composite primary key
99
+ CREATE TABLE student_courses (
100
+ student_id INT,
101
+ course_id INT,
102
+ enrollment_date DATE NOT NULL,
103
+ grade CHAR(2),
104
+ PRIMARY KEY (student_id, course_id),
105
+ FOREIGN KEY (student_id) REFERENCES students(student_id),
106
+ FOREIGN KEY (course_id) REFERENCES courses(course_id)
107
+ );
108
+
109
+ -- UUID primary keys (distributed systems, no sequence conflicts)
110
+ CREATE TABLE events (
111
+ event_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
112
+ event_type VARCHAR(50) NOT NULL,
113
+ event_data JSONB,
114
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
115
+ );
116
+
117
+ -- Foreign key with cascading actions
118
+ CREATE TABLE orders (
119
+ order_id SERIAL PRIMARY KEY,
120
+ customer_id INT NOT NULL,
121
+ order_date DATE DEFAULT CURRENT_DATE,
122
+ FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
123
+ ON DELETE CASCADE -- Delete orders when customer deleted
124
+ ON UPDATE CASCADE -- Update order.customer_id when customers.customer_id changes
125
+ );
126
+
127
+ CREATE TABLE order_items (
128
+ order_item_id SERIAL PRIMARY KEY,
129
+ order_id INT NOT NULL,
130
+ product_id INT NOT NULL,
131
+ quantity INT NOT NULL,
132
+ FOREIGN KEY (order_id) REFERENCES orders(order_id)
133
+ ON DELETE CASCADE, -- Delete items when order deleted
134
+ FOREIGN KEY (product_id) REFERENCES products(product_id)
135
+ ON DELETE RESTRICT -- Prevent deleting product if used in orders
136
+ );
137
+ ```
138
+
139
+ ## Constraints and Validation
140
+
141
+ ```sql
142
+ -- CHECK constraints
143
+ CREATE TABLE employees (
144
+ employee_id SERIAL PRIMARY KEY,
145
+ first_name VARCHAR(50) NOT NULL,
146
+ last_name VARCHAR(50) NOT NULL,
147
+ email VARCHAR(255) NOT NULL UNIQUE,
148
+ salary DECIMAL(12,2) NOT NULL,
149
+ hire_date DATE NOT NULL,
150
+ birth_date DATE NOT NULL,
151
+
152
+ CONSTRAINT chk_salary_positive CHECK (salary > 0),
153
+ CONSTRAINT chk_email_format CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}$'),
154
+ CONSTRAINT chk_hire_after_birth CHECK (hire_date > birth_date + INTERVAL '16 years'),
155
+ CONSTRAINT chk_hire_not_future CHECK (hire_date <= CURRENT_DATE)
156
+ );
157
+
158
+ -- Unique constraints (including composite)
159
+ CREATE TABLE user_preferences (
160
+ user_id INT NOT NULL,
161
+ preference_key VARCHAR(50) NOT NULL,
162
+ preference_value TEXT,
163
+
164
+ CONSTRAINT uq_user_preference UNIQUE (user_id, preference_key)
165
+ );
166
+
167
+ -- NOT NULL constraints with defaults
168
+ CREATE TABLE products (
169
+ product_id SERIAL PRIMARY KEY,
170
+ name VARCHAR(200) NOT NULL,
171
+ description TEXT,
172
+ price DECIMAL(10,2) NOT NULL DEFAULT 0.00,
173
+ is_active BOOLEAN NOT NULL DEFAULT true,
174
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
175
+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
176
+ );
177
+
178
+ -- Exclusion constraints (PostgreSQL - prevent overlapping ranges)
179
+ CREATE TABLE room_bookings (
180
+ booking_id SERIAL PRIMARY KEY,
181
+ room_id INT NOT NULL,
182
+ booked_during TSTZRANGE NOT NULL,
183
+
184
+ EXCLUDE USING GIST (
185
+ room_id WITH =,
186
+ booked_during WITH &&
187
+ ) -- Prevent overlapping bookings for same room
188
+ );
189
+ ```
190
+
191
+ ## Indexing Strategy
192
+
193
+ ```sql
194
+ -- Index foreign keys when joins, deletes, cascades, or referential checks make the access path important
195
+ CREATE INDEX idx_orders_customer_id ON orders(customer_id);
196
+ CREATE INDEX idx_order_items_order_id ON order_items(order_id);
197
+ CREATE INDEX idx_order_items_product_id ON order_items(product_id);
198
+
199
+ -- Composite index for common queries
200
+ CREATE INDEX idx_orders_customer_date ON orders(customer_id, order_date DESC);
201
+ -- Supports:
202
+ -- WHERE customer_id = ? AND order_date > ?
203
+ -- WHERE customer_id = ? ORDER BY order_date DESC
204
+
205
+ -- Partial index for common filters
206
+ CREATE INDEX idx_active_products ON products(category, price)
207
+ WHERE is_active = true AND deleted_at IS NULL;
208
+
209
+ -- Unique index for business rules
210
+ CREATE UNIQUE INDEX idx_users_active_email ON users(LOWER(email))
211
+ WHERE deleted_at IS NULL;
212
+ -- Ensures no duplicate emails among active users
213
+ ```
214
+
215
+ ## Common Design Patterns
216
+
217
+ ```sql
218
+ -- Polymorphic associations (flexible but harder to enforce integrity)
219
+ CREATE TABLE comments (
220
+ comment_id SERIAL PRIMARY KEY,
221
+ commentable_type VARCHAR(50) NOT NULL, -- 'Post', 'Photo', 'Video'
222
+ commentable_id INT NOT NULL,
223
+ content TEXT NOT NULL,
224
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
225
+
226
+ -- Cannot enforce FK without triggers/application logic
227
+ CHECK (commentable_type IN ('Post', 'Photo', 'Video'))
228
+ );
229
+
230
+ -- Better: Separate tables with proper FKs
231
+ CREATE TABLE post_comments (
232
+ comment_id SERIAL PRIMARY KEY,
233
+ post_id INT NOT NULL REFERENCES posts(post_id),
234
+ content TEXT NOT NULL,
235
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
236
+ );
237
+
238
+ CREATE TABLE photo_comments (
239
+ comment_id SERIAL PRIMARY KEY,
240
+ photo_id INT NOT NULL REFERENCES photos(photo_id),
241
+ content TEXT NOT NULL,
242
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
243
+ );
244
+
245
+ -- Many-to-many with attributes (junction/bridge table)
246
+ CREATE TABLE students (
247
+ student_id SERIAL PRIMARY KEY,
248
+ name VARCHAR(100) NOT NULL
249
+ );
250
+
251
+ CREATE TABLE courses (
252
+ course_id SERIAL PRIMARY KEY,
253
+ course_name VARCHAR(100) NOT NULL
254
+ );
255
+
256
+ CREATE TABLE enrollments (
257
+ enrollment_id SERIAL PRIMARY KEY,
258
+ student_id INT NOT NULL REFERENCES students(student_id),
259
+ course_id INT NOT NULL REFERENCES courses(course_id),
260
+ enrollment_date DATE NOT NULL DEFAULT CURRENT_DATE,
261
+ grade CHAR(2),
262
+ status VARCHAR(20) DEFAULT 'active',
263
+
264
+ UNIQUE (student_id, course_id),
265
+ CHECK (status IN ('active', 'completed', 'dropped'))
266
+ );
267
+
268
+ -- Self-referencing hierarchy
269
+ CREATE TABLE categories (
270
+ category_id SERIAL PRIMARY KEY,
271
+ category_name VARCHAR(100) NOT NULL,
272
+ parent_category_id INT REFERENCES categories(category_id),
273
+ level INT NOT NULL DEFAULT 0,
274
+
275
+ CHECK (category_id != parent_category_id) -- Prevent self-reference
276
+ );
277
+
278
+ -- Adjacency list example
279
+ INSERT INTO categories VALUES
280
+ (1, 'Electronics', NULL, 0),
281
+ (2, 'Computers', 1, 1),
282
+ (3, 'Laptops', 2, 2),
283
+ (4, 'Desktops', 2, 2);
284
+ ```
285
+
286
+ ## Temporal/Historical Data
287
+
288
+ ```sql
289
+ -- Slowly Changing Dimension Type 2 (SCD2) - Full history
290
+ CREATE TABLE customer_history (
291
+ customer_history_id SERIAL PRIMARY KEY,
292
+ customer_id INT NOT NULL,
293
+ name VARCHAR(100) NOT NULL,
294
+ email VARCHAR(255) NOT NULL,
295
+ address TEXT,
296
+ valid_from TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
297
+ valid_to TIMESTAMP,
298
+ is_current BOOLEAN NOT NULL DEFAULT true,
299
+
300
+ CHECK (valid_to IS NULL OR valid_to > valid_from)
301
+ );
302
+
303
+ -- Ensure only one current record per customer
304
+ CREATE UNIQUE INDEX idx_customer_current ON customer_history(customer_id)
305
+ WHERE is_current = true;
306
+
307
+ -- Temporal tables (PostgreSQL system-versioning)
308
+ CREATE TABLE products (
309
+ product_id SERIAL PRIMARY KEY,
310
+ name VARCHAR(200) NOT NULL,
311
+ price DECIMAL(10,2) NOT NULL,
312
+ sys_period TSTZRANGE NOT NULL DEFAULT tstzrange(CURRENT_TIMESTAMP, NULL)
313
+ );
314
+
315
+ CREATE TABLE products_history (LIKE products);
316
+
317
+ CREATE TRIGGER versioning_trigger
318
+ BEFORE INSERT OR UPDATE OR DELETE ON products
319
+ FOR EACH ROW EXECUTE FUNCTION versioning('sys_period', 'products_history', true);
320
+ ```
321
+
322
+ ## Soft Deletes
323
+
324
+ ```sql
325
+ -- Soft delete pattern
326
+ CREATE TABLE posts (
327
+ post_id SERIAL PRIMARY KEY,
328
+ title VARCHAR(255) NOT NULL,
329
+ content TEXT NOT NULL,
330
+ author_id INT NOT NULL REFERENCES users(user_id),
331
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
332
+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
333
+ deleted_at TIMESTAMP, -- NULL = active, non-NULL = deleted
334
+ deleted_by INT REFERENCES users(user_id)
335
+ );
336
+
337
+ -- Index for filtering active records
338
+ CREATE INDEX idx_posts_active ON posts(created_at DESC)
339
+ WHERE deleted_at IS NULL;
340
+
341
+ -- View for active posts only
342
+ CREATE VIEW active_posts AS
343
+ SELECT post_id, title, content, author_id, created_at, updated_at
344
+ FROM posts
345
+ WHERE deleted_at IS NULL;
346
+ ```
347
+
348
+ ## Audit Trails
349
+
350
+ ```sql
351
+ -- Audit table pattern
352
+ CREATE TABLE audit_log (
353
+ audit_id BIGSERIAL PRIMARY KEY,
354
+ table_name VARCHAR(100) NOT NULL,
355
+ record_id BIGINT NOT NULL,
356
+ action VARCHAR(10) NOT NULL CHECK (action IN ('INSERT', 'UPDATE', 'DELETE')),
357
+ old_values JSONB,
358
+ new_values JSONB,
359
+ changed_by INT REFERENCES users(user_id),
360
+ changed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
361
+ );
362
+
363
+ CREATE INDEX idx_audit_table_record ON audit_log(table_name, record_id);
364
+ CREATE INDEX idx_audit_timestamp ON audit_log(changed_at DESC);
365
+
366
+ -- Trigger function for automatic auditing
367
+ CREATE OR REPLACE FUNCTION audit_trigger_func()
368
+ RETURNS TRIGGER AS $$
369
+ BEGIN
370
+ IF (TG_OP = 'DELETE') THEN
371
+ INSERT INTO audit_log (table_name, record_id, action, old_values)
372
+ VALUES (TG_TABLE_NAME, OLD.product_id, 'DELETE', row_to_json(OLD));
373
+ RETURN OLD;
374
+ ELSIF (TG_OP = 'UPDATE') THEN
375
+ INSERT INTO audit_log (table_name, record_id, action, old_values, new_values)
376
+ VALUES (TG_TABLE_NAME, NEW.product_id, 'UPDATE', row_to_json(OLD), row_to_json(NEW));
377
+ RETURN NEW;
378
+ ELSIF (TG_OP = 'INSERT') THEN
379
+ INSERT INTO audit_log (table_name, record_id, action, new_values)
380
+ VALUES (TG_TABLE_NAME, NEW.product_id, 'INSERT', row_to_json(NEW));
381
+ RETURN NEW;
382
+ END IF;
383
+ END;
384
+ $$ LANGUAGE plpgsql;
385
+
386
+ CREATE TRIGGER products_audit
387
+ AFTER INSERT OR UPDATE OR DELETE ON products
388
+ FOR EACH ROW EXECUTE FUNCTION audit_trigger_func();
389
+ ```
390
+
391
+ ## Schema Design Best Practices
392
+
393
+ 1. **Choose appropriate data types**: Use smallest type that fits (INT vs BIGINT, VARCHAR(50) vs TEXT)
394
+ 2. **Index foreign keys deliberately**: Add FK indexes for demonstrated joins, deletes, cascades, or referential checks; verify write overhead and plan usage
395
+ 3. **Avoid NULLs when possible**: Use NOT NULL with defaults
396
+ 4. **Use constraints**: Enforce data integrity at database level
397
+ 5. **Normalize to 3NF**: Then denormalize strategically for performance
398
+ 6. **Consider soft deletes**: For auditing and data recovery
399
+ 7. **Plan for growth**: Use BIGINT for high-volume PKs
400
+ 8. **Document schema**: Comment tables and complex constraints
401
+ 9. **Version control**: Track schema changes with migrations
402
+ 10. **Test with realistic data**: Validate design with production-scale data