|
| 1 | +package mysql |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "database/sql" |
| 6 | + "encoding/json" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + |
| 10 | + "github.com/go-sql-driver/mysql" |
| 11 | + |
| 12 | + "github.com/uber/submitqueue/entity" |
| 13 | + "github.com/uber/submitqueue/extension/storage" |
| 14 | +) |
| 15 | + |
| 16 | +type batchDependentStore struct { |
| 17 | + db *sql.DB |
| 18 | +} |
| 19 | + |
| 20 | +// NewBatchDependentStore creates a new MySQL-backed BatchDependentStore. |
| 21 | +func NewBatchDependentStore(db *sql.DB) storage.BatchDependentStore { |
| 22 | + return &batchDependentStore{db: db} |
| 23 | +} |
| 24 | + |
| 25 | +// Get retrieves the batch dependent by batch ID. Returns ErrNotFound if the batch dependent is not found. |
| 26 | +func (s *batchDependentStore) Get(ctx context.Context, batchID string) (entity.BatchDependent, error) { |
| 27 | + var bd entity.BatchDependent |
| 28 | + var dependentsJSON []byte |
| 29 | + |
| 30 | + err := s.db.QueryRowContext(ctx, |
| 31 | + "SELECT batch_id, dependents FROM batch_dependent WHERE batch_id = ?", |
| 32 | + batchID, |
| 33 | + ).Scan(&bd.BatchID, &dependentsJSON) |
| 34 | + |
| 35 | + if errors.Is(err, sql.ErrNoRows) { |
| 36 | + return entity.BatchDependent{}, storage.WrapNotFound(err) |
| 37 | + } |
| 38 | + if err != nil { |
| 39 | + return entity.BatchDependent{}, fmt.Errorf("failed to get batch dependent entity batchID=%s from the database: %w", batchID, err) |
| 40 | + } |
| 41 | + |
| 42 | + if err := json.Unmarshal(dependentsJSON, &bd.Dependents); err != nil { |
| 43 | + return entity.BatchDependent{}, fmt.Errorf("failed to unmarshal dependents for batch dependent entity batchID=%s from the database: %w", batchID, err) |
| 44 | + } |
| 45 | + |
| 46 | + return bd, nil |
| 47 | +} |
| 48 | + |
| 49 | +// Create creates a new batch dependent. Returns ErrAlreadyExists if the entry already exists. |
| 50 | +func (s *batchDependentStore) Create(ctx context.Context, batchDependent entity.BatchDependent) error { |
| 51 | + dependentsJSON, err := json.Marshal(batchDependent.Dependents) |
| 52 | + if err != nil { |
| 53 | + return fmt.Errorf("failed to marshal dependents batchID=%s for Create batch dependent entity: %w", batchDependent.BatchID, err) |
| 54 | + } |
| 55 | + |
| 56 | + _, err = s.db.ExecContext(ctx, |
| 57 | + "INSERT INTO batch_dependent (batch_id, dependents) VALUES (?, ?)", |
| 58 | + batchDependent.BatchID, dependentsJSON, |
| 59 | + ) |
| 60 | + if err != nil { |
| 61 | + var mysqlErr *mysql.MySQLError |
| 62 | + if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 { |
| 63 | + return fmt.Errorf("batch dependent entity batchID=%s: %w", batchDependent.BatchID, storage.ErrAlreadyExists) |
| 64 | + } |
| 65 | + return fmt.Errorf("failed to insert batch dependent entity batchID=%s: %w", batchDependent.BatchID, err) |
| 66 | + } |
| 67 | + |
| 68 | + return nil |
| 69 | +} |
0 commit comments