@ecubelabs/mysql-mcp 0.0.1 → 1.0.0-next.2

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.
@@ -1,3 +1,4 @@
1
+ import { suggestedBranch } from './branch.js';
1
2
  const UNLINKED_SAMPLE_LIMIT = 30;
2
3
  const HOT_TABLE_LIMIT = 10;
3
4
  function sampled(values) {
@@ -63,7 +64,7 @@ export function renderToolDescriptionSuffix(catalog, budget) {
63
64
  }
64
65
  return HOT_TABLES_HEADING + listed + staticGuidance;
65
66
  }
66
- export function renderMap(catalog, warning = null) {
67
+ export function renderMap(catalog) {
67
68
  const schemas = Object.entries(catalog.schemas).map(([name, schema]) => ({
68
69
  app: schema.app,
69
70
  schema: name,
@@ -85,17 +86,13 @@ export function renderMap(catalog, warning = null) {
85
86
  lastUsedAt: entry.usage.lastUsedAt,
86
87
  })),
87
88
  }));
88
- const unlinkedTables = catalog.docs.repo
89
- ? Object.entries(catalog.schemas).flatMap(([schemaName, schema]) => Object.entries(schema.tables)
90
- .filter(([, table]) => !Object.prototype.hasOwnProperty.call(table.curated, 'doc'))
91
- .map(([tableName]) => `${schemaName}.${tableName}`))
92
- : [];
89
+ const unlinkedTables = Object.entries(catalog.schemas).flatMap(([schemaName, schema]) => Object.entries(schema.tables)
90
+ .filter(([, table]) => !Object.prototype.hasOwnProperty.call(table.curated, 'doc'))
91
+ .map(([tableName]) => `${schemaName}.${tableName}`));
93
92
  return JSON.stringify({
94
93
  profile: catalog.profile,
95
94
  schemas,
96
95
  unlinkedTables: sampled(unlinkedTables),
97
- unlinkedDocuments: sampled(catalog.docs.unlinked),
98
- ...(warning ? { warning } : {}),
99
96
  }, null, 2);
100
97
  }
101
98
  function matchScore(value, query, base) {
@@ -140,31 +137,50 @@ export function searchCatalog(catalog, query, limit) {
140
137
  }
141
138
  return results.sort((a, b) => b.score - a.score || a.table.localeCompare(b.table)).slice(0, limit);
142
139
  }
