I am facing an issue with reusing a query from another function within a WITH clause of a separate query. I experimented with the following code snippet to tackle this challenge.
Here is a snippet to provide a general overview.
const reuseQuery = async (IdType, eventID) => {
try {
const sqlQuery = `SELECT *
FROM TableA TA
WHERE TA.IdType = :IdType AND TA.eventID = :eventID`;
const replacements = {IdType, eventID};
const result = await this.sequelize.query(sqlQuery, {replacements, type: this.sequelize.QueryTypes.SELECT});
return result;
} catch (error) {
console.log(error);
}
};
const useReuseQuery = async () => {
try {
const sqlQuery = `WITH Query1 AS (${await reuseQuery(1, 1)}),
Query2 AS (${await reuseQuery(2, 1)})
Select q1.name AS Captain, q2.name AS Player
FROM Query1 q1, Query2 q2
WHERE q1.partnerID = q2.ID AND q2.partnerID = q1.ID`;
const result = await this.sequelize.query(sqlQuery, {type: this.sequelize.QueryTypes.SELECT});
return result;
} catch(error) {
}
};
Upon testing this approach, I encountered the following error message:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'query' of undefined