Safe dynamic SQL with squirrel (optional filters, stable ordering)

3822
0

Endpoints with optional filters often devolve into messy SQL string concatenation. I prefer building queries with squirrel so I can conditionally add WHERE clauses while keeping the final query parameterized. The pattern also helps keep ordering stable and limits bounded, which matters for pagination and cacheability. I still rely on the database for correctness (constraints) and performance (indexes), but the builder keeps application code readable and less error-prone. Another benefit is testability: you can unit test the generated SQL for key conditions without mocking the DB. This is particularly useful for admin search endpoints where new filters are added frequently.