I know three ways to solve this problem.
- With a stored procedure.
- Ignoring the error and continue.
- Working an algorithm in backend
I would resolve with Node in my backend. So I did this.
let exist = false
connection.query(`
SELECT IF(count(*) = 1, 'Exist','Not Exist') AS result
FROM information_schema.columns
WHERE table_schema = 'database'
AND table_name = 'table_name'
AND column_name = '${columnName}';
`,
(error, results, fields) => {
if (error) throw error
else if (results[0].result === 'Exist') {
exist = true
}
}
)
if (!exist) {
connection.query(`
ALTER TABLE ofertas
ADD COLUMN ${columnName} VARCHAR(255);
`,
(error, result, fields) => {
if (error) throw error
}
)
}
This code not work. I belive the problem is async because exist always is true. I use mysql module