Home - Waterfall Grid T-Grid Console Builders Recent Builds Buildslaves Changesources - JSON API - About

Console View


Categories: connectors experimental galera main
Legend:   Passed Failed Warnings Failed Again Running Exception Offline No data

connectors experimental galera main
Marko Mäkelä
MDEV-42557: innodb_snapshot_isolation=ON regression at READ COMMITTED

Based on my theoretical review of Generalized Isolation Level Definitions
(Adya, Liskov, O'Neil, Proceedings of the IEEE International Conference
on Data Engineering, San Diego, CA, March 2000), the error code
ER_CHECKREAD a.k.a. DB_RECORD_CHANGED only has to be returned at the
REPEATABLE READ or SERIALIZABLE isolation levels, to prevent the G2-item
anomaly (write-write conflicts). G2-item anomalies are allowed by PL-2
(READ COMMITTED), so we must not abort READ COMMITTED transactions
because of them.

The combination innodb_snapshot_isolation=OFF and READ COMMITTED
does not match the theoretical definition PL-2 because it is not free
of G1 anomalies, as demonstrated by the test case added in
commit 0a199cb81009590a1b337fe3ddec09e559dbb22d (MDEV-34108).

With innodb_snapshot_isolation=ON, I believe that our READ COMMITTED
matches the isolation levle definition PL-2. Specifically, the
absence of next-key or gap locks seems to be allowed.

lock_clust_rec_read_check_and_lock(): Avoid unnecessary ER_CHECKREAD
for READ COMMITTED, and only return DB_RECORD_CHANGED if the transaction
isolation level is REPEATABLE READ or SERIALIZABLE. (At READ UNCOMMITTED,
no read view snapshot should ever be created.)

ha_innobase::try_semi_consistent_read(): Enable
the vaguely defined semi-consistent read only
for READ COMMITTED when innodb_snapshot_isolation=OFF,
or for READ UNCOMMITTED transactions. This allows the
logic in row_search_mvcc() to be simplified. This should
be a non-functional change.
Vladislav Vaintroub
MDEV-42087 Memory leak in sql_service when a statement fails after it sent its metadata

When a statement that runs through mysql_real_connect_local() fails
after it sent its metadata, the error is stored in the dataset of the
result set. embedded_get_error() freed only the MYSQL_DATA, and not its
MEM_ROOT, so 8192 bytes were lost, for example for a statement that is
aborted by KILL QUERY. Free the dataset with free_rows().

Assisted-by: Claude:claude-sonnet-5-5
Monty
Cleanup binary logging API

- Add is_current_stmt_binlog_format_stmt()
- Replace !is_current_stmt_binlog_format_row() with
  is_current_stmt_binlog_format_stmt(). This is in prepartion for using
  BINLOG_FORMAT_UNSPEC if no binary logging.
- Removed printing of temporary_tables info in
  reset_current_stmt_binlog_format_row() as this is not relevant anymore.
- Added testing of (thd->variables.option_bits & OPTION_BIN_LOG) when
  binlogging create procedure.
Monty
MDEV-35915 Part: ANALYZE, CHECK, REPAIR and OPTIMIZE of GTT

ANALYZE, CHECK, REPAIR and OPTIMIZE TABLE now work on the
connection's instance of a global temporary table (GTT), in the
same way as for a local temporary table.
Before, they used the GTT definition and gave the note "The storage
engine for the table doesn't support ...". Under LOCK TABLES,
ANALYZE, REPAIR and OPTIMIZE gave ER_TABLE_NOT_LOCKED.

- A GTT without an instance in the connection has no data. No
  instance is created for it. Instead the command gives the status
  "Global temporary table without an instance" (new admin result
  code HA_ADMIN_NO_GTT_INSTANCE). This is always the case for an
  ON COMMIT DELETE ROWS GTT, as the implicit commit of the command
  drops its instance.
- A replica or a connection in pseudo_slave_mode never creates an
  instance, so it also gets the above status.

Binary logging of ANALYZE, OPTIMIZE and REPAIR:
- Temporary tables, local or GTT, are not written to the binary
  log. Neither are tables that could not be opened, as nothing was
  done to them.
- If no table is left to log, nothing is written to the binary log.
- If the statement also had other tables, a new statement with
  only these tables is logged. The tables are written as
  `db`.`table`, together with the PERSISTENT FOR clause of ANALYZE
  and the QUICK, EXTENDED, USE_FRM and FORCE options of REPAIR.
- If no tables were left out, the original statement is logged as
  before.

This replaces the logging of GTTs from MDEV-37929, where the replica
had to open the GTT definition. CF_USE_PARENT_GTT_SHARE is removed
from SQLCOM_REPAIR, SQLCOM_ANALYZE and SQLCOM_OPTIMIZE.

Other fixes:
- If the recreate done by OPTIMIZE failed, the error was sent again
  for the next table and left as a warning for the statement.
- ER_GTID_OPEN_TABLE_FAILED printed the table as table.db instead of
  db.table.

Tests:
- main.GTT: admin commands on GTTs for MyISAM, Aria and InnoDB,
  without an instance, with an empty instance and with data. Also
  covered: LOCK TABLES with the GTT listed and not listed,
  transactions, autocommit=0, a definition changed by another
  connection, engine-independent statistics, prepared statements,
  stored procedures and pseudo_slave_mode.
- Updated binlog.global_temporary_table: shows what is written to the
  binary log for lists with temporary, base and missing tables, and
  for all REPAIR and ANALYZE options.
- binlog.binlog_admin_cmd_kill: when OPTIMIZE TABLE t1,t2,no_such_table
  is killed after t1 is optimized, only t1 is logged. Before, the whole
  statement was logged, which was inconsistent with a kill before the
  first table, where nothing is logged.
- innodb_mysql_sync: if the analyze after the recreate in OPTIMIZE
  is not supported (MEMORY), the error is now ER_ILLEGAL_HA instead
  of "Got error -1".
- In case of lock timeout error for OPTIMIZE, one will now get a result
  set with a lock timeout message instead of an ER_LOCK_WAIT_TIMEOUT
  error. Tested in main.flush_and_binlog. MDEV-42749 covers giving that
  error again.
