postgrejs 2.23.1 → 3.0.2

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 (107) hide show
  1. package/CHANGELOG.md +171 -1
  2. package/LICENSE +26 -17
  3. package/README.md +195 -175
  4. package/connection/connection.d.ts +169 -16
  5. package/connection/connection.js +318 -56
  6. package/connection/copy-stream.d.ts +88 -0
  7. package/connection/copy-stream.js +244 -0
  8. package/connection/cursor.js +20 -13
  9. package/connection/intl-connection.d.ts +113 -5
  10. package/connection/intl-connection.js +500 -70
  11. package/connection/large-object.d.ts +65 -0
  12. package/connection/large-object.js +151 -0
  13. package/connection/logical-replication.d.ts +121 -0
  14. package/connection/logical-replication.js +279 -0
  15. package/connection/pool.d.ts +61 -4
  16. package/connection/pool.js +177 -29
  17. package/connection/portal.d.ts +18 -4
  18. package/connection/portal.js +53 -59
  19. package/connection/prepared-statement.d.ts +22 -1
  20. package/connection/prepared-statement.js +129 -109
  21. package/data-type-map.js +4 -2
  22. package/data-types/bool-type.js +14 -10
  23. package/data-types/box-type.js +15 -8
  24. package/data-types/bytea-type.js +9 -5
  25. package/data-types/char-type.js +11 -5
  26. package/data-types/circle-type.js +15 -7
  27. package/data-types/date-type.js +25 -19
  28. package/data-types/float4-type.js +10 -3
  29. package/data-types/float8-type.js +12 -3
  30. package/data-types/int2-type.js +9 -4
  31. package/data-types/int2-vector-type.js +9 -4
  32. package/data-types/int4-type.js +11 -5
  33. package/data-types/int8-type.js +22 -7
  34. package/data-types/json-type.js +17 -8
  35. package/data-types/jsonb-type.js +20 -14
  36. package/data-types/lseg-type.js +16 -8
  37. package/data-types/numeric-type.d.ts +8 -0
  38. package/data-types/numeric-type.js +118 -9
  39. package/data-types/oid-type.d.ts +0 -1
  40. package/data-types/oid-type.js +9 -10
  41. package/data-types/oid-vector-type.d.ts +9 -0
  42. package/data-types/oid-vector-type.js +51 -0
  43. package/data-types/point-type.js +14 -6
  44. package/data-types/time-type.js +20 -13
  45. package/data-types/timestamp-type.js +32 -25
  46. package/data-types/timestamptz-type.js +33 -21
  47. package/data-types/uuid-type.js +21 -11
  48. package/data-types/varchar-type.js +16 -4
  49. package/index.d.ts +5 -0
  50. package/index.js +5 -0
  51. package/interfaces/command-result.d.ts +2 -1
  52. package/interfaces/data-type.d.ts +5 -3
  53. package/interfaces/database-connection-params.d.ts +108 -0
  54. package/interfaces/query-options.d.ts +23 -0
  55. package/interfaces/script-execute-options.d.ts +23 -0
  56. package/interfaces/script-result.d.ts +3 -2
  57. package/package.json +2 -3
  58. package/protocol/backend.d.ts +6 -1
  59. package/protocol/backend.js +70 -45
  60. package/protocol/buffer-reader.d.ts +0 -2
  61. package/protocol/buffer-reader.js +3 -10
  62. package/protocol/cert-signature.d.ts +12 -0
  63. package/protocol/cert-signature.js +114 -0
  64. package/protocol/frontend.d.ts +16 -0
  65. package/protocol/frontend.js +70 -11
  66. package/protocol/pg-socket.d.ts +220 -9
  67. package/protocol/pg-socket.js +539 -102
  68. package/protocol/pgoutput.d.ts +76 -0
  69. package/protocol/pgoutput.js +155 -0
  70. package/protocol/protocol.d.ts +3 -4
  71. package/protocol/protocol.js +1 -1
  72. package/protocol/sasl.d.ts +11 -1
  73. package/protocol/sasl.js +36 -5
  74. package/protocol/smart-buffer.d.ts +0 -2
  75. package/protocol/smart-buffer.js +11 -16
  76. package/types.d.ts +5 -3
  77. package/util/abort-signal.d.ts +34 -0
  78. package/util/abort-signal.js +76 -0
  79. package/util/array-calculatedim.js +3 -1
  80. package/util/connection-config.js +77 -3
  81. package/util/decode-binaryarray.d.ts +1 -1
  82. package/util/decode-binaryarray.js +15 -6
  83. package/util/encode-binaryarray.js +7 -3
  84. package/util/escape-identifier.d.ts +14 -0
  85. package/util/escape-identifier.js +32 -0
  86. package/util/escape-literal.js +3 -0
  87. package/util/fast-parseint.d.ts +1 -0
  88. package/util/fast-parseint.js +12 -17
  89. package/util/format-datetime.d.ts +10 -0
  90. package/util/format-datetime.js +71 -0
  91. package/util/get-parsers.js +31 -10
  92. package/util/parse-array.js +2 -2
  93. package/util/parse-bytea.d.ts +2 -0
  94. package/util/parse-bytea.js +83 -0
  95. package/util/parse-datetime.d.ts +3 -1
  96. package/util/parse-datetime.js +86 -17
  97. package/util/parse-row.d.ts +3 -1
  98. package/util/parse-row.js +60 -5
  99. package/util/parse-time.js +8 -1
  100. package/util/sql-tag.d.ts +60 -0
  101. package/util/sql-tag.js +202 -0
  102. package/util/starts-transaction.d.ts +38 -0
  103. package/util/starts-transaction.js +148 -0
  104. package/util/stringify-arrayliteral.js +13 -1
  105. package/util/wrap-row-description.js +13 -4
  106. package/util/convert-row-to-object.d.ts +0 -2
  107. package/util/convert-row-to-object.js +0 -9
