Fixed a bug when grouping by a type safe value

- the type safe value was wrapped in another type safe value,
  also added a factory to allow custom code to convert values
  to type safe values, this will probably not be used a lot (hopefully),
  but it would be better than having to cast to query internal.