@remix-run/data-table-postgres 0.0.0 → 0.2.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,501 @@
1
+ import { getTableName, getTablePrimaryKey } from '@remix-run/data-table'
2
+ import type { DataManipulationOperation, Predicate, SqlStatement } from '@remix-run/data-table'
3
+ import {
4
+ collectColumns as collectColumnsHelper,
5
+ normalizeJoinType as normalizeJoinTypeHelper,
6
+ quotePath as quotePathHelper,
7
+ } from '@remix-run/data-table/sql-helpers'
8
+
9
+ type JoinClause = Extract<DataManipulationOperation, { kind: 'select' }>['joins'][number]
10
+ type UpsertOperation = Extract<DataManipulationOperation, { kind: 'upsert' }>
11
+ type OperationTable = Extract<DataManipulationOperation, { kind: 'select' }>['table']
12
+
13
+ type CompileContext = {
14
+ values: unknown[]
15
+ }
16
+
17
+ export function compilePostgresOperation(operation: DataManipulationOperation): SqlStatement {
18
+ if (operation.kind === 'raw') {
19
+ return compileRawOperation(operation.sql)
20
+ }
21
+
22
+ let context: CompileContext = { values: [] }
23
+
24
+ if (operation.kind === 'select') {
25
+ let selection = '*'
26
+
27
+ if (operation.select !== '*') {
28
+ selection = operation.select
29
+ .map((field) => quotePath(field.column) + ' as ' + quoteIdentifier(field.alias))
30
+ .join(', ')
31
+ }
32
+
33
+ let text =
34
+ 'select ' +
35
+ (operation.distinct ? 'distinct ' : '') +
36
+ selection +
37
+ compileFromClause(operation.table, operation.joins, context) +
38
+ compileWhereClause(operation.where, context) +
39
+ compileGroupByClause(operation.groupBy) +
40
+ compileHavingClause(operation.having, context) +
41
+ compileOrderByClause(operation.orderBy) +
42
+ compileLimitClause(operation.limit) +
43
+ compileOffsetClause(operation.offset)
44
+
45
+ return {
46
+ text,
47
+ values: context.values,
48
+ }
49
+ }
50
+
51
+ if (operation.kind === 'count' || operation.kind === 'exists') {
52
+ let inner =
53
+ 'select 1' +
54
+ compileFromClause(operation.table, operation.joins, context) +
55
+ compileWhereClause(operation.where, context) +
56
+ compileGroupByClause(operation.groupBy) +
57
+ compileHavingClause(operation.having, context)
58
+
59
+ return {
60
+ text:
61
+ 'select count(*) as ' +
62
+ quoteIdentifier('count') +
63
+ ' from (' +
64
+ inner +
65
+ ') as ' +
66
+ quoteIdentifier('__dt_count'),
67
+ values: context.values,
68
+ }
69
+ }
70
+
71
+ if (operation.kind === 'insert') {
72
+ return compileInsertOperation(operation.table, operation.values, operation.returning, context)
73
+ }
74
+
75
+ if (operation.kind === 'insertMany') {
76
+ return compileInsertManyOperation(
77
+ operation.table,
78
+ operation.values,
79
+ operation.returning,
80
+ context,
81
+ )
82
+ }
83
+
84
+ if (operation.kind === 'update') {
85
+ let changes = Object.keys(operation.changes)
86
+ let assignments = changes
87
+ .map((column) => quotePath(column) + ' = ' + pushValue(context, operation.changes[column]))
88
+ .join(', ')
89
+
90
+ return {
91
+ text:
92
+ 'update ' +
93
+ quotePath(getTableName(operation.table)) +
94
+ ' set ' +
95
+ assignments +
96
+ compileWhereClause(operation.where, context) +
97
+ compileReturningClause(operation.returning),
98
+ values: context.values,
99
+ }
100
+ }
101
+
102
+ if (operation.kind === 'delete') {
103
+ return {
104
+ text:
105
+ 'delete from ' +
106
+ quotePath(getTableName(operation.table)) +
107
+ compileWhereClause(operation.where, context) +
108
+ compileReturningClause(operation.returning),
109
+ values: context.values,
110
+ }
111
+ }
112
+
113
+ if (operation.kind === 'upsert') {
114
+ return compileUpsertOperation(operation, context)
115
+ }
116
+
117
+ throw new Error('Unsupported operation kind')
118
+ }
119
+
120
+ function compileInsertOperation(
121
+ table: OperationTable,
122
+ values: Record<string, unknown>,
123
+ returning: '*' | string[] | undefined,
124
+ context: CompileContext,
125
+ ): SqlStatement {
126
+ let columns = Object.keys(values)
127
+
128
+ if (columns.length === 0) {
129
+ return {
130
+ text:
131
+ 'insert into ' +
132
+ quotePath(getTableName(table)) +
133
+ ' default values' +
134
+ compileReturningClause(returning),
135
+ values: context.values,
136
+ }
137
+ }
138
+
139
+ let quotedColumns = columns.map((column) => quotePath(column))
140
+ let placeholders = columns.map((column) => pushValue(context, values[column]))
141
+
142
+ return {
143
+ text:
144
+ 'insert into ' +
145
+ quotePath(getTableName(table)) +
146
+ ' (' +
147
+ quotedColumns.join(', ') +
148
+ ') values (' +
149
+ placeholders.join(', ') +
150
+ ')' +
151
+ compileReturningClause(returning),
152
+ values: context.values,
153
+ }
154
+ }
155
+
156
+ function compileInsertManyOperation(
157
+ table: OperationTable,
158
+ rows: Record<string, unknown>[],
159
+ returning: '*' | string[] | undefined,
160
+ context: CompileContext,
161
+ ): SqlStatement {
162
+ if (rows.length === 0) {
163
+ return {
164
+ text: 'select 0 where 1 = 0',
165
+ values: context.values,
166
+ }
167
+ }
168
+
169
+ let columns = collectColumns(rows)
170
+
171
+ if (columns.length === 0) {
172
+ return {
173
+ text:
174
+ 'insert into ' +
175
+ quotePath(getTableName(table)) +
176
+ ' default values' +
177
+ compileReturningClause(returning),
178
+ values: context.values,
179
+ }
180
+ }
181
+
182
+ let quotedColumns = columns.map((column) => quotePath(column))
183
+
184
+ let valueSets = rows.map((row) => {
185
+ let placeholders = columns.map((column) => {
186
+ let value = Object.prototype.hasOwnProperty.call(row, column) ? row[column] : null
187
+ return pushValue(context, value)
188
+ })
189
+
190
+ return '(' + placeholders.join(', ') + ')'
191
+ })
192
+
193
+ return {
194
+ text:
195
+ 'insert into ' +
196
+ quotePath(getTableName(table)) +
197
+ ' (' +
198
+ quotedColumns.join(', ') +
199
+ ') values ' +
200
+ valueSets.join(', ') +
201
+ compileReturningClause(returning),
202
+ values: context.values,
203
+ }
204
+ }
205
+
206
+ function compileUpsertOperation(operation: UpsertOperation, context: CompileContext): SqlStatement {
207
+ let insertColumns = Object.keys(operation.values)
208
+ let conflictTarget = operation.conflictTarget ?? [...getTablePrimaryKey(operation.table)]
209
+
210
+ if (insertColumns.length === 0) {
211
+ throw new Error('upsert requires at least one value')
212
+ }
213
+
214
+ let quotedInsertColumns = insertColumns.map((column) => quotePath(column))
215
+ let insertPlaceholders = insertColumns.map((column) =>
216
+ pushValue(context, operation.values[column]),
217
+ )
218
+
219
+ let updateValues = operation.update ?? operation.values
220
+ let updateColumns = Object.keys(updateValues)
221
+ let onConflictClause = ''
222
+
223
+ if (updateColumns.length === 0) {
224
+ onConflictClause =
225
+ ' on conflict (' +
226
+ conflictTarget.map((column: string) => quotePath(column)).join(', ') +
227
+ ') do nothing'
228
+ } else {
229
+ onConflictClause =
230
+ ' on conflict (' +
231
+ conflictTarget.map((column: string) => quotePath(column)).join(', ') +
232
+ ') do update set ' +
233
+ updateColumns
234
+ .map((column) => quotePath(column) + ' = ' + pushValue(context, updateValues[column]))
235
+ .join(', ')
236
+ }
237
+
238
+ return {
239
+ text:
240
+ 'insert into ' +
241
+ quotePath(getTableName(operation.table)) +
242
+ ' (' +
243
+ quotedInsertColumns.join(', ') +
244
+ ') values (' +
245
+ insertPlaceholders.join(', ') +
246
+ ')' +
247
+ onConflictClause +
248
+ compileReturningClause(operation.returning),
249
+ values: context.values,
250
+ }
251
+ }
252
+
253
+ function compileRawOperation(statement: SqlStatement): SqlStatement {
254
+ if (!statement.text.includes('?')) {
255
+ return {
256
+ text: statement.text,
257
+ values: [...statement.values],
258
+ }
259
+ }
260
+
261
+ let index = 1
262
+ let text = statement.text.replace(/\?/g, function replaceParameter() {
263
+ let placeholder = '$' + String(index)
264
+ index += 1
265
+ return placeholder
266
+ })
267
+
268
+ return {
269
+ text,
270
+ values: [...statement.values],
271
+ }
272
+ }
273
+
274
+ function compileFromClause(
275
+ table: OperationTable,
276
+ joins: JoinClause[],
277
+ context: CompileContext,
278
+ ): string {
279
+ let output = ' from ' + quotePath(getTableName(table))
280
+
281
+ for (let join of joins) {
282
+ output +=
283
+ ' ' +
284
+ normalizeJoinType(join.type) +
285
+ ' join ' +
286
+ quotePath(getTableName(join.table)) +
287
+ ' on ' +
288
+ compilePredicate(join.on, context)
289
+ }
290
+
291
+ return output
292
+ }
293
+
294
+ function compileWhereClause(predicates: Predicate[], context: CompileContext): string {
295
+ if (predicates.length === 0) {
296
+ return ''
297
+ }
298
+
299
+ let where = predicates
300
+ .map((predicate) => '(' + compilePredicate(predicate, context) + ')')
301
+ .join(' and ')
302
+
303
+ return ' where ' + where
304
+ }
305
+
306
+ function compileGroupByClause(columns: string[]): string {
307
+ if (columns.length === 0) {
308
+ return ''
309
+ }
310
+
311
+ return ' group by ' + columns.map((column) => quotePath(column)).join(', ')
312
+ }
313
+
314
+ function compileHavingClause(predicates: Predicate[], context: CompileContext): string {
315
+ if (predicates.length === 0) {
316
+ return ''
317
+ }
318
+
319
+ let having = predicates
320
+ .map((predicate) => '(' + compilePredicate(predicate, context) + ')')
321
+ .join(' and ')
322
+
323
+ return ' having ' + having
324
+ }
325
+
326
+ function compileOrderByClause(orderBy: { column: string; direction: 'asc' | 'desc' }[]): string {
327
+ if (orderBy.length === 0) {
328
+ return ''
329
+ }
330
+
331
+ return (
332
+ ' order by ' +
333
+ orderBy
334
+ .map((clause) => quotePath(clause.column) + ' ' + clause.direction.toUpperCase())
335
+ .join(', ')
336
+ )
337
+ }
338
+
339
+ function compileLimitClause(limit: number | undefined): string {
340
+ if (limit === undefined) {
341
+ return ''
342
+ }
343
+
344
+ return ' limit ' + String(limit)
345
+ }
346
+
347
+ function compileOffsetClause(offset: number | undefined): string {
348
+ if (offset === undefined) {
349
+ return ''
350
+ }
351
+
352
+ return ' offset ' + String(offset)
353
+ }
354
+
355
+ function compileReturningClause(returning: '*' | string[] | undefined): string {
356
+ if (!returning) {
357
+ return ''
358
+ }
359
+
360
+ if (returning === '*') {
361
+ return ' returning *'
362
+ }
363
+
364
+ return ' returning ' + returning.map((column) => quotePath(column)).join(', ')
365
+ }
366
+
367
+ function compilePredicate(predicate: Predicate, context: CompileContext): string {
368
+ if (predicate.type === 'comparison') {
369
+ let column = quotePath(predicate.column)
370
+
371
+ if (predicate.operator === 'eq') {
372
+ if (
373
+ predicate.valueType === 'value' &&
374
+ (predicate.value === null || predicate.value === undefined)
375
+ ) {
376
+ return column + ' is null'
377
+ }
378
+
379
+ let comparisonValue = compileComparisonValue(predicate, context)
380
+ return column + ' = ' + comparisonValue
381
+ }
382
+
383
+ if (predicate.operator === 'ne') {
384
+ if (
385
+ predicate.valueType === 'value' &&
386
+ (predicate.value === null || predicate.value === undefined)
387
+ ) {
388
+ return column + ' is not null'
389
+ }
390
+
391
+ let comparisonValue = compileComparisonValue(predicate, context)
392
+ return column + ' <> ' + comparisonValue
393
+ }
394
+
395
+ if (predicate.operator === 'gt') {
396
+ let comparisonValue = compileComparisonValue(predicate, context)
397
+ return column + ' > ' + comparisonValue
398
+ }
399
+
400
+ if (predicate.operator === 'gte') {
401
+ let comparisonValue = compileComparisonValue(predicate, context)
402
+ return column + ' >= ' + comparisonValue
403
+ }
404
+
405
+ if (predicate.operator === 'lt') {
406
+ let comparisonValue = compileComparisonValue(predicate, context)
407
+ return column + ' < ' + comparisonValue
408
+ }
409
+
410
+ if (predicate.operator === 'lte') {
411
+ let comparisonValue = compileComparisonValue(predicate, context)
412
+ return column + ' <= ' + comparisonValue
413
+ }
414
+
415
+ if (predicate.operator === 'in' || predicate.operator === 'notIn') {
416
+ let values = Array.isArray(predicate.value) ? predicate.value : []
417
+
418
+ if (values.length === 0) {
419
+ return predicate.operator === 'in' ? '1 = 0' : '1 = 1'
420
+ }
421
+
422
+ let placeholders = values.map((value) => pushValue(context, value))
423
+ let keyword = predicate.operator === 'in' ? 'in' : 'not in'
424
+
425
+ return column + ' ' + keyword + ' (' + placeholders.join(', ') + ')'
426
+ }
427
+
428
+ if (predicate.operator === 'like') {
429
+ let comparisonValue = compileComparisonValue(predicate, context)
430
+ return column + ' like ' + comparisonValue
431
+ }
432
+
433
+ if (predicate.operator === 'ilike') {
434
+ let comparisonValue = compileComparisonValue(predicate, context)
435
+ return column + ' ilike ' + comparisonValue
436
+ }
437
+ }
438
+
439
+ if (predicate.type === 'between') {
440
+ return (
441
+ quotePath(predicate.column) +
442
+ ' between ' +
443
+ pushValue(context, predicate.lower) +
444
+ ' and ' +
445
+ pushValue(context, predicate.upper)
446
+ )
447
+ }
448
+
449
+ if (predicate.type === 'null') {
450
+ return (
451
+ quotePath(predicate.column) + (predicate.operator === 'isNull' ? ' is null' : ' is not null')
452
+ )
453
+ }
454
+
455
+ if (predicate.type === 'logical') {
456
+ if (predicate.predicates.length === 0) {
457
+ return predicate.operator === 'and' ? '1 = 1' : '1 = 0'
458
+ }
459
+
460
+ let childOperator = predicate.operator === 'and' ? ' and ' : ' or '
461
+ let childPredicates = predicate.predicates
462
+ .map((child) => '(' + compilePredicate(child, context) + ')')
463
+ .join(childOperator)
464
+
465
+ return childPredicates
466
+ }
467
+
468
+ throw new Error('Unsupported predicate')
469
+ }
470
+
471
+ function compileComparisonValue(
472
+ predicate: Extract<Predicate, { type: 'comparison' }>,
473
+ context: CompileContext,
474
+ ): string {
475
+ if (predicate.valueType === 'column') {
476
+ return quotePath(predicate.value)
477
+ }
478
+
479
+ return pushValue(context, predicate.value)
480
+ }
481
+
482
+ function normalizeJoinType(type: string): string {
483
+ return normalizeJoinTypeHelper(type)
484
+ }
485
+
486
+ function quoteIdentifier(value: string): string {
487
+ return '"' + value.replace(/"/g, '""') + '"'
488
+ }
489
+
490
+ function quotePath(path: string): string {
491
+ return quotePathHelper(path, quoteIdentifier)
492
+ }
493
+
494
+ function pushValue(context: CompileContext, value: unknown): string {
495
+ context.values.push(value)
496
+ return '$' + String(context.values.length)
497
+ }
498
+
499
+ function collectColumns(rows: Record<string, unknown>[]): string[] {
500
+ return collectColumnsHelper(rows)
501
+ }