Skip to content

Commit

Permalink
use upsert when inserting to postgres state store
Browse files Browse the repository at this point in the history
  • Loading branch information
sdil committed Dec 17, 2024
1 parent e1a6c8a commit 0d98428
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 11 deletions.
19 changes: 8 additions & 11 deletions plugins/statestore/postgres/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,15 +143,6 @@ func (s *DurableStore) WriteState(ctx context.Context, state *egopb.DurableState
return fmt.Errorf("failed to obtain a database transaction: %w", err)
}

query, args, err := s.sb.Delete(tableName).Where(sq.Eq{"persistence_id": state.GetPersistenceId()}).ToSql()
if err != nil {
return fmt.Errorf("failed to build the delete sql statement: %w", err)
}

if _, err := s.db.Exec(ctx, query, args...); err != nil {
return fmt.Errorf("failed to delete durable state from the database: %w", err)
}

bytea, _ := proto.Marshal(state.GetResultingState())
manifest := string(state.GetResultingState().ProtoReflect().Descriptor().FullName())

Expand All @@ -165,9 +156,15 @@ func (s *DurableStore) WriteState(ctx context.Context, state *egopb.DurableState
manifest,
state.GetTimestamp(),
state.GetShard(),
)
).Suffix("ON CONFLICT (persistence_id) " +
"DO UPDATE SET " +
"version_number = excluded.version_number," +
"state_payload = excluded.state_payload, " +
"state_manifest = excluded.state_manifest," +
"timestamp = excluded.timestamp",
)

query, args, err = statement.ToSql()
query, args, err := statement.ToSql()
if err != nil {
return fmt.Errorf("unable to build sql insert statement: %w", err)
}
Expand Down
1 change: 1 addition & 0 deletions resources/durablestore_postgres.sql
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,5 @@ CREATE TABLE IF NOT EXISTS states_store
shard_number BIGINT NOT NULL,

PRIMARY KEY (persistence_id, version_number)
CONSTRAINT unique_persistence_id UNIQUE (persistence_id)
);

0 comments on commit 0d98428

Please sign in to comment.