Alexey Botchkov
MDEV-41750 XMLISVALID should be 0 returns 1 for strings that are not a single well-formed XML document.

Additional fix to address the issue with BOF that Alice mentions in a
comment.
Check the beginning of the XML for a possible BOF.
Monty
Backported fix for perfschema.user_var_func
Monty
Changed ha_table_exists() to return Table_type to provide more information

- Added TABLE_TYPE_GLOBAL_TEMPORARY to Table_type
- Added TABLE_TYPE_FRM_ONLY to allow ha_table_exists() to inform caller
  that frm file exists but is not readable or has bad information.
- Removed parameter is_sequence from ha_table_exists()
Oleg Smirnov
MDEV-41654 Account cost of subqueries in conditions attached to tables

The optimizer costs the condition attached to a table at WHERE_COST per
row. A correlated subquery in that condition is executed again for
every row that reaches it, and costs far more than WHERE_COST. Plans
that check the condition on many rows, such as a full scan with a join
buffer, therefore look cheaper than they are compared to ref access.

Collect, once per JOIN in make_join_statistics(), the top-level
conjuncts of WHERE and of every ON condition that contain a subquery
executed again for each evaluation: an uncacheable subquery that is
not served by the subquery cache. The cost of one execution is a lower
bound, as correlated subqueries are optimized only after the outer
plan: one lookup into the first table of the subquery,
KEY_LOOKUP_COST + ROW_LOOKUP_COST + ROW_COPY_COST of its engine.

best_access_path() adds the cost of these executions to the access
method of the table where the conjunct is checked. A subquery is
assumed to run only for the rows that pass the cheap conjuncts, as
MDEV-40439 evaluates them first:
- with a join buffer, a conjunct that refers only to the table is in
  the scan filter, checked for the rows that pass the table's
  conditions on constants, once per buffer refill;
- otherwise it is checked for every row combination that passes the
  other conditions;
- in an outer join, the ON condition is checked again on the first
  match, or on every match with a join buffer on the last inner table.
  An ON conjunct on outer tables only is checked once per row
  combination before the inner tables are read, and again for every
  row of the first inner table.
test_if_cheaper_ordering() adds the cost per row read for ORDER BY ...
LIMIT. Row estimates do not change, only costs. The optimizer trace
shows the added cost as subquery_cond_cost.

The fix is OFF by default and enabled by setting FIX_SUBQUERY_COND_COST
flag in @@new_mode. The costs match the executions when
REORDER_EXPENSIVE_CONDS (MDEV-40439) is set as well.

Not covered yet: LooseScan (its cost is saved without the subquery cost).
Monty
MDEV-35915 Part: GTT and FLUSH TABLES

- FLUSH TABLE does not affect GTT instances: the data is kept, and
  other connections can still use their instances.
- Under LOCK TABLES, FLUSH TABLE of a GTT without an instance in the
  connection is ignored, like for temporary tables.
- FLUSH TABLE table_list WITH READ LOCK and FOR EXPORT lock the GTT
  definition against DDL (ALTER, DROP, ...), but all connections can
  still create and use their GTT instances.
- FLUSH TABLE table_list FOR EXPORT handles the (always empty) GTT
  definition like other tables.
- The global FLUSH TABLES WITH READ LOCK does not stop connections
  from using their GTT instances.
- ALTER TABLE ... DISCARD/IMPORT TABLESPACE work on the GTT definition.
    Like other DDL, they drop the GTT instance of the connection. The
    files of a GTT definition exported with FLUSH TABLES ... FOR EXPORT
    can be imported as a new GTT (copying .frm, .ibd and .cfg) or into
    an existing table after DISCARD TABLESPACE
Monty
Gtid fixups

- Force table_creation_was_logged=2 for GTT tables. This means that table
  was written to binary log but all updates of GTT tables will use ROW
  binlog format. Drop of GTT table will be binlogged.
- We gave an error for statements mixing GTT tables and normal tables under
  STATEMENT logging. Changed it to revert to row logging in this case
  (as we do for other cases).
- Removed binlogging of DROP [TEMPORARY TABLE] for create or replace where
  the original table did not exists.  binlog_show_create_table now takes
  an extra parameter if the orignal table was dropped.
- Changed binlog of DROP TABLE to be 'direct'. This simplifes replication a
  as it does not need to create a transation for DROP TABLE.
  The different in show binlog output is:
- Moved GTT variables HA_OPTION_.. variables to an enum in handler.cc:
  GTT_NONE=0, GTT_TABLE=1, GTT_ON_COMMIT_DELETE_ROWS=2. The gtt options
  are now stored in TABLE_SHARE->gtt_options and TABLE_LIST->gtt_options.
- Changed class Tmp_table_kind to an enum
  {TMP_TABLE_LOCAL, TMP_TABLE_GLOBAL, TMP_TABLE_LOCAL_OR_GLOBAL }
- Moved find_tmp_table_share_w_base_key() to use
  find_tmp_table_share(..., 1). This was because functions where
  practically identical, except for a length subtraction in one place.
- Fixed wrong test cases
- Fixed compiler errors by moving code from 'main'

-master-bin.000001      #      Gtid    #      #      BEGIN GTID #-#-#
+master-bin.000001      #      Gtid    #      #      GTID #-#-#
master-bin.000001      #      Query  #      #      use `test`; DROP TABLE IF EXISTS `test`.`t1`/* Generated to handle failed CREATE OR REPLACE */
-master-bin.000001      #      Query  #      #      ROLLBACK

Another consequence of the patch is that "Annotate rows" is binlogged for some
cases where it was not binlogged before. This can be seen in
mysql-test/suite/rpl/r/rpl_mixed_mixing_engines.result
Sergei Golubchik
fixup
Raghunandan Bhat
MDEV-39095: Fixes to MariaDB Syntax Checker

- Skip initializing stopwords for full-text indexes when checking
  syntax.
- Skip changing data directory when checking syntax.
- Show help message when syntax checker is used in interactive mode.
- Initialize THD with a dummy database name to prevent `No database
  selected` error.
