@gordon.gan/specflow 1.3.3-beta → 1.4.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 (85) hide show
  1. package/README.md +6 -2
  2. package/dist/integrations/shared/capability-evidence.js +37 -1
  3. package/dist/integrations/shared/command-catalog.js +1 -0
  4. package/dist/integrations/shared/parity-manifest.js +6 -0
  5. package/package.json +1 -1
  6. package/prompts/approval/database-guidance.md +79 -0
  7. package/prompts/approval/generate.md +1191 -0
  8. package/skills/database/LICENSE +405 -0
  9. package/skills/database/ORIGIN.md +6 -0
  10. package/skills/database/README.md +30 -0
  11. package/skills/database/elasticsearch/LICENSE.txt +202 -0
  12. package/skills/database/elasticsearch/SKILL.md +199 -0
  13. package/skills/database/elasticsearch/examples/01-fulltext-search.md +215 -0
  14. package/skills/database/elasticsearch/examples/02-aggregation-report.md +206 -0
  15. package/skills/database/elasticsearch/examples/03-reindex-zero-downtime.md +200 -0
  16. package/skills/database/elasticsearch/examples/04-cluster-monitoring.md +204 -0
  17. package/skills/database/elasticsearch/references/01-query-dsl-fulltext.md +162 -0
  18. package/skills/database/elasticsearch/references/02-query-dsl-term.md +210 -0
  19. package/skills/database/elasticsearch/references/03-aggregations-metric.md +161 -0
  20. package/skills/database/elasticsearch/references/04-aggregations-bucket.md +236 -0
  21. package/skills/database/elasticsearch/references/05-mapping-types.md +134 -0
  22. package/skills/database/elasticsearch/references/06-analyzers.md +187 -0
  23. package/skills/database/elasticsearch/references/07-cluster-ops.md +225 -0
  24. package/skills/database/elasticsearch/references/08-elk-integration.md +170 -0
  25. package/skills/database/mysql/SKILL.md +195 -0
  26. package/skills/database/mysql/examples/01-connection-pool.md +75 -0
  27. package/skills/database/mysql/examples/02-slow-query-optimization.md +98 -0
  28. package/skills/database/mysql/examples/03-master-slave-setup.md +144 -0
  29. package/skills/database/mysql/examples/04-backup-strategy.md +212 -0
  30. package/skills/database/mysql/references/01-functions-string.md +103 -0
  31. package/skills/database/mysql/references/02-functions-date.md +152 -0
  32. package/skills/database/mysql/references/03-functions-aggregate-window.md +167 -0
  33. package/skills/database/mysql/references/04-functions-json.md +129 -0
  34. package/skills/database/mysql/references/05-sql-ddl-types.md +235 -0
  35. package/skills/database/mysql/references/06-index-optimization.md +232 -0
  36. package/skills/database/mysql/references/07-replication-ha.md +213 -0
  37. package/skills/database/mysql/references/08-backup-restore.md +207 -0
  38. package/skills/database/mysql/references/09-advanced-features.md +345 -0
  39. package/skills/database/oracle/LICENSE.txt +202 -0
  40. package/skills/database/oracle/SKILL.md +238 -0
  41. package/skills/database/oracle/examples/01-plsql-procedure.md +90 -0
  42. package/skills/database/oracle/examples/02-awr-analysis.md +99 -0
  43. package/skills/database/oracle/examples/03-rman-backup.md +108 -0
  44. package/skills/database/oracle/examples/04-dataguard-setup.md +146 -0
  45. package/skills/database/oracle/references/01-functions-string.md +91 -0
  46. package/skills/database/oracle/references/02-functions-date.md +71 -0
  47. package/skills/database/oracle/references/03-analytic-functions.md +103 -0
  48. package/skills/database/oracle/references/04-plsql-guide.md +303 -0
  49. package/skills/database/oracle/references/05-performance-tuning.md +164 -0
  50. package/skills/database/oracle/references/06-backup-recovery.md +115 -0
  51. package/skills/database/oracle/references/07-dataguard-rac.md +76 -0
  52. package/skills/database/oracle/references/08-security.md +170 -0
  53. package/skills/database/oracle/references/09-sql-syntax.md +152 -0
  54. package/skills/database/oracle/references/10-features.md +174 -0
  55. package/skills/database/postgresql/LICENSE.txt +202 -0
  56. package/skills/database/postgresql/SKILL.md +182 -0
  57. package/skills/database/postgresql/examples/.gitkeep +0 -0
  58. package/skills/database/postgresql/examples/01-jsonb-query.md +72 -0
  59. package/skills/database/postgresql/examples/02-cte-recursive.md +110 -0
  60. package/skills/database/postgresql/examples/03-performance-tuning.md +114 -0
  61. package/skills/database/postgresql/examples/04-streaming-replication.md +113 -0
  62. package/skills/database/postgresql/references/.gitkeep +0 -0
  63. package/skills/database/postgresql/references/01-functions-string.md +174 -0
  64. package/skills/database/postgresql/references/02-functions-datetime.md +54 -0
  65. package/skills/database/postgresql/references/03-functions-aggregate-window.md +142 -0
  66. package/skills/database/postgresql/references/04-functions-jsonb.md +117 -0
  67. package/skills/database/postgresql/references/05-fulltext-search.md +109 -0
  68. package/skills/database/postgresql/references/06-index-types.md +95 -0
  69. package/skills/database/postgresql/references/07-partition-fdw.md +133 -0
  70. package/skills/database/postgresql/references/08-replication-backup.md +215 -0
  71. package/skills/database/redis/LICENSE.txt +202 -0
  72. package/skills/database/redis/SKILL.md +922 -0
  73. package/skills/database/redis/examples/01-cache-usage.md +104 -0
  74. package/skills/database/redis/examples/02-session-storage.md +72 -0
  75. package/skills/database/redis/examples/03-leaderboard.md +63 -0
  76. package/skills/database/redis/examples/04-redis-cluster-setup.md +70 -0
  77. package/skills/database/redis/examples/05-stream-queue.md +65 -0
  78. package/skills/database/redis/references/command-quick-ref.md +180 -0
  79. package/skills/database/redis/references/commands-admin-key.md +413 -0
  80. package/skills/database/redis/references/commands-set-sorted-advanced.md +539 -0
  81. package/skills/database/redis/references/commands-string-hash-list.md +458 -0
  82. package/skills/database/redis/references/memory-optimization.md +150 -0
  83. package/skills/database/redis/references/redis-conf-production.md +139 -0
  84. package/skills/specflow-approval/SKILL.md +427 -0
  85. package/templates/approval.md +464 -0
