@umacloud/knowledge 1.0.1

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 (418) hide show
  1. package/00-governance/governance-capabilities.md +557 -0
  2. package/00-governance/knowledge-map.md +39 -0
  3. package/00-governance/maintenance-policy.md +76 -0
  4. package/00-governance/review-checklist.md +81 -0
  5. package/README.md +13 -0
  6. package/ai/01-standards/agent-development-complete.md +691 -0
  7. package/ai/01-standards/llm-application-complete.md +488 -0
  8. package/ai/01-standards/mlops-complete.md +798 -0
  9. package/ai/01-standards/prompt-engineering-complete.md +646 -0
  10. package/ai/01-standards/rag-architecture-complete.md +649 -0
  11. package/ai/02-playbooks/llm-evaluation-playbook.md +847 -0
  12. package/ai/03-checklists/ai-project-checklist.md +215 -0
  13. package/ai/04-antipatterns/ai-antipatterns.md +661 -0
  14. package/ai/05-cases/case-rag-production.md +147 -0
  15. package/ai/06-glossary/ai-glossary.md +162 -0
  16. package/ai/agent-evaluation-benchmark.md +53 -0
  17. package/ai/ai-agent-memory-context-management.md +41 -0
  18. package/ai/ai-cost-capacity-optimization-playbook.md +42 -0
  19. package/ai/ai-data-security-and-compliance-playbook.md +37 -0
  20. package/ai/ai-domain-index-and-checklist.md +40 -0
  21. package/ai/ai-governance-maturity-model.md +50 -0
  22. package/ai/ai-model-selection-and-routing-strategy.md +47 -0
  23. package/ai/ai-observability-and-oncall-runbook.md +52 -0
  24. package/ai/ai-rag-engineering-playbook.md +42 -0
  25. package/ai/ai-red-team-and-safety-evaluation.md +42 -0
  26. package/ai/ai-release-readiness-and-rollback-gate.md +42 -0
  27. package/ai/llm-agent-engineering-deep-dive.md +57 -0
  28. package/ai/prompt-and-tool-guardrails.md +52 -0
  29. package/api/01-standards/enterprise-api-standards.md +198 -0
  30. package/api/01-standards/rest-api-design-guide.md +63 -0
  31. package/api/02-playbooks/api-pagination-playbook.md +93 -0
  32. package/api/02-playbooks/graphql-production-playbook.md +176 -0
  33. package/api/03-checklists/api-review-checklist.md +55 -0
  34. package/api/04-antipatterns/api-antipatterns.md +112 -0
  35. package/architecture/01-standards/api-gateway-patterns.md +496 -0
  36. package/architecture/01-standards/cloud-native-patterns.md +644 -0
  37. package/architecture/01-standards/distributed-systems-patterns.md +591 -0
  38. package/architecture/01-standards/event-driven-architecture.md +595 -0
  39. package/architecture/01-standards/microservices-patterns-complete.md +968 -0
  40. package/architecture/01-standards/microservices-patterns.md +495 -0
  41. package/architecture/01-standards/system-design-interview.md +664 -0
  42. package/architecture/02-playbooks/microservices-patterns-playbook.md +137 -0
  43. package/architecture/02-playbooks/migration-playbook.md +780 -0
  44. package/architecture/02-playbooks/system-design-playbook.md +779 -0
  45. package/architecture/03-checklists/architecture-decision-checklist.md +297 -0
  46. package/architecture/04-antipatterns/architecture-antipatterns.md +417 -0
  47. package/architecture/05-cases/case-netflix-microservices.md +413 -0
  48. package/architecture/06-glossary/architecture-glossary.md +164 -0
  49. package/architecture/adr-template-and-examples.md +38 -0
  50. package/architecture/api-gateway-deep-dive.md +1291 -0
  51. package/architecture/configuration-management.md +1162 -0
  52. package/architecture/distributed-transactions.md +1220 -0
  53. package/architecture/microservices-complete.md +735 -0
  54. package/architecture/resilience-and-disaster-patterns.md +37 -0
  55. package/architecture/service-governance.md +1198 -0
  56. package/architecture/system-architecture-deep-dive.md +37 -0
  57. package/backend/01-standards/analytics-and-growth.md +65 -0
  58. package/backend/01-standards/api-and-error-conventions.md +120 -0
  59. package/backend/01-standards/application-layering-and-packaging.md +160 -0
  60. package/backend/01-standards/auth-implementation.md +104 -0
  61. package/backend/01-standards/backend-framework-idioms.md +74 -0
  62. package/backend/01-standards/background-jobs-and-async.md +66 -0
  63. package/backend/01-standards/caching-strategies-complete.md +390 -0
  64. package/backend/01-standards/config-and-observability.md +77 -0
  65. package/backend/01-standards/data-modeling-and-persistence.md +94 -0
  66. package/backend/01-standards/django-complete.md +1765 -0
  67. package/backend/01-standards/email-and-notifications.md +64 -0
  68. package/backend/01-standards/fastapi-complete.md +925 -0
  69. package/backend/01-standards/file-upload-and-storage.md +66 -0
  70. package/backend/01-standards/graphql-api-complete.md +416 -0
  71. package/backend/01-standards/llm-application-standard.md +78 -0
  72. package/backend/01-standards/message-queue-patterns.md +379 -0
  73. package/backend/01-standards/microservices-and-distributed.md +78 -0
  74. package/backend/01-standards/nestjs-complete.md +2167 -0
  75. package/backend/01-standards/payment-integration.md +80 -0
  76. package/backend/01-standards/rate-limiting-complete.md +451 -0
  77. package/backend/01-standards/realtime-and-websocket.md +65 -0
  78. package/backend/01-standards/search-and-filtering.md +64 -0
  79. package/backend/01-standards/spring-boot-complete.md +445 -0
  80. package/backend/02-playbooks/api-design-playbook.md +718 -0
  81. package/backend/02-playbooks/email-send-playbook.md +130 -0
  82. package/backend/02-playbooks/file-upload-s3-playbook.md +153 -0
  83. package/backend/02-playbooks/typescript-enterprise-playbook.md +133 -0
  84. package/backend/02-playbooks/websocket-realtime-playbook.md +154 -0
  85. package/backend/03-checklists/api-launch-checklist.md +189 -0
  86. package/backend/04-antipatterns/backend-antipatterns.md +1051 -0
  87. package/blockchain/01-standards/blockchain-basics.md +557 -0
  88. package/blockchain/01-standards/smart-contract-development.md +1315 -0
  89. package/cicd/01-standards/deployment-and-delivery-standard.md +96 -0
  90. package/cicd/01-standards/github-actions-complete.md +473 -0
  91. package/cicd/01-standards/release-and-store-submission.md +75 -0
  92. package/cicd/02-playbooks/cicd-pipeline-playbook.md +144 -0
  93. package/cicd/02-playbooks/release-management-playbook.md +605 -0
  94. package/cicd/03-checklists/pipeline-security-checklist.md +168 -0
  95. package/cicd/04-antipatterns/cicd-antipatterns.md +589 -0
  96. package/cicd/05-cases/case-deployment-automation.md +221 -0
  97. package/cicd/05-cases/case-gitops-transformation.md +212 -0
  98. package/cicd/06-glossary/cicd-glossary.md +114 -0
  99. package/cicd/cicd-blueprint-deep-dive.md +38 -0
  100. package/cicd/release-readiness-gate.md +37 -0
  101. package/cloud-native/01-standards/container-security.md +741 -0
  102. package/cloud-native/01-standards/kubernetes-complete.md +812 -0
  103. package/cloud-native/02-playbooks/api-gateway-playbook.md +155 -0
  104. package/cloud-native/02-playbooks/gitops-with-argocd.md +760 -0
  105. package/cloud-native/02-playbooks/k8s-troubleshooting-playbook.md +1942 -0
  106. package/cloud-native/02-playbooks/message-queue-playbook.md +129 -0
  107. package/cloud-native/02-playbooks/multicloud-governance.md +726 -0
  108. package/cloud-native/02-playbooks/serverless-patterns.md +788 -0
  109. package/cloud-native/02-playbooks/service-mesh-playbook.md +612 -0
  110. package/cloud-native/02-playbooks/terraform-iac-playbook.md +143 -0
  111. package/cloud-native/03-checklists/container-security-checklist.md +431 -0
  112. package/cloud-native/03-checklists/k8s-production-readiness-checklist.md +460 -0
  113. package/cloud-native/04-antipatterns/container-antipatterns.md +660 -0
  114. package/cloud-native/04-antipatterns/k8s-antipatterns.md +743 -0
  115. package/cloud-native/05-cases/case-k8s-migration.md +478 -0
  116. package/cloud-native/05-cases/case-k8s-scaling.md +642 -0
  117. package/cloud-native/05-cases/case-k8s-security-incident.md +397 -0
  118. package/cloud-native/06-glossary/cloud-native-glossary.md +337 -0
  119. package/cross-platform/01-standards/cross-platform-frameworks.md +83 -0
  120. package/cross-platform/01-standards/platform-selection-and-architecture.md +77 -0
  121. package/data/01-standards/elasticsearch-complete.md +2098 -0
  122. package/data/01-standards/postgresql-complete.md +1613 -0
  123. package/data/01-standards/redis-complete.md +1527 -0
  124. package/data/02-playbooks/database-optimization-playbook.md +403 -0
  125. package/data/02-playbooks/elasticsearch-production-playbook.md +132 -0
  126. package/data/03-checklists/database-launch-checklist.md +187 -0
  127. package/data/04-antipatterns/database-antipatterns.md +873 -0
  128. package/data/05-cases/case-database-migration.md +310 -0
  129. package/data/06-glossary/database-glossary.md +440 -0
  130. package/data/data-governance-and-modeling-deep-dive.md +39 -0
  131. package/data-engineering/01-standards/airflow-complete.md +523 -0
  132. package/data-engineering/01-standards/kafka-complete.md +1521 -0
  133. package/data-engineering/02-playbooks/spark-etl-playbook.md +496 -0
  134. package/data-engineering/03-checklists/pipeline-launch-checklist.md +194 -0
  135. package/data-engineering/04-antipatterns/data-pipeline-antipatterns.md +684 -0
  136. package/data-engineering/05-cases/case-real-time-pipeline.md +355 -0
  137. package/data-engineering/06-glossary/data-engineering-glossary.md +429 -0
  138. package/database/01-standards/database-schema-standards.md +147 -0
  139. package/database/02-playbooks/postgresql-optimization-quick.md +52 -0
  140. package/database/02-playbooks/postgresql-performance-optimization.md +58 -0
  141. package/database/02-playbooks/postgresql-production-playbook.md +146 -0
  142. package/database/02-playbooks/redis-caching-playbook.md +117 -0
  143. package/database/03-checklists/database-review-checklist.md +50 -0
  144. package/database/04-antipatterns/database-antipatterns.md +112 -0
  145. package/design/01-standards/ui-design-system-complete.md +423 -0
  146. package/design/02-playbooks/design-handoff-playbook.md +254 -0
  147. package/design/02-playbooks/design-review-playbook.md +388 -0
  148. package/design/03-checklists/design-review-checklist.md +246 -0
  149. package/design/04-antipatterns/design-antipatterns.md +378 -0
  150. package/design/05-cases/case-design-system-adoption.md +328 -0
  151. package/design/06-glossary/design-glossary.md +329 -0
  152. package/design/ui-full-lifecycle-cross-platform-playbook.md +571 -0
  153. package/design/ux-system-deep-dive.md +38 -0
  154. package/design-systems/00-craft-rules.md +71 -0
  155. package/design-systems/aesthetic-families.md +43 -0
  156. package/design-systems/anti-ai-slop.md +162 -0
  157. package/design-systems/bold-geometric.md +120 -0
  158. package/design-systems/brutalist-bold.md +103 -0
  159. package/design-systems/editorial-clean.md +109 -0
  160. package/design-systems/glass-aurora.md +108 -0
  161. package/design-systems/modern-minimal.md +145 -0
  162. package/design-systems/premium-luxury.md +106 -0
  163. package/design-systems/product-type-design-map.md +48 -0
  164. package/design-systems/soft-warm.md +123 -0
  165. package/design-systems/tech-utility.md +113 -0
  166. package/desktop/01-standards/desktop-app-standard.md +72 -0
  167. package/desktop/01-standards/desktop-design.md +71 -0
  168. package/development/00-governance/document-template.md +41 -0
  169. package/development/01-standards/api-versioning-strategies.md +432 -0
  170. package/development/01-standards/authentication-patterns-complete.md +479 -0
  171. package/development/01-standards/css-architecture-complete.md +550 -0
  172. package/development/01-standards/database-migration-strategies.md +484 -0
  173. package/development/01-standards/elasticsearch-complete.md +347 -0
  174. package/development/01-standards/git-complete.md +371 -0
  175. package/development/01-standards/golang-complete.md +1565 -0
  176. package/development/01-standards/graphql-complete.md +298 -0
  177. package/development/01-standards/javascript-bundlers-complete.md +469 -0
  178. package/development/01-standards/javascript-typescript-complete.md +528 -0
  179. package/development/01-standards/jest-complete.md +275 -0
  180. package/development/01-standards/linux-complete.md +234 -0
  181. package/development/01-standards/logging-observability-complete.md +526 -0
  182. package/development/01-standards/microservices-communication.md +502 -0
  183. package/development/01-standards/mongodb-complete.md +406 -0
  184. package/development/01-standards/oauth2-complete.md +285 -0
  185. package/development/01-standards/performance-optimization-complete.md +289 -0
  186. package/development/01-standards/playwright-complete.md +247 -0
  187. package/development/01-standards/postgresql-complete.md +456 -0
  188. package/development/01-standards/pytest-complete.md +340 -0
  189. package/development/01-standards/python-async-programming.md +902 -0
  190. package/development/01-standards/python-complete.md +956 -0
  191. package/development/01-standards/python-decorators-complete.md +799 -0
  192. package/development/01-standards/python-design-patterns.md +2854 -0
  193. package/development/01-standards/python-packaging-distribution.md +420 -0
  194. package/development/01-standards/python-testing-strategies.md +607 -0
  195. package/development/01-standards/python-web-frameworks-comparison.md +471 -0
  196. package/development/01-standards/redis-complete.md +317 -0
  197. package/development/01-standards/rest-api-complete.md +316 -0
  198. package/development/01-standards/rust-complete.md +578 -0
  199. package/development/01-standards/typescript-advanced-types.md +1513 -0
  200. package/development/01-standards/web-security-complete.md +292 -0
  201. package/development/02-playbooks/api-design-playbook.md +810 -0
  202. package/development/02-playbooks/database-migration-playbook.md +580 -0
  203. package/development/02-playbooks/debugging-playbook.md +692 -0
  204. package/development/02-playbooks/feature-delivery-playbook.md +430 -0
  205. package/development/02-playbooks/incident-hotfix-playbook.md +387 -0
  206. package/development/02-playbooks/performance-optimization-playbook.md +531 -0
  207. package/development/02-playbooks/performance-tuning-playbook.md +652 -0
  208. package/development/02-playbooks/refactor-playbook.md +403 -0
  209. package/development/02-playbooks/release-playbook.md +469 -0
  210. package/development/03-checklists/architecture-review-checklist.md +168 -0
  211. package/development/03-checklists/data-migration-checklist.md +157 -0
  212. package/development/03-checklists/oncall-handover-checklist.md +173 -0
  213. package/development/03-checklists/pr-checklist.md +158 -0
  214. package/development/03-checklists/production-readiness-checklist.md +190 -0
  215. package/development/03-checklists/release-readiness-checklist.md +154 -0
  216. package/development/03-checklists/security-review-checklist.md +182 -0
  217. package/development/04-antipatterns/api-antipatterns.md +657 -0
  218. package/development/04-antipatterns/architecture-antipatterns.md +686 -0
  219. package/development/04-antipatterns/backend-antipatterns.md +648 -0
  220. package/development/04-antipatterns/cicd-antipatterns.md +540 -0
  221. package/development/04-antipatterns/code-smell-antipatterns.md +571 -0
  222. package/development/04-antipatterns/data-antipatterns.md +658 -0
  223. package/development/04-antipatterns/database-antipatterns.md +578 -0
  224. package/development/04-antipatterns/frontend-antipatterns.md +635 -0
  225. package/development/04-antipatterns/reliability-antipatterns.md +700 -0
  226. package/development/04-antipatterns/security-antipatterns.md +747 -0
  227. package/development/05-cases/case-api-version-migration.md +428 -0
  228. package/development/05-cases/case-authorization-hardening.md +383 -0
  229. package/development/05-cases/case-bluegreen-rollback.md +466 -0
  230. package/development/05-cases/case-cache-snowball-protection.md +485 -0
  231. package/development/05-cases/case-ci-cd-pipeline.md +544 -0
  232. package/development/05-cases/case-database-scaling.md +500 -0
  233. package/development/05-cases/case-db-hotspot-optimization.md +487 -0
  234. package/development/05-cases/case-incident-mttr-reduction.md +563 -0
  235. package/development/05-cases/case-microservice-migration.md +375 -0
  236. package/development/05-cases/case-performance-optimization.md +406 -0
  237. package/development/05-cases/case-security-incident-response.md +345 -0
  238. package/development/06-glossary/full-stack-glossary.md +166 -0
  239. package/development/09-maturity/quarterly-audit-template.md +35 -0
  240. package/development/11-ui-excellence/ui-aesthetic-system.md +41 -0
  241. package/development/11-ui-excellence/ui-engineering-excellence.md +435 -0
  242. package/development/12-scenarios/development-scenarios-guide.md +565 -0
  243. package/development/13-implementation-assets/implementation-toolkit.md +282 -0
  244. package/development/13-implementation-assets/knowledge-gates-execution.md +43 -0
  245. package/development/14-full-lifecycle/software-lifecycle-gates.md +511 -0
  246. package/development/15-lifecycle-templates/project-templates-collection.md +791 -0
  247. package/development/api-contract-and-versioning-guide.md +36 -0
  248. package/development/api-governance-complete.md +43 -0
  249. package/development/backend-engineering-complete.md +43 -0
  250. package/development/code-review-quality-complete.md +43 -0
  251. package/development/concurrency-reliability-complete.md +43 -0
  252. package/development/database-engineering-complete.md +43 -0
  253. package/development/engineering-effectiveness-complete.md +43 -0
  254. package/development/engineering-standards-deep-dive.md +38 -0
  255. package/development/frontend-engineering-complete.md +43 -0
  256. package/development/performance-capacity-complete.md +43 -0
  257. package/development/refactor-migration-complete.md +42 -0
  258. package/development/refactoring-and-techdebt-playbook.md +37 -0
  259. package/development/security-in-development-complete.md +43 -0
  260. package/devops/01-standards/cicd-pipeline-complete.md +262 -0
  261. package/devops/01-standards/docker-complete.md +1490 -0
  262. package/devops/01-standards/github-actions-complete.md +337 -0
  263. package/devops/01-standards/kubernetes-complete.md +638 -0
  264. package/devops/01-standards/terraform-complete.md +2117 -0
  265. package/devops/02-playbooks/docker-compose-playbook.md +233 -0
  266. package/devops/02-playbooks/docker-k8s-production-playbook.md +186 -0
  267. package/devops/02-playbooks/docker-production-playbook.md +952 -0
  268. package/edge-iot/01-standards/edge-iot-complete.md +473 -0
  269. package/experts/architect/api-design.md +178 -0
  270. package/experts/architect/methodology.md +124 -0
  271. package/experts/architect/security.md +75 -0
  272. package/experts/backend-lead/methodology.md +216 -0
  273. package/experts/devops/methodology.md +160 -0
  274. package/experts/frontend-lead/methodology.md +178 -0
  275. package/experts/product-manager/industry/ecommerce.md +43 -0
  276. package/experts/product-manager/industry/saas.md +40 -0
  277. package/experts/product-manager/methodology.md +97 -0
  278. package/experts/qa-lead/methodology.md +123 -0
  279. package/experts/qa-lead/test-strategy.md +128 -0
  280. package/experts/uiux-designer/methodology.md +125 -0
  281. package/frontend/01-standards/accessibility-complete.md +532 -0
  282. package/frontend/01-standards/accessibility-standard.md +74 -0
  283. package/frontend/01-standards/admin-dashboard-and-crud.md +72 -0
  284. package/frontend/01-standards/design-tokens-complete.md +444 -0
  285. package/frontend/01-standards/forms-and-validation.md +77 -0
  286. package/frontend/01-standards/frontend-architecture-and-layering.md +119 -0
  287. package/frontend/01-standards/i18n-and-localization.md +65 -0
  288. package/frontend/01-standards/nextjs-complete.md +451 -0
  289. package/frontend/01-standards/react-complete.md +713 -0
  290. package/frontend/01-standards/react-hooks-complete-guide.md +1100 -0
  291. package/frontend/01-standards/react-hooks-complete.md +1171 -0
  292. package/frontend/01-standards/seo-and-web-vitals.md +77 -0
  293. package/frontend/01-standards/state-management-complete.md +444 -0
  294. package/frontend/01-standards/vue-complete.md +499 -0
  295. package/frontend/01-standards/vue3-complete.md +2002 -0
  296. package/frontend/01-standards/web-framework-best-practices.md +64 -0
  297. package/frontend/01-standards/web-performance-complete.md +495 -0
  298. package/frontend/02-playbooks/accessibility-a11y-playbook.md +161 -0
  299. package/frontend/02-playbooks/frontend-performance-playbook.md +707 -0
  300. package/frontend/02-playbooks/i18n-internationalization-playbook.md +120 -0
  301. package/frontend/02-playbooks/performance-optimization-playbook.md +163 -0
  302. package/frontend/02-playbooks/react-nextjs-production-playbook.md +167 -0
  303. package/frontend/02-playbooks/react-state-management-playbook.md +173 -0
  304. package/frontend/03-checklists/component-quality-checklist.md +166 -0
  305. package/frontend/03-checklists/frontend-launch-checklist.md +299 -0
  306. package/frontend/04-antipatterns/frontend-antipatterns.md +886 -0
  307. package/frontend/05-cases/case-performance-optimization.md +274 -0
  308. package/harmony/01-standards/harmonyos-arkts-standard.md +75 -0
  309. package/harmony/01-standards/harmonyos-design.md +65 -0
  310. package/high-quality-engineering-playbook.md +54 -0
  311. package/incident/01-standards/incident-response-complete.md +303 -0
  312. package/incident/02-playbooks/chaos-engineering-playbook.md +883 -0
  313. package/incident/02-playbooks/postmortem-playbook.md +398 -0
  314. package/incident/03-checklists/incident-readiness-checklist.md +181 -0
  315. package/incident/04-antipatterns/incident-antipatterns.md +490 -0
  316. package/incident/05-cases/case-cascade-failure.md +176 -0
  317. package/incident/06-glossary/incident-glossary.md +114 -0
  318. package/incident/postmortem-and-response-deep-dive.md +39 -0
  319. package/industries/ecommerce/ecommerce-complete.md +631 -0
  320. package/industries/education/education-complete.md +555 -0
  321. package/industries/fintech/fintech-complete.md +501 -0
  322. package/industries/gaming/gaming-complete.md +587 -0
  323. package/industries/healthcare/healthcare-complete.md +452 -0
  324. package/low-code/01-standards/low-code-complete.md +944 -0
  325. package/miniprogram/01-standards/ai-common-mistakes.md +61 -0
  326. package/miniprogram/01-standards/miniprogram-custom-navbar-capsule.md +77 -0
  327. package/miniprogram/01-standards/miniprogram-design.md +61 -0
  328. package/miniprogram/01-standards/miniprogram-standard.md +81 -0
  329. package/mobile/01-standards/android-material-design.md +70 -0
  330. package/mobile/01-standards/flutter-complete.md +384 -0
  331. package/mobile/01-standards/ios-design-hig.md +78 -0
  332. package/mobile/01-standards/mobile-app-standard.md +85 -0
  333. package/mobile/01-standards/react-native-complete.md +352 -0
  334. package/mobile/02-playbooks/mobile-cross-platform-playbook.md +175 -0
  335. package/mobile/02-playbooks/mobile-performance.md +473 -0
  336. package/mobile/03-checklists/mobile-release-checklist.md +234 -0
  337. package/mobile/04-antipatterns/mobile-antipatterns.md +798 -0
  338. package/mobile/05-cases/case-app-performance.md +500 -0
  339. package/mobile/05-cases/case-app-startup-optimization.md +218 -0
  340. package/mobile/06-glossary/mobile-glossary.md +484 -0
  341. package/observability/01-standards/observability-standards.md +103 -0
  342. package/observability/02-playbooks/prometheus-grafana-playbook.md +135 -0
  343. package/observability/02-playbooks/structured-logging-playbook.md +73 -0
  344. package/observability/03-checklists/observability-checklist.md +54 -0
  345. package/observability/04-antipatterns/observability-antipatterns.md +106 -0
  346. package/operations/01-standards/prometheus-monitoring-complete.md +1578 -0
  347. package/operations/02-playbooks/capacity-planning-playbook.md +620 -0
  348. package/operations/03-checklists/production-launch-checklist.md +365 -0
  349. package/operations/04-antipatterns/operations-antipatterns.md +664 -0
  350. package/operations/05-cases/case-sre-practices.md +581 -0
  351. package/operations/06-glossary/operations-glossary.md +120 -0
  352. package/operations/aiops-anomaly-detection.md +758 -0
  353. package/operations/capacity-planning.md +1061 -0
  354. package/operations/chaos-engineering.md +659 -0
  355. package/operations/incident-command-system.md +38 -0
  356. package/operations/observability-complete.md +442 -0
  357. package/operations/slo-sli-playbook.md +517 -0
  358. package/operations/sre-operations-deep-dive.md +39 -0
  359. package/package.json +8 -0
  360. package/performance/01-standards/performance-and-scalability.md +80 -0
  361. package/performance/01-standards/performance-standards.md +156 -0
  362. package/performance/02-playbooks/query-optimization-playbook.md +103 -0
  363. package/performance/03-checklists/performance-checklist.md +56 -0
  364. package/performance/04-antipatterns/performance-antipatterns.md +146 -0
  365. package/product/01-standards/product-management-complete.md +285 -0
  366. package/product/02-playbooks/feature-launch-playbook.md +207 -0
  367. package/product/02-playbooks/user-research-playbook.md +532 -0
  368. package/product/03-checklists/feature-launch-checklist.md +275 -0
  369. package/product/04-antipatterns/product-antipatterns.md +355 -0
  370. package/product/05-cases/case-mvp-to-scale.md +384 -0
  371. package/product/06-glossary/product-glossary.md +462 -0
  372. package/product/feature-prioritization-framework.md +40 -0
  373. package/product/kpi-and-metric-tree.md +37 -0
  374. package/product/product-discovery-and-prd-deep-dive.md +41 -0
  375. package/quantum/01-standards/quantum-complete.md +1186 -0
  376. package/security/01-standards/api-security-complete.md +511 -0
  377. package/security/01-standards/container-runtime-security.md +574 -0
  378. package/security/01-standards/data-protection-gdpr.md +543 -0
  379. package/security/01-standards/owasp-top10-complete.md +1890 -0
  380. package/security/01-standards/secure-coding-baseline.md +90 -0
  381. package/security/01-standards/supply-chain-security.md +441 -0
  382. package/security/01-standards/web-security-checklist.md +108 -0
  383. package/security/01-standards/zero-trust-architecture.md +521 -0
  384. package/security/02-playbooks/auth-sso-playbook.md +166 -0
  385. package/security/02-playbooks/incident-response-security-playbook.md +588 -0
  386. package/security/02-playbooks/owasp-api-security-playbook.md +129 -0
  387. package/security/02-playbooks/payment-integration-playbook.md +119 -0
  388. package/security/02-playbooks/penetration-testing-playbook.md +517 -0
  389. package/security/03-checklists/security-audit-checklist.md +356 -0
  390. package/security/04-antipatterns/security-coding-antipatterns.md +580 -0
  391. package/security/05-cases/case-log4shell-incident.md +537 -0
  392. package/security/05-cases/case-major-breaches.md +468 -0
  393. package/security/06-glossary/security-glossary.md +212 -0
  394. package/security/compliance-automation.md +993 -0
  395. package/security/container-security.md +680 -0
  396. package/security/devsecops-complete.md +426 -0
  397. package/security/sast-dast-sca.md +775 -0
  398. package/security/secrets-management.md +594 -0
  399. package/security/security-architecture-deep-dive.md +37 -0
  400. package/security/threat-modeling-stride-playbook.md +40 -0
  401. package/seed-templates/auth-system.md +59 -0
  402. package/seed-templates/blog-content.md +94 -0
  403. package/seed-templates/dashboard.md +89 -0
  404. package/seed-templates/docs-site.md +73 -0
  405. package/seed-templates/e-commerce.md +50 -0
  406. package/seed-templates/saas-landing.md +92 -0
  407. package/seed-templates/settings-page.md +51 -0
  408. package/testing/01-standards/test-strategy-and-layering.md +83 -0
  409. package/testing/01-standards/testing-strategy-complete.md +422 -0
  410. package/testing/01-standards/unit-testing-best-practices.md +118 -0
  411. package/testing/02-playbooks/e2e-testing-playbook.md +988 -0
  412. package/testing/02-playbooks/testing-strategy-playbook.md +126 -0
  413. package/testing/03-checklists/test-strategy-checklist.md +208 -0
  414. package/testing/04-antipatterns/testing-antipatterns.md +718 -0
  415. package/testing/05-cases/case-testing-transformation.md +300 -0
  416. package/testing/06-glossary/testing-glossary.md +110 -0
  417. package/testing/risk-based-test-matrix.md +36 -0
  418. package/testing/testing-strategy-deep-dive.md +37 -0