- Rename `PARSER_STATE` in check_syntax.cc to `Syntax_checker_state` to
  avoid confusion with `Parser_state` class.
- Increase max length of delimiter token to 16 to match mariadb client.
- Support many statements in one query, like the client does
  (e.g. `SET @a=1; SELECT @a|` with DELIMITER |). Report correct line
  numbers for errors in them.
- Report only errors, not notes or warnings. A stored function with the
  name of a native function is accepted, a UDF with such a name is an
  error.
- Apply SET statements that change how later statements are parsed:
  - Applied: session sql_mode and character_set_client, SET NAMES,
    SET CHARACTER SET. Values can be constants, DEFAULT, user
    variables, @@sql_mode or @@character_set_client.
  - Tracked: user variables set from such values, so the
    `SET @OLD_SQL_MODE=@@SQL_MODE ... SET SQL_MODE=@OLD_SQL_MODE`
    pattern from dumps works.
  - Ignored: SET GLOBAL, other variables, and values that need
    executing (a user variable set from one is unset).
- Split statements using the current client character set.
- Treat enabled plugins as available, so that partitioning syntax is
  accepted. Initialize data type and function plugins, so that their
  types and functions are known.
- Recognize system variables of enabled plugins (binlog_checksum,
  innodb_*, aria_*) without initializing the plugins.
- Support CREATE PACKAGE BODY when CREATE PACKAGE is earlier in the
  input. DROP PACKAGE removes it. A body without its package is an
  error.
- Refuse to run --check-syntax together with --bootstrap.
- More tests: DDLs, DMLs, Stored Procedures, Views, sql_mode, character
  sets, plugins, packages
Marko Mäkelä
MDEV-42557: innodb_snapshot_isolation=ON regression at READ COMMITTED

Based on my theoretical review of Generalized Isolation Level Definitions
(Adya, Liskov, O'Neil, Proceedings of the IEEE International Conference
on Data Engineering, San Diego, CA, March 2000), the error code
ER_CHECKREAD a.k.a. DB_RECORD_CHANGED only has to be returned at the
REPEATABLE READ or SERIALIZABLE isolation levels, to prevent the G2-item
anomaly (write-write conflicts). G2-item anomalies are allowed by PL-2
(READ COMMITTED), so we must not abort READ COMMITTED transactions
because of them.

The combination innodb_snapshot_isolation=OFF and READ COMMITTED
does not match the theoretical definition PL-2 because it is not free
of G1 anomalies, as demonstrated by the test case added in
commit 0a199cb81009590a1b337fe3ddec09e559dbb22d (MDEV-34108).

With innodb_snapshot_isolation=ON, I believe that our READ COMMITTED
matches the isolation level definition PL-2. Specifically, the
absence of next-key or gap locks seems to be allowed.

lock_clust_rec_read_check_and_lock(): Avoid unnecessary ER_CHECKREAD
for READ COMMITTED, and only return DB_RECORD_CHANGED if the transaction
isolation level is REPEATABLE READ or SERIALIZABLE. (At READ UNCOMMITTED,
no read view snapshot should ever be created.)

ha_innobase::try_semi_consistent_read(): Enable
the vaguely defined semi-consistent read only
for READ COMMITTED when innodb_snapshot_isolation=OFF,
or for READ UNCOMMITTED transactions. This allows the
logic in row_search_mvcc() to be simplified. This should
be a non-functional change.
Monty
MDEV-35915 Part: SHOW TABLES / SHOW TABLE STATUS for GTT tables

- SHOW TABLE STATUS and INFORMATION_SCHEMA.TABLES show the GTT
  definition, which is always empty, with Temporary='N'. If the
  connection has a GTT instance, it is also shown, like a local
  temporary table, with Temporary='Y' and the rows and space it
  uses. Both have the table type GLOBAL TEMPORARY.
- SHOW TABLES only shows the GTT definition.
Monty
Ensure we test WSREP_NNULL() before calling wsrep_thd_is_local()

This is to ensure we follow the protocol defined for wsrep_thd_is_local()

Other things:
- Replace WSREP(thd) with WSREP_NNULL(thd) when we are sure thd cannot
  be NULL.
- Removed DBUG_ASSERT() in wsrep_mysqld.cc as it was already ensured
  by previous code a few lines up.
Sergei Golubchik
OpenSSL 4.0 fix for session resumption

The server closes the connection without close_notify. OpenSSL 4.0
client treats it as an unexpected EOF: a 0 returned by ma_bio_read
counts as EOF. Unexpected EOF made the session non-resumable.

OpenSSL 3.x asked ma_bio_ctrl() which said "not EOF" -
it's an aborted connection, but not an unexpected EOF.

Set SSL_OP_IGNORE_UNEXPECTED_EOF, EOF without close_notify is a
normal connection end. The protocol is not vulnerable to truncation,
every packet carries its length.

Assisted-By: Claude:claude-opus-5-5
Brandon Nesterenko
MDEV-38796 Clean up THD::decide_logging_format() checks

Continue the binlog_state refactoring by moving the remaining per
statement binary log checks into the cached THD::binlog_state, and
make the checks for whether binary logging is enabled consistent.

Changes:

* Track the binlog_do_db/binlog_ignore_db filter result for the
  current default database in binlog_state as BINLOG_STATE_FILTER_DB
  (renamed from BINLOG_STATE_FILTER, as the flag applies only to
  database filtering of statement format logging). The flag is
  updated in THD::set_db() and THD::reset_db() when the default
  database changes, so decide_logging_format() no longer calls
  binlog_filter->db_ok() for every statement. thd_binlog_filter_ok()
  now reads the flag instead of re-running the filter.

* Remove the THD local statement filter (m_binlog_filter_state and
  reset/clear/set/get_binlog_local_stmt_filter()). binlog_state now
  carries this information through BINLOG_STATE_FILTER_DB.

* Remove the 'silent' parameter from mysql_create_db_internal().
  mysql_upgrade_db() now suppresses binary logging of the internal
  CREATE DATABASE with tmp_disable_binlog() / reenable_binlog().

