Finished code to build graph structure from tables