I am using MySQL, ExpressJS, and Sequelize to build a function that returns a list of columns from a given SQL query. The function should work even if the query returns no rows.
Here is the current implementation of my function:
async getColumnsFromQuery ( query ) {
try {
let queryResponse = await db.sequelize.query ( query, {
type: db.sequelize.QueryTypes.SELECT
});
let columns = [];
if ( queryResponse.length > 0 ) {
columns = Object.keys( queryResponse[ 0 ] );
}
return columns;
} catch ( err ) {
throw err;
}
}
This function works perfectly when the query returns rows, but if the query returns no rows, the columns
array is empty. I need to ensure that the function still returns the correct column names even when no data is returned.
I tried Using INFORMATION_SCHEMA
, SHOW COLUMNS
or DESCRIBE
but they are only for tables not quries.
Owais Farooq is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
6