@@ -9,15 +9,18 @@ import type { DatabaseError } from '../protocol/database-error.js';
9
9
  import type { Protocol } from '../protocol/protocol.js';
10
10
  import { SafeEventEmitter } from '../safe-event-emitter.js';
11
11
  import type { Maybe } from '../types.js';
12
+ import { QueryRequest } from '../util/sql-tag.js';
13
+ import type { CopyFromStream, CopyToStream } from './copy-stream.js';
12
14
  import { IntlConnection } from './intl-connection.js';
15
+ import { LargeObject } from './large-object.js';
13
16
  import type { Pool } from './pool.js';
14
17
  import { PreparedStatement } from './prepared-statement.js';
15
18
  export type NotificationMessage = Protocol.NotificationResponseMessage;
16
19
  export type NotificationCallback = (msg: NotificationMessage) => any;
17
20
  export declare class Connection extends SafeEventEmitter implements AsyncDisposable {
18
- protected readonly _pool?: Pool;
19
- protected readonly _intlCon: IntlConnection;
20
- protected readonly _notificationListeners: SafeEventEmitter;
21
+ protected _pool?: Pool;
22
+ protected _intlCon: IntlConnection;
23
+ protected _notificationListeners?: SafeEventEmitter;
21
24
  protected _closing: boolean;
22
25
  constructor(pool: Pool, intlCon: IntlConnection);
23
26
  constructor(config?: ConnectionConfiguration | string);
@@ -26,25 +29,26 @@ export declare class Connection extends SafeEventEmitter implements AsyncDisposa
26
29
  */
27
30
  get config(): ConnectionConfiguration;
28
31
  /**
29
- * Returns true if connection is in a transaction
32
+ * Returns true if the connection is in a transaction
30
33
  */
31
34
  get inTransaction(): boolean;
32
35
  /**
33
- * Returns current state of the connection
36
+ * Returns the current state of the connection
34
37
  */
35
38
  get state(): ConnectionState;
36
39
  /**
37
- * Returns processId of current session
40
+ * Returns processId of the current session
38
41
  */
39
42
  get processID(): Maybe<number>;
40
43
  /**
41
- * Returns information parameters for current session
44
+ * Returns information parameters for the current session
42
45
  */
43
46
  get sessionParameters(): Record<string, string>;
44
47
  /**
45
- * Returns secret key of current session
48
+ * Returns the secret key of the current session
46
49
  */
47
50
  get secretKey(): Maybe<number>;
51
+ get runningQueryCount(): number;
48
52
  /**
49
53
  * Connects to the server
50
54
  */
@@ -52,7 +56,7 @@ export declare class Connection extends SafeEventEmitter implements AsyncDisposa
52
56
  /**
53
57
  * Closes connection. You can define how long time the connection will
54
58
  * wait for active queries before terminating the connection.
55
- * On the end of the given time, it forces to close the socket and than emits `terminate` event.
59
+ * At the end of the given time, it forces to close the socket and then emits the ` terminate ` event.
56
60
  *
57
61
  * @param terminateWait {number} - Determines how long the connection will wait for active queries before terminating.
58
62
  */
@@ -63,47 +67,196 @@ export declare class Connection extends SafeEventEmitter implements AsyncDisposa
63
67
  * @param sql {string} - SQL script that will be executed
64
68
  * @param options {ScriptExecuteOptions} - Execute options
65
69
  */
66
- execute(sql: string, options?: ScriptExecuteOptions): Promise<ScriptResult>;
67
- query(sql: string, options?: QueryOptions): Promise<QueryResult>;
70
+ execute(sql: string | QueryRequest, options?: ScriptExecuteOptions): Promise<ScriptResult>;
71
+ query(sql: string | QueryRequest, options?: QueryOptions): Promise<QueryResult>;
72
+ /**
73
+ * Runs a `COPY ... TO STDOUT` and returns its output as a stream of the
74
+ * raw bytes the server sends - text, CSV or binary, whichever the
75
+ * statement asked for. Nothing is decoded and nothing is copied.
76
+ *
77
+ * Resolves as soon as the server accepts the copy, so a large export is
78
+ * never held in memory; a consumer that falls behind pauses the socket
79
+ * rather than buffering. `rowCount` is set before the stream ends.
80
+ *
81
+ * ```ts
82
+ * const out = await connection.copyTo(`COPY users TO STDOUT (FORMAT csv)`);
83
+ * await pipeline(out, fs.createWriteStream('users.csv'));
84
+ * console.log(out.rowCount);
85
+ * ```
86
+ *
87
+ * The stream must be consumed or destroyed: until the copy finishes the
88
+ * connection is still mid-statement.
89
+ *
90
+ * @param sql {string} - A COPY ... TO STDOUT statement
91
+ */
92
+ copyTo(sql: string): Promise<CopyToStream>;
93
+ /**
94
+ * Runs a `COPY ... FROM STDIN` and returns a stream to feed it. Whatever
95
+ * is written is forwarded verbatim, so the statement's own FORMAT decides
96
+ * the encoding.
97
+ *
98
+ * ```ts
99
+ * const inp = await connection.copyFrom(`COPY users FROM STDIN (FORMAT csv)`);
100
+ * await pipeline(fs.createReadStream('users.csv'), inp);
101
+ * console.log(inp.rowCount);
102
+ * ```
103
+ *
104
+ * 'finish' means the server accepted the copy, not merely that the last
105
+ * byte was written. If the source fails, `pipeline()` destroys the stream
106
+ * and a CopyFail is sent, so the connection stays usable.
107
+ *
108
+ * @param sql {string} - A COPY ... FROM STDIN statement
109
+ */
110
+ copyFrom(sql: string): Promise<CopyFromStream>;
68
111
  /**
69
112
  * Creates a PreparedStatement instance
70
113
  * @param sql {string} - SQL script that will be executed
71
114
  * @param options {StatementPrepareOptions} - Options
72
115
  */
73
116
  prepare(sql: string, options?: StatementPrepareOptions): Promise<PreparedStatement>;
117
+ /**
118
+ * Creates a large object and opens it for reading and writing.
119
+ *
120
+ * A large object holds binary data outside any row, reachable a piece at
121
+ * a time instead of whole the way a `bytea` column is - which is what it
122
+ * is for, along with a 4TB ceiling rather than roughly 1GB.
123
+ *
124
+ * ```ts
125
+ * const lo = await connection.createLargeObject();
126
+ * await pipeline(fs.createReadStream('video.mp4'), lo.writable());
127
+ * await lo.close();
128
+ * await table.insert({ videoOid: lo.oid });
129
+ * ```
130
+ *
131
+ * Nothing links the object to the row that names it: dropping the row
132
+ * leaves the data behind, so unlinkLargeObject() has to be called when it
133
+ * is no longer wanted. PostgreSQL ships `vacuumlo` for finding the ones
134
+ * that were not.
135
+ */
136
+ createLargeObject(mode?: 393216): Promise<LargeObject>;
137
+ /**
138
+ * Opens an existing large object by its OID. See createLargeObject() for
139
+ * how the transaction is handled.
140
+ */
141
+ openLargeObject(oid: number, mode?: 262144): Promise<LargeObject>;
142
+ /** Deletes a large object and its data. */
143
+ unlinkLargeObject(oid: number): Promise<void>;
144
+ /**
145
+ * Asks the server to cancel whatever this connection is currently running.
146
+ *
147
+ * Travels on its own short-lived connection, since a backend busy with a
148
+ * query is not reading its own socket. It is a request, not a guarantee -
149
+ * the statement may finish first - and the cancelled call reports the
150
+ * outcome itself, rejecting with SQLSTATE 57014 if the server acted on it.
151
+ * Prefer the per-call `signal` option, which does this and reports the
152
+ * abort to the right caller.
153
+ */
154
+ cancel(): Promise<void>;
74
155
  /**
75
156
  * Starts a transaction
76
157
  */
77
158
  startTransaction(): Promise<void>;
78
159
  /**
79
- * Commits current transaction
160
+ * Commits current transaction.
161
+ * @param immediate - Commits right away, ignoring how many nested
162
+ * startTransaction() calls are still unmatched by a commit().
80
163
  */
81
- commit(): Promise<void>;
164
+ commit(immediate?: boolean): Promise<void>;
82
165
  /**
83
166
  * Rolls back current transaction
84
167
  */
85
168
  rollback(): Promise<void>;
169
+ /**
170
+ * Ends the current transaction as a prepared one, for two-phase commit.
171
+ *
172
+ * The transaction stops belonging to this session and waits under `name`
173
+ * until it is finished by commitPrepared() or rollbackPrepared() - which
174
+ * may run on another connection, in another process, after this one is
175
+ * gone. That is the point: it lets several databases agree to commit
176
+ * before any of them actually does.
177
+ *
178
+ * ```ts
179
+ * await connection.startTransaction();
180
+ * await connection.query(sql`insert into t values (${1})`);
181
+ * await connection.prepareTransaction('tx1');
182
+ * // ...later, anywhere:
183
+ * await other.commitPrepared('tx1');
184
+ * ```
185
+ *
186
+ * PostgreSQL ships with `max_prepared_transactions` at zero, so this
187
+ * fails until the server is configured for it.
188
+ */
189
+ prepareTransaction(name: string): Promise<void>;
190
+ /**
191
+ * Commits a transaction left waiting by prepareTransaction(), by name.
192
+ * Runs outside any transaction and needs no connection to the session
193
+ * that prepared it.
194
+ */
195
+ commitPrepared(name: string): Promise<void>;
196
+ /** Discards a transaction left waiting by prepareTransaction(), by name. */
197
+ rollbackPrepared(name: string): Promise<void>;
86
198
  /**
87
199
  * Starts transaction and creates a savepoint
88
200
  * @param name {string} - Name of the savepoint
89
201
  */
90
202
  savepoint(name: string): Promise<void>;
91
203
  /**
92
- * Rolls back current transaction to given savepoint
204
+ * Rolls back the current transaction to given savepoint
93
205
  * @param name {string} - Name of the savepoint
94
206
  */
95
207
  rollbackToSavepoint(name: string): Promise<void>;
96
208
  /**
97
209
  * Releases savepoint
98
210
  * @param name {string} - Name of the savepoint
211
+ * @param immediate - Releases right away, ignoring how many nested
212
+ * savepoint() calls under this name are still unmatched by a
213
+ * releaseSavepoint().
99
214
  */
100
- releaseSavepoint(name: string): Promise<void>;
215
+ releaseSavepoint(name: string, immediate?: boolean): Promise<void>;
101
216
  listen(channel: string, callback: NotificationCallback): Promise<void>;
102
217
  unListen(channel: string): Promise<void>;
103
218
  unListenAll(): Promise<void>;
219
+ protected _query(sql: string, options?: QueryOptions): Promise<QueryResult>;
220
+ /**
221
+ * A large object's descriptor is only valid inside the transaction that
222
+ * opened it. One is started here when there is none, and reported so that
223
+ * close() commits only what it started - a transaction the caller opened
224
+ * stays theirs. Mirrors what savepoint() already does.
225
+ */
226
+ protected _beginForLargeObject(): Promise<boolean>;
227
+ protected _openLargeObject(oid: number, mode: number, ownsTransaction: boolean): Promise<LargeObject>;
104
228
  protected _handleNotification(msg: NotificationMessage): void;
105
229
  protected _close(): Promise<void>;
106
230
  protected _handleError(err: DatabaseError, script: string): DatabaseError;
107
- protected _captureErrorStack<T>(promise: Promise<T>): Promise<T>;
231
+ /**
232
+ * Remembers where a call came from, so the error it may reject with points
233
+ * at the caller instead of at an internal async frame.
234
+ *
235
+ * `entry` is the public method to cut the trace at: everything from it
236
+ * inwards is this library's own plumbing and is dropped, which matters
237
+ * because the captured depth is deliberately small - spending four of five
238
+ * frames on our own call chain would leave one for the caller, and any
239
+ * helper of theirs would push the real call site off the end.
240
+ *
241
+ * Skippable via `asyncErrorHandling: false` - capturing costs a real,
242
+ * measurable slice of CPU time once many calls are in flight at once
243
+ * (a pipelined burst on one connection), where it has to compete with
244
+ * every other call for the same core instead of hiding behind network
245
+ * wait the way it does for a single sequential call.
246
+ *
247
+ * `asyncErrorHandling` is the per-call override (execute()/query()'s own
248
+ * option of the same name); when omitted, the connection's own
249
+ * `DatabaseConnectionParams.asyncErrorHandling` decides.
250
+ *
251
+ * Not `async` itself, deliberately: every branch below already returns a
252
+ * promise directly (`promise` itself, or `promise.catch(...)`'s own
253
+ * derived one) with no `await` in between, so there is nothing here that
254
+ * needs the function to be a coroutine. Marking it `async` anyway would
255
+ * still be correct, but the spec requires wrapping whatever an async
256
+ * function returns through a promise-resolve step, a genuine extra
257
+ * microtask tick on top of the one `promise`/`.catch()` already goes
258
+ * through - paid on every single query this wraps, disabled or not.
259
+ */
260
+ protected _captureErrorStack<T>(promise: Promise<T>, entry?: (...args: any[]) => any, asyncErrorHandling?: boolean): Promise<T>;
108
261
  [Symbol.asyncDispose](): Promise<void>;
109
262
  }