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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
|
/* Copyright (c) 2018, 2025, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "storage/secondary_engine_mock/ha_mock.h"
#include <stddef.h>
#include <algorithm>
#include <cassert>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <tuple>
#include <utility>
#include "lex_string.h"
#include "my_alloc.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_sys.h"
#include "mysql/plugin.h"
#include "mysqld_error.h"
#include "sql/debug_sync.h"
#include "sql/handler.h"
#include "sql/join_optimizer/access_path.h"
#include "sql/join_optimizer/make_join_hypergraph.h"
#include "sql/join_optimizer/walk_access_paths.h"
#include "sql/sql_class.h"
#include "sql/sql_const.h"
#include "sql/sql_lex.h"
#include "sql/sql_optimizer.h"
#include "sql/table.h"
#include "template_utils.h"
#include "thr_lock.h"
namespace dd {
class Table;
}
namespace {
struct MockShare {
THR_LOCK lock;
MockShare() { thr_lock_init(&lock); }
~MockShare() { thr_lock_delete(&lock); }
// Not copyable. The THR_LOCK object must stay where it is in memory
// after it has been initialized.
MockShare(const MockShare &) = delete;
MockShare &operator=(const MockShare &) = delete;
};
// Map from (db_name, table_name) to the MockShare with table state.
class LoadedTables {
std::map<std::pair<std::string, std::string>, MockShare> m_tables;
std::mutex m_mutex;
public:
void add(const std::string &db, const std::string &table) {
std::lock_guard<std::mutex> guard(m_mutex);
m_tables.emplace(std::piecewise_construct, std::make_tuple(db, table),
std::make_tuple());
}
MockShare *get(const std::string &db, const std::string &table) {
std::lock_guard<std::mutex> guard(m_mutex);
auto it = m_tables.find(std::make_pair(db, table));
return it == m_tables.end() ? nullptr : &it->second;
}
void erase(const std::string &db, const std::string &table) {
std::lock_guard<std::mutex> guard(m_mutex);
m_tables.erase(std::make_pair(db, table));
}
};
LoadedTables *loaded_tables{nullptr};
/**
Execution context class for the MOCK engine. It allocates some data
on the heap when it is constructed, and frees it when it is
destructed, so that LeakSanitizer and Valgrind can detect if the
server doesn't destroy the object when the query execution has
completed.
*/
class Mock_execution_context : public Secondary_engine_execution_context {
public:
Mock_execution_context() : m_data(std::make_unique<char[]>(10)) {}
/**
Checks if the specified cost is the lowest cost seen so far for executing
the given JOIN.
*/
bool BestPlanSoFar(const JOIN &join, double cost) {
if (&join != m_current_join) {
// No plan has been seen for this join. The current one is best so far.
m_current_join = &join;
m_best_cost = cost;
return true;
}
// Check if the current plan is the best seen so far.
const bool cheaper = cost < m_best_cost;
m_best_cost = std::min(m_best_cost, cost);
return cheaper;
}
private:
std::unique_ptr<char[]> m_data;
/// The JOIN currently being optimized.
const JOIN *m_current_join{nullptr};
/// The cost of the best plan seen so far for the current JOIN.
double m_best_cost;
};
} // namespace
namespace mock {
ha_mock::ha_mock(handlerton *hton, TABLE_SHARE *table_share_arg)
: handler(hton, table_share_arg) {}
int ha_mock::open(const char *, int, unsigned int, const dd::Table *) {
MockShare *share =
loaded_tables->get(table_share->db.str, table_share->table_name.str);
if (share == nullptr) {
// The table has not been loaded into the secondary storage engine yet.
my_error(ER_SECONDARY_ENGINE_PLUGIN, MYF(0), "Table has not been loaded");
return HA_ERR_GENERIC;
}
thr_lock_data_init(&share->lock, &m_lock, nullptr);
return 0;
}
int ha_mock::info(unsigned int flags) {
// Get the cardinality statistics from the primary storage engine.
handler *primary = ha_get_primary_handler();
int ret = primary->info(flags);
if (ret == 0) {
stats.records = primary->stats.records;
}
return ret;
}
handler::Table_flags ha_mock::table_flags() const {
// Secondary engines do not support index access. Indexes are only used for
// cost estimates.
return HA_NO_INDEX_ACCESS;
}
unsigned long ha_mock::index_flags(unsigned int idx, unsigned int part,
bool all_parts) const {
const handler *primary = ha_get_primary_handler();
const unsigned long primary_flags =
primary == nullptr ? 0 : primary->index_flags(idx, part, all_parts);
// Inherit the following index flags from the primary handler, if they are
// set:
//
// HA_READ_RANGE - to signal that ranges can be read from the index, so that
// the optimizer can use the index to estimate the number of rows in a range.
//
// HA_KEY_SCAN_NOT_ROR - to signal if the index returns records in rowid
// order. Used to disable use of the index in the range optimizer if it is not
// in rowid order.
return ((HA_READ_RANGE | HA_KEY_SCAN_NOT_ROR) & primary_flags);
}
ha_rows ha_mock::records_in_range(unsigned int index, key_range *min_key,
key_range *max_key) {
// Get the number of records in the range from the primary storage engine.
return ha_get_primary_handler()->records_in_range(index, min_key, max_key);
}
THR_LOCK_DATA **ha_mock::store_lock(THD *, THR_LOCK_DATA **to,
thr_lock_type lock_type) {
if (lock_type != TL_IGNORE && m_lock.type == TL_UNLOCK)
m_lock.type = lock_type;
*to++ = &m_lock;
return to;
}
int ha_mock::load_table(const TABLE &table_arg) {
assert(table_arg.file != nullptr);
loaded_tables->add(table_arg.s->db.str, table_arg.s->table_name.str);
if (loaded_tables->get(table_arg.s->db.str, table_arg.s->table_name.str) ==
nullptr) {
my_error(ER_NO_SUCH_TABLE, MYF(0), table_arg.s->db.str,
table_arg.s->table_name.str);
return HA_ERR_KEY_NOT_FOUND;
}
return 0;
}
int ha_mock::unload_table(const char *db_name, const char *table_name,
bool error_if_not_loaded) {
if (error_if_not_loaded &&
loaded_tables->get(db_name, table_name) == nullptr) {
my_error(ER_SECONDARY_ENGINE_PLUGIN, MYF(0),
"Table is not loaded on a secondary engine");
return 1;
} else {
loaded_tables->erase(db_name, table_name);
return 0;
}
}
} // namespace mock
static bool PrepareSecondaryEngine(THD *thd, LEX *lex) {
DBUG_EXECUTE_IF("secondary_engine_mock_prepare_error", {
my_error(ER_SECONDARY_ENGINE_PLUGIN, MYF(0), "");
return true;
});
auto context = new (thd->mem_root) Mock_execution_context;
if (context == nullptr) return true;
lex->set_secondary_engine_execution_context(context);
// Disable use of constant tables and evaluation of subqueries during
// optimization.
lex->add_statement_options(OPTION_NO_CONST_TABLES |
OPTION_NO_SUBQUERY_DURING_OPTIMIZATION);
return false;
}
static void AssertSupportedPath(const AccessPath *path) {
switch (path->type) {
// The only supported join type is hash join. Other join types are disabled
// in handlerton::secondary_engine_flags.
case AccessPath::NESTED_LOOP_JOIN: /* purecov: deadcode */
case AccessPath::NESTED_LOOP_SEMIJOIN_WITH_DUPLICATE_REMOVAL:
case AccessPath::BKA_JOIN:
// Index access is disabled in ha_mock::table_flags(), so we should see none
// of these access types.
case AccessPath::INDEX_SCAN:
case AccessPath::REF:
case AccessPath::REF_OR_NULL:
case AccessPath::EQ_REF:
case AccessPath::PUSHED_JOIN_REF:
case AccessPath::INDEX_RANGE_SCAN:
case AccessPath::INDEX_SKIP_SCAN:
case AccessPath::GROUP_INDEX_SKIP_SCAN:
case AccessPath::ROWID_INTERSECTION:
case AccessPath::ROWID_UNION:
case AccessPath::DYNAMIC_INDEX_RANGE_SCAN:
assert(false); /* purecov: deadcode */
break;
default:
break;
}
// This secondary storage engine does not yet store anything in the auxiliary
// data member of AccessPath.
assert(path->secondary_engine_data == nullptr);
}
static bool OptimizeSecondaryEngine(THD *thd [[maybe_unused]], LEX *lex) {
// The context should have been set by PrepareSecondaryEngine.
assert(lex->secondary_engine_execution_context() != nullptr);
DBUG_EXECUTE_IF("secondary_engine_mock_optimize_error", {
my_error(ER_SECONDARY_ENGINE_PLUGIN, MYF(0), "");
return true;
});
DEBUG_SYNC(thd, "before_mock_optimize");
if (lex->using_hypergraph_optimizer()) {
WalkAccessPaths(lex->unit->root_access_path(), nullptr,
WalkAccessPathPolicy::ENTIRE_TREE,
[](AccessPath *path, const JOIN *) {
AssertSupportedPath(path);
return false;
});
}
return false;
}
static bool CompareJoinCost(THD *thd, const JOIN &join, double optimizer_cost,
bool *use_best_so_far, bool *cheaper,
double *secondary_engine_cost) {
*use_best_so_far = false;
DBUG_EXECUTE_IF("secondary_engine_mock_compare_cost_error", {
my_error(ER_SECONDARY_ENGINE_PLUGIN, MYF(0), "");
return true;
});
DBUG_EXECUTE_IF("secondary_engine_mock_choose_first_plan", {
*use_best_so_far = true;
*cheaper = true;
*secondary_engine_cost = optimizer_cost;
});
// Just use the cost calculated by the optimizer by default.
*secondary_engine_cost = optimizer_cost;
// This debug flag makes the cost function prefer orders where a table with
// the alias "X" is closer to the beginning.
DBUG_EXECUTE_IF("secondary_engine_mock_change_join_order", {
double cost = join.tables;
for (size_t i = 0; i < join.tables; ++i) {
const Table_ref *ref = join.positions[i].table->table_ref;
if (std::string(ref->alias) == "X") {
cost += i;
}
}
*secondary_engine_cost = cost;
});
// Check if the calculated cost is cheaper than the best cost seen so far.
*cheaper = down_cast<Mock_execution_context *>(
thd->lex->secondary_engine_execution_context())
->BestPlanSoFar(join, *secondary_engine_cost);
return false;
}
static bool ModifyAccessPathCost(THD *thd [[maybe_unused]],
const JoinHypergraph &hypergraph
[[maybe_unused]],
AccessPath *path) {
assert(!thd->is_error());
assert(hypergraph.query_block()->join == hypergraph.join());
AssertSupportedPath(path);
return false;
}
static handler *Create(handlerton *hton, TABLE_SHARE *table_share, bool,
MEM_ROOT *mem_root) {
return new (mem_root) mock::ha_mock(hton, table_share);
}
static int Init(MYSQL_PLUGIN p) {
loaded_tables = new LoadedTables();
handlerton *hton = static_cast<handlerton *>(p);
hton->create = Create;
hton->state = SHOW_OPTION_YES;
hton->flags = HTON_IS_SECONDARY_ENGINE;
hton->db_type = DB_TYPE_UNKNOWN;
hton->prepare_secondary_engine = PrepareSecondaryEngine;
hton->optimize_secondary_engine = OptimizeSecondaryEngine;
hton->compare_secondary_engine_cost = CompareJoinCost;
hton->secondary_engine_flags =
MakeSecondaryEngineFlags(SecondaryEngineFlag::SUPPORTS_HASH_JOIN);
hton->secondary_engine_modify_access_path_cost = ModifyAccessPathCost;
return 0;
}
static int Deinit(MYSQL_PLUGIN) {
delete loaded_tables;
loaded_tables = nullptr;
return 0;
}
static st_mysql_storage_engine mock_storage_engine{
MYSQL_HANDLERTON_INTERFACE_VERSION};
mysql_declare_plugin(mock){
MYSQL_STORAGE_ENGINE_PLUGIN,
&mock_storage_engine,
"MOCK",
PLUGIN_AUTHOR_ORACLE,
"Mock storage engine",
PLUGIN_LICENSE_GPL,
Init,
nullptr,
Deinit,
0x0001,
nullptr,
nullptr,
nullptr,
0,
} mysql_declare_plugin_end;
|