* Replace the remaining tests of mysql_bin_log.is_open() in main code
  paths with thd->binlog_ready() / binlog_ready_no_wsrep(). is_open()
  was tested without holding a mutex, which made it unreliable; it is
  now checked under mysql_bin_log.LOCK_log when committing to the
  binary log. WSREP related is_open() usage is left for MDEV-38865.

New tests:

* binlog.binlog_close_during_commit exercises statements racing with
  a binary log close between the thd->binlog_ready() check and the
  commit time acquisition of mysql_bin_log.LOCK_log, using the new
  debug sync point commit_after_binlog_ready_before_LOCK_log.

* rpl.rpl_lsu_binlog_filter verifies that a slave configured with
  log_slave_updates and binlog_do_db/binlog_ignore_db filters does
  not binlog filtered transactions, using a three server chain
  topology.

Test updates: ER_BINLOG_STMT_MODE_AND_ROW_ENGINE is no longer an
error. The statement is switched to row format for its duration and
a note is raised instead. Tests relying on the old error are updated
accordingly.

Reviewed by: Monty <[email protected]>
bsrikanth-mariadb
MDEV-38303: Stop scan early when aggregate HAVING cannot become true

For a query without GROUP BY, such as

  SELECT COUNT(*) FROM t1 HAVING COUNT(*) < 10

the whole table was read even after the count reached 10 and the
condition could no longer be true.

Add Item_sum::is_having_shortcut_cmp(op, c), which tells whether a
HAVING condition "aggregate op constant", once false, stays false as
more rows are added. Item_sum_count implements it for COUNT(..) < c,
COUNT(..) <= c and COUNT(..) = 0. Other aggregates return false, so
they are read in full as before.

JOIN::setup_having_shortcut_conds() collects such AND-parts of HAVING
in a List at the end of JOIN::make_aggr_tables_info(), in the
optimizer. An error there is returned to the caller. When the list is
not empty, setup_end_select_func() uses check_having_shortcut_conds()
instead of end_send_group(), so other queries pay nothing. It calls
end_send_group(), then checks the conditions after each row and returns
NESTED_LOOP_QUERY_LIMIT, the same way LIMIT stops a scan, once one is
false. The end-of-records step still runs, so HAVING is checked on the
final state.

Only used when it is safe:
- implicit grouping, with no temporary table, ROLLUP, window functions,
  PROCEDURE, loose index scan, optimized-away GROUP BY or correlated
  HAVING
- COUNT(DISTINCT) is excluded, as its value is known only at the end
- the comparison must be numeric. COUNT compared with a DATE is not
  monotonic, so it is not used
- the constant must be a non-NULL numeric literal, a bound PS
  parameter, or a constant expression (5+5, ABS(0)) with no user
  variables, stored functions or subqueries. A user variable changed by
  a stored function during the scan would give a wrong result.
  String constants are not used, as evaluating them for every row
  would raise a warning for every row.
- a NULL result does not stop the scan

Like LIMIT, stopping early means the remaining rows are not read, so
errors and side effects from them no longer happen.

The code is in the new file sql/opt_having_shortcut.cc. Since the
decision is made at optimization time, it is also reported:
- EXPLAIN FORMAT=JSON shows "having_shortcut": true
- tabular EXPLAIN shows "Using having_shortcut" in the Extra column
  of the first table
- the optimizer trace has a "having_shortcut" object with the
  stop_conditions

The plan only says the scan may stop. The tests also cover queries where
the plan shows the shortcut, but the scan is not stopped, or is stopped
late.
Monty
Making LOCK TABLES work with GTT tables as it works with TEMPORARY tables.

Changes:
- A GTT instance doesn't keep a metadata lock on the definition. The lock
  is released as soon as the instance is created, and a second use in the
  same statement reuses the instance without taking a lock. Because of
  this, ALTER or DROP of the definition from another session no longer
  waits.

- LOCK TABLES for GTT always uses the GTT instance, not the table
  definition. One side effect of this is that one cannot do a DDL on
  the GTT definition, like ALTER, RENAME or DROP while one has a LOCK
  on the table.
- One can use GTT instances without having them in LOCK TABLE, like one
  can do with temporary tables.
- CREATE OR REPLACE GTT over a table locked with LOCK TABLES (plain, LIKE
  and SELECT) releases the replaced table's locks. If it was the last
  locked table, LOCK TABLES ends.
- FLUSH TABLES now ignores temporary tables and GTT instances under LOCK
  TABLES. Without LOCK TABLES, FLUSH TABLE of a GTT removes the
  definition from the table cache, as before.
- After FLUSH TABLES gtt WITH READ LOCK, statements skip the locked
  definition and use the instance. This fixes an assertion.
- DDL on a GTT definition under LOCK TABLES fails:
  CREATE OR REPLACE (all kinds) gives ER_TABLE_NOT_LOCKED.
  ALTER, RENAME and DROP give ER_TABLE_IN_USE while the session has a
  GTT instance, and ER_TABLE_NOT_LOCKED when it has none (for example
  after TRUNCATE).
- SHOW CREATE TABLE shows the session's instance if there is one. Under
  LOCK TABLES it can also show a definition that has no instance.
- "LOCK TABLE gtt_table write" now succeeds inside a read-only transaction
- mariadb-dump will not try to dump content of GTT tables.
- Moved MDL_context::release_lock(enum_mdl_duration duration,
  MDL_ticket *ticket) from private to public and added a DBUG_ASSERT if
  the duration is incorrect.
- The pseudo_slave_mode test cases now fail at LOCK TABLES.
- Removed defines/functions:  OPEN_FOR_LOCKED_TABLES_LIST,
  select_create::parent_global_tmp_table
- CREATE OR REPLACE under LOCK TABLES now releases the locks of a dropped
  table after binary logging, also for normal tables."

Bugs fixed:
- A failed CREATE GLOBAL TEMPORARY TABLE ... SELECT left the GTT
  definition behind (on disk, or in the table definition cache if the
  GTT instance could not be opened).
Monty
Removed mdl_ticket from TMP_TABLES_SHARE

This is preparation for versioning of GTT tables and also remove
LOCK TABLE for GTT instances and make GTT tables work as normal temporary
Monty
MDEV-35915 Part: GTT and CACHE/LOAD INDEX

