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