postgrejs 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/CHANGELOG.md +814 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -0
  4. package/cjs/connection/bind-param.js +10 -0
  5. package/cjs/connection/connection.js +279 -0
  6. package/cjs/connection/cursor.js +93 -0
  7. package/cjs/connection/intl-connection.js +243 -0
  8. package/cjs/connection/pool.js +226 -0
  9. package/cjs/connection/portal.js +148 -0
  10. package/cjs/connection/prepared-statement.js +217 -0
  11. package/cjs/constants.js +250 -0
  12. package/cjs/data-type-map.js +119 -0
  13. package/cjs/data-types/bool-type.js +27 -0
  14. package/cjs/data-types/box-type.js +52 -0
  15. package/cjs/data-types/bytea-type.js +29 -0
  16. package/cjs/data-types/char-type.js +27 -0
  17. package/cjs/data-types/circle-type.js +48 -0
  18. package/cjs/data-types/date-type.js +67 -0
  19. package/cjs/data-types/float4-type.js +25 -0
  20. package/cjs/data-types/float8-type.js +25 -0
  21. package/cjs/data-types/int2-type.js +26 -0
  22. package/cjs/data-types/int2-vector-type.js +38 -0
  23. package/cjs/data-types/int4-type.js +26 -0
  24. package/cjs/data-types/int8-type.js +31 -0
  25. package/cjs/data-types/json-type.js +38 -0
  26. package/cjs/data-types/jsonb-type.js +42 -0
  27. package/cjs/data-types/lseg-type.js +52 -0
  28. package/cjs/data-types/numeric-type.js +125 -0
  29. package/cjs/data-types/oid-type.js +32 -0
  30. package/cjs/data-types/point-type.js +39 -0
  31. package/cjs/data-types/time-type.js +54 -0
  32. package/cjs/data-types/timestamp-type.js +81 -0
  33. package/cjs/data-types/timestamptz-type.js +73 -0
  34. package/cjs/data-types/uuid-type.js +39 -0
  35. package/cjs/data-types/varchar-type.js +27 -0
  36. package/cjs/index.js +41 -0
  37. package/cjs/interfaces/command-result.js +2 -0
  38. package/cjs/interfaces/data-mapping-options.js +2 -0
  39. package/cjs/interfaces/data-type.js +2 -0
  40. package/cjs/interfaces/database-connection-params.js +2 -0
  41. package/cjs/interfaces/field-info.js +2 -0
  42. package/cjs/interfaces/query-options.js +2 -0
  43. package/cjs/interfaces/query-result.js +2 -0
  44. package/cjs/interfaces/script-execute-options.js +2 -0
  45. package/cjs/interfaces/script-result.js +2 -0
  46. package/cjs/interfaces/statement-prepare-options.js +2 -0
  47. package/cjs/package.json +3 -0
  48. package/cjs/protocol/backend.js +256 -0
  49. package/cjs/protocol/buffer-reader.js +78 -0
  50. package/cjs/protocol/database-error.js +17 -0
  51. package/cjs/protocol/frontend.js +218 -0
  52. package/cjs/protocol/pg-socket.js +345 -0
  53. package/cjs/protocol/protocol.js +71 -0
  54. package/cjs/protocol/sasl.js +108 -0
  55. package/cjs/protocol/smart-buffer.js +195 -0
  56. package/cjs/safe-event-emitter.js +17 -0
  57. package/cjs/types.js +2 -0
  58. package/cjs/util/array-calculatedim.js +19 -0
  59. package/cjs/util/bigint-methods.js +42 -0
  60. package/cjs/util/config-from-env.js +30 -0
  61. package/cjs/util/connection-config.js +65 -0
  62. package/cjs/util/convert-row-to-object.js +13 -0
  63. package/cjs/util/decode-binaryarray.js +39 -0
  64. package/cjs/util/encode-binaryarray.js +45 -0
  65. package/cjs/util/escape-literal.js +27 -0
  66. package/cjs/util/fast-parseint.js +32 -0
  67. package/cjs/util/get-parsers.js +42 -0
  68. package/cjs/util/parse-array.js +61 -0
  69. package/cjs/util/parse-datetime.js +38 -0
  70. package/cjs/util/parse-row.js +11 -0
  71. package/cjs/util/parse-time.js +29 -0
  72. package/cjs/util/stringify-arrayliteral.js +38 -0
  73. package/cjs/util/stringify-for-sql.js +30 -0
  74. package/cjs/util/wrap-row-description.js +35 -0
  75. package/esm/connection/bind-param.js +6 -0
  76. package/esm/connection/connection.js +275 -0
  77. package/esm/connection/cursor.js +86 -0
  78. package/esm/connection/intl-connection.js +238 -0
  79. package/esm/connection/pool.js +222 -0
  80. package/esm/connection/portal.js +144 -0
  81. package/esm/connection/prepared-statement.js +213 -0
  82. package/esm/constants.js +247 -0
  83. package/esm/data-type-map.js +115 -0
  84. package/esm/data-types/bool-type.js +24 -0
  85. package/esm/data-types/box-type.js +49 -0
  86. package/esm/data-types/bytea-type.js +23 -0
  87. package/esm/data-types/char-type.js +24 -0
  88. package/esm/data-types/circle-type.js +45 -0
  89. package/esm/data-types/date-type.js +64 -0
  90. package/esm/data-types/float4-type.js +22 -0
  91. package/esm/data-types/float8-type.js +22 -0
  92. package/esm/data-types/int2-type.js +23 -0
  93. package/esm/data-types/int2-vector-type.js +35 -0
  94. package/esm/data-types/int4-type.js +23 -0
  95. package/esm/data-types/int8-type.js +28 -0
  96. package/esm/data-types/json-type.js +35 -0
  97. package/esm/data-types/jsonb-type.js +39 -0
  98. package/esm/data-types/lseg-type.js +49 -0
  99. package/esm/data-types/numeric-type.js +121 -0
  100. package/esm/data-types/oid-type.js +29 -0
  101. package/esm/data-types/point-type.js +36 -0
  102. package/esm/data-types/time-type.js +51 -0
  103. package/esm/data-types/timestamp-type.js +78 -0
  104. package/esm/data-types/timestamptz-type.js +70 -0
  105. package/esm/data-types/uuid-type.js +36 -0
  106. package/esm/data-types/varchar-type.js +24 -0
  107. package/esm/index.js +25 -0
  108. package/esm/interfaces/command-result.js +1 -0
  109. package/esm/interfaces/data-mapping-options.js +1 -0
  110. package/esm/interfaces/data-type.js +1 -0
  111. package/esm/interfaces/database-connection-params.js +1 -0
  112. package/esm/interfaces/field-info.js +1 -0
  113. package/esm/interfaces/query-options.js +1 -0
  114. package/esm/interfaces/query-result.js +1 -0
  115. package/esm/interfaces/script-execute-options.js +1 -0
  116. package/esm/interfaces/script-result.js +1 -0
  117. package/esm/interfaces/statement-prepare-options.js +1 -0
  118. package/esm/protocol/backend.js +252 -0
  119. package/esm/protocol/buffer-reader.js +74 -0
  120. package/esm/protocol/database-error.js +13 -0
  121. package/esm/protocol/frontend.js +214 -0
  122. package/esm/protocol/pg-socket.js +338 -0
  123. package/esm/protocol/protocol.js +68 -0
  124. package/esm/protocol/sasl.js +102 -0
  125. package/esm/protocol/smart-buffer.js +168 -0
  126. package/esm/safe-event-emitter.js +13 -0
  127. package/esm/types.js +1 -0
  128. package/esm/util/array-calculatedim.js +15 -0
  129. package/esm/util/bigint-methods.js +37 -0
  130. package/esm/util/config-from-env.js +26 -0
  131. package/esm/util/connection-config.js +57 -0
  132. package/esm/util/convert-row-to-object.js +9 -0
  133. package/esm/util/decode-binaryarray.js +35 -0
  134. package/esm/util/encode-binaryarray.js +41 -0
  135. package/esm/util/escape-literal.js +23 -0
  136. package/esm/util/fast-parseint.js +28 -0
  137. package/esm/util/get-parsers.js +38 -0
  138. package/esm/util/parse-array.js +57 -0
  139. package/esm/util/parse-datetime.js +34 -0
  140. package/esm/util/parse-row.js +7 -0
  141. package/esm/util/parse-time.js +25 -0
  142. package/esm/util/stringify-arrayliteral.js +34 -0
  143. package/esm/util/stringify-for-sql.js +25 -0
  144. package/esm/util/wrap-row-description.js +31 -0
  145. package/package.json +54 -0
  146. package/typings/connection/bind-param.d.ts +6 -0
  147. package/typings/connection/connection.d.ts +110 -0
  148. package/typings/connection/cursor.d.ts +25 -0
  149. package/typings/connection/intl-connection.d.ts +40 -0
  150. package/typings/connection/pool.d.ts +52 -0
  151. package/typings/connection/portal.d.ts +23 -0
  152. package/typings/connection/prepared-statement.d.ts +27 -0
  153. package/typings/constants.d.ts +130 -0
  154. package/typings/data-type-map.d.ts +11 -0
  155. package/typings/data-types/bool-type.d.ts +3 -0
  156. package/typings/data-types/box-type.d.ts +3 -0
  157. package/typings/data-types/bytea-type.d.ts +3 -0
  158. package/typings/data-types/char-type.d.ts +3 -0
  159. package/typings/data-types/circle-type.d.ts +3 -0
  160. package/typings/data-types/date-type.d.ts +3 -0
  161. package/typings/data-types/float4-type.d.ts +3 -0
  162. package/typings/data-types/float8-type.d.ts +3 -0
  163. package/typings/data-types/int2-type.d.ts +3 -0
  164. package/typings/data-types/int2-vector-type.d.ts +3 -0
  165. package/typings/data-types/int4-type.d.ts +3 -0
  166. package/typings/data-types/int8-type.d.ts +3 -0
  167. package/typings/data-types/json-type.d.ts +3 -0
  168. package/typings/data-types/jsonb-type.d.ts +3 -0
  169. package/typings/data-types/lseg-type.d.ts +3 -0
  170. package/typings/data-types/numeric-type.d.ts +12 -0
  171. package/typings/data-types/oid-type.d.ts +4 -0
  172. package/typings/data-types/point-type.d.ts +3 -0
  173. package/typings/data-types/time-type.d.ts +3 -0
  174. package/typings/data-types/timestamp-type.d.ts +3 -0
  175. package/typings/data-types/timestamptz-type.d.ts +3 -0
  176. package/typings/data-types/uuid-type.d.ts +3 -0
  177. package/typings/data-types/varchar-type.d.ts +3 -0
  178. package/typings/index.d.ts +25 -0
  179. package/typings/interfaces/command-result.d.ts +28 -0
  180. package/typings/interfaces/data-mapping-options.d.ts +9 -0
  181. package/typings/interfaces/data-type.d.ts +31 -0
  182. package/typings/interfaces/database-connection-params.d.ts +38 -0
  183. package/typings/interfaces/field-info.d.ts +46 -0
  184. package/typings/interfaces/query-options.d.ts +46 -0
  185. package/typings/interfaces/query-result.d.ts +8 -0
  186. package/typings/interfaces/script-execute-options.d.ts +26 -0
  187. package/typings/interfaces/script-result.d.ts +15 -0
  188. package/typings/interfaces/statement-prepare-options.d.ts +13 -0
  189. package/typings/protocol/backend.d.ts +9 -0
  190. package/typings/protocol/buffer-reader.d.ts +18 -0
  191. package/typings/protocol/database-error.d.ts +20 -0
  192. package/typings/protocol/frontend.d.ts +59 -0
  193. package/typings/protocol/pg-socket.d.ts +51 -0
  194. package/typings/protocol/protocol.d.ts +180 -0
  195. package/typings/protocol/sasl.d.ts +13 -0
  196. package/typings/protocol/smart-buffer.d.ts +39 -0
  197. package/typings/safe-event-emitter.d.ts +5 -0
  198. package/typings/types.d.ts +15 -0
  199. package/typings/util/array-calculatedim.d.ts +1 -0
  200. package/typings/util/bigint-methods.d.ts +3 -0
  201. package/typings/util/config-from-env.d.ts +2 -0
  202. package/typings/util/connection-config.d.ts +3 -0
  203. package/typings/util/convert-row-to-object.d.ts +2 -0
  204. package/typings/util/decode-binaryarray.d.ts +4 -0
  205. package/typings/util/encode-binaryarray.d.ts +5 -0
  206. package/typings/util/escape-literal.d.ts +1 -0
  207. package/typings/util/fast-parseint.d.ts +1 -0
  208. package/typings/util/get-parsers.d.ts +4 -0
  209. package/typings/util/parse-array.d.ts +5 -0
  210. package/typings/util/parse-datetime.d.ts +1 -0
  211. package/typings/util/parse-row.d.ts +3 -0
  212. package/typings/util/parse-time.d.ts +3 -0
  213. package/typings/util/stringify-arrayliteral.d.ts +3 -0
  214. package/typings/util/stringify-for-sql.d.ts +4 -0
  215. package/typings/util/wrap-row-description.d.ts +5 -0
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.escapeLiteral = void 0;
4
+ // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
5
+ function escapeLiteral(str) {
6
+ let backSlash = false;
7
+ let out = "'";
8
+ let i;
9
+ let c;
10
+ const l = str.length;
11
+ for (i = 0; i < l; i++) {
12
+ c = str[i];
13
+ if (c === "'")
14
+ out += c + c;
15
+ else if (c === '\\') {
16
+ out += c + c;
17
+ backSlash = true;
18
+ }
19
+ else
20
+ out += c;
21
+ }
22
+ out += "'";
23
+ if (backSlash)
24
+ out = ' E' + out;
25
+ return out;
26
+ }
27
+ exports.escapeLiteral = escapeLiteral;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fastParseInt = void 0;
4
+ function fastParseInt(str) {
5
+ /* istanbul ignore next */
6
+ if (typeof str === 'number')
7
+ return Math.floor(str);
8
+ // noinspection SuspiciousTypeOfGuard
9
+ if (typeof str !== 'string')
10
+ return NaN;
11
+ const strLength = str.length;
12
+ let res = 0;
13
+ let i = 0;
14
+ let neg = false;
15
+ if (str.startsWith('-')) {
16
+ neg = true;
17
+ i++;
18
+ }
19
+ do {
20
+ const charCode = str.charCodeAt(i);
21
+ /* istanbul ignore next */
22
+ if (charCode === 46)
23
+ return res;
24
+ /* istanbul ignore next */
25
+ if (charCode < 48 || charCode > 57)
26
+ return NaN;
27
+ res *= 10;
28
+ res += charCode - 48;
29
+ } while (++i < strLength);
30
+ return neg ? -res : res;
31
+ }
32
+ exports.fastParseInt = fastParseInt;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getParsers = void 0;
4
+ const constants_js_1 = require("../constants.js");
5
+ const decode_binaryarray_js_1 = require("./decode-binaryarray.js");
6
+ const parse_array_js_1 = require("./parse-array.js");
7
+ const DefaultColumnParser = (v) => v;
8
+ function getParsers(typeMap, fields) {
9
+ const parsers = new Array(fields.length);
10
+ const l = fields.length;
11
+ let f;
12
+ let i;
13
+ for (i = 0; i < l; i++) {
14
+ f = fields[i];
15
+ const dataTypeReg = typeMap.get(f.dataTypeId);
16
+ if (dataTypeReg) {
17
+ const isArray = !!dataTypeReg.elementsOID;
18
+ if (f.format === constants_js_1.DataFormat.binary) {
19
+ const decode = dataTypeReg.parseBinary;
20
+ if (decode) {
21
+ parsers[i] = !isArray
22
+ ? decode
23
+ : (v, options) => (0, decode_binaryarray_js_1.decodeBinaryArray)(v, decode, options);
24
+ }
25
+ }
26
+ else if (f.format === constants_js_1.DataFormat.text) {
27
+ const parse = dataTypeReg.parseText;
28
+ if (parse) {
29
+ parsers[i] = !isArray
30
+ ? parse
31
+ : (v, options) => (0, parse_array_js_1.parsePostgresArray)(v, {
32
+ transform: x => parse(x, options),
33
+ separator: dataTypeReg.arraySeparator,
34
+ });
35
+ }
36
+ }
37
+ }
38
+ parsers[i] = parsers[i] || DefaultColumnParser;
39
+ }
40
+ return parsers;
41
+ }
42
+ exports.getParsers = getParsers;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parsePostgresArray = void 0;
4
+ function parsePostgresArray(s, opts) {
5
+ if (!s)
6
+ return;
7
+ const sep = (opts?.separator || ',').substring(0, 1);
8
+ const transform = opts?.transform;
9
+ const len = s.length;
10
+ let idx = 0;
11
+ const out = [];
12
+ const iterate = (arr) => {
13
+ let c;
14
+ let exactlyValue = false;
15
+ let token = '';
16
+ let quote = '';
17
+ while (idx < len) {
18
+ c = s.charAt(idx++);
19
+ if (!quote) {
20
+ if (!token && c === '{') {
21
+ const a = [];
22
+ arr.push(a);
23
+ iterate(a);
24
+ continue;
25
+ }
26
+ if (c === '}' || c === sep) {
27
+ if (token) {
28
+ if (token === 'NULL' && !exactlyValue)
29
+ arr.push(null);
30
+ else
31
+ arr.push(transform ? transform(token) : token);
32
+ exactlyValue = false;
33
+ }
34
+ token = '';
35
+ if (c === '}')
36
+ return;
37
+ continue;
38
+ }
39
+ }
40
+ if (c === '\\') {
41
+ c = s.charAt(idx++);
42
+ token += c;
43
+ continue;
44
+ }
45
+ if (c === '"' || c === "'") {
46
+ if (quote && quote === c) {
47
+ quote = '';
48
+ }
49
+ else {
50
+ exactlyValue = true;
51
+ quote = c;
52
+ }
53
+ continue;
54
+ }
55
+ token += c;
56
+ }
57
+ };
58
+ iterate(out);
59
+ return out.length ? out[0] : undefined;
60
+ }
61
+ exports.parsePostgresArray = parsePostgresArray;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseDateTime = void 0;
4
+ // noinspection RegExpUnnecessaryNonCapturingGroup
5
+ const fast_parseint_js_1 = require("./fast-parseint.js");
6
+ // noinspection RegExpUnnecessaryNonCapturingGroup
7
+ const TIMESTAMP_PATTERN =
8
+ // eslint-disable-next-line
9
+ /^(\d{4})-?(0[1-9]|1[012])?-?([123]0|[012][1-9]|31)?(?:[T ]?([01][0-9]|2[0-3]):?([0-5][0-9]):?([0-5][0-9])?(?:\.(\d+))?(?:(Z)|(?:([+-])([01]?[0-9]|2[0-3]):?([0-5][0-9])?))?)?$/;
10
+ const INFINITY_PATTERN = /^-?infinity$/;
11
+ function parseDateTime(str, parseTime, parseTimeZone, utc) {
12
+ let m = str.match(TIMESTAMP_PATTERN);
13
+ if (!m) {
14
+ m = str.match(INFINITY_PATTERN);
15
+ if (m)
16
+ return Number(str.replace('i', 'I'));
17
+ return new Date('invalid');
18
+ }
19
+ const args = [1970, 0, 1, 0, 0, 0, 0];
20
+ const l = parseTime ? 7 : 3;
21
+ for (let i = 0; i < l; i++) {
22
+ const s = m[i + 1];
23
+ args[i] = (0, fast_parseint_js_1.fastParseInt)(s) || 0;
24
+ }
25
+ // Months starts from 0
26
+ if (args[1] > 0)
27
+ args[1]--;
28
+ if (parseTimeZone && parseTime && m[9]) {
29
+ const r = m[9] === '-' ? -1 : 1;
30
+ args[3] -= ((0, fast_parseint_js_1.fastParseInt)(m[10]) || 0) * r;
31
+ args[4] -= ((0, fast_parseint_js_1.fastParseInt)(m[11]) || 0) * r;
32
+ return new Date(Date.UTC(...args));
33
+ }
34
+ if (m[8] || utc)
35
+ return new Date(Date.UTC(...args));
36
+ return new Date(...args);
37
+ }
38
+ exports.parseDateTime = parseDateTime;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseRow = void 0;
4
+ function parseRow(parsers, row, options) {
5
+ const l = row.length;
6
+ let i;
7
+ for (i = 0; i < l; i++) {
8
+ row[i] = row[i] == null ? null : parsers[i].call(undefined, row[i], options);
9
+ }
10
+ }
11
+ exports.parseRow = parseRow;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseTime = exports.TIME_PATTERN = exports.STRICT_TIME_PATTERN = void 0;
4
+ const fast_parseint_js_1 = require("./fast-parseint.js");
5
+ // eslint-disable-next-line
6
+ // noinspection RegExpUnnecessaryNonCapturingGroup
7
+ exports.STRICT_TIME_PATTERN = /^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\.(\d+))?(?:(Z)|(?:([+-])([01]?[0-9]|2[0-3]):?([0-5][0-9])?))?$/;
8
+ // noinspection RegExpUnnecessaryNonCapturingGroup
9
+ exports.TIME_PATTERN = /^([01][0-9]|2[0-3]):?([0-5][0-9]):?([0-5][0-9])?(?:\.(\d+))?(?:(Z)|(?:([+-])([01]?[0-9]|2[0-3]):?([0-5][0-9])?))?$/;
10
+ function parseTime(str, parseTimeZone, utc) {
11
+ const m = str.match(exports.TIME_PATTERN);
12
+ if (!m)
13
+ return new Date('invalid');
14
+ const args = [1970, 0, 1, 0, 0, 0, 0];
15
+ for (let i = 1; i < 4; i++) {
16
+ const s = m[i];
17
+ args[i + 2] = (0, fast_parseint_js_1.fastParseInt)(s) || 0;
18
+ }
19
+ if (parseTimeZone && m[6]) {
20
+ const r = m[9] === '-' ? -1 : 1;
21
+ args[3] -= ((0, fast_parseint_js_1.fastParseInt)(m[7]) || 0) * r;
22
+ args[4] -= ((0, fast_parseint_js_1.fastParseInt)(m[8]) || 0) * r;
23
+ return new Date(Date.UTC(...args));
24
+ }
25
+ if (m[5] || utc)
26
+ return new Date(Date.UTC(...args));
27
+ return new Date(...args);
28
+ }
29
+ exports.parseTime = parseTime;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stringifyArrayLiteral = void 0;
4
+ const array_calculatedim_js_1 = require("./array-calculatedim.js");
5
+ function stringifyArrayLiteral(value, options, encode) {
6
+ const dim = (0, array_calculatedim_js_1.arrayCalculateDim)(value);
7
+ const writeDim = (arr, level) => {
8
+ const elemCount = dim[level];
9
+ const out = [];
10
+ for (let i = 0; i < elemCount; i++) {
11
+ let x = arr && arr[i];
12
+ if (level < dim.length - 1) {
13
+ if (x != null && !Array.isArray(x))
14
+ x = [x];
15
+ out.push(writeDim(x, level + 1));
16
+ continue;
17
+ }
18
+ // if value is null
19
+ if (x == null) {
20
+ out.push('NULL');
21
+ continue;
22
+ }
23
+ if (Array.isArray(x)) {
24
+ out.push(stringifyArrayLiteral(x, options, encode));
25
+ continue;
26
+ }
27
+ if (encode)
28
+ x = encode(x, options || {});
29
+ out.push(escapeArrayItem('' + x));
30
+ }
31
+ return '{' + out.join(',') + '}';
32
+ };
33
+ return writeDim(value, 0);
34
+ }
35
+ exports.stringifyArrayLiteral = stringifyArrayLiteral;
36
+ function escapeArrayItem(str) {
37
+ return '"' + str.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
38
+ }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stringifyValueForSQL = exports.stringifyArrayForSQL = void 0;
4
+ const uuid_type_js_1 = require("../data-types/uuid-type.js");
5
+ const escape_literal_js_1 = require("./escape-literal.js");
6
+ function stringifyArrayForSQL(v, options, encode) {
7
+ const arr = v.map(x => stringifyValueForSQL(x, options, encode));
8
+ return 'ARRAY[' + arr.join(',') + ']';
9
+ }
10
+ exports.stringifyArrayForSQL = stringifyArrayForSQL;
11
+ function stringifyValueForSQL(v, options, encode) {
12
+ if (v == null)
13
+ return 'null';
14
+ if (typeof v === 'boolean')
15
+ return v ? 'true' : 'false';
16
+ if (Array.isArray(v))
17
+ return stringifyArrayForSQL(v, options, encode);
18
+ if (encode)
19
+ v = encode(v, options || {});
20
+ if (typeof v === 'number')
21
+ return '' + v;
22
+ if (typeof v === 'bigint')
23
+ return v.toString();
24
+ if (typeof v === 'string' && uuid_type_js_1.UuidType.isType(v))
25
+ return (0, escape_literal_js_1.escapeLiteral)('' + v) + '::uuid';
26
+ if (typeof v === 'object')
27
+ return (0, escape_literal_js_1.escapeLiteral)(JSON.stringify(v)) + '::json';
28
+ return (0, escape_literal_js_1.escapeLiteral)('' + v);
29
+ }
30
+ exports.stringifyValueForSQL = stringifyValueForSQL;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.wrapRowDescription = void 0;
4
+ const constants_js_1 = require("../constants.js");
5
+ function wrapRowDescription(typeMap, fields, columnFormat) {
6
+ return fields.map((f, idx) => {
7
+ const cf = Array.isArray(columnFormat) ? columnFormat[idx] : columnFormat;
8
+ const x = {
9
+ fieldName: f.fieldName,
10
+ tableId: f.tableId,
11
+ columnId: f.columnId,
12
+ dataTypeId: f.dataTypeId,
13
+ dataTypeName: constants_js_1.DataTypeNames[f.dataTypeId] || '',
14
+ jsType: cf === constants_js_1.DataFormat.binary ? 'Buffer' : 'string',
15
+ };
16
+ x.isArray = x.dataTypeName.startsWith('_');
17
+ if (x.isArray) {
18
+ x.elementDataTypeName = x.dataTypeName.substring(1);
19
+ for (const oid of Object.keys(constants_js_1.DataTypeNames)) {
20
+ if (constants_js_1.DataTypeNames[oid] === x.elementDataTypeName)
21
+ x.elementDataTypeId = parseInt(oid, 10);
22
+ }
23
+ }
24
+ if (f.fixedSize && f.fixedSize > 0)
25
+ x.fixedSize = f.fixedSize;
26
+ if (f.modifier && f.modifier > 0)
27
+ x.modifier = f.modifier;
28
+ const reg = typeMap.get(x.dataTypeId);
29
+ if (reg) {
30
+ x.jsType = reg.jsType;
31
+ }
32
+ return x;
33
+ });
34
+ }
35
+ exports.wrapRowDescription = wrapRowDescription;
@@ -0,0 +1,6 @@
1
+ export class BindParam {
2
+ constructor(oid, value) {
3
+ this.oid = oid;
4
+ this.value = value;
5
+ }
6
+ }
@@ -0,0 +1,275 @@
1
+ import { ConnectionState } from '../constants.js';
2
+ import { GlobalTypeMap } from '../data-type-map.js';
3
+ import { SafeEventEmitter } from '../safe-event-emitter.js';
4
+ import { BindParam } from './bind-param.js';
5
+ import { IntlConnection } from './intl-connection.js';
6
+ import { PreparedStatement } from './prepared-statement.js';
7
+ export class Connection extends SafeEventEmitter {
8
+ constructor(arg0, arg1) {
9
+ super();
10
+ this._notificationListeners = new SafeEventEmitter();
11
+ this._closing = false;
12
+ if (arg0 && typeof arg0 === 'object' && typeof arg0.acquire === 'function') {
13
+ if (!(arg1 instanceof IntlConnection))
14
+ throw new TypeError('Invalid argument');
15
+ this._pool = arg0;
16
+ this._intlCon = arg1;
17
+ }
18
+ else {
19
+ this._intlCon = new IntlConnection(arg0);
20
+ }
21
+ this._intlCon.on('ready', (...args) => this.emit('ready', ...args));
22
+ this._intlCon.on('error', (...args) => this.emit('error', ...args));
23
+ this._intlCon.on('close', (...args) => this.emit('close', ...args));
24
+ this._intlCon.on('connecting', (...args) => this.emit('connecting', ...args));
25
+ this._intlCon.on('ready', (...args) => this.emit('ready', ...args));
26
+ this._intlCon.on('terminate', (...args) => this.emit('terminate', ...args));
27
+ this._intlCon.on('notification', (msg) => this._handleNotification(msg));
28
+ }
29
+ /**
30
+ * Returns configuration object
31
+ */
32
+ get config() {
33
+ return this._intlCon.config;
34
+ }
35
+ /**
36
+ * Returns true if connection is in a transaction
37
+ */
38
+ get inTransaction() {
39
+ return this._intlCon.inTransaction;
40
+ }
41
+ /**
42
+ * Returns current state of the connection
43
+ */
44
+ get state() {
45
+ return this._intlCon.state;
46
+ }
47
+ /**
48
+ * Returns processId of current session
49
+ */
50
+ get processID() {
51
+ return this._intlCon.processID;
52
+ }
53
+ /**
54
+ * Returns information parameters for current session
55
+ */
56
+ get sessionParameters() {
57
+ return this._intlCon.sessionParameters;
58
+ }
59
+ /**
60
+ * Returns secret key of current session
61
+ */
62
+ get secretKey() {
63
+ return this._intlCon.secretKey;
64
+ }
65
+ /**
66
+ * Connects to the server
67
+ */
68
+ async connect() {
69
+ await this._captureErrorStack(this._intlCon.connect());
70
+ if (this.state === ConnectionState.READY)
71
+ this._closing = false;
72
+ }
73
+ /**
74
+ * Closes connection. You can define how long time the connection will
75
+ * wait for active queries before terminating the connection.
76
+ * On the end of the given time, it forces to close the socket and than emits `terminate` event.
77
+ *
78
+ * @param terminateWait {number} - Determines how long the connection will wait for active queries before terminating.
79
+ */
80
+ async close(terminateWait) {
81
+ this._notificationListeners.removeAllListeners();
82
+ this._intlCon.statementQueue.clearQueue();
83
+ if (this.state === ConnectionState.CLOSED || this._closing)
84
+ return;
85
+ /* istanbul ignore next */
86
+ if (this.listenerCount('debug'))
87
+ this.emit('debug', {
88
+ location: 'Connection.close',
89
+ connection: this,
90
+ message: `[${this.processID}] closing`,
91
+ });
92
+ this._closing = true;
93
+ if (this._intlCon.refCount > 0 && typeof terminateWait === 'number' && terminateWait > 0) {
94
+ const startTime = Date.now();
95
+ return this._captureErrorStack(new Promise((resolve, reject) => {
96
+ /* istanbul ignore next */
97
+ if (this.listenerCount('debug'))
98
+ this.emit('debug', {
99
+ location: 'Connection.close',
100
+ connection: this,
101
+ message: `[${this.processID}] waiting active queries`,
102
+ });
103
+ const timer = setInterval(() => {
104
+ if (this._intlCon.refCount <= 0 || Date.now() > startTime + terminateWait) {
105
+ clearInterval(timer);
106
+ if (this._intlCon.refCount > 0) {
107
+ /* istanbul ignore next */
108
+ if (this.listenerCount('debug'))
109
+ this.emit('debug', {
110
+ location: 'Connection.close',
111
+ connection: this,
112
+ message: `[${this.processID}] terminate`,
113
+ });
114
+ this.emit('terminate');
115
+ }
116
+ this._close().then(resolve).catch(reject);
117
+ }
118
+ }, 50);
119
+ }));
120
+ }
121
+ await this._close();
122
+ }
123
+ /**
124
+ * Executes single or multiple SQL scripts using Simple Query protocol.
125
+ *
126
+ * @param sql {string} - SQL script that will be executed
127
+ * @param options {ScriptExecuteOptions} - Execute options
128
+ */
129
+ async execute(sql, options) {
130
+ return this._captureErrorStack(this._intlCon.execute(sql, options)).catch((e) => {
131
+ throw this._handleError(e, sql);
132
+ });
133
+ }
134
+ async query(sql, options) {
135
+ this._intlCon.assertConnected();
136
+ /* istanbul ignore next */
137
+ if (this.listenerCount('debug'))
138
+ this.emit('debug', {
139
+ location: 'Connection.query',
140
+ connection: this,
141
+ message: `[${this.processID}] query | ${sql}`,
142
+ sql,
143
+ });
144
+ const typeMap = options?.typeMap || GlobalTypeMap;
145
+ const paramTypes = options?.params?.map(prm => prm instanceof BindParam ? prm.oid : typeMap.determine(prm));
146
+ const statement = await this.prepare(sql, { paramTypes, typeMap }).catch((e) => {
147
+ throw this._handleError(e, sql);
148
+ });
149
+ try {
150
+ const params = options?.params?.map(prm => (prm instanceof BindParam ? prm.value : prm));
151
+ return await this._captureErrorStack(statement.execute({ ...options, params }));
152
+ }
153
+ finally {
154
+ await statement.close();
155
+ }
156
+ }
157
+ /**
158
+ * Creates a PreparedStatement instance
159
+ * @param sql {string} - SQL script that will be executed
160
+ * @param options {StatementPrepareOptions} - Options
161
+ */
162
+ async prepare(sql, options) {
163
+ /* istanbul ignore next */
164
+ if (this.listenerCount('debug'))
165
+ this.emit('debug', {
166
+ location: 'Connection.prepare',
167
+ connection: this,
168
+ message: `[${this.processID}] prepare | ${sql}`,
169
+ sql,
170
+ });
171
+ return await this._captureErrorStack(PreparedStatement.prepare(this, sql, options));
172
+ }
173
+ /**
174
+ * Starts a transaction
175
+ */
176
+ startTransaction() {
177
+ return this._captureErrorStack(this._intlCon.startTransaction());
178
+ }
179
+ /**
180
+ * Commits current transaction
181
+ */
182
+ commit() {
183
+ return this._captureErrorStack(this._intlCon.commit());
184
+ }
185
+ /**
186
+ * Rolls back current transaction
187
+ */
188
+ rollback() {
189
+ return this._captureErrorStack(this._intlCon.rollback());
190
+ }
191
+ /**
192
+ * Starts transaction and creates a savepoint
193
+ * @param name {string} - Name of the savepoint
194
+ */
195
+ async savepoint(name) {
196
+ if (!this._intlCon.inTransaction)
197
+ await this._intlCon.startTransaction();
198
+ return this._captureErrorStack(this._intlCon.savepoint(name));
199
+ }
200
+ /**
201
+ * Rolls back current transaction to given savepoint
202
+ * @param name {string} - Name of the savepoint
203
+ */
204
+ rollbackToSavepoint(name) {
205
+ return this._captureErrorStack(this._intlCon.rollbackToSavepoint(name));
206
+ }
207
+ /**
208
+ * Releases savepoint
209
+ * @param name {string} - Name of the savepoint
210
+ */
211
+ releaseSavepoint(name) {
212
+ return this._captureErrorStack(this._intlCon.releaseSavepoint(name));
213
+ }
214
+ async listen(channel, callback) {
215
+ if (!/^[A-Z]\w+$/i.test(channel))
216
+ throw new TypeError(`Invalid channel name`);
217
+ const registered = !!this._notificationListeners.eventNames().length;
218
+ this._notificationListeners.on(channel, callback);
219
+ if (!registered)
220
+ await this._captureErrorStack(this.query('LISTEN ' + channel));
221
+ }
222
+ async unListen(channel) {
223
+ if (!/^[A-Z]\w+$/i.test(channel))
224
+ throw new TypeError(`Invalid channel name`);
225
+ this._notificationListeners.removeAllListeners(channel);
226
+ await this._captureErrorStack(this.query('UNLISTEN ' + channel));
227
+ }
228
+ async unListenAll() {
229
+ this._notificationListeners.removeAllListeners();
230
+ await this._captureErrorStack(this.query('UNLISTEN *'));
231
+ }
232
+ _handleNotification(msg) {
233
+ this.emit('notification', msg);
234
+ this._notificationListeners.emit(msg.channel, msg);
235
+ }
236
+ async _close() {
237
+ if (this._pool) {
238
+ await this._captureErrorStack(this._pool.release(this));
239
+ this.emit('release');
240
+ }
241
+ else
242
+ await this._captureErrorStack(this._intlCon.close());
243
+ this._closing = false;
244
+ }
245
+ _handleError(err, script) {
246
+ if (err.position) {
247
+ const i1 = script.lastIndexOf('\n', err.position) + 1;
248
+ let i2 = script.indexOf('\n', err.position);
249
+ if (i2 < 0)
250
+ i2 = Number.MAX_SAFE_INTEGER;
251
+ err.line = script.substring(i1, i2);
252
+ err.lineNr = [...script.substring(0, i1).matchAll(/\n/g)].length;
253
+ err.colNr = err.position - i1;
254
+ err.message +=
255
+ `\nAt line ${err.lineNr} column ${err.colNr}` +
256
+ `\n | ${err.line}\n | ${' '.repeat(Math.max(err.colNr - 2, 0))}-^-`;
257
+ }
258
+ return err;
259
+ }
260
+ async _captureErrorStack(promise) {
261
+ const stack = new Error().stack;
262
+ return promise.catch(e => {
263
+ if (e instanceof Error && stack) {
264
+ e.stack = stack
265
+ .split('\n')
266
+ .filter(x => !x.includes('Connection._captureErrorStack'))
267
+ .join('\n');
268
+ }
269
+ throw e;
270
+ });
271
+ }
272
+ [Symbol.asyncDispose]() {
273
+ return this.close();
274
+ }
275
+ }