jdreaver / eventful

Event Sourcing library for Haskell
MIT License
106 stars 22 forks source link

How does the sequence number of a new event get computed? #28

Closed JBetz closed 5 years ago

JBetz commented 5 years ago

Specifically, for the postgres backend.

The problem: I tried dropping my events table, then importing a bunch of rows from a csv, and subsequent writes failed because it was trying to insert an event with sequence_number equal to 1. A similar thing happens if I truncate the table, as it will try to insert the next event with whatever the max sequence_number was before it got truncated. Furthermore, the sequence_number continues to be incremented even when the inserts fail, so it seems to be completely independent of whatever exists in the table.

Hence my question: how does the sequence number get computed, and how can I get it to use the max value of the existing entries instead?

The use case is for importing an event log from a production database to debug locally. As it is, I can't get it to work unless I truncate my local database after it has at least as many entries as the one I'm importing, or if I run enough inserts that fail until they are equal.

jdreaver commented 5 years ago

sequence_number is the auto-incrementing primary key of the events table. Auto-incrementing primary keys in postgres are backed by a postgres sequence (see https://www.postgresql.org/docs/current/sql-createsequence.html).

After importing your events, you should be able to use pg_catalog.set_val on the sequence to update it. Something like this:

SELECT pg_catalog.setval('events_sequence_number_seq', (SELECT MAX(sequence_number) FROM events), true);

(The exact name of the sequence and your table depends on your events entity configuration, and possibly your version of postgres, but you should be able to poke around the generated schema of your events table to find the sequence.)

JBetz commented 5 years ago

That worked -- thanks!