Factorize foreign keys.

Everything works except for a caching bug (#13).