Viktor/sqlfunctions

This is a massive rewrite of a lot of stuff, but it will let us lock down the database a lot better.

I've tested everything affected afaik, but I could have missed something. We need to write real integration tests.
I tested it and it gave me a syntax error, so I went with a unique index. Here's a SO question about this:
"I don't think you can use a function with a unique constraint but you can with a unique index."
http://stackoverflow.com/questions/8443716/postgres-unique-constraint-for-array