@@ -0,0 +1,873 @@
1
+ ---
2
+ id: database-antipatterns
3
+ title: 数据库反模式完全指南
4
+ domain: data
5
+ category: 04-antipatterns
6
+ difficulty: intermediate
7
+ tags: [antipatterns, data, database, delete, index, pagination, problem, query]
8
+ quality_score: 70
9
+ last_updated: 2026-06-15
10
+ ---
11
+ # 数据库反模式完全指南
12
+
13
+ > 适用范围:PostgreSQL / MySQL / MongoDB / Redis
14
+ > 约束级别:SHALL(必须在 Code Review 和 SQL Review 阶段拦截)
15
+
16
+ ---
17
+
18
+ ## 1. 无索引查询(Missing Index)
19
+
20
+ ### 描述
21
+ 在高频查询的 WHERE / JOIN / ORDER BY 列上缺少索引,导致全表扫描。当表行数超过万级时,响应时间从毫秒级退化到秒级。
22
+
23
+ ### 错误示例
24
+ ```sql
25
+ -- 用户表 100 万行,email 列无索引
26
+ SELECT * FROM users WHERE email = 'alice@example.com';
27
+ -- Seq Scan on users (cost=0.00..25432.00 rows=1 width=128)
28
+ -- Execution Time: 850ms
29
+
30
+ -- 订单表按状态过滤,status 无索引
31
+ SELECT * FROM orders WHERE status = 'pending' ORDER BY created_at DESC;
32
+ -- Seq Scan on orders (cost=0.00..48210.00 rows=15000 width=256)
33
+ ```
34
+
35
+ ```python
36
+ # SQLAlchemy -- 定义模型时忘记添加索引
37
+ class User(Base):
38
+ __tablename__ = "users"
39
+ id = Column(Integer, primary_key=True)
40
+ email = Column(String(255)) # 缺少 index=True
41
+ phone = Column(String(20)) # 缺少 index=True
42
+ created_at = Column(DateTime) # 缺少 index=True
43
+ ```
44
+
45
+ ### 正确示例
46
+ ```sql
47
+ -- 为高频查询列创建索引
48
+ CREATE INDEX idx_users_email ON users (email);
49
+ CREATE INDEX idx_orders_status_created ON orders (status, created_at DESC);
50
+
51
+ -- 使用 EXPLAIN ANALYZE 验证
52
+ EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'alice@example.com';
53
+ -- Index Scan using idx_users_email on users (cost=0.42..8.44 rows=1 width=128)
54
+ -- Execution Time: 0.05ms
55
+ ```
56
+
57
+ ```python
58
+ # SQLAlchemy -- 正确声明索引
59
+ class User(Base):
60
+ __tablename__ = "users"
61
+ id = Column(Integer, primary_key=True)
62
+ email = Column(String(255), index=True, unique=True)
63
+ phone = Column(String(20), index=True)
64
+ created_at = Column(DateTime, index=True)
65
+
66
+ __table_args__ = (
67
+ Index("idx_users_email_phone", "email", "phone"), # 复合索引
68
+ )
69
+ ```
70
+
71
+ ### 检测方法
72
+ ```sql
73
+ -- PostgreSQL: 查找缺少索引的表
74
+ SELECT schemaname, relname, seq_scan, seq_tup_read,
75
+ idx_scan, idx_tup_fetch
76
+ FROM pg_stat_user_tables
77
+ WHERE seq_scan > 1000 AND idx_scan < 10
78
+ ORDER BY seq_tup_read DESC;
79
+
80
+ -- PostgreSQL: 查找未使用的索引(反向清理)
81
+ SELECT indexrelname, idx_scan
82
+ FROM pg_stat_user_indexes
83
+ WHERE idx_scan = 0 AND indexrelname NOT LIKE 'pg_%'
84
+ ORDER BY pg_relation_size(indexrelid) DESC;
85
+ ```
86
+
87
+ ---
88
+
89
+ ## 2. SELECT *(全列查询)
90
+
91
+ ### 描述
92
+ 使用 `SELECT *` 返回所有列,浪费带宽、内存和 I/O。尤其在包含 TEXT / BLOB / JSONB 大字段的表中,性能损失显著。还会导致索引覆盖扫描失效。
93
+
94
+ ### 错误示例
95
+ ```sql
96
+ -- 产品表含 description (TEXT) 和 images (JSONB),只需要名称和价格
97
+ SELECT * FROM products WHERE category_id = 5;
98
+ -- 返回 20 列 x 5000 行,含两个大字段,传输 15MB
99
+
100
+ -- 子查询中使用 SELECT *
101
+ SELECT * FROM (SELECT * FROM orders WHERE user_id = 100) sub
102
+ WHERE sub.status = 'completed';
103
+ ```
104
+
105
+ ```python
106
+ # Django -- 无意中加载所有字段
107
+ def product_list(request):
108
+ products = Product.objects.filter(category_id=5) # SELECT *
109
+ return JsonResponse([
110
+ {"name": p.name, "price": p.price} # 只用了 2 个字段
111
+ for p in products
112
+ ], safe=False)
113
+ ```
114
+
115
+ ### 正确示例
116
+ ```sql
117
+ -- 只查询需要的列
118
+ SELECT id, name, price, stock FROM products WHERE category_id = 5;
119
+
120
+ -- 覆盖索引生效
121
+ CREATE INDEX idx_products_category_covering
122
+ ON products (category_id) INCLUDE (id, name, price, stock);
123
+ -- Index Only Scan,无需回表
124
+ ```
125
+
126
+ ```python
127
+ # Django -- 使用 values / only / defer
128
+ def product_list(request):
129
+ products = Product.objects.filter(category_id=5).values("id", "name", "price")
130
+ # 或者 .only("id", "name", "price")
131
+ # 或者 .defer("description", "images")
132
+ return JsonResponse(list(products), safe=False)
133
+ ```
134
+
135
+ ---
136
+
137
+ ## 3. N+1 查询(N+1 Query Problem)
138
+
139
+ ### 描述
140
+ 先查主表获得 N 条记录,再对每条记录单独查关联表,共执行 N+1 次查询。列表页场景下 N 可达数百,接口响应时间线性增长。
141
+
142
+ ### 错误示例
143
+ ```python
144
+ # Django ORM -- 典型 N+1
145
+ def get_orders(request):
146
+ orders = Order.objects.all()[:100] # 1 次查询
147
+ result = []
148
+ for order in orders:
149
+ result.append({
150
+ "order_id": order.id,
151
+ "user_name": order.user.name, # 每次 1 次查询
152
+ "items_count": order.items.count(), # 每次 1 次查询
153
+ })
154
+ return result # 共 201 次查询
155
+ ```
156
+
157
+ ```javascript
158
+ // Prisma -- 典型 N+1
159
+ async function getArticles() {
160
+ const articles = await prisma.article.findMany({ take: 50 });
161
+ for (const article of articles) {
162
+ article.author = await prisma.user.findUnique({
163
+ where: { id: article.authorId },
164
+ });
165
+ article.tags = await prisma.tag.findMany({
166
+ where: { articleId: article.id },
167
+ });
168
+ }
169
+ return articles; // 共 101 次查询
170
+ }
171
+ ```
172
+
173
+ ### 正确示例
174
+ ```python
175
+ # Django -- select_related (FK/OneToOne) + prefetch_related (M2M/reverse FK)
176
+ def get_orders(request):
177
+ orders = (
178
+ Order.objects
179
+ .select_related("user")
180
+ .prefetch_related("items")
181
+ .all()[:100]
182
+ ) # 仅 2-3 次查询
183
+ result = [
184
+ {
185
+ "order_id": o.id,
186
+ "user_name": o.user.name,
187
+ "items_count": len(o.items.all()),
188
+ }
189
+ for o in orders
190
+ ]
191
+ return result
192
+ ```
193
+
194
+ ```javascript
195
+ // Prisma -- 使用 include 一次性加载
196
+ async function getArticles() {
197
+ const articles = await prisma.article.findMany({
198
+ take: 50,
199
+ include: {
200
+ author: true,
201
+ tags: true,
202
+ },
203
+ });
204
+ return articles; // 仅 1 次查询 (JOIN)
205
+ }
206
+ ```
207
+
208
+ ---
209
+
210
+ ## 4. 过度范式化(Over-Normalization)
211
+
212
+ ### 描述
213
+ 将数据拆分到过多的表中,导致简单的业务查询需要 5-10 个 JOIN,SQL 复杂度和执行时间剧增。在读多写少的场景中,适度冗余反而能大幅提升性能。
214
+
215
+ ### 错误示例
216
+ ```sql
217
+ -- 过度范式化:用户地址拆成 5 张表
218
+ SELECT u.name, s.name AS street, c.name AS city,
219
+ p.name AS province, co.name AS country
220
+ FROM users u
221
+ JOIN addresses a ON u.id = a.user_id
222
+ JOIN streets s ON a.street_id = s.id
223
+ JOIN cities c ON s.city_id = c.id
224
+ JOIN provinces p ON c.province_id = p.id
225
+ JOIN countries co ON p.country_id = co.id
226
+ WHERE u.id = 100;
227
+ -- 5 次 JOIN,执行计划复杂,维护成本高
228
+ ```
229
+
230
+ ### 正确示例
231
+ ```sql
232
+ -- 适度反范式化:将地址信息合并到一张表
233
+ CREATE TABLE user_addresses (
234
+ id SERIAL PRIMARY KEY,
235
+ user_id INTEGER NOT NULL REFERENCES users(id),
236
+ street VARCHAR(255) NOT NULL,
237
+ city VARCHAR(100) NOT NULL,
238
+ province VARCHAR(100) NOT NULL,
239
+ country VARCHAR(100) NOT NULL DEFAULT 'China',
240
+ postal_code VARCHAR(20),
241
+ is_default BOOLEAN DEFAULT FALSE,
242
+ CONSTRAINT idx_user_default UNIQUE (user_id, is_default) WHERE is_default = TRUE
243
+ );
244
+
245
+ -- 单次查询即可获取完整地址
246
+ SELECT u.name, a.street, a.city, a.province, a.country
247
+ FROM users u
248
+ JOIN user_addresses a ON u.id = a.user_id AND a.is_default = TRUE
249
+ WHERE u.id = 100;
250
+ ```
251
+
252
+ ### 反范式化适用场景判定
253
+ | 场景 | 是否适合反范式化 | 原因 |
254
+ |------|:---:|------|
255
+ | 读写比 > 10:1 的查询 | YES | 减少 JOIN,提升读取性能 |
256
+ | 报表/统计场景 | YES | 预计算聚合值避免实时大量 JOIN |
257
+ | 频繁变更的主数据 | NO | 冗余数据需要同步更新,容易不一致 |
258
+ | 事务一致性要求极高 | NO | 范式化能保证数据完整性 |
259
+
260
+ ---
261
+
262
+ ## 5. 不使用事务(Missing Transaction)
263
+
264
+ ### 描述
265
+ 涉及多表写操作时不使用事务,一旦中途失败会导致数据不一致。典型场景:转账、下单扣库存、注册同时创建关联数据。
266
+
267
+ ### 错误示例
268
+ ```python
269
+ # 转账 -- 无事务保护
270
+ def transfer(from_id, to_id, amount):
271
+ from_account = Account.objects.get(id=from_id)
272
+ to_account = Account.objects.get(id=to_id)
273
+
274
+ from_account.balance -= amount
275
+ from_account.save() # 扣款成功
276
+
277
+ # 如果这里抛异常,钱已扣但未到账!
278
+ to_account.balance += amount
279
+ to_account.save()
280
+
281
+ TransferLog.objects.create(
282
+ from_account=from_account,
283
+ to_account=to_account,
284
+ amount=amount,
285
+ )
286
+ ```
287
+
288
+ ```javascript
289
+ // 下单 -- 无事务保护
290
+ async function createOrder(userId, items) {
291
+ const order = await Order.create({ userId, status: "pending" });
292
+ for (const item of items) {
293
+ await OrderItem.create({ orderId: order.id, ...item });
294
+ // 如果这里失败,订单已创建但商品不全
295
+ await Product.decrement("stock", {
296
+ by: item.quantity,
297
+ where: { id: item.productId },
298
+ });
299
+ }
300
+ }
301
+ ```
302
+
303
+ ### 正确示例
304
+ ```python
305
+ # Django -- 使用 atomic 事务
306
+ from django.db import transaction
307
+
308
+ def transfer(from_id, to_id, amount):
309
+ with transaction.atomic():
310
+ from_account = Account.objects.select_for_update().get(id=from_id)
311
+ to_account = Account.objects.select_for_update().get(id=to_id)
312
+
313
+ if from_account.balance < amount:
314
+ raise InsufficientFundsError()
315
+
316
+ from_account.balance -= amount
317
+ from_account.save()
318
+
319
+ to_account.balance += amount
320
+ to_account.save()
321
+
322
+ TransferLog.objects.create(
323
+ from_account=from_account,
324
+ to_account=to_account,
325
+ amount=amount,
326
+ )
327
+ # 离开 with 块时自动 COMMIT,异常时自动 ROLLBACK
328
+ ```
329
+
330
+ ```javascript
331
+ // Prisma -- 使用 $transaction
332
+ async function createOrder(userId, items) {
333
+ return prisma.$transaction(async (tx) => {
334
+ const order = await tx.order.create({
335
+ data: { userId, status: "pending" },
336
+ });
337
+ for (const item of items) {
338
+ await tx.orderItem.create({
339
+ data: { orderId: order.id, ...item },
340
+ });
341
+ const product = await tx.product.update({
342
+ where: { id: item.productId },
343
+ data: { stock: { decrement: item.quantity } },
344
+ });
345
+ if (product.stock < 0) {
346
+ throw new Error(`Insufficient stock: ${item.productId}`);
347
+ }
348
+ }
349
+ return order;
350
+ });
351
+ }
352
+ ```
353
+
354
+ ---
355
+
356
+ ## 6. 硬删除(Hard Delete)
357
+
358
+ ### 描述
359
+ 直接 DELETE 数据,无法审计、无法恢复、可能违反合规要求。在有外键关联的场景下还会触发级联删除,造成大量数据丢失。
360
+
361
+ ### 错误示例
362
+ ```sql
363
+ -- 直接删除用户及关联数据
364
+ DELETE FROM users WHERE id = 100;
365
+ -- 如果有 ON DELETE CASCADE,订单/评论/收藏全部消失
366
+
367
+ -- 批量清理过期数据
368
+ DELETE FROM sessions WHERE expired_at < NOW();
369
+ -- 百万行删除可能锁表数分钟
370
+ ```
371
+
372
+ ```python
373
+ # Django -- 硬删除
374
+ def delete_user(request, user_id):
375
+ user = User.objects.get(id=user_id)
376
+ user.delete() # 永久删除,无法恢复
377
+ return JsonResponse({"status": "deleted"})
378
+ ```
379
+
380
+ ### 正确示例
381
+ ```sql
382
+ -- 软删除方案
383
+ ALTER TABLE users ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
384
+ CREATE INDEX idx_users_active ON users (id) WHERE deleted_at IS NULL;
385
+
386
+ -- "删除" 操作
387
+ UPDATE users SET deleted_at = NOW() WHERE id = 100;
388
+
389
+ -- 查询时自动过滤已删除记录
390
+ SELECT * FROM users WHERE deleted_at IS NULL AND email = 'alice@example.com';
391
+ ```
392
+
393
+ ```python
394
+ # Django -- 软删除 Mixin
395
+ class SoftDeleteMixin(models.Model):
396
+ deleted_at = models.DateTimeField(null=True, blank=True, db_index=True)
397
+
398
+ class Meta:
399
+ abstract = True
400
+
401
+ def soft_delete(self):
402
+ self.deleted_at = timezone.now()
403
+ self.save(update_fields=["deleted_at"])
404
+
405
+ def restore(self):
406
+ self.deleted_at = None
407
+ self.save(update_fields=["deleted_at"])
408
+
409
+ class SoftDeleteManager(models.Manager):
410
+ def get_queryset(self):
411
+ return super().get_queryset().filter(deleted_at__isnull=True)
412
+
413
+ class User(SoftDeleteMixin):
414
+ objects = SoftDeleteManager() # 默认排除已删除
415
+ all_objects = models.Manager() # 包含已删除(管理员用)
416
+ email = models.EmailField(unique=True)
417
+ name = models.CharField(max_length=100)
418
+ ```
419
+
420
+ ### 大批量删除的正确做法
421
+ ```sql
422
+ -- 分批删除,避免长时间锁表
423
+ DO $$
424
+ DECLARE
425
+ batch_size INT := 5000;
426
+ deleted_count INT;
427
+ BEGIN
428
+ LOOP
429
+ DELETE FROM sessions
430
+ WHERE id IN (
431
+ SELECT id FROM sessions
432
+ WHERE expired_at < NOW() - INTERVAL '30 days'
433
+ LIMIT batch_size
434
+ );
435
+ GET DIAGNOSTICS deleted_count = ROW_COUNT;
436
+ EXIT WHEN deleted_count = 0;
437
+ PERFORM pg_sleep(0.1); -- 释放锁,让其他查询通过
438
+ END LOOP;
439
+ END $$;
440
+ ```
441
+
442
+ ---
443
+
444
+ ## 7. 无分页查询(Missing Pagination)
445
+
446
+ ### 描述
447
+ 一次性返回全部记录,当数据量增长到万级以上时,接口响应缓慢、内存溢出、前端渲染卡死。
448
+
449
+ ### 错误示例
450
+ ```python
451
+ # 返回所有产品 -- 数据量增长后必崩
452
+ def product_list(request):
453
+ products = Product.objects.all() # 可能返回 10 万条
454
+ return JsonResponse(
455
+ [{"id": p.id, "name": p.name} for p in products],
456
+ safe=False,
457
+ )
458
+ ```
459
+
460
+ ```sql
461
+ -- 无限制查询
462
+ SELECT * FROM logs ORDER BY created_at DESC;
463
+ -- 日志表 500 万行,直接打满内存
464
+ ```
465
+
466
+ ### 正确示例
467
+ ```python
468
+ # Offset 分页(适合页数不多的场景)
469
+ from django.core.paginator import Paginator
470
+
471
+ def product_list(request):
472
+ page_num = int(request.GET.get("page", 1))
473
+ page_size = min(int(request.GET.get("size", 20)), 100) # 上限 100
474
+
475
+ products = Product.objects.order_by("-created_at")
476
+ paginator = Paginator(products, page_size)
477
+ page = paginator.get_page(page_num)
478
+
479
+ return JsonResponse({
480
+ "data": [{"id": p.id, "name": p.name} for p in page],
481
+ "total": paginator.count,
482
+ "page": page.number,
483
+ "pages": paginator.num_pages,
484
+ })
485
+ ```
486
+
487
+ ```python
488
+ # 游标分页(适合深翻页 / 无限滚动)
489
+ def product_list_cursor(request):
490
+ cursor = request.GET.get("cursor") # 上一页最后一条的 id
491
+ page_size = min(int(request.GET.get("size", 20)), 100)
492
+
493
+ qs = Product.objects.order_by("-id")
494
+ if cursor:
495
+ qs = qs.filter(id__lt=cursor)
496
+ products = list(qs[:page_size + 1])
497
+
498
+ has_next = len(products) > page_size
499
+ products = products[:page_size]
500
+
501
+ return JsonResponse({
502
+ "data": [{"id": p.id, "name": p.name} for p in products],
503
+ "next_cursor": products[-1].id if has_next else None,
504
+ })
505
+ ```
506
+
507
+ ```sql
508
+ -- Keyset 分页(数据库层面,性能稳定)
509
+ SELECT id, name, price
510
+ FROM products
511
+ WHERE id < 10050 -- 上一页最后一条 ID
512
+ ORDER BY id DESC
513
+ LIMIT 20;
514
+ -- 无论翻到第几页,执行时间恒定 ~1ms
515
+ ```
516
+
517
+ ---
518
+
519
+ ## 8. 不使用连接池(Missing Connection Pool)
520
+
521
+ ### 描述
522
+ 每次请求创建新的数据库连接,建立 TCP + TLS + 认证的开销约 50-100ms。在并发场景下,连接数暴涨可能打满数据库的 `max_connections`(PostgreSQL 默认 100),导致全站不可用。
523
+
524
+ ### 错误示例
525
+ ```python
526
+ # 每次请求创建新连接
527
+ import psycopg2
528
+
529
+ def get_user(user_id):
530
+ conn = psycopg2.connect(
531
+ host="localhost", dbname="myapp",
532
+ user="app", password="secret"
533
+ )
534
+ cursor = conn.cursor()
535
+ cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
536
+ user = cursor.fetchone()
537
+ conn.close() # 关闭后下次又要重建
538
+ return user
539
+ ```
540
+
541
+ ```javascript
542
+ // Node.js -- 每次创建新连接
543
+ const { Client } = require("pg");
544
+
545
+ async function getUser(userId) {
546
+ const client = new Client({ connectionString: DATABASE_URL });
547
+ await client.connect(); // 50-100ms 开销
548
+ const res = await client.query("SELECT * FROM users WHERE id = $1", [userId]);
549
+ await client.end();
550
+ return res.rows[0];
551
+ }
552
+ ```
553
+
554
+ ### 正确示例
555
+ ```python
556
+ # psycopg2 连接池
557
+ from psycopg2 import pool
558
+
559
+ # 应用启动时创建连接池(单例)
560
+ db_pool = pool.ThreadedConnectionPool(
561
+ minconn=5,
562
+ maxconn=20,
563
+ host="localhost",
564
+ dbname="myapp",
565
+ user="app",
566
+ password="secret",
567
+ )
568
+
569
+ def get_user(user_id):
570
+ conn = db_pool.getconn()
571
+ try:
572
+ cursor = conn.cursor()
573
+ cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
574
+ return cursor.fetchone()
575
+ finally:
576
+ db_pool.putconn(conn) # 归还连接,不关闭
577
+ ```
578
+
579
+ ```javascript
580
+ // Node.js -- 使用连接池
581
+ const { Pool } = require("pg");
582
+
583
+ const pool = new Pool({
584
+ connectionString: DATABASE_URL,
585
+ max: 20, // 最大连接数
586
+ idleTimeoutMillis: 30000,
587
+ connectionTimeoutMillis: 5000,
588
+ });
589
+
590
+ async function getUser(userId) {
591
+ const res = await pool.query("SELECT * FROM users WHERE id = $1", [userId]);
592
+ return res.rows[0]; // 自动从池中获取/归还连接
593
+ }
594
+ ```
595
+
596
+ ### 连接池参数调优指南
597
+ | 参数 | 推荐值 | 说明 |
598
+ |------|--------|------|
599
+ | `max_connections` | CPU 核数 x 2 + 磁盘数 | PostgreSQL 官方建议 |
600
+ | `pool_size` | 5-20 | 应用侧每个进程的池大小 |
601
+ | `max_overflow` | 10 | 突发流量时允许的额外连接 |
602
+ | `pool_recycle` | 3600 | 连接最大存活时间(秒),防止连接泄漏 |
603
+ | `pool_pre_ping` | True | 使用前检查连接是否存活 |
604
+
605
+ ---
606
+
607
+ ## 9. 未优化的 JOIN(Inefficient JOIN)
608
+
609
+ ### 描述
610
+ 在大表上执行笛卡尔积 JOIN、缺少 JOIN 条件、JOIN 列无索引、或在 JOIN 结果上再做全表排序,导致查询时间从毫秒级膨胀到分钟级。
611
+
612
+ ### 错误示例
613
+ ```sql
614
+ -- 缺少 JOIN 条件,产生笛卡尔积
615
+ SELECT u.name, o.total
616
+ FROM users u, orders o;
617
+ -- 1万用户 x 10万订单 = 10亿行结果
618
+
619
+ -- JOIN 列无索引
620
+ SELECT u.name, o.total, o.created_at
621
+ FROM users u
622
+ JOIN orders o ON o.user_id = u.id
623
+ WHERE o.created_at > '2024-01-01'
624
+ ORDER BY o.total DESC;
625
+ -- orders.user_id 无索引 -> Nested Loop + Seq Scan
626
+
627
+ -- 多表 JOIN 顺序不当
628
+ SELECT *
629
+ FROM order_items oi -- 500 万行
630
+ JOIN products p ON oi.product_id = p.id -- 10 万行
631
+ JOIN orders o ON oi.order_id = o.id -- 100 万行
632
+ JOIN users u ON o.user_id = u.id -- 10 万行
633
+ WHERE u.country = 'CN'
634
+ AND p.category = 'electronics';
635
+ -- 应该先过滤再 JOIN
636
+ ```
637
+
638
+ ### 正确示例
639
+ ```sql
640
+ -- 确保 JOIN 列有索引
641
+ CREATE INDEX idx_orders_user_id ON orders (user_id);
642
+ CREATE INDEX idx_orders_created_at ON orders (created_at);
643
+ CREATE INDEX idx_order_items_order_id ON order_items (order_id);
644
+ CREATE INDEX idx_order_items_product_id ON order_items (product_id);
645
+
646
+ -- 使用子查询先过滤,减少 JOIN 的数据量
647
+ SELECT u.name, o.total, o.created_at
648
+ FROM users u
649
+ JOIN (
650
+ SELECT user_id, total, created_at
651
+ FROM orders
652
+ WHERE created_at > '2024-01-01'
653
+ ORDER BY total DESC
654
+ LIMIT 100
655
+ ) o ON o.user_id = u.id;
656
+
657
+ -- 使用 CTE 拆分复杂查询
658
+ WITH target_users AS (
659
+ SELECT id, name FROM users WHERE country = 'CN'
660
+ ),
661
+ target_products AS (
662
+ SELECT id, name FROM products WHERE category = 'electronics'
663
+ )
664
+ SELECT tu.name AS user_name, tp.name AS product_name,
665
+ oi.quantity, oi.price
666
+ FROM order_items oi
667
+ JOIN target_products tp ON oi.product_id = tp.id
668
+ JOIN orders o ON oi.order_id = o.id
669
+ JOIN target_users tu ON o.user_id = tu.id;
670
+ ```
671
+
672
+ ---
673
+
674
+ ## 10. 缺少备份策略(Missing Backup)
675
+
676
+ ### 描述
677
+ 没有定期备份、没有验证备份可恢复、备份与主库在同一台机器上。一旦发生硬件故障、误操作或勒索攻击,数据永久丢失。
678
+
679
+ ### 错误示例
680
+ ```bash
681
+ # "我们有备份" -- 备份在同一台机器
682
+ pg_dump mydb > /var/lib/postgresql/backup.sql
683
+ # 磁盘故障 -> 主库和备份同时丢失
684
+
685
+ # 从不测试恢复
686
+ # 3 年前设置的 cron 备份任务,从未验证过
687
+ # 某天需要恢复时发现:备份文件损坏 / 格式不兼容 / 缺少依赖
688
+ ```
689
+
690
+ ### 正确示例
691
+ ```bash
692
+ #!/bin/bash
693
+ # backup.sh -- 生产级备份脚本
694
+
695
+ set -euo pipefail
696
+
697
+ DB_NAME="myapp_prod"
698
+ BACKUP_DIR="/mnt/nfs/backups/postgres"
699
+ S3_BUCKET="s3://myapp-backups/postgres"
700
+ RETENTION_DAYS=30
701
+ DATE=$(date +%Y%m%d_%H%M%S)
702
+
703
+ # 1. 创建压缩备份
704
+ pg_dump -Fc -Z 9 "$DB_NAME" > "${BACKUP_DIR}/${DB_NAME}_${DATE}.dump"
705
+
706
+ # 2. 上传到异地存储
707
+ aws s3 cp "${BACKUP_DIR}/${DB_NAME}_${DATE}.dump" \
708
+ "${S3_BUCKET}/${DB_NAME}_${DATE}.dump" \
709
+ --storage-class STANDARD_IA
710
+
711
+ # 3. 验证备份可恢复
712
+ pg_restore --list "${BACKUP_DIR}/${DB_NAME}_${DATE}.dump" > /dev/null 2>&1
713
+ if [ $? -ne 0 ]; then
714
+ echo "ALERT: Backup verification failed!" | \
715
+ mail -s "Backup Failed: ${DB_NAME}" ops@example.com
716
+ exit 1
717
+ fi
718
+
719
+ # 4. 清理过期本地备份
720
+ find "$BACKUP_DIR" -name "*.dump" -mtime +${RETENTION_DAYS} -delete
721
+
722
+ echo "Backup completed: ${DB_NAME}_${DATE}.dump"
723
+ ```
724
+
725
+ ```yaml
726
+ # PostgreSQL 持续归档 (WAL + PITR)
727
+ # postgresql.conf
728
+ archive_mode: "on"
729
+ archive_command: 'aws s3 cp %p s3://myapp-wal-archive/%f'
730
+ wal_level: replica
731
+
732
+ # 恢复到指定时间点
733
+ # recovery.conf
734
+ restore_command = 'aws s3 cp s3://myapp-wal-archive/%f %p'
735
+ recovery_target_time = '2024-06-15 14:30:00'
736
+ recovery_target_action = 'promote'
737
+ ```
738
+
739
+ ### 备份策略矩阵
740
+ | 备份类型 | 频率 | RPO | 存储位置 | 用途 |
741
+ |---------|------|-----|---------|------|
742
+ | 逻辑备份 (pg_dump) | 每日 | 24h | 异地 S3 | 完整恢复 / 迁移 |
743
+ | WAL 归档 (PITR) | 持续 | ~5min | 异地 S3 | 时间点恢复 |
744
+ | 物理备份 (pg_basebackup) | 每周 | 7d | 异地存储 | 快速全量恢复 |
745
+ | 流复制 (Streaming Replica) | 实时 | ~0s | 异地机房 | 高可用故障转移 |
746
+
747
+ ---
748
+
749
+ ## 11. 明文存储敏感数据(Plaintext Sensitive Data)
750
+
751
+ ### 描述
752
+ 密码、身份证号、银行卡号等敏感数据以明文存储在数据库中。一旦数据库被拖库或备份泄漏,所有用户信息直接暴露。违反 GDPR / 等保 / PCI-DSS 等合规要求。
753
+
754
+ ### 错误示例
755
+ ```sql
756
+ -- 密码明文存储
757
+ CREATE TABLE users (
758
+ id SERIAL PRIMARY KEY,
759
+ email VARCHAR(255) NOT NULL,
760
+ password VARCHAR(255) NOT NULL, -- 'P@ssw0rd123' 明文!
761
+ id_card VARCHAR(18), -- '310101199001011234' 明文!
762
+ bank_card VARCHAR(19) -- '6222021234567890123' 明文!
763
+ );
764
+
765
+ INSERT INTO users (email, password, id_card)
766
+ VALUES ('alice@example.com', 'P@ssw0rd123', '310101199001011234');
767
+ ```
768
+
769
+ ```python
770
+ # 应用层 -- 明文比对密码
771
+ def login(email, password):
772
+ user = User.objects.get(email=email)
773
+ if user.password == password: # 直接比对明文
774
+ return create_token(user)
775
+ raise AuthError("Invalid credentials")
776
+ ```
777
+
778
+ ### 正确示例
779
+ ```python
780
+ # 密码 -- 使用 bcrypt 哈希
781
+ import bcrypt
782
+
783
+ def register(email, password):
784
+ salt = bcrypt.gensalt(rounds=12)
785
+ hashed = bcrypt.hashpw(password.encode(), salt)
786
+ User.objects.create(
787
+ email=email,
788
+ password_hash=hashed.decode(), # '$2b$12$...' 存储哈希值
789
+ )
790
+
791
+ def login(email, password):
792
+ user = User.objects.get(email=email)
793
+ if bcrypt.checkpw(password.encode(), user.password_hash.encode()):
794
+ return create_token(user)
795
+ raise AuthError("Invalid credentials")
796
+ ```
797
+
798
+ ```python
799
+ # 敏感字段 -- 使用 AES 加密
800
+ from cryptography.fernet import Fernet
801
+
802
+ # 密钥从 KMS / Vault 获取,不硬编码
803
+ ENCRYPTION_KEY = get_key_from_vault("user-data-key")
804
+ cipher = Fernet(ENCRYPTION_KEY)
805
+
806
+ def save_id_card(user_id, id_card):
807
+ encrypted = cipher.encrypt(id_card.encode()).decode()
808
+ UserSensitive.objects.update_or_create(
809
+ user_id=user_id,
810
+ defaults={"id_card_encrypted": encrypted},
811
+ )
812
+
813
+ def get_id_card(user_id):
814
+ record = UserSensitive.objects.get(user_id=user_id)
815
+ return cipher.decrypt(record.id_card_encrypted.encode()).decode()
816
+ ```
817
+
818
+ ```sql
819
+ -- PostgreSQL -- 使用 pgcrypto 扩展
820
+ CREATE EXTENSION IF NOT EXISTS pgcrypto;
821
+
822
+ -- 密码哈希
823
+ INSERT INTO users (email, password_hash)
824
+ VALUES ('alice@example.com', crypt('P@ssw0rd123', gen_salt('bf', 12)));
825
+
826
+ -- 验证密码
827
+ SELECT id FROM users
828
+ WHERE email = 'alice@example.com'
829
+ AND password_hash = crypt('P@ssw0rd123', password_hash);
830
+
831
+ -- 字段加密
832
+ INSERT INTO user_sensitive (user_id, id_card_encrypted)
833
+ VALUES (1, pgp_sym_encrypt('310101199001011234', 'encryption-key'));
834
+
835
+ -- 解密
836
+ SELECT pgp_sym_decrypt(id_card_encrypted::bytea, 'encryption-key')
837
+ FROM user_sensitive WHERE user_id = 1;
838
+ ```
839
+
840
+ ---
841
+
842
+ ## 反模式速查矩阵
843
+
844
+ | # | 反模式 | 风险等级 | 检测时机 | 检测工具 |
845
+ |---|--------|:-------:|---------|---------|
846
+ | 1 | 无索引查询 | HIGH | CI/CD + Review | pg_stat_user_tables / EXPLAIN |
847
+ | 2 | SELECT * | MEDIUM | Lint + Review | sqlfluff / eslint-plugin-sql |
848
+ | 3 | N+1 查询 | HIGH | APM + Review | django-debug-toolbar / Prisma logging |
849
+ | 4 | 过度范式化 | MEDIUM | 架构评审 | ER 图审查 |
850
+ | 5 | 不用事务 | CRITICAL | Review | 静态分析 + 代码规范 |
851
+ | 6 | 硬删除 | HIGH | Review | 模型审查 |
852
+ | 7 | 无分页 | HIGH | API Review | API 规范检查 |
853
+ | 8 | 不用连接池 | HIGH | 架构评审 | 连接数监控 |
854
+ | 9 | 未优化 JOIN | MEDIUM | Slow Query Log | EXPLAIN ANALYZE |
855
+ | 10 | 缺少备份 | CRITICAL | 运维审计 | 备份监控 |
856
+ | 11 | 明文存储 | CRITICAL | 安全审计 | 数据分类扫描 |
857
+
858
+ ---
859
+
860
+ ## Agent Checklist
861
+
862
+ - [ ] 所有 SQL 查询的 WHERE / JOIN / ORDER BY 列已创建索引
863
+ - [ ] 代码中无 `SELECT *`,所有查询只返回必要字段
864
+ - [ ] ORM 查询已使用 eager loading 消除 N+1 问题
865
+ - [ ] 范式化程度适当,读多写少的场景已考虑反范式化
866
+ - [ ] 所有多表写操作包裹在事务中
867
+ - [ ] 业务数据使用软删除,硬删除有审批流程
868
+ - [ ] 所有列表接口实现分页,单页上限不超过 100
869
+ - [ ] 使用数据库连接池,连接参数已调优
870
+ - [ ] 复杂 JOIN 已通过 EXPLAIN ANALYZE 验证执行计划
871
+ - [ ] 备份策略覆盖逻辑备份 + WAL 归档,备份已验证可恢复
872
+ - [ ] 密码使用 bcrypt/argon2 哈希,敏感字段使用 AES 加密
873
+ - [ ] 加密密钥从 KMS / Vault 获取,不硬编码在代码或配置中