@remix-run/data-table-postgres 0.4.0 → 0.5.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.
@@ -1,454 +0,0 @@
1
- import type {
2
- DataManipulationRequest,
3
- DataManipulationResult,
4
- DataManipulationOperation,
5
- DatabaseAdapter,
6
- SqlStatement,
7
- TableRef,
8
- TransactionOptions,
9
- TransactionToken,
10
- } from '@remix-run/data-table'
11
- import { getTablePrimaryKey } from '@remix-run/data-table'
12
- import type {
13
- Client as PostgresClient,
14
- Pool as PostgresPool,
15
- PoolClient as PostgresPoolClient,
16
- } from 'pg'
17
-
18
- import { compilePostgresOperation } from './sql-compiler.ts'
19
-
20
- type TransactionState = {
21
- client: PostgresClient | PostgresPoolClient
22
- releaseOnClose: boolean
23
- }
24
-
25
- type PostgresQueryable = PostgresClient | PostgresPool | PostgresPoolClient
26
-
27
- /**
28
- * `DatabaseAdapter` implementation for postgres-compatible clients.
29
- */
30
- export class PostgresDatabaseAdapter implements DatabaseAdapter {
31
- /**
32
- * The SQL dialect identifier reported by this adapter.
33
- */
34
- dialect = 'postgres'
35
-
36
- /**
37
- * Feature flags describing the postgres behaviors supported by this adapter.
38
- */
39
- capabilities
40
-
41
- #client: PostgresQueryable
42
- #transactions = new Map<string, TransactionState>()
43
- #transactionCounter = 0
44
-
45
- constructor(client: PostgresQueryable) {
46
- this.#client = client
47
- this.capabilities = {
48
- returning: true,
49
- savepoints: true,
50
- upsert: true,
51
- transactionalDdl: true,
52
- migrationLock: true,
53
- }
54
- }
55
-
56
- /**
57
- * Compiles a data-manipulation operation to postgres SQL statements.
58
- * @param operation Operation to compile.
59
- * @returns Compiled SQL statements.
60
- */
61
- compileSql(operation: DataManipulationOperation): SqlStatement[] {
62
- let compiled = compilePostgresOperation(operation)
63
- return [{ text: compiled.text, values: compiled.values }]
64
- }
65
-
66
- /**
67
- * Executes a postgres data-manipulation request.
68
- * @param request Request to execute.
69
- * @returns Execution result.
70
- */
71
- async execute(request: DataManipulationRequest): Promise<DataManipulationResult> {
72
- if (request.operation.kind === 'insertMany' && request.operation.values.length === 0) {
73
- return {
74
- affectedRows: 0,
75
- insertId: undefined,
76
- rows: request.operation.returning ? [] : undefined,
77
- }
78
- }
79
-
80
- let statement = compilePostgresOperation(request.operation)
81
- let client = this.#resolveClient(request.transaction)
82
- let result = await client.query(statement.text, statement.values)
83
- let rows = normalizeRows(result.rows)
84
-
85
- if (request.operation.kind === 'count' || request.operation.kind === 'exists') {
86
- rows = normalizeCountRows(rows)
87
- }
88
-
89
- return {
90
- rows,
91
- affectedRows: normalizeAffectedRows(request.operation.kind, result.rowCount, rows),
92
- insertId: normalizeInsertId(request.operation.kind, request.operation, rows),
93
- }
94
- }
95
-
96
- /**
97
- * Executes a multi-statement postgres SQL script.
98
- *
99
- * Postgres natively supports multi-statement scripts when `query` is called
100
- * without a parameter array.
101
- * @param sql SQL script to execute.
102
- * @param transaction Optional transaction token.
103
- * @returns A promise that resolves once execution completes.
104
- */
105
- async executeScript(sql: string, transaction?: TransactionToken): Promise<void> {
106
- let client = this.#resolveClient(transaction)
107
- await client.query(sql)
108
- }
109
-
110
- /**
111
- * Checks whether a table exists in postgres.
112
- * @param table Table reference to inspect.
113
- * @param transaction Optional transaction token.
114
- * @returns `true` when the table exists.
115
- */
116
- async hasTable(table: TableRef, transaction?: TransactionToken): Promise<boolean> {
117
- let relation = toPostgresRelationName(table)
118
- let client = this.#resolveClient(transaction)
119
- let result = await client.query('select to_regclass($1) is not null as "exists"', [relation])
120
- let row = result.rows[0] as Record<string, unknown> | undefined
121
- return toBooleanExists(row?.exists)
122
- }
123
-
124
- /**
125
- * Checks whether a column exists in postgres.
126
- * @param table Table reference to inspect.
127
- * @param column Column name to look up.
128
- * @param transaction Optional transaction token.
129
- * @returns `true` when the column exists.
130
- */
131
- async hasColumn(
132
- table: TableRef,
133
- column: string,
134
- transaction?: TransactionToken,
135
- ): Promise<boolean> {
136
- let relation = toPostgresRelationName(table)
137
- let client = this.#resolveClient(transaction)
138
- let result = await client.query(
139
- 'select exists (select 1 from pg_attribute where attrelid = to_regclass($1) and attname = $2 and attnum > 0 and not attisdropped) as "exists"',
140
- [relation, column],
141
- )
142
- let row = result.rows[0] as Record<string, unknown> | undefined
143
- return toBooleanExists(row?.exists)
144
- }
145
-
146
- /**
147
- * Starts a postgres transaction.
148
- * @param options Transaction options.
149
- * @returns Transaction token.
150
- */
151
- async beginTransaction(options?: TransactionOptions): Promise<TransactionToken> {
152
- let releaseOnClose = false
153
- let transactionClient: PostgresClient | PostgresPoolClient
154
-
155
- if (isPostgresPool(this.#client)) {
156
- transactionClient = await this.#client.connect()
157
- releaseOnClose = true
158
- } else {
159
- transactionClient = this.#client
160
- }
161
-
162
- await transactionClient.query('begin')
163
-
164
- if (options?.isolationLevel || options?.readOnly !== undefined) {
165
- await transactionClient.query(buildSetTransactionStatement(options))
166
- }
167
-
168
- this.#transactionCounter += 1
169
- let token = { id: 'tx_' + String(this.#transactionCounter) }
170
-
171
- this.#transactions.set(token.id, {
172
- client: transactionClient,
173
- releaseOnClose,
174
- })
175
-
176
- return token
177
- }
178
-
179
- /**
180
- * Commits an open postgres transaction.
181
- * @param token Transaction token to commit.
182
- * @returns A promise that resolves when the transaction is committed.
183
- */
184
- async commitTransaction(token: TransactionToken): Promise<void> {
185
- let transaction = this.#transactions.get(token.id)
186
-
187
- if (!transaction) {
188
- throw new Error('Unknown transaction token: ' + token.id)
189
- }
190
-
191
- try {
192
- await transaction.client.query('commit')
193
- } finally {
194
- this.#transactions.delete(token.id)
195
-
196
- if (transaction.releaseOnClose) {
197
- releasePostgresClient(transaction.client)
198
- }
199
- }
200
- }
201
-
202
- /**
203
- * Rolls back an open postgres transaction.
204
- * @param token Transaction token to roll back.
205
- * @returns A promise that resolves when the transaction is rolled back.
206
- */
207
- async rollbackTransaction(token: TransactionToken): Promise<void> {
208
- let transaction = this.#transactions.get(token.id)
209
-
210
- if (!transaction) {
211
- throw new Error('Unknown transaction token: ' + token.id)
212
- }
213
-
214
- try {
215
- await transaction.client.query('rollback')
216
- } finally {
217
- this.#transactions.delete(token.id)
218
-
219
- if (transaction.releaseOnClose) {
220
- releasePostgresClient(transaction.client)
221
- }
222
- }
223
- }
224
-
225
- /**
226
- * Creates a savepoint in an open postgres transaction.
227
- * @param token Transaction token to use.
228
- * @param name Savepoint name.
229
- * @returns A promise that resolves when the savepoint is created.
230
- */
231
- async createSavepoint(token: TransactionToken, name: string): Promise<void> {
232
- let client = this.#transactionClient(token)
233
- await client.query('savepoint ' + quoteIdentifier(name))
234
- }
235
-
236
- /**
237
- * Rolls back to a savepoint in an open postgres transaction.
238
- * @param token Transaction token to use.
239
- * @param name Savepoint name.
240
- * @returns A promise that resolves when the rollback completes.
241
- */
242
- async rollbackToSavepoint(token: TransactionToken, name: string): Promise<void> {
243
- let client = this.#transactionClient(token)
244
- await client.query('rollback to savepoint ' + quoteIdentifier(name))
245
- }
246
-
247
- /**
248
- * Releases a savepoint in an open postgres transaction.
249
- * @param token Transaction token to use.
250
- * @param name Savepoint name.
251
- * @returns A promise that resolves when the savepoint is released.
252
- */
253
- async releaseSavepoint(token: TransactionToken, name: string): Promise<void> {
254
- let client = this.#transactionClient(token)
255
- await client.query('release savepoint ' + quoteIdentifier(name))
256
- }
257
-
258
- /**
259
- * Acquires the postgres migration lock.
260
- * @returns A promise that resolves when the lock is acquired.
261
- */
262
- async acquireMigrationLock(): Promise<void> {
263
- await this.#client.query('select pg_advisory_lock(hashtext($1))', ['data_table_migrations'])
264
- }
265
-
266
- /**
267
- * Releases the postgres migration lock.
268
- * @returns A promise that resolves when the lock is released.
269
- */
270
- async releaseMigrationLock(): Promise<void> {
271
- await this.#client.query('select pg_advisory_unlock(hashtext($1))', ['data_table_migrations'])
272
- }
273
-
274
- #resolveClient(token: TransactionToken | undefined): PostgresQueryable {
275
- if (!token) {
276
- return this.#client
277
- }
278
-
279
- return this.#transactionClient(token)
280
- }
281
-
282
- #transactionClient(token: TransactionToken): PostgresClient | PostgresPoolClient {
283
- let transaction = this.#transactions.get(token.id)
284
-
285
- if (!transaction) {
286
- throw new Error('Unknown transaction token: ' + token.id)
287
- }
288
-
289
- return transaction.client
290
- }
291
- }
292
-
293
- /**
294
- * Creates a postgres `DatabaseAdapter`.
295
- * @param client `pg` pool or pool client.
296
- * @param options Optional adapter capability overrides.
297
- * @returns A configured postgres adapter.
298
- * @example
299
- * ```ts
300
- * import { Pool } from 'pg'
301
- * import { createDatabase } from 'remix/data-table'
302
- * import { createPostgresDatabaseAdapter } from 'remix/data-table/postgres'
303
- *
304
- * let pool = new Pool({ connectionString: process.env.DATABASE_URL })
305
- * let adapter = createPostgresDatabaseAdapter(pool)
306
- * let db = createDatabase(adapter)
307
- * ```
308
- */
309
- export function createPostgresDatabaseAdapter(client: PostgresQueryable): PostgresDatabaseAdapter {
310
- return new PostgresDatabaseAdapter(client)
311
- }
312
-
313
- function isPostgresPool(client: PostgresQueryable): client is PostgresPool {
314
- return 'connect' in client && typeof client.connect === 'function'
315
- }
316
-
317
- function releasePostgresClient(client: PostgresClient | PostgresPoolClient): void {
318
- let release = (client as { release?: () => void }).release
319
- release?.()
320
- }
321
-
322
- function buildSetTransactionStatement(options: TransactionOptions): string {
323
- let parts = ['set transaction']
324
-
325
- if (options.isolationLevel) {
326
- parts.push('isolation level ' + options.isolationLevel)
327
- }
328
-
329
- if (options.readOnly !== undefined) {
330
- parts.push(options.readOnly ? 'read only' : 'read write')
331
- }
332
-
333
- return parts.join(' ')
334
- }
335
-
336
- function normalizeRows(rows: unknown[]): Record<string, unknown>[] {
337
- return rows.map((row) => {
338
- if (typeof row !== 'object' || row === null) {
339
- return {}
340
- }
341
-
342
- return { ...(row as Record<string, unknown>) }
343
- })
344
- }
345
-
346
- function normalizeCountRows(rows: Record<string, unknown>[]): Record<string, unknown>[] {
347
- return rows.map((row) => {
348
- let count = row.count
349
-
350
- if (typeof count === 'string') {
351
- let numeric = Number(count)
352
-
353
- if (!Number.isNaN(numeric)) {
354
- return {
355
- ...row,
356
- count: numeric,
357
- }
358
- }
359
- }
360
-
361
- if (typeof count === 'bigint') {
362
- return {
363
- ...row,
364
- count: Number(count),
365
- }
366
- }
367
-
368
- return row
369
- })
370
- }
371
-
372
- function normalizeAffectedRows(
373
- kind: DataManipulationRequest['operation']['kind'],
374
- rowCount: number | null,
375
- rows: Record<string, unknown>[],
376
- ): number | undefined {
377
- if (kind === 'select' || kind === 'count' || kind === 'exists') {
378
- return undefined
379
- }
380
-
381
- if (rowCount !== null) {
382
- return rowCount
383
- }
384
-
385
- if (kind === 'raw') {
386
- return undefined
387
- }
388
-
389
- return rows.length
390
- }
391
-
392
- function normalizeInsertId(
393
- kind: DataManipulationRequest['operation']['kind'],
394
- operation: DataManipulationRequest['operation'],
395
- rows: Record<string, unknown>[],
396
- ): unknown {
397
- if (!isInsertOperationKind(kind) || !isInsertOperation(operation)) {
398
- return undefined
399
- }
400
-
401
- let primaryKey = getTablePrimaryKey(operation.table)
402
-
403
- if (primaryKey.length !== 1) {
404
- return undefined
405
- }
406
-
407
- let key = primaryKey[0]
408
- let row = rows[rows.length - 1]
409
-
410
- return row ? row[key] : undefined
411
- }
412
-
413
- function quoteIdentifier(value: string): string {
414
- return '"' + value.replace(/"/g, '""') + '"'
415
- }
416
-
417
- function toPostgresRelationName(table: TableRef): string {
418
- if (table.schema) {
419
- return quoteIdentifier(table.schema) + '.' + quoteIdentifier(table.name)
420
- }
421
-
422
- return quoteIdentifier(table.name)
423
- }
424
-
425
- function toBooleanExists(value: unknown): boolean {
426
- if (typeof value === 'boolean') {
427
- return value
428
- }
429
-
430
- if (typeof value === 'number') {
431
- return value > 0
432
- }
433
-
434
- if (typeof value === 'string') {
435
- return value === 't' || value === 'true' || value === '1'
436
- }
437
-
438
- return false
439
- }
440
-
441
- function isInsertOperationKind(kind: DataManipulationRequest['operation']['kind']): boolean {
442
- return kind === 'insert' || kind === 'insertMany' || kind === 'upsert'
443
- }
444
-
445
- function isInsertOperation(
446
- operation: DataManipulationRequest['operation'],
447
- ): operation is Extract<
448
- DataManipulationRequest['operation'],
449
- { kind: 'insert' | 'insertMany' | 'upsert' }
450
- > {
451
- return (
452
- operation.kind === 'insert' || operation.kind === 'insertMany' || operation.kind === 'upsert'
453
- )
454
- }