2

I am using sequelize with a postgres database behind it and I have sometimes to create Tables in run time. It is generally working, but I would like to know if there is a possibility to check if a table already exists in the database. I know that sequelize is using something like "CREATE TABLE IF NOT EXITS ...", but I would like to know in my code if the table exists or not?

Any ideas? Maybe in the sync method of the define model?

Safari
  • 3,302
  • 9
  • 45
  • 64

1 Answers1

2

A very simple method:

SELECT 1 FROM schema_name.table_name LIMIT 0;

Raises an exception if the table does not exist. schema_name is optional. If omitted, it defaults to the "current" schema, the first schema in the search_path.

Or:

SELECT 'schema_name.table_name'::regclass;

Raises an exception if the name isn't used at all, yet (regular table, sequence, view, materialized view, composite type or TOAST table).

Or you can query the system catalogs or the unified information schema to find out without raising an exception:

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'
    AND    c.relkind = 'r'    -- only tables ...(?)
);

Related answer for more details:

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228