Does anyone know how to find the OID of a table in Postgres 9.1? I am writing an update script that needs to test for the existence of a column in a table before it tries to create the column. This is to prevent run of the script after the first from erroring out.
相关问题
- Django distinct is not working
- PostgreSQL: left outer join syntax
- Connecting Python to a Heroku PostgreSQL DB?
- PostgreSQL - Deleting data that are older than an
- Does PLV8 support making http calls to other serve
相关文章
- postgresql 关于使用between and 中是字符串的问题
- postgresql 月份差计算问题
- Using boolean expression in order by clause
- Table valued Parameter Equivalent in Postgresql
- in redshift postgresql can I skip columns with the
- Oracle equivalent of PostgreSQL INSERT…RETURNING *
- How to install tablefunc in postgres on Mac OS X?
- PostgreSQL field data type for IPv4 addresses
The postgres catalog table
pg_class
is what you should look at. There should be one row per table, with the table name in the columnrelname
, and the oid in the hidden columnoid
.The catalog tables are in the
postgres
database, so make sure to connect to that, rather than your application database.You may also be interested in the
pg_attribute
catalog table, which includes one row per table column.See: http://www.postgresql.org/docs/current/static/catalog-pg-class.html and http://www.postgresql.org/docs/current/static/catalog-pg-attribute.html
Just to complete the possibilities I'd like to add that there exists a syntax for dropping columns in order to no error out:
ALTER TABLE mytbl DROP COLUMN IF EXISTS mycol
See http://www.postgresql.org/docs/9.0/static/sql-altertable.html
Then you can safely add your column.
To get a table OID, cast to the object identifier type
regclass
(while connected to the same DB):This finds the first table (or view, etc.) with the given name along the
search_path
or raises an exception if not found.Schema-qualify the table name to remove the dependency on the search path:
In Postgres 9.4 or later you can also use
to_regclass('myschema.mytbl')
, which doesn't raise an exception if the table is not found:Then you only need to query the catalog table
pg_attribute
for the existence of the column: