@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,541 @@
1
+ import { getTableName, getTablePrimaryKey } from '@remix-run/data-table'
2
+ import type { AdapterStatement, Predicate, SqlStatement } from '@remix-run/data-table'
3
+
4
+ type JoinClause = Extract<AdapterStatement, { kind: 'select' }>['joins'][number]
5
+ type UpsertStatement = Extract<AdapterStatement, { kind: 'upsert' }>
6
+ type StatementTable = Extract<AdapterStatement, { kind: 'select' }>['table']
7
+
8
+ type CompiledSql = {
9
+ text: string
10
+ values: unknown[]
11
+ }
12
+
13
+ type CompileContext = {
14
+ values: unknown[]
15
+ }
16
+
17
+ export function compilePostgresStatement(statement: AdapterStatement): CompiledSql {
18
+ if (statement.kind === 'raw') {
19
+ return compileRawStatement(statement.sql)
20
+ }
21
+
22
+ let context: CompileContext = { values: [] }
23
+
24
+ if (statement.kind === 'select') {
25
+ let selection = '*'
26
+
27
+ if (statement.select !== '*') {
28
+ selection = statement.select
29
+ .map((field) => quotePath(field.column) + ' as ' + quoteIdentifier(field.alias))
30
+ .join(', ')
31
+ }
32
+
33
+ let text =
34
+ 'select ' +
35
+ (statement.distinct ? 'distinct ' : '') +
36
+ selection +
37
+ compileFromClause(statement.table, statement.joins, context) +
38
+ compileWhereClause(statement.where, context) +
39
+ compileGroupByClause(statement.groupBy) +
40
+ compileHavingClause(statement.having, context) +
41
+ compileOrderByClause(statement.orderBy) +
42
+ compileLimitClause(statement.limit) +
43
+ compileOffsetClause(statement.offset)
44
+
45
+ return {
46
+ text,
47
+ values: context.values,
48
+ }
49
+ }
50
+
51
+ if (statement.kind === 'count' || statement.kind === 'exists') {
52
+ let inner =
53
+ 'select 1' +
54
+ compileFromClause(statement.table, statement.joins, context) +
55
+ compileWhereClause(statement.where, context) +
56
+ compileGroupByClause(statement.groupBy) +
57
+ compileHavingClause(statement.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 (statement.kind === 'insert') {
72
+ return compileInsertStatement(statement.table, statement.values, statement.returning, context)
73
+ }
74
+
75
+ if (statement.kind === 'insertMany') {
76
+ return compileInsertManyStatement(
77
+ statement.table,
78
+ statement.values,
79
+ statement.returning,
80
+ context,
81
+ )
82
+ }
83
+
84
+ if (statement.kind === 'update') {
85
+ let changes = Object.keys(statement.changes)
86
+ let assignments = changes
87
+ .map((column) => quotePath(column) + ' = ' + pushValue(context, statement.changes[column]))
88
+ .join(', ')
89
+
90
+ return {
91
+ text:
92
+ 'update ' +
93
+ quotePath(getTableName(statement.table)) +
94
+ ' set ' +
95
+ assignments +
96
+ compileWhereClause(statement.where, context) +
97
+ compileReturningClause(statement.returning),
98
+ values: context.values,
99
+ }
100
+ }
101
+
102
+ if (statement.kind === 'delete') {
103
+ return {
104
+ text:
105
+ 'delete from ' +
106
+ quotePath(getTableName(statement.table)) +
107
+ compileWhereClause(statement.where, context) +
108
+ compileReturningClause(statement.returning),
109
+ values: context.values,
110
+ }
111
+ }
112
+
113
+ if (statement.kind === 'upsert') {
114
+ return compileUpsertStatement(statement, context)
115
+ }
116
+
117
+ throw new Error('Unsupported statement kind')
118
+ }
119
+
120
+ function compileInsertStatement(
121
+ table: StatementTable,
122
+ values: Record<string, unknown>,
123
+ returning: '*' | string[] | undefined,
124
+ context: CompileContext,
125
+ ): CompiledSql {
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 compileInsertManyStatement(
157
+ table: StatementTable,
158
+ rows: Record<string, unknown>[],
159
+ returning: '*' | string[] | undefined,
160
+ context: CompileContext,
161
+ ): CompiledSql {
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 compileUpsertStatement(statement: UpsertStatement, context: CompileContext): CompiledSql {
207
+ let insertColumns = Object.keys(statement.values)
208
+ let conflictTarget = statement.conflictTarget ?? [...getTablePrimaryKey(statement.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, statement.values[column]),
217
+ )
218
+
219
+ let updateValues = statement.update ?? statement.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(statement.table)) +
242
+ ' (' +
243
+ quotedInsertColumns.join(', ') +
244
+ ') values (' +
245
+ insertPlaceholders.join(', ') +
246
+ ')' +
247
+ onConflictClause +
248
+ compileReturningClause(statement.returning),
249
+ values: context.values,
250
+ }
251
+ }
252
+
253
+ function compileRawStatement(statement: SqlStatement): CompiledSql {
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: StatementTable,
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
+ if (type === 'left') {
484
+ return 'left'
485
+ }
486
+
487
+ if (type === 'right') {
488
+ return 'right'
489
+ }
490
+
491
+ return 'inner'
492
+ }
493
+
494
+ function quoteIdentifier(value: string): string {
495
+ return '"' + value.replace(/"/g, '""') + '"'
496
+ }
497
+
498
+ function quotePath(path: string): string {
499
+ if (path === '*') {
500
+ return '*'
501
+ }
502
+
503
+ let segments = path.split('.')
504
+
505
+ return segments
506
+ .map((segment) => {
507
+ if (segment === '*') {
508
+ return '*'
509
+ }
510
+
511
+ return quoteIdentifier(segment)
512
+ })
513
+ .join('.')
514
+ }
515
+
516
+ function pushValue(context: CompileContext, value: unknown): string {
517
+ context.values.push(value)
518
+ return '$' + String(context.values.length)
519
+ }
520
+
521
+ function collectColumns(rows: Record<string, unknown>[]): string[] {
522
+ let columns: string[] = []
523
+ let seen = new Set<string>()
524
+
525
+ for (let row of rows) {
526
+ for (let key in row) {
527
+ if (!Object.prototype.hasOwnProperty.call(row, key)) {
528
+ continue
529
+ }
530
+
531
+ if (seen.has(key)) {
532
+ continue
533
+ }
534
+
535
+ seen.add(key)
536
+ columns.push(key)
537
+ }
538
+ }
539
+
540
+ return columns
541
+ }