summaryrefslogtreecommitdiff
path: root/test/testdb-postgresql.cpp
blob: c59640af51fdb0b63a168255c0207f4397379661 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include "testdb-postgresql.h"
#include <compileTimeFormatter.h>
#include <cstdlib>
#include <fstream>
#include <helpers.h>
#include <output/pq/pqConn.h>

namespace MyGrate {
	namespace Testing {
		const auto CONNSTR {MyGrate::getenv("MYGRATE_POSTGRESQL_CONNSTR", "user=postgres")};
		std::size_t PqConnDB::mocknum;

		PqConnDB::PqConnDB() : PqConn(CONNSTR), mockname {scprintf<"mygrate_test_%?_%?">(getpid(), mocknum++)}
		{
			query(("DROP DATABASE IF EXISTS " + mockname).c_str());
			query(("CREATE DATABASE " + mockname).c_str());
		}

		PqConnDB::PqConnDB(const std::string & schemaFile) : PqConnDB()
		{
			auto mdb = mock();

			std::stringstream buffer;
			buffer << std::ifstream(schemaFile).rdbuf();

			mdb.query(buffer.str().c_str());
		}

		PqConnDB::~PqConnDB()
		{
			query(("DROP DATABASE IF EXISTS " + mockname).c_str());
			mockname.clear();
		}

		Output::Pq::PqConn
		PqConnDB::mock() const
		{
			return PqConn {scprintf<"%? dbname=%?">(CONNSTR, mockname).c_str()};
		}
	}
}