- CACHE INDEX and LOAD INDEX INTO CACHE are not supported for GTTs.
  They give a note for each GTT and don't create a GTT instance.

The reason is that the key cache would only be assigned to the GTT
instance, and the assignment is lost when the instance is dropped at
commit, TRUNCATE or disconnect. Preloading is also not useful, as the
index of a GTT instance was just created and is already in the cache.
forkfun
MDEV-42222 Item clone must not share String buffers owned by the original

On 2nd execution of a prepared statement with a condition pushed into
an IN subquery, the server could still use freed memory if the
condition had NULLIF, LIKE, HEX, RPAD, a JSON function or one of many
other string functions, and its argument became longer.

The previous commit made clones of 5 item classes forget their scratch
String buffers. Any other String member of a clone still pointed to
the buffer of the original item, which reallocates it for a longer
value.

A copy of a String that owns its buffer gets its own copy of the data
while a Binary_string::Deep_copy object exists in the thread.
get_item_copy(), which makes the copies for shallow_copy() and
deep_copy(), has one. The data is kept, because not all such Strings
are scratch buffers: Item_func_pad::pad_str holds the default padding
string. Other String copies stay shallow.

The deep_copy() overrides added by the previous commit and
Arg_comparator::reset_for_clone() are removed: release() does not free
a buffer, and the clone owns its buffers now.

The changes to Item_param::value_clone_item() and SFORMAT made earlier
for this bug are reverted, with the test of the former: these String
copies are made outside get_item_copy() and stay shallow.

Assisted-by: Claude:claude-opus-5-5
Monty
MDEV-35915 DDL drops the GTT instance of the connection

Before, DROP, ALTER, RENAME and CREATE OR REPLACE of a global
temporary table (GTT) failed with ER_TABLE_IN_USE when the connection
had an instance of the table. Now a DDL drops the connection's GTT
instances that have the same name as a table in the statement, after
the table names are locked and before the operation:

- DROP TABLE drops the instance and then the definition. If the
  definition was dropped by another connection (orphan instance), only
  the instance is dropped and a note ER_GTT_ORPHAN_INSTANCE_DROPPED is
  given.
- DROP TEMPORARY TABLE drops a GTT instance if it exists. If no temporary
  table or GTT instance exists it gives an error.
- ALTER TABLE drops the instance of the altered table and of the new
  name (ALTER ... RENAME).
- RENAME TABLE drops the instances of both old and new names.
- CREATE OR REPLACE drops the instance before the old table. Plain
  CREATE of an existing table fails and keeps the instance. CREATE
  ... IF NOT EXISTS of an existing table never touches the instance.
- CREATE TABLE/VIEW over a name that only has an orphan instance
  drops the instance.
- An instance used as a source by the statement is never dropped,
  ER_TABLE_IN_USE is given (CREATE OR REPLACE t1 SELECT * FROM t1).

CREATE TEMPORARY TABLE and GTT instances:
- A local temporary table and a GTT instance with the same name
  cannot exist at the same time.
- CREATE TEMPORARY TABLE fails if a local temporary table or a GTT
  instance with the name exists. IF NOT EXISTS gives a note. In both
  cases nothing is changed.
- CREATE OR REPLACE TEMPORARY TABLE replaces a local temporary table
  or a GTT instance.
- CREATE TEMPORARY TABLE shadows a GTT definition, like a base table.

Other changes:
- Added THD::drop_gtt_instance(), one version taking a name and one
  taking the TMP_TABLE_SHARE when it is known.
- GTT instances have table_creation_was_logged= 0, as they are never
  binary logged.
Monty
Fixing Galera test results
Monty
Improve ha_table_exists()

- If the table is not in the table definition cache, open the .frm
  file directly to get the table type. This saves one system call
  when the table exists (the common case), and removes the race of
  the .frm file being removed between the access() and open() calls.
- The return value is the same as before
Sergei Golubchik
11.4: compilation fix for OpenSSL 4.0

`X509_get_subject_name()` returns `const X509_NAME *`,
the caller isn't supposed to change it directly.
Monty
MDEV-35915 Part: GTT and FLUSH TABLES

- FLUSH TABLE does not affect GTT instances: the data is kept, and
  other connections can still use their instances.
- Under LOCK TABLES, FLUSH TABLE of a GTT without an instance in the
  connection is ignored, like for temporary tables.
- FLUSH TABLE table_list WITH READ LOCK and FOR EXPORT lock the GTT
  definition against DDL (ALTER, DROP, ...), but all connections can
  still create and use their GTT instances.
- FLUSH TABLE table_list FOR EXPORT handles the (always empty) GTT
  definition like other tables.
- The global FLUSH TABLES WITH READ LOCK does not stop connections
  from using their GTT instances.
- ALTER TABLE ... DISCARD/IMPORT TABLESPACE work on the GTT definition.
    Like other DDL, they drop the GTT instance of the connection. The
    files of a GTT definition exported with FLUSH TABLES ... FOR EXPORT
    can be imported as a new GTT (copying .frm, .ibd and .cfg) or into
    an existing table after DISCARD TABLESPACE
Sergei Golubchik
fixup
Monty
MDEV-35915 Part: GTT and CACHE/LOAD INDEX

- CACHE INDEX and LOAD INDEX INTO CACHE are not supported for GTTs.
  They give a note for each GTT and don't create a GTT instance.

The reason is that the key cache would only be assigned to the GTT
instance, and the assignment is lost when the instance is dropped at
commit, TRUNCATE or disconnect. Preloading is also not useful, as the
index of a GTT instance was just created and is already in the cache.
Alexey Botchkov
MDEV-41750 XMLISVALID should be 0 returns 1 for strings that are not a single well-formed XML document.

Additional fix to address the issue with BOF that Alice mentions in a
comment.
Check the beginning of the XML for a possible BOF.
Alexey Yurchenko
MDEV-42499 don't enclose handlerton members in #ifdef WITH_WSREP

Even if the member is used by wsrep only, the handlerton structure
is shared between embedded server compiled without WITH_WSREP and
plugins compiled normally.
Monty
Release the GTT metadata locks at the end of open_tables()
Monty
MDEV-35915 Part: GTT and SHOW COMMANDS / INFORMATION SCHEMA

