(query: string | undefined)
| 35 | * @see https://opentelemetry.io/docs/specs/semconv/database/database-spans/#generating-a-summary-of-the-query |
| 36 | */ |
| 37 | export function getSqlQuerySummary(query: string | undefined): string | undefined { |
| 38 | if (!query) { |
| 39 | return undefined; |
| 40 | } |
| 41 | |
| 42 | const pragmaMatch = PRAGMA_RE.exec(query); |
| 43 | if (pragmaMatch?.groups?.['operation'] && pragmaMatch.groups['command']) { |
| 44 | const operation = pragmaMatch.groups['operation']; |
| 45 | const command = pragmaMatch.groups['command']; |
| 46 | const parenIdx = command.indexOf('('); |
| 47 | return truncate(`${operation} ${parenIdx >= 0 ? command.substring(0, parenIdx) : command}`); |
| 48 | } |
| 49 | |
| 50 | const ddlMatch = DDL_RE.exec(query); |
| 51 | if (ddlMatch?.groups?.['operation'] && ddlMatch.groups['table']) { |
| 52 | return truncate(`${ddlMatch.groups['operation']} ${ddlMatch.groups['table']}`); |
| 53 | } |
| 54 | |
| 55 | const insertMatch = INSERT_RE.exec(query); |
| 56 | if (insertMatch?.groups?.['operation'] && insertMatch.groups['table']) { |
| 57 | const parts = [insertMatch.groups['operation'], insertMatch.groups['table']]; |
| 58 | const rest = query.slice(insertMatch[0].length); |
| 59 | const subSelect = /\b(SELECT)\b/i.exec(rest); |
| 60 | if (subSelect?.[1]) { |
| 61 | parts.push(subSelect[1]); |
| 62 | const selectTables = extractTableNames(rest.slice(subSelect.index)); |
| 63 | parts.push(...selectTables); |
| 64 | } |
| 65 | return truncate(parts.join(' ')); |
| 66 | } |
| 67 | |
| 68 | const updateMatch = UPDATE_RE.exec(query); |
| 69 | if (updateMatch?.groups?.['operation'] && updateMatch.groups['table']) { |
| 70 | return truncate(`${updateMatch.groups['operation']} ${updateMatch.groups['table']}`); |
| 71 | } |
| 72 | |
| 73 | const deleteMatch = DELETE_RE.exec(query); |
| 74 | if (deleteMatch?.groups?.['operation'] && deleteMatch.groups['table']) { |
| 75 | return truncate(`${deleteMatch.groups['operation']} ${deleteMatch.groups['table']}`); |
| 76 | } |
| 77 | |
| 78 | const selectMatch = SELECT_RE.exec(query); |
| 79 | if (selectMatch?.groups?.['operation']) { |
| 80 | const tables = extractTableNames(query.slice(selectMatch[0].length)); |
| 81 | if (tables.length > 0) { |
| 82 | return truncate(`${selectMatch.groups['operation']} ${tables.join(' ')}`); |
| 83 | } |
| 84 | return selectMatch.groups['operation']; |
| 85 | } |
| 86 | |
| 87 | return truncate(query.trim().split(/\s+/)[0] ?? query); |
| 88 | } |
| 89 | |
| 90 | function extractTableNames(sql: string): string[] { |
| 91 | const tables: string[] = []; |
no test coverage detected