@@ -1771,39 +1771,34 @@ SinkToStoragePtr StorageMerge::write(
17711771 bool async_insert)
17721772{
17731773 const auto & access = context_->getAccess ();
1774-
1774+ std::optional<StoragePtr> table_storage{};
17751775 if (table_to_write_auto)
17761776 {
1777- table_to_write = std::nullopt ;
1778- bool any_table_found = false ;
1779- forEachTableName ([&](const auto & table_name)
1777+ chassert (!database_name_or_regexp.database_is_regexp );
1778+ const auto & database = database_name_or_regexp.source_database_name_or_regexp ;
1779+ auto allShowGranted = access->isGranted (AccessType::SHOW, database);
1780+ forEachTable ([&](const StoragePtr & table)
17801781 {
1781- any_table_found = true ;
1782- if (!table_to_write.has_value () || table_to_write->getFullName () < table_name.getFullName ())
1783- {
1784- if (access->isGranted (AccessType::INSERT, table_name.database , table_name.table ))
1785- table_to_write = table_name;
1786- }
1782+ if (!allShowGranted && !access->isGranted (AccessType::SHOW_TABLES, database, table->getName ()))
1783+ return ;
1784+
1785+ if (!table_storage || table->getName () > table_storage.value ()->getName ())
1786+ table_storage = table;
17871787 });
1788- if (!table_to_write.has_value ())
1789- {
1790- if (any_table_found)
1791- throw Exception (ErrorCodes::ACCESS_DENIED, " Not allowed to write in any suitable table for storage {}" , getName ());
1792- else
1793- throw Exception (ErrorCodes::UNKNOWN_TABLE, " Can't find any table to write for storage {}" , getName ());
1794- }
1795- }
1796- else
1797- {
1798- if (!table_to_write.has_value ())
1788+
1789+ if (!table_storage)
1790+ throw Exception (ErrorCodes::UNKNOWN_TABLE, " Can't find any table to write for storage {}" , getName ());
1791+
1792+ access->checkAccess (AccessType::INSERT, database, table_storage.value ()->getName ());
1793+ } else {
1794+ if (!table_to_write)
17991795 throw Exception (ErrorCodes::TABLE_IS_READ_ONLY, " Method write is not allowed in storage {} without described table to write" , getName ());
18001796
1801- access->checkAccess (AccessType::INSERT, table_to_write->database , table_to_write->table );
1797+ access->checkAccess (AccessType::INSERT, table_to_write.value ().database , table_to_write.value ().table );
1798+ table_storage = DatabaseCatalog::instance ().getTable (StorageID (table_to_write.value ()), context_);
18021799 }
18031800
1804- auto database = DatabaseCatalog::instance ().getDatabase (table_to_write->database );
1805- auto table = database->getTable (table_to_write->table , context_);
1806- return table->write (query, metadata_snapshot, context_, async_insert);
1801+ return table_storage.value ()->write (query, metadata_snapshot, context_, async_insert);
18071802}
18081803
18091804void registerStorageMerge (StorageFactory & factory)
0 commit comments