Fix foreign key type inference

This fixes #852 and #1130