Skip to content

Commit

Permalink
fix: release connection in provider shutdown (#977)
Browse files Browse the repository at this point in the history
  • Loading branch information
Julien-R44 authored Dec 10, 2023
1 parent 2dbff86 commit 8b839d3
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
8 changes: 8 additions & 0 deletions providers/database_provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,12 @@ export default class DatabaseServiceProvider {
await this.registerReplBindings()
await this.registerVineJSRules(db)
}

/**
* Gracefully close connections during shutdown
*/
async shutdown() {
const db = await this.app.container.make('lucid.db')
await db.manager.closeAll()
}
}
84 changes: 84 additions & 0 deletions test/database_provider.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { test } from '@japa/runner'
import { IgnitorFactory } from '@adonisjs/core/factories'

import { defineConfig } from '../src/define_config.js'
import { Database } from '../src/database/main.js'

const BASE_URL = new URL('./tmp/', import.meta.url)
const IMPORTER = (filePath: string) => {
if (filePath.startsWith('./') || filePath.startsWith('../')) {
return import(new URL(filePath, BASE_URL).href)
}
return import(filePath)
}

test.group('Database Provider', () => {
test('register database provider', async ({ assert }) => {
const ignitor = new IgnitorFactory()
.merge({
rcFileContents: {
providers: [() => import('../providers/database_provider.js')],
},
})
.withCoreConfig()
.withCoreProviders()
.merge({
config: {
database: defineConfig({
connection: 'sqlite',
connections: {
sqlite: {
client: 'sqlite',
connection: { filename: new URL('./tmp/database.sqlite', import.meta.url).href },
migrations: { naturalSort: true, paths: ['database/migrations'] },
},
},
}),
},
})
.create(BASE_URL, { importer: IMPORTER })

const app = ignitor.createApp('web')
await app.init()
await app.boot()

assert.instanceOf(await app.container.make('lucid.db'), Database)
})

test('release connection when app is terminating', async ({ assert }) => {
const ignitor = new IgnitorFactory()
.merge({
rcFileContents: {
providers: [() => import('../providers/database_provider.js')],
},
})
.withCoreConfig()
.withCoreProviders()
.merge({
config: {
database: defineConfig({
connection: 'sqlite',
connections: {
sqlite: {
client: 'sqlite',
connection: { filename: new URL('./tmp/database.sqlite', import.meta.url).href },
migrations: { naturalSort: true, paths: ['database/migrations'] },
},
},
}),
},
})
.create(BASE_URL, { importer: IMPORTER })

const app = ignitor.createApp('web')
await app.init()
await app.boot()

const db = await app.container.make('lucid.db')

await db.from('users').catch(() => {})
await app.terminate()

assert.isFalse(db.manager.isConnected('sqlite'))
})
})

0 comments on commit 8b839d3

Please sign in to comment.