Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a table exists? [duplicate]

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...

like image 842
Rahul Iyer Avatar asked Dec 23 '22 13:12

Rahul Iyer


1 Answers

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

like image 78
Dr. X Avatar answered Dec 28 '22 10:12

Dr. X