/
createRawSqlSqlFragment.js
43 lines (33 loc) · 1.16 KB
/
createRawSqlSqlFragment.js
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
// @flow
import type {
RawSqlTokenType,
SqlFragmentType
} from '../types';
import {
UnexpectedStateError
} from '../errors';
export default (token: RawSqlTokenType, greatestParameterPosition: number): SqlFragmentType => {
let sql = '';
let leastMatchedParameterPosition = Infinity;
let greatestMatchedParameterPosition = 0;
sql += token.sql.replace(/\$(\d+)/g, (match, g1) => {
const parameterPosition = parseInt(g1, 10);
if (parameterPosition > greatestMatchedParameterPosition) {
greatestMatchedParameterPosition = parameterPosition;
}
if (parameterPosition < leastMatchedParameterPosition) {
leastMatchedParameterPosition = parameterPosition;
}
return '$' + (parameterPosition + greatestParameterPosition);
});
if (greatestMatchedParameterPosition > token.values.length) {
throw new UnexpectedStateError('The greatest parameter position is greater than the number of parameter values.');
}
if (leastMatchedParameterPosition !== Infinity && leastMatchedParameterPosition !== 1) {
throw new UnexpectedStateError('Parameter position must start at 1.');
}
return {
parameters: token.values,
sql
};
};