- SHOW COLUMNS, SHOW INDEX and DESCRIBE shows the GTT instance if one
  exists.
- If no instance exists it will show the GTT definition. No new instance
  will be created.
- INFORMATION SCHEMA always shows the definition.
Alexey Yurchenko
MDEV-42698 synchronize ~thd_async_state() against its mutex.

dec_pending_ops() decrements m_pending_ops while holding m_mtx and
still touches m_cond/m_mtx afterwards (cond_signal, unlock). If we
saw 0 in wait_for_pending_ops() without taking the mutex, we could
destroy it while decrementing thread is still inside dec_pending_ops().
Don't use wait_for_pending_ops(), just take the mutex in
~thd_async_state() before destroying.
Monty
MDEV-38865 Simplify testing if binary logging is enabled

In the MariaDB server most of the code uses different expressions to
test if binary logging should be done for the current query.

In many cases the current code does a lot of not needed work before
noticing that binary logging is not needed, which affects performance.
For example, in some cases early decision for preparing to do binary
logging was based on current_stmt_binlog_format (which is by default
statement) without checking if binary logging was enable.

There is also a lot of different variables that affects if binary logging
should be used:
- (thd->variables.option_bits & OPTION_BIN_LOG)
- (thd->variables.option_bits & OPTION_BIN_TMP_LOG_OFF)
- WSREP(thd) && wsrep_emulate_bin_log && WSREP_PROVIDER_EXISTS_
- mysql_bin_log.is_open()
- xxx_binlog_local_stmt_filter()
- binlog_filter
- thd->variables.sql_log_bin
- thd->binlog_evt_union.do_union

The goal is to move all states to a single variable (for performance,
simplicity and easier debugging). We should ignore all possible
extra work if binary logging is not needed for a particular query.

We should use the 'original state', from the start of the query, to
test if mysql_bin_log.is_open() or if wsrep_emulate_bin_log is set.
The reason for this is that all test are done without any mutex and
can cause effect if they change during the query execution.  The
testing of the above conditions should be done during a mutex when
deciding of we should copy the binary log changes to the real binary
log.

In most cases we can now use one the following functions to check if
we binary logging is needed.  We need different version to be able
to shortcut code if binary logging is not enabled (with different
code paths if Galera is enabled or not).

- binlog_ready()
- binlog_ready_no_wsrep()
- binlog_ready_precheck()
- binlog_ready_later()

The state of binary logging is stored in thd->binlog_state.
There are a few bits that shows why binary logging is needed and
one bit for every different reasons for disabling binary logging.
By printing this variable (gdb prints all bits with there enum name)
one can exactly see why binary logging is not happening.

The initial bits are set in THD::THD() and THD::init() and verified in
THD::decide_logging_format().

In this commit all testing of OPTION_BIN_LOG and most testing of
mysql_bin_log.is_open() is removed.
We should over time remove all testing of mysql_bin_log.is_open() from the
main code, except in binlog commit, as the value can change 'anytime' if
binlog rotation fails, which is very likely to result in crashes.
(The patch fixes some of these cases).

THD::binlog_state is a new variable that simplifies testing if replication
is permanently off, is on or temporarily off (for a sub statement).

We also set current_stmt_binlog_format to BINLOG_FORMAT_UNSPEC if binlog is
off.

The above changes allows some code changes:

One does not need to test for mysql_bin_log.is_open() if one also tests
for thd->is_current_stmt_binlog_format_stmt() or
thd->is_current_stmt_binlog_format_row().

The change also allows the following transformations:

(WSREP(thd) && wsrep_emulate_bin_log) ||
(mysql_bin_log.is_open()) && (thd->variables.option_bits & OPTION_BIN_LOG)
->
thd->binlog_ready()

(WSREP_NNULL(thd) && wsrep_emulate_bin_log) || mysql_bin_log.is_open())
->
thd->binlog_ready()

(WSREP_EMULATE_BINLOG(thd) || mysql_bin_log.is_open())
->
thd->binlog_ready()

mysql_bin_log.is_open() && (thd->variables.option_bits & OPTION_BIN_LOG)
->
thd->binlog_ready_no_wsrep()

Other transformation are easy to do by using the bits set in binlog_state
by decide_binlog_format().
Note that the new code takes into account if binary logging is
disabled, with the old code did not do (except in the first and last
examples)

Other things:
- Implement THD::tmp_disable_binlog() and THD::reenable_binlog() using
  the new binlog_state framework.
- THD::variables.wsrep_on is now updated by THD:enable_wsrep(),
  THD::disable_wsrep_on() and THD::set_wsrep_on(). I added an assert for
  (WSREP_PROVIDER_EXISTS_ && WSREP_ON_) when setting wsrep_on=1
- Reset sql_log_bin in THD::init(). This is to ensure that change user
  will not get affected by the previous users sql_log_bin state.
- Replaced OPTION_BIN_TMP_LOG_OFF with
  (thd->binlog_state & BINLOG_STATE_TMP_DISABLED)
- Added TABLE->disabled_rowlogging() and TABLE->enable_rowlogging() to
  be used when one want to only disable logging for single write, update
  or delete call. This fixes an possible issue with spider and mroonga
  that used the old tmp_disable_binlog() framework which did not work
  to disable row logging.
- I had to add a test for thd->binlog_evt_union.do_union() in a few
  places as binlog_state contains a state for do_union, which causes
  thd->binlog_ready() to fail if do_union is used.
  Other option would add a new function thd->binlog_ready_or_union()
  that could handle this case by just removing the
  BINLOG_STATE_UNION_DISABLE bit from binlog_state before testing
  disable bits.

Things to do:
- We should consider removing OPTION_BIN_LOG and instead use
  binlog_state. This would allow us to remove reset and setting it in
  decide_binlog_format(). The code is not anymore using the value of
  OPTION_BIN_LOG anywhere.
- Update binlog_state with BINLOG_STATE_FILTER only when database or filter
  is changed.  This means we do not have to call binlog_filter->db_ok() for
  every statement in decide_binlog_format().
