@trysqless/node 0.1.1 → 0.2.1
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.
- package/README.md +40 -32
- package/errors.js +0 -1
- package/index.d.ts +17 -24
- package/index.js +27 -20
- package/package.json +1 -1
- package/transport.js +1 -3
package/README.md
CHANGED
|
@@ -59,7 +59,7 @@ try {
|
|
|
59
59
|
await db.execute([
|
|
60
60
|
{ sql: 'CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY, message TEXT)', parameters: [] },
|
|
61
61
|
{ sql: 'INSERT INTO notes(message) VALUES (?)', parameters: ['hello'] },
|
|
62
|
-
]
|
|
62
|
+
]);
|
|
63
63
|
|
|
64
64
|
const { results } = await db.execute([
|
|
65
65
|
{ sql: 'SELECT id, message FROM notes WHERE message = ?', parameters: ['hello'] },
|
|
@@ -71,6 +71,26 @@ try {
|
|
|
71
71
|
```
|
|
72
72
|
|
|
73
73
|
Keep one client at process scope in an HTTP server and close it during shutdown.
|
|
74
|
+
Use `executeWithEvents` to publish a webhook with a SQL transaction. The result includes `eventIds`. Inside an interactive session, these IDs are provisional until the enclosing commit succeeds.
|
|
75
|
+
|
|
76
|
+
```js
|
|
77
|
+
const { eventIds } = await db.executeWithEvents(
|
|
78
|
+
[{ sql: "INSERT INTO orders(id) VALUES (?)", parameters: [orderId] }],
|
|
79
|
+
[{
|
|
80
|
+
webhook: "https://example.com/order-events?source=checkout",
|
|
81
|
+
method: "PATCH",
|
|
82
|
+
headers: { "X-Topic": "order.created" },
|
|
83
|
+
payload: { orderId },
|
|
84
|
+
}],
|
|
85
|
+
);
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Webhooks accept public HTTP and HTTPS URLs. The default method is `POST`. Supported methods are `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE` and `OPTIONS`. Supply `payload` for JSON, `body` for raw UTF-8 text, or omit both for an empty request. Put query parameters in the URL. Use `headers` for application headers and content types. Header names and values total at most 32 KiB per event. Use HTTPS for credentials.
|
|
89
|
+
|
|
90
|
+
Use an RFC 3339 timestamp in `startedAt` to schedule the first attempt. For example, `startedAt: new Date(Date.now() + 300_000).toISOString()` schedules delivery in five minutes. The initial pending event reports this time in `nextAttemptAt`. The scheduled-event wire operation is `execute_with_scheduled_events`, with native HTTP endpoint `POST /api/v1/sql/scheduled-events`.
|
|
91
|
+
|
|
92
|
+
SQLess sends the saved request after commit, and reuses it for retries. Deliveries can be duplicated and can arrive in any order. Return 2xx after recording the stable `Idempotency-Key` and processing the request. SQLess supplies `Idempotency-Key`, `X-SQLess-Event-ID` and transport headers such as `Host` and `Content-Length`. Failed attempts back off exponentially for 30 minutes, then retry hourly for up to 24 hours from the first failure. The database task queue records the final outcome. Clients implementing the wire protocol directly can use `execute_with_http_events` over WebSocket or `POST /api/v1/sql/http-events` on a native database endpoint so older peers reject an unsupported request before executing SQL.
|
|
93
|
+
|
|
74
94
|
Concurrent `execute()` calls share one authenticated WebSocket and a bounded
|
|
75
95
|
session pool. An idle connection does not issue SQL probes or keep database
|
|
76
96
|
compute running. `isClosed()` reports connection loss; reconnect explicitly for
|
|
@@ -114,14 +134,13 @@ Explicit sessions and automatic requests share this same pool limit.
|
|
|
114
134
|
| Client | `execute(statements, options?)` | `{ results, transaction? }` for a complete batch |
|
|
115
135
|
| Client | `executeScript(script, parameterSets?, options?)` | The same result for a SQL script |
|
|
116
136
|
| Client | `openSession()` | A reserved session for sequential, interactive work |
|
|
117
|
-
| Client or session | `getTransaction(transactionId)` | A transaction receipt |
|
|
118
137
|
| Client or session | `isClosed()` | Whether the connection/session has closed |
|
|
119
138
|
| Client or session | `close()` | Release the connection/session; safe to call twice |
|
|
120
139
|
| Session | `execute(statements, options?)` | Execute statements on the reserved session |
|
|
121
140
|
| Session | `executeScript(script, parameterSets?, options?)` | Execute a script on the reserved session |
|
|
122
|
-
| Session | `begin(
|
|
123
|
-
| Session | `commit()` | Commit
|
|
124
|
-
| Session | `rollback()` | Roll back
|
|
141
|
+
| Session | `begin()` | Begin a write transaction; resolves without a value |
|
|
142
|
+
| Session | `commit()` | Commit; resolves without a value |
|
|
143
|
+
| Session | `rollback()` | Roll back; resolves without a value |
|
|
125
144
|
|
|
126
145
|
A statement contains `sql`, `parameters`, and optional `maxRows`. Each result
|
|
127
146
|
contains `columns`, array-valued `rows`, `rowsAffected`, `truncated`, and optional
|
|
@@ -129,12 +148,9 @@ contains `columns`, array-valued `rows`, `rowsAffected`, `truncated`, and option
|
|
|
129
148
|
parameter array per SQL statement, including empty arrays for statements without
|
|
130
149
|
parameters.
|
|
131
150
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
need to look up a write whose response might be lost. Session execution options
|
|
136
|
-
accept `transactionId`; inside an active transaction, normally omit it and use
|
|
137
|
-
the ID returned by `begin()`.
|
|
151
|
+
SQLess determines read/write behavior from SQL. Execution methods take only
|
|
152
|
+
SQL statements and parameters; they do not accept write hints or transaction IDs.
|
|
153
|
+
Transactions belong to a reserved session and cannot be resumed on another one.
|
|
138
154
|
|
|
139
155
|
Integers outside JavaScript's safe range are returned as `bigint`. Pass `bigint`
|
|
140
156
|
for large integer parameters to preserve their exact value. Inputs support
|
|
@@ -148,12 +164,11 @@ Await each operation on a reserved session before starting the next one:
|
|
|
148
164
|
```js
|
|
149
165
|
const session = await db.openSession();
|
|
150
166
|
try {
|
|
151
|
-
|
|
167
|
+
await session.begin();
|
|
152
168
|
await session.execute([
|
|
153
169
|
{ sql: 'INSERT INTO notes(message) VALUES (?)', parameters: ['transactional'] },
|
|
154
170
|
]);
|
|
155
|
-
|
|
156
|
-
console.log(transaction.id, receipt.state);
|
|
171
|
+
await session.commit();
|
|
157
172
|
} finally {
|
|
158
173
|
session.close();
|
|
159
174
|
}
|
|
@@ -165,27 +180,20 @@ accepted COMMIT, closing the session cannot undo it. The pooled client methods
|
|
|
165
180
|
reject an unfinished interactive transaction and close that session instead of
|
|
166
181
|
lending it to another caller.
|
|
167
182
|
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
const transactionId = randomUUID();
|
|
174
|
-
await db.execute([
|
|
175
|
-
{ sql: 'INSERT INTO notes(message) VALUES (?)', parameters: ['receipt example'] },
|
|
176
|
-
], { transactionId });
|
|
177
|
-
|
|
178
|
-
// This may also be queried on a newly connected client after transport loss.
|
|
179
|
-
const receipt = await db.getTransaction(transactionId);
|
|
180
|
-
console.log(receipt.state);
|
|
181
|
-
```
|
|
183
|
+
Connection loss or a timeout during COMMIT can leave its outcome unknown. The
|
|
184
|
+
SDK never replays SQL and has no persistent transaction status API. Applications
|
|
185
|
+
that need safe retries must provide their own business operation keys and atomic
|
|
186
|
+
uniqueness checks. Closing a session rolls back unfinished work; a commit that
|
|
187
|
+
has already completed remains durable even if its reply was lost.
|
|
182
188
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
189
|
+
The server ignores unknown JSON fields, including `transactionId` sent by older
|
|
190
|
+
SDKs for `{ write: true }` or `session.begin()`. It samples compatibility warnings
|
|
191
|
+
without logging field values. This does not restore transaction receipts or the
|
|
192
|
+
removed `getTransaction()`/`status` operation; applications using those must be
|
|
193
|
+
updated. Invalid known-field types and malformed requests are still rejected.
|
|
186
194
|
|
|
187
195
|
Server errors reject with `SQLessError`, exposing `code`, optional
|
|
188
|
-
`statementIndex
|
|
196
|
+
`statementIndex`. Connection, timeout, and queue
|
|
189
197
|
errors reject with `Error`. Requests are limited to 4 MiB and responses to 9 MiB.
|
|
190
198
|
|
|
191
199
|
## Tests
|
package/errors.js
CHANGED
package/index.d.ts
CHANGED
|
@@ -14,25 +14,19 @@ export interface StatementResult {
|
|
|
14
14
|
truncated: boolean;
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
export
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
}
|
|
17
|
+
export type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
|
|
18
|
+
export type WebhookEvent = {
|
|
19
|
+
webhook: string;
|
|
20
|
+
/** Earliest delivery time, in RFC 3339 format. */
|
|
21
|
+
startedAt?: string;
|
|
22
|
+
method?: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
|
|
23
|
+
headers?: Record<string, string>;
|
|
24
|
+
} & ({ payload?: JSONValue; body?: never } | { body: string; payload?: never });
|
|
25
|
+
export interface ExecuteOptions { events: WebhookEvent[] }
|
|
25
26
|
|
|
26
27
|
export interface SQLResult {
|
|
28
|
+
eventIds?: string[];
|
|
27
29
|
results: StatementResult[];
|
|
28
|
-
transaction?: Transaction;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export interface ExecuteOptions {
|
|
32
|
-
/** Generate a transaction UUID before sending a complete write batch. */
|
|
33
|
-
write?: boolean;
|
|
34
|
-
/** Supply your own UUID to query the receipt after an uncertain outcome. */
|
|
35
|
-
transactionId?: string;
|
|
36
30
|
}
|
|
37
31
|
|
|
38
32
|
export type ConnectOptions = {
|
|
@@ -48,15 +42,14 @@ export class SQLessError extends Error {
|
|
|
48
42
|
private constructor();
|
|
49
43
|
readonly code: string;
|
|
50
44
|
readonly statementIndex?: number;
|
|
51
|
-
readonly transaction?: Transaction;
|
|
52
45
|
}
|
|
53
46
|
|
|
54
47
|
export class SQLessClient {
|
|
55
48
|
private constructor();
|
|
56
49
|
static connect(options: string | ConnectOptions): Promise<SQLessClient>;
|
|
57
50
|
execute(statements: Statement[], options?: ExecuteOptions): Promise<SQLResult>;
|
|
51
|
+
executeWithEvents(statements: Statement[], events: ExecuteOptions["events"]): Promise<SQLResult>;
|
|
58
52
|
executeScript(script: string, parameterSets?: SQLValue[][], options?: ExecuteOptions): Promise<SQLResult>;
|
|
59
|
-
getTransaction(transactionId: string): Promise<Transaction>;
|
|
60
53
|
openSession(): Promise<SQLessSession>;
|
|
61
54
|
isClosed(): boolean;
|
|
62
55
|
close(): void;
|
|
@@ -64,12 +57,12 @@ export class SQLessClient {
|
|
|
64
57
|
|
|
65
58
|
/** A reserved pool slot. Calls on a session must be awaited sequentially. */
|
|
66
59
|
export interface SQLessSession {
|
|
67
|
-
execute(statements: Statement[], options?:
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
60
|
+
execute(statements: Statement[], options?: ExecuteOptions): Promise<SQLResult>;
|
|
61
|
+
executeWithEvents(statements: Statement[], events: ExecuteOptions["events"]): Promise<SQLResult>;
|
|
62
|
+
executeScript(script: string, parameterSets?: SQLValue[][], options?: ExecuteOptions): Promise<SQLResult>;
|
|
63
|
+
begin(): Promise<void>;
|
|
64
|
+
commit(): Promise<void>;
|
|
65
|
+
rollback(): Promise<void>;
|
|
73
66
|
isClosed(): boolean;
|
|
74
67
|
/** Releases the slot and aborts uncommitted work; cannot undo an accepted COMMIT. */
|
|
75
68
|
close(): void;
|
package/index.js
CHANGED
|
@@ -1,10 +1,18 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
1
|
import { Connection } from './transport.js';
|
|
3
2
|
|
|
4
3
|
export { SQLessError } from './errors.js';
|
|
5
4
|
|
|
6
|
-
const result = response => ({ results: response.results ?? [], ...(response.
|
|
7
|
-
|
|
5
|
+
const result = response => ({ results: response.results ?? [], ...(response.eventIds && { eventIds: response.eventIds }) });
|
|
6
|
+
|
|
7
|
+
function execution(options) {
|
|
8
|
+
if (options?.events === undefined) return { op: 'execute' };
|
|
9
|
+
const { events } = options;
|
|
10
|
+
if (!Array.isArray(events) || !events.length) throw new TypeError('events must be a nonempty array');
|
|
11
|
+
if (events.some(e => e.startedAt != null)) return { op: 'execute_with_scheduled_events', events };
|
|
12
|
+
const extended = events.some(e => e.method != null || Object.keys(e.headers ?? {}).length > 0 ||
|
|
13
|
+
e.body != null || e.payload === undefined || !e.webhook.startsWith('https://'));
|
|
14
|
+
return { op: extended ? 'execute_with_http_events' : 'execute_with_events', events };
|
|
15
|
+
}
|
|
8
16
|
|
|
9
17
|
// Transport objects never leave this module. Clients and leased sessions share
|
|
10
18
|
// the same bounded pool; opening an interactive session reserves one pool slot.
|
|
@@ -18,15 +26,16 @@ export class SQLessClient {
|
|
|
18
26
|
constructor(connection) { this.#connection = connection; }
|
|
19
27
|
|
|
20
28
|
async execute(statements, options) {
|
|
21
|
-
return result(await this.#connection.request({
|
|
29
|
+
return result(await this.#connection.request({ ...execution(options), statements }));
|
|
22
30
|
}
|
|
23
31
|
|
|
24
|
-
async
|
|
25
|
-
|
|
32
|
+
async executeWithEvents(statements, events) {
|
|
33
|
+
if (!Array.isArray(events) || !events.length) throw new TypeError('events must be a nonempty array');
|
|
34
|
+
return this.execute(statements, { events });
|
|
26
35
|
}
|
|
27
36
|
|
|
28
|
-
async
|
|
29
|
-
return (await this.#connection.request({
|
|
37
|
+
async executeScript(script, parameterSets, options) {
|
|
38
|
+
return result(await this.#connection.request({ ...execution(options), script, parameterSets }));
|
|
30
39
|
}
|
|
31
40
|
|
|
32
41
|
async openSession() {
|
|
@@ -47,24 +56,22 @@ class SQLessSession {
|
|
|
47
56
|
this.#session = session;
|
|
48
57
|
}
|
|
49
58
|
|
|
50
|
-
async execute(statements,
|
|
51
|
-
return result(await this.#session.call({
|
|
59
|
+
async execute(statements, options) {
|
|
60
|
+
return result(await this.#session.call({ ...execution(options), statements }));
|
|
52
61
|
}
|
|
53
62
|
|
|
54
|
-
async
|
|
55
|
-
|
|
63
|
+
async executeWithEvents(statements, events) {
|
|
64
|
+
if (!Array.isArray(events) || !events.length) throw new TypeError('events must be a nonempty array');
|
|
65
|
+
return this.execute(statements, { events });
|
|
56
66
|
}
|
|
57
67
|
|
|
58
|
-
async
|
|
59
|
-
return (await this.
|
|
68
|
+
async executeScript(script, parameterSets, options) {
|
|
69
|
+
return result(await this.#session.call({ ...execution(options), script, parameterSets }));
|
|
60
70
|
}
|
|
61
71
|
|
|
62
|
-
async
|
|
63
|
-
async
|
|
64
|
-
|
|
65
|
-
async getTransaction(transactionId) {
|
|
66
|
-
return (await this.#session.call({ op: 'status', transactionId })).transaction;
|
|
67
|
-
}
|
|
72
|
+
async begin() { await this.executeScript('BEGIN IMMEDIATE'); }
|
|
73
|
+
async commit() { await this.executeScript('COMMIT'); }
|
|
74
|
+
async rollback() { await this.executeScript('ROLLBACK'); }
|
|
68
75
|
|
|
69
76
|
isClosed() { return this.#session.closed; }
|
|
70
77
|
|
package/package.json
CHANGED
package/transport.js
CHANGED
|
@@ -66,9 +66,7 @@ class Session {
|
|
|
66
66
|
this.chunks = []; this.bytes = 0; this.expected = null;
|
|
67
67
|
const pending = this.pending;
|
|
68
68
|
if (response.version !== 1 || response.id !== pending.id) throw new Error('SQLess response identity mismatch');
|
|
69
|
-
|
|
70
|
-
// necessarily the transaction currently running on this session.
|
|
71
|
-
if (pending.op === 'execute' || response.sessionState === 'closed') this.state = response.sessionState;
|
|
69
|
+
if (pending.op === 'execute' || pending.op === 'execute_with_events' || pending.op === 'execute_with_http_events' || pending.op === 'execute_with_scheduled_events' || response.sessionState === 'closed') this.state = response.sessionState;
|
|
72
70
|
this.pending = null; clearTimeout(pending.timer);
|
|
73
71
|
if (response.error) pending.reject(new SQLessError(response)); else pending.resolve(response);
|
|
74
72
|
if (response.sessionState === 'closed') this.close(new Error('SQLess session closed'));
|