@@ -28,9 +28,9 @@ func (s *batchDependentStore) Get(ctx context.Context, batchID string) (entity.B
2828 var dependentsJSON []byte
2929
3030 err := s .db .QueryRowContext (ctx ,
31- "SELECT batch_id, dependents FROM batch_dependent WHERE batch_id = ?" ,
31+ "SELECT batch_id, dependents, version FROM batch_dependent WHERE batch_id = ?" ,
3232 batchID ,
33- ).Scan (& bd .BatchID , & dependentsJSON )
33+ ).Scan (& bd .BatchID , & dependentsJSON , & bd . Version )
3434
3535 if errors .Is (err , sql .ErrNoRows ) {
3636 return entity.BatchDependent {}, storage .WrapNotFound (err )
@@ -54,8 +54,8 @@ func (s *batchDependentStore) Create(ctx context.Context, batchDependent entity.
5454 }
5555
5656 _ , err = s .db .ExecContext (ctx ,
57- "INSERT INTO batch_dependent (batch_id, dependents) VALUES (?, ?)" ,
58- batchDependent .BatchID , dependentsJSON ,
57+ "INSERT INTO batch_dependent (batch_id, dependents, version ) VALUES (?, ?, ?)" ,
58+ batchDependent .BatchID , dependentsJSON , batchDependent . Version ,
5959 )
6060 if err != nil {
6161 var mysqlErr * mysql.MySQLError
@@ -67,3 +67,41 @@ func (s *batchDependentStore) Create(ctx context.Context, batchDependent entity.
6767
6868 return nil
6969}
70+
71+ // UpdateDependents updates the dependents of a batch dependent if the current version matches the expected version.
72+ // If versions do not match, returns ErrVersionMismatch.
73+ // The implementation increments the version by 1 atomically with the dependents update.
74+ func (s * batchDependentStore ) UpdateDependents (ctx context.Context , batchID string , version int32 , dependents []string ) error {
75+ dependentsJSON , err := json .Marshal (dependents )
76+ if err != nil {
77+ return fmt .Errorf ("failed to marshal dependents batchID=%s for UpdateDependents batch dependent entity: %w" , batchID , err )
78+ }
79+
80+ result , err := s .db .ExecContext (ctx ,
81+ "UPDATE batch_dependent SET dependents = ?, version = version + 1 WHERE batch_id = ? AND version = ?" ,
82+ dependentsJSON , batchID , version ,
83+ )
84+ if err != nil {
85+ return fmt .Errorf (
86+ "failed to update batch dependent dependents for batchID=%q version=%d: %w" ,
87+ batchID , version , err ,
88+ )
89+ }
90+
91+ rowsAffected , err := result .RowsAffected ()
92+ if err != nil {
93+ return fmt .Errorf (
94+ "failed to get rows affected from update for batchID=%q version=%d: %w" ,
95+ batchID , version , err ,
96+ )
97+ }
98+
99+ if rowsAffected != 1 {
100+ return fmt .Errorf (
101+ "version mismatch for batch dependent update: batchID=%q expected_version=%d: %w" ,
102+ batchID , version , storage .ErrVersionMismatch ,
103+ )
104+ }
105+
106+ return nil
107+ }
0 commit comments