@remix-run/data-table-mysql 0.4.0 → 0.5.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.
@@ -1,344 +0,0 @@
1
- import { getTablePrimaryKey } from '@remix-run/data-table';
2
- import { compileMysqlOperation } from "./sql-compiler.js";
3
- /**
4
- * `DatabaseAdapter` implementation for mysql-compatible clients.
5
- */
6
- export class MysqlDatabaseAdapter {
7
- /**
8
- * The SQL dialect identifier reported by this adapter.
9
- */
10
- dialect = 'mysql';
11
- /**
12
- * Feature flags describing the mysql behaviors supported by this adapter.
13
- */
14
- capabilities;
15
- #client;
16
- #transactions = new Map();
17
- #transactionCounter = 0;
18
- constructor(client) {
19
- this.#client = client;
20
- this.capabilities = {
21
- returning: false,
22
- savepoints: true,
23
- upsert: true,
24
- transactionalDdl: false,
25
- migrationLock: true,
26
- };
27
- }
28
- /**
29
- * Compiles a data-manipulation operation to mysql SQL statements.
30
- * @param operation Operation to compile.
31
- * @returns Compiled SQL statements.
32
- */
33
- compileSql(operation) {
34
- let compiled = compileMysqlOperation(operation);
35
- return [{ text: compiled.text, values: compiled.values }];
36
- }
37
- /**
38
- * Executes a mysql data-manipulation request.
39
- * @param request Request to execute.
40
- * @returns Execution result.
41
- */
42
- async execute(request) {
43
- if (request.operation.kind === 'insertMany' && request.operation.values.length === 0) {
44
- return {
45
- affectedRows: 0,
46
- insertId: undefined,
47
- rows: request.operation.returning ? [] : undefined,
48
- };
49
- }
50
- let statements = this.compileSql(request.operation);
51
- let statement = statements[0];
52
- let client = this.#resolveClient(request.transaction);
53
- let [result] = await client.query(statement.text, statement.values);
54
- if (isRowsResult(result)) {
55
- let rows = normalizeRows(result);
56
- if (request.operation.kind === 'count' || request.operation.kind === 'exists') {
57
- rows = normalizeCountRows(rows);
58
- }
59
- return { rows };
60
- }
61
- let header = normalizeHeader(result);
62
- return {
63
- affectedRows: header.affectedRows,
64
- insertId: normalizeInsertId(request.operation.kind, request.operation, header),
65
- };
66
- }
67
- /**
68
- * Executes a multi-statement mysql SQL script.
69
- *
70
- * mysql2 only accepts multi-statement scripts when the underlying connection
71
- * was created with `multipleStatements: true`.
72
- * @param sql SQL script to execute.
73
- * @param transaction Optional transaction token.
74
- * @returns A promise that resolves once execution completes.
75
- */
76
- async executeScript(sql, transaction) {
77
- let client = this.#resolveClient(transaction);
78
- await client.query(sql);
79
- }
80
- /**
81
- * Checks whether a table exists in mysql.
82
- * @param table Table reference to inspect.
83
- * @param transaction Optional transaction token.
84
- * @returns `true` when the table exists.
85
- */
86
- async hasTable(table, transaction) {
87
- let schema = table.schema;
88
- let sql = schema
89
- ? 'select exists(select 1 from information_schema.tables where table_schema = ? and table_name = ?) as `exists`'
90
- : 'select exists(select 1 from information_schema.tables where table_schema = database() and table_name = ?) as `exists`';
91
- let values = schema ? [schema, table.name] : [table.name];
92
- let client = this.#resolveClient(transaction);
93
- let [result] = await client.query(sql, values);
94
- if (!isRowsResult(result)) {
95
- return false;
96
- }
97
- return toBooleanExists(result[0]?.exists);
98
- }
99
- /**
100
- * Checks whether a column exists in mysql.
101
- * @param table Table reference to inspect.
102
- * @param column Column name to look up.
103
- * @param transaction Optional transaction token.
104
- * @returns `true` when the column exists.
105
- */
106
- async hasColumn(table, column, transaction) {
107
- let schema = table.schema;
108
- let sql = schema
109
- ? 'select exists(select 1 from information_schema.columns where table_schema = ? and table_name = ? and column_name = ?) as `exists`'
110
- : 'select exists(select 1 from information_schema.columns where table_schema = database() and table_name = ? and column_name = ?) as `exists`';
111
- let values = schema ? [schema, table.name, column] : [table.name, column];
112
- let client = this.#resolveClient(transaction);
113
- let [result] = await client.query(sql, values);
114
- if (!isRowsResult(result)) {
115
- return false;
116
- }
117
- return toBooleanExists(result[0]?.exists);
118
- }
119
- /**
120
- * Starts a mysql transaction.
121
- * @param options Transaction options.
122
- * @returns Transaction token.
123
- */
124
- async beginTransaction(options) {
125
- let releaseOnClose = false;
126
- let connection;
127
- if (isMysqlPool(this.#client)) {
128
- connection = await this.#client.getConnection();
129
- releaseOnClose = true;
130
- }
131
- else {
132
- connection = this.#client;
133
- }
134
- if (options?.isolationLevel) {
135
- await connection.query('set transaction isolation level ' + options.isolationLevel);
136
- }
137
- if (options?.readOnly !== undefined) {
138
- await connection.query(options.readOnly ? 'set transaction read only' : 'set transaction read write');
139
- }
140
- await connection.beginTransaction();
141
- this.#transactionCounter += 1;
142
- let token = { id: 'tx_' + String(this.#transactionCounter) };
143
- this.#transactions.set(token.id, {
144
- connection,
145
- releaseOnClose,
146
- });
147
- return token;
148
- }
149
- /**
150
- * Commits an open mysql transaction.
151
- * @param token Transaction token to commit.
152
- * @returns A promise that resolves when the transaction is committed.
153
- */
154
- async commitTransaction(token) {
155
- let transaction = this.#transactions.get(token.id);
156
- if (!transaction) {
157
- throw new Error('Unknown transaction token: ' + token.id);
158
- }
159
- try {
160
- await transaction.connection.commit();
161
- }
162
- finally {
163
- this.#transactions.delete(token.id);
164
- if (transaction.releaseOnClose && isMysqlPoolConnection(transaction.connection)) {
165
- transaction.connection.release();
166
- }
167
- }
168
- }
169
- /**
170
- * Rolls back an open mysql transaction.
171
- * @param token Transaction token to roll back.
172
- * @returns A promise that resolves when the transaction is rolled back.
173
- */
174
- async rollbackTransaction(token) {
175
- let transaction = this.#transactions.get(token.id);
176
- if (!transaction) {
177
- throw new Error('Unknown transaction token: ' + token.id);
178
- }
179
- try {
180
- await transaction.connection.rollback();
181
- }
182
- finally {
183
- this.#transactions.delete(token.id);
184
- if (transaction.releaseOnClose && isMysqlPoolConnection(transaction.connection)) {
185
- transaction.connection.release();
186
- }
187
- }
188
- }
189
- /**
190
- * Creates a savepoint in an open mysql transaction.
191
- * @param token Transaction token to use.
192
- * @param name Savepoint name.
193
- * @returns A promise that resolves when the savepoint is created.
194
- */
195
- async createSavepoint(token, name) {
196
- let connection = this.#transactionConnection(token);
197
- await connection.query('savepoint ' + quoteIdentifier(name));
198
- }
199
- /**
200
- * Rolls back to a savepoint in an open mysql transaction.
201
- * @param token Transaction token to use.
202
- * @param name Savepoint name.
203
- * @returns A promise that resolves when the rollback completes.
204
- */
205
- async rollbackToSavepoint(token, name) {
206
- let connection = this.#transactionConnection(token);
207
- await connection.query('rollback to savepoint ' + quoteIdentifier(name));
208
- }
209
- /**
210
- * Releases a savepoint in an open mysql transaction.
211
- * @param token Transaction token to use.
212
- * @param name Savepoint name.
213
- * @returns A promise that resolves when the savepoint is released.
214
- */
215
- async releaseSavepoint(token, name) {
216
- let connection = this.#transactionConnection(token);
217
- await connection.query('release savepoint ' + quoteIdentifier(name));
218
- }
219
- /**
220
- * Acquires the mysql migration lock.
221
- * @returns A promise that resolves when the lock is acquired.
222
- */
223
- async acquireMigrationLock() {
224
- await this.#client.query('select get_lock(?, 60)', ['data_table_migrations']);
225
- }
226
- /**
227
- * Releases the mysql migration lock.
228
- * @returns A promise that resolves when the lock is released.
229
- */
230
- async releaseMigrationLock() {
231
- await this.#client.query('select release_lock(?)', ['data_table_migrations']);
232
- }
233
- #resolveClient(token) {
234
- if (!token) {
235
- return this.#client;
236
- }
237
- return this.#transactionConnection(token);
238
- }
239
- #transactionConnection(token) {
240
- let transaction = this.#transactions.get(token.id);
241
- if (!transaction) {
242
- throw new Error('Unknown transaction token: ' + token.id);
243
- }
244
- return transaction.connection;
245
- }
246
- }
247
- /**
248
- * Creates a mysql `DatabaseAdapter`.
249
- * @param client Mysql pool or connection.
250
- * @param options Optional adapter capability overrides.
251
- * @returns A configured mysql adapter.
252
- * @example
253
- * ```ts
254
- * import { createPool } from 'mysql2/promise'
255
- * import { createDatabase } from 'remix/data-table'
256
- * import { createMysqlDatabaseAdapter } from 'remix/data-table/mysql'
257
- *
258
- * let pool = createPool({ uri: process.env.DATABASE_URL })
259
- * let adapter = createMysqlDatabaseAdapter(pool)
260
- * let db = createDatabase(adapter)
261
- * ```
262
- */
263
- export function createMysqlDatabaseAdapter(client) {
264
- return new MysqlDatabaseAdapter(client);
265
- }
266
- function isMysqlPool(client) {
267
- return 'getConnection' in client && typeof client.getConnection === 'function';
268
- }
269
- function isMysqlPoolConnection(connection) {
270
- return 'release' in connection && typeof connection.release === 'function';
271
- }
272
- function isRowsResult(result) {
273
- return Array.isArray(result) && (result.length === 0 || !Array.isArray(result[0]));
274
- }
275
- function toBooleanExists(value) {
276
- if (typeof value === 'boolean') {
277
- return value;
278
- }
279
- if (typeof value === 'number') {
280
- return value > 0;
281
- }
282
- if (typeof value === 'bigint') {
283
- return value > 0n;
284
- }
285
- if (typeof value === 'string') {
286
- return value === '1' || value.toLowerCase() === 'true';
287
- }
288
- return false;
289
- }
290
- function normalizeRows(rows) {
291
- return rows.map((row) => ({ ...row }));
292
- }
293
- function normalizeHeader(result) {
294
- if (typeof result === 'object' && result !== null) {
295
- let header = result;
296
- return {
297
- affectedRows: typeof header.affectedRows === 'number' ? header.affectedRows : 0,
298
- insertId: header.insertId,
299
- };
300
- }
301
- return {
302
- affectedRows: 0,
303
- insertId: undefined,
304
- };
305
- }
306
- function normalizeCountRows(rows) {
307
- return rows.map((row) => {
308
- let count = row.count;
309
- if (typeof count === 'string') {
310
- let numeric = Number(count);
311
- if (!Number.isNaN(numeric)) {
312
- return {
313
- ...row,
314
- count: numeric,
315
- };
316
- }
317
- }
318
- if (typeof count === 'bigint') {
319
- return {
320
- ...row,
321
- count: Number(count),
322
- };
323
- }
324
- return row;
325
- });
326
- }
327
- function normalizeInsertId(kind, operation, header) {
328
- if (!isInsertOperationKind(kind) || !isInsertOperation(operation)) {
329
- return undefined;
330
- }
331
- if (getTablePrimaryKey(operation.table).length !== 1) {
332
- return undefined;
333
- }
334
- return header.insertId;
335
- }
336
- function quoteIdentifier(value) {
337
- return '`' + value.replace(/`/g, '``') + '`';
338
- }
339
- function isInsertOperationKind(kind) {
340
- return kind === 'insert' || kind === 'insertMany' || kind === 'upsert';
341
- }
342
- function isInsertOperation(operation) {
343
- return (operation.kind === 'insert' || operation.kind === 'insertMany' || operation.kind === 'upsert');
344
- }