@dotdo/postgres 0.1.2 → 0.1.3
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 +73 -1
- package/dist/client/index.d.ts +47 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +47 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/postgres-client.d.ts +273 -0
- package/dist/client/postgres-client.d.ts.map +1 -0
- package/dist/client/postgres-client.js +389 -0
- package/dist/client/postgres-client.js.map +1 -0
- package/dist/client/types.d.ts +167 -0
- package/dist/client/types.d.ts.map +1 -0
- package/dist/client/types.js +7 -0
- package/dist/client/types.js.map +1 -0
- package/dist/do/index.d.ts +18 -0
- package/dist/do/index.d.ts.map +1 -0
- package/dist/do/index.js +18 -0
- package/dist/do/index.js.map +1 -0
- package/dist/do/postgres.d.ts +110 -0
- package/dist/do/postgres.d.ts.map +1 -0
- package/dist/do/postgres.js +266 -0
- package/dist/do/postgres.js.map +1 -0
- package/dist/do/sql.d.ts +92 -0
- package/dist/do/sql.d.ts.map +1 -0
- package/dist/do/sql.js +204 -0
- package/dist/do/sql.js.map +1 -0
- package/dist/index.d.ts +25 -30
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +29 -30
- package/dist/index.js.map +1 -1
- package/dist/mcp/binding.d.ts +47 -0
- package/dist/mcp/binding.d.ts.map +1 -0
- package/dist/mcp/binding.js +183 -0
- package/dist/mcp/binding.js.map +1 -0
- package/dist/mcp/index.d.ts +92 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +91 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/server.d.ts +62 -0
- package/dist/mcp/server.d.ts.map +1 -0
- package/dist/mcp/server.js +278 -0
- package/dist/mcp/server.js.map +1 -0
- package/dist/mcp/tools.d.ts +58 -0
- package/dist/mcp/tools.d.ts.map +1 -0
- package/dist/mcp/tools.js +356 -0
- package/dist/mcp/tools.js.map +1 -0
- package/dist/mcp/types.d.ts +139 -0
- package/dist/mcp/types.d.ts.map +1 -0
- package/dist/mcp/types.js +7 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/pglite/workers-pglite.d.ts +13 -4
- package/dist/pglite/workers-pglite.d.ts.map +1 -1
- package/dist/pglite/workers-pglite.js +110 -5
- package/dist/pglite/workers-pglite.js.map +1 -1
- package/dist/pglite-assets/pglite.data +0 -0
- package/dist/pglite-assets/pglite.wasm +0 -0
- package/dist/worker/background-pglite-manager.d.ts +243 -0
- package/dist/worker/background-pglite-manager.d.ts.map +1 -0
- package/dist/worker/background-pglite-manager.js +528 -0
- package/dist/worker/background-pglite-manager.js.map +1 -0
- package/dist/worker/do-pglite-manager.d.ts +77 -0
- package/dist/worker/do-pglite-manager.d.ts.map +1 -1
- package/dist/worker/do-pglite-manager.js +189 -12
- package/dist/worker/do-pglite-manager.js.map +1 -1
- package/dist/worker/index.d.ts +7 -1
- package/dist/worker/index.d.ts.map +1 -1
- package/dist/worker/index.js +19 -1
- package/dist/worker/index.js.map +1 -1
- package/dist/worker/lazy-pglite-manager.d.ts +242 -0
- package/dist/worker/lazy-pglite-manager.d.ts.map +1 -0
- package/dist/worker/lazy-pglite-manager.js +463 -0
- package/dist/worker/lazy-pglite-manager.js.map +1 -0
- package/package.json +16 -3
- package/src/client/index.ts +61 -0
- package/src/client/postgres-client.ts +442 -0
- package/src/client/types.ts +211 -0
- package/src/do/index.ts +18 -0
- package/src/do/postgres.ts +367 -0
- package/src/do/sql.ts +280 -0
- package/src/index.ts +50 -30
- package/src/mcp/binding.ts +236 -0
- package/src/mcp/index.ts +122 -0
- package/src/mcp/server.ts +361 -0
- package/src/mcp/tools.ts +464 -0
- package/src/mcp/types.ts +148 -0
- package/src/pglite/workers-pglite.ts +141 -12
- package/src/pglite-assets/pglite.data +0 -0
- package/src/pglite-assets/pglite.wasm +0 -0
- package/src/worker/background-pglite-manager.ts +680 -0
- package/src/worker/do-pglite-manager.ts +235 -19
- package/src/worker/index.ts +71 -1
- package/src/worker/lazy-pglite-manager.ts +595 -0
- package/dist/iceberg/duckdb-wasm.d.ts +0 -447
- package/dist/iceberg/duckdb-wasm.d.ts.map +0 -1
- package/dist/iceberg/duckdb-wasm.js +0 -600
- package/dist/iceberg/duckdb-wasm.js.map +0 -1
- package/dist/iceberg/test-fixtures.d.ts +0 -151
- package/dist/iceberg/test-fixtures.d.ts.map +0 -1
- package/dist/iceberg/test-fixtures.js +0 -446
- package/dist/iceberg/test-fixtures.js.map +0 -1
- package/dist/worker/__mocks__/cloudflare-workers.d.ts +0 -31
- package/dist/worker/__mocks__/cloudflare-workers.d.ts.map +0 -1
- package/dist/worker/__mocks__/cloudflare-workers.js +0 -33
- package/dist/worker/__mocks__/cloudflare-workers.js.map +0 -1
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Postgres Durable Object
|
|
3
|
+
*
|
|
4
|
+
* A PostgreSQL database running in a Cloudflare Durable Object with:
|
|
5
|
+
* - DO SQLite for durable persistence (survives evictions)
|
|
6
|
+
* - PGLite for full PostgreSQL features (arrays, JSON, window functions, etc.)
|
|
7
|
+
* - Automatic sync between the two layers
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* import { sql, Postgres } from '@dotdo/postgres'
|
|
12
|
+
* export { Postgres }
|
|
13
|
+
*
|
|
14
|
+
* export default {
|
|
15
|
+
* fetch: () => Response.json(await sql`SELECT * FROM posts`)
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { PGlite } from '@dotdo/pglite'
|
|
21
|
+
|
|
22
|
+
// Types for DO SQLite (Cloudflare's built-in SQL storage)
|
|
23
|
+
interface SqlStorage {
|
|
24
|
+
exec(query: string, ...bindings: unknown[]): SqlStorageCursor
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface SqlStorageCursor {
|
|
28
|
+
[Symbol.iterator](): Iterator<Record<string, SqlStorageValue>>
|
|
29
|
+
toArray(): Record<string, SqlStorageValue>[]
|
|
30
|
+
one(): Record<string, SqlStorageValue> | null
|
|
31
|
+
raw<T>(): T[][]
|
|
32
|
+
columnNames: string[]
|
|
33
|
+
rowsRead: number
|
|
34
|
+
rowsWritten: number
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type SqlStorageValue = string | number | null | ArrayBuffer
|
|
38
|
+
|
|
39
|
+
interface DurableObjectState {
|
|
40
|
+
storage: {
|
|
41
|
+
sql: SqlStorage
|
|
42
|
+
get<T>(key: string): Promise<T | undefined>
|
|
43
|
+
put<T>(key: string, value: T): Promise<void>
|
|
44
|
+
delete(key: string): Promise<boolean>
|
|
45
|
+
}
|
|
46
|
+
waitUntil(promise: Promise<unknown>): void
|
|
47
|
+
id: { toString(): string }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface PostgresEnv {
|
|
51
|
+
[key: string]: unknown
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface QueryResult<T = Record<string, unknown>> {
|
|
55
|
+
rows: T[]
|
|
56
|
+
rowCount: number
|
|
57
|
+
fields?: { name: string; dataTypeID: number }[]
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Postgres Durable Object
|
|
63
|
+
*
|
|
64
|
+
* Provides a full PostgreSQL database in each Durable Object instance.
|
|
65
|
+
* Data persists in DO SQLite and is loaded into PGLite on initialization.
|
|
66
|
+
*/
|
|
67
|
+
export class Postgres implements DurableObject {
|
|
68
|
+
private pglite: PGlite | null = null
|
|
69
|
+
private initPromise: Promise<void> | null = null
|
|
70
|
+
private initialized = false
|
|
71
|
+
private sql: SqlStorage
|
|
72
|
+
|
|
73
|
+
constructor(
|
|
74
|
+
private state: DurableObjectState,
|
|
75
|
+
_env: PostgresEnv
|
|
76
|
+
) {
|
|
77
|
+
this.sql = state.storage.sql
|
|
78
|
+
this.initStorage()
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Initialize DO SQLite schema for persistence
|
|
83
|
+
*/
|
|
84
|
+
private initStorage(): void {
|
|
85
|
+
// Core metadata table
|
|
86
|
+
this.sql.exec(`
|
|
87
|
+
CREATE TABLE IF NOT EXISTS __pg_metadata (
|
|
88
|
+
key TEXT PRIMARY KEY,
|
|
89
|
+
value TEXT NOT NULL,
|
|
90
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
91
|
+
)
|
|
92
|
+
`)
|
|
93
|
+
|
|
94
|
+
// Table registry - tracks all tables and their schemas
|
|
95
|
+
this.sql.exec(`
|
|
96
|
+
CREATE TABLE IF NOT EXISTS __pg_tables (
|
|
97
|
+
name TEXT PRIMARY KEY,
|
|
98
|
+
schema TEXT NOT NULL,
|
|
99
|
+
created_at TEXT DEFAULT (datetime('now'))
|
|
100
|
+
)
|
|
101
|
+
`)
|
|
102
|
+
|
|
103
|
+
// Generic data storage - stores all table data as JSON
|
|
104
|
+
this.sql.exec(`
|
|
105
|
+
CREATE TABLE IF NOT EXISTS __pg_data (
|
|
106
|
+
table_name TEXT NOT NULL,
|
|
107
|
+
row_id TEXT NOT NULL,
|
|
108
|
+
data TEXT NOT NULL,
|
|
109
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
110
|
+
updated_at TEXT DEFAULT (datetime('now')),
|
|
111
|
+
PRIMARY KEY (table_name, row_id)
|
|
112
|
+
)
|
|
113
|
+
`)
|
|
114
|
+
|
|
115
|
+
// Create index for faster queries
|
|
116
|
+
this.sql.exec(`
|
|
117
|
+
CREATE INDEX IF NOT EXISTS idx_pg_data_table ON __pg_data(table_name)
|
|
118
|
+
`)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Initialize PGLite and restore data from DO SQLite
|
|
123
|
+
*/
|
|
124
|
+
private async init(): Promise<void> {
|
|
125
|
+
if (this.initialized && this.pglite) {
|
|
126
|
+
return
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (this.initPromise) {
|
|
130
|
+
return this.initPromise
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
this.initPromise = (async () => {
|
|
134
|
+
// Initialize PGLite (in-memory PostgreSQL)
|
|
135
|
+
this.pglite = new PGlite()
|
|
136
|
+
await this.pglite.waitReady
|
|
137
|
+
|
|
138
|
+
// Restore tables and data from DO SQLite
|
|
139
|
+
await this.restoreFromStorage()
|
|
140
|
+
|
|
141
|
+
this.initialized = true
|
|
142
|
+
})()
|
|
143
|
+
|
|
144
|
+
return this.initPromise
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Restore all tables and data from DO SQLite into PGLite
|
|
149
|
+
*/
|
|
150
|
+
private async restoreFromStorage(): Promise<void> {
|
|
151
|
+
if (!this.pglite) return
|
|
152
|
+
|
|
153
|
+
// Get all registered tables
|
|
154
|
+
const tables = [...this.sql.exec('SELECT name, schema FROM __pg_tables')]
|
|
155
|
+
|
|
156
|
+
for (const table of tables) {
|
|
157
|
+
const tableName = table.name as string
|
|
158
|
+
const schema = table.schema as string
|
|
159
|
+
|
|
160
|
+
// Create table in PGLite
|
|
161
|
+
try {
|
|
162
|
+
await this.pglite.exec(schema)
|
|
163
|
+
} catch (e) {
|
|
164
|
+
// Table might already exist, ignore
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Restore data for this table
|
|
168
|
+
const rows = [...this.sql.exec(
|
|
169
|
+
'SELECT row_id, data FROM __pg_data WHERE table_name = ?',
|
|
170
|
+
tableName
|
|
171
|
+
)]
|
|
172
|
+
|
|
173
|
+
for (const row of rows) {
|
|
174
|
+
const data = JSON.parse(row.data as string)
|
|
175
|
+
const columns = Object.keys(data)
|
|
176
|
+
const values = columns.map(c => data[c])
|
|
177
|
+
const placeholders = columns.map((_, i) => `$${i + 1}`).join(', ')
|
|
178
|
+
|
|
179
|
+
try {
|
|
180
|
+
await this.pglite.query(
|
|
181
|
+
`INSERT INTO ${tableName} (${columns.join(', ')}) VALUES (${placeholders}) ON CONFLICT DO NOTHING`,
|
|
182
|
+
values
|
|
183
|
+
)
|
|
184
|
+
} catch (e) {
|
|
185
|
+
// Row might already exist or schema mismatch, continue
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Register a table schema for persistence
|
|
193
|
+
*/
|
|
194
|
+
private registerTable(tableName: string, createStatement: string): void {
|
|
195
|
+
this.sql.exec(
|
|
196
|
+
'INSERT OR REPLACE INTO __pg_tables (name, schema) VALUES (?, ?)',
|
|
197
|
+
tableName,
|
|
198
|
+
createStatement
|
|
199
|
+
)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Persist a row to DO SQLite
|
|
204
|
+
*/
|
|
205
|
+
private persistRow(tableName: string, rowId: string, data: Record<string, unknown>): void {
|
|
206
|
+
this.sql.exec(
|
|
207
|
+
`INSERT OR REPLACE INTO __pg_data (table_name, row_id, data, updated_at)
|
|
208
|
+
VALUES (?, ?, ?, datetime('now'))`,
|
|
209
|
+
tableName,
|
|
210
|
+
rowId,
|
|
211
|
+
JSON.stringify(data)
|
|
212
|
+
)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Delete a row from DO SQLite
|
|
217
|
+
*/
|
|
218
|
+
private deleteRowFromStorage(tableName: string, rowId: string): void {
|
|
219
|
+
this.sql.exec(
|
|
220
|
+
'DELETE FROM __pg_data WHERE table_name = ? AND row_id = ?',
|
|
221
|
+
tableName,
|
|
222
|
+
rowId
|
|
223
|
+
)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Delete all rows from a table in DO SQLite
|
|
228
|
+
*/
|
|
229
|
+
private deleteAllRowsFromStorage(tableName: string): void {
|
|
230
|
+
this.sql.exec(
|
|
231
|
+
'DELETE FROM __pg_data WHERE table_name = ?',
|
|
232
|
+
tableName
|
|
233
|
+
)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Execute a SQL query
|
|
238
|
+
*/
|
|
239
|
+
async query<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<QueryResult<T>> {
|
|
240
|
+
await this.init()
|
|
241
|
+
|
|
242
|
+
if (!this.pglite) {
|
|
243
|
+
throw new Error('PGLite not initialized')
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Detect and handle DDL statements
|
|
247
|
+
const upperSql = sql.trim().toUpperCase()
|
|
248
|
+
|
|
249
|
+
if (upperSql.startsWith('CREATE TABLE')) {
|
|
250
|
+
// Extract table name and register for persistence
|
|
251
|
+
const match = sql.match(/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["']?(\w+)["']?/i)
|
|
252
|
+
if (match) {
|
|
253
|
+
this.registerTable(match[1], sql)
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Execute on PGLite
|
|
258
|
+
const result = await this.pglite.query<T>(sql, params)
|
|
259
|
+
|
|
260
|
+
// Handle INSERT/UPDATE/DELETE - persist changes
|
|
261
|
+
if (upperSql.startsWith('INSERT') || upperSql.startsWith('UPDATE') || upperSql.startsWith('DELETE')) {
|
|
262
|
+
// Extract table name
|
|
263
|
+
let tableName: string | null = null
|
|
264
|
+
|
|
265
|
+
if (upperSql.startsWith('INSERT')) {
|
|
266
|
+
const match = sql.match(/INSERT\s+INTO\s+["']?(\w+)["']?/i)
|
|
267
|
+
tableName = match?.[1] || null
|
|
268
|
+
} else if (upperSql.startsWith('UPDATE')) {
|
|
269
|
+
const match = sql.match(/UPDATE\s+["']?(\w+)["']?/i)
|
|
270
|
+
tableName = match?.[1] || null
|
|
271
|
+
} else if (upperSql.startsWith('DELETE')) {
|
|
272
|
+
const match = sql.match(/DELETE\s+FROM\s+["']?(\w+)["']?/i)
|
|
273
|
+
tableName = match?.[1] || null
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// For RETURNING clauses, persist the returned rows (INSERT/UPDATE)
|
|
277
|
+
if (tableName && (upperSql.startsWith('INSERT') || upperSql.startsWith('UPDATE'))) {
|
|
278
|
+
if (result.rows && result.rows.length > 0) {
|
|
279
|
+
for (const row of result.rows as Record<string, unknown>[]) {
|
|
280
|
+
const rowId = (row.id as string) || (row._id as string) || JSON.stringify(row)
|
|
281
|
+
this.persistRow(tableName, rowId, row)
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// For DELETE with RETURNING, remove the deleted rows
|
|
287
|
+
if (tableName && upperSql.startsWith('DELETE')) {
|
|
288
|
+
if (result.rows && result.rows.length > 0) {
|
|
289
|
+
for (const row of result.rows as Record<string, unknown>[]) {
|
|
290
|
+
const rowId = (row.id as string) || (row._id as string) || JSON.stringify(row)
|
|
291
|
+
this.deleteRowFromStorage(tableName, rowId)
|
|
292
|
+
}
|
|
293
|
+
} else {
|
|
294
|
+
// DELETE without RETURNING - sync entire table
|
|
295
|
+
// This is expensive but ensures consistency
|
|
296
|
+
this.deleteAllRowsFromStorage(tableName)
|
|
297
|
+
// Re-persist all remaining rows
|
|
298
|
+
const allRows = await this.pglite!.query(`SELECT * FROM ${tableName}`)
|
|
299
|
+
for (const row of allRows.rows as Record<string, unknown>[]) {
|
|
300
|
+
const rowId = (row.id as string) || (row._id as string) || JSON.stringify(row)
|
|
301
|
+
this.persistRow(tableName, rowId, row)
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
return {
|
|
308
|
+
rows: result.rows as T[],
|
|
309
|
+
rowCount: result.rows?.length || 0,
|
|
310
|
+
fields: result.fields?.map(f => ({ name: f.name, dataTypeID: f.dataTypeID })),
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Execute SQL without returning results
|
|
316
|
+
*/
|
|
317
|
+
async exec(sql: string): Promise<void> {
|
|
318
|
+
await this.query(sql)
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Handle HTTP requests to the Durable Object
|
|
323
|
+
*/
|
|
324
|
+
async fetch(request: Request): Promise<Response> {
|
|
325
|
+
try {
|
|
326
|
+
await this.init()
|
|
327
|
+
|
|
328
|
+
const url = new URL(request.url)
|
|
329
|
+
|
|
330
|
+
// POST /query - Execute SQL
|
|
331
|
+
if (url.pathname === '/query' && request.method === 'POST') {
|
|
332
|
+
const body = await request.json() as { sql: string; params?: unknown[] }
|
|
333
|
+
|
|
334
|
+
if (!body.sql) {
|
|
335
|
+
return Response.json({ error: 'Missing sql' }, { status: 400 })
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const result = await this.query(body.sql, body.params)
|
|
339
|
+
return Response.json(result)
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// GET /health - Health check
|
|
343
|
+
if (url.pathname === '/health') {
|
|
344
|
+
return Response.json({
|
|
345
|
+
ok: true,
|
|
346
|
+
initialized: this.initialized,
|
|
347
|
+
id: this.state.id.toString(),
|
|
348
|
+
})
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// GET /tables - List tables
|
|
352
|
+
if (url.pathname === '/tables') {
|
|
353
|
+
const tables = [...this.sql.exec('SELECT name FROM __pg_tables')]
|
|
354
|
+
return Response.json({ tables: tables.map(t => t.name) })
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
return Response.json({ error: 'Not found' }, { status: 404 })
|
|
358
|
+
} catch (error) {
|
|
359
|
+
return Response.json(
|
|
360
|
+
{ error: error instanceof Error ? error.message : 'Unknown error' },
|
|
361
|
+
{ status: 500 }
|
|
362
|
+
)
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export default Postgres
|
package/src/do/sql.ts
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQL Tagged Template & Database Client
|
|
3
|
+
*
|
|
4
|
+
* Execute PostgreSQL queries with a simple API.
|
|
5
|
+
* Automatically routes to the Postgres Durable Object using cloudflare:workers env.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { sql, db } from '@dotdo/postgres'
|
|
10
|
+
*
|
|
11
|
+
* // Tagged template (safe from SQL injection)
|
|
12
|
+
* const posts = await sql`SELECT * FROM posts WHERE id = ${id}`
|
|
13
|
+
*
|
|
14
|
+
* // db.query for dynamic queries
|
|
15
|
+
* const result = await db.query('SELECT * FROM posts')
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export interface SqlConfig {
|
|
20
|
+
/** DO binding name (default: 'POSTGRES') */
|
|
21
|
+
binding?: string
|
|
22
|
+
/** DO instance name (default: 'default') */
|
|
23
|
+
instance?: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SqlResult<T = Record<string, unknown>> {
|
|
27
|
+
rows: T[]
|
|
28
|
+
rowCount: number
|
|
29
|
+
fields?: { name: string; dataTypeID: number }[]
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type PostgresNamespace = {
|
|
33
|
+
idFromName(name: string): { toString(): string }
|
|
34
|
+
get(id: { toString(): string }): {
|
|
35
|
+
fetch(request: Request): Promise<Response>
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type DOStub = {
|
|
40
|
+
fetch(request: Request): Promise<Response>
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Build a parameterized SQL query from template literals
|
|
45
|
+
*/
|
|
46
|
+
function buildQuery(strings: TemplateStringsArray, values: unknown[]): { sql: string; params: unknown[] } {
|
|
47
|
+
let sql = ''
|
|
48
|
+
const params: unknown[] = []
|
|
49
|
+
|
|
50
|
+
for (let i = 0; i < strings.length; i++) {
|
|
51
|
+
sql += strings[i]
|
|
52
|
+
if (i < values.length) {
|
|
53
|
+
params.push(values[i])
|
|
54
|
+
sql += `$${params.length}`
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return { sql, params }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Cached env and stub
|
|
62
|
+
let cachedEnv: Record<string, unknown> | null = null
|
|
63
|
+
let cachedStub: DOStub | null = null
|
|
64
|
+
|
|
65
|
+
async function getStub(config: SqlConfig = {}): Promise<DOStub> {
|
|
66
|
+
if (cachedStub) return cachedStub
|
|
67
|
+
|
|
68
|
+
if (!cachedEnv) {
|
|
69
|
+
try {
|
|
70
|
+
const mod = await import('cloudflare:workers')
|
|
71
|
+
cachedEnv = mod.env as Record<string, unknown>
|
|
72
|
+
} catch {
|
|
73
|
+
throw new Error(
|
|
74
|
+
'Could not import cloudflare:workers. ' +
|
|
75
|
+
'Ensure you are running in Cloudflare Workers with nodejs_compat.'
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const binding = config.binding || 'POSTGRES'
|
|
81
|
+
const instance = config.instance || 'default'
|
|
82
|
+
|
|
83
|
+
const namespace = cachedEnv[binding] as PostgresNamespace | undefined
|
|
84
|
+
if (!namespace) {
|
|
85
|
+
throw new Error(`Postgres binding "${binding}" not found. Add it to wrangler.toml.`)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
cachedStub = namespace.get(namespace.idFromName(instance))
|
|
89
|
+
return cachedStub
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function executeQuery<T>(sql: string, params?: unknown[]): Promise<SqlResult<T>> {
|
|
93
|
+
const stub = await getStub()
|
|
94
|
+
|
|
95
|
+
const response = await stub.fetch(new Request('http://do/query', {
|
|
96
|
+
method: 'POST',
|
|
97
|
+
headers: { 'Content-Type': 'application/json' },
|
|
98
|
+
body: JSON.stringify({ sql, params }),
|
|
99
|
+
}))
|
|
100
|
+
|
|
101
|
+
if (!response.ok) {
|
|
102
|
+
const error = await response.json() as { error: string }
|
|
103
|
+
throw new Error(error.error || 'Query failed')
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return response.json() as Promise<SqlResult<T>>
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// =============================================================================
|
|
110
|
+
// sql - Tagged Template API
|
|
111
|
+
// =============================================================================
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* SQL tagged template - safe parameterized queries
|
|
115
|
+
*
|
|
116
|
+
* @example
|
|
117
|
+
* ```typescript
|
|
118
|
+
* import { sql } from '@dotdo/postgres'
|
|
119
|
+
*
|
|
120
|
+
* const posts = await sql`SELECT * FROM posts`
|
|
121
|
+
* const post = await sql`SELECT * FROM posts WHERE id = ${id}`
|
|
122
|
+
* const newPost = await sql`INSERT INTO posts (title) VALUES (${title}) RETURNING *`
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
export async function sql<T = Record<string, unknown>>(
|
|
126
|
+
strings: TemplateStringsArray,
|
|
127
|
+
...values: unknown[]
|
|
128
|
+
): Promise<SqlResult<T>> {
|
|
129
|
+
const { sql: query, params } = buildQuery(strings, values)
|
|
130
|
+
return executeQuery<T>(query, params)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Execute raw SQL (use with caution - ensure input is sanitized)
|
|
135
|
+
*/
|
|
136
|
+
sql.unsafe = async function<T = Record<string, unknown>>(
|
|
137
|
+
query: string,
|
|
138
|
+
params?: unknown[]
|
|
139
|
+
): Promise<SqlResult<T>> {
|
|
140
|
+
return executeQuery<T>(query, params)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// =============================================================================
|
|
144
|
+
// db - Database Client API
|
|
145
|
+
// =============================================================================
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Database client for programmatic access
|
|
149
|
+
*
|
|
150
|
+
* @example
|
|
151
|
+
* ```typescript
|
|
152
|
+
* import { db } from '@dotdo/postgres'
|
|
153
|
+
*
|
|
154
|
+
* const result = await db.query('SELECT * FROM posts')
|
|
155
|
+
* await db.exec('CREATE TABLE posts (id SERIAL PRIMARY KEY, title TEXT)')
|
|
156
|
+
* ```
|
|
157
|
+
*/
|
|
158
|
+
export const db = {
|
|
159
|
+
/**
|
|
160
|
+
* Execute a query and return results
|
|
161
|
+
*/
|
|
162
|
+
async query<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<SqlResult<T>> {
|
|
163
|
+
return executeQuery<T>(sql, params)
|
|
164
|
+
},
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Execute SQL without returning results (DDL, etc.)
|
|
168
|
+
*/
|
|
169
|
+
async exec(sql: string): Promise<void> {
|
|
170
|
+
await executeQuery(sql)
|
|
171
|
+
},
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Get raw access to the DO stub for advanced use cases
|
|
175
|
+
*/
|
|
176
|
+
async getStub(): Promise<DOStub> {
|
|
177
|
+
return getStub()
|
|
178
|
+
},
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// =============================================================================
|
|
182
|
+
// Factory Functions (for custom binding/instance)
|
|
183
|
+
// =============================================================================
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Create a sql function bound to a specific binding/instance
|
|
187
|
+
*/
|
|
188
|
+
export function createSql(env: Record<string, unknown>, config: SqlConfig = {}) {
|
|
189
|
+
const binding = config.binding || 'POSTGRES'
|
|
190
|
+
const instance = config.instance || 'default'
|
|
191
|
+
|
|
192
|
+
const namespace = env[binding] as PostgresNamespace | undefined
|
|
193
|
+
if (!namespace) {
|
|
194
|
+
throw new Error(`Postgres binding "${binding}" not found in env.`)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const stub = namespace.get(namespace.idFromName(instance))
|
|
198
|
+
|
|
199
|
+
async function boundSql<T = Record<string, unknown>>(
|
|
200
|
+
strings: TemplateStringsArray,
|
|
201
|
+
...values: unknown[]
|
|
202
|
+
): Promise<SqlResult<T>> {
|
|
203
|
+
const { sql: query, params } = buildQuery(strings, values)
|
|
204
|
+
|
|
205
|
+
const response = await stub.fetch(new Request('http://do/query', {
|
|
206
|
+
method: 'POST',
|
|
207
|
+
headers: { 'Content-Type': 'application/json' },
|
|
208
|
+
body: JSON.stringify({ sql: query, params }),
|
|
209
|
+
}))
|
|
210
|
+
|
|
211
|
+
if (!response.ok) {
|
|
212
|
+
const error = await response.json() as { error: string }
|
|
213
|
+
throw new Error(error.error || 'Query failed')
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return response.json() as Promise<SqlResult<T>>
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
boundSql.unsafe = async function<T = Record<string, unknown>>(
|
|
220
|
+
query: string,
|
|
221
|
+
params?: unknown[]
|
|
222
|
+
): Promise<SqlResult<T>> {
|
|
223
|
+
const response = await stub.fetch(new Request('http://do/query', {
|
|
224
|
+
method: 'POST',
|
|
225
|
+
headers: { 'Content-Type': 'application/json' },
|
|
226
|
+
body: JSON.stringify({ sql: query, params }),
|
|
227
|
+
}))
|
|
228
|
+
|
|
229
|
+
if (!response.ok) {
|
|
230
|
+
const error = await response.json() as { error: string }
|
|
231
|
+
throw new Error(error.error || 'Query failed')
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return response.json() as Promise<SqlResult<T>>
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
return boundSql
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Create a db client bound to a specific binding/instance
|
|
242
|
+
*/
|
|
243
|
+
export function createDb(env: Record<string, unknown>, config: SqlConfig = {}) {
|
|
244
|
+
const binding = config.binding || 'POSTGRES'
|
|
245
|
+
const instance = config.instance || 'default'
|
|
246
|
+
|
|
247
|
+
const namespace = env[binding] as PostgresNamespace | undefined
|
|
248
|
+
if (!namespace) {
|
|
249
|
+
throw new Error(`Postgres binding "${binding}" not found in env.`)
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const stub = namespace.get(namespace.idFromName(instance))
|
|
253
|
+
|
|
254
|
+
return {
|
|
255
|
+
async query<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<SqlResult<T>> {
|
|
256
|
+
const response = await stub.fetch(new Request('http://do/query', {
|
|
257
|
+
method: 'POST',
|
|
258
|
+
headers: { 'Content-Type': 'application/json' },
|
|
259
|
+
body: JSON.stringify({ sql, params }),
|
|
260
|
+
}))
|
|
261
|
+
|
|
262
|
+
if (!response.ok) {
|
|
263
|
+
const error = await response.json() as { error: string }
|
|
264
|
+
throw new Error(error.error || 'Query failed')
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return response.json() as Promise<SqlResult<T>>
|
|
268
|
+
},
|
|
269
|
+
|
|
270
|
+
async exec(sql: string): Promise<void> {
|
|
271
|
+
await this.query(sql)
|
|
272
|
+
},
|
|
273
|
+
|
|
274
|
+
getStub(): DOStub {
|
|
275
|
+
return stub
|
|
276
|
+
},
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export default sql
|