| 14 | * @returns The SQL with replacements rewritten in their dialect-specific syntax. |
| 15 | */ |
| 16 | export function injectReplacements( |
| 17 | sqlString: string, |
| 18 | dialect: AbstractDialect, |
| 19 | replacements: BindOrReplacements |
| 20 | ): string { |
| 21 | if (replacements == null) { |
| 22 | return sqlString; |
| 23 | } |
| 24 | |
| 25 | if (!Array.isArray(replacements) && !isPlainObject(replacements)) { |
| 26 | throw new TypeError(`"replacements" must be an array or a plain object, but received ${JSON.stringify(replacements)} instead.`); |
| 27 | } |
| 28 | |
| 29 | const isNamedReplacements = isPlainObject(replacements); |
| 30 | const isPositionalReplacements = Array.isArray(replacements); |
| 31 | let lastConsumedPositionalReplacementIndex = -1; |
| 32 | |
| 33 | let output = ''; |
| 34 | |
| 35 | let currentDollarStringTagName = null; |
| 36 | let isString = false; |
| 37 | let isColumn = false; |
| 38 | let previousSliceEnd = 0; |
| 39 | let isSingleLineComment = false; |
| 40 | let isCommentBlock = false; |
| 41 | let stringIsBackslashEscapable = false; |
| 42 | |
| 43 | for (let i = 0; i < sqlString.length; i++) { |
| 44 | const char = sqlString[i]; |
| 45 | |
| 46 | if (isColumn) { |
| 47 | if (char === dialect.TICK_CHAR_RIGHT) { |
| 48 | isColumn = false; |
| 49 | } |
| 50 | |
| 51 | continue; |
| 52 | } |
| 53 | |
| 54 | if (isString) { |
| 55 | if ( |
| 56 | char === '\'' && |
| 57 | (!stringIsBackslashEscapable || !isBackslashEscaped(sqlString, i - 1)) |
| 58 | ) { |
| 59 | isString = false; |
| 60 | stringIsBackslashEscapable = false; |
| 61 | } |
| 62 | |
| 63 | continue; |
| 64 | } |
| 65 | |
| 66 | if (currentDollarStringTagName !== null) { |
| 67 | if (char !== '$') { |
| 68 | continue; |
| 69 | } |
| 70 | |
| 71 | const remainingString = sqlString.slice(i, sqlString.length); |
| 72 | |
| 73 | const dollarStringStartMatch = remainingString.match(/^\$(?<name>[a-z_][0-9a-z_]*)?(\$)/i); |