summaryrefslogtreecommitdiff
path: root/libmysqlpp/embeddedmy-server.cpp
blob: a0fc3e398f60ab8a3ddf4f637041a5e4a4fda4fa (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include "embeddedmy-server.h"
#include "embeddedmy-connection.h"
#include <stdexcept>
#include <buffer.h>
#include <mysql.h>
#include <boost/filesystem/convenience.hpp>
#include <fstream>

namespace MySQL {
	namespace Embedded {
		ServerPtr
		Server::get(const boost::filesystem::path & path, const std::vector<std::string> & extraOpts)
		{
			if (instance) {
				if (path == instance->path) {
					return instance;
				}
				throw std::runtime_error(stringbf("Only one embedded server per process. [old=%s, new=%s]", instance->path, path));
			}
			instance = new Server(path, extraOpts);
			return instance;
		}

		ServerPtr
		Server::getMock(const boost::filesystem::path & path)
		{
			boost::filesystem::create_directories(path / "mysql");
			if (instance) {
				if (path == instance->path && dynamic_cast<MockServer *>(instance)) {
					return instance;
				}
				throw std::runtime_error(stringbf("Only one embedded server per process. [old=%s, new=%s]", instance->path, path));
			}
			auto i = new MockServer(path);
			i->initialize();
			return (instance = i);
		}

		Server::Server(const boost::filesystem::path & p, const std::vector<std::string> & extraOpts) :
			path(p)
		{
			const auto datadir = stringbf("--datadir=%s", path.string());
			std::vector<const char *> opts;
			opts.push_back(typeid(this).name());
			opts.push_back(datadir.c_str());
			for (auto & opt : extraOpts) {
				opts.push_back(opt.c_str());
			}
			opts.push_back(nullptr);
			static const char * groups[] = { NULL };
			mysql_library_init(opts.size() - 1, (char**)&opts.front(), (char**)groups);
		}

		Server::~Server()
		{
			mysql_library_end();
			instance = nullptr;
		}

		MockServer::MockServer(const boost::filesystem::path & p) :
			Server(p, { "--bootstrap" })
		{
		}

		void
		MockServer::initialize()
		{
			Connection initialize(this, "mysql");
			std::ifstream sql1("/usr/share/mysql/mysql_system_tables.sql");
			initialize.executeScript(sql1, path);
			std::ifstream sql2("/usr/share/mysql/mysql_system_tables_data.sql");
			initialize.executeScript(sql2, path);
		}

		MockServer::~MockServer()
		{
			boost::filesystem::remove_all(path);
		}

		Server * Server::instance = nullptr;
	}
}