Skip to content

Use upsert statement when inserting to postgres state store #105

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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);
);
Loading