@remix-run/data-table-postgres 0.0.0 → 0.1.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.
@@ -0,0 +1,326 @@
1
+ import type {
2
+ AdapterCapabilityOverrides,
3
+ AdapterExecuteRequest,
4
+ AdapterResult,
5
+ DatabaseAdapter,
6
+ TransactionOptions,
7
+ TransactionToken,
8
+ } from '@remix-run/data-table'
9
+ import { getTablePrimaryKey } from '@remix-run/data-table'
10
+
11
+ import { compilePostgresStatement } from './sql-compiler.ts'
12
+
13
+ type Pretty<value> = {
14
+ [key in keyof value]: value[key]
15
+ } & {}
16
+
17
+ /**
18
+ * Result shape returned by postgres client `query()` calls.
19
+ */
20
+ export type PostgresQueryResult = {
21
+ rows: unknown[]
22
+ rowCount: number | null
23
+ }
24
+
25
+ /**
26
+ * Minimal postgres client contract used by this adapter.
27
+ */
28
+ export type PostgresDatabaseClient = {
29
+ query(text: string, values?: unknown[]): Promise<PostgresQueryResult>
30
+ }
31
+
32
+ /**
33
+ * Postgres transaction client with optional connection release support.
34
+ */
35
+ export type PostgresTransactionClient = Pretty<
36
+ PostgresDatabaseClient & {
37
+ release?: () => void
38
+ }
39
+ >
40
+
41
+ /**
42
+ * Postgres pool-like client contract used by this adapter.
43
+ */
44
+ export type PostgresDatabasePool = Pretty<
45
+ PostgresDatabaseClient & {
46
+ connect?: () => Promise<PostgresTransactionClient>
47
+ }
48
+ >
49
+
50
+ /**
51
+ * Postgres adapter configuration.
52
+ */
53
+ export type PostgresDatabaseAdapterOptions = {
54
+ capabilities?: AdapterCapabilityOverrides
55
+ }
56
+
57
+ type TransactionState = {
58
+ client: PostgresTransactionClient
59
+ releaseOnClose: boolean
60
+ }
61
+
62
+ /**
63
+ * `DatabaseAdapter` implementation for postgres-compatible clients.
64
+ */
65
+ export class PostgresDatabaseAdapter implements DatabaseAdapter {
66
+ dialect = 'postgres'
67
+ capabilities
68
+
69
+ #client: PostgresDatabasePool
70
+ #transactions = new Map<string, TransactionState>()
71
+ #transactionCounter = 0
72
+
73
+ constructor(client: PostgresDatabasePool, options?: PostgresDatabaseAdapterOptions) {
74
+ this.#client = client
75
+ this.capabilities = {
76
+ returning: options?.capabilities?.returning ?? true,
77
+ savepoints: options?.capabilities?.savepoints ?? true,
78
+ upsert: options?.capabilities?.upsert ?? true,
79
+ }
80
+ }
81
+
82
+ async execute(request: AdapterExecuteRequest): Promise<AdapterResult> {
83
+ if (request.statement.kind === 'insertMany' && request.statement.values.length === 0) {
84
+ return {
85
+ affectedRows: 0,
86
+ insertId: undefined,
87
+ rows: request.statement.returning ? [] : undefined,
88
+ }
89
+ }
90
+
91
+ let statement = compilePostgresStatement(request.statement)
92
+ let client = this.#resolveClient(request.transaction)
93
+ let result = await client.query(statement.text, statement.values)
94
+ let rows = normalizeRows(result.rows)
95
+
96
+ if (request.statement.kind === 'count' || request.statement.kind === 'exists') {
97
+ rows = normalizeCountRows(rows)
98
+ }
99
+
100
+ return {
101
+ rows,
102
+ affectedRows: normalizeAffectedRows(request.statement.kind, result.rowCount, rows),
103
+ insertId: normalizeInsertId(request.statement.kind, request.statement, rows),
104
+ }
105
+ }
106
+
107
+ async beginTransaction(options?: TransactionOptions): Promise<TransactionToken> {
108
+ let releaseOnClose = false
109
+ let transactionClient: PostgresTransactionClient
110
+
111
+ if (this.#client.connect) {
112
+ transactionClient = await this.#client.connect()
113
+ releaseOnClose = true
114
+ } else {
115
+ transactionClient = this.#client
116
+ }
117
+
118
+ await transactionClient.query('begin')
119
+
120
+ if (options?.isolationLevel || options?.readOnly !== undefined) {
121
+ await transactionClient.query(buildSetTransactionStatement(options))
122
+ }
123
+
124
+ this.#transactionCounter += 1
125
+ let token = { id: 'tx_' + String(this.#transactionCounter) }
126
+
127
+ this.#transactions.set(token.id, {
128
+ client: transactionClient,
129
+ releaseOnClose,
130
+ })
131
+
132
+ return token
133
+ }
134
+
135
+ async commitTransaction(token: TransactionToken): Promise<void> {
136
+ let transaction = this.#transactions.get(token.id)
137
+
138
+ if (!transaction) {
139
+ throw new Error('Unknown transaction token: ' + token.id)
140
+ }
141
+
142
+ try {
143
+ await transaction.client.query('commit')
144
+ } finally {
145
+ this.#transactions.delete(token.id)
146
+
147
+ if (transaction.releaseOnClose) {
148
+ transaction.client.release?.()
149
+ }
150
+ }
151
+ }
152
+
153
+ async rollbackTransaction(token: TransactionToken): Promise<void> {
154
+ let transaction = this.#transactions.get(token.id)
155
+
156
+ if (!transaction) {
157
+ throw new Error('Unknown transaction token: ' + token.id)
158
+ }
159
+
160
+ try {
161
+ await transaction.client.query('rollback')
162
+ } finally {
163
+ this.#transactions.delete(token.id)
164
+
165
+ if (transaction.releaseOnClose) {
166
+ transaction.client.release?.()
167
+ }
168
+ }
169
+ }
170
+
171
+ async createSavepoint(token: TransactionToken, name: string): Promise<void> {
172
+ let client = this.#transactionClient(token)
173
+ await client.query('savepoint ' + quoteIdentifier(name))
174
+ }
175
+
176
+ async rollbackToSavepoint(token: TransactionToken, name: string): Promise<void> {
177
+ let client = this.#transactionClient(token)
178
+ await client.query('rollback to savepoint ' + quoteIdentifier(name))
179
+ }
180
+
181
+ async releaseSavepoint(token: TransactionToken, name: string): Promise<void> {
182
+ let client = this.#transactionClient(token)
183
+ await client.query('release savepoint ' + quoteIdentifier(name))
184
+ }
185
+
186
+ #resolveClient(token: TransactionToken | undefined): PostgresDatabaseClient {
187
+ if (!token) {
188
+ return this.#client
189
+ }
190
+
191
+ return this.#transactionClient(token)
192
+ }
193
+
194
+ #transactionClient(token: TransactionToken): PostgresTransactionClient {
195
+ let transaction = this.#transactions.get(token.id)
196
+
197
+ if (!transaction) {
198
+ throw new Error('Unknown transaction token: ' + token.id)
199
+ }
200
+
201
+ return transaction.client
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Creates a postgres `DatabaseAdapter`.
207
+ * @param client Postgres pool or client.
208
+ * @param options Optional adapter capability overrides.
209
+ * @returns A configured postgres adapter.
210
+ */
211
+ export function createPostgresDatabaseAdapter(
212
+ client: PostgresDatabasePool,
213
+ options?: PostgresDatabaseAdapterOptions,
214
+ ): PostgresDatabaseAdapter {
215
+ return new PostgresDatabaseAdapter(client, options)
216
+ }
217
+
218
+ function buildSetTransactionStatement(options: TransactionOptions): string {
219
+ let parts = ['set transaction']
220
+
221
+ if (options.isolationLevel) {
222
+ parts.push('isolation level ' + options.isolationLevel)
223
+ }
224
+
225
+ if (options.readOnly !== undefined) {
226
+ parts.push(options.readOnly ? 'read only' : 'read write')
227
+ }
228
+
229
+ return parts.join(' ')
230
+ }
231
+
232
+ function normalizeRows(rows: unknown[]): Record<string, unknown>[] {
233
+ return rows.map((row) => {
234
+ if (typeof row !== 'object' || row === null) {
235
+ return {}
236
+ }
237
+
238
+ return { ...(row as Record<string, unknown>) }
239
+ })
240
+ }
241
+
242
+ function normalizeCountRows(rows: Record<string, unknown>[]): Record<string, unknown>[] {
243
+ return rows.map((row) => {
244
+ let count = row.count
245
+
246
+ if (typeof count === 'string') {
247
+ let numeric = Number(count)
248
+
249
+ if (!Number.isNaN(numeric)) {
250
+ return {
251
+ ...row,
252
+ count: numeric,
253
+ }
254
+ }
255
+ }
256
+
257
+ if (typeof count === 'bigint') {
258
+ return {
259
+ ...row,
260
+ count: Number(count),
261
+ }
262
+ }
263
+
264
+ return row
265
+ })
266
+ }
267
+
268
+ function normalizeAffectedRows(
269
+ kind: AdapterExecuteRequest['statement']['kind'],
270
+ rowCount: number | null,
271
+ rows: Record<string, unknown>[],
272
+ ): number | undefined {
273
+ if (kind === 'select' || kind === 'count' || kind === 'exists') {
274
+ return undefined
275
+ }
276
+
277
+ if (rowCount !== null) {
278
+ return rowCount
279
+ }
280
+
281
+ if (kind === 'raw') {
282
+ return undefined
283
+ }
284
+
285
+ return rows.length
286
+ }
287
+
288
+ function normalizeInsertId(
289
+ kind: AdapterExecuteRequest['statement']['kind'],
290
+ statement: AdapterExecuteRequest['statement'],
291
+ rows: Record<string, unknown>[],
292
+ ): unknown {
293
+ if (!isInsertStatementKind(kind) || !isInsertStatement(statement)) {
294
+ return undefined
295
+ }
296
+
297
+ let primaryKey = getTablePrimaryKey(statement.table)
298
+
299
+ if (primaryKey.length !== 1) {
300
+ return undefined
301
+ }
302
+
303
+ let key = primaryKey[0]
304
+ let row = rows[rows.length - 1]
305
+
306
+ return row ? row[key] : undefined
307
+ }
308
+
309
+ function quoteIdentifier(value: string): string {
310
+ return '"' + value.replace(/"/g, '""') + '"'
311
+ }
312
+
313
+ function isInsertStatementKind(kind: AdapterExecuteRequest['statement']['kind']): boolean {
314
+ return kind === 'insert' || kind === 'insertMany' || kind === 'upsert'
315
+ }
316
+
317
+ function isInsertStatement(
318
+ statement: AdapterExecuteRequest['statement'],
319
+ ): statement is Extract<
320
+ AdapterExecuteRequest['statement'],
321
+ { kind: 'insert' | 'insertMany' | 'upsert' }
322
+ > {
323
+ return (
324
+ statement.kind === 'insert' || statement.kind === 'insertMany' || statement.kind === 'upsert'
325
+ )
326
+ }