如何检查 table 是否存在?

How do I check if a table exists?

在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);
    }
};

在我的 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);
    });

输出为:

undefined

如何检查名称为 "session" 的 table 是否存在?我怎么知道我的查询有效?

编辑:这不是上述问题的重复,因为我的问题与 Node.js javascript 代码有关。不是SQL!我只想知道在 res 对象中寻找什么,因为它似乎未定义...

您可以查看下面的代码;

SELECT EXISTS (
   SELECT 1
   FROM   information_schema.tables 
   WHERE  table_schema = 'schema_name'
   AND    table_name = 'table_name'
   );

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'
   );

SELECT 'schema_name.table_name'::regclass

SELECT to_regclass('schema_name.table_name');

如果不存在此查询returns null