###############################################################################
# Bug#21317739: APPLYING CREATE TEMPORARY TABLE SQL ON A SLAVE WITH
# REPLICATE-REWRITE-DB FAILS
#
# Problem:
# =======
# As part of fix for BUG#16290902, at the time of writing the 'DROP TEMPORARY
# TABLE IF EXISTS' query into the binlog, the query will not be preceded by a
# 'use `db`' statement. The query will have a fully qualified table name.
# Eg:
# 'USE `db`; DROP TEMPORARY TABLE IF EXISTS `t1`;'
# will be logged as
# 'DROP TEMPORARY TABLE IF EXISTS `db`.`t1`;'.
#
# Because of this change application of 'replicate-rewrite-db' filter rule
# will fail on slave, as it works only on default database specified in 'use'
# statement. This causes slave to break when the 'CREATE TEMPORARY TABLE' is
# re-executed on slave.
#
# Test:
# =====
# Specify replicate-rewrite-db=test->new_test on slave. On master use 'test'
# database and 'CREATE TEMPORARY TABLE 't1'. Then drop the temporary table and
# recreate it on master. Now sync master with slave. Slave should be in sync
# and up and running.
###############################################################################
--source include/master-slave.inc
--source include/have_binlog_format_statement.inc

# Database 'test' on master is mapped with 'new_test' on slave by using
# replicate_rewrite_db filter
--source include/rpl_connection_slave.inc
CREATE DATABASE new_test;

# Create a temporary table on the default database.
--source include/rpl_connection_master.inc
use test;
CREATE TEMPORARY TABLE t1(id int);
--source include/sync_slave_sql_with_master.inc

# On slave verify that all the queries are rewritten as per the rewrite db
# rules.
--source include/show_binlog_events.inc

# On slave verify that one temporary table is created.
SHOW STATUS LIKE 'Slave_open_temp_tables';

# On master drop the temporary table.
--source include/rpl_connection_master.inc
use test;
DROP TEMPORARY TABLE IF EXISTS t1;

--source include/sync_slave_sql_with_master.inc
--source include/show_binlog_events.inc
# On slave verify that  temporary table is dropped. Hence output should
# be 0.
SHOW STATUS LIKE 'Slave_open_temp_tables';

# On master recreate the temporary tables once again.
--source include/rpl_connection_master.inc
use test;
CREATE TEMPORARY TABLE t1(id int);
--source include/sync_slave_sql_with_master.inc

# On slave temporary table should be recreated.
SHOW STATUS LIKE 'Slave_open_temp_tables';

# Disconnect the master, temp table on slave should dissapear
disconnect master;

--source include/rpl_connection_slave.inc
# Wait until drop of temp tables appers in slave's binlog
let $wait_binlog_event= DROP;
source include/wait_for_binlog_event.inc;

# On slave verify that  temporary table is dropped. Hence output should
# be 0.
SHOW STATUS LIKE 'Slave_open_temp_tables';

# ===========Clean up==========
DROP DATABASE new_test;

--source include/rpl_end.inc
