| 259 | } |
| 260 | |
| 261 | func TestQuery_PracticalComposition(t *testing.T) { |
| 262 | // Realistic example: build a complex query with reusable parts |
| 263 | getUser := true |
| 264 | getEmail := true |
| 265 | filterActive := true |
| 266 | filterRole := "admin" |
| 267 | |
| 268 | // Build SELECT clause dynamically |
| 269 | sel := Q().Space("SELECT id") |
| 270 | if getUser { |
| 271 | sel.Join(", ", "name") |
| 272 | } |
| 273 | if getEmail { |
| 274 | sel.Join(", ", "email") |
| 275 | } |
| 276 | |
| 277 | // Build WHERE clause |
| 278 | where := Q() |
| 279 | if filterActive { |
| 280 | where.Space("WHERE active = ?", true) |
| 281 | } |
| 282 | if filterRole != "" { |
| 283 | if where.Len() > 0 { |
| 284 | where.And("role = ?", filterRole) |
| 285 | } else { |
| 286 | where.Space("WHERE role = ?", filterRole) |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | // Compose final query |
| 291 | q := Q().Space("? FROM users ?", sel, where). |
| 292 | Space("ORDER BY created_at DESC"). |
| 293 | Space("LIMIT ?", 10) |
| 294 | |
| 295 | sql, args, err := q.ToSQL() |
| 296 | require.NoError(t, err) |
| 297 | require.Equal(t, "SELECT id, name, email FROM users WHERE active = $1 AND role = $2 ORDER BY created_at DESC LIMIT $3", sql) |
| 298 | require.Equal(t, []any{true, "admin", 10}, args) |
| 299 | } |
| 300 | |
| 301 | func TestQuery_ErrorHandling(t *testing.T) { |
| 302 | // Create a query with nil nested query to trigger error |