In db/index.js:
const { Pool } = require('pg'); //node-postgres
const pool = new Pool;
module.exports = {
query: (text, params, callback) => {
return pool.query(text,params,callback);
}
};
In my main.js:
const db = require('./db/index');
db.query('SELECT count(*) from pg_class where relname ="session" and relkind="r"', (err, res) => {
if (err) {
//TODO: What to do if there is an error?
}
console.log(res);
});
The output is:
undefined
How do I check if the table with name "session" exists or not ? How do I know my query even works ?
EDIT: This is not a duplicate of the above questions, because my question has to do with the Node.js javascript code. Not the SQL! I just want to know what to look for in the res object, since it seems to be undefined...
You can check below code;
SELECT EXISTS (
SELECT 1
FROM information_schema.tables
WHERE table_schema = 'schema_name'
AND table_name = 'table_name'
);
or
SELECT EXISTS (
SELECT 1
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'schema_name'
AND c.relname = 'table_name'
);
or
SELECT 'schema_name.table_name'::regclass
or
SELECT to_regclass('schema_name.table_name');
If not exist this query returns null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With