Adding Custom Fields to search Listing

We are attempting to patch RT so that the custom fields will show up as
columns in the ticket search listing. We were able to get that part
working, however we are having trouble sorting on the custom fields
since they are not located in a separate table. RT tries to sort on
the custom field as if it were a column in the tickets table which
fails giving this error: main.<custom_field> does not exist.

In order to sort on custom fields, we will need to join the tickets and
ticketcustomfieldvalues tables so that the fields of both tables appear
as targets in the query. How is the search query built? Where is the
appropriate place to add this code?

Thanks for any help in advance, it is greatly appreciated.