2011-10-24 12:10:59 +00:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <fcntl.h>
|
|
|
|
|
|
|
|
#include <DB/IO/ReadBufferFromFileDescriptor.h>
|
2016-01-21 01:47:28 +00:00
|
|
|
#include <DB/Common/CurrentMetrics.h>
|
2011-10-24 12:10:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
namespace DB
|
|
|
|
{
|
|
|
|
|
2016-01-11 21:46:36 +00:00
|
|
|
namespace ErrorCodes
|
|
|
|
{
|
|
|
|
extern const int FILE_DOESNT_EXIST;
|
|
|
|
extern const int CANNOT_OPEN_FILE;
|
|
|
|
extern const int CANNOT_CLOSE_FILE;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2011-10-24 12:10:59 +00:00
|
|
|
/** Принимает имя файла. Самостоятельно открывает и закрывает файл.
|
|
|
|
*/
|
|
|
|
class ReadBufferFromFile : public ReadBufferFromFileDescriptor
|
|
|
|
{
|
|
|
|
private:
|
|
|
|
std::string file_name;
|
2016-01-21 01:47:28 +00:00
|
|
|
CurrentMetrics::Increment metric_increment{CurrentMetrics::OpenFileForRead};
|
2015-12-13 08:51:28 +00:00
|
|
|
|
2011-10-24 12:10:59 +00:00
|
|
|
public:
|
2014-01-04 04:52:22 +00:00
|
|
|
ReadBufferFromFile(const std::string & file_name_, size_t buf_size = DBMS_DEFAULT_BUFFER_SIZE, int flags = -1,
|
2014-04-08 07:31:51 +00:00
|
|
|
char * existing_memory = nullptr, size_t alignment = 0)
|
2014-01-03 06:31:32 +00:00
|
|
|
: ReadBufferFromFileDescriptor(-1, buf_size, existing_memory, alignment), file_name(file_name_)
|
2011-10-24 12:10:59 +00:00
|
|
|
{
|
2014-01-03 08:20:13 +00:00
|
|
|
ProfileEvents::increment(ProfileEvents::FileOpen);
|
|
|
|
|
2014-01-04 04:52:22 +00:00
|
|
|
fd = open(file_name.c_str(), flags == -1 ? O_RDONLY : flags);
|
2013-11-20 00:49:47 +00:00
|
|
|
|
2011-10-24 12:10:59 +00:00
|
|
|
if (-1 == fd)
|
2012-04-14 11:45:27 +00:00
|
|
|
throwFromErrno("Cannot open file " + file_name, errno == ENOENT ? ErrorCodes::FILE_DOESNT_EXIST : ErrorCodes::CANNOT_OPEN_FILE);
|
2011-10-24 12:10:59 +00:00
|
|
|
}
|
|
|
|
|
2015-12-13 08:51:28 +00:00
|
|
|
/// Использовать уже открытый файл.
|
|
|
|
ReadBufferFromFile(int fd, size_t buf_size = DBMS_DEFAULT_BUFFER_SIZE, int flags = -1,
|
|
|
|
char * existing_memory = nullptr, size_t alignment = 0)
|
|
|
|
: ReadBufferFromFileDescriptor(fd, buf_size, existing_memory, alignment), file_name("(fd = " + toString(fd) + ")")
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2013-11-20 00:49:47 +00:00
|
|
|
virtual ~ReadBufferFromFile()
|
2011-10-24 12:10:59 +00:00
|
|
|
{
|
2015-12-13 08:51:28 +00:00
|
|
|
if (fd < 0)
|
|
|
|
return;
|
|
|
|
|
|
|
|
::close(fd);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Закрыть файл раньше вызова деструктора.
|
|
|
|
void close()
|
|
|
|
{
|
|
|
|
if (0 != ::close(fd))
|
|
|
|
throw Exception("Cannot close file", ErrorCodes::CANNOT_CLOSE_FILE);
|
|
|
|
|
|
|
|
fd = -1;
|
2016-01-21 01:47:28 +00:00
|
|
|
metric_increment.destroy();
|
2011-10-24 12:10:59 +00:00
|
|
|
}
|
|
|
|
|
2016-03-07 04:36:54 +00:00
|
|
|
std::string getFileName() const override
|
2011-10-24 12:10:59 +00:00
|
|
|
{
|
|
|
|
return file_name;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
}
|