WITH defs AS (
    SELECT
        'function'::text AS kind,
        n.nspname AS schema_name,
        p.oid::regprocedure::text AS object,
        pg_get_functiondef(p.oid) AS definition
    FROM pg_proc p
    JOIN pg_namespace n ON n.oid = p.pronamespace
    WHERE p.prokind IN ('f', 'p')

    UNION ALL

    SELECT
        'view/matview',
        n.nspname,
        c.oid::regclass::text,
        pg_get_viewdef(c.oid)
    FROM pg_class c
    JOIN pg_namespace n ON n.oid = c.relnamespace
    WHERE c.relkind IN ('v', 'm')

    UNION ALL

    SELECT
        'trigger',
        n.nspname,
        format('%s.%s', t.tgrelid::regclass, t.tgname),
        pg_get_triggerdef(t.oid)
    FROM pg_trigger t
    JOIN pg_class c ON c.oid = t.tgrelid
    JOIN pg_namespace n ON n.oid = c.relnamespace
    WHERE NOT t.tgisinternal

    UNION ALL

    SELECT
        'default',
        n.nspname,
        format('%s.%s', a.attrelid::regclass, a.attname),
        pg_get_expr(d.adbin, d.adrelid)
    FROM pg_attrdef d
    JOIN pg_attribute a ON a.attrelid = d.adrelid AND a.attnum = d.adnum
    JOIN pg_class c ON c.oid = a.attrelid
    JOIN pg_namespace n ON n.oid = c.relnamespace

    UNION ALL

    SELECT
        'constraint',
        n.nspname,
        format('%s.%s', c.conrelid::regclass, c.conname),
        pg_get_constraintdef(c.oid)
    FROM pg_constraint c
    JOIN pg_class cl ON cl.oid = c.conrelid
    JOIN pg_namespace n ON n.oid = cl.relnamespace
    WHERE c.conrelid <> 0

    UNION ALL

    SELECT
        'index',
        n.nspname,
        i.indexrelid::regclass::text,
        pg_get_indexdef(i.indexrelid)
    FROM pg_index i
    JOIN pg_class c ON c.oid = i.indexrelid
    JOIN pg_namespace n ON n.oid = c.relnamespace

    UNION ALL

    SELECT
        'rule',
        n.nspname,
        format('%s.%s', r.ev_class::regclass, r.rulename),
        pg_get_ruledef(r.oid)
    FROM pg_rewrite r
    JOIN pg_class c ON c.oid = r.ev_class
    JOIN pg_namespace n ON n.oid = c.relnamespace
)
SELECT 
    kind,
    schema_name,
    object,
    definition
FROM defs
WHERE definition LIKE '%public.%'
   OR definition LIKE '%"public".%'
ORDER BY schema_name, kind, object;