Fix query building