refactor search and history fns to CTE