How to find inherited tables programatically in PostgreSQL?

前端 未结 4 816
借酒劲吻你
借酒劲吻你 2021-01-05 13:41

I have a PostgreSQL 8.3 database where table inheritance is being used. I would like to get a list of all tables along with its schema name which is inherited from a base ta

4条回答
  •  情话喂你
    2021-01-05 14:10

    For those who are running a version of PostgreSQL with RECURSIVE support here's a function that finds derived tables for the specified base table.

    CREATE OR REPLACE FUNCTION tables_derived_from(base_namespace name, base_table name)
    RETURNS TABLE (table_schema name, table_name name, oid oid)
    AS $BODY$
        WITH RECURSIVE inherited_id AS
        (
            SELECT i.inhrelid AS oid
            FROM pg_inherits i
            JOIN pg_class base_t ON i.inhparent = base_t.oid
            JOIN pg_namespace base_ns ON base_t.relnamespace = base_ns.oid
            WHERE base_ns.nspname = base_namespace AND base_t.relname = base_table
    
            UNION
    
            SELECT i.inhrelid AS oid
            FROM pg_inherits i
            JOIN inherited_id b ON i.inhparent = b.oid
        )
        SELECT child_ns.nspname as table_schema, child_t.relname as table_name, child_t.oid
        FROM inherited_id i
        JOIN pg_class child_t ON i.oid = child_t.oid 
        JOIN pg_namespace child_ns ON child_t.relnamespace = child_ns.oid
        ORDER BY 1, 2, 3;
    $BODY$ LANGUAGE sql STABLE;
    

提交回复
热议问题