Fix for Postgres connections, seemed to be some issues with out of order, connections not opening in time.

This commit is contained in:
mike12345567 2022-05-20 17:41:27 +01:00
parent 8a815fea2c
commit a23e4efd8c
1 changed files with 34 additions and 14 deletions

View File

@ -136,7 +136,7 @@ module PostgresModule {
: undefined, : undefined,
} }
this.client = new Client(newConfig) this.client = new Client(newConfig)
this.setSchema() this.open = false
} }
getBindingIdentifier(): string { getBindingIdentifier(): string {
@ -147,7 +147,34 @@ module PostgresModule {
return parts.join(" || ") return parts.join(" || ")
} }
async openConnection() {
await this.client.connect()
if (!this.config.schema) {
this.config.schema = "public"
}
this.client.query(`SET search_path TO ${this.config.schema}`)
this.COLUMNS_SQL = `select * from information_schema.columns where table_schema = '${this.config.schema}'`
this.open = true
}
closeConnection() {
const pg = this
return new Promise<void>((resolve, reject) => {
this.client.end((err: any) => {
pg.open = false
if (err) {
reject(err)
} else {
resolve()
}
})
})
}
async internalQuery(query: SqlQuery, close: boolean = true) { async internalQuery(query: SqlQuery, close: boolean = true) {
if (!this.open) {
await this.openConnection()
}
const client = this.client const client = this.client
this.index = 1 this.index = 1
// need to handle a specific issue with json data types in postgres, // need to handle a specific issue with json data types in postgres,
@ -164,21 +191,14 @@ module PostgresModule {
try { try {
return await client.query(query.sql, query.bindings || []) return await client.query(query.sql, query.bindings || [])
} catch (err) { } catch (err) {
await this.client.end() await this.closeConnection()
// @ts-ignore // @ts-ignore
throw new Error(err) throw new Error(err)
} finally { } finally {
if (close) await this.client.end() if (close) {
await this.closeConnection()
} }
} }
async setSchema() {
await this.client.connect()
if (!this.config.schema) {
this.config.schema = "public"
}
this.client.query(`SET search_path TO ${this.config.schema}`)
this.COLUMNS_SQL = `select * from information_schema.columns where table_schema = '${this.config.schema}'`
} }
/** /**
@ -251,7 +271,7 @@ module PostgresModule {
// @ts-ignore // @ts-ignore
throw new Error(err) throw new Error(err)
} finally { } finally {
await this.client.end() await this.closeConnection()
} }
} }
@ -283,7 +303,7 @@ module PostgresModule {
for (let query of input) { for (let query of input) {
responses.push(await this.internalQuery(query, false)) responses.push(await this.internalQuery(query, false))
} }
await this.client.end() await this.closeConnection()
return responses return responses
} else { } else {
const response = await this.internalQuery(input) const response = await this.internalQuery(input)