1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | 'use strict';
|
19 |
|
20 | const {
|
21 | memoizedTagFunction,
|
22 | trimCommonWhitespaceFromLines,
|
23 | } = require('template-tag-common');
|
24 |
|
25 | const LITERAL_BACKTICK_FIXUP_PATTERN = /((?:[^\\]|\\[^`])+)|\\(`)(?!`)/g;
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | function prepareStrings(strings) {
|
35 | const raw = trimCommonWhitespaceFromLines(strings).raw.slice();
|
36 | for (let i = 0, len = raw.length; i < len; ++i) {
|
37 |
|
38 | raw[i] = raw[i].replace(LITERAL_BACKTICK_FIXUP_PATTERN, '$1$2');
|
39 | }
|
40 | return raw;
|
41 | }
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 | function makeSqlTagFunction(
|
48 | { makeLexer },
|
49 | escape,
|
50 | escapeDelimitedValue,
|
51 | fixupBackticks,
|
52 | decorateOutput) {
|
53 | |
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 | function computeStatic(strings) {
|
66 | const chunks = fixupBackticks ? prepareStrings(strings) : strings.raw;
|
67 | const lexer = makeLexer();
|
68 |
|
69 | const delimiters = [];
|
70 | for (let i = 0, len = chunks.length; i < len; ++i) {
|
71 | const chunk = String(chunks[i]);
|
72 | delimiters.push(lexer(chunk));
|
73 | }
|
74 |
|
75 |
|
76 | lexer(null);
|
77 |
|
78 | return { delimiters, chunks };
|
79 | }
|
80 |
|
81 | function defangMergeHazard(before, escaped, after) {
|
82 | const escapedLast = escaped[escaped.length - 1];
|
83 | if ('"\'`'.indexOf(escapedLast) < 0) {
|
84 |
|
85 | return escaped;
|
86 | }
|
87 |
|
88 | let escapedSetOff = escaped;
|
89 | const lastBefore = before[before.length - 1];
|
90 | if (escapedLast === escaped[0] && escapedLast === lastBefore) {
|
91 | escapedSetOff = ` ${ escapedSetOff }`;
|
92 | }
|
93 | if (escapedLast === after[0]) {
|
94 | escapedSetOff += ' ';
|
95 | }
|
96 | return escapedSetOff;
|
97 | }
|
98 |
|
99 | function interpolateSqlIntoFragment(
|
100 | { stringifyObjects, timeZone, forbidQualified },
|
101 | { delimiters, chunks },
|
102 | strings, values) {
|
103 |
|
104 | let [ result ] = chunks;
|
105 | for (let i = 1, len = chunks.length; i < len; ++i) {
|
106 | const chunk = chunks[i];
|
107 |
|
108 |
|
109 | const delimiter = delimiters[i - 1];
|
110 | const value = values[i - 1];
|
111 |
|
112 | const escaped = delimiter ?
|
113 | escapeDelimitedValue(value, delimiter, timeZone, forbidQualified) :
|
114 | defangMergeHazard(
|
115 | result,
|
116 | escape(value, stringifyObjects, timeZone),
|
117 | chunk);
|
118 |
|
119 | result += escaped + chunk;
|
120 | }
|
121 |
|
122 | return decorateOutput(result);
|
123 | }
|
124 |
|
125 | return memoizedTagFunction(computeStatic, interpolateSqlIntoFragment);
|
126 | }
|
127 |
|
128 | module.exports.makeSqlTagFunction = makeSqlTagFunction;
|