@platformatic/sql-mapper 1.17.0 → 1.18.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.
Files changed (2) hide show
  1. package/mapper.js +55 -0
  2. package/package.json +2 -2
package/mapper.js CHANGED
@@ -275,9 +275,64 @@ async function sqlMapper (app, opts) {
275
275
  })
276
276
  }
277
277
 
278
+ async function dropTable (db, sql, table) {
279
+ try {
280
+ if (db.isSQLite) {
281
+ await db.query(sql`DROP TABLE ${sql(table)};`)
282
+ } else {
283
+ await db.query(sql`DROP TABLE ${sql(table)} CASCADE;`)
284
+ }
285
+ return table
286
+ } catch (err) {
287
+ // ignore, it will be dropped on the next roundon the next roundon the next roundon the next round
288
+ }
289
+ }
290
+
291
+ async function dropAllTables (db, sql, schemas) {
292
+ let queries
293
+ /* istanbul ignore next */
294
+ if (db.isPg) {
295
+ queries = queriesFactory.pg
296
+ } else if (db.isMySql) {
297
+ queries = queriesFactory.mysql
298
+ } else if (db.isMariaDB) {
299
+ queries = queriesFactory.mariadb
300
+ } else if (db.isSQLite) {
301
+ queries = queriesFactory.sqlite
302
+ }
303
+
304
+ const tables = new Set((await queries.listTables(db, sql, schemas)).map((t) => {
305
+ /* istanbul ignore next */
306
+ if (t.schema) {
307
+ return `${t.schema}.${t.table}`
308
+ }
309
+ return t.table
310
+ }))
311
+ let count = 0
312
+
313
+ while (tables.size > 0) {
314
+ if (count++ > 100) {
315
+ throw new Error('too many iterations, unable to clear the db')
316
+ }
317
+
318
+ const deletes = []
319
+ for (const table of tables) {
320
+ deletes.push(dropTable(db, sql, table))
321
+ }
322
+
323
+ const res = await Promise.all(deletes)
324
+ for (const table of res) {
325
+ if (table) {
326
+ tables.delete(table)
327
+ }
328
+ }
329
+ }
330
+ }
331
+
278
332
  module.exports = fp(sqlMapper)
279
333
  module.exports.connect = connect
280
334
  module.exports.createConnectionPool = createConnectionPool
281
335
  module.exports.plugin = module.exports
282
336
  module.exports.utils = require('./lib/utils')
283
337
  module.exports.errors = errors
338
+ module.exports.dropAllTables = dropAllTables
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@platformatic/sql-mapper",
3
- "version": "1.17.0",
3
+ "version": "1.18.0",
4
4
  "description": "A data mapper utility for SQL databases",
5
5
  "main": "mapper.js",
6
6
  "types": "mapper.d.ts",
@@ -33,7 +33,7 @@
33
33
  "camelcase": "^6.3.0",
34
34
  "fastify-plugin": "^4.5.1",
35
35
  "inflected": "^2.1.0",
36
- "@platformatic/utils": "1.17.0"
36
+ "@platformatic/utils": "1.18.0"
37
37
  },
38
38
  "tsd": {
39
39
  "directory": "test/types"