HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

What is the fastest way to reset SQL Server database if you can not use RESTORE?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
canthewhatyousqlrestorewaydatabasefastestserver

Problem

I have integration tests that require test database to function.

Since tests should generally be independent, I reset the database in the beginning of each
test.

I can not use RESTORE, since some parts of architecture (which I do not control) are caching the connections, and will fail with connection lost on next call.

Right now I am creating a snapshot, then calling DELETE + INSERT on each table to synchronize data with snapshot. However, it takes 1 second per reset which is way too much (150 tests = 150 seconds). I have a lot of tables, but they are almost empty so there is no reason for it to be so slow.

So how can I replace database with its previous version in less than 1 second without losing connections?

My next idea would be to add some kind of change tracking since each test only affects some tables, but it would make reset code even more complicated.

UPDATE: I added SET STATISTICS TIME ON and I am getting

SQL Server parse and compile time: 
   CPU time = 327 ms, elapsed time = 343 ms.


for my reset SP. I assume it is due to ALTER TABLE ... NOCHECK CONSTRAINT ALL calls in the beginning of the SP. I wonder if it is possible to suppress recompilation in this case.

Solution

I know it's an old topic but times have changed and here is what is possible now.

-
You could create and use a dockerimage with the Database State you need for the tests and run a new container for eacht test.
Pro: You can run multiple tests in parallel because you have more than one database
Pro: You can be sure you'll get the desired state!
Con: If you don't run it in parallel the Container Startup could take a while

-
You can create a Dump and reset the database with this dump before each test
Pro: You can be sure you'll get the desired state!
Pro/Con: (Depending of the amount of data) the reset may take a while

-
Combine both ways and run the Tests in Parallel. You could keep the prepatched Docker container per thread/process/cpu/whatever and reset it with the dump between each test. This may be faster depending on the amount of data as well

Depending on your setup you could manage the Containers with tools like "testcontainers" if you want to make sure the containers are stopped afterwards

Context

StackExchange Database Administrators Q#11547, answer score: 2

Revisions (0)

No revisions yet.