• Tom Lane's avatar
    Use the typcache to cache constraints for domain types. · 8abb3cda
    Tom Lane authored
    Previously, we cached domain constraints for the life of a query, or
    really for the life of the FmgrInfo struct that was used to invoke
    domain_in() or domain_check().  But plpgsql (and probably other places)
    are set up to cache such FmgrInfos for the whole lifespan of a session,
    which meant they could be enforcing really stale sets of constraints.
    On the other hand, searching pg_constraint once per query gets kind of
    expensive too: testing says that as much as half the runtime of a
    trivial query such as "SELECT 0::domaintype" went into that.
    
    To fix this, delegate the responsibility for tracking a domain's
    constraints to the typcache, which has the infrastructure needed to
    detect syscache invalidation events that signal possible changes.
    This not only removes unnecessary repeat reads of pg_constraint,
    but ensures that we never apply stale constraint data: whatever we
    use is the current data according to syscache rules.
    
    Unfortunately, the current configuration of the system catalogs means
    we have to flush cached domain-constraint data whenever either pg_type
    or pg_constraint changes, which happens rather a lot (eg, creation or
    deletion of a temp table will do it).  It might be worth rearranging
    things to split pg_constraint into two catalogs, of which the domain
    constraint one would probably be very low-traffic.  That's a job for
    another patch though, and in any case this patch should improve matters
    materially even with that handicap.
    
    This patch makes use of the recently-added memory context reset callback
    feature to manage the lifespan of domain constraint caches, so that we
    don't risk deleting a cache that might be in the midst of evaluation.
    
    Although this is a bug fix as well as a performance improvement, no
    back-patch.  There haven't been many if any field complaints about
    stale domain constraint checks, so it doesn't seem worth taking the
    risk of modifying data structures as basic as MemoryContexts in back
    branches.
    8abb3cda
domain.sql 14.2 KB