You want to write functions and build triggers in Postgres' scripting language plpgsql.
As superuser (postgres) use the command-line tool createlang ref.
So to activate plpgsql in database db1 use:
createlang plpgsql db1