This sub-repository demonstrates the Builder Design Pattern in Golang using an SQL Query Builder as an example.
Ever built SQL queries dynamically and ended up with string concatenation nightmares?
- Adding conditions (
WHERE
,ORDER BY
) makes the query messy. - Handling optional filters leads to tons of if-else statements.
- Forgetting to escape values properly can break the query.
Using the Builder Pattern, we can construct complex queries step by step while keeping the code clean, flexible, and readable.
Say you need to generate SQL queries dynamically:
- Sometimes you need a
WHERE
clause, sometimes you don’t. - Sorting (
ORDER BY
) should be optional. - Filtering by multiple fields should be composable.
Hardcoding these conditions in string concatenation quickly gets out of control.
- Encapsulates query-building logic in a structured way.
- Allows method chaining for an intuitive API.
- Prevents syntax errors by handling query construction internally.
query := NewSQLBuilder().
Select("id", "name").
From("users").
Where("age > ?", 18).
OrderBy("created_at DESC").
Build()
fmt.Println(query)
// Output: SELECT id, name FROM users WHERE age > ? ORDER BY created_at DESC;
Read my article on Medium on Builder Design Pattern: -