Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Disconnect db service on shutdown #327

Merged
merged 9 commits into from
Nov 15, 2023
25 changes: 19 additions & 6 deletions db-service/lib/common/DatabaseService.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,16 @@ const cds = require('@sap/cds/lib')
/** @typedef {unknown} DatabaseDriver */

class DatabaseService extends cds.Service {

init() {
cds.on('shutdown', () => this.disconnect())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might need to implement something that disconnects all tenant pools in multitenancy mode. Something like disconnect('*')

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

disconnect(undefined) should match all tenants. Will update the disconnect function to just go over all pools.

return super.init()
}

/**
* Dictionary of connection pools per tenant
*/
pools = { _factory: this.factory }
pools = Object.setPrototypeOf({}, { _factory: this.factory })

/**
* Return a pool factory + options property as expected by
Expand Down Expand Up @@ -111,11 +117,18 @@ class DatabaseService extends cds.Service {
* @param {string} tenant
*/
async disconnect(tenant) {
const pool = this.pools[tenant]
if (!pool) return
await pool.drain()
await pool.clear()
delete this.pools[tenant]
const _disconnect = async tenant => {
const pool = this.pools[tenant]
if (!pool) {
return
}
await pool.drain()
await pool.clear()
delete this.pools[tenant]
}
if (tenant == null)
return Promise.all(Object.keys(this.pools).map(_disconnect))
return _disconnect(tenant)
johannes-vogel marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand Down