I have DB
class which has public static query
method. There can be multiple connection pools saved in _coonection_pools
so I am creating a random number then get the pool and execute the query . this is the code
static async query(queryInfo: Query): Promise<any> {
const query = `select * from ${queryInfo.name} ${queryInfo.arguments} as info;`;
try {
return this._queryReplicaDB(queryInfo);
} catch (err) {
console.log("err", err);
throw err;
}
}
static async _queryReplicaDB(query: Query): Promise<any> {
const randomNumber = Math.floor(Math.random() * this._connection_pools.length);
// get the pool using random number
const pool = this._connection_pools[randomNumber];
try {
const response = await pool.query(query);
return response.rows[0].info;
} catch {
let response;
// if replica db fails then try with other pools
for (let i = 0; i < this._connection_pools.length; i++) {
// iterrate through every pool
const pool = this._connection_pools[i];
try {
response = await pool.query(query);
break;
} catch {
console.log("Error in Pool index: ", i);
}
}
return response.rows[0].info;
}
}
This is return empty rows
in the response array
but if instead of calling nested _queryReplicaDB
object this works fine
static async query(queryInfo: Query): Promise<any> {
const query = `select * from ${queryInfo.name} ${queryInfo.arguments} as info;`;
try {
const response = await this._connection_pools[0].query(query);
return response.rows[0].info;
} catch (err) {
console.log("err", err);
throw err;
}
}
i have tried this._connection_pools[0]
in the _queryReplicaDB
as well but this does not work.
I tried random number thing directlty in the query
method in this method this works.
what can be the issue?
In my case code was correct, its just I was passing the wrong object type. Instead of passing Query object
static async _queryReplicaDB(query: Query): Promise<any> {
this function should accept string type as the query
static async _queryReplicaDB(query: string): Promise<any> {