@ecubelabs/mysql-mcp 1.0.0-next.4 → 1.0.0-next.6
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/README.md +110 -104
- package/dist/index.js +35 -43
- package/dist/src/catalog/collect.js +33 -40
- package/dist/src/catalog/docs.js +2 -4
- package/dist/src/catalog/index.js +80 -16
- package/dist/src/catalog/owner.js +35 -0
- package/dist/src/catalog/render.js +23 -5
- package/dist/src/catalog/store.js +32 -9
- package/dist/src/catalog/types.js +2 -10
- package/dist/src/config/index.js +0 -36
- package/dist/src/db/permissions.js +21 -5
- package/dist/src/ssh/known-hosts.js +7 -4
- package/dist/src/ssh/tunnel.js +3 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -15,12 +15,11 @@ Tunnel은 서버가 직접 엽니다. 이미 쓰고 있는 `~/.ssh/config` alias
|
|
|
15
15
|
온 답인지 밝힙니다.
|
|
16
16
|
- **기본 읽기 전용, prod는 깨뜨릴 수 없음.** `prod`/`production`은 설정과
|
|
17
17
|
무관하게 모든 쓰기를 거부합니다.
|
|
18
|
-
- **
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
다시 읽습니다. 실제 query에 등장한 table의 column·index·foreign key는 필요할 때만
|
|
18
|
+
- **DB에 물을 수 없는 사실은 사용자가 확인해 기록.** 어떤 schema가 어느 저장소의
|
|
19
|
+
어느 앱 것인지(owner), 데이터가 저장소마다 어느 git branch에 대응하는지는 사용자가
|
|
20
|
+
한 번 확인해 catalog에 기록합니다.
|
|
21
|
+
- **로컬 schema catalog.** 계정이 볼 수 있는 schema의 table 목록을 저장해 두고 TTL이
|
|
22
|
+
지나면 다시 읽습니다. 실제 query에 등장한 table의 column·index·foreign key는 필요할 때만
|
|
24
23
|
수집합니다.
|
|
25
24
|
- **실행 상한과 타임아웃 보고서.** 읽기 쿼리는 10초·5000행에서 끊깁니다. 시간
|
|
26
25
|
상한에 걸리면 실행 계획을 한 번 읽어, 플랜과 인덱스 목록과 선택지를 돌려줍니다.
|
|
@@ -58,6 +57,7 @@ Host ecubelabs2-prod-db
|
|
|
58
57
|
|
|
59
58
|
```bash
|
|
60
59
|
ssh ecubelabs2-stage-db "echo ok"
|
|
60
|
+
ssh ecubelabs2-prod-db "echo ok"
|
|
61
61
|
```
|
|
62
62
|
|
|
63
63
|
- alias가 동작하는지 확인합니다.
|
|
@@ -67,7 +67,6 @@ ssh ecubelabs2-stage-db "echo ok"
|
|
|
67
67
|
### 2. MCP 클라이언트에 등록하기
|
|
68
68
|
|
|
69
69
|
- `MYSQL_PROFILE`은 빼지 마세요. prod 쓰기 금지를 이 값이 정합니다.
|
|
70
|
-
- `MYSQL_APP_SCHEMAS` 형식은 [아래 절](#mysql_app_schemas--어떤-schema가-어떤-앱의-것인가)에 있습니다.
|
|
71
70
|
- 나머지 변수는 [환경 변수](#환경-변수) 절에 있습니다.
|
|
72
71
|
|
|
73
72
|
#### Claude Code
|
|
@@ -76,12 +75,6 @@ ssh ecubelabs2-stage-db "echo ok"
|
|
|
76
75
|
claude mcp add mysql-stage -s user \
|
|
77
76
|
-e MYSQL_PROFILE=stage \
|
|
78
77
|
-e MYSQL_SSH_CONFIG_HOST=ecubelabs2-stage-db \
|
|
79
|
-
-e "MYSQL_APP_SCHEMAS=core-api:haulla:Main product service - the primary schema;
|
|
80
|
-
core-api:haulla-shared:Tenant-shared data, also owned by core-api;
|
|
81
|
-
customer-tycoon-api:tycoon:Internal sales/CRM tool;
|
|
82
|
-
hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
|
|
83
|
-
call-analyzer:call:Call transcription and analysis output;
|
|
84
|
-
simulator:simulator:HubSpot API simulator, stage only" \
|
|
85
78
|
-e MYSQL_USER=<user> \
|
|
86
79
|
-e MYSQL_PASS=<password> \
|
|
87
80
|
-- npx -y @ecubelabs/mysql-mcp
|
|
@@ -89,11 +82,6 @@ simulator:simulator:HubSpot API simulator, stage only" \
|
|
|
89
82
|
claude mcp add mysql-prod -s user \
|
|
90
83
|
-e MYSQL_PROFILE=prod \
|
|
91
84
|
-e MYSQL_SSH_CONFIG_HOST=ecubelabs2-prod-db \
|
|
92
|
-
-e "MYSQL_APP_SCHEMAS=core-api:haulla:Main product service - the primary schema;
|
|
93
|
-
core-api:haulla-shared:Tenant-shared data, also owned by core-api;
|
|
94
|
-
customer-tycoon-api:tycoon:Internal sales/CRM tool;
|
|
95
|
-
hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
|
|
96
|
-
call-analyzer:call:Call transcription and analysis output" \
|
|
97
85
|
-e MYSQL_USER=<user> \
|
|
98
86
|
-e MYSQL_PASS=<password> \
|
|
99
87
|
-- npx -y @ecubelabs/mysql-mcp
|
|
@@ -105,12 +93,6 @@ call-analyzer:call:Call transcription and analysis output" \
|
|
|
105
93
|
codex mcp add mysql-stage \
|
|
106
94
|
--env MYSQL_PROFILE=stage \
|
|
107
95
|
--env MYSQL_SSH_CONFIG_HOST=ecubelabs2-stage-db \
|
|
108
|
-
--env "MYSQL_APP_SCHEMAS=core-api:haulla:Main product service - the primary schema;
|
|
109
|
-
core-api:haulla-shared:Tenant-shared data, also owned by core-api;
|
|
110
|
-
customer-tycoon-api:tycoon:Internal sales/CRM tool;
|
|
111
|
-
hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
|
|
112
|
-
call-analyzer:call:Call transcription and analysis output;
|
|
113
|
-
simulator:simulator:HubSpot API simulator, stage only" \
|
|
114
96
|
--env MYSQL_USER=<user> \
|
|
115
97
|
--env MYSQL_PASS=<password> \
|
|
116
98
|
-- npx -y @ecubelabs/mysql-mcp
|
|
@@ -118,11 +100,6 @@ simulator:simulator:HubSpot API simulator, stage only" \
|
|
|
118
100
|
codex mcp add mysql-prod \
|
|
119
101
|
--env MYSQL_PROFILE=prod \
|
|
120
102
|
--env MYSQL_SSH_CONFIG_HOST=ecubelabs2-prod-db \
|
|
121
|
-
--env "MYSQL_APP_SCHEMAS=core-api:haulla:Main product service - the primary schema;
|
|
122
|
-
core-api:haulla-shared:Tenant-shared data, also owned by core-api;
|
|
123
|
-
customer-tycoon-api:tycoon:Internal sales/CRM tool;
|
|
124
|
-
hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
|
|
125
|
-
call-analyzer:call:Call transcription and analysis output" \
|
|
126
103
|
--env MYSQL_USER=<user> \
|
|
127
104
|
--env MYSQL_PASS=<password> \
|
|
128
105
|
-- npx -y @ecubelabs/mysql-mcp
|
|
@@ -134,13 +111,17 @@ call-analyzer:call:Call transcription and analysis output" \
|
|
|
134
111
|
|
|
135
112
|
```text
|
|
136
113
|
mysql-stage catalog의 table을 model.md 문서와 모두 연결해줘
|
|
114
|
+
mysql-prod catalog의 table을 model.md 문서와 모두 연결해줘
|
|
137
115
|
```
|
|
138
116
|
|
|
117
|
+
- Catalog는 profile마다 따로 있으므로 연결도 profile마다 합니다.
|
|
139
118
|
- 모델이 저장소에서 문서를 찾아 저장소 기준 상대 경로와 GitHub 저장소(`owner/name`)로
|
|
140
119
|
기록합니다. 서버는 파일이 있는지 확인하지 않습니다.
|
|
141
120
|
- Branch가 기록되지 않은 저장소를 연결하면 `link` 응답이 그 저장소의 branch를 묻게
|
|
142
121
|
합니다. stage profile이면 `develop`, prod profile이면 `main`이 맞는지 확인합니다.
|
|
143
122
|
답은 저장소별로 catalog에 기록되어 다음 세션에도 씁니다.
|
|
123
|
+
- Owner가 기록되지 않은 schema의 table을 연결하면 `link` 응답이 그 schema의 저장소와
|
|
124
|
+
앱을 묻게 합니다. 답은 schema별로 catalog에 기록됩니다.
|
|
144
125
|
- 그 뒤로 `describe`하면 문서를 읽는 명령 두 개가 옵니다.
|
|
145
126
|
- `command`: 문서 저장소 안의 세션에서 `git show origin/<branch>:<경로>`
|
|
146
127
|
- `remoteCommand`: 어느 디렉터리에서든 `gh api`. 저장소 밖의 세션은 `gh auth login`이
|
|
@@ -154,8 +135,11 @@ Profile 이름으로 물어보면 답변에 환경이 함께 돌아옵니다:
|
|
|
154
135
|
|
|
155
136
|
```text
|
|
156
137
|
stage db에 Active Account가 몇 개 있는지 알려줘
|
|
138
|
+
prod db에 Active Account가 몇 개 있는지 알려줘
|
|
157
139
|
```
|
|
158
140
|
|
|
141
|
+
stage 응답:
|
|
142
|
+
|
|
159
143
|
```text
|
|
160
144
|
[profile: STAGE | read-only | database: multi-db | code: Ecube-Labs/haulla@develop | ssh tunnel: dev@<stage bastion 호스트명> -> <stage RDS reader 엔드포인트>:3306]
|
|
161
145
|
[
|
|
@@ -165,6 +149,12 @@ stage db에 Active Account가 몇 개 있는지 알려줘
|
|
|
165
149
|
]
|
|
166
150
|
```
|
|
167
151
|
|
|
152
|
+
prod 응답의 banner:
|
|
153
|
+
|
|
154
|
+
```text
|
|
155
|
+
[profile: PROD | READ-ONLY (enforced) | database: multi-db | code: Ecube-Labs/haulla@main | ssh tunnel: dev@<prod bastion 호스트명> -> <prod RDS reader 엔드포인트>:3306]
|
|
156
|
+
```
|
|
157
|
+
|
|
168
158
|
- 모든 툴 응답이 성공이든 거부든 이 banner를 달고 나오므로, stage 결과를 prod
|
|
169
159
|
결과로 착각할 수 없습니다.
|
|
170
160
|
- `mysql_query` 툴 설명에도 환경 이름이 들어갑니다. 모델이 툴을 고르기 전에 읽는
|
|
@@ -174,54 +164,37 @@ stage db에 Active Account가 몇 개 있는지 알려줘
|
|
|
174
164
|
|
|
175
165
|
내버려 두면 모델은 "lead는 어느 schema에 있지?"라는 질문에 `SHOW DATABASES`와
|
|
176
166
|
`information_schema` 쿼리 몇 번, 그리고 추측으로 답합니다. 하나하나가 왕복
|
|
177
|
-
비용이고, 추측은 가끔 틀립니다.
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
### `MYSQL_APP_SCHEMAS` — 어떤 schema가 어떤 앱의 것인가
|
|
181
|
-
|
|
182
|
-
각 항목은 `app:schema`, 또는 `app:schema:설명` 형식입니다. 항목 구분자는 `;` 또는
|
|
183
|
-
개행입니다. 쉼표가 아니므로 설명을 문장처럼 쓸 수 있습니다:
|
|
184
|
-
|
|
185
|
-
```dotenv
|
|
186
|
-
MYSQL_APP_SCHEMAS="core-api:haulla:Main product service - the primary schema;
|
|
187
|
-
core-api:haulla-shared:Tenant-shared data, also owned by core-api;
|
|
188
|
-
customer-tycoon-api:tycoon:Internal sales/CRM tool;
|
|
189
|
-
hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
|
|
190
|
-
call-analyzer:call:Call transcription and analysis output;
|
|
191
|
-
simulator:simulator:HubSpot API simulator, stage only"
|
|
192
|
-
```
|
|
193
|
-
|
|
194
|
-
- 한 앱이 여러 번 나올 수 있습니다. 테넌트별 schema와 공용 schema를 함께 갖는
|
|
195
|
-
서비스는 둘 다 적으세요. 뒤엣것만 남기면 모델에게 필요한 schema가 사라집니다.
|
|
196
|
-
- 같은 `app:schema` 쌍이 반복될 때만 실수로 보고 첫 항목만 남깁니다. 대소문자는
|
|
197
|
-
가리지 않습니다.
|
|
198
|
-
- 설명에는 `;`를 쓸 수 없습니다. 항목이 쪼개집니다.
|
|
199
|
-
- 이 map은 쿼리 범위를 제한하지 않습니다. map에 없는 schema도 쿼리할 수 있습니다.
|
|
200
|
-
|
|
201
|
-
이 map은 `mysql_query` 툴 설명에 붙습니다. 모델이 첫 호출 전에 읽는 것이 툴
|
|
202
|
-
설명입니다:
|
|
167
|
+
비용이고, 추측은 가끔 틀립니다. table이 어느 schema에 있는지는
|
|
168
|
+
[schema catalog](#schema-catalog)가 DB에서 모아 둡니다. DB에 물어볼 수 없는 아래 두
|
|
169
|
+
사실은 사용자가 한 번 확인해 catalog에 기록합니다.
|
|
203
170
|
|
|
204
|
-
|
|
205
|
-
APP -> SCHEMA (authoritative — use these directly; do not run SHOW DATABASES or search information_schema to find a schema):
|
|
206
|
-
- core-api -> haulla — Main product service - the primary schema
|
|
207
|
-
- core-api -> haulla-shared — Tenant-shared data, also owned by core-api
|
|
208
|
-
- customer-tycoon-api -> tycoon — Internal sales/CRM tool
|
|
209
|
-
- hubspot-adapter -> hubspot — HubSpot integration - mirrored CRM objects
|
|
210
|
-
- call-analyzer -> call — Call transcription and analysis output
|
|
211
|
-
- simulator -> simulator — HubSpot API simulator, stage only
|
|
212
|
-
Qualify every table with its schema (schema.table). Any schema not listed here is either absent from this environment or not owned by an application.
|
|
213
|
-
A schema name that is not a bare identifier must be backtick-quoted, e.g. SELECT ... FROM `haulla-shared`.some_table.
|
|
214
|
-
```
|
|
215
|
-
|
|
216
|
-
**여기에는 migration을 넘겨서도 살아남는 사실만 적으세요.**
|
|
171
|
+
### Schema owner — 어떤 schema가 어느 저장소의 어느 앱 것인가
|
|
217
172
|
|
|
218
|
-
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
-
|
|
223
|
-
|
|
224
|
-
|
|
173
|
+
- 사용자가 확인한 값을
|
|
174
|
+
`mysql_catalog {action:"owner", target:"haulla", repo:"Ecube-Labs/haulla", app:"core-api"}`로
|
|
175
|
+
catalog에 기록합니다. 서버는 문서 경로, 이름, 앱 설정으로 추측하지 않습니다
|
|
176
|
+
([이유](#schema-owner를-추론하지-않는-이유)).
|
|
177
|
+
- 모델이 묻는 자리는 `link` 응답 하나입니다. 연결한 table의 schema에 owner가 없으면
|
|
178
|
+
`guidance`가 묻게 합니다. 이미 기록된 schema는 묻지 않습니다.
|
|
179
|
+
|
|
180
|
+
```text
|
|
181
|
+
[카탈로그] haulla schema를 가진 저장소와 앱이 기록되지 않았습니다. 방금 연결한 문서는 Ecube-Labs/haulla의 apps/core-api/src/services/accounts/domain/model.md입니다.
|
|
182
|
+
haulla schema가 어느 저장소의 어느 앱 것인지 사용자에게 물으세요.
|
|
183
|
+
확인받은 값을 mysql_catalog {action:"owner", target:"haulla", repo:"<owner/name>", app:"<앱 이름>"} 로 기록하세요.
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
- 문서 연결 없이 바로 기록하려면 모델에게 알려 주세요:
|
|
187
|
+
|
|
188
|
+
```text
|
|
189
|
+
mysql-stage의 haulla schema는 Ecube-Labs/haulla의 core-api 것이야. owner로 기록해줘
|
|
190
|
+
mysql-prod의 haulla schema는 Ecube-Labs/haulla의 core-api 것이야. owner로 기록해줘
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
- 기록된 owner는 `map`의 schema마다, `search` 결과의 table마다, `describe`,
|
|
194
|
+
`mysql://schemas`에 `{repo, app}`으로 나옵니다. 기록 전에는 그 키가 없습니다.
|
|
195
|
+
- Query 응답, banner, 툴 설명은 owner를 싣지도 묻지도 않습니다.
|
|
196
|
+
- 예전 버전이 env에서 옮겨 적은 앱 이름은 저장소가 없어 버립니다. 다음 `link` 때 다시
|
|
197
|
+
묻습니다.
|
|
225
198
|
|
|
226
199
|
### 코드 branch — 데이터가 어느 branch에 대응하는가
|
|
227
200
|
|
|
@@ -244,8 +217,8 @@ migration이 빠진 것처럼 보이기 때문입니다.
|
|
|
244
217
|
- `mysql_query` 툴 설명은 서버 시작 때 한 번 만들어집니다. 세션 중에 바꾸면 banner와
|
|
245
218
|
`branch` 응답이 새 값을 알립니다. `mysql_catalog` 툴 설명은 툴 목록을 받을 때마다
|
|
246
219
|
다시 만듭니다.
|
|
247
|
-
- Catalog가 꺼진 profile(`MYSQL_CATALOG_ENABLED=false`
|
|
248
|
-
|
|
220
|
+
- Catalog가 꺼진 profile(`MYSQL_CATALOG_ENABLED=false`)은 branch를 기록할 곳이 없어
|
|
221
|
+
표시하지 않습니다.
|
|
249
222
|
- 예전 버전이 DB 하나에 기록한 branch(`codeBranch`)는 어느 저장소의 것인지 몰라
|
|
250
223
|
버립니다. 필요한 곳에서 다시 묻습니다.
|
|
251
224
|
- Branch는 실제로 쓰이는 곳에서만 묻습니다. profile별 제안은 질문 형태이고 저장되지
|
|
@@ -266,13 +239,15 @@ migration이 빠진 것처럼 보이기 때문입니다.
|
|
|
266
239
|
|
|
267
240
|
## Schema catalog
|
|
268
241
|
|
|
269
|
-
이미 알아낸 구조를 다시 찾지 않도록, 서버는
|
|
270
|
-
|
|
242
|
+
이미 알아낸 구조를 다시 찾지 않도록, 서버는 계정이 볼 수 있는 schema를 모두 로컬 JSON
|
|
243
|
+
catalog에 기록합니다. `information_schema`, `mysql`, `performance_schema`, `sys`만
|
|
244
|
+
뺍니다.
|
|
271
245
|
|
|
272
246
|
### 수집 시점
|
|
273
247
|
|
|
274
|
-
- **table 이름·comment·예상 row 수**는 시작할 때 갱신합니다. catalog가
|
|
275
|
-
`MYSQL_CATALOG_TTL_HOURS`(기본 24시간)가 지났을 때만입니다.
|
|
248
|
+
- **schema 목록과 table 이름·comment·예상 row 수**는 시작할 때 갱신합니다. catalog가
|
|
249
|
+
비어 있거나 `MYSQL_CATALOG_TTL_HOURS`(기본 24시간)가 지났을 때만입니다. DB에서
|
|
250
|
+
사라진 schema는 그 owner와 함께 지웁니다.
|
|
276
251
|
- **column, primary key, index, foreign key**는 table이 실제 SQL에 처음 등장한 뒤
|
|
277
252
|
비동기로 수집합니다. 이 작업은 `mysql_query`의 실행 시간에 포함되지 않습니다.
|
|
278
253
|
- Query가 없는 column이나 table을 참조해 실패하면 서버가 그 항목을 즉시 다시
|
|
@@ -289,7 +264,7 @@ column·index·foreign key가 **추가**되면 오류가 나지 않으므로, ca
|
|
|
289
264
|
|
|
290
265
|
**구조 읽기**
|
|
291
266
|
|
|
292
|
-
- `map`:
|
|
267
|
+
- `map`: schema와 그 owner, 자주 쓰는 table의 개요를 봅니다.
|
|
293
268
|
- `search`: table 이름·comment, 수집된 column, memo, alias를 keyword로 찾습니다.
|
|
294
269
|
- `describe`: 한 table의 column, key, index, foreign key를 봅니다. 상세 정보가
|
|
295
270
|
아직 없거나 TTL이 지났다면 이 호출이 갱신을 기다립니다.
|
|
@@ -315,6 +290,13 @@ column·index·foreign key가 **추가**되면 오류가 나지 않으므로, ca
|
|
|
315
290
|
`git check-ref-format --branch`에 준하는 형식만 받습니다.
|
|
316
291
|
공백·제어문자·`~^:?*[\`·`..`·`@{`는 거절하고, 100자까지입니다.
|
|
317
292
|
- 둘 중 하나라도 틀리면 아무것도 기록하지 않습니다.
|
|
293
|
+
- `owner`: 사용자가 확인한 schema의 저장소와 앱을 기록합니다. `target`(schema 이름),
|
|
294
|
+
`repo`, `app`이 모두 필요합니다. 처음 기록과 변경을 함께 받고, 응답이 무엇을
|
|
295
|
+
기록했는지 또는 `이전 → 새` 값을 알립니다.
|
|
296
|
+
- `target`: 수집된 schema만 받습니다. 대소문자는 가리지 않고 DB의 철자로 저장합니다.
|
|
297
|
+
- `repo`: `link`와 같은 형태를 받아 `owner/name`으로 저장합니다.
|
|
298
|
+
- `app`: 그 저장소 안의 앱 이름. 빈 값·공백·제어문자는 거절하고, 100자까지입니다.
|
|
299
|
+
- 셋 중 하나라도 틀리면 아무것도 기록하지 않습니다.
|
|
318
300
|
|
|
319
301
|
**기록 관리**
|
|
320
302
|
|
|
@@ -327,10 +309,10 @@ column·index·foreign key가 **추가**되면 오류가 나지 않으므로, ca
|
|
|
327
309
|
- `refresh`: 지정한 범위를 강제로 다시 수집합니다. `target`을 생략하면 inventory를
|
|
328
310
|
갱신합니다.
|
|
329
311
|
|
|
330
|
-
| `target`
|
|
331
|
-
|
|
|
332
|
-
| `schema.table`
|
|
333
|
-
|
|
|
312
|
+
| `target` | 다시 수집하는 것 |
|
|
313
|
+
| -------------- | ----------------------------------- |
|
|
314
|
+
| `schema.table` | 그 table의 column·index·foreign key |
|
|
315
|
+
| schema 이름 | schema 목록과 table inventory |
|
|
334
316
|
|
|
335
317
|
### 문서 연결
|
|
336
318
|
|
|
@@ -397,21 +379,20 @@ Catalog에는 schema metadata와 사용 기록만 들어갑니다.
|
|
|
397
379
|
|
|
398
380
|
### Catalog를 끄면
|
|
399
381
|
|
|
400
|
-
`MYSQL_CATALOG_ENABLED=false`로 끄거나 `
|
|
401
|
-
`
|
|
402
|
-
|
|
403
|
-
남깁니다.
|
|
382
|
+
`MYSQL_CATALOG_ENABLED=false`로 끄거나 디스크에 쓸 수 없으면 `mysql_catalog` 툴과
|
|
383
|
+
`mysql://schemas` resource가 사라지고, 나머지 resource는 `information_schema`를 직접
|
|
384
|
+
읽습니다. Owner와 code branch는 기록할 곳이 없어 표시하지 않습니다.
|
|
404
385
|
|
|
405
386
|
## Resource
|
|
406
387
|
|
|
407
388
|
툴만 읽는 클라이언트라면 이 절은 건너뛰어도 됩니다. Resource를 읽는 클라이언트를
|
|
408
389
|
위해 세 가지를 제공합니다.
|
|
409
390
|
|
|
410
|
-
| URI | 내용
|
|
411
|
-
| --------------------------------- |
|
|
412
|
-
| `mysql://tables` | table 목록. 이름, schema, comment, 예상 row 수. catalog가 켜져 있으면
|
|
413
|
-
| `mysql://tables/<schema>/<table>` | 한 table의 구조. catalog가 켜져 있으면 `mysql_catalog describe`와 같은 내용이고, 실패하면 `information_schema`의 column 목록으로 물러납니다. catalog가 꺼져 있으면 `information_schema`의 column 목록을 바로 돌려줍니다.
|
|
414
|
-
| `mysql://schemas` |
|
|
391
|
+
| URI | 내용 |
|
|
392
|
+
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
393
|
+
| `mysql://tables` | table 목록. 이름, schema, comment, 예상 row 수. catalog가 켜져 있으면 저장된 inventory로 답하고, 꺼져 있거나 아직 비어 있으면 `information_schema`에서 읽을 수 있는 모든 table을 읽습니다 — 이때는 크기와 생성·수정 시각도 함께 옵니다. |
|
|
394
|
+
| `mysql://tables/<schema>/<table>` | 한 table의 구조. catalog가 켜져 있으면 `mysql_catalog describe`와 같은 내용이고, 실패하면 `information_schema`의 column 목록으로 물러납니다. catalog가 꺼져 있으면 `information_schema`의 column 목록을 바로 돌려줍니다. |
|
|
395
|
+
| `mysql://schemas` | 사용자가 기록한 schema owner. `profile`, `schemas`(owner가 기록된 schema만, schema → `{repo, app}`), 그리고 branch가 기록돼 있으면 저장소별 `codeBranches`를 담은 JSON입니다. catalog가 꺼져 있으면 목록에 오르지 않습니다. |
|
|
415
396
|
|
|
416
397
|
## 환경 변수
|
|
417
398
|
|
|
@@ -420,13 +401,12 @@ Catalog는 선언된 schema만 훑으므로, 선언이 없으면 스스로 꺼
|
|
|
420
401
|
|
|
421
402
|
### Profile
|
|
422
403
|
|
|
423
|
-
| 변수 | 기본값 | 의미
|
|
424
|
-
| ------------------------- | ---------------------------- |
|
|
425
|
-
| `MYSQL_PROFILE` | _(미설정)_ | 환경 label. `prod`/`production`은 읽기 전용을 강제합니다.
|
|
426
|
-
| `
|
|
427
|
-
| `
|
|
428
|
-
| `
|
|
429
|
-
| `MYSQL_CATALOG_TTL_HOURS` | `24` | DB metadata를 stale로 보는 시간입니다. |
|
|
404
|
+
| 변수 | 기본값 | 의미 |
|
|
405
|
+
| ------------------------- | ---------------------------- | ----------------------------------------------------------------------------------------------------- |
|
|
406
|
+
| `MYSQL_PROFILE` | _(미설정)_ | 환경 label. `prod`/`production`은 읽기 전용을 강제합니다. |
|
|
407
|
+
| `MYSQL_CATALOG_ENABLED` | `true` | 로컬 schema catalog를 켭니다. `false`이면 `mysql_catalog` 툴과 `mysql://schemas`가 제공되지 않습니다. |
|
|
408
|
+
| `MYSQL_CATALOG_PATH` | `~/.cache/mysql-mcp/catalog` | profile·대상·user별 JSON 파일을 둘 directory입니다. |
|
|
409
|
+
| `MYSQL_CATALOG_TTL_HOURS` | `24` | DB metadata를 stale로 보는 시간입니다. |
|
|
430
410
|
|
|
431
411
|
### SSH tunnel
|
|
432
412
|
|
|
@@ -488,6 +468,8 @@ Catalog는 선언된 schema만 훑으므로, 선언이 없으면 스스로 꺼
|
|
|
488
468
|
`ALLOW_*`로 판정합니다.
|
|
489
469
|
- 그래서 `ALLOW_UPDATE_OPERATION`을 끈 채 `SCHEMA_UPDATE_PERMISSIONS=haulla:true`만 적으면
|
|
490
470
|
`haulla`에서만 UPDATE가 열립니다.
|
|
471
|
+
- `false`는 대소문자를 가리지 않고 맞춥니다. `haulla:false`면 `HAULLA`도 거부합니다.
|
|
472
|
+
`true`는 적은 철자와 같은 이름에만 적용되고, 철자가 다르면 `ALLOW_*`로 판정합니다.
|
|
491
473
|
- 쓰기가 하나라도 열리면 도구 설명에 `with support for: UPDATE (haulla only) …`처럼 적고
|
|
492
474
|
`readOnlyHint`를 `false`로 알립니다.
|
|
493
475
|
|
|
@@ -555,6 +537,28 @@ redaction이 아니라 그 앞단에 있습니다 — read-only 강제, profile
|
|
|
555
537
|
tunnel, 그리고 애초에 어떤 계정으로 접속하는지입니다. Column 이름 목록을 손으로
|
|
556
538
|
관리해서 얻는 masking 한 겹은 그 위에 얹을 값이 없었습니다.
|
|
557
539
|
|
|
540
|
+
## Schema owner를 추론하지 않는 이유
|
|
541
|
+
|
|
542
|
+
Owner는 사용자가 확인한 값만 기록합니다. 서버는 문서 경로, 이름 일치, 앱 설정의
|
|
543
|
+
`DB_NAME`, git 어느 것으로도 owner를 정하지 않습니다.
|
|
544
|
+
|
|
545
|
+
- 코드에는 schema 이름이 없습니다. haulla의 엔티티는 `@Entity()`만 쓰고, schema
|
|
546
|
+
이름은 env `DB_NAME`에서 옵니다.
|
|
547
|
+
- 저장소에 남은 단서는 로컬 값이라 환경과 다릅니다.
|
|
548
|
+
- core-api 공용 데이터: 로컬 `docker-compose.yml`은 `haulla`, stage는 `haulla-shared`
|
|
549
|
+
- hubspot-adapter: `.env.example`은 `hubspot-adapter`, stage는 `hubspot`
|
|
550
|
+
- 틀린 schema를 골라도 쿼리는 성공합니다. stage에는 여러 schema에 걸친 같은 이름
|
|
551
|
+
table이 12개 있고(`account`, `user`, `contract`, `deal`, `notification` 등), 숫자도
|
|
552
|
+
그럴듯합니다.
|
|
553
|
+
|
|
554
|
+
예전에는 app → schema map을 env로 받아 툴 설명에 실었습니다. 이 방식은 버렸습니다.
|
|
555
|
+
|
|
556
|
+
- 사용자마다 같은 map을 MCP 설정에 적어야 했습니다.
|
|
557
|
+
- Map에는 table 목록이 없어서, map이 있어도 모델은 table 위치를 찾으려고
|
|
558
|
+
`information_schema`를 조회했습니다.
|
|
559
|
+
- 그래서 owner는 같은 이름 table이 함께 드러나는 catalog 응답(`map`·`search`·
|
|
560
|
+
`describe`)에 둡니다. 묻는 자리는 모델이 table과 코드를 맞대 본 `link` 응답입니다.
|
|
561
|
+
|
|
558
562
|
## Tunnel이 동작하는 방식
|
|
559
563
|
|
|
560
564
|
Forwarding은 `ssh -N -L`을 spawn 하는 대신 `ssh2`를 통해 프로세스 내부에서
|
|
@@ -580,8 +584,10 @@ Forwarding은 `ssh -N -L`을 spawn 하는 대신 `ssh2`를 통해 프로세스
|
|
|
580
584
|
`known_hosts`를 읽지 않고, 검증하지 않으면 어떤 키든 받습니다. 그러면 경로 위의
|
|
581
585
|
공격자가 bastion을 사칭해 DB 비밀번호를 받아 갈 수 있습니다.
|
|
582
586
|
- alias의 `UserKnownHostsFile`(없으면 `~/.ssh/known_hosts`, `~/.ssh/known_hosts2`)와
|
|
583
|
-
`/etc/ssh/ssh_known_hosts`를 읽습니다.
|
|
584
|
-
|
|
587
|
+
`/etc/ssh/ssh_known_hosts`를 읽습니다.
|
|
588
|
+
- 찾는 이름은 OpenSSH와 같습니다. alias에 `HostKeyAlias`가 있으면 포트를 붙이지 않고 그
|
|
589
|
+
이름 그대로 찾습니다. 없으면 호스트 이름을 소문자로 바꾸고, 22번이 아닌 포트는
|
|
590
|
+
`[host]:port`로 찾습니다.
|
|
585
591
|
- 기록된 키 종류로만 협상합니다. 처음 보는 호스트는 기록하지 않고 거부합니다. 지문을
|
|
586
592
|
확인할 수 있는 `ssh`로 한 번 접속해 기록하세요.
|
|
587
593
|
- `@cert-authority` 인증서 기반 호스트 키는 지원하지 않습니다.
|
package/dist/index.js
CHANGED
|
@@ -6,9 +6,10 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
|
|
|
6
6
|
import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
7
7
|
import { log, sharedOnce, tableResourceUri } from './src/utils/index.js';
|
|
8
8
|
import { writeCapabilities } from './src/db/permissions.js';
|
|
9
|
-
import { SCHEMA_DELETE_PERMISSIONS, SCHEMA_DDL_PERMISSIONS, SCHEMA_INSERT_PERMISSIONS, SCHEMA_UPDATE_PERMISSIONS, isMultiDbMode, mcpConfig as config, MYSQL_PROFILE, PROFILE_LABEL, IS_WRITE_FORBIDDEN_PROFILE,
|
|
9
|
+
import { SCHEMA_DELETE_PERMISSIONS, SCHEMA_DDL_PERMISSIONS, SCHEMA_INSERT_PERMISSIONS, SCHEMA_UPDATE_PERMISSIONS, isMultiDbMode, mcpConfig as config, MYSQL_PROFILE, PROFILE_LABEL, IS_WRITE_FORBIDDEN_PROFILE, MYSQL_CATALOG_ENABLED, MYSQL_CATALOG_PATH, MYSQL_CATALOG_TTL_HOURS, MYSQL_DEFAULT_TIMEOUT_SECONDS, MYSQL_MAX_TIMEOUT_SECONDS, MAX_RESPONSE_ROWS, MYSQL_SSL_ENABLED, MYSQL_SSL_CA_PATH, MYSQL_SSL_CERT_PATH, MYSQL_SSL_KEY_PATH, PACKAGE_VERSION, SSH_ENABLED, } from './src/config/index.js';
|
|
10
10
|
import { codeBranchToolInstruction, codeRevisionDescription } from './src/catalog/branch.js';
|
|
11
11
|
import { catalogIdentity, SchemaCatalog } from './src/catalog/index.js';
|
|
12
|
+
import { renderSchemasResource } from './src/catalog/render.js';
|
|
12
13
|
import { describeConnection, getPool, executeQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, setCodeBranchSource, clampTimeoutSeconds, describeQueryError, poolPromise, profileBanner, } from './src/db/index.js';
|
|
13
14
|
import { describeTunnel, ensureTunnel, resolveTunnelConfig, stopTunnel } from './src/ssh/tunnel.js';
|
|
14
15
|
log('info', `Starting MySQL MCP server v${PACKAGE_VERSION}...`);
|
|
@@ -43,25 +44,9 @@ baseToolDescription +=
|
|
|
43
44
|
`${MAX_RESPONSE_ROWS.toLocaleString('en-US')} rows. Aggregate in SQL rather than pulling rows to count them. ` +
|
|
44
45
|
`USE and SET are rejected; write schema.table instead of USE. ` +
|
|
45
46
|
`Executable comments (/*! ... */) and MAX_EXECUTION_TIME or SET_VAR hints are rejected; use timeout_seconds instead.`;
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
'\n\nAPP -> SCHEMA (authoritative — use these directly; do not run SHOW DATABASES ' +
|
|
50
|
-
'or search information_schema to find a schema):';
|
|
51
|
-
for (const entry of APP_SCHEMAS) {
|
|
52
|
-
appSchemaDescription +=
|
|
53
|
-
`\n - ${entry.app} -> ${entry.schema}` + (entry.description ? ` — ${entry.description}` : '');
|
|
54
|
-
}
|
|
55
|
-
appSchemaDescription +=
|
|
56
|
-
'\nQualify every table with its schema (schema.table). Any schema not listed here is ' +
|
|
57
|
-
'either absent from this environment or not owned by an application.';
|
|
58
|
-
const needsQuoting = APP_SCHEMAS.find((entry) => !/^[A-Za-z0-9_$]+$/.test(entry.schema));
|
|
59
|
-
if (needsQuoting) {
|
|
60
|
-
appSchemaDescription +=
|
|
61
|
-
`\nA schema name that is not a bare identifier must be backtick-quoted, ` +
|
|
62
|
-
`e.g. SELECT ... FROM \`${needsQuoting.schema}\`.some_table.`;
|
|
63
|
-
}
|
|
64
|
-
}
|
|
47
|
+
baseToolDescription +=
|
|
48
|
+
'\n\nQualify every table with its schema (schema.table). ' +
|
|
49
|
+
'A schema name that is not a bare identifier must be backtick-quoted, e.g. SELECT ... FROM `my-schema`.some_table.';
|
|
65
50
|
const isReadOnly = writes.length === 0;
|
|
66
51
|
const mysqlCatalogTool = {
|
|
67
52
|
name: 'mysql_catalog',
|
|
@@ -73,6 +58,7 @@ const mysqlCatalogTool = {
|
|
|
73
58
|
'in a session inside the document repository; never unlink from a session outside it. ' +
|
|
74
59
|
'Use branch to record which branch of a GitHub repository matches this database, once ' +
|
|
75
60
|
'the user confirmed it. ' +
|
|
61
|
+
'Use owner to record which repository and app own a schema, once the user confirmed it. ' +
|
|
76
62
|
'Use note to save a table memo or alias, and forget to clear one catalog scope. ' +
|
|
77
63
|
'Use refresh when cached metadata contradicts what a query actually returned, ' +
|
|
78
64
|
'or right after a migration: added columns and indexes raise no error, so ' +
|
|
@@ -82,7 +68,7 @@ const mysqlCatalogTool = {
|
|
|
82
68
|
properties: {
|
|
83
69
|
action: {
|
|
84
70
|
type: 'string',
|
|
85
|
-
enum: ['map', 'search', 'describe', 'link', 'unlink', 'branch', 'note', 'forget', 'refresh'],
|
|
71
|
+
enum: ['map', 'search', 'describe', 'link', 'unlink', 'branch', 'owner', 'note', 'forget', 'refresh'],
|
|
86
72
|
description: 'Catalog operation to perform',
|
|
87
73
|
},
|
|
88
74
|
q: {
|
|
@@ -102,9 +88,15 @@ const mysqlCatalogTool = {
|
|
|
102
88
|
},
|
|
103
89
|
repo: {
|
|
104
90
|
type: 'string',
|
|
105
|
-
description: 'GitHub repository for branch, as owner/name. Take it from `git remote get-url origin`; ' +
|
|
91
|
+
description: 'GitHub repository for branch or owner, as owner/name. Take it from `git remote get-url origin`; ' +
|
|
106
92
|
'https and git@ URLs are accepted.',
|
|
107
93
|
},
|
|
94
|
+
app: {
|
|
95
|
+
type: 'string',
|
|
96
|
+
maxLength: 100,
|
|
97
|
+
description: 'App inside repo that owns the schema given as target, e.g. core-api. ' +
|
|
98
|
+
'Pass it only after the user confirmed it.',
|
|
99
|
+
},
|
|
108
100
|
branch: {
|
|
109
101
|
type: 'string',
|
|
110
102
|
maxLength: 100,
|
|
@@ -114,8 +106,8 @@ const mysqlCatalogTool = {
|
|
|
114
106
|
},
|
|
115
107
|
target: {
|
|
116
108
|
type: 'string',
|
|
117
|
-
description: 'Qualified schema.table for note or forget.
|
|
118
|
-
'columns, indexes and foreign keys; a
|
|
109
|
+
description: 'Qualified schema.table for note or forget. Schema name for owner. For refresh: ' +
|
|
110
|
+
'"schema.table" for one table\'s columns, indexes and foreign keys; a schema name for the ' +
|
|
119
111
|
'table inventory. Omit it to refresh the inventory.',
|
|
120
112
|
},
|
|
121
113
|
text: {
|
|
@@ -223,29 +215,23 @@ export default function createMcpServer() {
|
|
|
223
215
|
user: String(mysqlSettings.user ?? ''),
|
|
224
216
|
customPath: MYSQL_CATALOG_PATH,
|
|
225
217
|
});
|
|
226
|
-
const noDeclaredSchemas = APP_SCHEMAS.length === 0;
|
|
227
|
-
if (noDeclaredSchemas && MYSQL_CATALOG_ENABLED) {
|
|
228
|
-
console.error('[catalog] disabled: MYSQL_APP_SCHEMAS declares no schema, so there is ' +
|
|
229
|
-
'nothing to catalog. Declare the app -> schema map to enable it.');
|
|
230
|
-
}
|
|
231
218
|
const catalog = new SchemaCatalog({
|
|
232
|
-
enabled: MYSQL_CATALOG_ENABLED
|
|
219
|
+
enabled: MYSQL_CATALOG_ENABLED,
|
|
233
220
|
profile: MYSQL_PROFILE || 'default',
|
|
234
221
|
fingerprint: identity.fingerprint,
|
|
235
222
|
filePath: identity.filePath,
|
|
236
223
|
ttlHours: MYSQL_CATALOG_TTL_HOURS,
|
|
237
|
-
appSchemas: APP_SCHEMAS,
|
|
238
224
|
defaultSchema: typeof mysqlSettings.database === 'string' ? mysqlSettings.database : null,
|
|
239
225
|
});
|
|
240
226
|
setQueryDiagnosticsSource({
|
|
241
227
|
indexFacts: (reference) => catalog.indexFacts(reference),
|
|
242
228
|
});
|
|
243
229
|
setCodeBranchSource(() => catalog.codeBranchSummary());
|
|
244
|
-
const queryBaseDescription = baseToolDescription + codeRevisionDescription(catalog.codeBranches())
|
|
230
|
+
const queryBaseDescription = baseToolDescription + codeRevisionDescription(catalog.codeBranches());
|
|
245
231
|
if (queryBaseDescription.length > TOOL_DESCRIPTION_LIMIT) {
|
|
246
232
|
console.error(`[warn] tool description is ${queryBaseDescription.length} characters before the ` +
|
|
247
233
|
`catalog tail; clients keep ${TOOL_DESCRIPTION_LIMIT} and silently drop the rest. ` +
|
|
248
|
-
`
|
|
234
|
+
`Record fewer code branches, or shorten the text in index.ts.`);
|
|
249
235
|
}
|
|
250
236
|
const mysqlQueryDescription = () => queryBaseDescription + catalog.toolDescriptionSuffix(TOOL_DESCRIPTION_LIMIT - queryBaseDescription.length);
|
|
251
237
|
const loadResourceTables = async () => {
|
|
@@ -307,12 +293,12 @@ export default function createMcpServer() {
|
|
|
307
293
|
description: 'List of all MySQL tables',
|
|
308
294
|
mimeType: 'application/json',
|
|
309
295
|
});
|
|
310
|
-
if (
|
|
296
|
+
if (catalog.isEnabled()) {
|
|
311
297
|
resources.push({
|
|
312
298
|
uri: 'mysql://schemas',
|
|
313
|
-
name: '
|
|
314
|
-
title: '
|
|
315
|
-
description: `Which
|
|
299
|
+
name: 'Schema owners',
|
|
300
|
+
title: 'Schema to repository and app map',
|
|
301
|
+
description: `Which repository and app own each schema in ${PROFILE_LABEL}, as confirmed by users`,
|
|
316
302
|
mimeType: 'application/json',
|
|
317
303
|
});
|
|
318
304
|
}
|
|
@@ -327,17 +313,12 @@ export default function createMcpServer() {
|
|
|
327
313
|
try {
|
|
328
314
|
log('info', 'Handling ReadResourceRequest:', request.params.uri);
|
|
329
315
|
if (request.params.uri === 'mysql://schemas') {
|
|
330
|
-
const codeBranches = catalog.codeBranches();
|
|
331
316
|
return {
|
|
332
317
|
contents: [
|
|
333
318
|
{
|
|
334
319
|
uri: request.params.uri,
|
|
335
320
|
mimeType: 'application/json',
|
|
336
|
-
text:
|
|
337
|
-
profile: PROFILE_LABEL,
|
|
338
|
-
...(Object.keys(codeBranches).length > 0 ? { codeBranches } : {}),
|
|
339
|
-
apps: APP_SCHEMAS,
|
|
340
|
-
}, null, 2),
|
|
321
|
+
text: renderSchemasResource(PROFILE_LABEL, catalog.codeBranches(), catalog.schemaOwners()),
|
|
341
322
|
},
|
|
342
323
|
],
|
|
343
324
|
};
|
|
@@ -481,6 +462,17 @@ export default function createMcpServer() {
|
|
|
481
462
|
}
|
|
482
463
|
text = catalog.setCodeBranch(args.repo, args.branch);
|
|
483
464
|
}
|
|
465
|
+
else if (action === 'owner') {
|
|
466
|
+
if (typeof args.target !== 'string' ||
|
|
467
|
+
!args.target.trim() ||
|
|
468
|
+
typeof args.repo !== 'string' ||
|
|
469
|
+
!args.repo.trim() ||
|
|
470
|
+
typeof args.app !== 'string' ||
|
|
471
|
+
!args.app.trim()) {
|
|
472
|
+
throw new Error('mysql_catalog owner requires "target", "repo" and "app", e.g. {target: "haulla", repo: "owner/name", app: "core-api"}.');
|
|
473
|
+
}
|
|
474
|
+
text = await catalog.setSchemaOwner(args.target, args.repo, args.app);
|
|
475
|
+
}
|
|
484
476
|
else if (action === 'refresh') {
|
|
485
477
|
if (args.target !== undefined && typeof args.target !== 'string') {
|
|
486
478
|
throw new Error('mysql_catalog refresh takes "target" as a string.');
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { executeQuery } from '../db/index.js';
|
|
2
|
-
import { emptyTable, normalizeName } from './types.js';
|
|
2
|
+
import { emptyTable, normalizeName, SYSTEM_SCHEMAS } from './types.js';
|
|
3
3
|
function chainAfter(pending, run) {
|
|
4
4
|
if (!pending) {
|
|
5
5
|
return run();
|
|
@@ -26,13 +26,11 @@ export class CatalogCollector {
|
|
|
26
26
|
this.options = options;
|
|
27
27
|
}
|
|
28
28
|
inventoryNeedsRefresh() {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
return !state || isExpired(state.scannedAt, this.options.ttlHours);
|
|
32
|
-
});
|
|
29
|
+
const scannedAt = this.store.schemaScanTimes();
|
|
30
|
+
return scannedAt.length === 0 || scannedAt.some((value) => isExpired(value, this.options.ttlHours));
|
|
33
31
|
}
|
|
34
32
|
async collectInventory(force = false) {
|
|
35
|
-
if (!this.store.isEnabled()
|
|
33
|
+
if (!this.store.isEnabled()) {
|
|
36
34
|
return;
|
|
37
35
|
}
|
|
38
36
|
if (!force && !this.inventoryNeedsRefresh()) {
|
|
@@ -51,42 +49,41 @@ export class CatalogCollector {
|
|
|
51
49
|
return promise;
|
|
52
50
|
}
|
|
53
51
|
async runInventory() {
|
|
54
|
-
const placeholders =
|
|
52
|
+
const placeholders = SYSTEM_SCHEMAS.map(() => '?').join(', ');
|
|
55
53
|
const rows = await executeQuery(`SELECT
|
|
56
|
-
|
|
57
|
-
table_name AS \`table_name\`,
|
|
58
|
-
table_comment AS \`table_comment\`,
|
|
59
|
-
table_rows AS \`table_rows\`
|
|
60
|
-
FROM information_schema.
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
54
|
+
s.schema_name AS \`table_schema\`,
|
|
55
|
+
t.table_name AS \`table_name\`,
|
|
56
|
+
t.table_comment AS \`table_comment\`,
|
|
57
|
+
t.table_rows AS \`table_rows\`
|
|
58
|
+
FROM information_schema.schemata s
|
|
59
|
+
LEFT JOIN information_schema.tables t ON t.table_schema = s.schema_name
|
|
60
|
+
WHERE s.schema_name NOT IN (${placeholders})
|
|
61
|
+
ORDER BY s.schema_name, t.table_name`, [...SYSTEM_SCHEMAS]);
|
|
64
62
|
const rowsBySchema = new Map();
|
|
65
63
|
for (const row of rows) {
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
const bucket = rowsBySchema.get(declared);
|
|
71
|
-
if (bucket) {
|
|
64
|
+
const schemaName = String(row.table_schema);
|
|
65
|
+
const bucket = rowsBySchema.get(schemaName) ?? [];
|
|
66
|
+
if (row.table_name !== null && row.table_name !== undefined) {
|
|
72
67
|
bucket.push(row);
|
|
73
68
|
}
|
|
74
|
-
|
|
75
|
-
rowsBySchema.set(declared, [row]);
|
|
76
|
-
}
|
|
69
|
+
rowsBySchema.set(schemaName, bucket);
|
|
77
70
|
}
|
|
78
71
|
const now = new Date().toISOString();
|
|
72
|
+
let tableCount = 0;
|
|
79
73
|
this.store.update((catalog) => {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
74
|
+
const previousByName = new Map(Object.keys(catalog.schemas).map((name) => [normalizeName(name), name]));
|
|
75
|
+
const schemas = {};
|
|
76
|
+
for (const [schemaName, schemaRows] of rowsBySchema) {
|
|
77
|
+
const previousName = catalog.schemas[schemaName]
|
|
78
|
+
? schemaName
|
|
79
|
+
: previousByName.get(normalizeName(schemaName));
|
|
80
|
+
const previous = previousName ? catalog.schemas[previousName] : undefined;
|
|
81
|
+
const tables = Object.fromEntries(schemaRows.map((row) => {
|
|
82
|
+
const tableName = row.table_name;
|
|
83
|
+
const existing = previous?.tables[tableName] ?? emptyTable();
|
|
87
84
|
const numericRows = Number(row.table_rows);
|
|
88
85
|
return [
|
|
89
|
-
|
|
86
|
+
tableName,
|
|
90
87
|
{
|
|
91
88
|
...existing,
|
|
92
89
|
comment: row.table_comment ?? '',
|
|
@@ -94,16 +91,12 @@ export class CatalogCollector {
|
|
|
94
91
|
},
|
|
95
92
|
];
|
|
96
93
|
}));
|
|
97
|
-
|
|
98
|
-
|
|
94
|
+
tableCount += schemaRows.length;
|
|
95
|
+
schemas[schemaName] = { ...previous, scannedAt: now, tables };
|
|
99
96
|
}
|
|
97
|
+
catalog.schemas = schemas;
|
|
100
98
|
});
|
|
101
|
-
|
|
102
|
-
if (!rowsBySchema.has(schemaName)) {
|
|
103
|
-
console.error(`[catalog] declared schema "${schemaName}" returned no tables; check MYSQL_APP_SCHEMAS and the account's grants.`);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
console.error(`[catalog] inventory scan complete: ${this.options.schemas.length} schemas, ${rows.length} tables`);
|
|
99
|
+
console.error(`[catalog] inventory scan complete: ${rowsBySchema.size} schemas, ${tableCount} tables`);
|
|
107
100
|
}
|
|
108
101
|
detailNeedsRefresh(schemaName, tableName) {
|
|
109
102
|
const meta = this.store.tableMeta(schemaName, tableName);
|
package/dist/src/catalog/docs.js
CHANGED
|
@@ -42,7 +42,7 @@ export class CatalogDocuments {
|
|
|
42
42
|
constructor(store) {
|
|
43
43
|
this.store = store;
|
|
44
44
|
}
|
|
45
|
-
link(links, guidanceFor = () =>
|
|
45
|
+
link(links, guidanceFor = () => []) {
|
|
46
46
|
const resolved = links.map((link) => ({
|
|
47
47
|
...link,
|
|
48
48
|
doc: normalizeDocumentPath(link.doc),
|
|
@@ -68,9 +68,7 @@ export class CatalogDocuments {
|
|
|
68
68
|
}
|
|
69
69
|
}
|
|
70
70
|
});
|
|
71
|
-
const guidance =
|
|
72
|
-
.map(guidanceFor)
|
|
73
|
-
.filter((entry) => entry !== null);
|
|
71
|
+
const guidance = guidanceFor(resolved);
|
|
74
72
|
return JSON.stringify({
|
|
75
73
|
linked: resolved.map((link) => ({
|
|
76
74
|
table: `${link.schema}.${link.table}`,
|
|
@@ -4,9 +4,10 @@ import * as path from 'path';
|
|
|
4
4
|
import { CatalogCollector } from './collect.js';
|
|
5
5
|
import { CatalogDocuments, normalizeGithubRepo } from './docs.js';
|
|
6
6
|
import { formatCodeBranches, normalizeBranchName } from './branch.js';
|
|
7
|
-
import {
|
|
7
|
+
import { normalizeSchemaOwner } from './owner.js';
|
|
8
|
+
import { missingBranchNotice, missingOwnerNotice, renderDescribe, renderMap, renderToolDescriptionSuffix, searchCatalog, } from './render.js';
|
|
8
9
|
import { CatalogStore } from './store.js';
|
|
9
|
-
import { emptyUsage, normalizeName, pruneJoins } from './types.js';
|
|
10
|
+
import { emptyUsage, normalizeName, pruneJoins, SYSTEM_SCHEMAS } from './types.js';
|
|
10
11
|
import { prepareCatalogQuery, resultColumnNames } from './usage.js';
|
|
11
12
|
const UNKNOWN_REFERENCE_REFRESH_COOLDOWN_MS = 60_000;
|
|
12
13
|
const UNKNOWN_REFERENCE_MEMORY_LIMIT = 256;
|
|
@@ -56,7 +57,6 @@ export class SchemaCatalog {
|
|
|
56
57
|
this.options = options;
|
|
57
58
|
this.store = new CatalogStore(options);
|
|
58
59
|
this.collector = new CatalogCollector(this.store, {
|
|
59
|
-
schemas: options.appSchemas.map((entry) => entry.schema),
|
|
60
60
|
ttlHours: options.ttlHours,
|
|
61
61
|
});
|
|
62
62
|
this.documents = new CatalogDocuments(this.store);
|
|
@@ -97,6 +97,55 @@ export class SchemaCatalog {
|
|
|
97
97
|
note: 'banner와 describe는 바로 이 값을 씁니다. mysql_query 툴 설명의 CODE REVISION은 서버를 다시 띄우면 바뀝니다.',
|
|
98
98
|
}, null, 2);
|
|
99
99
|
}
|
|
100
|
+
schemaOwners() {
|
|
101
|
+
return this.isEnabled() ? this.store.schemaOwners() : {};
|
|
102
|
+
}
|
|
103
|
+
async setSchemaOwner(target, repoInput, appInput) {
|
|
104
|
+
if (!this.isEnabled()) {
|
|
105
|
+
throw new Error('The schema catalog is disabled.');
|
|
106
|
+
}
|
|
107
|
+
const requested = target.replace(/`/g, '').trim();
|
|
108
|
+
const owner = normalizeSchemaOwner(repoInput, appInput);
|
|
109
|
+
let schema = this.store.schemaName(requested);
|
|
110
|
+
if (!schema) {
|
|
111
|
+
await this.collector.collectInventory(false);
|
|
112
|
+
schema = this.store.schemaName(requested);
|
|
113
|
+
}
|
|
114
|
+
if (!schema) {
|
|
115
|
+
throw new Error(`Unknown schema "${requested}". owner takes a schema name from mysql_catalog {action:"map"}, not schema.table.`);
|
|
116
|
+
}
|
|
117
|
+
const name = schema;
|
|
118
|
+
const previous = this.store.schemaOwners()[name] ?? null;
|
|
119
|
+
const label = `${owner.repo}의 ${owner.app}`;
|
|
120
|
+
if (previous && previous.repo === owner.repo && previous.app === owner.app) {
|
|
121
|
+
return JSON.stringify({ schema: name, ...owner, changed: false, status: `${name} schema의 owner는 이미 ${label}입니다.` }, null, 2);
|
|
122
|
+
}
|
|
123
|
+
let missing = false;
|
|
124
|
+
this.store.update((catalog) => {
|
|
125
|
+
const entry = catalog.schemas[name];
|
|
126
|
+
if (!entry) {
|
|
127
|
+
missing = true;
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
entry.repo = owner.repo;
|
|
131
|
+
entry.app = owner.app;
|
|
132
|
+
});
|
|
133
|
+
if (missing) {
|
|
134
|
+
throw new Error(`${name} is no longer in the catalog. Run mysql_catalog {action:"map"} to see what remains.`);
|
|
135
|
+
}
|
|
136
|
+
if (!this.isEnabled()) {
|
|
137
|
+
throw new Error('The catalog cache is disabled, so the owner was not recorded.');
|
|
138
|
+
}
|
|
139
|
+
return JSON.stringify({
|
|
140
|
+
schema: name,
|
|
141
|
+
...owner,
|
|
142
|
+
...(previous ? { previous } : {}),
|
|
143
|
+
changed: true,
|
|
144
|
+
status: previous
|
|
145
|
+
? `${name} schema의 owner를 바꿨습니다: ${previous.repo}의 ${previous.app} → ${label}`
|
|
146
|
+
: `${name} schema의 owner를 ${label}(으)로 기록했습니다. 다음 세션에도 이어 씁니다.`,
|
|
147
|
+
}, null, 2);
|
|
148
|
+
}
|
|
100
149
|
startInventory() {
|
|
101
150
|
if (!this.isEnabled() || this.closing) {
|
|
102
151
|
return;
|
|
@@ -147,11 +196,10 @@ export class SchemaCatalog {
|
|
|
147
196
|
}
|
|
148
197
|
catalogKeyForReference(reference) {
|
|
149
198
|
const requestedSchema = reference.schema ?? this.options.defaultSchema;
|
|
150
|
-
if (!requestedSchema) {
|
|
199
|
+
if (!requestedSchema || SYSTEM_SCHEMAS.some((name) => sameName(name, requestedSchema))) {
|
|
151
200
|
return null;
|
|
152
201
|
}
|
|
153
|
-
|
|
154
|
-
return declared ? `${declared.schema}.${reference.table}`.toLowerCase() : null;
|
|
202
|
+
return `${requestedSchema}.${reference.table}`.toLowerCase();
|
|
155
203
|
}
|
|
156
204
|
resolveReferences(references) {
|
|
157
205
|
return references
|
|
@@ -165,7 +213,7 @@ export class SchemaCatalog {
|
|
|
165
213
|
resolved = this.resolveTable(input);
|
|
166
214
|
}
|
|
167
215
|
if (!resolved) {
|
|
168
|
-
throw new Error(`Unknown or ambiguous table "${input}". Use a
|
|
216
|
+
throw new Error(`Unknown or ambiguous table "${input}". Use a qualified schema.table name.`);
|
|
169
217
|
}
|
|
170
218
|
return resolved;
|
|
171
219
|
}
|
|
@@ -198,7 +246,7 @@ export class SchemaCatalog {
|
|
|
198
246
|
if (!entry) {
|
|
199
247
|
throw new Error(`Table disappeared during refresh: ${input}`);
|
|
200
248
|
}
|
|
201
|
-
return renderDescribe(`${resolved.schema}.${resolved.table}`, entry, this.store.codeBranches(), this.store.readJoins(resolved.schema, resolved.table), this.options.profile);
|
|
249
|
+
return renderDescribe(`${resolved.schema}.${resolved.table}`, entry, this.store.codeBranches(), this.store.readJoins(resolved.schema, resolved.table), this.options.profile, this.store.schemaOwners()[resolved.schema] ?? null);
|
|
202
250
|
}
|
|
203
251
|
async refresh(target) {
|
|
204
252
|
if (!this.isEnabled()) {
|
|
@@ -214,15 +262,13 @@ export class SchemaCatalog {
|
|
|
214
262
|
at,
|
|
215
263
|
}, null, 2);
|
|
216
264
|
}
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
: this.options.appSchemas.find((entry) => sameName(entry.schema, requested));
|
|
220
|
-
if (declared) {
|
|
265
|
+
const schema = requested.includes('.') ? null : this.store.schemaName(requested);
|
|
266
|
+
if (schema) {
|
|
221
267
|
await this.collector.collectInventory(true);
|
|
222
268
|
return JSON.stringify({
|
|
223
269
|
refreshed: 'inventory',
|
|
224
|
-
requestedSchema:
|
|
225
|
-
note: '인벤토리는
|
|
270
|
+
requestedSchema: schema,
|
|
271
|
+
note: '인벤토리는 모든 스키마를 쿼리 한 번으로 함께 갱신합니다.',
|
|
226
272
|
...this.inventoryReport(),
|
|
227
273
|
at,
|
|
228
274
|
}, null, 2);
|
|
@@ -246,7 +292,7 @@ export class SchemaCatalog {
|
|
|
246
292
|
}, null, 2);
|
|
247
293
|
}
|
|
248
294
|
throw new Error(`Unknown refresh target "${requested}". Use schema.table for one table's ` +
|
|
249
|
-
'columns, a
|
|
295
|
+
'columns, a schema name for the table inventory, or omit target ' +
|
|
250
296
|
'for the inventory.');
|
|
251
297
|
}
|
|
252
298
|
inventoryReport() {
|
|
@@ -275,7 +321,25 @@ export class SchemaCatalog {
|
|
|
275
321
|
repo: link.repo,
|
|
276
322
|
});
|
|
277
323
|
}
|
|
278
|
-
return this.documents.link(resolvedLinks, (
|
|
324
|
+
return this.documents.link(resolvedLinks, (linked) => {
|
|
325
|
+
const branchNotices = [...new Set(linked.map((link) => link.repo))]
|
|
326
|
+
.filter((repo) => !this.store.codeBranches()[repo])
|
|
327
|
+
.map((repo) => missingBranchNotice(this.options.profile, repo));
|
|
328
|
+
const owners = this.store.schemaOwners();
|
|
329
|
+
const docsBySchema = new Map();
|
|
330
|
+
for (const link of linked) {
|
|
331
|
+
if (owners[link.schema]) {
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
const docs = docsBySchema.get(link.schema) ?? [];
|
|
335
|
+
if (!docs.some((entry) => entry.repo === link.repo && entry.doc === link.doc)) {
|
|
336
|
+
docs.push({ repo: link.repo, doc: link.doc });
|
|
337
|
+
}
|
|
338
|
+
docsBySchema.set(link.schema, docs);
|
|
339
|
+
}
|
|
340
|
+
const ownerNotices = [...docsBySchema].map(([schema, docs]) => missingOwnerNotice(schema, docs));
|
|
341
|
+
return [...branchNotices, ...ownerNotices];
|
|
342
|
+
});
|
|
279
343
|
}
|
|
280
344
|
async unlink(input) {
|
|
281
345
|
if (!this.isEnabled()) {
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { normalizeGithubRepo } from './docs.js';
|
|
2
|
+
const APP_MAX_LENGTH = 100;
|
|
3
|
+
export function normalizeAppName(input) {
|
|
4
|
+
const app = typeof input === 'string' ? input.trim() : '';
|
|
5
|
+
const reject = (reason) => {
|
|
6
|
+
throw new Error(`Invalid app name ${JSON.stringify(input)}: ${reason}.`);
|
|
7
|
+
};
|
|
8
|
+
if (!app) {
|
|
9
|
+
reject('it is empty');
|
|
10
|
+
}
|
|
11
|
+
if (app.length > APP_MAX_LENGTH) {
|
|
12
|
+
reject(`it is longer than ${APP_MAX_LENGTH} characters`);
|
|
13
|
+
}
|
|
14
|
+
if (/[\u0000- \u007f]/.test(app)) {
|
|
15
|
+
reject('it contains whitespace or a control character');
|
|
16
|
+
}
|
|
17
|
+
return app;
|
|
18
|
+
}
|
|
19
|
+
export function normalizeSchemaOwner(repo, app) {
|
|
20
|
+
return { repo: normalizeGithubRepo(repo), app: normalizeAppName(app) };
|
|
21
|
+
}
|
|
22
|
+
export function schemaOwnerOf(schema) {
|
|
23
|
+
return typeof schema.repo === 'string' && typeof schema.app === 'string'
|
|
24
|
+
? { repo: schema.repo, app: schema.app }
|
|
25
|
+
: null;
|
|
26
|
+
}
|
|
27
|
+
export function loadedSchemaOwner(schema) {
|
|
28
|
+
try {
|
|
29
|
+
const owner = normalizeSchemaOwner(schema.repo, schema.app);
|
|
30
|
+
return owner.repo === schema.repo && owner.app === schema.app ? owner : {};
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return {};
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { suggestedBranch } from './branch.js';
|
|
2
|
+
import { schemaOwnerOf } from './owner.js';
|
|
2
3
|
const UNLINKED_SAMPLE_LIMIT = 30;
|
|
3
4
|
const HOT_TABLE_LIMIT = 10;
|
|
4
5
|
function sampled(values) {
|
|
@@ -32,7 +33,6 @@ function rankTables(tables) {
|
|
|
32
33
|
}
|
|
33
34
|
function allTables(catalog) {
|
|
34
35
|
return Object.entries(catalog.schemas).flatMap(([schema, entry]) => Object.entries(entry.tables).map(([table, tableEntry]) => ({
|
|
35
|
-
app: entry.app,
|
|
36
36
|
schema,
|
|
37
37
|
table,
|
|
38
38
|
entry: tableEntry,
|
|
@@ -64,15 +64,16 @@ export function renderToolDescriptionSuffix(catalog, budget) {
|
|
|
64
64
|
}
|
|
65
65
|
return HOT_TABLES_HEADING + listed + staticGuidance;
|
|
66
66
|
}
|
|
67
|
+
function ownerField(owner) {
|
|
68
|
+
return owner ? { owner } : {};
|
|
69
|
+
}
|
|
67
70
|
export function renderMap(catalog) {
|
|
68
71
|
const schemas = Object.entries(catalog.schemas).map(([name, schema]) => ({
|
|
69
|
-
app: schema.app,
|
|
70
72
|
schema: name,
|
|
71
|
-
|
|
73
|
+
...ownerField(schemaOwnerOf(schema)),
|
|
72
74
|
scannedAt: schema.scannedAt,
|
|
73
75
|
tableCount: Object.keys(schema.tables).length,
|
|
74
76
|
tables: rankTables(Object.entries(schema.tables).map(([table, entry]) => ({
|
|
75
|
-
app: schema.app,
|
|
76
77
|
schema: name,
|
|
77
78
|
table,
|
|
78
79
|
entry,
|
|
@@ -115,6 +116,7 @@ export function searchCatalog(catalog, query, limit) {
|
|
|
115
116
|
}
|
|
116
117
|
const results = [];
|
|
117
118
|
for (const [schemaName, schema] of Object.entries(catalog.schemas)) {
|
|
119
|
+
const owner = ownerField(schemaOwnerOf(schema));
|
|
118
120
|
for (const [tableName, table] of Object.entries(schema.tables)) {
|
|
119
121
|
const qualified = `${schemaName}.${tableName}`;
|
|
120
122
|
const matchedColumns = table.columns
|
|
@@ -127,6 +129,7 @@ export function searchCatalog(catalog, query, limit) {
|
|
|
127
129
|
score += Math.min(9, Math.floor(Math.log2(table.usage.successCount + 1)));
|
|
128
130
|
results.push({
|
|
129
131
|
table: qualified,
|
|
132
|
+
...owner,
|
|
130
133
|
score,
|
|
131
134
|
comment: table.comment,
|
|
132
135
|
matchedColumns,
|
|
@@ -148,13 +151,27 @@ function branchQuestion(profile, repo) {
|
|
|
148
151
|
export function missingBranchNotice(profile, repo) {
|
|
149
152
|
return (`[카탈로그] ${repo}에서 이 DB에 대응하는 코드 브랜치가 기록되지 않았습니다. ` + branchQuestion(profile, repo));
|
|
150
153
|
}
|
|
154
|
+
export function missingOwnerNotice(schema, linkedDocs) {
|
|
155
|
+
const docs = linkedDocs.map(({ repo, doc }) => `${repo}의 ${doc}`).join(', ');
|
|
156
|
+
return (`[카탈로그] ${schema} schema를 가진 저장소와 앱이 기록되지 않았습니다. ` +
|
|
157
|
+
`방금 연결한 문서는 ${docs}입니다.\n` +
|
|
158
|
+
`${schema} schema가 어느 저장소의 어느 앱 것인지 사용자에게 물으세요.\n` +
|
|
159
|
+
`확인받은 값을 mysql_catalog {action:"owner", target:"${schema}", repo:"<owner/name>", app:"<앱 이름>"} 로 기록하세요.`);
|
|
160
|
+
}
|
|
161
|
+
export function renderSchemasResource(profile, codeBranches, owners) {
|
|
162
|
+
return JSON.stringify({
|
|
163
|
+
profile,
|
|
164
|
+
...(Object.keys(codeBranches).length > 0 ? { codeBranches } : {}),
|
|
165
|
+
schemas: owners,
|
|
166
|
+
}, null, 2);
|
|
167
|
+
}
|
|
151
168
|
function shellQuote(value) {
|
|
152
169
|
if (/^[A-Za-z0-9_./:@+-]+$/.test(value)) {
|
|
153
170
|
return value;
|
|
154
171
|
}
|
|
155
172
|
return `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
156
173
|
}
|
|
157
|
-
export function renderDescribe(qualifiedName, table, codeBranches, observedJoins, profile) {
|
|
174
|
+
export function renderDescribe(qualifiedName, table, codeBranches, observedJoins, profile, owner = null) {
|
|
158
175
|
let docs;
|
|
159
176
|
const hasDocumentDecision = Object.prototype.hasOwnProperty.call(table.curated, 'doc');
|
|
160
177
|
const documentLink = table.curated.doc;
|
|
@@ -190,6 +207,7 @@ export function renderDescribe(qualifiedName, table, codeBranches, observedJoins
|
|
|
190
207
|
}
|
|
191
208
|
return JSON.stringify({
|
|
192
209
|
table: qualifiedName,
|
|
210
|
+
...ownerField(owner),
|
|
193
211
|
...table,
|
|
194
212
|
...(observedJoins.length > 0 ? { observedJoins } : {}),
|
|
195
213
|
docs,
|
|
@@ -2,6 +2,7 @@ import * as fs from 'fs';
|
|
|
2
2
|
import * as path from 'path';
|
|
3
3
|
import { loadedCodeBranches } from './branch.js';
|
|
4
4
|
import { normalizeDocumentPath, normalizeGithubRepo } from './docs.js';
|
|
5
|
+
import { loadedSchemaOwner, schemaOwnerOf } from './owner.js';
|
|
5
6
|
import { CATALOG_VERSION, emptyCatalog, emptyTable, normalizeName, pruneJoins } from './types.js';
|
|
6
7
|
const FLUSH_DELAY_MS = 2_000;
|
|
7
8
|
const LOCK_RETRY_MS = 25;
|
|
@@ -200,6 +201,11 @@ function mergeTable(external, local, base) {
|
|
|
200
201
|
curated: mergeCurated(external.curated ?? { notes: [], aliases: [] }, local.curated ?? { notes: [], aliases: [] }, base?.curated),
|
|
201
202
|
};
|
|
202
203
|
}
|
|
204
|
+
function mergeOwner(external, local, base) {
|
|
205
|
+
const localOwner = schemaOwnerOf(local);
|
|
206
|
+
const baseOwner = base ? schemaOwnerOf(base) : null;
|
|
207
|
+
return JSON.stringify(localOwner) !== JSON.stringify(baseOwner) ? localOwner : schemaOwnerOf(external);
|
|
208
|
+
}
|
|
203
209
|
function mergeSchema(external, local, base) {
|
|
204
210
|
const newerInventory = timestamp(local.scannedAt) >= timestamp(external.scannedAt) ? local : external;
|
|
205
211
|
const olderInventory = newerInventory === local ? external : local;
|
|
@@ -209,7 +215,7 @@ function mergeSchema(external, local, base) {
|
|
|
209
215
|
? mergeTable(newerInventory === local ? olderInventory.tables[name] : table, newerInventory === local ? table : olderInventory.tables[name], base?.tables[name])
|
|
210
216
|
: table;
|
|
211
217
|
}
|
|
212
|
-
return { ...newerInventory, tables };
|
|
218
|
+
return { ...mergeOwner(external, local, base), scannedAt: newerInventory.scannedAt, tables };
|
|
213
219
|
}
|
|
214
220
|
function mergeCodeBranches(external, local, base) {
|
|
215
221
|
const merged = {};
|
|
@@ -227,7 +233,7 @@ function mergeCatalog(external, local, base) {
|
|
|
227
233
|
if (external.schemas[name] && local.schemas[name]) {
|
|
228
234
|
schemas[name] = mergeSchema(external.schemas[name], local.schemas[name], base.schemas[name]);
|
|
229
235
|
}
|
|
230
|
-
else {
|
|
236
|
+
else if (!base.schemas[name]) {
|
|
231
237
|
schemas[name] = external.schemas[name] ?? local.schemas[name];
|
|
232
238
|
}
|
|
233
239
|
}
|
|
@@ -343,12 +349,17 @@ export class CatalogStore {
|
|
|
343
349
|
sanitizeLoaded(loaded) {
|
|
344
350
|
const fresh = emptyCatalog(this.options);
|
|
345
351
|
fresh.codeBranches = loadedCodeBranches(loaded.codeBranches);
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
if (!cached) {
|
|
352
|
+
const loadedSchemas = loaded.schemas && typeof loaded.schemas === 'object' ? loaded.schemas : {};
|
|
353
|
+
for (const [schemaName, cached] of Object.entries(loadedSchemas)) {
|
|
354
|
+
if (!cached || typeof cached !== 'object') {
|
|
349
355
|
continue;
|
|
350
356
|
}
|
|
351
|
-
schema
|
|
357
|
+
const schema = {
|
|
358
|
+
...loadedSchemaOwner(cached),
|
|
359
|
+
scannedAt: cached.scannedAt ?? null,
|
|
360
|
+
tables: {},
|
|
361
|
+
};
|
|
362
|
+
fresh.schemas[schemaName] = schema;
|
|
352
363
|
for (const [tableName, raw] of Object.entries(cached.tables ?? {})) {
|
|
353
364
|
const base = emptyTable();
|
|
354
365
|
const table = {
|
|
@@ -429,9 +440,21 @@ export class CatalogStore {
|
|
|
429
440
|
}
|
|
430
441
|
return matches;
|
|
431
442
|
}
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
443
|
+
schemaScanTimes() {
|
|
444
|
+
return Object.values(this.data.schemas).map((schema) => schema.scannedAt);
|
|
445
|
+
}
|
|
446
|
+
schemaName(input) {
|
|
447
|
+
return this.ensureNameIndex().get(normalizeName(input))?.schema ?? null;
|
|
448
|
+
}
|
|
449
|
+
schemaOwners() {
|
|
450
|
+
const owners = {};
|
|
451
|
+
for (const [name, schema] of Object.entries(this.data.schemas)) {
|
|
452
|
+
const owner = schemaOwnerOf(schema);
|
|
453
|
+
if (owner) {
|
|
454
|
+
owners[name] = owner;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return owners;
|
|
435
458
|
}
|
|
436
459
|
tableMeta(schema, table) {
|
|
437
460
|
const entry = this.data.schemas[schema]?.tables[table];
|
|
@@ -6,6 +6,7 @@ export function pruneJoins(joins) {
|
|
|
6
6
|
}
|
|
7
7
|
return [...joins].sort((a, b) => b.lastUsedAt.localeCompare(a.lastUsedAt)).slice(0, JOIN_EDGE_LIMIT);
|
|
8
8
|
}
|
|
9
|
+
export const SYSTEM_SCHEMAS = ['information_schema', 'mysql', 'performance_schema', 'sys'];
|
|
9
10
|
export function normalizeName(value) {
|
|
10
11
|
return value.trim().toLowerCase();
|
|
11
12
|
}
|
|
@@ -32,21 +33,12 @@ export function emptyUsage() {
|
|
|
32
33
|
};
|
|
33
34
|
}
|
|
34
35
|
export function emptyCatalog(options) {
|
|
35
|
-
const schemas = {};
|
|
36
|
-
for (const entry of options.appSchemas) {
|
|
37
|
-
schemas[entry.schema] = {
|
|
38
|
-
app: entry.app,
|
|
39
|
-
...(entry.description ? { description: entry.description } : {}),
|
|
40
|
-
scannedAt: null,
|
|
41
|
-
tables: {},
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
36
|
return {
|
|
45
37
|
version: CATALOG_VERSION,
|
|
46
38
|
profile: options.profile,
|
|
47
39
|
fingerprint: options.fingerprint,
|
|
48
40
|
codeBranches: {},
|
|
49
|
-
schemas,
|
|
41
|
+
schemas: {},
|
|
50
42
|
joins: [],
|
|
51
43
|
};
|
|
52
44
|
}
|
package/dist/src/config/index.js
CHANGED
|
@@ -61,42 +61,6 @@ export const MYSQL_PROFILE = (process.env.MYSQL_PROFILE ?? '').trim().toLowerCas
|
|
|
61
61
|
const WRITE_FORBIDDEN_PROFILES = new Set(['prod', 'production']);
|
|
62
62
|
export const IS_WRITE_FORBIDDEN_PROFILE = WRITE_FORBIDDEN_PROFILES.has(MYSQL_PROFILE);
|
|
63
63
|
export const PROFILE_LABEL = MYSQL_PROFILE ? MYSQL_PROFILE.toUpperCase() : 'UNSPECIFIED';
|
|
64
|
-
function parseAppSchemas(raw) {
|
|
65
|
-
if (!raw) {
|
|
66
|
-
return [];
|
|
67
|
-
}
|
|
68
|
-
const entries = [];
|
|
69
|
-
const seen = new Set();
|
|
70
|
-
for (const entry of raw.split(/[;\n]/)) {
|
|
71
|
-
const trimmed = entry.trim();
|
|
72
|
-
if (!trimmed || trimmed.startsWith('#')) {
|
|
73
|
-
continue;
|
|
74
|
-
}
|
|
75
|
-
const firstColon = trimmed.indexOf(':');
|
|
76
|
-
if (firstColon === -1) {
|
|
77
|
-
console.error(`[config] ignoring MYSQL_APP_SCHEMAS entry "${trimmed}": expected "app:schema" or "app:schema:description".`);
|
|
78
|
-
continue;
|
|
79
|
-
}
|
|
80
|
-
const app = trimmed.slice(0, firstColon).trim();
|
|
81
|
-
const rest = trimmed.slice(firstColon + 1);
|
|
82
|
-
const secondColon = rest.indexOf(':');
|
|
83
|
-
const schema = (secondColon === -1 ? rest : rest.slice(0, secondColon)).trim();
|
|
84
|
-
const description = secondColon === -1 ? undefined : rest.slice(secondColon + 1).trim() || undefined;
|
|
85
|
-
if (!app || !schema) {
|
|
86
|
-
console.error(`[config] ignoring MYSQL_APP_SCHEMAS entry "${trimmed}": app and schema must both be non-empty.`);
|
|
87
|
-
continue;
|
|
88
|
-
}
|
|
89
|
-
const pair = `${app.toLowerCase()}\u0000${schema.toLowerCase()}`;
|
|
90
|
-
if (seen.has(pair)) {
|
|
91
|
-
console.error(`[config] MYSQL_APP_SCHEMAS repeats "${app}:${schema}"; keeping the first.`);
|
|
92
|
-
continue;
|
|
93
|
-
}
|
|
94
|
-
seen.add(pair);
|
|
95
|
-
entries.push({ app, schema, description });
|
|
96
|
-
}
|
|
97
|
-
return entries;
|
|
98
|
-
}
|
|
99
|
-
export const APP_SCHEMAS = parseAppSchemas(process.env.MYSQL_APP_SCHEMAS);
|
|
100
64
|
export const MYSQL_CATALOG_ENABLED = process.env.MYSQL_CATALOG_ENABLED !== 'false';
|
|
101
65
|
export const MYSQL_CATALOG_PATH = process.env.MYSQL_CATALOG_PATH?.trim() || undefined;
|
|
102
66
|
function parseCatalogTtl(raw) {
|
|
@@ -1,27 +1,43 @@
|
|
|
1
1
|
import { ALLOW_DELETE_OPERATION, ALLOW_DDL_OPERATION, ALLOW_INSERT_OPERATION, ALLOW_UPDATE_OPERATION, SCHEMA_DELETE_PERMISSIONS, SCHEMA_DDL_PERMISSIONS, SCHEMA_INSERT_PERMISSIONS, SCHEMA_UPDATE_PERMISSIONS, } from '../config/index.js';
|
|
2
|
+
function schemaOverride(permissions, schema) {
|
|
3
|
+
const lowered = schema.toLowerCase();
|
|
4
|
+
let override;
|
|
5
|
+
for (const [name, allowed] of Object.entries(permissions)) {
|
|
6
|
+
if (name.toLowerCase() !== lowered) {
|
|
7
|
+
continue;
|
|
8
|
+
}
|
|
9
|
+
if (!allowed) {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
if (name === schema) {
|
|
13
|
+
override = true;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return override;
|
|
17
|
+
}
|
|
2
18
|
function isInsertAllowedForSchema(schema) {
|
|
3
19
|
if (!schema) {
|
|
4
20
|
return ALLOW_INSERT_OPERATION;
|
|
5
21
|
}
|
|
6
|
-
return
|
|
22
|
+
return schemaOverride(SCHEMA_INSERT_PERMISSIONS, schema) ?? ALLOW_INSERT_OPERATION;
|
|
7
23
|
}
|
|
8
24
|
function isUpdateAllowedForSchema(schema) {
|
|
9
25
|
if (!schema) {
|
|
10
26
|
return ALLOW_UPDATE_OPERATION;
|
|
11
27
|
}
|
|
12
|
-
return
|
|
28
|
+
return schemaOverride(SCHEMA_UPDATE_PERMISSIONS, schema) ?? ALLOW_UPDATE_OPERATION;
|
|
13
29
|
}
|
|
14
30
|
function isDeleteAllowedForSchema(schema) {
|
|
15
31
|
if (!schema) {
|
|
16
32
|
return ALLOW_DELETE_OPERATION;
|
|
17
33
|
}
|
|
18
|
-
return
|
|
34
|
+
return schemaOverride(SCHEMA_DELETE_PERMISSIONS, schema) ?? ALLOW_DELETE_OPERATION;
|
|
19
35
|
}
|
|
20
36
|
function isDDLAllowedForSchema(schema) {
|
|
21
37
|
if (!schema) {
|
|
22
38
|
return ALLOW_DDL_OPERATION;
|
|
23
39
|
}
|
|
24
|
-
return
|
|
40
|
+
return schemaOverride(SCHEMA_DDL_PERMISSIONS, schema) ?? ALLOW_DDL_OPERATION;
|
|
25
41
|
}
|
|
26
42
|
function writeCapabilities() {
|
|
27
43
|
const kinds = [
|
|
@@ -36,7 +52,7 @@ function writeCapabilities() {
|
|
|
36
52
|
capabilities.push({ label, schemas: null });
|
|
37
53
|
continue;
|
|
38
54
|
}
|
|
39
|
-
const opened = Object.keys(perSchema).filter((schema) => perSchema
|
|
55
|
+
const opened = Object.keys(perSchema).filter((schema) => schemaOverride(perSchema, schema) === true);
|
|
40
56
|
if (opened.length > 0) {
|
|
41
57
|
capabilities.push({ label, schemas: opened });
|
|
42
58
|
}
|
|
@@ -3,8 +3,12 @@ import * as fs from 'fs';
|
|
|
3
3
|
import { expandHome } from './config.js';
|
|
4
4
|
export const DEFAULT_USER_KNOWN_HOSTS_FILES = ['~/.ssh/known_hosts', '~/.ssh/known_hosts2'];
|
|
5
5
|
const GLOBAL_KNOWN_HOSTS_FILES = ['/etc/ssh/ssh_known_hosts', '/etc/ssh/ssh_known_hosts2'];
|
|
6
|
-
export function knownHostsName(host, port) {
|
|
7
|
-
|
|
6
|
+
export function knownHostsName(host, port, hostKeyAlias) {
|
|
7
|
+
if (hostKeyAlias) {
|
|
8
|
+
return hostKeyAlias;
|
|
9
|
+
}
|
|
10
|
+
const lowered = host.toLowerCase();
|
|
11
|
+
return port === 22 ? lowered : `[${lowered}]:${port}`;
|
|
8
12
|
}
|
|
9
13
|
function matchesWildcard(pattern, name) {
|
|
10
14
|
const source = pattern
|
|
@@ -38,8 +42,7 @@ function hostFieldMatches(field, name) {
|
|
|
38
42
|
}
|
|
39
43
|
return matched;
|
|
40
44
|
}
|
|
41
|
-
export function lookupKnownHosts(
|
|
42
|
-
const name = knownHostsName(host, port);
|
|
45
|
+
export function lookupKnownHosts(name, files) {
|
|
43
46
|
const result = { name, files: [], keys: [], revoked: [] };
|
|
44
47
|
for (const file of [...files.map(expandHome), ...GLOBAL_KNOWN_HOSTS_FILES]) {
|
|
45
48
|
let raw;
|
package/dist/src/ssh/tunnel.js
CHANGED
|
@@ -4,7 +4,7 @@ import { Client as SSHClient } from 'ssh2';
|
|
|
4
4
|
import { MYSQL_HOST, MYSQL_PORT, SSH_CONFIG_HOST, SSH_ENABLED, SSH_HOST, SSH_LOCAL_PORT, SSH_PASSPHRASE, SSH_PORT, SSH_PRIVATE_KEY_PATH, SSH_REUSE_EXISTING, SSH_USER, } from '../config/index.js';
|
|
5
5
|
import { log } from '../utils/index.js';
|
|
6
6
|
import { expandHome, readSSHConfigHost } from './config.js';
|
|
7
|
-
import { DEFAULT_USER_KNOWN_HOSTS_FILES, hostKeyAlgorithms, isKnownHostKey, lookupKnownHosts } from './known-hosts.js';
|
|
7
|
+
import { DEFAULT_USER_KNOWN_HOSTS_FILES, hostKeyAlgorithms, isKnownHostKey, knownHostsName, lookupKnownHosts, } from './known-hosts.js';
|
|
8
8
|
class LocalPortTakenError extends Error {
|
|
9
9
|
}
|
|
10
10
|
const RECONNECT_MAX_ATTEMPTS = 3;
|
|
@@ -63,7 +63,7 @@ export function resolveTunnelConfig() {
|
|
|
63
63
|
privateKeyPath,
|
|
64
64
|
passphrase: SSH_PASSPHRASE,
|
|
65
65
|
knownHostsFiles: fromConfig?.userKnownHostsFiles ?? DEFAULT_USER_KNOWN_HOSTS_FILES,
|
|
66
|
-
hostKeyName: fromConfig?.hostKeyAlias
|
|
66
|
+
hostKeyName: knownHostsName(sshHost, sshPort, fromConfig?.hostKeyAlias),
|
|
67
67
|
sshTarget: configHost ?? `${sshPort === 22 ? '' : `-p ${sshPort} `}${sshUser}@${sshHost}`,
|
|
68
68
|
localPort,
|
|
69
69
|
remoteHost: remoteHost,
|
|
@@ -99,7 +99,7 @@ let shuttingDown = false;
|
|
|
99
99
|
let fatalError = null;
|
|
100
100
|
function connectSSH(cfg) {
|
|
101
101
|
return new Promise((resolve, reject) => {
|
|
102
|
-
const known = lookupKnownHosts(cfg.hostKeyName, cfg.
|
|
102
|
+
const known = lookupKnownHosts(cfg.hostKeyName, cfg.knownHostsFiles);
|
|
103
103
|
const algorithms = hostKeyAlgorithms(known.keys);
|
|
104
104
|
if (algorithms.length === 0) {
|
|
105
105
|
const searched = known.files.length > 0 ? known.files.join(', ') : cfg.knownHostsFiles.join(', ');
|
package/package.json
CHANGED