@@ -0,0 +1,174 @@
1
+ # Oracle 特有特性 — 分区 / 索引 / 物化视图 / Flashback / AQ
2
+
3
+ ## 表空间与数据文件
4
+
5
+ ```sql
6
+ -- 创建表空间
7
+ CREATE TABLESPACE tbs_app_data
8
+ DATAFILE '/u01/oradata/orcl/app_data01.dbf' SIZE 10G
9
+ AUTOEXTEND ON NEXT 1G MAXSIZE 32G;
10
+
11
+ -- 创建临时/撤销表空间
12
+ CREATE TEMPORARY TABLESPACE tbs_app_temp TEMPFILE '/u01/oradata/orcl/app_temp01.dbf' SIZE 5G;
13
+ CREATE UNDO TABLESPACE tbs_app_undo DATAFILE '/u01/oradata/orcl/app_undo01.dbf' SIZE 10G;
14
+
15
+ -- 表空间管理
16
+ ALTER TABLESPACE tbs_app_data ADD DATAFILE '/u01/oradata/orcl/app_data02.dbf' SIZE 10G;
17
+ ALTER TABLESPACE tbs_app_data READ ONLY;
18
+ ALTER TABLESPACE tbs_app_data OFFLINE NORMAL;
19
+
20
+ -- 表空间使用率
21
+ SELECT df.tablespace_name,
22
+ ROUND(df.bytes/1024/1024/1024,2) AS total_gb,
23
+ ROUND((1-fs.bytes/df.bytes)*100,2) AS used_pct
24
+ FROM (SELECT tablespace_name, SUM(bytes) AS bytes FROM dba_data_files GROUP BY tablespace_name) df
25
+ JOIN (SELECT tablespace_name, SUM(bytes) AS bytes FROM dba_free_space GROUP BY tablespace_name) fs
26
+ ON df.tablespace_name = fs.tablespace_name;
27
+ ```
28
+
29
+ ## 分区表
30
+
31
+ ```sql
32
+ -- RANGE 分区
33
+ CREATE TABLE sales (
34
+ sale_id NUMBER(10), sale_date DATE, amount NUMBER(10,2)
35
+ ) PARTITION BY RANGE (sale_date) (
36
+ PARTITION p_2023_q1 VALUES LESS THAN (DATE '2023-04-01'),
37
+ PARTITION p_2023_q2 VALUES LESS THAN (DATE '2023-07-01'),
38
+ PARTITION p_future VALUES LESS THAN (MAXVALUE)
39
+ );
40
+
41
+ -- LIST 分区
42
+ CREATE TABLE customers PARTITION BY LIST (region) (
43
+ PARTITION p_north VALUES ('北京','天津','河北'),
44
+ PARTITION p_east VALUES ('上海','江苏','浙江'),
45
+ PARTITION p_other VALUES (DEFAULT)
46
+ );
47
+
48
+ -- HASH 分区
49
+ CREATE TABLE logs PARTITION BY HASH (log_id) PARTITIONS 8;
50
+
51
+ -- 复合分区(RANGE-HASH)
52
+ CREATE TABLE sales_comp PARTITION BY RANGE (sale_date)
53
+ SUBPARTITION BY HASH (region) SUBPARTITIONS 4 (
54
+ PARTITION p_2023_q1 VALUES LESS THAN (DATE '2023-04-01')
55
+ );
56
+
57
+ -- 间隔分区(11g+ 自动建分区)
58
+ CREATE TABLE sales_interval PARTITION BY RANGE (sale_date)
59
+ INTERVAL(NUMTOYMINTERVAL(1,'MONTH')) (
60
+ PARTITION p_first VALUES LESS THAN (DATE '2023-01-01')
61
+ );
62
+
63
+ -- 分区操作
64
+ ALTER TABLE sales ADD PARTITION p_2024_q1 VALUES LESS THAN (DATE '2024-04-01');
65
+ ALTER TABLE sales TRUNCATE PARTITION p_future;
66
+ ALTER TABLE sales EXCHANGE PARTITION p_2023_q1 WITH TABLE sales_2023_q1;
67
+ ALTER TABLE sales MERGE PARTITIONS p_2023_q1, p_2023_q2 INTO PARTITION p_2023_h1;
68
+ ALTER TABLE sales SPLIT PARTITION p_future AT (DATE '2024-04-01')
69
+ INTO (PARTITION p_2024_q1, PARTITION p_future);
70
+ ```
71
+
72
+ ## 索引
73
+
74
+ ```sql
75
+ -- B-Tree 索引(默认)
76
+ CREATE INDEX idx_emp_dept_id ON employees(department_id);
77
+ CREATE INDEX idx_emp_dept_name ON employees(department_id, last_name); -- 复合
78
+ CREATE UNIQUE INDEX idx_emp_email ON employees(email); -- 唯一
79
+
80
+ -- 位图索引(适合低基数、数据仓库)
81
+ CREATE BITMAP INDEX idx_sales_region ON sales(region);
82
+
83
+ -- 函数索引
84
+ CREATE INDEX idx_emp_upper_name ON employees(UPPER(last_name));
85
+
86
+ -- 域索引(Oracle Text 全文)
87
+ CREATE INDEX idx_docs_content ON documents(content) INDEXTYPE IS CTXSYS.CONTEXT;
88
+
89
+ -- 索引监控
90
+ ALTER INDEX idx_emp_dept_id MONITORING USAGE;
91
+ SELECT * FROM v$object_usage; -- 查看未被使用的索引
92
+ ```
93
+
94
+ ## 物化视图
95
+
96
+ ```sql
97
+ -- 基本物化视图
98
+ CREATE MATERIALIZED VIEW mv_dept_salary_summary
99
+ BUILD IMMEDIATE REFRESH COMPLETE ON DEMAND ENABLE QUERY REWRITE
100
+ AS SELECT d.department_id, d.department_name,
101
+ COUNT(e.employee_id) AS emp_count, SUM(e.salary) AS total_salary
102
+ FROM departments d LEFT JOIN employees e ON d.department_id = e.department_id
103
+ GROUP BY d.department_id, d.department_name;
104
+
105
+ -- 快速刷新物化视图(需物化视图日志)
106
+ CREATE MATERIALIZED VIEW LOG ON employees WITH PRIMARY KEY, ROWID (salary, department_id) INCLUDING NEW VALUES;
107
+ CREATE MATERIALIZED VIEW mv_emp_fast
108
+ BUILD IMMEDIATE REFRESH FAST ON COMMIT
109
+ AS SELECT department_id, COUNT(*) AS cnt, SUM(salary) AS total_sal
110
+ FROM employees GROUP BY department_id;
111
+
112
+ -- 刷新
113
+ EXEC DBMS_MVIEW.REFRESH('mv_dept_salary_summary', 'C'); -- C=完全, F=快速
114
+ ALTER SESSION SET QUERY_REWRITE_ENABLED = TRUE;
115
+ ```
116
+
117
+ ## Flashback 技术
118
+
119
+ ```sql
120
+ -- Flashback Query — 见 references/09-sql-syntax.md
121
+
122
+ -- Flashback Table(需启用行移动)
123
+ ALTER TABLE employees ENABLE ROW MOVEMENT;
124
+ FLASHBACK TABLE employees TO TIMESTAMP (SYSTIMESTAMP - INTERVAL '15' MINUTE);
125
+ FLASHBACK TABLE employees TO SCN 1234567;
126
+ FLASHBACK TABLE employees TO RESTORE POINT before_batch;
127
+
128
+ -- Flashback Drop(回收站)
129
+ DROP TABLE employees;
130
+ SELECT object_name, original_name, droptime FROM recyclebin;
131
+ FLASHBACK TABLE employees TO BEFORE DROP;
132
+
133
+ -- Flashback Database(需启用闪回日志)
134
+ -- FLASHBACK DATABASE TO TIMESTAMP (SYSTIMESTAMP - INTERVAL '1' HOUR);
135
+ ```
136
+
137
+ ## AQ(Advanced Queuing)— 高级队列
138
+
139
+ ```sql
140
+ -- 创建类型和队列表
141
+ CREATE OR REPLACE TYPE order_msg AS OBJECT (order_id NUMBER, customer_id NUMBER, amount NUMBER);
142
+ /
143
+ BEGIN
144
+ DBMS_AQADM.CREATE_QUEUE_TABLE(queue_table => 'order_queue_table', queue_payload_type => 'order_msg');
145
+ DBMS_AQADM.CREATE_QUEUE(queue_name => 'order_queue', queue_table => 'order_queue_table');
146
+ DBMS_AQADM.START_QUEUE(queue_name => 'order_queue');
147
+ END;
148
+ /
149
+
150
+ -- 发送消息
151
+ DECLARE
152
+ enqueue_options DBMS_AQ.ENQUEUE_OPTIONS_T;
153
+ message_properties DBMS_AQ.MESSAGE_PROPERTIES_T;
154
+ message_handle RAW(16);
155
+ msg order_msg := order_msg(1001, 500, 1500.00);
156
+ BEGIN
157
+ DBMS_AQ.ENQUEUE('order_queue', enqueue_options, message_properties, msg, message_handle);
158
+ COMMIT;
159
+ END;
160
+ /
161
+
162
+ -- 接收消息
163
+ DECLARE
164
+ dequeue_options DBMS_AQ.DEQUEUE_OPTIONS_T;
165
+ message_properties DBMS_AQ.MESSAGE_PROPERTIES_T;
166
+ message_handle RAW(16);
167
+ msg order_msg;
168
+ BEGIN
169
+ dequeue_options.wait := DBMS_AQ.FOREVER;
170
+ DBMS_AQ.DEQUEUE('order_queue', dequeue_options, message_properties, msg, message_handle);
171
+ COMMIT;
172
+ END;
173
+ /
174
+ ```
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,182 @@
1
+ ---
2
+ name: postgresql
3
+ description: Provides comprehensive guidance for PostgreSQL including SQL syntax, advanced features (JSONB/CTE/Full-text), functions, indexing, performance tuning, replication, and backup. Use when the user asks about PostgreSQL, needs to work with PostgreSQL features, write complex queries, or optimize PostgreSQL databases.
4
+ license: Complete terms in LICENSE.txt
5
+ ---
6
+
7
+ # PostgreSQL — 高级关系型数据库系统
8
+
9
+ ## Workflow — 使用流程
10
+
11
+ ```text
12
+ 遇到 PostgreSQL 需求时,按以下顺序决策:
13
+
14
+ 1. 明确需求类型
15
+ ├── DDL (建表/改表) → 见 SQL 语法速查
16
+ ├── DML (查询/插入/更新) → 见 SQL 语法速查
17
+ ├── 函数/数据处理 → 见 函数速查
18
+ ├── 查询性能优化 → 见 references/06-index-types.md + examples/03-performance-tuning.md
19
+ └── 高可用/备份/复制 → 见 references/08-replication-backup.md + examples/04-streaming-replication.md
20
+
21
+ 2. 确定模型: 关系型 → 标准表+B-Tree | JSON文档 → JSONB+GIN | 全文搜索 → tsvector+GIN | 地理 → PostGIS+GiST
22
+
23
+ 3. 索引策略: 等值→B-Tree | 范围→B-Tree | 全文→GIN | JSON→GIN | 向量→IVFFlat/HNSW | 大表时序→BRIN
24
+
25
+ 4. 数据量评估: <100GB→单实例 | 100GB-1TB→分区 | 1TB-10TB→分区+只读副本 | >10TB→Citus/逻辑复制
26
+
27
+ 5. 运维策略: autovacuum + pg_stat_statements + WAL归档 + PgBouncer
28
+ ```
29
+
30
+ ## When to Use (and When NOT to)
31
+
32
+ | ✅ Use When | ❌ Skip When |
33
+ |------------|-------------|
34
+ | 需要完整 ACID 事务和复杂 SQL | 纯键值缓存 (用 Redis/Memcached) |
35
+ | JSON 文档 + SQL 查询混合 | 纯文档无关联查询 (用 MongoDB) |
36
+ | 地理空间数据分析 (PostGIS) | 大规模全文搜索 (用 Elasticsearch) |
37
+ | 强数据完整性约束 | 海量无模式日志 (用 Elasticsearch/S3) |
38
+ | OLTP + 复杂 OLAP 混合负载 | 超大规模 OLAP (用 ClickHouse/Snowflake) |
39
+ | 需要流复制/逻辑复制/PITR | 自动水平分片 (用 CockroachDB/YugabyteDB) |
40
+
41
+ **核心原则:PostgreSQL 是全能型关系型数据库,但不是所有场景的最佳选择。**
42
+
43
+ ## Boundary — 能力边界
44
+
45
+ | ✅ 完全适用 | ⚠️ 有条件适用 | ❌ 不适用 → 替代 |
46
+ |------------|--------------|----------------|
47
+ | 标准 OLTP 业务系统 | 超大规模 OLAP >20TB → ClickHouse/cstore_fdw | 纯内存缓存 <1ms → Redis |
48
+ | JSONB + 关系查询混合 | 高并发简单 KV >50万 QPS → Redis | 海量时序写入 >100万点/秒 → InfluxDB |
49
+ | 全文搜索 (数亿文档) | 实时搜索 >10亿文档 → Elasticsearch | 复杂图遍历 → Neo4j |
50
+ | 流复制 HA (故障恢复 <30s) | 跨地域多活 → CockroachDB | 自动分片无感扩缩容 |
51
+
52
+ ## SQL 语法速查
53
+
54
+ 深度 SQL 内容见 `references/` 各文件,此处为索引。
55
+
56
+ - **DDL**: `CREATE TABLE` (含分区、继承), `ALTER TABLE`, 数据类型 (JSONB/TSVECTOR/CITEXT/数组等), 约束 (CHECK/EXCLUDE/UNIQUE/FOREIGN KEY)
57
+ - **DML**: `INSERT ... ON CONFLICT` (UPSERT), `UPDATE ... FROM`, `DELETE ... USING`, `TRUNCATE`, `RETURNING` 子句
58
+ - **CTE**: 公用表表达式 (`WITH`), 递归 CTE (`WITH RECURSIVE`) — 见 `examples/02-cte-recursive.md`
59
+ - **连接**: `INNER/LEFT/RIGHT/FULL/CROSS JOIN`, `LATERAL` 子查询
60
+ - **事务**: `READ COMMITTED` (默认), `REPEATABLE READ`, `SERIALIZABLE`, `SAVEPOINT`, `FOR UPDATE/SHARE/NOWAIT/SKIP LOCKED`, 咨询锁
61
+
62
+ ## 函数速查
63
+
64
+ 深度内容见 `references/`:
65
+
66
+ | 类别 | 关键函数 | 参考文件 |
67
+ |------|---------|---------|
68
+ | 字符串/正则 | `FORMAT`, `SPLIT_PART`, `REGEXP_MATCH/REPLACE`, `STRING_AGG`, `CONCAT_WS`, `TRANSLATE`, `SUBSTRING` | `references/01-functions-string.md` |
69
+ | 日期/时间 | `AGE`, `DATE_TRUNC`, `EXTRACT`, `TO_CHAR`, `MAKE_DATE`, `JUSTIFY_*`, 时区转换 | `references/02-functions-datetime.md` |
70
+ | 聚合/窗口 | `ARRAY_AGG`, `JSONB_AGG`, `STRING_AGG`, `PERCENTILE_CONT/DISC`, `MODE`, `GROUPING SETS/CUBE/ROLLUP`, `ROW_NUMBER`, `RANK`, `LAG/LEAD`, `NTILE`, 窗口帧 | `references/03-functions-aggregate-window.md` |
71
+ | JSONB | `->`/`->>`/`#>`, `@>`/`?`/`?|`/`?&`, `JSONB_SET`, `JSONB_BUILD_OBJECT`, `JSONB_EACH`, `JSONB_TYPEOF`, GIN 索引 | `references/04-functions-jsonb.md` |
72
+
73
+ ## 高级特性索引
74
+
75
+ | 特性 | 说明 | 参考 |
76
+ |------|------|------|
77
+ | 6种索引 | B-Tree, Hash, GiST, GIN, BRIN, SP-GiST, Bloom + 部分索引/覆盖索引/CONCURRENTLY | `references/06-index-types.md` |
78
+ | 视图与物化视图 | 普通视图 (虚拟表) vs 物化视图 (物理快照), WITH CHECK OPTION, CONCURRENTLY 刷新 | `references/06-index-types.md` |
79
+ | PL/pgSQL | 函数 (FUNCTION) vs 过程 (PROCEDURE), 控制结构, 异常处理, 函数重载 | `references/01-functions-string.md` |
80
+ | 触发器 | BEFORE/AFTER/INSTEAD OF, 行级/语句级, 事件触发器, 约束触发器 | `references/01-functions-string.md` |
81
+ | 全文搜索 | tsvector/tsquery, @@ 操作符, ts_rank, ts_headline, 短语搜索, 中文搜索 (zhparser) | `references/05-fulltext-search.md` |
82
+ | 分区表 | RANGE/LIST/HASH 分区, 子分区, 分区裁剪, ATTACH/DETACH | `references/07-partition-fdw.md` |
83
+ | FDW 外部表 | postgres_fdw, file_fdw, IMPORT FOREIGN SCHEMA | `references/07-partition-fdw.md` |
84
+ | 扩展 | PostGIS, pgvector, pg_stat_statements, uuid-ossp, pgcrypto, citext, pg_trgm, unaccent | `references/08-replication-backup.md` |
85
+ | 权限管理 | ROLE, SCHEMA, GRANT, 默认权限, RLS 行级安全 | `references/08-replication-backup.md` |
86
+ | 流复制与逻辑复制 | 同步/异步, PUBLICATION/SUBSCRIPTION, Patroni/repmgr | `references/08-replication-backup.md` |
87
+ | 备份与恢复 | pg_dump/pg_restore, pg_basebackup, WAL 归档 + PITR | `references/08-replication-backup.md` |
88
+ | 性能优化 | EXPLAIN ANALYZE, VACUUM/autovacuum, pg_stat_statements, 配置调优 | `examples/03-performance-tuning.md` |
89
+
90
+ ## Gotchas — 常见陷阱与反模式
91
+
92
+ | # | 陷阱 | 风险 | 解决方案 |
93
+ |---|------|------|---------|
94
+ | 1 | JSONB 未建 GIN 索引 | 全表扫描, 性能差 | `CREATE INDEX ... USING GIN (config)` |
95
+ | 2 | 大量直连数据库 | 每个连接耗 5-10MB, 撑爆内存 | 使用 PgBouncer 连接池 |
96
+ | 3 | 索引膨胀未维护 | 索引体积远超表大小 | 定期 `REINDEX` 或 pg_repack |
97
+ | 4 | N+1 查询 + `SELECT *` | 传输冗余数据, 多次查询 | 只选需要列, 用 JOIN/LATERAL |
98
+ | 5 | 生产高峰期 `VACUUM FULL` | 锁表, 业务中断 | 用 pg_repack (不锁表) |
99
+ | 6 | autovacuum 触发不及时 | 死元组堆积 → 表膨胀 → 性能崩溃 | 监控 n_dead_tup, 调参 |
100
+ | 7 | `SERIAL` 而非 `BIGSERIAL` | 超 21 亿行后 ID 溢出 | 新表用 `BIGSERIAL` 或 UUID |
101
+ | 8 | 多租户未设 RLS | 数据泄露 | 启用 RLS + 外键约束 |
102
+ | 9 | 忽略事务 ID 回卷 | 数据库强制只读 | 监控 `age(relfrozenxid)` |
103
+ | 10 | UUID 做主键 (v4 随机) | B-Tree 页分裂, 写入慢 2-3x | 用 UUID v7 或 BIGSERIAL |
104
+ | 11 | 大表 `COUNT(*)` | 千万行以上全表扫描极慢 | 用 `pg_class.reltuples` 近似值 |
105
+ | 12 | 外键无索引 | 删除/更新父表时子表全表扫描 | 外键列上建索引 |
106
+ | 13 | SERIALIZABLE 无重试逻辑 | 事务冲突失败 | 应用层实现重试 |
107
+
108
+ ## FAQ
109
+
110
+ **Q1: PostgreSQL vs MySQL 主要区别?**
111
+ PostgreSQL: 完全 ACID, JSONB 可索引, 6 种索引类型, 递归 CTE, 流复制+逻辑复制, 丰富 EXTENSION。MySQL: Web 应用为主, 简单查询, InnoDB 事务, 间隙锁并发控制。
112
+
113
+ **Q2: JSONB vs JSON?**
114
+ 始终选 JSONB。二进制格式, 支持 GIN 索引, 查询更快。JSON 仅在你需要保留空格和键顺序时使用。
115
+
116
+ **Q3: UUID 为什么不适合做主键?**
117
+ UUID v4 随机值导致 B-Tree 页频繁分裂, 比 BIGSERIAL 慢 2-3 倍。方案: UUID v7 (时间排序), BIGSERIAL, 或 ULID/Snowflake。
118
+
119
+ **Q4: 如何在线迁移 PostgreSQL?**
120
+ 逻辑复制 (PG 10+, 推荐) > pglogical 扩展 > pg_dump+pg_restore (需停机)。逻辑复制支持跨大版本、选择性复制。
121
+
122
+ **Q5: work_mem 怎么设?**
123
+ 每个排序操作分配, 最大内存 = work_mem × (连接数 × 并发排序数)。64GB 机器建议 64-128MB。监控 temp_files 指标, 有磁盘排序则调大。
124
+
125
+ **Q6: pg_repack vs VACUUM FULL?**
126
+ VACUUM FULL 锁表 (ACCESS EXCLUSIVE)。pg_repack 不锁写, 适合在线环境, 优先选择。
127
+
128
+ **Q7: 死锁怎么处理?**
129
+ PG 自动检测并回滚一个事务。预防: 保持锁顺序一致、缩短事务、用 NOWAIT/SKIP LOCKED, 监控 pg_stat_database.deadlocks。
130
+
131
+ **Q8: 如何选择分区键?**
132
+ 条件: 查询频繁出现 (分区裁剪)、数据均匀分布、稳定不变。常见: 时间 (RANGE)、地区 (LIST)、ID 哈希 (HASH)。分区数建议 10-200。
133
+
134
+ **Q9: 连接数设多少?**
135
+ 每个连接 5-10MB, 一般 200-500 够用。超过 500 必须用 PgBouncer。(max_connections × work_mem × 0.5) + shared_buffers + 系统开销 < 内存 80%。
136
+
137
+ **Q10: 何时用 SERIALIZABLE?**
138
+ 金融转账、库存扣减、强一致性报表。注意: 失败率随冲突上升, 应用层需重试逻辑。
139
+
140
+ **Q11: 查询没走索引的原因?**
141
+ 统计信息过旧→ANALYZE | 类型不匹配→隐式转换 | 选择性低→规划器认为全表更优 | 函数包裹索引列→避免 WHERE DATE(col) = 写法。
142
+
143
+ **Q12: 怎么判断要不要分区?**
144
+ 表 > 100GB | 存在明显按时间/地区查询模式 | 旧数据定期归档 | VACUUM 跟不上更新。不满足则分区复杂度 > 收益。
145
+
146
+ **Q13: 如何大版本升级?**
147
+ pg_upgrade 最推荐: `pg_upgrade -b old_bin -B new_bin -d old_data -D new_data`, --link 模式最快。升级后执行 ANALYZE。
148
+
149
+ **Q14: 逻辑复制 vs 流复制?**
150
+ 流复制: 物理块级, 全库, 大版本必须一致, 用于 HA。逻辑复制: SQL 变更, 选表/行, 跨大版本, 用于数据同步/迁移。
151
+
152
+ **Q15: VACUUM 后表大小没变小?**
153
+ VACUUM (不带 FULL) 只标记空间可重用, 不还给 OS。真正缩小需 VACUUM FULL 或 pg_repack。
154
+
155
+ ## Keywords
156
+
157
+ postgresql, postgres, psql, SQL, DDL, DML, ACID, MVCC, 事务, 索引, B-Tree, GIN, GiST, BRIN, JSONB, hstore, 数组, 全文搜索, tsvector, tsquery, 窗口函数, CTE, 递归CTE, LATERAL, PL/pgSQL, 存储过程, 触发器, 物化视图, 分区表, PostGIS, pgvector, pg_stat_statements, pgcrypto, citext, pg_trgm, FDW, postgres_fdw, EXPLAIN, VACUUM, autovacuum, pg_dump, pg_restore, pg_basebackup, WAL归档, PITR, 流复制, 逻辑复制, PUBLICATION, SUBSCRIPTION, Patroni, repmgr, PgBouncer, RLS, 行级安全, 性能优化, 备份恢复, 高可用, 死锁, 连接池
158
+
159
+ ## References
160
+
161
+ - [PostgreSQL 官方文档](https://www.postgresql.org/docs/current/)
162
+ - [PostgreSQL 中文文档](http://www.postgres.cn/docs/16/)
163
+ - [PostgreSQL 性能调优 — pgtune](https://pgtune.leopard.in.ua)
164
+ - [Patroni 文档](https://patroni.readthedocs.io/)
165
+ - [PgBouncer 官方文档](https://www.pgbouncer.org/)
166
+ - [pgvector 文档](https://github.com/pgvector/pgvector)
167
+ - [PostGIS 文档](https://postgis.net/documentation/)
168
+
169
+ ### 内部参考
170
+
171
+ - `references/01-functions-string.md` — 字符串/正则函数详解
172
+ - `references/02-functions-datetime.md` — 日期/时间函数详解
173
+ - `references/03-functions-aggregate-window.md` — 聚合/窗口函数详解
174
+ - `references/04-functions-jsonb.md` — JSONB 函数与操作详解
175
+ - `references/05-fulltext-search.md` — 全文搜索详解
176
+ - `references/06-index-types.md` — 索引类型与视图详解
177
+ - `references/07-partition-fdw.md` — 分区表与 FDW 详解
178
+ - `references/08-replication-backup.md` — 复制/备份/权限详解
179
+ - `examples/01-jsonb-query.md` — JSONB 查询示例
180
+ - `examples/02-cte-recursive.md` — 递归 CTE 示例
181
+ - `examples/03-performance-tuning.md` — 性能调优示例
182
+ - `examples/04-streaming-replication.md` — 流复制搭建示例
File without changes
@@ -0,0 +1,72 @@
1
+ # JSONB 查询示例
2
+
3
+ ## 场景:电商用户配置系统
4
+
5
+ 本示例演示如何使用 JSONB 存储和查询用户偏好配置。
6
+
7
+ ## 建表与数据
8
+
9
+ ```sql
10
+ -- 建表
11
+ CREATE TABLE user_configs (
12
+ id BIGSERIAL PRIMARY KEY,
13
+ user_id INTEGER NOT NULL,
14
+ config JSONB NOT NULL DEFAULT '{}'
15
+ );
16
+
17
+ -- 插入示例数据
18
+ INSERT INTO user_configs (user_id, config) VALUES
19
+ (1, '{
20
+ "theme": "dark",
21
+ "notifications": {"email": true, "sms": false, "push": true},
22
+ "preferences": {"language": "zh-CN", "timezone": "Asia/Shanghai"},
23
+ "tags": ["developer", "premium"],
24
+ "trust_score": 4.5
25
+ }'),
26
+ (2, '{
27
+ "theme": "light",
28
+ "notifications": {"email": false, "sms": true, "push": false},
29
+ "preferences": {"language": "en", "timezone": "America/New_York"},
30
+ "tags": ["basic"]
31
+ }');
32
+
33
+ -- 创建 GIN 索引
34
+ CREATE INDEX idx_config_gin ON user_configs USING GIN (config);
35
+ ```
36
+
37
+ ## 查询示例
38
+
39
+ ```sql
40
+ -- 1. 查询所有使用深色主题的用户
41
+ SELECT user_id, config ->> 'theme' AS theme
42
+ FROM user_configs
43
+ WHERE config @> '{"theme": "dark"}';
44
+
45
+ -- 2. 查询开启了邮件通知的用户
46
+ SELECT user_id FROM user_configs
47
+ WHERE config @> '{"notifications": {"email": true}}';
48
+
49
+ -- 3. 查询有 trust_score 字段的用户
50
+ SELECT user_id FROM user_configs WHERE config ? 'trust_score';
51
+
52
+ -- 4. 查询语言为中文的高级用户 (tags 包含 "premium")
53
+ SELECT user_id FROM user_configs
54
+ WHERE config @> '{"preferences": {"language": "zh-CN"}}'
55
+ AND config @> '{"tags": ["premium"]}';
56
+
57
+ -- 5. 更新嵌套字段(开启 SMS 通知)
58
+ UPDATE user_configs SET config = JSONB_SET(
59
+ config, '{notifications, sms}', 'true'::JSONB
60
+ ) WHERE user_id = 1;
61
+
62
+ -- 6. 追加标签
63
+ UPDATE user_configs SET config = config || '{"tags": ["vip"]}'
64
+ WHERE user_id = 1;
65
+
66
+ -- 7. 展开 JSONB 查看所有键值对
67
+ SELECT key, value FROM user_configs c,
68
+ JSONB_EACH(c.config) WHERE user_id = 1;
69
+
70
+ -- 8. 聚合用户配置为 JSONB 数组
71
+ SELECT JSONB_AGG(config) AS all_configs FROM user_configs;
72
+ ```