Is it possible to discover the column types from a Postgres function? - postgresql

I'm working on a utility that is using templates to generate a data access layer against a Postgres database. As part of this I'm trying to dynamically discover the return types of the stored procedures. This is easy enough in simple cases where a single standard type is returned, but I'm struggling when it comes to it returning a user defined type.
I'd appreciate if someone could provide the necessary SQL to return this data.
Thanks
Mark
I appreciate the answers that I have so far, which effectively boil to to the following SQL
SELECT p.proname, t.typname, p,proretset
FROM pg_catalog.pg_proc p
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
INNER JOIN pg_type t ON p.prorettype = t.oid
WHERE n.nspname = 'public'
--and proname = 'foo'
ORDER BY proname;
This will return the name of the return types. However I still need to decompose the type into the properties that make it up when it returns a user defined type.
In the case that a function returns a record I don't think there is any way to discover its return structure other than calling the function and examining its return values.

psql meta commands are an easy shortcut to finding information schema stuff.
try test=# \d? to find introspection info.
then psql -E -c '\df' will show the sql behind the show function command:
d$ psql -E -c '\df+'
********* QUERY **********
SELECT n.nspname as "Schema",
p.proname as "Name",
pg_catalog.pg_get_function_result(p.oid) as "Result data type",
pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types",
CASE
WHEN p.proisagg THEN 'agg'
WHEN p.proiswindow THEN 'window'
WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger'
ELSE 'normal'
END as "Type",
CASE
WHEN p.provolatile = 'i' THEN 'immutable'
WHEN p.provolatile = 's' THEN 'stable'
WHEN p.provolatile = 'v' THEN 'volatile'
END as "Volatility",
pg_catalog.pg_get_userbyid(p.proowner) as "Owner",
l.lanname as "Language",
p.prosrc as "Source code",
pg_catalog.obj_description(p.oid, 'pg_proc') as "Description"
FROM pg_catalog.pg_proc p
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
LEFT JOIN pg_catalog.pg_language l ON l.oid = p.prolang
WHERE pg_catalog.pg_function_is_visible(p.oid)
AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
ORDER BY 1, 2, 4;
**************************
In your case the would be what you want:
pg_catalog.pg_get_function_result(p.oid) as "Result data type",

This query will list the stored procedures with the types.
SELECT proname, proargnames as arguments,
oidvectortypes(proargtypes) as arguments_type,
t.typname as return_type,prosrc as source
FROM pg_catalog.pg_namespace n
JOIN pg_catalog.pg_proc p ON pronamespace = n.oid
JOIN pg_type t ON p.prorettype = t.oid
WHERE nspname = 'public'
You can always filter by proname.

Just to get started:
SELECT
*
FROM
pg_proc
JOIN pg_type ON pg_type.oid = ANY(proallargtypes)
WHERE
proname = 'foo';

Are you looking for this?
SELECT proname,
pg_get_function_result(oid)
FROM pg_proc
WHERE proname = 'foo';

if the function returns a record then the type is not known until runtime, demonstrated with:
create or replace function func() returns record language plpgsql immutable as $$
declare
r record;
q record;
begin
select 10, 'hello' into r;
select 11, 'hello', 'helloagain' into q;
if random()>0.5 then
return r;
else
return q;
end if;
end;$$;
in other words, you can't know the type until after you call the function. Once you have called the function, you could dynamically determine information about the record by passing it into a C-language function as referenced here

Thanks for the help guys, I'm think JackPDouglas is correct and that since functions that return record sets can be polymorphic that there's no way to find out the return type definition.
However here's the SQL I was looking for to get the definition of a function that returns a composite type:
SELECT t.typname, attname, a.typname
from pg_type t
JOIN pg_class on (reltype = t.oid)
JOIN pg_attribute on (attrelid = pg_class.oid)
JOIN pg_type a on (atttypid = a.oid)
WHERE t.typname = (
SELECT t.typname
FROM pg_catalog.pg_proc p
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
INNER JOIN pg_type t ON p.prorettype = t.oid
WHERE n.nspname = 'public'
and proname = 'foo'
ORDER BY proname
);

