vibes-plug 1.0.0 → 2.5.0

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 (123) hide show
  1. package/.github/workflows/publish.yml +20 -0
  2. package/AGENTS.md +66 -0
  3. package/BLUEPRINT.md +152 -60
  4. package/CHANGELOG.md +50 -0
  5. package/README.md +346 -194
  6. package/package.json +25 -25
  7. package/plugin.json +1 -1
  8. package/skills/ai-cost-token-optimizer/SKILL.md +52 -0
  9. package/skills/ai-llm-integration-expert/SKILL.md +180 -162
  10. package/skills/api-design-expert/SKILL.md +314 -310
  11. package/skills/app-analyzer-optimizer/SKILL.md +193 -189
  12. package/skills/apple-ecosystem-expert/SKILL.md +142 -0
  13. package/skills/async-queue-temporal-expert/SKILL.md +54 -0
  14. package/skills/authentication-identity-expert/SKILL.md +251 -20
  15. package/skills/auto-doc-updater/SKILL.md +214 -204
  16. package/skills/autonomous-chaos-monkey/SKILL.md +63 -0
  17. package/skills/autonomous-red-teamer/SKILL.md +59 -0
  18. package/skills/autonomous-swarm-director/SKILL.md +69 -0
  19. package/skills/autonomous-tdd-debugger/SKILL.md +65 -0
  20. package/skills/bootstrap-to-modern/SKILL.md +90 -86
  21. package/skills/brainstorming/SKILL.md +373 -353
  22. package/skills/browser-automation-expert/SKILL.md +46 -0
  23. package/skills/ci-cd-devops-architect/SKILL.md +72 -45
  24. package/skills/cloud-hosting-expert/SKILL.md +244 -244
  25. package/skills/coderabbit/SKILL.md +192 -192
  26. package/skills/cron-scheduler-expert/SKILL.md +298 -0
  27. package/skills/data-telemetry-expert/SKILL.md +213 -213
  28. package/skills/database-orm-expert/SKILL.md +294 -294
  29. package/skills/dependency-upgrade-migrator/SKILL.md +295 -0
  30. package/skills/design-system-architect/SKILL.md +27 -10
  31. package/skills/doku-mcp-server/SKILL.md +251 -0
  32. package/skills/doku-payment-gateway/SKILL.md +227 -0
  33. package/skills/e2e-testing-expert/SKILL.md +315 -315
  34. package/skills/edge-serverless-db-expert/SKILL.md +43 -0
  35. package/skills/email-notification-expert/SKILL.md +362 -0
  36. package/skills/error-resilience-expert/SKILL.md +480 -0
  37. package/skills/event-driven-architect/SKILL.md +81 -81
  38. package/skills/feature-flag-analytics-expert/SKILL.md +46 -0
  39. package/skills/file-upload-media-expert/SKILL.md +431 -0
  40. package/skills/form-validation-expert/SKILL.md +401 -0
  41. package/skills/fullstack-expert/SKILL.md +202 -202
  42. package/skills/fullstack-expert/references/api_design_guide.md +466 -466
  43. package/skills/fullstack-expert/references/multi_language_backend.md +528 -528
  44. package/skills/fullstack-expert/scripts/api_contract_validator.py +253 -253
  45. package/skills/fullstack-expert/scripts/architecture_analyzer.py +326 -326
  46. package/skills/gemini-agent-booster/SKILL.md +135 -135
  47. package/skills/global-a11y-i18n-expert/SKILL.md +81 -81
  48. package/skills/glsl-shader-expert/SKILL.md +101 -0
  49. package/skills/go-programming-expert/SKILL.md +295 -295
  50. package/skills/graphql-apollo-expert/SKILL.md +108 -0
  51. package/skills/hig/SKILL.md +188 -188
  52. package/skills/hyper-context-synthesizer/SKILL.md +55 -0
  53. package/skills/js-backend-expert/SKILL.md +34 -9
  54. package/skills/legacy-code-translator/SKILL.md +65 -0
  55. package/skills/llm-cost-arbitrage-router/SKILL.md +59 -0
  56. package/skills/logging-error-tracking-expert/SKILL.md +338 -0
  57. package/skills/mcp-client-orchestrator/SKILL.md +70 -0
  58. package/skills/mcp-server-architect/SKILL.md +194 -194
  59. package/skills/micro-frontend-architect/SKILL.md +106 -0
  60. package/skills/mobile-expo-expert/SKILL.md +186 -186
  61. package/skills/mobile-push-notification-expert/SKILL.md +51 -0
  62. package/skills/monday-design-aesthetic/SKILL.md +67 -67
  63. package/skills/monorepo-architect/SKILL.md +227 -227
  64. package/skills/mpa-orchestrator/SKILL.md +101 -101
  65. package/skills/multi-agent-orchestration/SKILL.md +234 -234
  66. package/skills/multiple-entry-points/SKILL.md +55 -55
  67. package/skills/mvc-expert/SKILL.md +231 -231
  68. package/skills/payment-gateway-expert/SKILL.md +45 -45
  69. package/skills/performance-web-vitals/SKILL.md +332 -332
  70. package/skills/post-quantum-crypto-migrator/SKILL.md +57 -0
  71. package/skills/prd-architect/SKILL.md +201 -191
  72. package/skills/proactive-background-watcher/SKILL.md +62 -0
  73. package/skills/production-ready-hardener/PRODUCTION_READINESS_REPORT.md +67 -0
  74. package/skills/production-ready-hardener/SKILL.md +173 -186
  75. package/skills/production-ready-hardener/references/production_checklist.md +161 -161
  76. package/skills/production-ready-hardener/scripts/production_readiness_scanner.py +881 -875
  77. package/skills/project-context-mapper/SKILL.md +79 -0
  78. package/skills/python-programming-expert/SKILL.md +263 -132
  79. package/skills/rate-limit-abuse-prevention/SKILL.md +371 -0
  80. package/skills/realtime-collaboration-expert/SKILL.md +45 -45
  81. package/skills/rust-programming-expert/SKILL.md +235 -235
  82. package/skills/saas-billing/SKILL.md +377 -377
  83. package/skills/saas-multi-tenant/SKILL.md +251 -237
  84. package/skills/saas-mvp-launcher/SKILL.md +10 -0
  85. package/skills/saas-transformer/SKILL.md +187 -144
  86. package/skills/saas-transformer/references/billing_integration_guide.md +401 -401
  87. package/skills/saas-transformer/references/feature_gating_patterns.md +137 -137
  88. package/skills/saas-transformer/references/saas_transformation_checklist.md +121 -121
  89. package/skills/saas-transformer/scripts/saas_transformation_scanner.py +39 -29
  90. package/skills/scalability-clean-code/SKILL.md +229 -229
  91. package/skills/self-evolving-memory-graph/SKILL.md +75 -0
  92. package/skills/self-healing-cloud-orchestrator/SKILL.md +57 -0
  93. package/skills/senior-frontend/SKILL.md +161 -161
  94. package/skills/senior-fullstack/SKILL.md +167 -167
  95. package/skills/seo/SKILL.md +235 -225
  96. package/skills/seo-geo/SKILL.md +188 -188
  97. package/skills/session-context-loader/SKILL.md +77 -0
  98. package/skills/session-handoff-resume/SKILL.md +158 -158
  99. package/skills/skill_baru/SKILL.md +172 -147
  100. package/skills/spa-orchestrator/SKILL.md +288 -288
  101. package/skills/state-management-expert/SKILL.md +272 -272
  102. package/skills/supabase-security-expert/SKILL.md +243 -243
  103. package/skills/tailwind-expert/SKILL.md +188 -188
  104. package/skills/tanstack-query-expert/SKILL.md +199 -199
  105. package/skills/token-saver/SKILL.md +119 -111
  106. package/skills/typescript-expert/SKILL.md +324 -279
  107. package/skills/ui-components-expert/SKILL.md +263 -46
  108. package/skills/ui-ux-pro-max/SKILL.md +202 -201
  109. package/skills/ui-ux-pro-max/scripts/__pycache__/core.cpython-310.pyc +0 -0
  110. package/skills/ui-ux-pro-max/scripts/__pycache__/design_system.cpython-310.pyc +0 -0
  111. package/skills/ui_ux_expert/SKILL.md +17 -6
  112. package/skills/vector-db-rag-expert/SKILL.md +52 -0
  113. package/skills/vibe-code-gardener/SKILL.md +181 -173
  114. package/skills/visual-qa-vision-agent/SKILL.md +65 -0
  115. package/skills/vue-frontend-expert/SKILL.md +126 -0
  116. package/skills/web-3d-graphics-expert/SKILL.md +131 -0
  117. package/skills/web-game-engine-expert/SKILL.md +96 -0
  118. package/skills/web-scraper/SKILL.md +207 -205
  119. package/skills/website-design-cloner/SKILL.md +174 -0
  120. package/skills/webxr-ar-vr-expert/SKILL.md +117 -0
  121. package/skills/zero-to-prod-orchestrator/SKILL.md +206 -180
  122. package/skills/zero-trust-secret-vault/SKILL.md +40 -0
  123. package/vibes-swarm-demo.gif +0 -0
