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