- Remove clear/reset xxx_binlog_local_stmt_filter() as this is now handled
  by binlog_state.
- Remove 'silent' option from mysql_create_db_internal and instead use
  tmp_disable_binlog() / reenable_binlog()
- Remove testing if binary log is desabled in:
  MYSQL_BIN_LOG::write(Log_event *event_info, my_bool *with_annotate):
    if ((!(option_bin_log_flag)) ||
        (thd->lex->sql_command != SQLCOM_ROLLBACK_TO_SAVEPOINT &&
        thd->lex->sql_command != SQLCOM_SAVEPOINT &&
        !binlog_filter->db_ok(local_db)))
      DBUG_RETURN(0);
- Remove all testing of mysql_bin_log.is_open(). Instead test for
  binlog_ready() in main code and add testing of is_open() when
  trying to commit the binary log.  This is needed as currently
  mysql_bin_log.is_open() is tested without a mutex which makes
  it unreliable.
- Remove testing of WSREP_PROVIDER_EXISTS_ in WSREP_NULL() as this
  is guaranteed by THD::enable_wsrep()
- Ensure that WSREP_PROVIDER_EXISTS can never change while there are
  any connections with a THD.
- BINLOG_STATE_FILTER need a bit more work. It is currently only used
  in decide_binlog_format()
- Remove BINLOG_STATE_BYPASS (Not needed as some other BINLOG_STATE disable
  bit is set if BYPASS is set).  BYPASS was added mostly to simplify
  testing of the new code.
Monty
MDEV-35915 Part: SHOW TABLES / SHOW TABLE STATUS for GTT tables

- SHOW TABLE STATUS and INFORMATION_SCHEMA.TABLES show the GTT
  definition, which is always empty, with Temporary='N'. If the
  connection has a GTT instance, it is also shown, like a local
  temporary table, with Temporary='Y' and the rows and space it
  uses. Both have the table type GLOBAL TEMPORARY.
- SHOW TABLES only shows the GTT definition.
Alexander Barkov
MDEV-39563 Implement UPDATE ... RETURNING ... INTO

Adding support for UPDATE .. RETURNING .. INTO queries.

For example:

  UPDATE t1 SET a=10,b=20 RETURNING a,b INTO va,vb;
  UPDATE t1 SET a=10,b=20 RETURNING a,b INTO @a,@b;

Limitations:
1. These types of queries:
  - REPLACE .. RETURNING .. INTO
  - DELETE .. RETURNING .. INTO
  - INSERT .. RETURNING .. INTO
  are not supported yet, and ER_NOT_SUPPORTED_YET is raised with
  'REPLACE..RETURNING..INTO', 'DELETE..RETURNING..INTO' or
  'INSERT..RETURNING..INTO' as the argument. The same is for
  the INSERT..SELECT and REPLACE..SELECT forms.
  They will be implemented separately, when needed.

2. UPDATE..RETURNING..INTO is rejected with ER_WRONG_USAGE if it would
  be written to the binary log in the statement format
  (--binlog_format=statement), as the order of the rows is not
  predictable, like in SELECT..LIMIT without ORDER BY. With
  --binlog_format=mixed it is written in the row format.
  No warning "Unsafe statement written to the binary log" is raised
  for it, as the statement is rejected and is not written.
  Supporting the statement format is tracked in MDEV-42398.

3. Using OLD_VALUE(col) in the RETURNING list of UPDATE..RETURNING..INTO
  is not allowed and an error is raised.

4. Multi-table updates do not work, and neither do single table
  updates that get converted to multi-table:
  - UPDATE t1,t2 ..: ER_NOT_SUPPORTED_YET
    ('RETURNING for multi-table UPDATE')
  - an UPDATE of a view over several tables, or with an IN subquery
    converted to a semi-join (even on another table):
    ER_NOT_SUPPORTED_YET ('multi-table UPDATE..RETURNING..INTO')
  - a subquery on the updated table in WHERE: ER_UPDATE_TABLE_USED.
    With ORDER BY .. LIMIT the statement is not converted to
    multi-table, so it works.

5. UPDATE IGNORE .. RETURNING .. INTO is not supported yet and
  ER_NOT_SUPPORTED_YET is raised (MDEV-42381). A row rejected by the
  engine (a duplicate key, no partition found) is ignored by IGNORE,
  so it is not known before ha_update_row() whether the row is
  a second changed row.
  UPDATE IGNORE .. RETURNING without INTO works as before.

6. Some statements are written to the binary log as the statement text
  even with --binlog_format=row or mixed. The replica cannot execute
  RETURNING..INTO, as it does not have the target variables, so
  ER_NOT_SUPPORTED_YET is raised in these cases:
  - UPDATE of a table with transaction-precise system versioning
    (VERS_TRX_ID), if the binary log is enabled. The error is raised
    before any row is changed.
  - UPDATE that changes no rows but auto-creates a history partition
    (PARTITION BY SYSTEM_TIME .. AUTO). The partition is created
    already, and the error is raised after that.

Notes:

1. ANALYZE and EXPLAIN
  Both
    ANALYZE UPDATE .. RETURNING .. INTO ..
    EXPLAIN UPDATE .. RETURNING .. INTO ..
  return this error:
    'RETURNING..INTO' is not allowed in this context

