listInstancesBatched is a helper function that retrieves instances in batches and converts them to params.Instance. It accepts a query modifier function to customize the base query (e.g., add WHERE clauses).
(queryModifier func(*gorm.DB) *gorm.DB)
| 475 | // and converts them to params.Instance. It accepts a query modifier function |
| 476 | // to customize the base query (e.g., add WHERE clauses). |
| 477 | func (s *sqlDatabase) listInstancesBatched(queryModifier func(*gorm.DB) *gorm.DB) ([]params.Instance, error) { |
| 478 | ret := []params.Instance{} |
| 479 | err := s.conn.Transaction(func(tx *gorm.DB) error { |
| 480 | batchSize := 1000 |
| 481 | offset := 0 |
| 482 | for { |
| 483 | var batch []Instance |
| 484 | |
| 485 | // Start with base query and apply modifier |
| 486 | query := tx.Limit(batchSize).Offset(offset). |
| 487 | Preload("Pool"). |
| 488 | Preload("ScaleSet"). |
| 489 | Preload("Job") |
| 490 | |
| 491 | if queryModifier != nil { |
| 492 | query = queryModifier(query) |
| 493 | } |
| 494 | |
| 495 | q := query.Find(&batch) |
| 496 | if q.Error != nil { |
| 497 | return fmt.Errorf("error fetching instances: %w", q.Error) |
| 498 | } |
| 499 | if len(batch) == 0 { |
| 500 | break |
| 501 | } |
| 502 | |
| 503 | // Pre-grow slice to avoid multiple small reallocations |
| 504 | if cap(ret) < len(ret)+len(batch) { |
| 505 | newCap := max(len(ret)+len(batch), cap(ret)*2) |
| 506 | newRet := make([]params.Instance, len(ret), newCap) |
| 507 | copy(newRet, ret) |
| 508 | ret = newRet |
| 509 | } |
| 510 | |
| 511 | // Convert directly into result slice |
| 512 | for _, instance := range batch { |
| 513 | converted, err := s.sqlToParamsInstance(instance) |
| 514 | if err != nil { |
| 515 | return fmt.Errorf("error converting instance: %w", err) |
| 516 | } |
| 517 | ret = append(ret, converted) |
| 518 | } |
| 519 | offset += len(batch) |
| 520 | } |
| 521 | return nil |
| 522 | }) |
| 523 | return ret, err |
| 524 | } |
| 525 | |
| 526 | func (s *sqlDatabase) ListPoolInstances(_ context.Context, poolID string, outdatedOnly bool) ([]params.Instance, error) { |
| 527 | u, err := uuid.Parse(poolID) |
no test coverage detected