Skip to content

Commit

Permalink
refactor: use upsert statement when inserting to postgres state store (
Browse files Browse the repository at this point in the history
…#105)

Signed-off-by: Mohamad Fadhil <[email protected]>
  • Loading branch information
sdil authored Dec 17, 2024
1 parent 7574335 commit c7cf58d
Show file tree
Hide file tree
Showing 2 changed files with 10 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 @@ -135,15 +135,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 @@ -157,9 +148,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
2 changes: 2 additions & 0 deletions resources/durablestore_postgres.sql
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,6 @@ CREATE TABLE IF NOT EXISTS states_store
shard_number BIGINT NOT NULL,

PRIMARY KEY (persistence_id, version_number)
CREATE INDEX IF NOT EXISTS idx_states_store_persistence_id ON events_store(persistence_id);
CREATE INDEX IF NOT EXISTS idx_states_store_version_number ON events_store(version_number);
);

0 comments on commit c7cf58d

Please sign in to comment.