2. Behavior on no data and on multiple rows

  Only the rows that were actually changed are processed. A row that
  matches the WHERE condition but needs no update is not changed,
  so it is not returned by plain RETURNING either.

  Situation                | RETURNING  | RETURNING .. INTO
  --------------------------+-------------+-----------------------------
  Empty table, WHERE        | empty set  | Warning ER_SP_FETCH_NO_DATA,
  matches nothing (1=0),    |            | target is not changed
  LIMIT 0                  |            |

  One row matches, needs    | empty set  | Warning ER_SP_FETCH_NO_DATA,
  no update                |            | target is not changed

  Several rows match, none  | empty set  | Warning ER_SP_FETCH_NO_DATA,
  needs an update          |            | target is not changed
                            |            | (no ER_TOO_MANY_ROWS)

  One row matches and is    | that row    | Target is assigned
  changed                  |            |

  Several rows match,      | that row    | Target is assigned from
  exactly one changes      |            | that row

  Two or more rows change  | all changed | ER_TOO_MANY_ROWS at the 2nd
                            |            | changed row (not updated)

  Notes:
  - The warning is never an error: not in the strict mode and not with
    sql_mode=''. The INTO targets keep their old values.
    In stored routines the warning activates NOT FOUND handlers.
  - This is the same for all storage engines, including those that
    quickly know the table is empty and use a degenerated plan
    (e.g. MyISAM).
  - After ER_TOO_MANY_ROWS, transactional engines roll back the
    statement, non-transactional engines keep the rows updated before
    the error (the second changed row is not updated).
  - The targets can be user variables, SP variables, ROW variables
    and ROW fields.
  - For a system-versioned table, an update that sets the same values
    still creates a new row version, so such a row counts as changed:
    plain RETURNING returns it, and RETURNING .. INTO assigns it
    (or raises ER_TOO_MANY_ROWS if two rows match).

3. Behavior on VIEW with CHECK OPTION

  The "too many rows" check is done after the view's CHECK OPTION
  check, so a row rejected by WITH CHECK OPTION raises the CHECK OPTION
  error and not ER_TOO_MANY_ROWS.

4. The OK packet

  UPDATE .. RETURNING .. INTO sends the same OK packet as a plain
  UPDATE. The affected rows are the changed rows (the matched rows with
  CLIENT_FOUND_ROWS), and the info is:
    Rows matched: N  Changed: M  Warnings: W
  with "Inserted: K" added for system versioned and period tables.
  The "No data" warning is counted in Warnings. ROW_COUNT() in a stored
  routine is the number of the changed rows, not of the assigned rows.
  If there is nothing to read (WHERE 1=0, LIMIT 0, an empty table on
  some engines), a plain OK without the info is sent, as for UPDATE.

Helper changes:

1. The grammar in analyze_stmt_command was changed to have
  LEX::analyze_stmt set to true earlier, so
  LEX::set_returning_into_result() already knows if this
  is an ANALYZE statement.

2. The Sql_cmd_update constructor is now called earlier in the grammar,
  to be able to call Sql_cmd_update::set_with_old_value_items()
  in the SET and RETURNING clauses.

3. Sql_cmd_dml::lex is now set during the constructor time.
  It makes things easier:
  - Sql_cmd_update::returns_result_set() needs the lex.
  - Sql_cmd_delete::orig_multitable and Sql_cmd_update::orig_multitable
    are not needed any more.
    They were used only in Sql_cmd_delete::sql_command_code() and
    Sql_cmd_update::sql_command_code().
    Sql_cmd_dml::sql_command_code() now returns lex->sql_command.
    The overrides Sql_cmd_delete::sql_command_code() and
    Sql_cmd_update::sql_command_code() were removed.

4. A new unsafe statement type BINLOG_STMT_UNSAFE_RETURNING_INTO is set
  for RETURNING..INTO. decide_logging_format() rejects the statement
  in the statement format, and logs it in the row format in MIXED.
  A new error message ER_BINLOG_UNSAFE_CLAUSE
  ("... because it uses %s ...") explains the unsafeness when
  a statement-only engine is used. It is filled by the new helper
  class Binlog_unsafe_explanation.
  A new debug injection point binlog_stmt_only_engine simulates such
  an engine in tests.

This commit also fixes bugs found during testing:
- MDEV-41262 ER_TOO_MANY_ROWS should be checked after CHECK OPTION
  in view while Update Returning Into
- MDEV-41265 SELECT/ UPDATE RETURNING INTO a single row-field fails
  with ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT, even though the column
  count matches
  This bug was also fixed in 12.3.4.
- MDEV-41260 Misleading message text "uses a LIMIT clause" after
  Update Returning Into
- MDEV-42212 UPDATE ... RETURNING ... INTO raises ER_TOO_MANY_ROWS
  on InnoDB when the second found row needs no update
- MDEV-41448 Update Returning Into expected to produce warning/error
  for zero-row plan (a test was added; the warning is now raised
  consistently)
- MDEV-41443 Update Returning into produces error when values don't
  change (a test was added; a warning is raised instead of an error)
- MDEV-42734 UPDATE ... RETURNING ... INTO a routine variable is
  written as a statement in ROW and MIXED binlog format, and the
  replica stops with "Undeclared variable" (see Limitation 6)
- MDEV-42715 Failed UPDATE ... RETURNING keeps the row change on MyISAM
  but loses its history row, FOR PORTION OF remainders and binlog event
Monty
Rename gtt functions.

Renames:
- global_tmp_table() -> is_gtt()
- local_tmp_table()  -> is_local_tmp_table()

New functions:
- is_gtt_instance()
- is_gtt_definition()
Monty
MDEV-35915 Part: Fixes for TRUNCATE of GTT

This patch adds:
- TRUNCATE of a GTT without an instance in the connection does
  nothing (assuming one has the privileges).
- To use TRUNCATE on a GTT instance/table one needs DELETE or DROP
  privilege.

A GTT without an instance in the connection has no data, so TRUNCATE
now just returns OK. Before, it was handled like a base table:
- Under LOCK TABLES it gave ER_TABLE_NOT_LOCKED, as the GTT definition
  is never locked. This also happened when the GTT was listed in LOCK
  TABLES with ON COMMIT DELETE ROWS, as the implicit commit of TRUNCATE
  drops the instance before the truncate.
- Without LOCK TABLES it took an exclusive metadata lock on the GTT
  definition and removed its share from the table definition cache.
  After the patch no MDL lock is taken (not needed as no changes will
  be done).

TRUNCATE of a GTT instance is unchanged (the instance is dropped).
Vladislav Vaintroub
MDEV-42087 Memory leak in sql_service when a statement fails after it sent its metadata

When a statement that runs through mysql_real_connect_local() fails
after it sent its metadata, the error is stored in the dataset of the
result set. embedded_get_error() freed only the MYSQL_DATA, and not its
MEM_ROOT, so 8192 bytes were lost, for example for a statement that is
aborted by KILL QUERY. Free the dataset with free_rows().

Assisted-by: Claude:claude-sonnet-5-5