ClickHouse/src/Databases/DatabaseAtomic.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

606 lines
23 KiB
C++
Raw Normal View History

2019-10-23 13:46:38 +00:00
#include <Databases/DatabaseAtomic.h>
2019-10-30 12:17:52 +00:00
#include <Databases/DatabaseOnDisk.h>
#include <Databases/DatabaseReplicated.h>
2019-11-11 11:34:03 +00:00
#include <IO/ReadHelpers.h>
#include <IO/WriteHelpers.h>
2020-11-24 10:24:39 +00:00
#include <IO/ReadBufferFromFile.h>
2020-01-27 20:31:39 +00:00
#include <Parsers/formatAST.h>
2022-04-11 12:32:55 +00:00
#include <Common/atomicRename.h>
2022-08-15 10:30:47 +00:00
#include <Common/filesystemHelpers.h>
2020-04-10 01:35:37 +00:00
#include <Storages/StorageMaterializedView.h>
#include <Interpreters/Context.h>
2020-07-16 14:25:39 +00:00
#include <Interpreters/ExternalDictionariesLoader.h>
2020-05-17 01:01:26 +00:00
#include <filesystem>
2020-11-20 16:06:27 +00:00
#include <Interpreters/DDLTask.h>
2019-10-23 13:46:38 +00:00
2021-04-30 16:48:42 +00:00
namespace fs = std::filesystem;
2019-10-23 13:46:38 +00:00
namespace DB
{
2019-11-11 11:34:03 +00:00
namespace ErrorCodes
{
extern const int UNKNOWN_TABLE;
2020-07-17 13:11:44 +00:00
extern const int UNKNOWN_DATABASE;
2019-11-11 11:34:03 +00:00
extern const int TABLE_ALREADY_EXISTS;
2020-03-23 00:12:13 +00:00
extern const int CANNOT_ASSIGN_ALTER;
2020-04-10 23:02:15 +00:00
extern const int DATABASE_NOT_EMPTY;
2020-04-11 15:38:41 +00:00
extern const int NOT_IMPLEMENTED;
2020-07-02 20:39:31 +00:00
extern const int FILE_ALREADY_EXISTS;
2020-07-16 21:41:26 +00:00
extern const int INCORRECT_QUERY;
extern const int ABORTED;
2019-11-11 11:34:03 +00:00
}
2019-10-23 13:46:38 +00:00
2020-04-01 22:41:29 +00:00
class AtomicDatabaseTablesSnapshotIterator final : public DatabaseTablesSnapshotIterator
{
public:
2020-04-08 01:02:00 +00:00
explicit AtomicDatabaseTablesSnapshotIterator(DatabaseTablesSnapshotIterator && base)
2020-04-01 22:41:29 +00:00
: DatabaseTablesSnapshotIterator(std::move(base)) {}
UUID uuid() const override { return table()->getStorageID().uuid; }
};
DatabaseAtomic::DatabaseAtomic(String name_, String metadata_path_, UUID uuid, const String & logger_name, ContextPtr context_)
: DatabaseOrdinary(name_, metadata_path_, "store/", logger_name, context_)
2021-05-08 10:59:55 +00:00
, path_to_table_symlinks(fs::path(getContext()->getPath()) / "data" / escapeForFileName(name_) / "")
, path_to_metadata_symlink(fs::path(getContext()->getPath()) / "metadata" / escapeForFileName(name_))
2020-07-02 20:39:31 +00:00
, db_uuid(uuid)
2019-10-23 13:46:38 +00:00
{
2020-07-02 20:39:31 +00:00
assert(db_uuid != UUIDHelpers::Nil);
fs::create_directories(fs::path(getContext()->getPath()) / "metadata");
2021-04-30 16:48:42 +00:00
fs::create_directories(path_to_table_symlinks);
2020-07-07 12:11:58 +00:00
tryCreateMetadataSymlink();
2019-11-11 11:34:03 +00:00
}
DatabaseAtomic::DatabaseAtomic(String name_, String metadata_path_, UUID uuid, ContextPtr context_)
2020-09-15 13:30:30 +00:00
: DatabaseAtomic(name_, std::move(metadata_path_), uuid, "DatabaseAtomic (" + name_ + ")", context_)
{
}
String DatabaseAtomic::getTableDataPath(const String & table_name) const
2019-11-11 11:34:03 +00:00
{
2019-12-02 19:11:18 +00:00
std::lock_guard lock(mutex);
2019-11-11 11:34:03 +00:00
auto it = table_name_to_path.find(table_name);
if (it == table_name_to_path.end())
throw Exception(ErrorCodes::UNKNOWN_TABLE, "Table {} not found in database {}", table_name, database_name);
2020-01-16 18:13:18 +00:00
assert(it->second != data_path && !it->second.empty());
return it->second;
2019-11-11 11:34:03 +00:00
}
String DatabaseAtomic::getTableDataPath(const ASTCreateQuery & query) const
2019-11-11 11:34:03 +00:00
{
2020-04-06 23:22:44 +00:00
auto tmp = data_path + DatabaseCatalog::getPathForUUID(query.uuid);
2020-01-16 18:13:18 +00:00
assert(tmp != data_path && !tmp.empty());
return tmp;
2019-11-11 11:34:03 +00:00
}
void DatabaseAtomic::drop(ContextPtr)
2019-11-11 11:34:03 +00:00
{
2022-06-28 14:25:29 +00:00
assert(TSA_SUPPRESS_WARNING_FOR_READ(tables).empty());
2020-07-02 20:39:31 +00:00
try
{
2021-04-30 17:20:53 +00:00
fs::remove(path_to_metadata_symlink);
fs::remove_all(path_to_table_symlinks);
2020-07-02 20:39:31 +00:00
}
catch (...)
{
2023-01-16 23:11:59 +00:00
LOG_WARNING(log, getCurrentExceptionMessageAndPattern(/* with_stacktrace */ true));
2020-07-02 20:39:31 +00:00
}
2021-04-30 17:20:53 +00:00
fs::remove_all(getMetadataPath());
2019-11-11 11:34:03 +00:00
}
void DatabaseAtomic::attachTable(ContextPtr /* context_ */, const String & name, const StoragePtr & table, const String & relative_table_path)
2019-11-11 11:34:03 +00:00
{
2020-01-16 18:13:18 +00:00
assert(relative_table_path != data_path && !relative_table_path.empty());
2020-04-06 23:22:44 +00:00
DetachedTables not_in_use;
2022-06-27 20:48:27 +00:00
std::lock_guard lock(mutex);
not_in_use = cleanupDetachedTables();
2020-07-07 12:11:58 +00:00
auto table_id = table->getStorageID();
assertDetachedTableNotInUse(table_id.uuid);
2022-06-27 20:48:27 +00:00
DatabaseOrdinary::attachTableUnlocked(name, table);
2019-12-02 19:11:18 +00:00
table_name_to_path.emplace(std::make_pair(name, relative_table_path));
2019-10-23 13:46:38 +00:00
}
StoragePtr DatabaseAtomic::detachTable(ContextPtr /* context */, const String & name)
2019-11-11 11:34:03 +00:00
{
2020-04-22 20:43:10 +00:00
DetachedTables not_in_use;
2022-06-27 20:48:27 +00:00
std::lock_guard lock(mutex);
auto table = DatabaseOrdinary::detachTableUnlocked(name);
2020-03-23 00:12:13 +00:00
table_name_to_path.erase(name);
detached_tables.emplace(table->getStorageID().uuid, table);
2023-02-19 22:15:09 +00:00
not_in_use = cleanupDetachedTables();
2020-03-23 00:12:13 +00:00
return table;
2019-11-11 11:34:03 +00:00
}
2019-10-23 13:46:38 +00:00
2022-06-23 07:59:13 +00:00
void DatabaseAtomic::dropTable(ContextPtr local_context, const String & table_name, bool sync)
2020-01-22 11:30:11 +00:00
{
auto table = tryGetTable(table_name, local_context);
/// Remove the inner table (if any) to avoid deadlock
/// (due to attempt to execute DROP from the worker thread)
if (table)
2022-06-23 07:59:13 +00:00
table->dropInnerTableIfAny(sync, local_context);
else
2022-07-29 16:33:16 +00:00
throw Exception(ErrorCodes::UNKNOWN_TABLE, "Table {}.{} doesn't exist", backQuote(getDatabaseName()), backQuote(table_name));
2022-07-29 16:33:16 +00:00
dropTableImpl(local_context, table_name, sync);
}
void DatabaseAtomic::dropTableImpl(ContextPtr local_context, const String & table_name, bool sync)
{
2020-01-22 11:30:11 +00:00
String table_metadata_path = getObjectMetadataPath(table_name);
2020-03-23 00:12:13 +00:00
String table_metadata_path_drop;
2022-07-29 16:33:16 +00:00
StoragePtr table;
2020-03-23 00:12:13 +00:00
{
2022-06-27 20:48:27 +00:00
std::lock_guard lock(mutex);
2022-07-29 16:33:16 +00:00
table = getTableUnlocked(table_name);
2020-03-23 00:12:13 +00:00
table_metadata_path_drop = DatabaseCatalog::instance().getPathForDroppedMetadata(table->getStorageID());
auto txn = local_context->getZooKeeperMetadataTransaction();
if (txn && !local_context->isInternalSubquery())
2020-11-29 11:45:32 +00:00
txn->commit(); /// Commit point (a sort of) for Replicated database
/// NOTE: replica will be lost if server crashes before the following rename
2021-02-19 23:41:58 +00:00
/// We apply changes in ZooKeeper before applying changes in local metadata file
/// to reduce probability of failures between these operations
/// (it's more likely to lost connection, than to fail before applying local changes).
2020-11-29 11:45:32 +00:00
/// TODO better detection and recovery
2020-11-24 10:24:39 +00:00
2021-04-30 17:20:53 +00:00
fs::rename(table_metadata_path, table_metadata_path_drop); /// Mark table as dropped
2022-06-27 20:48:27 +00:00
DatabaseOrdinary::detachTableUnlocked(table_name); /// Should never throw
2020-03-23 00:12:13 +00:00
table_name_to_path.erase(table_name);
}
2021-04-27 19:09:03 +00:00
2020-11-01 17:38:43 +00:00
if (table->storesDataOnDisk())
2021-02-20 22:13:14 +00:00
tryRemoveSymlink(table_name);
2020-04-22 20:43:10 +00:00
/// Notify DatabaseCatalog that table was dropped. It will remove table data in background.
/// Cleanup is performed outside of database to allow easily DROP DATABASE without waiting for cleanup to complete.
2022-06-23 07:59:13 +00:00
DatabaseCatalog::instance().enqueueDroppedTableCleanup(table->getStorageID(), table, table_metadata_path_drop, sync);
2020-01-22 11:30:11 +00:00
}
void DatabaseAtomic::renameTable(ContextPtr local_context, const String & table_name, IDatabase & to_database,
2020-07-16 21:41:26 +00:00
const String & to_table_name, bool exchange, bool dictionary)
2022-06-27 20:48:27 +00:00
TSA_NO_THREAD_SAFETY_ANALYSIS /// TSA does not support conditional locking
2019-11-11 14:28:28 +00:00
{
if (typeid(*this) != typeid(to_database))
2019-12-02 19:11:18 +00:00
{
if (typeid_cast<DatabaseOrdinary *>(&to_database))
{
/// Allow moving tables between Atomic and Ordinary (with table lock)
DatabaseOnDisk::renameTable(local_context, table_name, to_database, to_table_name, exchange, dictionary);
return;
}
if (!allowMoveTableToOtherDatabaseEngine(to_database))
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Moving tables between databases of different engines is not supported");
2019-12-02 19:11:18 +00:00
}
2020-07-16 21:41:26 +00:00
2022-04-11 12:32:55 +00:00
if (exchange && !supportsAtomicRename())
2020-11-24 10:24:39 +00:00
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "RENAME EXCHANGE is not supported");
2020-07-16 21:41:26 +00:00
2020-03-31 20:38:05 +00:00
auto & other_db = dynamic_cast<DatabaseAtomic &>(to_database);
2020-04-10 01:35:37 +00:00
bool inside_database = this == &other_db;
2019-11-11 14:28:28 +00:00
2020-03-23 00:12:13 +00:00
String old_metadata_path = getObjectMetadataPath(table_name);
2020-03-23 22:40:40 +00:00
String new_metadata_path = to_database.getObjectMetadataPath(to_table_name);
2019-11-11 14:28:28 +00:00
2022-06-27 20:48:27 +00:00
auto detach = [](DatabaseAtomic & db, const String & table_name_, bool has_symlink) TSA_REQUIRES(db.mutex)
2020-03-23 00:12:13 +00:00
{
2020-07-16 21:41:26 +00:00
auto it = db.table_name_to_path.find(table_name_);
String table_data_path_saved;
/// Path can be not set for DDL dictionaries, but it does not matter for StorageDictionary.
if (it != db.table_name_to_path.end())
table_data_path_saved = it->second;
2021-04-21 13:45:13 +00:00
assert(!table_data_path_saved.empty());
2020-03-31 20:38:05 +00:00
db.tables.erase(table_name_);
db.table_name_to_path.erase(table_name_);
2020-11-01 17:38:43 +00:00
if (has_symlink)
2020-07-16 21:41:26 +00:00
db.tryRemoveSymlink(table_name_);
2020-04-07 14:05:51 +00:00
return table_data_path_saved;
2020-03-31 20:38:05 +00:00
};
2022-06-27 20:48:27 +00:00
auto attach = [](DatabaseAtomic & db, const String & table_name_, const String & table_data_path_, const StoragePtr & table_) TSA_REQUIRES(db.mutex)
2020-03-31 20:38:05 +00:00
{
db.tables.emplace(table_name_, table_);
2020-07-16 21:41:26 +00:00
if (table_data_path_.empty())
return;
2020-03-31 20:38:05 +00:00
db.table_name_to_path.emplace(table_name_, table_data_path_);
2020-11-01 17:38:43 +00:00
if (table_->storesDataOnDisk())
db.tryCreateSymlink(table_name_, table_data_path_);
2020-03-31 20:38:05 +00:00
};
2020-04-11 15:38:41 +00:00
auto assert_can_move_mat_view = [inside_database](const StoragePtr & table_)
2020-04-10 01:35:37 +00:00
{
if (inside_database)
return;
if (const auto * mv = dynamic_cast<const StorageMaterializedView *>(table_.get()))
if (mv->hasInnerTable())
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Cannot move MaterializedView with inner table to other database");
2020-04-10 01:35:37 +00:00
};
2020-03-31 20:38:05 +00:00
String table_data_path;
String other_table_data_path;
if (inside_database && table_name == to_table_name)
return;
std::unique_lock<std::mutex> db_lock;
std::unique_lock<std::mutex> other_db_lock;
if (inside_database)
db_lock = std::unique_lock{mutex};
2021-06-18 20:59:35 +00:00
else if (this < &other_db)
2020-03-31 20:38:05 +00:00
{
db_lock = std::unique_lock{mutex};
other_db_lock = std::unique_lock{other_db.mutex};
2020-03-23 00:12:13 +00:00
}
else
{
2020-03-31 20:38:05 +00:00
other_db_lock = std::unique_lock{other_db.mutex};
db_lock = std::unique_lock{mutex};
2020-03-23 00:12:13 +00:00
}
2020-03-31 20:38:05 +00:00
if (!exchange)
2022-06-27 20:48:27 +00:00
other_db.checkMetadataFilenameAvailabilityUnlocked(to_table_name);
2022-06-27 20:48:27 +00:00
StoragePtr table = getTableUnlocked(table_name);
2021-04-22 14:09:30 +00:00
if (dictionary && !table->isDictionary())
throw Exception(ErrorCodes::INCORRECT_QUERY, "Use RENAME/EXCHANGE TABLE (instead of RENAME/EXCHANGE DICTIONARY) for tables");
2021-04-22 14:09:30 +00:00
2022-04-13 14:51:59 +00:00
StorageID old_table_id = table->getStorageID();
StorageID new_table_id = {other_db.database_name, to_table_name, old_table_id.uuid};
table->checkTableCanBeRenamed({new_table_id});
2020-04-11 15:38:41 +00:00
assert_can_move_mat_view(table);
2020-04-10 00:08:43 +00:00
StoragePtr other_table;
2022-04-13 14:51:59 +00:00
StorageID other_table_new_id = StorageID::createEmpty();
2020-04-10 00:08:43 +00:00
if (exchange)
2020-04-10 01:35:37 +00:00
{
2022-06-27 20:48:27 +00:00
other_table = other_db.getTableUnlocked(to_table_name);
if (dictionary && !other_table->isDictionary())
throw Exception(ErrorCodes::INCORRECT_QUERY, "Use RENAME/EXCHANGE TABLE (instead of RENAME/EXCHANGE DICTIONARY) for tables");
2022-04-13 14:51:59 +00:00
other_table_new_id = {database_name, table_name, other_table->getStorageID().uuid};
other_table->checkTableCanBeRenamed(other_table_new_id);
2020-04-11 15:38:41 +00:00
assert_can_move_mat_view(other_table);
2020-04-10 01:35:37 +00:00
}
2020-04-10 00:08:43 +00:00
2020-04-22 20:43:10 +00:00
/// Table renaming actually begins here
auto txn = local_context->getZooKeeperMetadataTransaction();
if (txn && !local_context->isInternalSubquery())
2020-11-29 11:45:32 +00:00
txn->commit(); /// Commit point (a sort of) for Replicated database
/// NOTE: replica will be lost if server crashes before the following rename
/// TODO better detection and recovery
2020-11-24 10:24:39 +00:00
2020-03-31 20:38:05 +00:00
if (exchange)
renameExchange(old_metadata_path, new_metadata_path);
else
renameNoReplace(old_metadata_path, new_metadata_path);
2023-03-06 22:44:41 +00:00
/// After metadata was successfully moved, the following methods should not throw (if they do, it's a logical error)
2020-11-01 17:38:43 +00:00
table_data_path = detach(*this, table_name, table->storesDataOnDisk());
2020-03-31 20:38:05 +00:00
if (exchange)
2020-11-01 17:38:43 +00:00
other_table_data_path = detach(other_db, to_table_name, other_table->storesDataOnDisk());
2020-03-31 20:38:05 +00:00
2022-04-13 14:51:59 +00:00
table->renameInMemory(new_table_id);
2020-03-31 20:38:05 +00:00
if (exchange)
2022-04-13 14:51:59 +00:00
other_table->renameInMemory(other_table_new_id);
2020-03-31 20:38:05 +00:00
if (!inside_database)
{
2020-07-16 21:41:26 +00:00
DatabaseCatalog::instance().updateUUIDMapping(old_table_id.uuid, other_db.shared_from_this(), table);
2020-03-31 20:38:05 +00:00
if (exchange)
DatabaseCatalog::instance().updateUUIDMapping(other_table->getStorageID().uuid, shared_from_this(), other_table);
}
attach(other_db, to_table_name, table_data_path, table);
if (exchange)
attach(*this, table_name, other_table_data_path, other_table);
2019-11-11 14:28:28 +00:00
}
2020-03-23 00:12:13 +00:00
void DatabaseAtomic::commitCreateTable(const ASTCreateQuery & query, const StoragePtr & table,
2020-11-20 16:06:27 +00:00
const String & table_metadata_tmp_path, const String & table_metadata_path,
ContextPtr query_context)
2020-03-23 00:12:13 +00:00
{
2020-04-06 23:22:44 +00:00
DetachedTables not_in_use;
2020-03-23 00:12:13 +00:00
auto table_data_path = getTableDataPath(query);
try
{
2022-06-27 20:48:27 +00:00
std::lock_guard lock{mutex};
if (query.getDatabase() != database_name)
2020-07-17 13:11:44 +00:00
throw Exception(ErrorCodes::UNKNOWN_DATABASE, "Database was renamed to `{}`, cannot create table in `{}`",
database_name, query.getDatabase());
2020-10-27 20:52:49 +00:00
/// Do some checks before renaming file from .tmp to .sql
not_in_use = cleanupDetachedTables();
assertDetachedTableNotInUse(query.uuid);
2022-06-22 16:31:42 +00:00
chassert(DatabaseCatalog::instance().hasUUIDMapping(query.uuid));
2020-11-20 16:06:27 +00:00
auto txn = query_context->getZooKeeperMetadataTransaction();
if (txn && !query_context->isInternalSubquery())
2020-11-29 11:45:32 +00:00
txn->commit(); /// Commit point (a sort of) for Replicated database
/// NOTE: replica will be lost if server crashes before the following renameNoReplace(...)
/// TODO better detection and recovery
2020-11-20 16:06:27 +00:00
2020-10-27 20:52:49 +00:00
/// It throws if `table_metadata_path` already exists (it's possible if table was detached)
renameNoReplace(table_metadata_tmp_path, table_metadata_path); /// Commit point (a sort of)
2022-06-27 20:48:27 +00:00
attachTableUnlocked(query.getTable(), table); /// Should never throw
table_name_to_path.emplace(query.getTable(), table_data_path);
2020-03-23 00:12:13 +00:00
}
catch (...)
{
2021-04-30 17:20:53 +00:00
fs::remove(table_metadata_tmp_path);
2020-03-23 00:12:13 +00:00
throw;
}
2020-11-01 17:38:43 +00:00
if (table->storesDataOnDisk())
tryCreateSymlink(query.getTable(), table_data_path);
2020-03-23 00:12:13 +00:00
}
2020-11-29 11:45:32 +00:00
void DatabaseAtomic::commitAlterTable(const StorageID & table_id, const String & table_metadata_tmp_path, const String & table_metadata_path,
const String & /*statement*/, ContextPtr query_context)
2020-03-23 00:12:13 +00:00
{
2020-09-19 14:19:06 +00:00
bool check_file_exists = true;
2020-07-17 13:11:44 +00:00
SCOPE_EXIT({ std::error_code code; if (check_file_exists) std::filesystem::remove(table_metadata_tmp_path, code); });
2020-03-23 00:12:13 +00:00
2022-06-27 20:48:27 +00:00
std::lock_guard lock{mutex};
auto actual_table_id = getTableUnlocked(table_id.table_name)->getStorageID();
2020-03-23 00:12:13 +00:00
if (table_id.uuid != actual_table_id.uuid)
throw Exception(ErrorCodes::CANNOT_ASSIGN_ALTER, "Cannot alter table because it was renamed");
2020-03-23 00:12:13 +00:00
auto txn = query_context->getZooKeeperMetadataTransaction();
if (txn && !query_context->isInternalSubquery())
2020-11-29 11:45:32 +00:00
txn->commit(); /// Commit point (a sort of) for Replicated database
/// NOTE: replica will be lost if server crashes before the following rename
/// TODO better detection and recovery
2020-11-24 10:24:39 +00:00
2020-09-19 14:19:06 +00:00
check_file_exists = renameExchangeIfSupported(table_metadata_tmp_path, table_metadata_path);
if (!check_file_exists)
2020-07-17 13:11:44 +00:00
std::filesystem::rename(table_metadata_tmp_path, table_metadata_path);
2020-03-23 00:12:13 +00:00
}
void DatabaseAtomic::assertDetachedTableNotInUse(const UUID & uuid)
{
2020-04-22 20:43:10 +00:00
/// Without this check the following race is possible since table RWLocks are not used:
/// 1. INSERT INTO table ...;
/// 2. DETACH TABLE table; (INSERT still in progress, it holds StoragePtr)
/// 3. ATTACH TABLE table; (new instance of Storage with the same UUID is created, instances share data on disk)
/// 4. INSERT INTO table ...; (both Storage instances writes data without any synchronization)
/// To avoid it, we remember UUIDs of detached tables and does not allow ATTACH table with such UUID until detached instance still in use.
if (detached_tables.contains(uuid))
2021-04-16 12:18:53 +00:00
throw Exception(ErrorCodes::TABLE_ALREADY_EXISTS, "Cannot attach table with UUID {}, "
"because it was detached but still used by some query. Retry later.", uuid);
}
2021-02-11 22:23:40 +00:00
void DatabaseAtomic::setDetachedTableNotInUseForce(const UUID & uuid)
{
2022-06-27 20:48:27 +00:00
std::lock_guard lock{mutex};
2021-02-11 22:23:40 +00:00
detached_tables.erase(uuid);
}
DatabaseAtomic::DetachedTables DatabaseAtomic::cleanupDetachedTables()
{
2020-04-06 23:22:44 +00:00
DetachedTables not_in_use;
auto it = detached_tables.begin();
while (it != detached_tables.end())
{
if (it->second.unique())
2020-04-06 23:22:44 +00:00
{
not_in_use.emplace(it->first, it->second);
it = detached_tables.erase(it);
2020-04-06 23:22:44 +00:00
}
else
++it;
}
2020-04-22 20:43:10 +00:00
/// It should be destroyed in caller with released database mutex
2020-04-06 23:22:44 +00:00
return not_in_use;
}
void DatabaseAtomic::assertCanBeDetached(bool cleanup)
2020-04-10 23:02:15 +00:00
{
if (cleanup)
2020-04-10 23:02:15 +00:00
{
DetachedTables not_in_use;
{
std::lock_guard lock(mutex);
not_in_use = cleanupDetachedTables();
2020-04-10 23:02:15 +00:00
}
}
std::lock_guard lock(mutex);
if (!detached_tables.empty())
throw Exception(ErrorCodes::DATABASE_NOT_EMPTY, "Database {} cannot be detached, because some tables are still in use. "
"Retry later.", backQuoteIfNeed(database_name));
2020-04-10 23:02:15 +00:00
}
DatabaseTablesIteratorPtr
DatabaseAtomic::getTablesIterator(ContextPtr local_context, const IDatabase::FilterByNameFunction & filter_by_table_name) const
2020-04-01 22:41:29 +00:00
{
auto base_iter = DatabaseWithOwnTablesBase::getTablesIterator(local_context, filter_by_table_name);
2020-04-01 22:41:29 +00:00
return std::make_unique<AtomicDatabaseTablesSnapshotIterator>(std::move(typeid_cast<DatabaseTablesSnapshotIterator &>(*base_iter)));
}
2020-04-13 14:09:56 +00:00
UUID DatabaseAtomic::tryGetTableUUID(const String & table_name) const
{
if (auto table = tryGetTable(table_name, getContext()))
2020-04-13 14:09:56 +00:00
return table->getStorageID().uuid;
return UUIDHelpers::Nil;
}
2022-07-20 20:54:43 +00:00
void DatabaseAtomic::beforeLoadingMetadata(ContextMutablePtr /*context*/, LoadingStrictnessLevel mode)
2020-04-10 00:08:43 +00:00
{
2022-07-20 20:54:43 +00:00
if (mode < LoadingStrictnessLevel::FORCE_RESTORE)
2021-08-31 08:53:48 +00:00
return;
2020-04-10 00:08:43 +00:00
/// Recreate symlinks to table data dirs in case of force restore, because some of them may be broken
2021-08-31 08:53:48 +00:00
for (const auto & table_path : fs::directory_iterator(path_to_table_symlinks))
{
2022-08-15 10:30:47 +00:00
if (!FS::isSymlink(table_path))
{
2021-08-31 08:53:48 +00:00
throw Exception(ErrorCodes::ABORTED,
"'{}' is not a symlink. Atomic database should contains only symlinks.", std::string(table_path.path()));
}
2021-08-31 08:53:48 +00:00
fs::remove(table_path);
}
2021-08-31 08:53:48 +00:00
}
2020-04-10 00:08:43 +00:00
2021-08-31 08:53:48 +00:00
void DatabaseAtomic::loadStoredObjects(
2022-07-20 20:54:43 +00:00
ContextMutablePtr local_context, LoadingStrictnessLevel mode, bool skip_startup_tables)
2021-08-31 08:53:48 +00:00
{
2022-07-20 20:54:43 +00:00
beforeLoadingMetadata(local_context, mode);
DatabaseOrdinary::loadStoredObjects(local_context, mode, skip_startup_tables);
2021-08-31 08:53:48 +00:00
}
2020-04-10 00:08:43 +00:00
2022-07-20 20:54:43 +00:00
void DatabaseAtomic::startupTables(ThreadPool & thread_pool, LoadingStrictnessLevel mode)
2021-08-31 08:53:48 +00:00
{
2022-07-20 20:54:43 +00:00
DatabaseOrdinary::startupTables(thread_pool, mode);
2020-04-10 00:08:43 +00:00
2022-07-20 20:54:43 +00:00
if (mode < LoadingStrictnessLevel::FORCE_RESTORE)
2021-08-31 08:53:48 +00:00
return;
2020-08-13 17:09:40 +00:00
2021-08-31 08:53:48 +00:00
NameToPathMap table_names;
{
std::lock_guard lock{mutex};
table_names = table_name_to_path;
2020-04-10 00:08:43 +00:00
}
2021-08-31 08:53:48 +00:00
fs::create_directories(path_to_table_symlinks);
for (const auto & table : table_names)
tryCreateSymlink(table.first, table.second, true);
2020-04-10 00:08:43 +00:00
}
2020-11-01 17:38:43 +00:00
void DatabaseAtomic::tryCreateSymlink(const String & table_name, const String & actual_data_path, bool if_data_path_exist)
2020-04-10 00:08:43 +00:00
{
try
{
String link = path_to_table_symlinks + escapeForFileName(table_name);
fs::path data = fs::canonical(getContext()->getPath()) / actual_data_path;
2021-04-30 17:20:53 +00:00
if (!if_data_path_exist || fs::exists(data))
fs::create_directory_symlink(data, link);
2020-04-10 00:08:43 +00:00
}
catch (...)
{
2023-01-16 23:11:59 +00:00
LOG_WARNING(log, getCurrentExceptionMessageAndPattern(/* with_stacktrace */ true));
2020-04-10 00:08:43 +00:00
}
}
void DatabaseAtomic::tryRemoveSymlink(const String & table_name)
{
try
{
String path = path_to_table_symlinks + escapeForFileName(table_name);
2021-04-30 17:20:53 +00:00
fs::remove(path);
2020-04-10 00:08:43 +00:00
}
catch (...)
{
2023-01-16 23:11:59 +00:00
LOG_WARNING(log, getCurrentExceptionMessageAndPattern(/* with_stacktrace */ true));
2020-04-10 00:08:43 +00:00
}
}
2020-07-07 12:11:58 +00:00
void DatabaseAtomic::tryCreateMetadataSymlink()
{
/// Symlinks in data/db_name/ directory and metadata/db_name/ are not used by ClickHouse,
/// it's needed only for convenient introspection.
assert(path_to_metadata_symlink != metadata_path);
2021-04-30 17:20:53 +00:00
fs::path metadata_symlink(path_to_metadata_symlink);
if (fs::exists(metadata_symlink))
2020-07-07 12:11:58 +00:00
{
2022-08-15 10:30:47 +00:00
if (!FS::isSymlink(metadata_symlink))
2020-07-07 12:11:58 +00:00
throw Exception(ErrorCodes::FILE_ALREADY_EXISTS, "Directory {} exists", path_to_metadata_symlink);
}
else
{
try
{
/// fs::exists could return false for broken symlink
if (FS::isSymlinkNoThrow(metadata_symlink))
fs::remove(metadata_symlink);
fs::create_directory_symlink(metadata_path, path_to_metadata_symlink);
2020-07-07 12:11:58 +00:00
}
catch (...)
{
tryLogCurrentException(log);
}
}
}
2021-11-02 12:58:45 +00:00
void DatabaseAtomic::renameDatabase(ContextPtr query_context, const String & new_name)
2020-07-07 12:11:58 +00:00
{
2020-07-08 14:28:07 +00:00
/// CREATE, ATTACH, DROP, DETACH and RENAME DATABASE must hold DDLGuard
2021-11-02 12:58:45 +00:00
bool check_ref_deps = query_context->getSettingsRef().check_referential_table_dependencies;
bool check_loading_deps = !check_ref_deps && query_context->getSettingsRef().check_table_dependencies;
if (check_ref_deps || check_loading_deps)
2021-11-02 12:58:45 +00:00
{
std::lock_guard lock(mutex);
for (auto & table : tables)
DatabaseCatalog::instance().checkTableCanBeRemovedOrRenamed({database_name, table.first}, check_ref_deps, check_loading_deps);
2021-11-02 12:58:45 +00:00
}
2020-07-07 12:11:58 +00:00
try
{
2021-04-30 17:20:53 +00:00
fs::remove(path_to_metadata_symlink);
2020-07-07 12:11:58 +00:00
}
catch (...)
{
2023-01-16 23:11:59 +00:00
LOG_WARNING(log, getCurrentExceptionMessageAndPattern(/* with_stacktrace */ true));
2020-07-07 12:11:58 +00:00
}
2020-07-08 14:28:07 +00:00
auto new_name_escaped = escapeForFileName(new_name);
auto old_database_metadata_path = getContext()->getPath() + "metadata/" + escapeForFileName(getDatabaseName()) + ".sql";
auto new_database_metadata_path = getContext()->getPath() + "metadata/" + new_name_escaped + ".sql";
2020-07-08 14:28:07 +00:00
renameNoReplace(old_database_metadata_path, new_database_metadata_path);
String old_path_to_table_symlinks;
2020-07-07 12:11:58 +00:00
{
std::lock_guard lock(mutex);
2021-11-02 12:58:45 +00:00
{
Strings table_names;
table_names.reserve(tables.size());
for (auto & table : tables)
table_names.push_back(table.first);
DatabaseCatalog::instance().updateDatabaseName(database_name, new_name, table_names);
}
2020-07-07 12:11:58 +00:00
database_name = new_name;
for (auto & table : tables)
{
auto table_id = table.second->getStorageID();
table_id.database_name = database_name;
table.second->renameInMemory(table_id);
}
path_to_metadata_symlink = getContext()->getPath() + "metadata/" + new_name_escaped;
2020-07-08 14:28:07 +00:00
old_path_to_table_symlinks = path_to_table_symlinks;
path_to_table_symlinks = getContext()->getPath() + "data/" + new_name_escaped + "/";
2020-07-07 12:11:58 +00:00
}
2021-04-30 17:20:53 +00:00
fs::rename(old_path_to_table_symlinks, path_to_table_symlinks);
2020-07-07 12:11:58 +00:00
tryCreateMetadataSymlink();
}
void DatabaseAtomic::waitDetachedTableNotInUse(const UUID & uuid)
{
/// Table is in use while its shared_ptr counter is greater than 1.
/// We cannot trigger condvar on shared_ptr destruction, so it's busy wait.
while (true)
{
DetachedTables not_in_use;
{
std::lock_guard lock{mutex};
not_in_use = cleanupDetachedTables();
if (!detached_tables.contains(uuid))
return;
}
2020-09-29 22:30:34 +00:00
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
2020-07-16 14:25:39 +00:00
2021-04-20 11:22:02 +00:00
void DatabaseAtomic::checkDetachedTableNotInUse(const UUID & uuid)
{
DetachedTables not_in_use;
std::lock_guard lock{mutex};
not_in_use = cleanupDetachedTables();
assertDetachedTableNotInUse(uuid);
}
2019-10-23 13:46:38 +00:00
}