ClickHouse/programs/odbc-bridge/ODBCConnectionFactory.h

83 lines
1.8 KiB
C++
Raw Normal View History

2021-03-31 12:41:12 +00:00
#pragma once
#include <common/logger_useful.h>
#include <nanodbc/nanodbc.h>
#include <mutex>
2021-04-13 18:52:59 +00:00
#include <common/BorrowedObjectPool.h>
2021-03-31 12:41:12 +00:00
#include <unordered_map>
namespace nanodbc
{
static constexpr inline auto ODBC_CONNECT_TIMEOUT = 100;
using ConnectionPtr = std::shared_ptr<nanodbc::connection>;
using Pool = BorrowedObjectPool<ConnectionPtr>;
using PoolPtr = std::shared_ptr<Pool>;
class ConnectionHolder
{
public:
ConnectionHolder(const std::string & connection_string_, PoolPtr pool_) : connection_string(connection_string_), pool(pool_) {}
~ConnectionHolder()
{
2021-04-02 21:26:19 +00:00
if (connection)
pool->returnObject(std::move(connection));
2021-03-31 12:41:12 +00:00
}
nanodbc::connection & operator*()
{
2021-04-02 21:26:19 +00:00
if (!connection)
2021-03-31 12:41:12 +00:00
{
pool->borrowObject(connection, [&]()
{
return std::make_shared<nanodbc::connection>(connection_string, ODBC_CONNECT_TIMEOUT);
});
}
return *connection;
}
private:
std::string connection_string;
PoolPtr pool;
ConnectionPtr connection;
};
}
namespace DB
{
class ODBCConnectionFactory final : private boost::noncopyable
{
public:
static ODBCConnectionFactory & instance()
{
static ODBCConnectionFactory ret;
return ret;
}
2021-04-06 18:59:34 +00:00
nanodbc::ConnectionHolder get(const std::string & connection_string, size_t pool_size)
2021-03-31 12:41:12 +00:00
{
std::lock_guard lock(mutex);
if (!factory.count(connection_string))
factory.emplace(std::make_pair(connection_string, std::make_shared<nanodbc::Pool>(pool_size)));
return nanodbc::ConnectionHolder(connection_string, factory[connection_string]);
}
private:
2021-04-06 18:59:34 +00:00
/// [connection_settings_string] -> [connection_pool]
2021-03-31 12:41:12 +00:00
using PoolFactory = std::unordered_map<std::string, nanodbc::PoolPtr>;
PoolFactory factory;
std::mutex mutex;
};
}