Repository navigation
Expand file tree
/
Copy pathsql.ts
More file actions
398 lines (352 loc) · 15.9 KB
/
Copy pathsql.ts
File metadata and controls
398 lines (352 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
const MAX_SUMMARY_LENGTH = 255;
// A single identifier: quoted (`"..."`, `'...'`, or MySQL backticks) or bare. The quoted forms have
// to be matched as a unit, otherwise an identifier containing a space or a dot is cut in half.
const IDENTIFIER = '(?:"[^"]*"|\'[^\']*\'|`[^`]*`|[^\\s(,;).\'"`]+)';
// A table reference can be schema-qualified (`"public"."User"`, `db.schema.table`), with each part
// quoted independently. The whole qualified name is the summary target, since the schema is what
// distinguishes two same-named tables.
const TABLE_NAME = `${IDENTIFIER}(?:\\.${IDENTIFIER})*`;
const DDL_RE = new RegExp(
`^\\s*(?<operation>(?:CREATE|DROP)\\s+(?:TABLE|INDEX)|ALTER\\s+TABLE)(?:\\s+IF\\s+(?:NOT\\s+)?EXISTS)?\\s+(?<table>${TABLE_NAME})`,
'i',
);
// SQLite upserts insert an optional conflict clause between operation and INTO
// (`INSERT OR REPLACE INTO`, https://sqlite.org/lang_insert.html), with `REPLACE INTO` as the
// standalone shorthand. The clause is filler like INTO — stripping it keeps upserts on the same
// low-cardinality summary as plain inserts.
const INSERT_RE = new RegExp(
`^\\s*(?<operation>INSERT|REPLACE)(?:\\s+OR\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\s+INTO\\s+(?<table>${TABLE_NAME})`,
'i',
);
const UPDATE_RE = new RegExp(
`^\\s*(?<operation>UPDATE)(?:\\s+OR\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\s+(?<table>${TABLE_NAME})`,
'i',
);
const DELETE_RE = new RegExp(`^\\s*(?<operation>DELETE)\\s+FROM\\s+(?<table>${TABLE_NAME})`, 'i');
const SELECT_RE = /^\s*\(?\s*(?<operation>SELECT)\b/i;
const PRAGMA_RE = /^\s*(?<operation>PRAGMA)\s+(?<command>\S+)/i;
const TOKEN_RE = /\b(?:FROM|JOIN)\s+|\(\s*(SELECT)\b|\b(?:UNION|INTERSECT|EXCEPT|MINUS)\s+(?:ALL\s+)?(SELECT)\b/gi;
const TABLE_REF_RE = new RegExp(`^${TABLE_NAME}`);
const COMMA_TABLE_RE = new RegExp(`^\\s*,\\s*(${TABLE_NAME})`);
const SUBQUERY_SELECT_RE = /^\(\s*(SELECT)\b/i;
/**
* Derives a low-cardinality summary from a SQL query for use as `db.query.summary`.
*
* Conforms to the OTEL semantic convention for generating query summaries:
* - Preserves original case of operations and identifiers (no normalization)
* - Uses format: `{operation} {target1} {target2} ...`
* - Strips filler words (INTO, FROM) from the operation
* - Captures multiple table targets (JOINs)
* - Handles INSERT...SELECT with both targets
* - Truncates to 255 characters without splitting mid-value
*
* @see https://opentelemetry.io/docs/specs/semconv/database/database-spans/#generating-a-summary-of-the-query
*/
export function getSqlQuerySummary(query: string | undefined): string | undefined {
if (!query) {
return undefined;
}
const pragmaMatch = PRAGMA_RE.exec(query);
if (pragmaMatch?.groups?.['operation'] && pragmaMatch.groups['command']) {
const operation = pragmaMatch.groups['operation'];
const command = pragmaMatch.groups['command'];
const parenIdx = command.indexOf('(');
return truncate(`${operation} ${parenIdx >= 0 ? command.substring(0, parenIdx) : command}`);
}
const ddlMatch = DDL_RE.exec(query);
if (ddlMatch?.groups?.['operation'] && ddlMatch.groups['table']) {
return truncate(`${ddlMatch.groups['operation']} ${ddlMatch.groups['table']}`);
}
const insertMatch = INSERT_RE.exec(query);
if (insertMatch?.groups?.['operation'] && insertMatch.groups['table']) {
const parts = [insertMatch.groups['operation'], insertMatch.groups['table']];
const rest = query.slice(insertMatch[0].length);
const subSelect = /\b(SELECT)\b/i.exec(rest);
if (subSelect?.[1]) {
parts.push(subSelect[1]);
const selectTables = extractTableNames(rest.slice(subSelect.index));
parts.push(...selectTables);
}
return truncate(parts.join(' '));
}
const updateMatch = UPDATE_RE.exec(query);
if (updateMatch?.groups?.['operation'] && updateMatch.groups['table']) {
return truncate(`${updateMatch.groups['operation']} ${updateMatch.groups['table']}`);
}
const deleteMatch = DELETE_RE.exec(query);
if (deleteMatch?.groups?.['operation'] && deleteMatch.groups['table']) {
return truncate(`${deleteMatch.groups['operation']} ${deleteMatch.groups['table']}`);
}
const selectMatch = SELECT_RE.exec(query);
if (selectMatch?.groups?.['operation']) {
const tables = extractTableNames(query.slice(selectMatch[0].length));
if (tables.length > 0) {
return truncate(`${selectMatch.groups['operation']} ${tables.join(' ')}`);
}
return selectMatch.groups['operation'];
}
return truncate(query.trim().split(/\s+/)[0] ?? query);
}
function extractTableNames(sql: string): string[] {
const tables: string[] = [];
TOKEN_RE.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = TOKEN_RE.exec(sql)) !== null) {
if (match[1] || match[2]) {
tables.push((match[1] || match[2])!);
continue;
}
const rest = sql.slice(match.index + match[0].length);
const subqueryMatch = SUBQUERY_SELECT_RE.exec(rest);
if (subqueryMatch?.[1]) {
tables.push(subqueryMatch[1]);
TOKEN_RE.lastIndex = match.index + match[0].length + subqueryMatch[0].length;
continue;
}
const tableMatch = TABLE_REF_RE.exec(rest);
if (!tableMatch) continue;
tables.push(tableMatch[0]);
let afterTable = rest.slice(tableMatch[0].length);
let commaMatch: RegExpExecArray | null;
while ((commaMatch = COMMA_TABLE_RE.exec(afterTable)) !== null) {
if (!commaMatch[1]) break;
tables.push(commaMatch[1]);
afterTable = afterTable.slice(commaMatch[0].length);
}
}
return tables;
}
function truncate(summary: string): string {
if (summary.length <= MAX_SUMMARY_LENGTH) {
return summary;
}
const truncated = summary.substring(0, MAX_SUMMARY_LENGTH);
const lastSpace = truncated.lastIndexOf(' ');
return lastSpace > 0 ? truncated.substring(0, lastSpace) : truncated;
}
let integerLiteralRE: RegExp | undefined;
let mssqlIntegerLiteralRE: RegExp | undefined;
/**
* The lookbehind keeps `$n` and `?n` parameter placeholders out of the match. T-SQL has neither,
* and `$1000` there is a money literal, so `$` only guards a placeholder outside `mssql`.
*
* Lazy init: constructing a lookbehind at module scope evaluates it on import and crashes
* Safari <16.4 browser bundles that reach this file via the core barrel.
*/
function getIntegerLiteralRE(dialect: SqlDialect): RegExp {
if (dialect === 'mssql') {
if (!mssqlIntegerLiteralRE) {
mssqlIntegerLiteralRE = new RegExp('(?<!\\?)-?\\b\\d+\\b', 'g');
}
return mssqlIntegerLiteralRE;
}
if (!integerLiteralRE) {
integerLiteralRE = new RegExp('(?<![$?])-?\\b\\d+\\b', 'g');
}
return integerLiteralRE;
}
/**
* SQL dialect variants that matter for finding the end of a string literal:
* - `standard` (PostgreSQL, SQLite): `"` quotes identifiers, `''` is the only in-string escape,
* and PostgreSQL's `$$…$$` dollar quoting opens a literal.
* - `mysql`: `"` quotes a string literal unless `ANSI_QUOTES` is set, and `\` escapes the next
* character unless `NO_BACKSLASH_ESCAPES` is set. Both default to off, and mysql/mysql2 escape
* inlined values with backslashes, so this is the mode their statements arrive in.
* - `mssql`: `[...]` quotes an identifier, so a `'` inside one is part of the name. `"` quotes
* one too, unless the connection sets `QUOTED_IDENTIFIER OFF`, which tedious leaves on.
*/
export type SqlDialect = 'standard' | 'mysql' | 'mssql';
/**
* Maps a driver or `db.system.name` value to the dialect its statements are written in. Callers
* report different spellings for one engine: knex uses the driver name, Prisma the provider name,
* and OTel the semantic-convention name. An engine we do not know about is lexed as `standard`.
*/
export function toSqlDialect(system: unknown): SqlDialect {
if (system === 'mysql' || system === 'mysql2' || system === 'mariadb') {
return 'mysql';
}
if (system === 'mssql' || system === 'sqlserver' || system === 'microsoft.sql_server') {
return 'mssql';
}
return 'standard';
}
// Sticky, so the scanner can test one position without slicing the query on every `$`.
const DOLLAR_QUOTE_RE = /\$(?:[A-Za-z_]\w*)?\$/y;
/**
* Returns the index just past the run's closing `delimiter`, or -1 if the run never closes. The
* caller cannot derive that from the index alone: a query ending in `[a]]` consumed a doubled
* delimiter, not a closing one.
*
* A doubled delimiter (`''`) escapes itself in every dialect; backslash escapes are dialect- and
* context-dependent, so the caller decides.
*/
function findQuotedRunEnd(sql: string, start: number, delimiter: string, backslashEscapes: boolean): number {
for (let i = start + 1; i < sql.length; i++) {
const char = sql[i];
if (backslashEscapes && char === '\\') {
i++;
} else if (char === delimiter) {
if (sql[i + 1] !== delimiter) {
return i + 1;
}
i++;
}
}
return -1;
}
/**
* Replaces every string literal with `?` and drops every comment, in one pass.
*
* Doing this by scanning rather than by regex is what keeps quote state and comment state from
* being decided independently: a regex for `'...'` cannot see that the quote it stopped at was
* backslash-escaped, and a regex for `--...` cannot see that the `--` sits inside a literal. Both
* mistakes end with user data surviving into `db.query.text` and `db.query.summary`.
*
* Quoted identifiers are preserved — they are the table and column names the query summary is
* built from.
*/
function stripLiteralsAndComments(sql: string, dialect: SqlDialect): string {
const isMysql = dialect === 'mysql';
const out: string[] = [];
let i = 0;
while (i < sql.length) {
const char = sql[i]!;
const next = sql[i + 1];
if ((char === '-' && next === '-') || (isMysql && char === '#')) {
const lineEnd = sql.indexOf('\n', i);
i = lineEnd === -1 ? sql.length : lineEnd;
continue;
}
if (char === '/' && next === '*') {
const commentEnd = sql.indexOf('*/', i + 2);
i = commentEnd === -1 ? sql.length : commentEnd + 2;
continue;
}
// In a dollar-quoted body (`$$body$$`, `$tag$body$tag$`) nothing has syntax meaning. Read the
// previous character from the query, not from `out`, where a dropped comment would leave `$$`
// looking like part of an identifier. Of the `standard` engines only PostgreSQL has dollar
// quoting. SQLite `$name` parameters do not match the tag pattern, apart from the rare `$a$b`.
if (dialect === 'standard' && char === '$' && !isIdentifierChar(sql[i - 1])) {
const tag = matchDollarQuoteTag(sql, i);
if (tag) {
const bodyEnd = sql.indexOf(tag, i + tag.length);
i = bodyEnd === -1 ? sql.length : bodyEnd + tag.length;
out.push('?');
continue;
}
}
const identifierCloser = getIdentifierCloser(char, dialect);
if (identifierCloser) {
const runEnd = findQuotedRunEnd(sql, i, identifierCloser, false);
// A run that never closes is not an identifier, so it collapses instead of being copied out.
// Copying would carry every literal in the rest of the statement through unlexed.
out.push(runEnd === -1 ? '?' : sql.slice(i, runEnd));
i = runEnd === -1 ? sql.length : runEnd;
continue;
}
if (char === "'" || (char === '"' && isMysql)) {
// A prefix like `X'1A'`, `B'01'`, `N'…'` or PostgreSQL's `E'a\nb'` is part of the literal, so it has
// to collapse into the same `?` instead of being left behind as a bare identifier.
const prefix = char === "'" ? getLiteralPrefix(out, dialect) : undefined;
if (prefix) {
out.pop();
}
const runEnd = findQuotedRunEnd(sql, i, char, isMysql || prefix === 'E');
i = runEnd === -1 ? sql.length : runEnd;
out.push('?');
continue;
}
out.push(char);
i++;
}
return out.join('');
}
/**
* Returns the character that closes an identifier opened by `char`, or undefined if `char` opens
* none. SQL Server brackets close on `]`, and `]]` escapes a `]` inside the name, which is the same
* doubling rule `findQuotedRunEnd` applies to quotes.
*/
function getIdentifierCloser(char: string, dialect: SqlDialect): string | undefined {
if (char === '`') {
return '`';
}
if (char === '"' && dialect !== 'mysql') {
return '"';
}
return char === '[' && dialect === 'mssql' ? ']' : undefined;
}
/** Whether `char` can appear inside an identifier. `undefined` (start of query) counts as a break. */
function isIdentifierChar(char: string | undefined): boolean {
return char !== undefined && /[\w$]/.test(char);
}
/** Returns the opening dollar-quote tag at `start` (`$$` or `$tag$`), or undefined if there is none. */
function matchDollarQuoteTag(sql: string, start: number): string | undefined {
DOLLAR_QUOTE_RE.lastIndex = start;
return DOLLAR_QUOTE_RE.exec(sql)?.[0];
}
/**
* Returns the literal-prefix character immediately before a `'`, if there is one: `X`/`B` for
* hex/binary literals, `N` for a national-character literal (SQL Server, MySQL), or `E` for a
* PostgreSQL escape string (which honors backslash escapes).
*/
function getLiteralPrefix(out: string[], dialect: SqlDialect): 'X' | 'B' | 'N' | 'E' | undefined {
const last = out[out.length - 1];
// A prefix only counts when it stands alone — the `X` in `MAX'...'` belongs to the identifier
if (last?.length !== 1 || isIdentifierChar(out[out.length - 2]?.slice(-1))) {
return undefined;
}
const prefix = last.toUpperCase();
if (prefix === 'X' || prefix === 'B' || prefix === 'N') {
return prefix;
}
return prefix === 'E' && dialect === 'standard' ? 'E' : undefined;
}
/**
* Sanitize SQL query as per the OTEL semantic conventions
* https://opentelemetry.io/docs/specs/semconv/database/database-spans/#sanitization-of-dbquerytext
*
* Parameter placeholders survive: PostgreSQL `$n`, SQLite `?n`, and named forms like `:name` and
* `@name`. Per the OTEL spec they mark a parameterized query, so only values (strings, numbers,
* booleans) are sanitized.
*
* Pass `dialect` when the statement comes from a driver whose literals are not standard-quoted;
* see {@link SqlDialect}.
*/
export function sanitizeSqlQuery(sqlQuery: string | undefined, dialect: SqlDialect = 'standard'): string {
if (!sqlQuery) {
return 'Unknown SQL Query';
}
return (
// Strip comments and string literals first: everything below is a regex that cannot tell
// whether it is looking at SQL syntax or at a user-supplied value.
stripLiteralsAndComments(sqlQuery, dialect)
.replace(/;\s*$/, '') // Remove trailing semicolons
// Collapse whitespace to a single space (after removing comments)
.replace(/\s+/g, ' ')
.trim() // Remove extra spaces and trim
// Sanitize hex numbers
.replace(/\b0x[0-9A-Fa-f]+/gi, '?')
// Sanitize boolean literals
.replace(/\b(?:TRUE|FALSE)\b/gi, '?')
// Sanitize numeric literals (preserve $n placeholders via negative lookbehind)
.replace(/-?\b\d+\.?\d*[eE][+-]?\d+\b/g, '?') // Scientific notation
.replace(/-?\b\d+\.\d+\b/g, '?') // Decimals
.replace(/-?\.\d+\b/g, '?') // Decimals starting with dot
.replace(getIntegerLiteralRE(dialect), '?') // Integers (NOT parameter placeholders)
// Collapse IN clauses for cardinality (both ? and $n variants)
.replace(/\bIN\b\s*\(\s*\?(?:\s*,\s*\?)*\s*\)/gi, 'IN (?)')
.replace(/\bIN\b\s*\(\s*\$\d+(?:\s*,\s*\$\d+)*\s*\)/gi, 'IN ($?)')
);
}
/**
* Sanitizes a collected SQL statement and derives the matching `db.query.summary`, the pair the SQL
* integrations attach to their spans. Both come back `undefined` when there is no statement, so an
* empty query omits the attributes instead of reporting the sanitizer's fallback text.
*/
export function sanitizeSqlQueryWithSummary(
sqlQuery: string | undefined,
dialect?: SqlDialect,
): { queryText: string | undefined; querySummary: string | undefined } {
const queryText = sqlQuery ? sanitizeSqlQuery(sqlQuery, dialect) : undefined;
return { queryText, querySummary: getSqlQuerySummary(queryText) };
}