@hivehub/rulebook 1.2.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.
- package/LICENSE +191 -0
- package/README.md +539 -0
- package/dist/agents/claude-code.d.ts +69 -0
- package/dist/agents/claude-code.d.ts.map +1 -0
- package/dist/agents/claude-code.js +180 -0
- package/dist/agents/claude-code.js.map +1 -0
- package/dist/agents/cursor-agent.d.ts +184 -0
- package/dist/agents/cursor-agent.d.ts.map +1 -0
- package/dist/agents/cursor-agent.js +299 -0
- package/dist/agents/cursor-agent.js.map +1 -0
- package/dist/agents/gemini-cli.d.ts +69 -0
- package/dist/agents/gemini-cli.d.ts.map +1 -0
- package/dist/agents/gemini-cli.js +180 -0
- package/dist/agents/gemini-cli.js.map +1 -0
- package/dist/cli/commands.d.ts +57 -0
- package/dist/cli/commands.d.ts.map +1 -0
- package/dist/cli/commands.js +1370 -0
- package/dist/cli/commands.js.map +1 -0
- package/dist/cli/docs-prompts.d.ts +3 -0
- package/dist/cli/docs-prompts.d.ts.map +1 -0
- package/dist/cli/docs-prompts.js +45 -0
- package/dist/cli/docs-prompts.js.map +1 -0
- package/dist/cli/prompts.d.ts +6 -0
- package/dist/cli/prompts.d.ts.map +1 -0
- package/dist/cli/prompts.js +376 -0
- package/dist/cli/prompts.js.map +1 -0
- package/dist/core/agent-manager.d.ts +89 -0
- package/dist/core/agent-manager.d.ts.map +1 -0
- package/dist/core/agent-manager.js +546 -0
- package/dist/core/agent-manager.js.map +1 -0
- package/dist/core/auto-fixer.d.ts +14 -0
- package/dist/core/auto-fixer.d.ts.map +1 -0
- package/dist/core/auto-fixer.js +207 -0
- package/dist/core/auto-fixer.js.map +1 -0
- package/dist/core/changelog-generator.d.ts +44 -0
- package/dist/core/changelog-generator.d.ts.map +1 -0
- package/dist/core/changelog-generator.js +222 -0
- package/dist/core/changelog-generator.js.map +1 -0
- package/dist/core/cli-bridge.d.ts +113 -0
- package/dist/core/cli-bridge.d.ts.map +1 -0
- package/dist/core/cli-bridge.js +1094 -0
- package/dist/core/cli-bridge.js.map +1 -0
- package/dist/core/config-manager.d.ts +65 -0
- package/dist/core/config-manager.d.ts.map +1 -0
- package/dist/core/config-manager.js +266 -0
- package/dist/core/config-manager.js.map +1 -0
- package/dist/core/coverage-checker.d.ts +14 -0
- package/dist/core/coverage-checker.d.ts.map +1 -0
- package/dist/core/coverage-checker.js +176 -0
- package/dist/core/coverage-checker.js.map +1 -0
- package/dist/core/custom-templates.d.ts +27 -0
- package/dist/core/custom-templates.d.ts.map +1 -0
- package/dist/core/custom-templates.js +122 -0
- package/dist/core/custom-templates.js.map +1 -0
- package/dist/core/dependency-checker.d.ts +21 -0
- package/dist/core/dependency-checker.d.ts.map +1 -0
- package/dist/core/dependency-checker.js +247 -0
- package/dist/core/dependency-checker.js.map +1 -0
- package/dist/core/detector.d.ts +3 -0
- package/dist/core/detector.d.ts.map +1 -0
- package/dist/core/detector.js +1443 -0
- package/dist/core/detector.js.map +1 -0
- package/dist/core/docs-generator.d.ts +9 -0
- package/dist/core/docs-generator.d.ts.map +1 -0
- package/dist/core/docs-generator.js +531 -0
- package/dist/core/docs-generator.js.map +1 -0
- package/dist/core/generator.d.ts +16 -0
- package/dist/core/generator.d.ts.map +1 -0
- package/dist/core/generator.js +561 -0
- package/dist/core/generator.js.map +1 -0
- package/dist/core/gitignore-generator.d.ts +13 -0
- package/dist/core/gitignore-generator.d.ts.map +1 -0
- package/dist/core/gitignore-generator.js +307 -0
- package/dist/core/gitignore-generator.js.map +1 -0
- package/dist/core/health-scorer.d.ts +22 -0
- package/dist/core/health-scorer.d.ts.map +1 -0
- package/dist/core/health-scorer.js +395 -0
- package/dist/core/health-scorer.js.map +1 -0
- package/dist/core/logger.d.ts +116 -0
- package/dist/core/logger.d.ts.map +1 -0
- package/dist/core/logger.js +289 -0
- package/dist/core/logger.js.map +1 -0
- package/dist/core/merger.d.ts +6 -0
- package/dist/core/merger.d.ts.map +1 -0
- package/dist/core/merger.js +131 -0
- package/dist/core/merger.js.map +1 -0
- package/dist/core/migrator.d.ts +19 -0
- package/dist/core/migrator.d.ts.map +1 -0
- package/dist/core/migrator.js +102 -0
- package/dist/core/migrator.js.map +1 -0
- package/dist/core/minimal-scaffolder.d.ts +8 -0
- package/dist/core/minimal-scaffolder.d.ts.map +1 -0
- package/dist/core/minimal-scaffolder.js +51 -0
- package/dist/core/minimal-scaffolder.js.map +1 -0
- package/dist/core/modern-console-new.d.ts +81 -0
- package/dist/core/modern-console-new.d.ts.map +1 -0
- package/dist/core/modern-console-new.js +340 -0
- package/dist/core/modern-console-new.js.map +1 -0
- package/dist/core/modern-console.d.ts +99 -0
- package/dist/core/modern-console.d.ts.map +1 -0
- package/dist/core/modern-console.js +568 -0
- package/dist/core/modern-console.js.map +1 -0
- package/dist/core/openspec-manager.d.ts +133 -0
- package/dist/core/openspec-manager.d.ts.map +1 -0
- package/dist/core/openspec-manager.js +605 -0
- package/dist/core/openspec-manager.js.map +1 -0
- package/dist/core/openspec-migrator.d.ts +27 -0
- package/dist/core/openspec-migrator.d.ts.map +1 -0
- package/dist/core/openspec-migrator.js +255 -0
- package/dist/core/openspec-migrator.js.map +1 -0
- package/dist/core/task-manager.d.ts +65 -0
- package/dist/core/task-manager.d.ts.map +1 -0
- package/dist/core/task-manager.js +318 -0
- package/dist/core/task-manager.js.map +1 -0
- package/dist/core/test-task-manager.d.ts +49 -0
- package/dist/core/test-task-manager.d.ts.map +1 -0
- package/dist/core/test-task-manager.js +121 -0
- package/dist/core/test-task-manager.js.map +1 -0
- package/dist/core/validator.d.ts +21 -0
- package/dist/core/validator.d.ts.map +1 -0
- package/dist/core/validator.js +177 -0
- package/dist/core/validator.js.map +1 -0
- package/dist/core/version-bumper.d.ts +19 -0
- package/dist/core/version-bumper.d.ts.map +1 -0
- package/dist/core/version-bumper.js +180 -0
- package/dist/core/version-bumper.js.map +1 -0
- package/dist/core/watcher.d.ts +9 -0
- package/dist/core/watcher.d.ts.map +1 -0
- package/dist/core/watcher.js +22 -0
- package/dist/core/watcher.js.map +1 -0
- package/dist/core/workflow-generator.d.ts +10 -0
- package/dist/core/workflow-generator.d.ts.map +1 -0
- package/dist/core/workflow-generator.js +279 -0
- package/dist/core/workflow-generator.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +159 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/handlers/archive-task.d.ts +17 -0
- package/dist/mcp/handlers/archive-task.d.ts.map +1 -0
- package/dist/mcp/handlers/archive-task.js +36 -0
- package/dist/mcp/handlers/archive-task.js.map +1 -0
- package/dist/mcp/handlers/create-task.d.ts +17 -0
- package/dist/mcp/handlers/create-task.d.ts.map +1 -0
- package/dist/mcp/handlers/create-task.js +56 -0
- package/dist/mcp/handlers/create-task.js.map +1 -0
- package/dist/mcp/handlers/list-tasks.d.ts +22 -0
- package/dist/mcp/handlers/list-tasks.d.ts.map +1 -0
- package/dist/mcp/handlers/list-tasks.js +42 -0
- package/dist/mcp/handlers/list-tasks.js.map +1 -0
- package/dist/mcp/handlers/show-task.d.ts +25 -0
- package/dist/mcp/handlers/show-task.d.ts.map +1 -0
- package/dist/mcp/handlers/show-task.js +43 -0
- package/dist/mcp/handlers/show-task.js.map +1 -0
- package/dist/mcp/handlers/update-task.d.ts +17 -0
- package/dist/mcp/handlers/update-task.d.ts.map +1 -0
- package/dist/mcp/handlers/update-task.js +35 -0
- package/dist/mcp/handlers/update-task.js.map +1 -0
- package/dist/mcp/handlers/validate-task.d.ts +15 -0
- package/dist/mcp/handlers/validate-task.d.ts.map +1 -0
- package/dist/mcp/handlers/validate-task.js +27 -0
- package/dist/mcp/handlers/validate-task.js.map +1 -0
- package/dist/mcp/rulebook-config.d.ts +22 -0
- package/dist/mcp/rulebook-config.d.ts.map +1 -0
- package/dist/mcp/rulebook-config.js +65 -0
- package/dist/mcp/rulebook-config.js.map +1 -0
- package/dist/mcp/rulebook-server.d.ts +4 -0
- package/dist/mcp/rulebook-server.d.ts.map +1 -0
- package/dist/mcp/rulebook-server.js +246 -0
- package/dist/mcp/rulebook-server.js.map +1 -0
- package/dist/types.d.ts +190 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/file-system.d.ts +9 -0
- package/dist/utils/file-system.d.ts.map +1 -0
- package/dist/utils/file-system.js +51 -0
- package/dist/utils/file-system.js.map +1 -0
- package/dist/utils/git-hooks.d.ts +8 -0
- package/dist/utils/git-hooks.d.ts.map +1 -0
- package/dist/utils/git-hooks.js +440 -0
- package/dist/utils/git-hooks.js.map +1 -0
- package/dist/utils/rulesignore.d.ts +9 -0
- package/dist/utils/rulesignore.d.ts.map +1 -0
- package/dist/utils/rulesignore.js +42 -0
- package/dist/utils/rulesignore.js.map +1 -0
- package/package.json +106 -0
- package/templates/cli/AIDER.md +49 -0
- package/templates/cli/AMAZON_Q.md +25 -0
- package/templates/cli/AUGGIE.md +32 -0
- package/templates/cli/CLAUDE.md +32 -0
- package/templates/cli/CLAUDE_CODE.md +35 -0
- package/templates/cli/CLINE.md +32 -0
- package/templates/cli/CODEBUDDY.md +20 -0
- package/templates/cli/CODEIUM.md +20 -0
- package/templates/cli/CODEX.md +21 -0
- package/templates/cli/CONTINUE.md +34 -0
- package/templates/cli/CURSOR_CLI.md +28 -0
- package/templates/cli/FACTORY.md +18 -0
- package/templates/cli/GEMINI.md +35 -0
- package/templates/cli/KILOCODE.md +18 -0
- package/templates/cli/OPENCODE.md +18 -0
- package/templates/cli/_GENERIC_TEMPLATE.md +29 -0
- package/templates/commands/rulebook-task-apply.md +67 -0
- package/templates/commands/rulebook-task-archive.md +70 -0
- package/templates/commands/rulebook-task-create.md +93 -0
- package/templates/commands/rulebook-task-list.md +42 -0
- package/templates/commands/rulebook-task-show.md +52 -0
- package/templates/commands/rulebook-task-validate.md +53 -0
- package/templates/core/AGENT_AUTOMATION.md +184 -0
- package/templates/core/DAG.md +304 -0
- package/templates/core/DOCUMENTATION_RULES.md +37 -0
- package/templates/core/QUALITY_ENFORCEMENT.md +68 -0
- package/templates/core/RULEBOOK.md +1874 -0
- package/templates/frameworks/ANGULAR.md +36 -0
- package/templates/frameworks/DJANGO.md +83 -0
- package/templates/frameworks/ELECTRON.md +147 -0
- package/templates/frameworks/FLASK.md +38 -0
- package/templates/frameworks/FLUTTER.md +55 -0
- package/templates/frameworks/JQUERY.md +32 -0
- package/templates/frameworks/LARAVEL.md +38 -0
- package/templates/frameworks/NESTJS.md +43 -0
- package/templates/frameworks/NEXTJS.md +127 -0
- package/templates/frameworks/NUXT.md +40 -0
- package/templates/frameworks/RAILS.md +66 -0
- package/templates/frameworks/REACT.md +38 -0
- package/templates/frameworks/REACT_NATIVE.md +47 -0
- package/templates/frameworks/SPRING.md +39 -0
- package/templates/frameworks/SYMFONY.md +36 -0
- package/templates/frameworks/VUE.md +36 -0
- package/templates/frameworks/ZEND.md +35 -0
- package/templates/git/CI_CD_PATTERNS.md +661 -0
- package/templates/git/GITHUB_ACTIONS.md +728 -0
- package/templates/git/GITLAB_CI.md +730 -0
- package/templates/git/GIT_WORKFLOW.md +1157 -0
- package/templates/git/SECRETS_MANAGEMENT.md +585 -0
- package/templates/hooks/COMMIT_MSG.md +530 -0
- package/templates/hooks/POST_CHECKOUT.md +546 -0
- package/templates/hooks/PREPARE_COMMIT_MSG.md +619 -0
- package/templates/hooks/PRE_COMMIT.md +414 -0
- package/templates/hooks/PRE_PUSH.md +601 -0
- package/templates/hooks/csharp-pre-commit.sh +23 -0
- package/templates/hooks/csharp-pre-push.sh +23 -0
- package/templates/hooks/dart-pre-commit.sh +30 -0
- package/templates/hooks/dart-pre-push.sh +25 -0
- package/templates/hooks/elixir-pre-commit.sh +32 -0
- package/templates/hooks/elixir-pre-push.sh +31 -0
- package/templates/hooks/erlang-pre-commit.sh +30 -0
- package/templates/hooks/erlang-pre-push.sh +37 -0
- package/templates/hooks/go-pre-commit.sh +40 -0
- package/templates/hooks/go-pre-push.sh +31 -0
- package/templates/hooks/haskell-pre-commit.sh +41 -0
- package/templates/hooks/haskell-pre-push.sh +37 -0
- package/templates/hooks/java-pre-commit.sh +34 -0
- package/templates/hooks/java-pre-push.sh +24 -0
- package/templates/hooks/kotlin-pre-commit.sh +32 -0
- package/templates/hooks/kotlin-pre-push.sh +16 -0
- package/templates/hooks/php-pre-commit.sh +36 -0
- package/templates/hooks/php-pre-push.sh +26 -0
- package/templates/hooks/python-pre-commit.sh +51 -0
- package/templates/hooks/python-pre-push.sh +25 -0
- package/templates/hooks/ruby-pre-commit.sh +33 -0
- package/templates/hooks/ruby-pre-push.sh +32 -0
- package/templates/hooks/rust-pre-commit.sh +30 -0
- package/templates/hooks/rust-pre-push.sh +30 -0
- package/templates/hooks/scala-pre-commit.sh +32 -0
- package/templates/hooks/scala-pre-push.sh +24 -0
- package/templates/hooks/swift-pre-commit.sh +25 -0
- package/templates/hooks/swift-pre-push.sh +23 -0
- package/templates/hooks/typescript-pre-commit.sh +37 -0
- package/templates/hooks/typescript-pre-push.sh +36 -0
- package/templates/ides/COPILOT.md +37 -0
- package/templates/ides/CURSOR.md +43 -0
- package/templates/ides/JETBRAINS_AI.md +35 -0
- package/templates/ides/REPLIT.md +36 -0
- package/templates/ides/TABNINE.md +29 -0
- package/templates/ides/VSCODE.md +40 -0
- package/templates/ides/WINDSURF.md +36 -0
- package/templates/ides/ZED.md +32 -0
- package/templates/languages/ADA.md +58 -0
- package/templates/languages/C.md +333 -0
- package/templates/languages/CPP.md +743 -0
- package/templates/languages/CSHARP.md +417 -0
- package/templates/languages/DART.md +332 -0
- package/templates/languages/ELIXIR.md +454 -0
- package/templates/languages/ERLANG.md +361 -0
- package/templates/languages/GO.md +645 -0
- package/templates/languages/HASKELL.md +177 -0
- package/templates/languages/JAVA.md +607 -0
- package/templates/languages/JAVASCRIPT.md +631 -0
- package/templates/languages/JULIA.md +97 -0
- package/templates/languages/KOTLIN.md +511 -0
- package/templates/languages/LISP.md +100 -0
- package/templates/languages/LUA.md +74 -0
- package/templates/languages/OBJECTIVEC.md +90 -0
- package/templates/languages/PHP.md +416 -0
- package/templates/languages/PYTHON.md +682 -0
- package/templates/languages/R.md +350 -0
- package/templates/languages/RUBY.md +421 -0
- package/templates/languages/RUST.md +477 -0
- package/templates/languages/SAS.md +73 -0
- package/templates/languages/SCALA.md +348 -0
- package/templates/languages/SOLIDITY.md +580 -0
- package/templates/languages/SQL.md +137 -0
- package/templates/languages/SWIFT.md +466 -0
- package/templates/languages/TYPESCRIPT.md +591 -0
- package/templates/languages/ZIG.md +265 -0
- package/templates/modules/ATLASSIAN.md +255 -0
- package/templates/modules/CONTEXT7.md +54 -0
- package/templates/modules/FIGMA.md +267 -0
- package/templates/modules/GITHUB_MCP.md +64 -0
- package/templates/modules/GRAFANA.md +328 -0
- package/templates/modules/NOTION.md +247 -0
- package/templates/modules/PLAYWRIGHT.md +90 -0
- package/templates/modules/RULEBOOK_MCP.md +156 -0
- package/templates/modules/SERENA.md +337 -0
- package/templates/modules/SUPABASE.md +223 -0
- package/templates/modules/SYNAP.md +69 -0
- package/templates/modules/VECTORIZER.md +63 -0
- package/templates/services/AZURE_BLOB.md +184 -0
- package/templates/services/CASSANDRA.md +239 -0
- package/templates/services/DYNAMODB.md +308 -0
- package/templates/services/ELASTICSEARCH.md +347 -0
- package/templates/services/GCS.md +178 -0
- package/templates/services/INFLUXDB.md +265 -0
- package/templates/services/KAFKA.md +341 -0
- package/templates/services/MARIADB.md +183 -0
- package/templates/services/MEMCACHED.md +242 -0
- package/templates/services/MINIO.md +201 -0
- package/templates/services/MONGODB.md +268 -0
- package/templates/services/MYSQL.md +358 -0
- package/templates/services/NEO4J.md +247 -0
- package/templates/services/ORACLE.md +290 -0
- package/templates/services/POSTGRESQL.md +326 -0
- package/templates/services/RABBITMQ.md +286 -0
- package/templates/services/REDIS.md +292 -0
- package/templates/services/S3.md +298 -0
- package/templates/services/SQLITE.md +294 -0
- package/templates/services/SQLSERVER.md +294 -0
- package/templates/workflows/codespell.yml +31 -0
- package/templates/workflows/cpp-lint.yml +47 -0
- package/templates/workflows/cpp-publish.yml +119 -0
- package/templates/workflows/cpp-test.yml +77 -0
- package/templates/workflows/dotnet-lint.yml +29 -0
- package/templates/workflows/dotnet-publish.yml +40 -0
- package/templates/workflows/dotnet-test.yml +41 -0
- package/templates/workflows/elixir-lint.yml +45 -0
- package/templates/workflows/elixir-publish.yml +49 -0
- package/templates/workflows/elixir-test.yml +54 -0
- package/templates/workflows/erlang-lint.yml +47 -0
- package/templates/workflows/erlang-test.yml +62 -0
- package/templates/workflows/go-lint.yml +39 -0
- package/templates/workflows/go-publish.yml +95 -0
- package/templates/workflows/go-test.yml +59 -0
- package/templates/workflows/java-lint.yml +60 -0
- package/templates/workflows/java-publish.yml +120 -0
- package/templates/workflows/java-test.yml +85 -0
- package/templates/workflows/kotlin-lint.yml +34 -0
- package/templates/workflows/kotlin-publish.yml +56 -0
- package/templates/workflows/kotlin-test.yml +48 -0
- package/templates/workflows/php-lint.yml +39 -0
- package/templates/workflows/php-publish.yml +50 -0
- package/templates/workflows/php-test.yml +54 -0
- package/templates/workflows/python-lint.yml +47 -0
- package/templates/workflows/python-publish.yml +91 -0
- package/templates/workflows/python-test.yml +59 -0
- package/templates/workflows/rust-lint.yml +54 -0
- package/templates/workflows/rust-publish.yml +66 -0
- package/templates/workflows/rust-test.yml +75 -0
- package/templates/workflows/solidity-lint.yml +41 -0
- package/templates/workflows/solidity-test.yml +47 -0
- package/templates/workflows/swift-lint.yml +32 -0
- package/templates/workflows/swift-publish.yml +58 -0
- package/templates/workflows/swift-test.yml +44 -0
- package/templates/workflows/typescript-lint.yml +61 -0
- package/templates/workflows/typescript-publish.yml +60 -0
- package/templates/workflows/typescript-test.yml +73 -0
- package/templates/workflows/zig-lint.yml +27 -0
- package/templates/workflows/zig-test.yml +40 -0
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
<!-- MONGODB:START -->
|
|
2
|
+
# MongoDB Database Instructions
|
|
3
|
+
|
|
4
|
+
**CRITICAL**: Use MongoDB for document-based NoSQL storage with flexible schemas, horizontal scaling, and rich querying.
|
|
5
|
+
|
|
6
|
+
## Core Features
|
|
7
|
+
|
|
8
|
+
### Connection
|
|
9
|
+
```typescript
|
|
10
|
+
// Using mongodb driver
|
|
11
|
+
import { MongoClient } from 'mongodb'
|
|
12
|
+
|
|
13
|
+
const client = new MongoClient(process.env.MONGODB_URI || 'mongodb://localhost:27017', {
|
|
14
|
+
maxPoolSize: 10,
|
|
15
|
+
minPoolSize: 2,
|
|
16
|
+
maxIdleTimeMS: 30000,
|
|
17
|
+
serverSelectionTimeoutMS: 5000,
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
await client.connect()
|
|
21
|
+
const db = client.db(process.env.DB_NAME || 'myapp')
|
|
22
|
+
|
|
23
|
+
// Using Mongoose
|
|
24
|
+
import mongoose from 'mongoose'
|
|
25
|
+
|
|
26
|
+
await mongoose.connect(process.env.MONGODB_URI, {
|
|
27
|
+
maxPoolSize: 10,
|
|
28
|
+
minPoolSize: 2,
|
|
29
|
+
bufferCommands: false,
|
|
30
|
+
bufferMaxEntries: 0,
|
|
31
|
+
})
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Basic Operations
|
|
35
|
+
```typescript
|
|
36
|
+
// Insert
|
|
37
|
+
const result = await db.collection('users').insertOne({
|
|
38
|
+
name: 'John Doe',
|
|
39
|
+
email: 'john@example.com',
|
|
40
|
+
createdAt: new Date(),
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
// Insert many
|
|
44
|
+
await db.collection('users').insertMany([
|
|
45
|
+
{ name: 'User 1', email: 'user1@example.com' },
|
|
46
|
+
{ name: 'User 2', email: 'user2@example.com' },
|
|
47
|
+
])
|
|
48
|
+
|
|
49
|
+
// Find
|
|
50
|
+
const user = await db.collection('users').findOne({ email: 'john@example.com' })
|
|
51
|
+
const users = await db.collection('users').find({ active: true }).toArray()
|
|
52
|
+
|
|
53
|
+
// Update
|
|
54
|
+
await db.collection('users').updateOne(
|
|
55
|
+
{ email: 'john@example.com' },
|
|
56
|
+
{ $set: { name: 'Jane Doe', updatedAt: new Date() } }
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
// Update many
|
|
60
|
+
await db.collection('users').updateMany(
|
|
61
|
+
{ active: false },
|
|
62
|
+
{ $set: { status: 'inactive' } }
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
// Delete
|
|
66
|
+
await db.collection('users').deleteOne({ email: 'john@example.com' })
|
|
67
|
+
await db.collection('users').deleteMany({ active: false })
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Advanced Queries
|
|
71
|
+
```typescript
|
|
72
|
+
// Aggregation pipeline
|
|
73
|
+
const result = await db.collection('orders').aggregate([
|
|
74
|
+
{ $match: { status: 'completed' } },
|
|
75
|
+
{ $group: { _id: '$userId', total: { $sum: '$amount' } } },
|
|
76
|
+
{ $sort: { total: -1 } },
|
|
77
|
+
{ $limit: 10 },
|
|
78
|
+
]).toArray()
|
|
79
|
+
|
|
80
|
+
// Text search
|
|
81
|
+
await db.collection('articles').createIndex({ title: 'text', content: 'text' })
|
|
82
|
+
const results = await db.collection('articles').find({
|
|
83
|
+
$text: { $search: 'search term' },
|
|
84
|
+
}).toArray()
|
|
85
|
+
|
|
86
|
+
// Geospatial queries
|
|
87
|
+
await db.collection('locations').createIndex({ location: '2dsphere' })
|
|
88
|
+
const nearby = await db.collection('locations').find({
|
|
89
|
+
location: {
|
|
90
|
+
$near: {
|
|
91
|
+
$geometry: { type: 'Point', coordinates: [longitude, latitude] },
|
|
92
|
+
$maxDistance: 1000, // meters
|
|
93
|
+
},
|
|
94
|
+
},
|
|
95
|
+
}).toArray()
|
|
96
|
+
|
|
97
|
+
// Array operations
|
|
98
|
+
await db.collection('users').find({
|
|
99
|
+
tags: { $in: ['javascript', 'typescript'] },
|
|
100
|
+
})
|
|
101
|
+
await db.collection('users').updateOne(
|
|
102
|
+
{ email: 'john@example.com' },
|
|
103
|
+
{ $push: { tags: 'new-tag' } }
|
|
104
|
+
)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Common Patterns
|
|
108
|
+
|
|
109
|
+
### Mongoose Schemas
|
|
110
|
+
```typescript
|
|
111
|
+
import mongoose, { Schema } from 'mongoose'
|
|
112
|
+
|
|
113
|
+
const userSchema = new Schema({
|
|
114
|
+
name: { type: String, required: true },
|
|
115
|
+
email: { type: String, required: true, unique: true, index: true },
|
|
116
|
+
age: { type: Number, min: 0, max: 120 },
|
|
117
|
+
tags: [String],
|
|
118
|
+
metadata: { type: Schema.Types.Mixed },
|
|
119
|
+
createdAt: { type: Date, default: Date.now },
|
|
120
|
+
updatedAt: { type: Date, default: Date.now },
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
userSchema.pre('save', function(next) {
|
|
124
|
+
this.updatedAt = new Date()
|
|
125
|
+
next()
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
const User = mongoose.model('User', userSchema)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### Transactions
|
|
132
|
+
```typescript
|
|
133
|
+
const session = client.startSession()
|
|
134
|
+
try {
|
|
135
|
+
await session.withTransaction(async () => {
|
|
136
|
+
await db.collection('accounts').updateOne(
|
|
137
|
+
{ userId: userId },
|
|
138
|
+
{ $inc: { balance: -100 } },
|
|
139
|
+
{ session }
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
await db.collection('transactions').insertOne(
|
|
143
|
+
{ userId, amount: -100, type: 'debit' },
|
|
144
|
+
{ session }
|
|
145
|
+
)
|
|
146
|
+
})
|
|
147
|
+
} finally {
|
|
148
|
+
await session.endSession()
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### Indexing
|
|
153
|
+
```typescript
|
|
154
|
+
// Create indexes
|
|
155
|
+
await db.collection('users').createIndex({ email: 1 }, { unique: true })
|
|
156
|
+
await db.collection('users').createIndex({ name: 1, email: 1 })
|
|
157
|
+
await db.collection('users').createIndex({ createdAt: -1 })
|
|
158
|
+
|
|
159
|
+
// Compound index
|
|
160
|
+
await db.collection('posts').createIndex({ authorId: 1, createdAt: -1 })
|
|
161
|
+
|
|
162
|
+
// TTL index (auto-delete after time)
|
|
163
|
+
await db.collection('sessions').createIndex(
|
|
164
|
+
{ createdAt: 1 },
|
|
165
|
+
{ expireAfterSeconds: 3600 }
|
|
166
|
+
)
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Best Practices
|
|
170
|
+
|
|
171
|
+
✅ **DO:**
|
|
172
|
+
- Use connection pooling (10-20 connections)
|
|
173
|
+
- Create indexes on frequently queried fields
|
|
174
|
+
- Use transactions for multi-document operations
|
|
175
|
+
- Use $set for updates (don't replace entire documents)
|
|
176
|
+
- Use projection to limit returned fields
|
|
177
|
+
- Use aggregation pipeline for complex queries
|
|
178
|
+
- Enable replica sets for production
|
|
179
|
+
- Use sharding for large datasets
|
|
180
|
+
- Monitor slow queries
|
|
181
|
+
- Use appropriate data types (ObjectId, Date, etc.)
|
|
182
|
+
|
|
183
|
+
❌ **DON'T:**
|
|
184
|
+
- Store large binary data (use GridFS)
|
|
185
|
+
- Create too many indexes (affects write performance)
|
|
186
|
+
- Use $where (slow, use aggregation instead)
|
|
187
|
+
- Skip error handling
|
|
188
|
+
- Hardcode connection strings
|
|
189
|
+
- Ignore connection pool limits
|
|
190
|
+
- Use nested arrays deeply (limit to 2-3 levels)
|
|
191
|
+
- Skip validation
|
|
192
|
+
- Ignore query performance
|
|
193
|
+
- Store sensitive data without encryption
|
|
194
|
+
|
|
195
|
+
## Configuration
|
|
196
|
+
|
|
197
|
+
### Environment Variables
|
|
198
|
+
```bash
|
|
199
|
+
MONGODB_URI=mongodb://localhost:27017/myapp
|
|
200
|
+
MONGODB_URI=mongodb://user:password@host:27017/database?authSource=admin
|
|
201
|
+
MONGODB_URI=mongodb+srv://user:password@cluster.mongodb.net/database
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
### Docker Compose
|
|
205
|
+
```yaml
|
|
206
|
+
services:
|
|
207
|
+
mongodb:
|
|
208
|
+
image: mongo:7
|
|
209
|
+
ports:
|
|
210
|
+
- "27017:27017"
|
|
211
|
+
environment:
|
|
212
|
+
MONGO_INITDB_ROOT_USERNAME: admin
|
|
213
|
+
MONGO_INITDB_ROOT_PASSWORD: securepassword
|
|
214
|
+
MONGO_INITDB_DATABASE: myapp
|
|
215
|
+
volumes:
|
|
216
|
+
- mongodb_data:/data/db
|
|
217
|
+
healthcheck:
|
|
218
|
+
test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
|
|
219
|
+
interval: 10s
|
|
220
|
+
timeout: 5s
|
|
221
|
+
retries: 5
|
|
222
|
+
|
|
223
|
+
volumes:
|
|
224
|
+
mongodb_data:
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
## Integration with Development
|
|
228
|
+
|
|
229
|
+
### Testing
|
|
230
|
+
```typescript
|
|
231
|
+
// Use test database
|
|
232
|
+
const testClient = new MongoClient('mongodb://localhost:27017/test_db')
|
|
233
|
+
await testClient.connect()
|
|
234
|
+
const testDb = testClient.db('test_db')
|
|
235
|
+
|
|
236
|
+
// Clean up after tests
|
|
237
|
+
afterEach(async () => {
|
|
238
|
+
await testDb.collection('users').deleteMany({})
|
|
239
|
+
await testDb.collection('posts').deleteMany({})
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
// Use transactions for test isolation
|
|
243
|
+
beforeEach(async () => {
|
|
244
|
+
const session = testClient.startSession()
|
|
245
|
+
session.startTransaction()
|
|
246
|
+
// Store session for rollback
|
|
247
|
+
})
|
|
248
|
+
|
|
249
|
+
afterEach(async () => {
|
|
250
|
+
await session.abortTransaction()
|
|
251
|
+
await session.endSession()
|
|
252
|
+
})
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
### Health Checks
|
|
256
|
+
```typescript
|
|
257
|
+
async function checkDatabaseHealth(): Promise<boolean> {
|
|
258
|
+
try {
|
|
259
|
+
await client.db('admin').command({ ping: 1 })
|
|
260
|
+
return true
|
|
261
|
+
} catch {
|
|
262
|
+
return false
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
<!-- MONGODB:END -->
|
|
268
|
+
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
<!-- MYSQL:START -->
|
|
2
|
+
# MySQL Database Instructions
|
|
3
|
+
|
|
4
|
+
**CRITICAL**: Use MySQL for relational data storage with high performance, replication, and wide ecosystem support.
|
|
5
|
+
|
|
6
|
+
## Core Features
|
|
7
|
+
|
|
8
|
+
### Connection
|
|
9
|
+
```typescript
|
|
10
|
+
// Using mysql2 (Node.js)
|
|
11
|
+
import mysql from 'mysql2/promise'
|
|
12
|
+
|
|
13
|
+
const pool = mysql.createPool({
|
|
14
|
+
host: process.env.DB_HOST,
|
|
15
|
+
port: parseInt(process.env.DB_PORT || '3306'),
|
|
16
|
+
database: process.env.DB_NAME,
|
|
17
|
+
user: process.env.DB_USER,
|
|
18
|
+
password: process.env.DB_PASSWORD,
|
|
19
|
+
waitForConnections: true,
|
|
20
|
+
connectionLimit: 10,
|
|
21
|
+
queueLimit: 0,
|
|
22
|
+
enableKeepAlive: true,
|
|
23
|
+
keepAliveInitialDelay: 0,
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
// Using Prisma
|
|
27
|
+
import { PrismaClient } from '@prisma/client'
|
|
28
|
+
const prisma = new PrismaClient()
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### Basic Queries
|
|
32
|
+
```typescript
|
|
33
|
+
// SELECT
|
|
34
|
+
const [rows] = await pool.execute('SELECT * FROM users WHERE id = ?', [userId])
|
|
35
|
+
const users = rows as User[]
|
|
36
|
+
|
|
37
|
+
// INSERT
|
|
38
|
+
const [result] = await pool.execute(
|
|
39
|
+
'INSERT INTO users (name, email) VALUES (?, ?)',
|
|
40
|
+
['John Doe', 'john@example.com']
|
|
41
|
+
)
|
|
42
|
+
const insertId = (result as any).insertId
|
|
43
|
+
|
|
44
|
+
// UPDATE
|
|
45
|
+
const [result] = await pool.execute(
|
|
46
|
+
'UPDATE users SET name = ? WHERE id = ?',
|
|
47
|
+
['Jane Doe', userId]
|
|
48
|
+
)
|
|
49
|
+
const affectedRows = (result as any).affectedRows
|
|
50
|
+
|
|
51
|
+
// DELETE
|
|
52
|
+
const [result] = await pool.execute('DELETE FROM users WHERE id = ?', [userId])
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Transactions
|
|
56
|
+
```typescript
|
|
57
|
+
const connection = await pool.getConnection()
|
|
58
|
+
try {
|
|
59
|
+
await connection.beginTransaction()
|
|
60
|
+
|
|
61
|
+
await connection.execute('INSERT INTO accounts (user_id, balance) VALUES (?, ?)', [userId, 1000])
|
|
62
|
+
await connection.execute('INSERT INTO transactions (account_id, amount) VALUES (?, ?)', [accountId, 1000])
|
|
63
|
+
|
|
64
|
+
await connection.commit()
|
|
65
|
+
} catch (error) {
|
|
66
|
+
await connection.rollback()
|
|
67
|
+
throw error
|
|
68
|
+
} finally {
|
|
69
|
+
connection.release()
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Advanced Features
|
|
74
|
+
```typescript
|
|
75
|
+
// JSON queries (MySQL 5.7+)
|
|
76
|
+
const [rows] = await pool.execute(
|
|
77
|
+
"SELECT * FROM products WHERE JSON_EXTRACT(metadata, '$.category') = ?",
|
|
78
|
+
['electronics']
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
// Full-text search
|
|
82
|
+
const [rows] = await pool.execute(
|
|
83
|
+
"SELECT * FROM articles WHERE MATCH(title, content) AGAINST(? IN NATURAL LANGUAGE MODE)",
|
|
84
|
+
['search term']
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
// Window functions (MySQL 8.0+)
|
|
88
|
+
const [rows] = await pool.execute(`
|
|
89
|
+
SELECT
|
|
90
|
+
name,
|
|
91
|
+
salary,
|
|
92
|
+
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) as rank
|
|
93
|
+
FROM employees
|
|
94
|
+
`)
|
|
95
|
+
|
|
96
|
+
// Common Table Expressions (CTE) (MySQL 8.0+)
|
|
97
|
+
const [rows] = await pool.execute(`
|
|
98
|
+
WITH RECURSIVE cte AS (
|
|
99
|
+
SELECT id, name, parent_id FROM categories WHERE parent_id IS NULL
|
|
100
|
+
UNION ALL
|
|
101
|
+
SELECT c.id, c.name, c.parent_id FROM categories c
|
|
102
|
+
INNER JOIN cte ON c.parent_id = cte.id
|
|
103
|
+
)
|
|
104
|
+
SELECT * FROM cte
|
|
105
|
+
`)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Common Patterns
|
|
109
|
+
|
|
110
|
+
### Connection Pooling
|
|
111
|
+
```typescript
|
|
112
|
+
// Reuse connection pool
|
|
113
|
+
let pool: mysql.Pool | null = null
|
|
114
|
+
|
|
115
|
+
export function getPool(): mysql.Pool {
|
|
116
|
+
if (!pool) {
|
|
117
|
+
pool = mysql.createPool({
|
|
118
|
+
// ... config
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
pool.on('connection', (connection) => {
|
|
122
|
+
connection.query('SET SESSION sql_mode = "STRICT_TRANS_TABLES"')
|
|
123
|
+
})
|
|
124
|
+
}
|
|
125
|
+
return pool
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Graceful shutdown
|
|
129
|
+
process.on('SIGINT', async () => {
|
|
130
|
+
if (pool) {
|
|
131
|
+
await pool.end()
|
|
132
|
+
}
|
|
133
|
+
process.exit(0)
|
|
134
|
+
})
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### Prepared Statements
|
|
138
|
+
```typescript
|
|
139
|
+
// Always use parameterized queries (?) to prevent SQL injection
|
|
140
|
+
// ❌ WRONG
|
|
141
|
+
await pool.execute(`SELECT * FROM users WHERE email = '${email}'`)
|
|
142
|
+
|
|
143
|
+
// ✅ CORRECT
|
|
144
|
+
await pool.execute('SELECT * FROM users WHERE email = ?', [email])
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### Error Handling
|
|
148
|
+
```typescript
|
|
149
|
+
try {
|
|
150
|
+
const [rows] = await pool.execute('SELECT * FROM users WHERE id = ?', [userId])
|
|
151
|
+
if ((rows as any[]).length === 0) {
|
|
152
|
+
throw new Error('User not found')
|
|
153
|
+
}
|
|
154
|
+
return rows[0]
|
|
155
|
+
} catch (error: any) {
|
|
156
|
+
if (error.code === 'ER_DUP_ENTRY') {
|
|
157
|
+
throw new Error('Duplicate entry')
|
|
158
|
+
}
|
|
159
|
+
if (error.code === 'ER_NO_REFERENCED_ROW_2') {
|
|
160
|
+
throw new Error('Referenced record does not exist')
|
|
161
|
+
}
|
|
162
|
+
throw error
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### Migrations
|
|
167
|
+
```typescript
|
|
168
|
+
// Using db-migrate
|
|
169
|
+
import { migrate } from 'db-migrate'
|
|
170
|
+
|
|
171
|
+
await migrate({
|
|
172
|
+
config: {
|
|
173
|
+
dev: {
|
|
174
|
+
driver: 'mysql',
|
|
175
|
+
database: process.env.DB_NAME,
|
|
176
|
+
user: process.env.DB_USER,
|
|
177
|
+
password: process.env.DB_PASSWORD,
|
|
178
|
+
host: process.env.DB_HOST,
|
|
179
|
+
}
|
|
180
|
+
},
|
|
181
|
+
env: 'dev',
|
|
182
|
+
})
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## Best Practices
|
|
186
|
+
|
|
187
|
+
✅ **DO:**
|
|
188
|
+
- Use connection pooling (10-20 connections typically)
|
|
189
|
+
- Always use parameterized queries (? placeholders)
|
|
190
|
+
- Use transactions for multi-step operations
|
|
191
|
+
- Create indexes on frequently queried columns
|
|
192
|
+
- Use EXPLAIN to optimize queries
|
|
193
|
+
- Enable query caching for read-heavy workloads
|
|
194
|
+
- Use InnoDB engine (ACID compliance)
|
|
195
|
+
- Set appropriate charset (utf8mb4 for full Unicode)
|
|
196
|
+
- Monitor slow query log
|
|
197
|
+
- Use prepared statements for repeated queries
|
|
198
|
+
|
|
199
|
+
❌ **DON'T:**
|
|
200
|
+
- Use string concatenation for queries (SQL injection risk)
|
|
201
|
+
- Create too many connections (exhaust pool)
|
|
202
|
+
- Skip error handling
|
|
203
|
+
- Ignore connection pool limits
|
|
204
|
+
- Use SELECT * in production (specify columns)
|
|
205
|
+
- Skip indexes on foreign keys
|
|
206
|
+
- Hardcode connection strings
|
|
207
|
+
- Use MyISAM engine (no transactions)
|
|
208
|
+
- Ignore query performance
|
|
209
|
+
- Use synchronous queries
|
|
210
|
+
|
|
211
|
+
## Configuration
|
|
212
|
+
|
|
213
|
+
### Environment Variables
|
|
214
|
+
```bash
|
|
215
|
+
DB_HOST=localhost
|
|
216
|
+
DB_PORT=3306
|
|
217
|
+
DB_NAME=myapp
|
|
218
|
+
DB_USER=myuser
|
|
219
|
+
DB_PASSWORD=securepassword
|
|
220
|
+
DATABASE_URL=mysql://user:password@host:port/database
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
### Docker Compose
|
|
224
|
+
```yaml
|
|
225
|
+
services:
|
|
226
|
+
mysql:
|
|
227
|
+
image: mysql:8.0
|
|
228
|
+
environment:
|
|
229
|
+
MYSQL_DATABASE: myapp
|
|
230
|
+
MYSQL_USER: myuser
|
|
231
|
+
MYSQL_PASSWORD: securepassword
|
|
232
|
+
MYSQL_ROOT_PASSWORD: rootpassword
|
|
233
|
+
ports:
|
|
234
|
+
- "3306:3306"
|
|
235
|
+
volumes:
|
|
236
|
+
- mysql_data:/var/lib/mysql
|
|
237
|
+
command: --default-authentication-plugin=mysql_native_password
|
|
238
|
+
healthcheck:
|
|
239
|
+
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
|
|
240
|
+
interval: 10s
|
|
241
|
+
timeout: 5s
|
|
242
|
+
retries: 5
|
|
243
|
+
|
|
244
|
+
volumes:
|
|
245
|
+
mysql_data:
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### Prisma Schema
|
|
249
|
+
```prisma
|
|
250
|
+
datasource db {
|
|
251
|
+
provider = "mysql"
|
|
252
|
+
url = env("DATABASE_URL")
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
model User {
|
|
256
|
+
id Int @id @default(autoincrement())
|
|
257
|
+
email String @unique @db.VarChar(255)
|
|
258
|
+
name String? @db.VarChar(255)
|
|
259
|
+
createdAt DateTime @default(now()) @db.Timestamp(6)
|
|
260
|
+
posts Post[]
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
model Post {
|
|
264
|
+
id Int @id @default(autoincrement())
|
|
265
|
+
title String @db.VarChar(255)
|
|
266
|
+
content String? @db.Text
|
|
267
|
+
authorId Int
|
|
268
|
+
author User @relation(fields: [authorId], references: [id])
|
|
269
|
+
createdAt DateTime @default(now()) @db.Timestamp(6)
|
|
270
|
+
|
|
271
|
+
@@index([authorId, createdAt(sort: Desc)])
|
|
272
|
+
}
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
## Performance Optimization
|
|
276
|
+
|
|
277
|
+
### Indexing
|
|
278
|
+
```sql
|
|
279
|
+
-- Single column index
|
|
280
|
+
CREATE INDEX idx_users_email ON users(email);
|
|
281
|
+
|
|
282
|
+
-- Composite index
|
|
283
|
+
CREATE INDEX idx_posts_author_created ON posts(author_id, created_at DESC);
|
|
284
|
+
|
|
285
|
+
-- Full-text index
|
|
286
|
+
CREATE FULLTEXT INDEX idx_articles_content ON articles(title, content);
|
|
287
|
+
|
|
288
|
+
-- Prefix index (for long strings)
|
|
289
|
+
CREATE INDEX idx_users_name_prefix ON users(name(10));
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
### Query Optimization
|
|
293
|
+
```typescript
|
|
294
|
+
// Use LIMIT for pagination
|
|
295
|
+
const [rows] = await pool.execute(
|
|
296
|
+
'SELECT * FROM posts ORDER BY created_at DESC LIMIT ? OFFSET ?',
|
|
297
|
+
[limit, offset]
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
// Use EXISTS instead of COUNT
|
|
301
|
+
const [rows] = await pool.execute(
|
|
302
|
+
'SELECT EXISTS(SELECT 1 FROM users WHERE email = ?) as exists',
|
|
303
|
+
[email]
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
// Use JOIN instead of subqueries when possible
|
|
307
|
+
const [rows] = await pool.execute(`
|
|
308
|
+
SELECT u.*, COUNT(p.id) as post_count
|
|
309
|
+
FROM users u
|
|
310
|
+
LEFT JOIN posts p ON u.id = p.author_id
|
|
311
|
+
GROUP BY u.id
|
|
312
|
+
`)
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
## Integration with Development
|
|
316
|
+
|
|
317
|
+
### Testing
|
|
318
|
+
```typescript
|
|
319
|
+
// Use test database
|
|
320
|
+
const testPool = mysql.createPool({
|
|
321
|
+
database: 'myapp_test',
|
|
322
|
+
// ... config
|
|
323
|
+
})
|
|
324
|
+
|
|
325
|
+
// Clean up after tests
|
|
326
|
+
afterEach(async () => {
|
|
327
|
+
await testPool.execute('SET FOREIGN_KEY_CHECKS = 0')
|
|
328
|
+
await testPool.execute('TRUNCATE TABLE users')
|
|
329
|
+
await testPool.execute('TRUNCATE TABLE posts')
|
|
330
|
+
await testPool.execute('SET FOREIGN_KEY_CHECKS = 1')
|
|
331
|
+
})
|
|
332
|
+
|
|
333
|
+
// Use transactions for test isolation
|
|
334
|
+
beforeEach(async () => {
|
|
335
|
+
const connection = await testPool.getConnection()
|
|
336
|
+
await connection.beginTransaction()
|
|
337
|
+
// Store connection for rollback
|
|
338
|
+
})
|
|
339
|
+
|
|
340
|
+
afterEach(async () => {
|
|
341
|
+
// Rollback transaction
|
|
342
|
+
})
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
### Health Checks
|
|
346
|
+
```typescript
|
|
347
|
+
async function checkDatabaseHealth(): Promise<boolean> {
|
|
348
|
+
try {
|
|
349
|
+
const [rows] = await pool.execute('SELECT 1 as health')
|
|
350
|
+
return (rows as any[]).length > 0
|
|
351
|
+
} catch {
|
|
352
|
+
return false
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
<!-- MYSQL:END -->
|
|
358
|
+
|