I want to get the relation name for a given relid or RelOptInfo data structure.

For some experiment I need to fetch the relation name while processing a given query inside postgresql. is there some way of doing this?

  • Isn't that what pg_class is for?
    – mustaccio
    Oct 5 '17 at 18:53
  • I want to be able to do that from inside the postgres code, when I am in middle of executing a query, somewhere in parser or in the planner. Oct 5 '17 at 21:00

You want RelationGetRelationName(Relation).

If you don't have a Relation, use get_rel_name(Oid). This uses the syscache so you must have an open transaction. Beware though, it doesn't schema-qualify the name. If you need that, you should probably do a syscache lookup yourself (see the code for get_rel_name in src/backend/utils/cache/lsyscache.c) so you can also get_namespace_name the schema name. Then use quote_qualified_identifier.

I am constantly surprised that Pg doesn't seem to have a public C-level equivalent of the regclass formatting in regclassout. See src/backend/utils/adt/regproc.c.

There's generate_qualified_relation_name, but it's static for some reason. I think I'll submit a patch proposing to move it, generate_relation_name and get_relation_name to lsyscache.c and make them public.

In the mean time I suggest shameless ripping off what generate_relation_name or generate_qualified_relation_name does if you're doing something where get_rel_name isn't good enough.

Update: patch submitted. Feel free to shamelessly rip off that function.

  • I didn't get what do you mean by 'schema-qualify the name' ? Oct 6 '17 at 5:18
  • @GouravKumar public.mytable vs just mytable. Imagine if there are two mytables, one in schema public and one in schema other... Oct 6 '17 at 5:22
  • Just like global and local variables with same name. I used get_rel_name(oid), it doesn't gives me relation name but a number. I am not sure what that number is. Oct 6 '17 at 5:45
  • Er ... what? get_rel_name returns a relation name as a string. Oct 6 '17 at 5:54
  • Sorry ! mybad. I used %d instead of %s. There are some relations though for which I get Oid as 0, and relname as null, in the same query. I am using TPC-DS query 50. Oct 6 '17 at 6:09

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .