Trying to reset primary keys

16 views
Skip to first unread message

Mitch

unread,
May 20, 2021, 1:11:33 PM5/20/21
to pgTAP Users
Hello folks, it's lovely to be part of your community.
I was wondering if you could help me with a rollback issue.

I have a test suite that currently asserts that an INSERT query doesn't throw an error.
I also have another assertion that checks the number of rows and the primary keys of the newly inserted rows. This works fine on the first test run.
On subsequent runs these tests fail because the rollback appears to truncate the data but does not reset the primary keys in the table.
Is this behaviour deliberate or am I missing something from my test setup ?
Ideally I'd like to have a totally reset db state between each test run so I'm entirely confident about the state of the database.
Any help will be much appreciated!
Cheers Mitch

Kyle Jensen

unread,
May 20, 2021, 2:06:08 PM5/20/21
to Mitch, pgTAP Users
Hi Mitch, pgtap doesn’t reset your database or alter your sequences. You can do that yourself if you want. When I write a test as you’re describing I do not check the exact values of the primary keys. I would instead check a row count or similar.  This is less fragile I think

Sincerely,
Kyle 


--
You received this message because you are subscribed to the Google Groups "pgTAP Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pgtap-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/pgtap-users/d3728363-ed4b-46cc-831b-07d4113d9f1bn%40googlegroups.com.

David E. Wheeler

unread,
May 20, 2021, 2:30:56 PM5/20/21
to Mitch, pgTAP Users
I assume you’re using SERIAL columns for your primary keys. They use a sequence, and in order for sequences to be unique across transactions and connections, their increment is not transactional. I recommend against that practice these days, but you can work around this by resetting the sequence at the start of your tests. Something like:

ALTER SEQUENCE foo_id_seq RESTART WITH 1;

HTH,

David

signature.asc

Nasby, Jim

unread,
May 20, 2021, 7:03:13 PM5/20/21
to David E. Wheeler, Mitch, pgTAP Users
A key concept with pgTap is to avoid testing that Postgres itself works. In this case, you're in essence testing that sequences work, and that you have a default value for the PK field, and that defaults work. But the only thing you really need to check is that you have the appropriate default value for the PK column. You can use col_default_is() to do that.
--
You received this message because you are subscribed to the Google Groups "pgTAP Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pgtap-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/pgtap-users/7EE968B7-3CAE-429B-8D64-524F71587B1D%40justatheory.com.

Reply all
Reply to author
Forward
0 new messages