Related

Check return type of a function in postgresql

I want to get return type of a function, so query will like this:
select t.typname
from pg_proc p
inner join pg_namespace n on p.pronamespace = n.oid
inner join pg_type t on t.oid = p.prorettype
where n.nspname = current_schema() and p.prokind = 'f' and p.proname = 'my_function_name';
Now, I use typname to compare to get return type of function: refcursor, record, int,...
But I want to ask that I can change below query to (not join pg_type):
select p.prorettype
from pg_proc p
inner join pg_namespace n on p.pronamespace = n.oid
where n.nspname = current_schema() and p.prokind = 'f' and p.proname = 'my_function_name'
So now, to check return type is refcursor, instead of if typname = 'refcursor' then, I will use if prorettype = 1790 then (1790 is oid of data type 'refcursor'). So can I do this? I mean, in all Postgresql version, everytime, oid of 'refecursor' is still 1790?
Thank you.
You can use format_type()
select format_type(p.prorettype, null) as return_type
from pg_proc p
where p.proname = 'my_function_name';
and p.pronamespace = current_schema::regnamespace;
and p.prokind = 'f'

Getting a column comment in PostgreSql [duplicate]

I'm running a project on a Postgres database and need to retrieve the comments on columns within the DB to be used as table headings and such. I have seen that there are a couple of built in functions (pg_description and col_description) but i haven't been able to find examples on how to use them and playing around with them has proved pretty futile.
So I was wondering if any has been able to do this before and if so, how?
select
c.table_schema,
c.table_name,
c.column_name,
pgd.description
from pg_catalog.pg_statio_all_tables as st
inner join pg_catalog.pg_description pgd on (
pgd.objoid = st.relid
)
inner join information_schema.columns c on (
pgd.objsubid = c.ordinal_position and
c.table_schema = st.schemaname and
c.table_name = st.relname
);
It all works by oid,
mat=> SELECT c.oid FROM pg_catalog.pg_class c WHERE c.relname = 'customers';
oid
-------
23208
(1 row)
Now, I have the oid for that table, so I can ask :
mat=> select pg_catalog.obj_description(23208);
obj_description
-------------------
Customers
(1 row)
Then, I can ask for the description of the fourth column :
mat=> select pg_catalog.col_description(23208,4);
col_description
-----------------------------------------
Customer codes, CHS, FACTPOST, POWER...
(1 row)
If you want to know which queries does psql run when you do \dt+ or \d+ customers, just run it with -E.
Just to be here if somebody will need it.
There are many answers here, but none of them was as simple as I would like it to be. So, based on previous answers and current postgres 9.4, I have created this query:
SELECT
obj_description(format('%s.%s',isc.table_schema,isc.table_name)::regclass::oid, 'pg_class') as table_description,
pg_catalog.col_description(format('%s.%s',isc.table_schema,isc.table_name)::regclass::oid,isc.ordinal_position) as column_description
FROM
information_schema.columns isc
It fetches table and column descriptions, without any confusing joins and ugly string concatenations.
Take care with schemas, this code considers them:
SELECT
cols.column_name, (
SELECT
pg_catalog.col_description(c.oid, cols.ordinal_position::int)
FROM
pg_catalog.pg_class c
WHERE
c.oid = (SELECT ('"' || cols.table_name || '"')::regclass::oid)
AND c.relname = cols.table_name
) AS column_comment
FROM
information_schema.columns cols
WHERE
cols.table_catalog = 'your_database'
AND cols.table_name = 'your_table'
AND cols.table_schema = 'your_schema';
References:
Postgresql Document Table and Column Description Comments on Table and Column
Determining the OID of a table in Postgres 9.1?
A slight change to one of the other answers which only gives you columns that have comments on them, this gives you all columns whether they have a comment or not.
select c.table_schema, st.relname as TableName, c.column_name,
pgd.description
from pg_catalog.pg_statio_all_tables as st
inner join information_schema.columns c
on c.table_schema = st.schemaname
and c.table_name = st.relname
left join pg_catalog.pg_description pgd
on pgd.objoid=st.relid
and pgd.objsubid=c.ordinal_position
where st.relname = 'YourTableName';
This works for me using the PostBooks 3.2.2 DB:
select cols.column_name,
(select pg_catalog.obj_description(oid) from pg_catalog.pg_class c where c.relname=cols.table_name) as table_comment
,(select pg_catalog.col_description(oid,cols.ordinal_position::int) from pg_catalog.pg_class c where c.relname=cols.table_name) as column_comment
from information_schema.columns cols
where cols.table_catalog='postbooks' and cols.table_name='apapply'
Regards,
Sylnsr
If you just need to show the comments for your columns among other data, you can also use:
\d+ my_table
Enhance for #Nick and #mat suggestions: use
SELECT obj_description('schemaName.tableName'::regclass, 'pg_class');
when you have string name (not oid).
To avoid to remember 'pg_class' parameter, and to avoid ugly concatenations at the function calls, as (tname||'.'||schema)::regclass, an useful overload for obj_description:
CREATE FUNCTION obj_description(
p_rname text, p_schema text DEFAULT NULL,
p_catalname text DEFAULT 'pg_class'
) RETURNS text AS $f$
SELECT obj_description((CASE
WHEN strpos($1, '.')>0 OR $2 IS NULL OR $2='' THEN $1
ELSE $2||'.'||$1
END)::regclass, $3);
$f$ LANGUAGE SQL IMMUTABLE;
-- USAGE: obj_description('mytable')
-- SELECT obj_description('s.t');
-- PS: obj_description('s.t', 'otherschema') is a syntax error,
-- but not generates exception: returns the same as ('s.t')
Now is easy to use, because the table name (rname parameter) is a varchar and can be expressed with a separated field for schema name, as in the main tables and queries.
See also "Getting list of table comments in PostgreSQL" or the new pg9.3 Guide
This answer is a little late, but it popped up on a google search I did to research this problem. We only needed Table descriptions, but the method would be the same for columns.
The column descriptions are in the pg_description table also, referenced by objoid.
Add this view:
CREATE OR REPLACE VIEW our_tables AS
SELECT c.oid, n.nspname AS schemaname, c.relname AS tablename, d.description,
pg_get_userbyid(c.relowner) AS tableowner, t.spcname AS "tablespace",
c.relhasindex AS hasindexes, c.relhasrules AS hasrules, c.reltriggers > 0 AS hastriggers
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
LEFT JOIN pg_description d ON c.oid = d.objoid
WHERE c.relkind = 'r'::"char";
ALTER TABLE our_tables OWNER TO postgres;
GRANT SELECT, UPDATE, INSERT, DELETE, REFERENCES, TRIGGER ON TABLE our_tables TO postgres;
GRANT SELECT ON TABLE our_tables TO public;
Then run:
SELECT tablename, description FROM our_tables WHERE schemaname = 'public'
The view is a modified version of the pg_tables view which adds in the description column.
You could also monkey around with the view definition to make it a single query.
I accessed table comments like this:
select c.relname table_name, pg_catalog.obj_description(c.oid) as comment from pg_catalog.pg_class c where c.relname = 'table_name';
and column comments thusly:
SELECT c.column_name, pgd.description FROM pg_catalog.pg_statio_all_tables as st inner join pg_catalog.pg_description pgd on (pgd.objoid=st.relid) inner join information_schema.columns c on (pgd.objsubid=c.ordinal_position and c.table_schema=st.schemaname and c.table_name=st.relname and c.table_name = 'table_name' and c.table_schema = 'public');
I asked a similar question about Postgresql comments last month. If you dig through that, you'll come across some Perl code over on my blog that automates the process of extracting a comment.
To pull out the column names of a table, you can use something like the following:
select
a.attname as "colname"
,a.attrelid as "tableoid"
,a.attnum as "columnoid"
from
pg_catalog.pg_attribute a
inner join pg_catalog.pg_class c on a.attrelid = c.oid
where
c.relname = 'mytable' -- better to use a placeholder
and a.attnum > 0
and a.attisdropped is false
and pg_catalog.pg_table_is_visible(c.oid)
order by a.attnum
You can then use the tableoid,columnoid tuple to extract the comment of each column (see my question).
I just found this here. It will provide you with all kind of metadata on one specific table (type, default value, not null flag, length, comment, foreign key name, primary key name). It seems to work well.
SELECT pg_tables.tablename, pg_attribute.attname AS field,
format_type(pg_attribute.atttypid, NULL) AS "type",
pg_attribute.atttypmod AS len,
(SELECT col_description(pg_attribute.attrelid,
pg_attribute.attnum)) AS comment,
CASE pg_attribute.attnotnull
WHEN false THEN 1 ELSE 0
END AS "notnull",
pg_constraint.conname AS "key", pc2.conname AS ckey,
(SELECT pg_attrdef.adsrc FROM pg_attrdef
WHERE pg_attrdef.adrelid = pg_class.oid
AND pg_attrdef.adnum = pg_attribute.attnum) AS def
FROM pg_tables, pg_class
JOIN pg_attribute ON pg_class.oid = pg_attribute.attrelid
AND pg_attribute.attnum > 0
LEFT JOIN pg_constraint ON pg_constraint.contype = 'p'::"char"
AND pg_constraint.conrelid = pg_class.oid AND
(pg_attribute.attnum = ANY (pg_constraint.conkey))
LEFT JOIN pg_constraint AS pc2 ON pc2.contype = 'f'::"char"
AND pc2.conrelid = pg_class.oid
AND (pg_attribute.attnum = ANY (pc2.conkey))
WHERE pg_class.relname = pg_tables.tablename
-- AND pg_tables.tableowner = "current_user"()
AND pg_attribute.atttypid <> 0::oid
AND tablename='your_table'
ORDER BY field ASC
Source: http://golden13.blogspot.de/2012/08/how-to-get-some-information-about_7.html
Ok, so i worked it out to degree...
select col_description(table id, column number)...
ie: select col_description(36698,2);
That worked, but is there an easier way to do this maybe bringing all the comments on all the columns and using the table name instead of the oid???
To display comments from all columns of all table :
SELECT
cols.table_name,
cols.column_name, (
SELECT
pg_catalog.col_description(c.oid, cols.ordinal_position::int)
FROM
pg_catalog.pg_class c
WHERE
c.oid = (SELECT ('"' || cols.table_name || '"')::regclass::oid)
AND c.relname = cols.table_name
) AS column_comment
FROM
information_schema.columns cols
WHERE
cols.table_name IN (SELECT cols.table_name FROM information_schema.columns)
AND cols.table_catalog = 'your_database_name'
AND cols.table_schema = 'your_schema_name';
You need to execute this query outside any schema/catalog/db
This query is based on another answer in this question which display comments from one table only
To extend on the response provided by #amxy; I found that adding a schema filter can help in some environments. As I found #amxy's solution didn't work until I added by schema filters
SELECT
pg_tables.schemaname,
pg_tables.TABLENAME,
pg_attribute.attname AS field,
format_type(pg_attribute.atttypid, NULL) AS "type",
pg_attribute.atttypmod AS len,
(
SELECT col_description(pg_attribute.attrelid, pg_attribute.attnum)) AS COMMENT,
CASE pg_attribute.attnotnull
WHEN FALSE THEN 1
ELSE 0
END AS "notnull",
pg_constraint.conname AS "key", pc2.conname AS ckey,
(
SELECT pg_attrdef.adsrc
FROM pg_attrdef
WHERE pg_attrdef.adrelid = pg_class.oid
AND pg_attrdef.adnum = pg_attribute.attnum) AS def
FROM pg_tables, pg_class
JOIN pg_attribute
ON pg_class.oid = pg_attribute.attrelid
AND pg_attribute.attnum > 0
LEFT JOIN pg_constraint
ON pg_constraint.contype = 'p'::"char"
AND pg_constraint.conrelid = pg_class.oid
AND
(pg_attribute.attnum = ANY (pg_constraint.conkey))
LEFT JOIN pg_constraint AS pc2
ON pc2.contype = 'f'::"char"
AND pc2.conrelid = pg_class.oid
AND (pg_attribute.attnum = ANY (pc2.conkey))
WHERE pg_class.relname = pg_tables.TABLENAME
AND pg_tables.schemaname IN ('op', 'im', 'cs','usr','li')
-- AND pg_tables.tableowner = "current_user"()
AND pg_attribute.atttypid <> 0::oid
---AND TABLENAME='your_table'
ORDER BY pg_tables.schemaname,
pg_tables.TABLENAME ASC;
RESULTS:
SELECT
relname table_name,
obj_description(oid) table_description,
column_name,
pgd.description column_description
FROM pg_class
INNER JOIN
information_schema.columns
ON table_name = pg_class.relname
LEFT JOIN
pg_catalog.pg_description pgd
ON pgd.objsubid = ordinal_position
WHERE
relname = 'your_table_name'
SELECT sc.table_schema , sc.table_name, sc.column_name, col_description(pc."oid" , sc.ordinal_position) col_description FROM pg_class pc
INNER JOIN pg_namespace ns ON ns."oid" =pc.relnamespace
INNER JOIN information_schema.COLUMNS sc ON sc.table_name=pc.relname AND sc.table_schema=ns.nspname
WHERE 1=1
AND upper(ns.nspname) = 'TABLE_SCHEMA'
AND upper(pc.relname) = 'TABLE_NAME'
Retrieving Comments from a PostgreSQL DB

