Subject: Get relid for a relation

From: Amin <[email-masked]>
Date: Thu, 12 Jan 2023 17:48:59 -0800

Hi,

In CustomScan cost estimator, where PlannerInfo and RelOptInfo are passed,
I want to get access to the relation stats (for example pg_stat_all_tables)
by calling pg_stat_fetch_stat_tabentry(). However, I don't have access to
relid to pass to this function. For a sample relation, when I hardcode the
relid (for example 16385), it works. However, RelOptInfo->relid is always 1
(for whatever relation the query is scanning). Why this happens and how to
get access to the correct relid (16385) as in pg_stat_all_tables?

Thank you!

---

From: Tom Lane <[email-masked]>
Date: Fri, 13 Jan 2023 09:45:26 -0500

Amin <[email-masked]> writes:
> relid to pass to this function.

Sure you do.  The existing code, eg in selfuncs.c, does it about like
this:

        RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);

        Assert(rte->rtekind == RTE_RELATION);
        relid = rte->relid;
        Assert(relid != InvalidOid);
        ...
        vardata.statsTuple = SearchSysCache3(STATRELATTINH,
                                             ObjectIdGetDatum(relid),
                                             Int16GetDatum(colnum),
                                             BoolGetDatum(rte->inh));

This is maybe a bit confusing, in that rel->relid is a range
table index but rte->relid is an OID.

FWIW, I seriously doubt that the numbers kept by the pg_stat mechanisms
are what you want for query planning purposes.

			regards, tom lane