mariadb/sql/my_json_writer.h

794 lines
18 KiB
C
Raw Normal View History

2014-12-02 00:14:17 +01:00
/* Copyright (C) 2014 SkySQL Ab, MariaDB Corporation Ab
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
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 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
2019-05-11 21:19:05 +02:00
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */
#ifndef JSON_WRITER_INCLUDED
#define JSON_WRITER_INCLUDED
#include "my_base.h"
#include "sql_string.h"
2021-11-16 13:26:13 +01:00
#if !defined(NDEBUG) || defined(JSON_WRITER_UNIT_TEST) || defined ENABLED_JSON_WRITER_CONSISTENCY_CHECKS
2021-11-14 23:42:26 +01:00
#include <set>
#include <stack>
#include <string>
#include <vector>
2021-11-08 20:11:05 +01:00
#endif
#ifdef JSON_WRITER_UNIT_TEST
// Also, mock objects are defined in my_json_writer-t.cc
2021-11-09 19:06:22 +01:00
#define VALIDITY_ASSERT(x) if (!(x)) this->invalid_json= true;
#else
#include "sql_class.h" // For class THD
#include "log.h" // for sql_print_error
#define VALIDITY_ASSERT(x) DBUG_ASSERT(x)
#endif
2021-11-14 23:42:26 +01:00
#include <type_traits>
class Opt_trace_stmt;
class Opt_trace_context;
class Json_writer;
struct TABLE;
struct st_join_table;
using JOIN_TAB= struct st_join_table;
/*
2014-12-02 00:14:17 +01:00
Single_line_formatting_helper is used by Json_writer to do better formatting
of JSON documents.
The idea is to catch arrays that can be printed on one line:
arrayName : [ "boo", 123, 456 ]
and actually print them on one line. Arrrays that occupy too much space on
the line, or have nested members cannot be printed on one line.
We hook into JSON printing functions and try to detect the pattern. While
detecting the pattern, we will accumulate "boo", 123, 456 as strings.
Then,
- either the pattern is broken, and we print the elements out,
- or the pattern lasts till the end of the array, and we print the
array on one line.
*/
class Single_line_formatting_helper
{
enum enum_state
{
INACTIVE,
ADD_MEMBER,
IN_ARRAY,
DISABLED
};
/*
This works like a finite automaton.
state=DISABLED means the helper is disabled - all on_XXX functions will
return false (which means "not handled") and do nothing.
+->-+
| v
INACTIVE ---> ADD_MEMBER ---> IN_ARRAY--->-+
^ |
+------------------<--------------------+
For other states:
INACTIVE - initial state, we have nothing.
ADD_MEMBER - add_member() was called, the buffer has "member_name\0".
IN_ARRAY - start_array() was called.
*/
enum enum_state state;
enum { MAX_LINE_LEN= 80 };
char buffer[80];
/* The data in the buffer is located between buffer[0] and buf_ptr */
char *buf_ptr;
uint line_len;
Json_writer *owner;
public:
Single_line_formatting_helper() : state(INACTIVE), buf_ptr(buffer) {}
void init(Json_writer *owner_arg) { owner= owner_arg; }
bool on_add_member(const char *name, size_t len);
bool on_start_array();
bool on_end_array();
void on_start_object();
// on_end_object() is not needed.
bool on_add_str(const char *str, size_t num_bytes);
/*
Returns true if the helper is flushing its buffer and is probably
making calls back to its Json_writer. (The Json_writer uses this
function to avoid re-doing the processing that it has already done
before making a call to fmt_helper)
*/
bool is_making_writer_calls() const { return state == DISABLED; }
private:
void flush_on_one_line();
void disable_and_flush();
};
/*
Something that looks like class String, but has an internal limit of
how many bytes one can append to it.
Bytes that were truncated due to the size limitation are counted.
*/
class String_with_limit
{
public:
2019-02-13 12:15:14 +01:00
String_with_limit() : size_limit(SIZE_T_MAX), truncated_len(0)
{
str.length(0);
}
size_t get_truncated_bytes() const { return truncated_len; }
size_t get_size_limit() { return size_limit; }
void set_size_limit(size_t limit_arg)
{
// Setting size limit to be shorter than length will not have the desired
// effect
DBUG_ASSERT(str.length() < size_limit);
size_limit= limit_arg;
}
void append(const char *s, size_t size)
{
if (str.length() + size <= size_limit)
{
// Whole string can be added, just do it
str.append(s, size);
}
else
{
// We cannot add the whole string
if (str.length() < size_limit)
{
// But we can still add something
size_t bytes_to_add = size_limit - str.length();
str.append(s, bytes_to_add);
truncated_len += size - bytes_to_add;
}
else
truncated_len += size;
}
}
void append(const char *s)
{
append(s, strlen(s));
}
void append(char c)
{
if (str.length() + 1 > size_limit)
truncated_len++;
else
str.append(c);
}
const String *get_string() { return &str; }
size_t length() { return str.length(); }
private:
String str;
// str must not get longer than this many bytes.
size_t size_limit;
// How many bytes were truncated from the string
size_t truncated_len;
};
/*
A class to write well-formed JSON documents. The documents are also formatted
for human readability.
*/
class Json_writer
{
2021-11-08 20:11:05 +01:00
#if !defined(NDEBUG) || defined(JSON_WRITER_UNIT_TEST)
/*
In debug mode, Json_writer will fail and assertion if one attempts to
produce an invalid JSON document (e.g. JSON array having named elements).
*/
std::vector<bool> named_items_expectation;
std::stack<std::set<std::string> > named_items;
bool named_item_expected() const;
bool got_name;
#ifdef JSON_WRITER_UNIT_TEST
public:
// When compiled for unit test, creating invalid JSON will set this to true
// instead of an assertion.
bool invalid_json= false;
#endif
#endif
public:
/* Add a member. We must be in an object. */
Json_writer& add_member(const char *name);
Json_writer& add_member(const char *name, size_t len);
/* Add atomic values */
/* Note: the add_str methods do not do escapes. Should this change? */
void add_str(const char* val);
void add_str(const char* val, size_t num_bytes);
void add_str(const String &str);
void add_str(Item *item);
void add_table_name(const JOIN_TAB *tab);
void add_table_name(const TABLE* table);
void add_ll(longlong val);
2019-06-12 22:54:46 +02:00
void add_ull(ulonglong val);
void add_size(longlong val);
void add_double(double val);
void add_bool(bool val);
void add_null();
private:
void add_unquoted_str(const char* val);
void add_unquoted_str(const char* val, size_t len);
bool on_add_str(const char *str, size_t num_bytes);
void on_start_object();
public:
/* Start a child object */
void start_object();
void start_array();
void end_object();
void end_array();
/*
One can set a limit of how large a JSON document should be.
Writes beyond that size will be counted, but will not be collected.
*/
void set_size_limit(size_t mem_size) { output.set_size_limit(mem_size); }
size_t get_truncated_bytes() { return output.get_truncated_bytes(); }
Json_writer() :
2021-11-08 20:11:05 +01:00
#if !defined(NDEBUG) || defined(JSON_WRITER_UNIT_TEST)
got_name(false),
#endif
indent_level(0), document_start(true), element_started(false),
first_child(true)
{
fmt_helper.init(this);
}
private:
// TODO: a stack of (name, bool is_object_or_array) elements.
int indent_level;
enum { INDENT_SIZE = 2 };
friend class Single_line_formatting_helper;
friend class Json_writer_nesting_guard;
bool document_start;
bool element_started;
bool first_child;
Single_line_formatting_helper fmt_helper;
void append_indent();
void start_element();
void start_sub_element();
public:
String_with_limit output;
};
/* A class to add values to Json_writer_object and Json_writer_array */
class Json_value_helper
{
Json_writer* writer;
public:
void init(Json_writer *my_writer) { writer= my_writer; }
void add_str(const char* val)
{
writer->add_str(val);
}
void add_str(const char* val, size_t length)
{
writer->add_str(val, length);
}
void add_str(const String &str)
{
writer->add_str(str.ptr(), str.length());
}
void add_str(const LEX_CSTRING &str)
{
writer->add_str(str.str, str.length);
}
void add_str(Item *item)
{
writer->add_str(item);
}
void add_ll(longlong val)
{
writer->add_ll(val);
}
void add_size(longlong val)
{
writer->add_size(val);
}
void add_double(double val)
{
writer->add_double(val);
}
void add_bool(bool val)
{
writer->add_bool(val);
}
void add_null()
{
writer->add_null();
}
void add_table_name(const JOIN_TAB *tab)
{
writer->add_table_name(tab);
}
void add_table_name(const TABLE* table)
{
writer->add_table_name(table);
}
};
/* A common base for Json_writer_object and Json_writer_array */
class Json_writer_struct
{
2021-11-09 19:06:22 +01:00
Json_writer_struct(const Json_writer_struct&)= delete;
Json_writer_struct& operator=(const Json_writer_struct&)= delete;
#ifdef ENABLED_JSON_WRITER_CONSISTENCY_CHECKS
static thread_local std::vector<bool> named_items_expectation;
#endif
protected:
Json_writer* my_writer;
Json_value_helper context;
/*
Tells when a json_writer_struct has been closed or not
*/
bool closed;
explicit Json_writer_struct(Json_writer *writer)
: my_writer(writer)
{
context.init(my_writer);
closed= false;
#ifdef ENABLED_JSON_WRITER_CONSISTENCY_CHECKS
named_items_expectation.push_back(expect_named_children);
#endif
}
explicit Json_writer_struct(THD *thd)
: Json_writer_struct(thd->opt_trace.get_current_json())
{
}
public:
2023-02-10 11:02:11 +01:00
#ifdef ENABLED_JSON_WRITER_CONSISTENCY_CHECKS
virtual ~Json_writer_struct()
{
named_items_expectation.pop_back();
}
2023-02-10 11:02:11 +01:00
#else
virtual ~Json_writer_struct() = default;
2023-02-10 11:02:11 +01:00
#endif
Update row and key fetch cost models to take into account data copy costs Before this patch, when calculating the cost of fetching and using a row/key from the engine, we took into account the cost of finding a row or key from the engine, but did not consistently take into account index only accessed, clustered key or covered keys for all access paths. The cost of the WHERE clause (TIME_FOR_COMPARE) was not consistently considered in best_access_path(). TIME_FOR_COMPARE was used in calculation in other places, like greedy_search(), but was in some cases (like scans) done an a different number of rows than was accessed. The cost calculation of row and index scans didn't take into account the number of rows that where accessed, only the number of accepted rows. When using a filter, the cost of index_only_reads and cost of accessing and disregarding 'filtered rows' where not taken into account, which made filters cost less than there actually where. To remedy the above, the following key & row fetch related costs has been added: - The cost of fetching and using a row is now split into different costs: - key + Row fetch cost (as before) but multiplied with the variable 'optimizer_cache_cost' (default to 0.5). This allows the user to tell the optimizer the likehood of finding the key and row in the engine cache. - ROW_COPY_COST, The cost copying a row from the engine to the sql layer or creating a row from the join_cache to the record buffer. Mostly affects table scan costs. - ROW_LOOKUP_COST, the cost of fetching a row by rowid. - KEY_COPY_COST the cost of finding the next key and copying it from the engine to the SQL layer. This is used when we calculate the cost index only reads. It makes index scans more expensive than before if they cover a lot of rows. (main.index_merge_myisam) - KEY_LOOKUP_COST, the cost of finding the first key in a range. This replaces the old define IDX_LOOKUP_COST, but with a higher cost. - KEY_NEXT_FIND_COST, the cost of finding the next key (and rowid). when doing a index scan and comparing the rowid to the filter. Before this cost was assumed to be 0. All of the above constants/variables are now tuned to be somewhat in proportion of executing complexity to each other. There is tuning need for these in the future, but that can wait until the above are made user variables as that will make tuning much easier. To make the usage of the above easy, there are new (not virtual) cost calclation functions in handler: - ha_read_time(), like read_time(), but take optimizer_cache_cost into account. - ha_read_and_copy_time(), like ha_read_time() but take into account ROW_COPY_TIME - ha_read_and_compare_time(), like ha_read_and_copy_time() but take TIME_FOR_COMPARE into account. - ha_rnd_pos_time(). Read row with row id, taking ROW_COPY_COST into account. This is used with filesort where we don't need to execute the WHERE clause again. - ha_keyread_time(), like keyread_time() but take optimizer_cache_cost into account. - ha_keyread_and_copy_time(), like ha_keyread_time(), but add KEY_COPY_COST. - ha_key_scan_time(), like key_scan_time() but take optimizer_cache_cost nto account. - ha_key_scan_and_compare_time(), like ha_key_scan_time(), but add KEY_COPY_COST & TIME_FOR_COMPARE. I also added some setup costs for doing different types of scans and creating temporary tables (on disk and in memory). This encourages the optimizer to not use these for simple 'a few row' lookups if there are adequate key lookup strategies. - TABLE_SCAN_SETUP_COST, cost of starting a table scan. - INDEX_SCAN_SETUP_COST, cost of starting an index scan. - HEAP_TEMPTABLE_CREATE_COST, cost of creating in memory temporary table. - DISK_TEMPTABLE_CREATE_COST, cost of creating an on disk temporary table. When calculating cost of fetching ranges, we had a cost of IDX_LOOKUP_COST (0.125) for doing a key div for a new range. This is now replaced with 'io_cost * KEY_LOOKUP_COST (1.0) * optimizer_cache_cost', which matches the cost we use for 'ref' and other key lookups. The effect is that the cost is now a bit higher when we have many ranges for a key. Allmost all calculation with TIME_FOR_COMPARE is now done in best_access_path(). 'JOIN::read_time' now includes the full cost for finding the rows in the table. In the result files, many of the changes are now again close to what they where before the "Update cost for hash and cached joins" commit, as that commit didn't fix the filter cost (too complex to do everything in one commit). The above changes showed a lot of a lot of inconsistencies in optimizer cost calculation. The main objective with the other changes was to do calculation as similar (and accurate) as possible and to make different plans more comparable. Detailed list of changes: - Calculate index_only_cost consistently and correctly for all scan and ref accesses. The row fetch_cost and index_only_cost now takes into account clustered keys, covered keys and index only accesses. - cost_for_index_read now returns both full cost and index_only_cost - Fixed cost calculation of get_sweep_read_cost() to match other similar costs. This is bases on the assumption that data is more often stored on SSD than a hard disk. - Replaced constant 2.0 with new define TABLE_SCAN_SETUP_COST. - Some scan cost estimates did not take into account TIME_FOR_COMPARE. Now all scan costs takes this into account. (main.show_explain) - Added session variable optimizer_cache_hit_ratio (default 50%). By adjusting this on can reduce or increase the cost of index or direct record lookups. The effect of the default is that key lookups is now a bit cheaper than before. See usage of 'optimizer_cache_cost' in handler.h. - JOIN_TAB::scan_time() did not take into account index only scans, which produced a wrong cost when index scan was used. Changed JOIN_TAB:::scan_time() to take into consideration clustered and covered keys. The values are now cached and we only have to call this function once. Other calls are changed to use the cached values. Function renamed to JOIN_TAB::estimate_scan_time(). - Fixed that most index cost calculations are done the same way and more close to 'range' calculations. The cost is now lower than before for small data sets and higher for large data sets as we take into account how many keys are read (main.opt_trace_selectivity, main.limit_rows_examined). - Ensured that index_scan_cost() == range(scan_of_all_rows_in_table_using_one_range) + MULTI_RANGE_READ_INFO_CONST. One effect of this is that if there is choice of doing a full index scan and a range-index scan over almost the whole table then index scan will be preferred (no range-read setup cost). (innodb.innodb, main.show_explain, main.range) - Fixed the EQ_REF and REF takes into account clustered and covered keys. This changes some plans to use covered or clustered indexes as these are much cheaper. (main.subselect_mat_cost, main.state_tables_innodb, main.limit_rows_examined) - Rowid filter setup cost and filter compare cost now takes into account fetching and checking the rowid (KEY_NEXT_FIND_COST). (main.partition_pruning heap.heap_btree main.log_state) - Added KEY_NEXT_FIND_COST to Range_rowid_filter_cost_info::lookup_cost to account of the time to find and check the next key value against the container - Introduced ha_keyread_time(rows) that takes into account finding the next row and copying the key value to 'record' (KEY_COPY_COST). - Introduced ha_key_scan_time() for calculating an index scan over all rows. - Added IDX_LOOKUP_COST to keyread_time() as a startup cost. - Added index_only_fetch_cost() as a convenience function to OPT_RANGE. - keyread_time() cost is slightly reduced to prefer shorter keys. (main.index_merge_myisam) - All of the above caused some index_merge combinations to be rejected because of cost (main.index_intersect). In some cases 'ref' where replaced with index_merge because of the low cost calculation of get_sweep_read_cost(). - Some index usage moved from PRIMARY to a covering index. (main.subselect_innodb) - Changed cost calculation of filter to take KEY_LOOKUP_COST and TIME_FOR_COMPARE into account. See sql_select.cc::apply_filter(). filter parameters and costs are now written to optimizer_trace. - Don't use matchings_records_in_range() to try to estimate the number of filtered rows for ranges. The reason is that we want to ensure that 'range' is calculated similar to 'ref'. There is also more work needed to calculate the selectivity when using ranges and ranges and filtering. This causes filtering column in EXPLAIN EXTENDED to be 100.00 for some cases where range cannot use filtering. (main.rowid_filter) - Introduced ha_scan_time() that takes into account the CPU cost of finding the next row and copying the row from the engine to 'record'. This causes costs of table scan to slightly increase and some test to changed their plan from ALL to RANGE or ALL to ref. (innodb.innodb_mysql, main.select_pkeycache) In a few cases where scan time of very small tables have lower cost than a ref or range, things changed from ref/range to ALL. (main.myisam, main.func_group, main.limit_rows_examined, main.subselect2) - Introduced ha_scan_and_compare_time() which is like ha_scan_time() but also adds the cost of the where clause (TIME_FOR_COMPARE). - Added small cost for creating temporary table for materialization. This causes some very small tables to use scan instead of materialization. - Added checking of the WHERE clause (TIME_FOR_COMPARE) of the accepted rows to ROR costs in get_best_ror_intersect() - Removed '- 0.001' from 'join->best_read' and optimize_straight_join() to ensure that the 'Last_query_cost' status variable contains the same value as the one that was calculated by the optimizer. - Take avg_io_cost() into account in handler::keyread_time() and handler::read_time(). This should have no effect as it's 1.0 by default, except for heap that overrides these functions. - Some 'ref_or_null' accesses changed to 'range' because of cost adjustments (main.order_by) - Added scan type "scan_with_join_cache" for optimizer_trace. This is just to show in the trace what kind of scan was used. - When using 'scan_with_join_cache' take into account number of preceding tables (as have to restore all fields for all previous table combination when checking the where clause) The new cost added is: (row_combinations * ROW_COPY_COST * number_of_cached_tables). This increases the cost of join buffering in proportion of the number of tables in the join buffer. One effect is that full scans are now done earlier as the cost is then smaller. (main.join_outer_innodb, main.greedy_optimizer) - Removed the usage of 'worst_seeks' in cost_for_index_read as it caused wrong plans to be created; It prefered JT_EQ_REF even if it would be much more expensive than a full table scan. A related issue was that worst_seeks only applied to full lookup, not to clustered or index only lookups, which is not consistent. This caused some plans to use index scan instead of eq_ref (main.union) - Changed federated block size from 4096 to 1500, which is the typical size of an IO packet. - Added costs for reading rows to Federated. Needed as there is no caching of rows in the federated engine. - Added ha_innobase::rnd_pos_time() cost function. - A lot of extra things added to optimizer trace - More costs, especially for materialization and index_merge. - Make lables more uniform - Fixed a lot of minor bugs - Added 'trace_started()' around a lot of trace blocks. - When calculating ORDER BY with LIMIT cost for using an index the cost did not take into account the number of row retrivals that has to be done or the cost of comparing the rows with the WHERE clause. The cost calculated would be just a fraction of the real cost. Now we calculate the cost as we do for ranges and 'ref'. - 'Using index for group-by' is used a bit more than before as now take into account the WHERE clause cost when comparing with 'ref' and prefer the method with fewer row combinations. (main.group_min_max). Bugs fixed: - Fixed that we don't calculate TIME_FOR_COMPARE twice for some plans, like in optimize_straight_join() and greedy_search() - Fixed bug in save_explain_data where we could test for the wrong index when displaying 'Using index'. This caused some old plans to show 'Using index'. (main.subselect_innodb, main.subselect2) - Fixed bug in get_best_ror_intersect() where 'min_cost' was not updated, and the cost we compared with was not the one that was used. - Fixed very wrong cost calculation for priority queues in check_if_pq_applicable(). (main.order_by now correctly uses priority queue) - When calculating cost of EQ_REF or REF, we added the cost of comparing the WHERE clause with the found rows, not all row combinations. This made ref and eq_ref to be regarded way to cheap compared to other access methods. - FORCE INDEX cost calculation didn't take into account clustered or covered indexes. - JT_EQ_REF cost was estimated as avg_io_cost(), which is half the cost of a JT_REF key. This may be true for InnoDB primary key, but not for other unique keys or other engines. Now we use handler function to calculate the cost, which allows us to handle consistently clustered, covered keys and not covered keys. - ha_start_keyread() didn't call extra_opt() if keyread was already enabled but still changed the 'keyread' variable (which is wrong). Fixed by not doing anything if keyread is already enabled. - multi_range_read_info_cost() didn't take into account io_cost when calculating the cost of ranges. - fix_semijoin_strategies_for_picked_join_order() used the wrong record_count when calling best_access_path() for SJ_OPT_FIRST_MATCH and SJ_OPT_LOOSE_SCAN. - Hash joins didn't provide correct best_cost to the upper level, which means that the cost for hash_joins more expensive than calculated in best_access_path (a difference of 10x * TIME_OF_COMPARE). This is fixed in the new code thanks to that we now include TIME_OF_COMPARE cost in 'read_time'. Other things: - Added some 'if (thd->trace_started())' to speed up code - Removed not used function Cost_estimate::is_zero() - Simplified testing of HA_POS_ERROR in get_best_ror_intersect(). (No cost changes) - Moved ha_start_keyread() from join_read_const_table() to join_read_const() to enable keyread for all types of JT_CONST tables. - Made a few very short functions inline in handler.h Notes: - In main.rowid_filter the join order of order and lineitem is swapped. This is because the cost of doing a range fetch of lineitem(98 rows) is almost as big as the whole join of order,lineitem. The filtering will also ensure that we only have to do very small key fetches of the rows in lineitem. - main.index_merge_myisam had a few changes where we are now using less keys for index_merge. This is because index scans are now more expensive than before. - handler->optimizer_cache_cost is updated in ha_external_lock(). This ensures that it is up to date per statements. Not an optimal solution (for locked tables), but should be ok for now. - 'DELETE FROM t1 WHERE t1.a > 0 ORDER BY t1.a' does not take cost of filesort into consideration when table scan is chosen. (main.myisam_explain_non_select_all) - perfschema.table_aggregate_global_* has changed because an update on a table with 1 row will now use table scan instead of key lookup. TODO in upcomming commits: - Fix selectivity calculation for ranges with and without filtering and when there is a ref access but scan is chosen. For this we have to store the lowest known value for 'accepted_records' in the OPT_RANGE structure. - Change that records_read does not include filtered rows. - test_if_cheaper_ordering() needs to be updated to properly calculate costs. This will fix tests like main.order_by_innodb, main.single_delete_update - Extend get_range_limit_read_cost() to take into considering cost_for_index_read() if there where no quick keys. This will reduce the computed cost for ORDER BY with LIMIT in some cases. (main.innodb_ext_key) - Fix that we take into account selectivity when counting the number of rows we have to read when considering using a index table scan to resolve ORDER BY. - Add new calculation for rnd_pos_time() where we take into account the benefit of reading multiple rows from the same page.
2021-11-01 11:34:24 +01:00
inline bool trace_started() const
{
return my_writer != 0;
}
#ifdef ENABLED_JSON_WRITER_CONSISTENCY_CHECKS
bool named_item_expected() const
{
return named_items_expectation.size() > 1
&& *(named_items_expectation.rbegin() + 1);
}
#endif
};
/*
RAII-based class to start/end writing a JSON object into the JSON document
There is "ignore mode": one can initialize Json_writer_object with a NULL
Json_writer argument, and then all its calls will do nothing. This is used
by optimizer trace which can be enabled or disabled.
*/
class Json_writer_object : public Json_writer_struct
{
private:
void add_member(const char *name)
{
my_writer->add_member(name);
}
public:
explicit Json_writer_object(Json_writer* writer, const char *str= nullptr)
: Json_writer_struct(writer)
{
#ifdef ENABLED_JSON_WRITER_CONSISTENCY_CHECKS
DBUG_ASSERT(named_item_expected());
#endif
if (unlikely(my_writer))
2021-11-09 19:06:22 +01:00
{
if (str)
my_writer->add_member(str);
my_writer->start_object();
}
}
explicit Json_writer_object(THD* thd, const char *str= nullptr)
: Json_writer_object(thd->opt_trace.get_current_json(), str)
{
}
~Json_writer_object()
{
if (my_writer && !closed)
my_writer->end_object();
closed= TRUE;
}
Json_writer_object& add(const char *name, bool value)
{
DBUG_ASSERT(!closed);
if (my_writer)
{
add_member(name);
context.add_bool(value);
}
return *this;
}
2021-11-14 23:42:26 +01:00
Json_writer_object& add(const char *name, ulonglong value)
{
DBUG_ASSERT(!closed);
if (my_writer)
{
add_member(name);
2021-11-14 23:42:26 +01:00
my_writer->add_ull(value);
}
return *this;
}
2021-11-14 23:42:26 +01:00
template<class IntT,
typename= typename ::std::enable_if<std::is_integral<IntT>::value>::type
>
Json_writer_object& add(const char *name, IntT value)
{
DBUG_ASSERT(!closed);
if (my_writer)
{
add_member(name);
context.add_ll(value);
}
return *this;
}
2021-11-14 23:42:26 +01:00
Json_writer_object& add(const char *name, double value)
{
DBUG_ASSERT(!closed);
if (my_writer)
{
add_member(name);
context.add_double(value);
}
return *this;
}
2021-11-14 23:42:26 +01:00
Json_writer_object& add(const char *name, const char *value)
{
DBUG_ASSERT(!closed);
if (my_writer)
{
add_member(name);
context.add_str(value);
}
return *this;
}
Json_writer_object& add(const char *name, const char *value, size_t num_bytes)
{
add_member(name);
context.add_str(value, num_bytes);
return *this;
}
Json_writer_object& add(const char *name, const LEX_CSTRING &value)
{
DBUG_ASSERT(!closed);
if (my_writer)
{
add_member(name);
context.add_str(value.str, value.length);
}
return *this;
}
Json_writer_object& add(const char *name, Item *value)
{
DBUG_ASSERT(!closed);
if (my_writer)
{
add_member(name);
context.add_str(value);
}
return *this;
}
Json_writer_object& add_null(const char*name)
{
DBUG_ASSERT(!closed);
if (my_writer)
{
add_member(name);
context.add_null();
}
return *this;
}
Json_writer_object& add_table_name(const JOIN_TAB *tab)
{
DBUG_ASSERT(!closed);
if (my_writer)
{
add_member("table");
context.add_table_name(tab);
}
return *this;
}
Json_writer_object& add_table_name(const TABLE *table)
{
DBUG_ASSERT(!closed);
if (my_writer)
{
add_member("table");
context.add_table_name(table);
}
return *this;
}
Json_writer_object& add_select_number(uint select_number)
{
DBUG_ASSERT(!closed);
if (my_writer)
{
add_member("select_id");
if (unlikely(select_number == FAKE_SELECT_LEX_ID))
context.add_str("fake");
else
context.add_ll(static_cast<longlong>(select_number));
}
return *this;
}
void end()
{
DBUG_ASSERT(!closed);
if (unlikely(my_writer))
my_writer->end_object();
closed= TRUE;
}
};
/*
RAII-based class to start/end writing a JSON array into the JSON document
There is "ignore mode": one can initialize Json_writer_array with a NULL
Json_writer argument, and then all its calls will do nothing. This is used
by optimizer trace which can be enabled or disabled.
*/
class Json_writer_array : public Json_writer_struct
{
public:
explicit Json_writer_array(Json_writer *writer, const char *str= nullptr)
: Json_writer_struct(writer)
{
#ifdef ENABLED_JSON_WRITER_CONSISTENCY_CHECKS
DBUG_ASSERT(!named_item_expected());
#endif
if (unlikely(my_writer))
{
if (str)
my_writer->add_member(str);
my_writer->start_array();
}
}
explicit Json_writer_array(THD *thd, const char *str= nullptr)
: Json_writer_array(thd->opt_trace.get_current_json(), str)
{
}
~Json_writer_array()
{
if (unlikely(my_writer && !closed))
{
my_writer->end_array();
closed= TRUE;
}
}
void end()
{
DBUG_ASSERT(!closed);
if (unlikely(my_writer))
my_writer->end_array();
closed= TRUE;
}
Json_writer_array& add(bool value)
{
DBUG_ASSERT(!closed);
if (my_writer)
context.add_bool(value);
return *this;
}
Json_writer_array& add(ulonglong value)
{
DBUG_ASSERT(!closed);
if (my_writer)
context.add_ll(static_cast<longlong>(value));
return *this;
}
Json_writer_array& add(longlong value)
{
DBUG_ASSERT(!closed);
if (my_writer)
context.add_ll(value);
return *this;
}
Json_writer_array& add(double value)
{
DBUG_ASSERT(!closed);
if (my_writer)
context.add_double(value);
return *this;
}
#ifndef _WIN64
Json_writer_array& add(size_t value)
{
DBUG_ASSERT(!closed);
if (my_writer)
context.add_ll(static_cast<longlong>(value));
return *this;
}
#endif
Json_writer_array& add(const char *value)
{
DBUG_ASSERT(!closed);
if (my_writer)
context.add_str(value);
return *this;
}
Json_writer_array& add(const char *value, size_t num_bytes)
{
DBUG_ASSERT(!closed);
if (my_writer)
context.add_str(value, num_bytes);
return *this;
}
Json_writer_array& add(const LEX_CSTRING &value)
{
DBUG_ASSERT(!closed);
if (my_writer)
context.add_str(value.str, value.length);
return *this;
}
Json_writer_array& add(Item *value)
{
DBUG_ASSERT(!closed);
if (my_writer)
context.add_str(value);
return *this;
}
Json_writer_array& add_null()
{
DBUG_ASSERT(!closed);
if (my_writer)
context.add_null();
return *this;
}
Json_writer_array& add_table_name(const JOIN_TAB *tab)
{
DBUG_ASSERT(!closed);
if (my_writer)
context.add_table_name(tab);
return *this;
}
Json_writer_array& add_table_name(const TABLE *table)
{
DBUG_ASSERT(!closed);
if (my_writer)
context.add_table_name(table);
return *this;
}
};
/*
RAII-based class to disable writing into the JSON document
The tracing is disabled as soon as the object is created.
The destuctor is called as soon as we exit the scope of the object
and the tracing is enabled back.
*/
class Json_writer_temp_disable
{
public:
Json_writer_temp_disable(THD *thd_arg);
~Json_writer_temp_disable();
THD *thd;
};
/*
RAII-based helper class to detect incorrect use of Json_writer.
The idea is that a function typically must leave Json_writer at the same
identation level as it was when it was invoked. Leaving it at a different
level typically means we forgot to close an object or an array
So, here is a way to guard
void foo(Json_writer *writer)
{
Json_writer_nesting_guard(writer);
.. do something with writer
// at the end of the function, ~Json_writer_nesting_guard() is called
// and it makes sure that the nesting is the same as when the function was
// entered.
}
*/
class Json_writer_nesting_guard
{
#ifdef DBUG_OFF
public:
Json_writer_nesting_guard(Json_writer *) {}
#else
Json_writer* writer;
int indent_level;
public:
Json_writer_nesting_guard(Json_writer *writer_arg) :
writer(writer_arg),
indent_level(writer->indent_level)
{}
~Json_writer_nesting_guard()
{
DBUG_ASSERT(indent_level == writer->indent_level);
}
#endif
};
#endif