make sure no more than one session is active at once

problem: Unit tests use an in-memory database, but that only supports one concurrent connection at a time.

This pull request fixes the code so connections are only held open as shortly as possible, solving the dead-lock problem.