@forestfuture/active-record 0.0.0 → 0.7.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.
- package/LICENSE +21 -0
- package/README.md +27 -2
- package/config-schema.json +56 -0
- package/dist/adapter-AGKp6wfO.d.mts +1326 -0
- package/dist/adapter.d.mts +3 -0
- package/dist/adapter.mjs +4 -0
- package/dist/batch-BS_WseLf.mjs +4255 -0
- package/dist/cli.d.mts +345 -0
- package/dist/cli.mjs +4 -0
- package/dist/command.d.mts +1 -0
- package/dist/command.mjs +2471 -0
- package/dist/d1.d.mts +68 -0
- package/dist/d1.mjs +0 -0
- package/dist/epoch-storage-o2aoOH7H.mjs +112 -0
- package/dist/for-adapters-Ch6CoHD4.mjs +240 -0
- package/dist/for-adapters-D_Iu0gS_.mjs +33 -0
- package/dist/for-adapters-t3-LukJQ.d.mts +21 -0
- package/dist/generated-model-Cnt0Ot9q.mjs +1857 -0
- package/dist/index-CyCJuM96.d.mts +149 -0
- package/dist/index.d.mts +3 -0
- package/dist/index.mjs +4 -0
- package/dist/plugin-Cyoej7qV.mjs +600 -0
- package/dist/plugin-XOHYndhP.mjs +939 -0
- package/dist/postgresql.d.mts +72 -0
- package/dist/postgresql.mjs +588 -0
- package/dist/src-la_KkjCS.mjs +1 -0
- package/dist/storage-override-CpbkdIqE.mjs +187 -0
- package/llms-full.txt +5033 -0
- package/package.json +65 -4
- package/skills/active-record/SKILL.md +88 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { i as AnyDatabase, lt as QueryEvent$1, r as SchemaAdapter, ut as QueryListener$1 } from "./adapter-AGKp6wfO.mjs";
|
|
2
|
+
import pg from "pg";
|
|
3
|
+
//#region src/adapters/postgresql/adapter.d.ts
|
|
4
|
+
/** The Postgres database a generated schema's Models query: `adapter: postgresql({ binding: "HYPERDRIVE" })`. */
|
|
5
|
+
export declare function postgresql({ binding }: {
|
|
6
|
+
binding: string;
|
|
7
|
+
}): SchemaAdapter;
|
|
8
|
+
//#endregion
|
|
9
|
+
//#region src/adapters/postgresql/clients.d.ts
|
|
10
|
+
/** Reads a column's text, by its type's OID, as a JavaScript value: `pg`'s `types` option. */
|
|
11
|
+
interface TypeParsers {
|
|
12
|
+
getTypeParser(oid: number, format?: string): (text: string) => unknown;
|
|
13
|
+
}
|
|
14
|
+
/** One query, as `pg`'s `query` takes it. */
|
|
15
|
+
interface QueryConfig {
|
|
16
|
+
text: string;
|
|
17
|
+
values?: unknown[];
|
|
18
|
+
types?: TypeParsers;
|
|
19
|
+
}
|
|
20
|
+
/** What `pg`'s `query` resolves to, as far as this adapter reads it. */
|
|
21
|
+
interface QueryResult {
|
|
22
|
+
rows: Record<string, unknown>[];
|
|
23
|
+
rowCount: number | null;
|
|
24
|
+
command: string;
|
|
25
|
+
}
|
|
26
|
+
/** What sends a query: a client of `pg`'s. */
|
|
27
|
+
interface Queryable {
|
|
28
|
+
query(config: QueryConfig): Promise<QueryResult>;
|
|
29
|
+
}
|
|
30
|
+
/** A client lent by a `pg` Pool, released when it's done. */
|
|
31
|
+
interface PoolClient extends Queryable {
|
|
32
|
+
release(error?: Error | boolean): void;
|
|
33
|
+
}
|
|
34
|
+
/** A `pg` Pool, as `connect` takes it: the app's own, which the app ends. */
|
|
35
|
+
interface Pool {
|
|
36
|
+
connect(): Promise<PoolClient>;
|
|
37
|
+
/** What it was built with: its connection string, when it was built from one. */
|
|
38
|
+
readonly options?: {
|
|
39
|
+
readonly connectionString?: string | undefined;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
//#region src/adapters/postgresql/driver.d.ts
|
|
44
|
+
/** What `onQuery` hears from Postgres about a statement: its command and the rows it counted. */
|
|
45
|
+
interface PostgreSQLMeta {
|
|
46
|
+
/** `SELECT`, `INSERT`, `UPDATE`, `DELETE`, … */
|
|
47
|
+
command: string;
|
|
48
|
+
rowCount: number | null;
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/adapters/postgresql/database.d.ts
|
|
52
|
+
/** What `onQuery` hears about a statement: its Model, SQL, bound values, timing, and Postgres's `meta`. */
|
|
53
|
+
type QueryEvent = QueryEvent$1<PostgreSQLMeta>;
|
|
54
|
+
/** Hears each statement's `QueryEvent`, with Postgres's `meta`. */
|
|
55
|
+
type QueryListener = QueryListener$1<PostgreSQLMeta>;
|
|
56
|
+
interface ConnectOptions {
|
|
57
|
+
/** Called once for every statement sent to Postgres, with Postgres's `meta`. */
|
|
58
|
+
onQuery?: QueryListener;
|
|
59
|
+
}
|
|
60
|
+
/** Where a Database's Postgres is: a Hyperdrive binding (`env.HYPERDRIVE`), a connection string, or a `pg` Pool. */
|
|
61
|
+
type PostgreSQLSource = Hyperdrive | string | Pool;
|
|
62
|
+
/**
|
|
63
|
+
* A handle on a Postgres database; every query goes through it. `db.batch` writes in one
|
|
64
|
+
* transaction, on a client of its own.
|
|
65
|
+
*/
|
|
66
|
+
export declare class Database extends AnyDatabase {
|
|
67
|
+
#private;
|
|
68
|
+
constructor(source: PostgreSQLSource, options?: ConnectOptions);
|
|
69
|
+
}
|
|
70
|
+
export declare function connect(source: PostgreSQLSource, options?: ConnectOptions): Database;
|
|
71
|
+
//#endregion
|
|
72
|
+
export type { ConnectOptions, Pool, PostgreSQLMeta, PostgreSQLSource, QueryEvent, QueryListener };
|
|
@@ -0,0 +1,588 @@
|
|
|
1
|
+
import { L as boundValue, ct as NoDatabase } from "./generated-model-Cnt0Ot9q.mjs";
|
|
2
|
+
import { a as databaseExecutor, i as AnyDatabase, s as DatabaseExecutor } from "./batch-BS_WseLf.mjs";
|
|
3
|
+
import { n as onlyRequested, t as workersEnv } from "./for-adapters-D_Iu0gS_.mjs";
|
|
4
|
+
import pg from "pg";
|
|
5
|
+
//#region src/adapters/postgresql/connect-timeout.ts
|
|
6
|
+
/** The limit when the connection string sets none, in milliseconds. */
|
|
7
|
+
const defaultTimeoutMs = 1e4;
|
|
8
|
+
/** The longest a timer waits, in milliseconds (about 24 days): it fires at once for longer. */
|
|
9
|
+
const longestTimeoutMs = 2 ** 31 - 1;
|
|
10
|
+
/** libpq's shortest limit, in seconds: a `connect_timeout` of 1 waits 2. */
|
|
11
|
+
const shortestTimeoutSeconds = 2;
|
|
12
|
+
/** A whole number as libpq reads one: a sign, digits, and spaces around them. */
|
|
13
|
+
const wholeNumber = /^\s*[-+]?\d+\s*$/;
|
|
14
|
+
/**
|
|
15
|
+
* `pg`'s `connectionTimeoutMillis` for clients opened from `connectionString`: its `connect_timeout`
|
|
16
|
+
* in seconds, as libpq takes it (`pg` reads it only through libpq), where 0 or less sets no limit.
|
|
17
|
+
* Throws `TypeError` for a value that isn't a whole number, as libpq refuses one, naming the
|
|
18
|
+
* parameter but not the connection string, which may hold a password.
|
|
19
|
+
*/
|
|
20
|
+
function connectTimeoutOf(connectionString) {
|
|
21
|
+
const value = queryParameter(connectionString, "connect_timeout");
|
|
22
|
+
if (value === void 0) return defaultTimeoutMs;
|
|
23
|
+
if (!wholeNumber.test(value)) throw new TypeError(`connect_timeout must be a whole number of seconds, not ${JSON.stringify(value)}`);
|
|
24
|
+
const seconds = Number.parseInt(value, 10);
|
|
25
|
+
if (seconds <= 0) return 0;
|
|
26
|
+
return Math.min(Math.max(seconds, shortestTimeoutSeconds) * 1e3, longestTimeoutMs);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A parameter of a connection string's query (its last, when it's given twice, as `pg` reads it),
|
|
30
|
+
* or undefined when it has none. The query is read on its own, before any `#` and after the first
|
|
31
|
+
* `?`, as a URL's is: `pg` takes strings a URL can't parse, such as a socket's with no host
|
|
32
|
+
* (`postgres://app@/app?host=/tmp`).
|
|
33
|
+
*/
|
|
34
|
+
function queryParameter(connectionString, name) {
|
|
35
|
+
const [beforeFragment = ""] = connectionString.split("#");
|
|
36
|
+
const start = beforeFragment.indexOf("?");
|
|
37
|
+
if (start === -1) return void 0;
|
|
38
|
+
return new URLSearchParams(beforeFragment.slice(start + 1)).getAll(name).at(-1);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* A client of `connectionString`'s, connected: `pg` gives up on it after `timeoutMs` (0: never).
|
|
42
|
+
* An open that took that long fails with libpq's `timeout expired`, `pg`'s own error as its
|
|
43
|
+
* cause, on Workers too, where `pg` reports it as a dropped connection.
|
|
44
|
+
*/
|
|
45
|
+
async function openClient(connectionString, timeoutMs) {
|
|
46
|
+
const client = new pg.Client({
|
|
47
|
+
connectionString,
|
|
48
|
+
connectionTimeoutMillis: timeoutMs
|
|
49
|
+
});
|
|
50
|
+
client.on("error", () => {});
|
|
51
|
+
if (timeoutMs === 0) return client.connect().then(() => client);
|
|
52
|
+
let expired = false;
|
|
53
|
+
const timer = setTimeout(() => expired = true, timeoutMs);
|
|
54
|
+
try {
|
|
55
|
+
await client.connect();
|
|
56
|
+
return client;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
throw expired ? new Error("timeout expired", { cause: error }) : error;
|
|
59
|
+
} finally {
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/adapters/postgresql/clients.ts
|
|
65
|
+
/**
|
|
66
|
+
* The connection string a source opens its clients from: a Hyperdrive binding's, or the source
|
|
67
|
+
* itself when it's one. Undefined for anything else, such as a Pool.
|
|
68
|
+
*/
|
|
69
|
+
function connectionStringOf(source) {
|
|
70
|
+
if (typeof source === "string") return source;
|
|
71
|
+
const held = source?.connectionString;
|
|
72
|
+
return typeof held === "string" ? held : void 0;
|
|
73
|
+
}
|
|
74
|
+
/** Clients lent by the app's Pool. */
|
|
75
|
+
var PoolClients = class {
|
|
76
|
+
#pool;
|
|
77
|
+
constructor(pool) {
|
|
78
|
+
this.#pool = pool;
|
|
79
|
+
}
|
|
80
|
+
async borrow() {
|
|
81
|
+
const client = await this.#pool.connect();
|
|
82
|
+
return {
|
|
83
|
+
client,
|
|
84
|
+
done: async (error) => client.release(error instanceof Error ? error : void 0)
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
own() {
|
|
88
|
+
return this.borrow();
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* One `withDatabase` scope's client: opened by its first operation, it serves the rest, one at a
|
|
93
|
+
* time, and closes when the scope ends and the operations sent before then are done.
|
|
94
|
+
*/
|
|
95
|
+
var ClientScope = class {
|
|
96
|
+
#open;
|
|
97
|
+
/** The client, once an operation has asked for it. */
|
|
98
|
+
#client;
|
|
99
|
+
/**
|
|
100
|
+
* Settles when the latest operation is done. Each waits for the one before it, so `pg` never
|
|
101
|
+
* gets a query while another is running (its queue for those is deprecated), and closing the
|
|
102
|
+
* client waits for the last.
|
|
103
|
+
*/
|
|
104
|
+
#lastDone = Promise.resolve();
|
|
105
|
+
#hasEnded = false;
|
|
106
|
+
constructor(open) {
|
|
107
|
+
this.#open = open;
|
|
108
|
+
}
|
|
109
|
+
/** Whether the scope has ended: an operation sent after it (a `waitUntil` save) opens its own. */
|
|
110
|
+
get hasEnded() {
|
|
111
|
+
return this.#hasEnded;
|
|
112
|
+
}
|
|
113
|
+
async lease() {
|
|
114
|
+
const previous = this.#lastDone;
|
|
115
|
+
let finish = () => {};
|
|
116
|
+
this.#lastDone = new Promise((resolve) => finish = resolve);
|
|
117
|
+
await previous;
|
|
118
|
+
const opening = this.#opened();
|
|
119
|
+
const done = async (error) => {
|
|
120
|
+
if (isSessionEnding(error)) this.#forget(opening);
|
|
121
|
+
finish();
|
|
122
|
+
};
|
|
123
|
+
try {
|
|
124
|
+
return {
|
|
125
|
+
client: await opening,
|
|
126
|
+
done
|
|
127
|
+
};
|
|
128
|
+
} catch (error) {
|
|
129
|
+
await done();
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Ends the scope at once, and closes its client in the background once its operations are
|
|
135
|
+
* done, so a query still running (a `waitUntil` save's) never holds up the response.
|
|
136
|
+
*/
|
|
137
|
+
end() {
|
|
138
|
+
this.#hasEnded = true;
|
|
139
|
+
this.#closeWhenDone();
|
|
140
|
+
}
|
|
141
|
+
/** Closes the client the scope holds once its last operation is done, if it holds one. */
|
|
142
|
+
async #closeWhenDone() {
|
|
143
|
+
await this.#lastDone;
|
|
144
|
+
const client = await this.#client?.catch(() => void 0);
|
|
145
|
+
if (client !== void 0) await closed(client);
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* The client, opened on first use. A failed open is tried again by the next operation, and so
|
|
149
|
+
* is a client whose connection has gone, as `pg` reports it (`error` on the client itself, then
|
|
150
|
+
* `end`) or the server does (`isSessionEnding`). An error that leaves the connection healthy,
|
|
151
|
+
* such as `pg` refusing a value before sending it, never costs the scope its client.
|
|
152
|
+
*/
|
|
153
|
+
#opened() {
|
|
154
|
+
if (this.#client !== void 0) return this.#client;
|
|
155
|
+
const opening = this.#open().then((client) => client.on("error", () => this.#forget(opening)).once("end", () => this.#forget(opening)), (error) => {
|
|
156
|
+
this.#forget(opening);
|
|
157
|
+
throw error;
|
|
158
|
+
});
|
|
159
|
+
this.#client = opening;
|
|
160
|
+
return opening;
|
|
161
|
+
}
|
|
162
|
+
#forget(opening) {
|
|
163
|
+
if (this.#client === opening) this.#client = void 0;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
/**
|
|
167
|
+
* Clients opened from a connection string. Inside a `withDatabase` scope, its client serves each
|
|
168
|
+
* operation (`ClientScope`). Outside one, before it or after it, each operation opens its own and
|
|
169
|
+
* closes it when it's done, as no client may outlive a Worker's request.
|
|
170
|
+
*/
|
|
171
|
+
var UrlClients = class {
|
|
172
|
+
#connectionString;
|
|
173
|
+
/** How long opening a client may take, in milliseconds: no limit when 0. */
|
|
174
|
+
#connectTimeoutMs;
|
|
175
|
+
constructor(connectionString) {
|
|
176
|
+
this.#connectionString = connectionString;
|
|
177
|
+
this.#connectTimeoutMs = connectTimeoutOf(connectionString);
|
|
178
|
+
}
|
|
179
|
+
openScope() {
|
|
180
|
+
return new ClientScope(() => this.#open());
|
|
181
|
+
}
|
|
182
|
+
async closeScope(scope) {
|
|
183
|
+
scope.end();
|
|
184
|
+
}
|
|
185
|
+
borrow(scope) {
|
|
186
|
+
return scope === void 0 || scope.hasEnded ? this.own() : scope.lease();
|
|
187
|
+
}
|
|
188
|
+
async own() {
|
|
189
|
+
const client = await this.#open();
|
|
190
|
+
return {
|
|
191
|
+
client,
|
|
192
|
+
done: () => closed(client)
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
#open() {
|
|
196
|
+
return openClient(this.#connectionString, this.#connectTimeoutMs);
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
/** Whether the server sent `error` as it ends the session: a `FATAL` or `PANIC` (57P01, a terminated backend). */
|
|
200
|
+
function isSessionEnding(error) {
|
|
201
|
+
const severity = error?.severity;
|
|
202
|
+
return severity === "FATAL" || severity === "PANIC";
|
|
203
|
+
}
|
|
204
|
+
/** Ends `client`. A connection that fails to close has nothing left to do, so it's not an error. */
|
|
205
|
+
async function closed(client) {
|
|
206
|
+
await client.end().catch(() => {});
|
|
207
|
+
}
|
|
208
|
+
//#endregion
|
|
209
|
+
//#region src/adapters/postgresql/is-object.ts
|
|
210
|
+
/** Whether `value` is an object, one a WeakMap can key. */
|
|
211
|
+
const isObject = (value) => typeof value === "object" && value !== null;
|
|
212
|
+
//#endregion
|
|
213
|
+
//#region src/adapters/postgresql/errors.ts
|
|
214
|
+
const kinds = {
|
|
215
|
+
"23505": "unique",
|
|
216
|
+
"23502": "notNull",
|
|
217
|
+
"23503": "foreignKey",
|
|
218
|
+
"23514": "check"
|
|
219
|
+
};
|
|
220
|
+
const fields = (error) => isObject(error) ? error : {};
|
|
221
|
+
const text = (value) => typeof value === "string" ? value : void 0;
|
|
222
|
+
/** The key columns an error's `detail` named, read before `detail` is stripped. */
|
|
223
|
+
const keyColumns = /* @__PURE__ */ new WeakMap();
|
|
224
|
+
/** The key columns in a unique or foreign-key failure's detail. */
|
|
225
|
+
function keyColumnsIn(detail) {
|
|
226
|
+
const key = /^Key \((.+?)\)=/.exec(text(detail) ?? "")?.[1];
|
|
227
|
+
return key === void 0 ? [] : key.split(", ").map((part) => part.replace(/^"(.*)"$/, "$1"));
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* `error` without the fields where Postgres writes a row's values (`detail`: "Key (email)=(…)",
|
|
231
|
+
* "Failing row contains (…)"; `where`; the internal query), so they never reach a log through an
|
|
232
|
+
* error's `cause` or `onQuery`, and a data error's message without the value it refused. Its key
|
|
233
|
+
* columns are kept for `constraintFailure`.
|
|
234
|
+
*/
|
|
235
|
+
function withoutRowValues(error) {
|
|
236
|
+
if (!isObject(error) || !("detail" in error)) return error;
|
|
237
|
+
keyColumns.set(error, keyColumnsIn(error.detail));
|
|
238
|
+
for (const field of [
|
|
239
|
+
"detail",
|
|
240
|
+
"where",
|
|
241
|
+
"internalQuery"
|
|
242
|
+
]) delete error[field];
|
|
243
|
+
if (text(error.code)?.startsWith("22")) withoutRefusedValue(error);
|
|
244
|
+
return error;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* A data error's message (SQLSTATE class 22) with the value it refused filtered, in its stack
|
|
248
|
+
* too: `invalid input syntax for type uuid: "[FILTERED]"`, `value "[FILTERED]" is out of range`.
|
|
249
|
+
* Postgres quotes the value without escaping it, so all from its first quote to its last goes,
|
|
250
|
+
* but for an enum's quoted type name.
|
|
251
|
+
*/
|
|
252
|
+
function withoutRefusedValue(error) {
|
|
253
|
+
const message = text(error.message);
|
|
254
|
+
const filtered = message === void 0 ? void 0 : refusedValueFiltered(message);
|
|
255
|
+
if (message === void 0 || filtered === message) return;
|
|
256
|
+
error.message = filtered;
|
|
257
|
+
const stack = text(error.stack);
|
|
258
|
+
if (stack !== void 0) error.stack = stack.replace(message, filtered);
|
|
259
|
+
}
|
|
260
|
+
const enumRefusal = "invalid input value for enum ";
|
|
261
|
+
/** Where the quoted identifier opening at `at` ends, past its closing quote; its own quotes are doubled. -1 if it never closes. */
|
|
262
|
+
function quotedEnd(message, at) {
|
|
263
|
+
let next = at + 1;
|
|
264
|
+
while (next < message.length) if (message[next] !== "\"") next += 1;
|
|
265
|
+
else if (message[next + 1] === "\"") next += 2;
|
|
266
|
+
else return next + 1;
|
|
267
|
+
return -1;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Where an enum refusal's type name ends: identifiers joined by dots, each bare or quoted
|
|
271
|
+
* (`mood`, `"Mood"`, `app."Mood"`), read in one pass. -1 if it isn't one.
|
|
272
|
+
*/
|
|
273
|
+
function enumNameEnd(message) {
|
|
274
|
+
let at = 29;
|
|
275
|
+
for (;;) {
|
|
276
|
+
if (message[at] === "\"") at = quotedEnd(message, at);
|
|
277
|
+
else while (at < message.length && !/[\s:".]/.test(message[at])) at += 1;
|
|
278
|
+
if (at === -1 || message[at] !== ".") return at;
|
|
279
|
+
at += 1;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* `message` with its refused value, from its first quote to its last, written `[FILTERED]`, but
|
|
284
|
+
* for an enum's quoted type name: `invalid input value for enum "Mood": "[FILTERED]"`. Scanned,
|
|
285
|
+
* not matched with a pattern that could backtrack, since the value is the user's.
|
|
286
|
+
*/
|
|
287
|
+
function refusedValueFiltered(message) {
|
|
288
|
+
if (message.startsWith(enumRefusal)) {
|
|
289
|
+
const end = enumNameEnd(message);
|
|
290
|
+
if (end !== -1 && message.startsWith(": \"", end) && message.endsWith("\"")) return `${message.slice(0, end)}: "[FILTERED]"`;
|
|
291
|
+
}
|
|
292
|
+
return message.replace(/".*"/s, "\"[FILTERED]\"");
|
|
293
|
+
}
|
|
294
|
+
/** The columns a failure names: a not-null's column, or the key in a unique failure's detail. */
|
|
295
|
+
function columnsOf(error, { column }) {
|
|
296
|
+
const named = text(column);
|
|
297
|
+
if (named !== void 0) return [named];
|
|
298
|
+
return isObject(error) ? keyColumns.get(error) ?? [] : [];
|
|
299
|
+
}
|
|
300
|
+
/** What a Postgres constraint failure says failed. Any other error, undefined. */
|
|
301
|
+
function constraintFailure(error) {
|
|
302
|
+
const failed = fields(error);
|
|
303
|
+
const kind = kinds[text(failed.code) ?? ""];
|
|
304
|
+
if (kind === void 0) return void 0;
|
|
305
|
+
return {
|
|
306
|
+
kind,
|
|
307
|
+
table: text(failed.table),
|
|
308
|
+
columns: columnsOf(error, failed)
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
/** The table Postgres's "relation … does not exist" names. Any other error, undefined. */
|
|
312
|
+
function missingTable(error) {
|
|
313
|
+
const { code, message } = fields(error);
|
|
314
|
+
if (code !== "42P01") return void 0;
|
|
315
|
+
return /relation "(.+?)" does not exist/.exec(text(message) ?? "")?.[1];
|
|
316
|
+
}
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/adapters/postgresql/type-parsers.ts
|
|
319
|
+
/** Postgres's type OIDs this adapter reads its own way. */
|
|
320
|
+
const oids = {
|
|
321
|
+
bool: 16,
|
|
322
|
+
int8: 20,
|
|
323
|
+
json: 114,
|
|
324
|
+
date: 1082,
|
|
325
|
+
timestamp: 1114,
|
|
326
|
+
timestamptz: 1184,
|
|
327
|
+
jsonb: 3802
|
|
328
|
+
};
|
|
329
|
+
const asText = (text) => text;
|
|
330
|
+
/**
|
|
331
|
+
* A `bigint`'s number, or the value as a JavaScript `bigint` past a safe integer, which the core
|
|
332
|
+
* refuses to read, naming its attribute, so a key is never silently wrong.
|
|
333
|
+
*/
|
|
334
|
+
function int8(text) {
|
|
335
|
+
const value = Number(text);
|
|
336
|
+
return Number.isSafeInteger(value) ? value : BigInt(text);
|
|
337
|
+
}
|
|
338
|
+
/** A `timestamptz` as ISO text, or its own text when it's no instant (`infinity`). */
|
|
339
|
+
function timestamptz(text) {
|
|
340
|
+
const read = pg.types.getTypeParser(oids.timestamptz)(text);
|
|
341
|
+
return read instanceof Date && !Number.isNaN(read.getTime()) ? read.toISOString() : text;
|
|
342
|
+
}
|
|
343
|
+
const parsers = {
|
|
344
|
+
[oids.bool]: (text) => text === "t" ? 1 : 0,
|
|
345
|
+
[oids.int8]: int8,
|
|
346
|
+
[oids.json]: asText,
|
|
347
|
+
[oids.jsonb]: asText,
|
|
348
|
+
[oids.date]: asText,
|
|
349
|
+
[oids.timestamp]: asText,
|
|
350
|
+
[oids.timestamptz]: timestamptz
|
|
351
|
+
};
|
|
352
|
+
/**
|
|
353
|
+
* What each query reads its columns with: given per query, so the app's own `pg` (and its
|
|
354
|
+
* Pool's other queries) keep `pg`'s defaults.
|
|
355
|
+
*/
|
|
356
|
+
const typeParsers = { getTypeParser(oid, format) {
|
|
357
|
+
return (format === void 0 || format === "text" ? parsers[oid] : void 0) ?? pg.types.getTypeParser(oid, format);
|
|
358
|
+
} };
|
|
359
|
+
//#endregion
|
|
360
|
+
//#region src/adapters/postgresql/driver.ts
|
|
361
|
+
/** Every query the driver sends: its error, if it fails, without the row values Postgres wrote in it. */
|
|
362
|
+
function queried(client, query) {
|
|
363
|
+
return client.query(query).catch((error) => {
|
|
364
|
+
throw withoutRowValues(error);
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
/** Sends `statement` on `client`, its values bound as the core stores them. */
|
|
368
|
+
async function sent(client, { sql, params }) {
|
|
369
|
+
const { rows, rowCount, command } = await queried(client, {
|
|
370
|
+
text: sql,
|
|
371
|
+
values: params.map(boundValue),
|
|
372
|
+
types: typeParsers
|
|
373
|
+
});
|
|
374
|
+
return {
|
|
375
|
+
rows,
|
|
376
|
+
rowsAffected: rowCount ?? 0,
|
|
377
|
+
meta: {
|
|
378
|
+
command,
|
|
379
|
+
rowCount
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
/** The single place the adapter calls Postgres. */
|
|
384
|
+
var PgDriver = class {
|
|
385
|
+
#clients;
|
|
386
|
+
constructor(clients) {
|
|
387
|
+
this.#clients = clients;
|
|
388
|
+
}
|
|
389
|
+
async send(statement, scope) {
|
|
390
|
+
return (await this.read([statement], scope))[0];
|
|
391
|
+
}
|
|
392
|
+
/** One after another on one client: Postgres has no batch, and reads needn't be atomic. */
|
|
393
|
+
async read(statements, scope) {
|
|
394
|
+
const lease = await this.#clients.borrow(scope);
|
|
395
|
+
try {
|
|
396
|
+
const results = [];
|
|
397
|
+
for (const statement of statements) results.push(await sent(lease.client, statement));
|
|
398
|
+
await lease.done();
|
|
399
|
+
return results;
|
|
400
|
+
} catch (error) {
|
|
401
|
+
await lease.done(error);
|
|
402
|
+
throw error;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* In one transaction, on a client nothing else sends on: a write sent beside it on a shared
|
|
407
|
+
* client would join the transaction, and be lost if it rolls back (ADR-0017).
|
|
408
|
+
*/
|
|
409
|
+
async write(statements) {
|
|
410
|
+
const lease = await this.#clients.own();
|
|
411
|
+
const { client } = lease;
|
|
412
|
+
try {
|
|
413
|
+
await queried(client, { text: "BEGIN" });
|
|
414
|
+
const results = [];
|
|
415
|
+
for (const statement of statements) results.push(await sent(client, statement));
|
|
416
|
+
await queried(client, { text: "COMMIT" });
|
|
417
|
+
await lease.done();
|
|
418
|
+
return results;
|
|
419
|
+
} catch (error) {
|
|
420
|
+
await rolledBack(client);
|
|
421
|
+
await lease.done(error);
|
|
422
|
+
throw error;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
openScope() {
|
|
426
|
+
return this.#clients.openScope?.();
|
|
427
|
+
}
|
|
428
|
+
async closeScope(scope) {
|
|
429
|
+
if (scope !== void 0) await this.#clients.closeScope?.(scope);
|
|
430
|
+
}
|
|
431
|
+
/** Postgres's errors are final: nothing is sent again. */
|
|
432
|
+
recover() {
|
|
433
|
+
return false;
|
|
434
|
+
}
|
|
435
|
+
};
|
|
436
|
+
/** Rolls back an open transaction. A client too broken to is given back as broken anyway. */
|
|
437
|
+
async function rolledBack(client) {
|
|
438
|
+
await client.query({ text: "ROLLBACK" }).catch(() => {});
|
|
439
|
+
}
|
|
440
|
+
//#endregion
|
|
441
|
+
//#region src/adapters/postgresql/current-database.ts
|
|
442
|
+
/** The Worker's bindings, from `cloudflare:workers`, read once; undefined outside a Worker. */
|
|
443
|
+
let bindings;
|
|
444
|
+
/** The `env` a test mocks with the PostgreSQL adapter inlined is this module's import, so it's imported here. */
|
|
445
|
+
function workerBindings() {
|
|
446
|
+
bindings ??= workersEnv(() => import("cloudflare:workers"));
|
|
447
|
+
return bindings;
|
|
448
|
+
}
|
|
449
|
+
/** @internal The library's key for the connection string a Database opens its clients from. */
|
|
450
|
+
const pgConnectionString = Symbol("pgConnectionString");
|
|
451
|
+
/**
|
|
452
|
+
* Each binding's own Database: a Hyperdrive binding's kept by the binding, so it goes when the
|
|
453
|
+
* binding does; a connection string's by the string, of which a Worker's env holds a few.
|
|
454
|
+
*/
|
|
455
|
+
const byHyperdrive = /* @__PURE__ */ new WeakMap();
|
|
456
|
+
const byString = /* @__PURE__ */ new Map();
|
|
457
|
+
function defaultDatabase(binding, connectionString, name) {
|
|
458
|
+
const hyperdrive = isObject(binding) ? binding : void 0;
|
|
459
|
+
let db = hyperdrive === void 0 ? byString.get(connectionString) : byHyperdrive.get(hyperdrive);
|
|
460
|
+
if (db === void 0) {
|
|
461
|
+
db = new AnyDatabase(new DatabaseExecutor(pgAdapter, new PgDriver(new UrlClients(connectionString))));
|
|
462
|
+
db[databaseExecutor].setOrigin({ binding: name });
|
|
463
|
+
if (hyperdrive === void 0) byString.set(connectionString, db);
|
|
464
|
+
else byHyperdrive.set(hyperdrive, db);
|
|
465
|
+
}
|
|
466
|
+
return db;
|
|
467
|
+
}
|
|
468
|
+
/** The connection string a request's Postgres database opens its clients from, or its Pool was built from. */
|
|
469
|
+
const dbConnectionString = (db) => db[pgConnectionString];
|
|
470
|
+
/** The database a query on binding `name` uses now: the request's for it, or the binding's own. */
|
|
471
|
+
async function databaseFor(name, requested) {
|
|
472
|
+
const env = name === void 0 ? void 0 : await workerBindings();
|
|
473
|
+
if (env === void 0 || name === void 0) return onlyRequested(requested, name, "connect(…)");
|
|
474
|
+
const binding = env[name];
|
|
475
|
+
const connectionString = connectionStringOf(binding);
|
|
476
|
+
if (connectionString === void 0) throw new NoDatabase(`The binding ${name} isn't in this Worker's env as a Hyperdrive binding or a connection string; check hyperdrive in your Wrangler config`);
|
|
477
|
+
return requested.find((db) => dbConnectionString(db) === connectionString) ?? defaultDatabase(binding, connectionString, name);
|
|
478
|
+
}
|
|
479
|
+
//#endregion
|
|
480
|
+
//#region src/adapters/postgresql/dialect.ts
|
|
481
|
+
/** A text literal, as an escape string, so it reads the same whatever `standard_conforming_strings` is. */
|
|
482
|
+
const literal = (text) => `E'${text.replaceAll("\\", "\\\\").replaceAll("'", "''")}'`;
|
|
483
|
+
/** A quoted identifier; embedded double quotes are doubled. */
|
|
484
|
+
const quoted = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
485
|
+
/** A function call takes at most 100 arguments: 50 key and value pairs to an object. */
|
|
486
|
+
const pairsPerObject = 50;
|
|
487
|
+
/** One JSON object of `pairs`, joined from as many `jsonb_build_object` calls as they need. */
|
|
488
|
+
function jsonObject(pairs) {
|
|
489
|
+
const parts = [];
|
|
490
|
+
for (let start = 0; start < pairs.length; start += pairsPerObject) parts.push(`jsonb_build_object(${pairs.slice(start, start + pairsPerObject).join(", ")})`);
|
|
491
|
+
return parts.join(" || ");
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* A json attribute's cell, which is its JSON's text: read as JSON for a json or jsonb column,
|
|
495
|
+
* which would otherwise keep it as a JSON string, and kept as that text for any other column.
|
|
496
|
+
*/
|
|
497
|
+
function jsonCell(table, column, index) {
|
|
498
|
+
return `CASE WHEN ${`pg_typeof((NULL::${table}).${quoted(column)})`} IN ('json'::regtype, 'jsonb'::regtype) THEN (cells ->> ${index})::jsonb ELSE cells -> ${index} END`;
|
|
499
|
+
}
|
|
500
|
+
//#endregion
|
|
501
|
+
//#region src/adapters/postgresql/adapter.ts
|
|
502
|
+
const pgAdapter = {
|
|
503
|
+
name: "Postgres",
|
|
504
|
+
dialect: {
|
|
505
|
+
placeholder: (index) => `$${index}`,
|
|
506
|
+
inList: (column, cells) => ({
|
|
507
|
+
sql: `${column} = ANY()`,
|
|
508
|
+
value: [...cells]
|
|
509
|
+
}),
|
|
510
|
+
pagination(limit, offset, params) {
|
|
511
|
+
let text = "";
|
|
512
|
+
if (limit !== void 0) {
|
|
513
|
+
params.push(limit);
|
|
514
|
+
text += ` LIMIT `;
|
|
515
|
+
}
|
|
516
|
+
if (offset !== void 0) {
|
|
517
|
+
params.push(offset);
|
|
518
|
+
text += ` OFFSET `;
|
|
519
|
+
}
|
|
520
|
+
return text;
|
|
521
|
+
},
|
|
522
|
+
/**
|
|
523
|
+
* Postgres compares no text with a number. A number selected for a text attribute is its text,
|
|
524
|
+
* and text selected for a number is the number its digits are, as a condition casts it; text
|
|
525
|
+
* that isn't one matches nothing.
|
|
526
|
+
*/
|
|
527
|
+
linkedKey(key, keyAttribute, linked) {
|
|
528
|
+
if (linked.isText === keyAttribute.isText) return key;
|
|
529
|
+
if (linked.isText) return `CAST(${key} AS TEXT)`;
|
|
530
|
+
return `CASE WHEN ${key} ~ ${literal("^\\s*[+-]?[0-9]+\\s*$")} THEN CAST(${key} AS NUMERIC) END`;
|
|
531
|
+
},
|
|
532
|
+
/**
|
|
533
|
+
* Each row's cells become an object of its columns, read into a record of `table`, so every
|
|
534
|
+
* value converts to its column's own type as an insert's would.
|
|
535
|
+
*/
|
|
536
|
+
bulkRows(table, attributes) {
|
|
537
|
+
const pairs = attributes.map(({ column, isJson }, index) => {
|
|
538
|
+
const cell = isJson ? jsonCell(table, column, index) : `cells -> ${index}`;
|
|
539
|
+
return `${literal(column)}, ${cell}`;
|
|
540
|
+
});
|
|
541
|
+
return {
|
|
542
|
+
select: attributes.map(({ column }) => `row.${quoted(column)}`).join(", "),
|
|
543
|
+
from: `jsonb_array_elements(::jsonb) AS cells, jsonb_populate_record(NULL::${table}, ${jsonObject(pairs)}) AS row`
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
},
|
|
547
|
+
maxBoundValues: 65535,
|
|
548
|
+
constraintFailure,
|
|
549
|
+
missingTable,
|
|
550
|
+
refusal: () => void 0,
|
|
551
|
+
databaseFor
|
|
552
|
+
};
|
|
553
|
+
/** The Postgres database a generated schema's Models query: `adapter: postgresql({ binding: "HYPERDRIVE" })`. */
|
|
554
|
+
function postgresql({ binding }) {
|
|
555
|
+
return {
|
|
556
|
+
adapter: pgAdapter,
|
|
557
|
+
binding
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
//#endregion
|
|
561
|
+
//#region src/adapters/postgresql/database.ts
|
|
562
|
+
function clientsFor(source) {
|
|
563
|
+
const connectionString = connectionStringOf(source);
|
|
564
|
+
return connectionString === void 0 ? new PoolClients(source) : new UrlClients(connectionString);
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* A handle on a Postgres database; every query goes through it. `db.batch` writes in one
|
|
568
|
+
* transaction, on a client of its own.
|
|
569
|
+
*/
|
|
570
|
+
var Database = class extends AnyDatabase {
|
|
571
|
+
#connectionString;
|
|
572
|
+
constructor(source, options = {}) {
|
|
573
|
+
super(new DatabaseExecutor(pgAdapter, new PgDriver(clientsFor(source)), options.onQuery));
|
|
574
|
+
this.#connectionString = connectionStringOf(source) ?? source.options?.connectionString;
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* @internal Its connection string, to match a Model's binding: a Pool's, when it was built from
|
|
578
|
+
* one. A Pool built any other way matches none.
|
|
579
|
+
*/
|
|
580
|
+
get [pgConnectionString]() {
|
|
581
|
+
return this.#connectionString;
|
|
582
|
+
}
|
|
583
|
+
};
|
|
584
|
+
function connect(source, options) {
|
|
585
|
+
return new Database(source, options);
|
|
586
|
+
}
|
|
587
|
+
//#endregion
|
|
588
|
+
export { Database, connect, postgresql };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|