How to get the table a FK refers to in Postgres sql

For a given table, I am trying to get all the columns, to include their name, type, whether the column is a primary key, or a foreign key, and if it is a FK, what table it points to. I wrote the query below, but it seems to be give me the what the columns are referenced by, instead of the other way around:
select c.column_name, c.udt_name, constraint_type, kcu.table_name as references from information_schema.columns c
left outer join information_schema.constraint_column_usage u on c.column_name=u.column_name
left outer join information_schema.table_constraints t on u.constraint_name=t.constraint_name
left outer join information_schema.key_column_usage AS kcu on t.constraint_name = kcu.constraint_name
where c.table_name=#name
I am not too worried about edge cases, I am just trying to inverse the references column. Thanks for your time.
Here is a query to get all the foreign keys from a given table along with what they point to:
SELECT c.conname,
t1.relname AS from_table,
a1.attname AS from_column,
t2.relname AS to_table,
a2.attname AS to_column
FROM pg_catalog.pg_constraint c,
pg_catalog.pg_class t1,
pg_catalog.pg_class t2,
pg_catalog.pg_attribute a1,
pg_catalog.pg_attribute a2,
pg_catalog.pg_namespace n1,
pg_catalog.pg_namespace n2
WHERE c.conrelid = t1.oid
AND c.confrelid = t2.oid
AND c.contype = 'f'
AND a1.attrelid = t1.oid
AND a1.attnum = ANY(c.conkey)
AND a2.attrelid = t2.oid
AND a2.attnum = ANY(c.confkey)
AND t1.relkind = 'r'
AND t2.relkind = 'r'
AND n1.oid = t1.relnamespace
AND n2.oid = t2.relnamespace
AND n1.nspname NOT IN ('pg_catalog', 'pg_toast')
AND n2.nspname NOT IN ('pg_catalog', 'pg_toast')
AND pg_catalog.pg_table_is_visible(t1.oid)
AND pg_catalog.pg_table_is_visible(t2.oid)
AND t1.relname = #name;
I see you are using information_schema instead of pg_catalog, so the easiest way might be to turn my query into a CTE or subquery, then join to it based on your table and column name.
EDIT: It sounds like you just need some help joining my query to what you already have. Actually your query has a lot of errors in how it does the joins, so I've rewritten it to include the correct foreign key results:
SELECT c.column_name,
c.udt_name,
t.constraint_type,
t.constraint_name,
x.to_table
FROM information_schema.columns c
LEFT OUTER JOIN (
SELECT t.constraint_type,
t.constraint_catalog,
t.constraint_schema,
t.constraint_name,
t.table_catalog,
t.table_schema,
t.table_name,
u.column_name
FROM information_schema.constraint_column_usage u
LEFT OUTER JOIN information_schema.table_constraints t
ON t.table_catalog = u.table_catalog
AND t.table_schema = u.table_schema
AND t.table_name = u.table_name
AND t.constraint_catalog = u.constraint_catalog
AND t.constraint_schema = u.constraint_schema
AND t.constraint_name = u.constraint_name
WHERE t.constraint_type IS DISTINCT FROM 'FOREIGN KEY'
) t
ON c.table_catalog = t.table_catalog
AND c.table_schema = t.table_schema
AND c.table_name = t.table_name
AND c.column_name = t.column_name
LEFT OUTER JOIN (
SELECT c.conname,
t1.relname AS from_table,
a1.attname AS from_column,
t2.relname AS to_table,
a2.attname AS to_column
FROM pg_catalog.pg_constraint c,
pg_catalog.pg_class t1,
pg_catalog.pg_class t2,
pg_catalog.pg_attribute a1,
pg_catalog.pg_attribute a2,
pg_catalog.pg_namespace n1,
pg_catalog.pg_namespace n2
WHERE c.conrelid = t1.oid
AND c.confrelid = t2.oid
AND c.contype = 'f'
AND a1.attrelid = t1.oid
AND a1.attnum = ANY(c.conkey)
AND a2.attrelid = t2.oid
AND a2.attnum = ANY(c.confkey)
AND t1.relkind = 'r'
AND t2.relkind = 'r'
AND n1.oid = t1.relnamespace
AND n2.oid = t2.relnamespace
AND n1.nspname NOT IN ('pg_catalog', 'pg_toast')
AND n2.nspname NOT IN ('pg_catalog', 'pg_toast')
AND pg_catalog.pg_table_is_visible(t1.oid)
AND pg_catalog.pg_table_is_visible(t2.oid)
) x
ON x.from_table = c.table_name
AND x.from_column = c.column_name
WHERE c.table_name = #cards
;
This version also prevents lots of duplicate rows if you have NOT NULL or CHECK constraints.
I am not sure if you know how to programming with other languages(such as java, C#) besides writing Sql queries
If you know any of them, you can use the function which are int the JDBC/ODBC drivers to get the things you want
Here is an example of using jdbc
you open a connection to the database
from the connection you get, and you can get the meta data, here is the code
conn=dataSource.getConnection();
DatabaseMetaData dbmeta = conn.getMetaData();
After you get the meta data, you can get all the columns, primary keys, foreign keys and even indexed. See the sample codes below
ResultSet rsKey = dbmeta.getPrimaryKeys(null, schemaName, tableName);
ResultSet rs = dbmeta.getColumns(null, schemaName, tableName, "%");
ResultSet rsForeign=meta.getExportedKeys(null, schemaName, tableName);

Postgres: variable saying from which schema I select

I have created a SQL SELECT to get all enums and their values in a schema:
SELECT
t.typname, array_agg(e.enumlabel)
FROM pg_type t
JOIN pg_enum e ON t.oid = e.enumtypid
JOIN pg_namespace n ON t.typnamespace = n.oid
WHERE t.typtype = 'e' AND n.nspname = 'public'
GROUP BY typname
I have put the select into a view so I dont have to write it everytime I want to call it. The only thing that bothers me is that if I rename the schema or use it in another schema I have to rewrite the name of the schema manually, check line 6 of the code:
WHERE t.typtype = 'e' AND n.nspname = 'public'
Public is hardtyped there. When selecting in postgres, is there a "global" variable saying from which schema you select? I was not able to find any.
Thanks
PS: I use postgres 8.4
The current schema can be retrieved using the function current_schema()
http://www.postgresql.org/docs/current/static/functions-info.html
Alternatively to wiring the schema or looking it up with current_schema(), you could make your view group by schema as well and then select on the view.
create or replace view enum_vw as
SELECT
n.nspname, t.typname, array_agg(e.enumlabel)
FROM pg_type t
JOIN pg_enum e ON t.oid = e.enumtypid
JOIN pg_namespace n ON t.typnamespace = n.oid
WHERE t.typtype = 'e'
GROUP BY n.nspname, t.typname;
select * from enum_vw where nspname = 'public';

Get table and column "owning" a sequence

I can run the following line:
ALTER SEQUENCE seqName OWNED BY table.id;
How can I get the 'owner' set by OWNED BY for a sequence (in this case: table.id)?
You may use following query:
select s.relname as seq, n.nspname as sch, t.relname as tab, a.attname as col
from pg_class s
join pg_depend d on d.objid=s.oid and d.classid='pg_class'::regclass and d.refclassid='pg_class'::regclass
join pg_class t on t.oid=d.refobjid
join pg_namespace n on n.oid=t.relnamespace
join pg_attribute a on a.attrelid=t.oid and a.attnum=d.refobjsubid
where s.relkind='S' and d.deptype='a'
It returns all sequences with owner information. Just filter them in WHERE clause and that's it.
Get the "owning" table and column
ALTER SEQUENCE seqName OWNED BY table.id;
Your ALTER SEQUENCE statement causes an entry in the system catalog pg_depend with the dependency type (deptype) 'a' and a refobjsubid greater than 0, pointing to the attribute number (attnum) in pg_attribute. With that knowledge you can devise a simple query:
SELECT d.refobjid::regclass, a.attname
FROM pg_depend d
JOIN pg_attribute a ON a.attrelid = d.refobjid
AND a.attnum = d.refobjsubid
WHERE d.objid = 'public."seqName"'::regclass -- your sequence here
AND d.refobjsubid > 0
AND d.classid = 'pg_class'::regclass;
Double quotes ("") are only needed for otherwise illegal names (mixed case, reserved words, ...).
No need to assert that refclassid is of type regclass since the join to pg_attribute does that automatically.
No need to assert that the sequence is a sequence since schema-qualified object names are unique across the database.
No need to join to pg_class or pg_namespace at all.
The schema name is only needed to disambiguate or if it's not in the search_path.
The same table name (or sequence name for that matter) can be used in multiple schemas. A cast to the object identifier type regclass observes the current search_path to pick the best match if you omit the schema qualification. If the table is not visible, you get an error message.
What's more, a regclass type is displayed as text to the user automatically. (If not, cast to text.) The schema-name is prepended automatically where necessary to be unambiguous in your session.
Get the actual "owner" (the role)
To get the role owning a specific sequence, as requested:
SELECT c.relname, u.usename
FROM pg_class c
JOIN pg_user u ON u.usesysid = c.relowner
WHERE c.oid = '"seqName"'::regclass; -- your sequence here
I was able to list the table and corresponding sequence for a particular column using the following SQL statement:
SELECT table_schema
, table_name
, column_name
, LTRIM(RTRIM(RTRIM(column_default, '::regclass)'),''''),'nextval(''') AS SEQUENCE_NAME
FROM information_schema.columns
WHERE column_default like '%nextval%';
SELECT c.relname,u.usename
FROM pg_class c, pg_user u
WHERE c.relowner = u.usesysid and c.relkind = 'S'
AND relnamespace IN (
SELECT oid
FROM pg_namespace
WHERE nspname NOT LIKE 'pg_%'
AND nspname != 'information_schema'
);
I use that query for get all queries.
Change CTE to filter the result
WITH table_with_sequence as (
SELECT
d.refobjid::regclass::text tablename,
c.relname::text sequencename,
np.nspname::text schemaname,
a.attname::text attname,
u.usename::text
FROM
pg_depend d
INNER JOIN pg_class c ON c.oid = d.objid
AND c.relkind = 'S'
INNER JOIN pg_namespace np ON np.oid = c.relnamespace
AND (np.nspname NOT LIKE 'pg_%'
AND np.nspname != 'information_schema')
INNER JOIN pg_user u ON u.usesysid = c.relowner
INNER JOIN pg_attribute a ON a.attrelid = d.refobjid
AND a.attnum = d.refobjsubid
)
SELECT
'ALTER SEQUENCE '|| QUOTE_LITERAL(QUOTE_IDENT(schemaname) || '.' || QUOTE_IDENT(sequencename)) ||' OWNED BY ' || tablename || '.' || QUOTE_IDENT(attname)
FROM table_with_sequence