I had a similar situation in one of the projects. A separate test database is created before starting the tests and the structure of the prod database is copied into it and filled with fake data. Then it is removed.
Tests use a mock object to work with a database, where a test database is substituted instead of a prod.
Sometimes you need to run non-destructive tests on existing records in a prod or stage database; or if it is not convenient to update the test data - you can switch the used database.
Never try to unify something without having a unified thing. Refactoring or optimization is done only if there is working code to compare the results. In your case, write a few examples by hand and then try to find a common denominator. The transition should always be from simple to complex.