@@ -1,294 +1,294 @@
1
- ---
2
- name: database-orm-expert
3
- description: "Expert guide for database schema design, ORM tools (Prisma 6, Drizzle ORM, TypeORM), migrations, query optimization, and type-safe SQL patterns in TypeScript / Panduan ahli untuk desain skema database, ORM tools (Prisma 6, Drizzle ORM, TypeORM), migrasi, optimasi query, dan pola SQL type-safe di TypeScript."
4
- author: "Roedy Rustam"
5
- ---
6
-
7
- # Database ORM Expert (Prisma 6 + Drizzle ORM Edition)
8
-
9
- [English](#english) | [Bahasa Indonesia](#bahasa-indonesia)
10
-
11
- ---
12
-
13
- <a name="english"></a>
14
- ## English
15
-
16
- ### Description
17
- Expert-level database development covering schema design, ORM selection, migrations, query optimization, and type-safe SQL patterns. Focuses on **Prisma 6** and **Drizzle ORM** as primary modern ORMs, with coverage of TypeORM, raw SQL via `postgres.js`, and connection pooling strategies for production workloads.
18
-
19
- ### Trigger Conditions
20
- - Designing or migrating a database schema.
21
- - Choosing between Prisma, Drizzle ORM, or TypeORM.
22
- - Writing complex queries with joins, aggregations, or pagination.
23
- - Optimizing slow queries or N+1 problems.
24
- - Setting up database migrations in CI/CD pipelines.
25
- - Implementing Row Level Security (RLS) patterns.
26
- - Working with PostgreSQL, MySQL, SQLite, or PlanetScale.
27
-
28
- ---
29
-
30
- ### ORM Selection Guide
31
-
32
- | Criteria | Prisma 6 | Drizzle ORM | TypeORM |
33
- |---|---|---|---|
34
- | **Type Safety** | Schema-generated types | SQL-like, inferred types | Decorator-based |
35
- | **Bundle Size** | Heavy (binary client) | Lightweight (<35KB) | Medium |
36
- | **Query Style** | Fluent ORM API | SQL-first, composable | ActiveRecord / QueryBuilder |
37
- | **Edge Runtime** | Prisma Accelerate needed | Native edge support | No |
38
- | **Migrations** | `prisma migrate dev` | `drizzle-kit push/migrate` | `synchronize` (dev only) |
39
- | **Best For** | Rapid prototyping, teams | Production edge, monorepos | Legacy NestJS projects |
40
-
41
- **Recommendation**: Use **Drizzle ORM** for edge-compatible apps and performance-critical systems. Use **Prisma 6** for teams that prefer a schema-first DX and rich Studio tooling.
42
-
43
- ---
44
-
45
- ### Prisma 6 — Best Practices
46
-
47
- #### Schema Design
48
- ```prisma
49
- // schema.prisma
50
- generator client {
51
- provider = "prisma-client-js"
52
- previewFeatures = ["relationJoins", "nativeDistinct"]
53
- }
54
-
55
- datasource db {
56
- provider = "postgresql"
57
- url = env("DATABASE_URL")
58
- directUrl = env("DIRECT_URL") // for Supabase Pooler
59
- }
60
-
61
- model User {
62
- id String @id @default(cuid())
63
- email String @unique
64
- name String?
65
- role Role @default(USER)
66
- posts Post[]
67
- createdAt DateTime @default(now())
68
- updatedAt DateTime @updatedAt
69
-
70
- @@index([email])
71
- @@map("users")
72
- }
73
-
74
- model Post {
75
- id String @id @default(cuid())
76
- title String
77
- content String?
78
- published Boolean @default(false)
79
- authorId String
80
- author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
81
- publishedAt DateTime?
82
-
83
- @@index([authorId, published])
84
- @@map("posts")
85
- }
86
-
87
- enum Role {
88
- USER
89
- ADMIN
90
- SUPER_ADMIN
91
- }
92
- ```
93
-
94
- #### Avoiding N+1 with `include` vs `select`
95
- ```typescript
96
- // BAD: triggers N+1 queries
97
- const users = await prisma.user.findMany();
98
- for (const user of users) {
99
- const posts = await prisma.post.findMany({ where: { authorId: user.id } });
100
- }
101
-
102
- // GOOD: single query with JOIN (Prisma 5.7+ relationJoins preview)
103
- const users = await prisma.user.findMany({
104
- select: {
105
- id: true,
106
- name: true,
107
- email: true,
108
- _count: { select: { posts: true } },
109
- posts: {
110
- where: { published: true },
111
- select: { id: true, title: true },
112
- take: 5,
113
- orderBy: { publishedAt: 'desc' },
114
- },
115
- },
116
- });
117
- ```
118
-
119
- #### Optimistic Transactions
120
- ```typescript
121
- // Use $transaction for atomic operations
122
- const [updatedUser, newPost] = await prisma.$transaction([
123
- prisma.user.update({ where: { id }, data: { name } }),
124
- prisma.post.create({ data: { title, authorId: id } }),
125
- ]);
126
-
127
- // Interactive transaction for complex logic
128
- const result = await prisma.$transaction(async (tx) => {
129
- const user = await tx.user.findUniqueOrThrow({ where: { id } });
130
- if (user.role !== 'ADMIN') throw new Error('Unauthorized');
131
- return tx.post.updateMany({ where: { authorId: id }, data: { published: true } });
132
- });
133
- ```
134
-
135
- ---
136
-
137
- ### Drizzle ORM — Best Practices
138
-
139
- #### Schema Definition (PostgreSQL)
140
- ```typescript
141
- // src/db/schema.ts
142
- import { pgTable, text, boolean, timestamp, pgEnum, index } from 'drizzle-orm/pg-core';
143
- import { createId } from '@paralleldrive/cuid2';
144
- import { relations } from 'drizzle-orm';
145
-
146
- export const roleEnum = pgEnum('role', ['USER', 'ADMIN', 'SUPER_ADMIN']);
147
-
148
- export const users = pgTable('users', {
149
- id: text('id').primaryKey().$defaultFn(() => createId()),
150
- email: text('email').notNull().unique(),
151
- name: text('name'),
152
- role: roleEnum('role').default('USER').notNull(),
153
- createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
154
- updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull().$onUpdateFn(() => new Date()),
155
- }, (t) => [
156
- index('users_email_idx').on(t.email),
157
- ]);
158
-
159
- export const posts = pgTable('posts', {
160
- id: text('id').primaryKey().$defaultFn(() => createId()),
161
- title: text('title').notNull(),
162
- content: text('content'),
163
- published: boolean('published').default(false).notNull(),
164
- authorId: text('author_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
165
- publishedAt: timestamp('published_at', { withTimezone: true }),
166
- }, (t) => [
167
- index('posts_author_published_idx').on(t.authorId, t.published),
168
- ]);
169
-
170
- export const usersRelations = relations(users, ({ many }) => ({
171
- posts: many(posts),
172
- }));
173
-
174
- export const postsRelations = relations(posts, ({ one }) => ({
175
- author: one(users, { fields: [posts.authorId], references: [users.id] }),
176
- }));
177
- ```
178
-
179
- #### Type-safe Queries with Drizzle
180
- ```typescript
181
- // src/db/index.ts
182
- import { drizzle } from 'drizzle-orm/postgres-js';
183
- import postgres from 'postgres';
184
- import * as schema from './schema';
185
-
186
- const client = postgres(process.env.DATABASE_URL!);
187
- export const db = drizzle(client, { schema });
188
-
189
- // Type-safe query with joins
190
- import { eq, and, desc, count } from 'drizzle-orm';
191
-
192
- const usersWithPosts = await db.query.users.findMany({
193
- with: {
194
- posts: {
195
- where: eq(posts.published, true),
196
- orderBy: desc(posts.publishedAt),
197
- limit: 5,
198
- },
199
- },
200
- extras: {
201
- postCount: db.$count(posts, eq(posts.authorId, users.id)).as('post_count'),
202
- },
203
- });
204
-
205
- // Paginated query
206
- async function getPaginatedPosts(page: number, pageSize = 20) {
207
- const offset = (page - 1) * pageSize;
208
- const [items, [{ total }]] = await Promise.all([
209
- db.select().from(posts).where(eq(posts.published, true))
210
- .orderBy(desc(posts.publishedAt))
211
- .limit(pageSize)
212
- .offset(offset),
213
- db.select({ total: count() }).from(posts).where(eq(posts.published, true)),
214
- ]);
215
- return { items, total, pages: Math.ceil(total / pageSize) };
216
- }
217
- ```
218
-
219
- #### Drizzle Migration Workflow
220
- ```bash
221
- # drizzle.config.ts defines connection + schema path
222
- npx drizzle-kit generate # generate migration SQL files
223
- npx drizzle-kit migrate # apply migrations to database
224
- npx drizzle-kit push # push schema directly (dev only)
225
- npx drizzle-kit studio # open Drizzle Studio GUI
226
- ```
227
-
228
- ---
229
-
230
- ### Query Optimization Principles
231
-
232
- 1. **Always index foreign keys** and columns used in `WHERE`, `ORDER BY`, and `JOIN`.
233
- 2. **Use `EXPLAIN ANALYZE`** to detect sequential scans and missing indexes.
234
- 3. **Cursor-based pagination** over offset for large datasets:
235
- ```typescript
236
- // Cursor pagination with Drizzle
237
- const items = await db.select().from(posts)
238
- .where(cursor ? lt(posts.createdAt, cursor) : undefined)
239
- .orderBy(desc(posts.createdAt))
240
- .limit(pageSize);
241
- ```
242
- 4. **Connection pooling**: Use PgBouncer or Supabase's built-in pooler. Set `DIRECT_URL` for migrations and `DATABASE_URL` for pooled reads/writes.
243
- 5. **Avoid `SELECT *`**: Always select only the columns you need.
244
- 6. **Batch inserts**: Use `db.insert(table).values([...items])` instead of looping.
245
-
246
- ---
247
-
248
- ### Migration Best Practices
249
-
250
- - **Never use `synchronize: true`** in production (TypeORM).
251
- - **Never run `prisma db push`** in production — always use `prisma migrate deploy`.
252
- - Store migration files in version control.
253
- - Run migrations as a separate step before deploying new app versions.
254
- - Use **advisory locks** or migration tools to prevent concurrent migration runs.
255
-
256
- ---
257
-
258
- <a name="bahasa-indonesia"></a>
259
- ## Bahasa Indonesia
260
-
261
- ### Deskripsi
262
- Panduan pengembangan database level ahli mencakup desain skema, pemilihan ORM, migrasi, optimasi query, dan pola SQL type-safe. Berfokus pada **Prisma 6** dan **Drizzle ORM** sebagai ORM modern utama, dengan cakupan TypeORM, SQL mentah via `postgres.js`, dan strategi connection pooling untuk beban kerja produksi.
263
-
264
- ### Kondisi Pemicu
265
- - Merancang atau memigrasikan skema database.
266
- - Memilih antara Prisma, Drizzle ORM, atau TypeORM.
267
- - Menulis query kompleks dengan join, agregasi, atau paginasi.
268
- - Mengoptimalkan query lambat atau masalah N+1.
269
- - Menyiapkan migrasi database dalam pipeline CI/CD.
270
- - Mengimplementasikan pola Row Level Security (RLS).
271
- - Bekerja dengan PostgreSQL, MySQL, SQLite, atau PlanetScale.
272
-
273
- ### Panduan Pemilihan ORM
274
-
275
- Gunakan tabel di atas (lihat bagian English) sebagai referensi pemilihan ORM. Rekomendasi singkat:
276
- - **Drizzle ORM**: Untuk aplikasi edge-compatible dan sistem kritis performa.
277
- - **Prisma 6**: Untuk tim yang lebih menyukai DX schema-first dan tooling Studio yang kaya.
278
- - **TypeORM**: Hanya untuk proyek lama (legacy) berbasis NestJS.
279
-
280
- ### Prinsip Utama
281
-
282
- 1. **Selalu index foreign key** dan kolom yang digunakan di `WHERE`, `ORDER BY`, dan `JOIN`.
283
- 2. **Gunakan `EXPLAIN ANALYZE`** untuk mendeteksi sequential scan dan index yang hilang.
284
- 3. **Cursor-based pagination** lebih baik dari offset untuk dataset besar.
285
- 4. **Connection pooling**: Gunakan PgBouncer atau Supabase pooler bawaan.
286
- 5. **Hindari `SELECT *`**: Selalu pilih hanya kolom yang dibutuhkan.
287
- 6. **Batch insert**: Gunakan insert massal, bukan looping satu per satu.
288
-
289
- ### Prinsip Migrasi
290
-
291
- - Jangan gunakan `synchronize: true` di produksi (TypeORM).
292
- - Jangan jalankan `prisma db push` di produksi — selalu gunakan `prisma migrate deploy`.
293
- - Simpan file migrasi di version control.
294
- - Jalankan migrasi sebagai langkah terpisah sebelum deploy versi aplikasi baru.
1
+ ---
2
+ name: database-orm-expert
3
+ description: "Expert guide for database schema design, ORM tools (Prisma 6, Drizzle ORM, TypeORM), migrations, query optimization, and type-safe SQL patterns in TypeScript / Panduan ahli untuk desain skema database, ORM tools (Prisma 6, Drizzle ORM, TypeORM), migrasi, optimasi query, dan pola SQL type-safe di TypeScript."
4
+ author: "Roedy Rustam"
5
+ ---
6
+
7
+ # Database ORM Expert (Prisma 6 + Drizzle ORM Edition)
8
+
9
+ [English](#english) | [Bahasa Indonesia](#bahasa-indonesia)
10
+
11
+ ---
12
+
13
+ <a name="english"></a>
14
+ ## English
15
+
16
+ ### Description
17
+ Expert-level database development covering schema design, ORM selection, migrations, query optimization, and type-safe SQL patterns. Focuses on **Prisma 6** and **Drizzle ORM** as primary modern ORMs, with coverage of TypeORM, raw SQL via `postgres.js`, and connection pooling strategies for production workloads.
18
+
19
+ ### Trigger Conditions
20
+ - Designing or migrating a database schema.
21
+ - Choosing between Prisma, Drizzle ORM, or TypeORM.
22
+ - Writing complex queries with joins, aggregations, or pagination.
23
+ - Optimizing slow queries or N+1 problems.
24
+ - Setting up database migrations in CI/CD pipelines.
25
+ - Implementing Row Level Security (RLS) patterns.
26
+ - Working with PostgreSQL, MySQL, SQLite, or PlanetScale.
27
+
28
+ ---
29
+
30
+ ### ORM Selection Guide
31
+
32
+ | Criteria | Prisma 6 | Drizzle ORM | TypeORM |
33
+ |---|---|---|---|
34
+ | **Type Safety** | Schema-generated types | SQL-like, inferred types | Decorator-based |
35
+ | **Bundle Size** | Heavy (binary client) | Lightweight (<35KB) | Medium |
36
+ | **Query Style** | Fluent ORM API | SQL-first, composable | ActiveRecord / QueryBuilder |
37
+ | **Edge Runtime** | Prisma Accelerate needed | Native edge support | No |
38
+ | **Migrations** | `prisma migrate dev` | `drizzle-kit push/migrate` | `synchronize` (dev only) |
39
+ | **Best For** | Rapid prototyping, teams | Production edge, monorepos | Legacy NestJS projects |
40
+
41
+ **Recommendation**: Use **Drizzle ORM** for edge-compatible apps and performance-critical systems. Use **Prisma 6** for teams that prefer a schema-first DX and rich Studio tooling.
42
+
43
+ ---
44
+
45
+ ### Prisma 6 — Best Practices
46
+
47
+ #### Schema Design
48
+ ```prisma
49
+ // schema.prisma
50
+ generator client {
51
+ provider = "prisma-client-js"
52
+ previewFeatures = ["relationJoins", "nativeDistinct"]
53
+ }
54
+
55
+ datasource db {
56
+ provider = "postgresql"
57
+ url = env("DATABASE_URL")
58
+ directUrl = env("DIRECT_URL") // for Supabase Pooler
59
+ }
60
+
61
+ model User {
62
+ id String @id @default(cuid())
63
+ email String @unique
64
+ name String?
65
+ role Role @default(USER)
66
+ posts Post[]
67
+ createdAt DateTime @default(now())
68
+ updatedAt DateTime @updatedAt
69
+
70
+ @@index([email])
71
+ @@map("users")
72
+ }
73
+
74
+ model Post {
75
+ id String @id @default(cuid())
76
+ title String
77
+ content String?
78
+ published Boolean @default(false)
79
+ authorId String
80
+ author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
81
+ publishedAt DateTime?
82
+
83
+ @@index([authorId, published])
84
+ @@map("posts")
85
+ }
86
+
87
+ enum Role {
88
+ USER
89
+ ADMIN
90
+ SUPER_ADMIN
91
+ }
92
+ ```
93
+
94
+ #### Avoiding N+1 with `include` vs `select`
95
+ ```typescript
96
+ // BAD: triggers N+1 queries
97
+ const users = await prisma.user.findMany();
98
+ for (const user of users) {
99
+ const posts = await prisma.post.findMany({ where: { authorId: user.id } });
100
+ }
101
+
102
+ // GOOD: single query with JOIN (Prisma 5.7+ relationJoins preview)
103
+ const users = await prisma.user.findMany({
104
+ select: {
105
+ id: true,
106
+ name: true,
107
+ email: true,
108
+ _count: { select: { posts: true } },
109
+ posts: {
110
+ where: { published: true },
111
+ select: { id: true, title: true },
112
+ take: 5,
113
+ orderBy: { publishedAt: 'desc' },
114
+ },
115
+ },
116
+ });
117
+ ```
118
+
119
+ #### Optimistic Transactions
120
+ ```typescript
121
+ // Use $transaction for atomic operations
122
+ const [updatedUser, newPost] = await prisma.$transaction([
123
+ prisma.user.update({ where: { id }, data: { name } }),
124
+ prisma.post.create({ data: { title, authorId: id } }),
125
+ ]);
126
+
127
+ // Interactive transaction for complex logic
128
+ const result = await prisma.$transaction(async (tx) => {
129
+ const user = await tx.user.findUniqueOrThrow({ where: { id } });
130
+ if (user.role !== 'ADMIN') throw new Error('Unauthorized');
131
+ return tx.post.updateMany({ where: { authorId: id }, data: { published: true } });
132
+ });
133
+ ```
134
+
135
+ ---
136
+
137
+ ### Drizzle ORM — Best Practices
138
+
139
+ #### Schema Definition (PostgreSQL)
140
+ ```typescript
141
+ // src/db/schema.ts
142
+ import { pgTable, text, boolean, timestamp, pgEnum, index } from 'drizzle-orm/pg-core';
143
+ import { createId } from '@paralleldrive/cuid2';
144
+ import { relations } from 'drizzle-orm';
145
+
146
+ export const roleEnum = pgEnum('role', ['USER', 'ADMIN', 'SUPER_ADMIN']);
147
+
148
+ export const users = pgTable('users', {
149
+ id: text('id').primaryKey().$defaultFn(() => createId()),
150
+ email: text('email').notNull().unique(),
151
+ name: text('name'),
152
+ role: roleEnum('role').default('USER').notNull(),
153
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
154
+ updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull().$onUpdateFn(() => new Date()),
155
+ }, (t) => [
156
+ index('users_email_idx').on(t.email),
157
+ ]);
158
+
159
+ export const posts = pgTable('posts', {
160
+ id: text('id').primaryKey().$defaultFn(() => createId()),
161
+ title: text('title').notNull(),
162
+ content: text('content'),
163
+ published: boolean('published').default(false).notNull(),
164
+ authorId: text('author_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
165
+ publishedAt: timestamp('published_at', { withTimezone: true }),
166
+ }, (t) => [
167
+ index('posts_author_published_idx').on(t.authorId, t.published),
168
+ ]);
169
+
170
+ export const usersRelations = relations(users, ({ many }) => ({
171
+ posts: many(posts),
172
+ }));
173
+
174
+ export const postsRelations = relations(posts, ({ one }) => ({
175
+ author: one(users, { fields: [posts.authorId], references: [users.id] }),
176
+ }));
177
+ ```
178
+
179
+ #### Type-safe Queries with Drizzle
180
+ ```typescript
181
+ // src/db/index.ts
182
+ import { drizzle } from 'drizzle-orm/postgres-js';
183
+ import postgres from 'postgres';
184
+ import * as schema from './schema';
185
+
186
+ const client = postgres(process.env.DATABASE_URL!);
187
+ export const db = drizzle(client, { schema });
188
+
189
+ // Type-safe query with joins
190
+ import { eq, and, desc, count } from 'drizzle-orm';
191
+
192
+ const usersWithPosts = await db.query.users.findMany({
193
+ with: {
194
+ posts: {
195
+ where: eq(posts.published, true),
196
+ orderBy: desc(posts.publishedAt),
197
+ limit: 5,
198
+ },
199
+ },
200
+ extras: {
201
+ postCount: db.$count(posts, eq(posts.authorId, users.id)).as('post_count'),
202
+ },
203
+ });
204
+
205
+ // Paginated query
206
+ async function getPaginatedPosts(page: number, pageSize = 20) {
207
+ const offset = (page - 1) * pageSize;
208
+ const [items, [{ total }]] = await Promise.all([
209
+ db.select().from(posts).where(eq(posts.published, true))
210
+ .orderBy(desc(posts.publishedAt))
211
+ .limit(pageSize)
212
+ .offset(offset),
213
+ db.select({ total: count() }).from(posts).where(eq(posts.published, true)),
214
+ ]);
215
+ return { items, total, pages: Math.ceil(total / pageSize) };
216
+ }
217
+ ```
218
+
219
+ #### Drizzle Migration Workflow
220
+ ```bash
221
+ # drizzle.config.ts defines connection + schema path
222
+ npx drizzle-kit generate # generate migration SQL files
223
+ npx drizzle-kit migrate # apply migrations to database
224
+ npx drizzle-kit push # push schema directly (dev only)
225
+ npx drizzle-kit studio # open Drizzle Studio GUI
226
+ ```
227
+
228
+ ---
229
+
230
+ ### Query Optimization Principles
231
+
232
+ 1. **Always index foreign keys** and columns used in `WHERE`, `ORDER BY`, and `JOIN`.
233
+ 2. **Use `EXPLAIN ANALYZE`** to detect sequential scans and missing indexes.
234
+ 3. **Cursor-based pagination** over offset for large datasets:
235
+ ```typescript
236
+ // Cursor pagination with Drizzle
237
+ const items = await db.select().from(posts)
238
+ .where(cursor ? lt(posts.createdAt, cursor) : undefined)
239
+ .orderBy(desc(posts.createdAt))
240
+ .limit(pageSize);
241
+ ```
242
+ 4. **Connection pooling**: Use PgBouncer or Supabase's built-in pooler. Set `DIRECT_URL` for migrations and `DATABASE_URL` for pooled reads/writes.
243
+ 5. **Avoid `SELECT *`**: Always select only the columns you need.
244
+ 6. **Batch inserts**: Use `db.insert(table).values([...items])` instead of looping.
245
+
246
+ ---
247
+
248
+ ### Migration Best Practices
249
+
250
+ - **Never use `synchronize: true`** in production (TypeORM).
251
+ - **Never run `prisma db push`** in production — always use `prisma migrate deploy`.
252
+ - Store migration files in version control.
253
+ - Run migrations as a separate step before deploying new app versions.
254
+ - Use **advisory locks** or migration tools to prevent concurrent migration runs.
255
+
256
+ ---
257
+
258
+ <a name="bahasa-indonesia"></a>
259
+ ## Bahasa Indonesia
260
+
261
+ ### Deskripsi
262
+ Panduan pengembangan database level ahli mencakup desain skema, pemilihan ORM, migrasi, optimasi query, dan pola SQL type-safe. Berfokus pada **Prisma 6** dan **Drizzle ORM** sebagai ORM modern utama, dengan cakupan TypeORM, SQL mentah via `postgres.js`, dan strategi connection pooling untuk beban kerja produksi.
263
+
264
+ ### Kondisi Pemicu
265
+ - Merancang atau memigrasikan skema database.
266
+ - Memilih antara Prisma, Drizzle ORM, atau TypeORM.
267
+ - Menulis query kompleks dengan join, agregasi, atau paginasi.
268
+ - Mengoptimalkan query lambat atau masalah N+1.
269
+ - Menyiapkan migrasi database dalam pipeline CI/CD.
270
+ - Mengimplementasikan pola Row Level Security (RLS).
271
+ - Bekerja dengan PostgreSQL, MySQL, SQLite, atau PlanetScale.
272
+
273
+ ### Panduan Pemilihan ORM
274
+
275
+ Gunakan tabel di atas (lihat bagian English) sebagai referensi pemilihan ORM. Rekomendasi singkat:
276
+ - **Drizzle ORM**: Untuk aplikasi edge-compatible dan sistem kritis performa.
277
+ - **Prisma 6**: Untuk tim yang lebih menyukai DX schema-first dan tooling Studio yang kaya.
278
+ - **TypeORM**: Hanya untuk proyek lama (legacy) berbasis NestJS.
279
+
280
+ ### Prinsip Utama
281
+
282
+ 1. **Selalu index foreign key** dan kolom yang digunakan di `WHERE`, `ORDER BY`, dan `JOIN`.
283
+ 2. **Gunakan `EXPLAIN ANALYZE`** untuk mendeteksi sequential scan dan index yang hilang.
284
+ 3. **Cursor-based pagination** lebih baik dari offset untuk dataset besar.
285
+ 4. **Connection pooling**: Gunakan PgBouncer atau Supabase pooler bawaan.
286
+ 5. **Hindari `SELECT *`**: Selalu pilih hanya kolom yang dibutuhkan.
287
+ 6. **Batch insert**: Gunakan insert massal, bukan looping satu per satu.
288
+
289
+ ### Prinsip Migrasi
290
+
291
+ - Jangan gunakan `synchronize: true` di produksi (TypeORM).
292
+ - Jangan jalankan `prisma db push` di produksi — selalu gunakan `prisma migrate deploy`.
293
+ - Simpan file migrasi di version control.
294
+ - Jalankan migrasi sebagai langkah terpisah sebelum deploy versi aplikasi baru.