Skip to content

Commit

Permalink
refactor: handle pragma foreign_keys
Browse files Browse the repository at this point in the history
  • Loading branch information
Julien-R44 committed Feb 16, 2024
1 parent 918733f commit ca31c69
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
20 changes: 20 additions & 0 deletions src/dialects/base_sqlite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,31 @@ export abstract class BaseSqliteDialect implements DialectContract {
*/
async dropAllTables() {
const tables = await this.getAllTables()

/**
* Check for foreign key pragma and turn it off if enabled
* so that we can drop tables without any issues
*/
const pragma = await this.client.rawQuery('PRAGMA foreign_keys;')
if (pragma[0].foreign_keys === 1) {
await this.client.rawQuery('PRAGMA foreign_keys = OFF;')
}

/**
* Drop all tables
*/
const promises = tables
.filter((table) => !this.config.wipe?.ignoreTables?.includes(table))
.map((table) => this.client.rawQuery(`DROP TABLE ${table};`))

await Promise.all(promises)

/**
* Restore foreign key pragma to it's original value
*/
if (pragma[0].foreign_keys === 1) {
await this.client.rawQuery('PRAGMA foreign_keys = ON;')
}
}

/**
Expand Down
30 changes: 29 additions & 1 deletion test/database/drop_tables.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,6 @@ test.group('Query client | drop tables', (group) => {
table.integer('temp_users_id').unsigned().references('id').inTable('temp_users')
})


await connection.client?.table('temp_users').insert({ id: 1 })
await connection.client?.table('temp_posts').insert({ id: 1, temp_users_id: 1 })

Expand All @@ -133,4 +132,33 @@ test.group('Query client | drop tables', (group) => {

await connection.disconnect()
})

if (['better-sqlite', 'sqlite'].includes(process.env.DB!)) {
test('drop tables when PRAGMA foreign_keys is enabled', async ({ assert }) => {
const connection = new Connection('primary', getConfig(), logger)
connection.connect()

await connection.client!.schema.createTable('temp_posts', (table) => {
table.increments('id')
})

await connection.client!.schema.createTableIfNotExists('temp_users', (table) => {
table.increments('id')
table.integer('temp_posts_id').unsigned().references('id').inTable('temp_posts')
})

await connection.client?.table('temp_posts').insert({ id: 1 })
await connection.client?.table('temp_users').insert({ id: 1, temp_posts_id: 1 })

const client = new QueryClient('dual', connection, createEmitter())

await client.rawQuery('PRAGMA foreign_keys = ON;')
await client.dialect.dropAllTables(['public'])

assert.isFalse(await connection.client!.schema.hasTable('temp_users'))
assert.isFalse(await connection.client!.schema.hasTable('temp_posts'))

await connection.disconnect()
})
}
})

0 comments on commit ca31c69

Please sign in to comment.