143
- export function renderDescribe(qualifiedName, table, documents, observedJoins) {
140
+ export function missingBranchNotice(profile) {
141
+ const suggestion = suggestedBranch(profile);
142
+ const question = suggestion
143
+ ? `${profile} profile은 보통 ${suggestion} 브랜치에 대응합니다. ${suggestion}이 맞는지 사용자에게 물으세요.`
144
+ : `이 profile(${profile})이 어느 브랜치에 대응하는지 사용자에게 물으세요.`;
145
+ return (`[카탈로그] 이 DB에 대응하는 코드 브랜치가 기록되지 않았습니다. ${question}\n` +
146
+ '확인받은 값을 mysql_catalog {action:"branch", branch:"<브랜치 이름>"} 로 기록하세요.');
147
+ }
148
+ function shellQuote(value) {
149
+ if (/^[A-Za-z0-9_./:@+-]+$/.test(value)) {
150
+ return value;
151
+ }
152
+ return `'${value.replace(/'/g, `'"'"'`)}'`;
153
+ }
154
+ export function renderDescribe(qualifiedName, table, codeBranch, observedJoins, profile) {
144
155
  let docs;
145
156
  const hasDocumentDecision = Object.prototype.hasOwnProperty.call(table.curated, 'doc');
146
157
  const documentLink = table.curated.doc;
147
- if (!documents.configured) {
148
- docs = '문서 축 비활성 (MYSQL_DOCS_REPO 미설정)';
149
- }
150
- else if (!documents.available) {
151
- docs = '문서 축 비활성';
152
- }
153
- else if (!hasDocumentDecision) {
158
+ if (!hasDocumentDecision) {
154
159
  docs =
155
160
  '연결 안 됨\n' +
156
- `후보를 보려면 mysql_catalog {action:"docs_list", schema:"${documents.schema}"}\n` +
157
- 'status 같은 코드 컬럼의 의미는 도메인 문서에만 있습니다.';
161
+ `도메인 문서(model.md)를 찾으면 mysql_catalog {action:"link", links:[{table:"${qualifiedName}", doc:"<저장소 기준 상대 경로>", repo:"<owner/name>"}]} 로 연결하세요.\n` +
162
+ 'status 같은 코드 컬럼의 의미는 도메인 문서에만 있습니다.' +
163
+ (codeBranch ? '' : `\n${missingBranchNotice(profile)}`);
158
164
  }
159
165
  else if (documentLink == null) {
160
166
  docs = '문서 없음 확인됨';
161
167
  }
162
168
  else {
169
+ const { repo } = documentLink;
163
170
  docs = {
164
171
  path: documentLink.path,
165
- ref: documents.ref,
166
- command: documents.command,
167
- guidance: '상태 코드·도메인 규칙은 이 문서를 먼저 읽어라.',
172
+ repo,
173
+ branch: codeBranch,
174
+ command: codeBranch ? `git show ${shellQuote(`origin/${codeBranch}:${documentLink.path}`)}` : null,
175
+ remoteCommand: codeBranch
176
+ ? `gh api -H 'Accept: application/vnd.github.raw' ${shellQuote(`repos/${repo}/contents/${documentLink.path
177
+ .split('/')
178
+ .map(encodeURIComponent)
179
+ .join('/')}?ref=${encodeURIComponent(codeBranch)}`)}`
180
+ : null,
181
+ guidance: '상태 코드·도메인 규칙은 이 문서를 먼저 읽어라. ' +
182
+ 'command는 문서가 있는 저장소 안에서, remoteCommand는 어디서든(gh 인증 필요) 실행한다.' +
183
+ (codeBranch ? '' : `\n${missingBranchNotice(profile)}`),
168
184
  };
169
185
  }
170
186
  return JSON.stringify({
@@ -172,6 +188,5 @@ export function renderDescribe(qualifiedName, table, documents, observedJoins) {
172
188
  ...table,
173
189
  ...(observedJoins.length > 0 ? { observedJoins } : {}),
174
190
  docs,
175
- ...(documents.warning ? { warning: documents.warning } : {}),
176
191
  }, null, 2);
177
192
  }
@@ -1,5 +1,7 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
+ import { loadedBranch } from './branch.js';
4
+ import { normalizeDocumentPath, normalizeGithubRepo } from './docs.js';
3
5
  import { CATALOG_VERSION, emptyCatalog, emptyTable, normalizeName, pruneJoins } from './types.js';
4
6
  const FLUSH_DELAY_MS = 2_000;
5
7
  const LOCK_RETRY_MS = 25;
@@ -242,40 +244,34 @@ function mergeCatalog(external, local, base) {
242
244
  lastUsedAt: newerUsageTimestamp(outside?.lastUsedAt, inside?.lastUsedAt, outside?.count ?? 0, inside?.count ?? 0, ancestor?.count ?? 0) ?? EPOCH,
243
245
  });
244
246
  }
245
- const localDocsChanged = local.docs.refCommit !== base.docs.refCommit;
246
- const externalDocsChanged = external.docs.refCommit !== base.docs.refCommit;
247
- const chosenDocs = localDocsChanged && externalDocsChanged
248
- ? timestamp(local.docs.refUpdatedAt) >= timestamp(external.docs.refUpdatedAt)
249
- ? local.docs
250
- : external.docs
251
- : localDocsChanged
252
- ? local.docs
253
- : external.docs;
254
- const merged = {
247
+ return {
255
248
  ...local,
256
- docs: {
257
- ...chosenDocs,
258
- repo: local.docs.repo,
259
- ref: local.docs.ref,
260
- paths: chosenDocs.paths ?? [],
261
- unlinked: [],
262
- },
249
+ codeBranch: local.codeBranch !== base.codeBranch ? local.codeBranch : external.codeBranch,
263
250
  schemas,
264
251
  joins: pruneJoins([...joins.values()]),
265
252
  };
266
- const linked = new Set();
267
- for (const schema of Object.values(merged.schemas)) {
268
- for (const table of Object.values(schema.tables)) {
269
- if (table.curated.doc && !merged.docs.paths.includes(table.curated.doc.path)) {
270
- delete table.curated.doc;
271
- }
272
- if (table.curated.doc) {
273
- linked.add(table.curated.doc.path);
274
- }
275
- }
253
+ }
254
+ function loadedDocumentDecision(curated) {
255
+ if (!curated || !Object.prototype.hasOwnProperty.call(curated, 'doc')) {
256
+ return {};
257
+ }
258
+ const doc = curated.doc;
259
+ if (!doc) {
260
+ return { doc: null };
261
+ }
262
+ try {
263
+ return {
264
+ doc: {
265
+ path: normalizeDocumentPath(String(doc.path ?? '')),
266
+ repo: normalizeGithubRepo(doc.repo),
267
+ linkedBy: doc.linkedBy ?? 'model',
268
+ linkedAt: doc.linkedAt ?? EPOCH,
269
+ },
270
+ };
271
+ }
272
+ catch {
273
+ return {};
276
274
  }
277
- merged.docs.unlinked = merged.docs.paths.filter((path) => !linked.has(path));
278
- return merged;
279
275
  }
280
276
  export class CatalogStore {
281
277
  options;
@@ -336,7 +332,7 @@ export class CatalogStore {
336
332
  }
337
333
  sanitizeLoaded(loaded) {
338
334
  const fresh = emptyCatalog(this.options);
339
- const docsCompatible = loaded.docs?.repo === this.options.docsRepo && loaded.docs?.ref === this.options.docsRef;
335
+ fresh.codeBranch = loadedBranch(loaded.codeBranch);
340
336
  for (const [schemaName, schema] of Object.entries(fresh.schemas)) {
341
337
  const cached = loaded.schemas?.[schemaName];
342
338
  if (!cached) {
@@ -362,23 +358,12 @@ export class CatalogStore {
362
358
  curated: {
363
359
  notes: raw.curated?.notes ?? [],
364
360
  aliases: raw.curated?.aliases ?? [],
365
- ...(docsCompatible && Object.prototype.hasOwnProperty.call(raw.curated ?? {}, 'doc')
366
- ? { doc: raw.curated.doc }
367
- : {}),
361
+ ...loadedDocumentDecision(raw.curated),
368
362
  },
369
363
  };
370
364
  schema.tables[tableName] = table;
371
365
  }
372
366
  }
373
- if (docsCompatible) {
374
- fresh.docs = {
375
- ...fresh.docs,
376
- refCommit: loaded.docs.refCommit ?? null,
377
- refUpdatedAt: loaded.docs.refUpdatedAt ?? null,
378
- paths: loaded.docs.paths ?? [],
379
- unlinked: loaded.docs.unlinked ?? [],
380
- };
381
- }
382
367
  fresh.joins = pruneJoins((loaded.joins ?? [])
383
368
  .map((edge) => ({ ...edge, lastUsedAt: edge.lastUsedAt ?? EPOCH })));
384
369
  return fresh;
@@ -415,8 +400,8 @@ export class CatalogStore {
415
400
  snapshot() {
416
401
  return structuredClone(this.data);
417
402
  }
418
- docsView() {
419
- return structuredClone(this.data.docs);
403
+ codeBranch() {
404
+ return this.data.codeBranch;
420
405
  }
421
406
  lookup(schemaHint, table) {
422
407
  const index = this.ensureNameIndex();
@@ -45,14 +45,7 @@ export function emptyCatalog(options) {
45
45
  version: CATALOG_VERSION,
46
46
  profile: options.profile,
47
47
  fingerprint: options.fingerprint,
48
- docs: {
49
- repo: options.docsRepo,
50
- ref: options.docsRef,
51
- refCommit: null,
52
- refUpdatedAt: null,
53
- paths: [],
54
- unlinked: [],
55
- },
48
+ codeBranch: null,
56
49
  schemas,
57
50
  joins: [],
58
51
  };
@@ -61,15 +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
- const DEFAULT_CODE_BRANCH = {
65
- stage: 'develop',
66
- staging: 'develop',
67
- dev: 'develop',
68
- develop: 'develop',
69
- prod: 'main',
70
- production: 'main',
71
- };
72
- export const CODE_BRANCH = process.env.MYSQL_CODE_BRANCH?.trim() || DEFAULT_CODE_BRANCH[MYSQL_PROFILE] || '';
73
64
  function parseAppSchemas(raw) {
74
65
  if (!raw) {
75
66
  return [];
@@ -120,7 +111,6 @@ function parseCatalogTtl(raw) {
120
111
  return value;
121
112
  }
122
113
  export const MYSQL_CATALOG_TTL_HOURS = parseCatalogTtl(process.env.MYSQL_CATALOG_TTL_HOURS);
123
- export const MYSQL_DOCS_REPO = process.env.MYSQL_DOCS_REPO?.trim() || undefined;
124
114
  export const ENABLE_LOGGING = process.env.ENABLE_LOGGING === 'true' || process.env.ENABLE_LOGGING === '1';
125
115
  export const PACKAGE_VERSION = readPackageVersion(path.dirname(fileURLToPath(import.meta.url))) ?? 'unknown';
126
116
  export const MYSQL_DB = process.env.MYSQL_DB?.trim() || undefined;
@@ -1,8 +1,8 @@
1
1
  import { performance } from 'perf_hooks';
2
2
  import * as mysql2 from 'mysql2/promise';
3
- import { mcpConfig as config, describeConfiguredTarget, SSH_ENABLED, MYSQL_PROFILE, PROFILE_LABEL, CODE_BRANCH, IS_WRITE_FORBIDDEN_PROFILE, MYSQL_DISABLE_READ_ONLY_TRANSACTIONS, MYSQL_DEFAULT_TIMEOUT_SECONDS, MYSQL_MAX_TIMEOUT_SECONDS, MYSQL_CATALOG_TIMEOUT_SECONDS, MAX_RESPONSE_ROWS, } from './../config/index.js';
3
+ import { mcpConfig as config, describeConfiguredTarget, SSH_ENABLED, MYSQL_PROFILE, PROFILE_LABEL, IS_WRITE_FORBIDDEN_PROFILE, MYSQL_DISABLE_READ_ONLY_TRANSACTIONS, MYSQL_DEFAULT_TIMEOUT_SECONDS, MYSQL_MAX_TIMEOUT_SECONDS, MYSQL_CATALOG_TIMEOUT_SECONDS, MAX_RESPONSE_ROWS, } from './../config/index.js';
4
4
  import { isDDLAllowedForSchema, isInsertAllowedForSchema, isUpdateAllowedForSchema, isDeleteAllowedForSchema, } from './permissions.js';
5
- import { extractReferencedSchemas, findFileExport, findUnsupportedStatementType, getQueryTypes, isUnparseableIntrospection, extractQualifiers, } from './utils.js';
5
+ import { DDL_STATEMENT_TYPES, extractReferencedSchemas, findFileExport, findLimitOverrideHint, findUnsupportedStatementType, getQueryTypes, hasExecutableComment, isUnparseableIntrospection, extractQualifiers, } from './utils.js';
6
6
  import { isQueryTimeoutError, parseExplainPayload, renderTimeoutDiagnostic } from './diagnose.js';
7
7
  import { log } from './../utils/index.js';
8
8
  import { ensureTunnel, getTunnelEndpoint, getTunnelFatalError, describeTunnel } from './../ssh/tunnel.js';
@@ -89,6 +89,14 @@ function describeQueryError(error) {
89
89
  }
90
90
  return error.message;
91
91
  }
92
+ async function rollbackQuietly(connection) {
93
+ try {
94
+ await connection.rollback();
95
+ }
96
+ catch (error) {
97
+ log('error', 'Rollback failed; reporting the original error instead:', describeQueryError(error));
98
+ }
99
+ }
92
100
  function assertTunnelHealthy() {
93
101
  const fatal = getTunnelFatalError();
94
102
  if (fatal) {
@@ -103,13 +111,18 @@ function describeConnection() {
103
111
  const target = describeConfiguredTarget();
104
112
  return SSH_ENABLED ? `${target} (via ssh tunnel, not yet established)` : target;
105
113
  }
114
+ let codeBranchSource = null;
115
+ function setCodeBranchSource(source) {
116
+ codeBranchSource = source;
117
+ }
106
118
  function profileBanner() {
107
119
  const parts = [`profile: ${PROFILE_LABEL}`];
108
120
  parts.push(IS_WRITE_FORBIDDEN_PROFILE ? 'READ-ONLY (enforced)' : 'read-only');
109
121
  const db = config.mysql.database || 'multi-db';
110
122
  parts.push(`database: ${db}`);
111
- if (CODE_BRANCH) {
112
- parts.push(`code: ${CODE_BRANCH} branch`);
123
+ const branch = codeBranchSource?.();
124
+ if (branch) {
125
+ parts.push(`code: ${branch} branch`);
113
126
  }
114
127
  const tunnel = describeTunnel();
115
128
  if (tunnel) {
@@ -140,7 +153,7 @@ async function executeQuery(sql, params = []) {
140
153
  log('error', 'Error restoring session limits:', restoreError);
141
154
  }
142
155
  connection.release();
143
- log('error', 'Connection released');
156
+ log('info', 'Connection released');
144
157
  }
145
158
  }
146
159
  }
@@ -163,7 +176,7 @@ async function executeWriteQuery(sql) {
163
176
  assertTunnelHealthy();
164
177
  const pool = await getPool();
165
178
  connection = await pool.getConnection();
166
- log('error', 'Write connection acquired');
179
+ log('info', 'Write connection acquired');
167
180
  const schema = (extractReferencedSchemas(sql) ?? [null]).map((name) => name ?? 'default').join(', ');
168
181
  await connection.beginTransaction();
169
182
  try {
@@ -178,7 +191,7 @@ async function executeWriteQuery(sql) {
178
191
  const isUpdateOperation = queryTypes.some((type) => ['update'].includes(type));
179
192
  const isInsertOperation = queryTypes.some((type) => ['insert'].includes(type));
180
193
  const isDeleteOperation = queryTypes.some((type) => ['delete'].includes(type));
181
- const isDDLOperation = queryTypes.some((type) => ['create', 'alter', 'drop', 'truncate'].includes(type));
194
+ const isDDLOperation = queryTypes.some((type) => DDL_STATEMENT_TYPES.has(type));
182
195
  if (isInsertOperation) {
183
196
  const resultHeader = response;
184
197
  responseText = `Insert successful on schema '${schema}'. Affected rows: ${resultHeader.affectedRows}, Last insert ID: ${resultHeader.insertId}`;
@@ -213,7 +226,7 @@ async function executeWriteQuery(sql) {
213
226
  }
214
227
  catch (error) {
215
228
  log('error', 'Error executing write query:', describeQueryError(error));
216
- await connection.rollback();
229
+ await rollbackQuietly(connection);
217
230
  return {
218
231
  content: [
219
232
  {
@@ -240,7 +253,7 @@ async function executeWriteQuery(sql) {
240
253
  finally {
241
254
  if (connection) {
242
255
  connection.release();
243
- log('error', 'Write connection released');
256
+ log('info', 'Write connection released');
244
257
  }
245
258
  }
246
259
  }
@@ -297,6 +310,34 @@ async function executeReadOnlyQuery(sql, options = {}) {
297
310
  let connection;
298
311
  try {
299
312
  assertTunnelHealthy();
313
+ if (hasExecutableComment(sql)) {
314
+ log('error', 'Refusing a statement with an executable comment.');
315
+ return {
316
+ content: [
317
+ {
318
+ type: 'text',
319
+ text: 'Error: executable comments (/*! ... */) are not allowed because MySQL runs their ' +
320
+ 'contents. Write the statement without them.',
321
+ },
322
+ ],
323
+ isError: true,
324
+ };
325
+ }
326
+ const limitHint = findLimitOverrideHint(sql);
327
+ if (limitHint) {
328
+ log('error', `Refusing a statement with the ${limitHint} optimizer hint.`);
329
+ return {
330
+ content: [
331
+ {
332
+ type: 'text',
333
+ text: `Error: the ${limitHint} optimizer hint is not allowed because it overrides the ` +
334
+ `server's execution limit. Remove it and pass timeout_seconds (up to ` +
335
+ `${MYSQL_MAX_TIMEOUT_SECONDS}) if the query needs more time.`,
336
+ },
337
+ ],
338
+ isError: true,
339
+ };
340
+ }
300
341
  const bypassesQueryTypeChecks = isUnparseableIntrospection(sql);
301
342
  let queryTypes = [];
302
343
  let isUpdateOperation = false;
@@ -305,6 +346,12 @@ async function executeReadOnlyQuery(sql, options = {}) {
305
346
  let isDDLOperation = false;
306
347
  if (!bypassesQueryTypeChecks) {
307
348
  queryTypes = await getQueryTypes(sql);
349
+ if (queryTypes.length === 0) {
350
+ return {
351
+ content: [{ type: 'text', text: 'Error: no SQL statement found outside comments.' }],
352
+ isError: true,
353
+ };
354
+ }
308
355
  const unsupported = findUnsupportedStatementType(queryTypes);
309
356
  if (unsupported) {
310
357
  const statement = unsupported.toUpperCase();
@@ -338,7 +385,7 @@ async function executeReadOnlyQuery(sql, options = {}) {
338
385
  isUpdateOperation = queryTypes.some((type) => ['update'].includes(type));
339
386
  isInsertOperation = queryTypes.some((type) => ['insert'].includes(type));
340
387
  isDeleteOperation = queryTypes.some((type) => ['delete'].includes(type));
341
- isDDLOperation = queryTypes.some((type) => ['create', 'alter', 'drop', 'truncate'].includes(type));
388
+ isDDLOperation = queryTypes.some((type) => DDL_STATEMENT_TYPES.has(type));
342
389
  }
343
390
  const writeChecks = [
344
391
  { enabled: isInsertOperation, label: 'INSERT', allowed: isInsertAllowedForSchema },
@@ -370,7 +417,7 @@ async function executeReadOnlyQuery(sql, options = {}) {
370
417
  }
371
418
  const pool = await getPool();
372
419
  connection = await pool.getConnection();
373
- log('error', 'Read-only connection acquired');
420
+ log('info', 'Read-only connection acquired');
374
421
  const timeoutSeconds = clampTimeoutSeconds(options.timeoutSeconds);
375
422
  let roundTrips = await applySessionLimits(connection, {
376
423
  maxExecutionTimeMs: timeoutSeconds * 1_000,
@@ -427,7 +474,7 @@ async function executeReadOnlyQuery(sql, options = {}) {
427
474
  }
428
475
  catch (error) {
429
476
  log('error', 'Error executing read-only query:', describeQueryError(error));
430
- await connection.rollback();
477
+ await rollbackQuietly(connection);
431
478
  if (isQueryTimeoutError(error)) {
432
479
  const diagnostic = await diagnoseTimeout(connection, sql, timeoutSeconds);
433
480
  log('info', `Read query cancelled at ${timeoutSeconds}s after ${roundTrips + 3} DB round trips (including one EXPLAIN)`);
@@ -441,21 +488,16 @@ async function executeReadOnlyQuery(sql, options = {}) {
441
488
  }
442
489
  catch (error) {
443
490
  log('error', 'Error in read-only query transaction:', describeQueryError(error));
444
- try {
445
- if (connection) {
446
- await connection.rollback();
447
- }
448
- }
449
- catch (cleanupError) {
450
- log('error', 'Error during cleanup:', cleanupError);
491
+ if (connection) {
492
+ await rollbackQuietly(connection);
451
493
  }
452
494
  throw error;
453
495
  }
454
496
  finally {
455
497
  if (connection) {
456
498
  connection.release();
457
- log('error', 'Read-only connection released');
499
+ log('info', 'Read-only connection released');
458
500
  }
459
501
  }
460
502
  }
461
- export { profileBanner, describeConnection, executeQuery, getPool, executeWriteQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, clampTimeoutSeconds, describeQueryError, poolPromise, };
503
+ export { profileBanner, describeConnection, executeQuery, getPool, executeWriteQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, setCodeBranchSource, clampTimeoutSeconds, describeQueryError, rollbackQuietly, poolPromise, };
@@ -23,4 +23,24 @@ function isDDLAllowedForSchema(schema) {
23
23
  }
24
24
  return schema in SCHEMA_DDL_PERMISSIONS ? SCHEMA_DDL_PERMISSIONS[schema] : ALLOW_DDL_OPERATION;
25
25
  }
26
- export { isInsertAllowedForSchema, isUpdateAllowedForSchema, isDeleteAllowedForSchema, isDDLAllowedForSchema };
26
+ function writeCapabilities() {
27
+ const kinds = [
28
+ { label: 'INSERT', global: ALLOW_INSERT_OPERATION, perSchema: SCHEMA_INSERT_PERMISSIONS },
29
+ { label: 'UPDATE', global: ALLOW_UPDATE_OPERATION, perSchema: SCHEMA_UPDATE_PERMISSIONS },
30
+ { label: 'DELETE', global: ALLOW_DELETE_OPERATION, perSchema: SCHEMA_DELETE_PERMISSIONS },
31
+ { label: 'DDL', global: ALLOW_DDL_OPERATION, perSchema: SCHEMA_DDL_PERMISSIONS },
32
+ ];
33
+ const capabilities = [];
34
+ for (const { label, global, perSchema } of kinds) {
35
+ if (global) {
36
+ capabilities.push({ label, schemas: null });
37
+ continue;
38
+ }
39
+ const opened = Object.keys(perSchema).filter((schema) => perSchema[schema]);
40
+ if (opened.length > 0) {
41
+ capabilities.push({ label, schemas: opened });
42
+ }
43
+ }
44
+ return capabilities;
45
+ }
46
+ export { isInsertAllowedForSchema, isUpdateAllowedForSchema, isDeleteAllowedForSchema, isDDLAllowedForSchema, writeCapabilities, };
@@ -4,10 +4,26 @@ import { log } from './../utils/index.js';
4
4
  const { Parser } = SqlParser;
5
5
  const parser = new Parser();
6
6
  const READ_STATEMENT_TYPES = new Set(['select', 'show', 'desc', 'explain']);
7
- const WRITE_STATEMENT_TYPES = new Set(['insert', 'update', 'delete', 'create', 'alter', 'drop', 'truncate']);
7
+ const DDL_STATEMENT_TYPES = new Set(['create', 'alter', 'drop', 'truncate', 'rename']);
8
+ const WRITE_STATEMENT_TYPES = new Set(['insert', 'update', 'delete', ...DDL_STATEMENT_TYPES]);
8
9
  function findUnsupportedStatementType(queryTypes) {
9
10
  return queryTypes.find((type) => !READ_STATEMENT_TYPES.has(type) && !WRITE_STATEMENT_TYPES.has(type)) ?? null;
10
11
  }
12
+ const EXECUTABLE_COMMENT_RE = /\/\*!/;
13
+ function hasExecutableComment(sql) {
14
+ return EXECUTABLE_COMMENT_RE.test(sql);
15
+ }
16
+ const OPTIMIZER_HINT_RE = /\/\*\+([\s\S]*?)\*\//g;
17
+ const LIMIT_OVERRIDE_HINT_RE = /\b(MAX_EXECUTION_TIME|SET_VAR)\s*\(/i;
18
+ function findLimitOverrideHint(sql) {
19
+ for (const [, body] of sql.matchAll(OPTIMIZER_HINT_RE)) {
20
+ const hint = body.match(LIMIT_OVERRIDE_HINT_RE);
21
+ if (hint) {
22
+ return hint[1].toUpperCase();
23
+ }
24
+ }
25
+ return null;
26
+ }
11
27
  function findFileExport(sql) {
12
28
  let astOrArray;
13
29
  try {
@@ -56,8 +72,9 @@ function extractReferencedSchemas(sql) {
56
72
  }
57
73
  const defaultSchema = MYSQL_DB ?? null;
58
74
  const schemas = new Set();
59
- const qualified = new Map();
60
- const unqualified = [];
75
+ const names = new Map();
76
+ const deleteTargets = new Set();
77
+ const targetNames = [];
61
78
  const visit = (node) => {
62
79
  if (!isRecord(node)) {
63
80
  return;
@@ -65,17 +82,23 @@ function extractReferencedSchemas(sql) {
65
82
  if ((node.keyword === 'database' || node.keyword === 'schema') && typeof node.type === 'string') {
66
83
  schemas.add(databaseStatementName(node));
67
84
  }
85
+ if (node.type === 'delete' && Array.isArray(node.table)) {
86
+ for (const target of node.table) {
87
+ deleteTargets.add(target);
88
+ }
89
+ }
68
90
  const name = typeof node.table === 'string' ? node.table : typeof node.view === 'string' ? node.view : null;
69
91
  if (node.type !== 'column_ref' && name && (typeof node.db === 'string' || node.db === null)) {
70
- if (typeof node.db === 'string' && node.db) {
71
- schemas.add(node.db);
72
- qualified.set(name.toLowerCase(), node.db);
73
- if (typeof node.as === 'string' && node.as) {
74
- qualified.set(node.as.toLowerCase(), node.db);
75
- }
92
+ if (deleteTargets.has(node) && !node.db) {
93
+ targetNames.push(name.toLowerCase());
76
94
  }
77
95
  else {
78
- unqualified.push(name.toLowerCase());
96
+ const schema = typeof node.db === 'string' && node.db ? node.db : defaultSchema;
97
+ schemas.add(schema);
98
+ const key = (typeof node.as === 'string' && node.as ? node.as : name).toLowerCase();
99
+ const known = names.get(key) ?? new Set();
100
+ known.add(schema);
101
+ names.set(key, known);
79
102
  }
80
103
  }
81
104
  for (const value of Object.values(node)) {
@@ -90,8 +113,10 @@ function extractReferencedSchemas(sql) {
90
113
  }
91
114
  };
92
115
  visit(astOrArray);
93
- for (const name of unqualified) {
94
- schemas.add(qualified.get(name) ?? defaultSchema);
116
+ for (const name of targetNames) {
117
+ for (const schema of names.get(name) ?? [defaultSchema]) {
118
+ schemas.add(schema);
119
+ }
95
120
  }
96
121
  if (schemas.size === 0) {
97
122
  schemas.add(null);
@@ -261,4 +286,4 @@ function isUnparseableIntrospection(sql) {
261
286
  const kind = isIntrospectionQuery(sql).kind;
262
287
  return kind !== null && kind !== 'information_schema' && kind !== 'mysql_schema';
263
288
  }
264
- export { findUnsupportedStatementType, findFileExport, extractReferencedSchemas, getQueryTypes, isIntrospectionQuery, isUnparseableIntrospection, extractQualifiers, stripExplainModifiers, };
289
+ export { DDL_STATEMENT_TYPES, findUnsupportedStatementType, hasExecutableComment, findLimitOverrideHint, findFileExport, extractReferencedSchemas, getQueryTypes, isIntrospectionQuery, isUnparseableIntrospection, extractQualifiers, stripExplainModifiers, };
@@ -122,6 +122,15 @@ export function readSSHConfigHost(alias, configPath = path.join(os.homedir(), '.
122
122
  case 'identityfile':
123
123
  entry.identityFile ??= expandHome(value.replace(/^"|"$/g, ''));
124
124
  break;
125
+ case 'userknownhostsfile':
126
+ entry.userKnownHostsFiles ??=
127
+ value.toLowerCase() === 'none'
128
+ ? []
129
+ : value.split(/\s+/).map((file) => expandHome(file.replace(/^"|"$/g, '')));
130
+ break;
131
+ case 'hostkeyalias':
132
+ entry.hostKeyAlias ??= value;
133
+ break;
125
134
  case 'localforward': {
126
135
  const forward = parseLocalForward(value);
127
136
  if (forward && !entry.localForward) {