-- https://psutil.readthedocs.io/en/latest/#psutil.Process.memory_full_info
-- Linux: 0=rss, 1=vms, 2=shared, 3=text, 4=lib, 5=data, 6=dirty, 7=uss, 8=pss, 9=swap
CREATE OR REPLACE FUNCTION get_memory_info(pid INTEGER DEFAULT NULL, memtype INTEGER DEFAULT 0)
RETURNS BIGINT
AS
$$
    import psutil
    p = psutil.Process(pid)
    return p.memory_full_info()[memtype]
$$
LANGUAGE plpythonu;

-- With this function you can get the following memory information about current PostgreSQL backends (aka processes)
--
-- fabrizio=# \e
--   pid  |         backend_type         | datname  |                                             query                                              | memory_usage 
-- -------+------------------------------+----------+------------------------------------------------------------------------------------------------+--------------
--  27429 | autovacuum launcher          |          |                                                                                                | 5420 kB
--  27427 | background writer            |          |                                                                                                | 4948 kB
--  27426 | checkpointer                 |          |                                                                                                | 4496 kB
--  21592 | client backend               | fabrizio |                                                                                                | 8236 kB
--  27436 | client backend               | fabrizio | SELECT pid, backend_type, datname, query, pg_size_pretty(get_memory_info(pid)) AS memory_usage+| 30 MB
--        |                              |          | FROM pg_stat_activity                                                                         +| 
--        |                              |          | ORDER BY 2;                                                                                    | 
--  27431 | logical replication launcher |          |                                                                                                | 5396 kB
--  27428 | walwriter                    |          |                                                                                                | 7748 kB
-- (7 rows)