=== added file 'Percona-Server/mysql-test/r/percona_bug_1113388.result'
--- Percona-Server/mysql-test/r/percona_bug_1113388.result	1970-01-01 00:00:00 +0000
+++ Percona-Server/mysql-test/r/percona_bug_1113388.result	2013-08-01 15:13:09 +0000
@@ -0,0 +1,16 @@
+DROP TABLE IF EXISTS t1;
+CREATE TABLE t1(a INT PRIMARY KEY) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1);
+INSERT INTO t1 VALUES (2);
+SET DEBUG_SYNC= 'after_copy_data_between_tables_one_row SIGNAL optimize_ready WAIT_FOR i_s_stopped';
+OPTIMIZE TABLE t1;
+SET DEBUG_SYNC= 'now WAIT_FOR optimize_ready';
+SET DEBUG_SYNC= 'before_store_temporary_table_record SIGNAL i_s_stopped';
+SELECT COUNT(*) FROM INFORMATION_SCHEMA.GLOBAL_TEMPORARY_TABLES;
+Table	Op	Msg_type	Msg_text
+test.t1	optimize	note	Table does not support optimize, doing recreate + analyze instead
+test.t1	optimize	status	OK
+SET DEBUG_SYNC= 'now SIGNAL optimize_completed';
+COUNT(*)
+1
+DROP TABLE t1;

=== added file 'Percona-Server/mysql-test/t/percona_bug_1113388.test'
--- Percona-Server/mysql-test/t/percona_bug_1113388.test	1970-01-01 00:00:00 +0000
+++ Percona-Server/mysql-test/t/percona_bug_1113388.test	2013-08-01 15:13:09 +0000
@@ -0,0 +1,34 @@
+# Test for bug 1113388 (field.cc:3822: virtual longlong Field_long::val_int(): Assertion `table->in_use == _current_thd()' failed)
+
+--source include/have_innodb.inc
+--source include/have_debug_sync.inc
+
+--disable_warnings
+DROP TABLE IF EXISTS t1;
+--enable_warnings
+
+CREATE TABLE t1(a INT PRIMARY KEY) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1);
+INSERT INTO t1 VALUES (2);
+
+SET DEBUG_SYNC= 'after_copy_data_between_tables_one_row SIGNAL optimize_ready WAIT_FOR i_s_stopped';
+send OPTIMIZE TABLE t1;
+
+connect (conn2,localhost,root,,);
+connection conn2;
+
+SET DEBUG_SYNC= 'now WAIT_FOR optimize_ready';
+SET DEBUG_SYNC= 'before_store_temporary_table_record SIGNAL i_s_stopped';
+send SELECT COUNT(*) FROM INFORMATION_SCHEMA.GLOBAL_TEMPORARY_TABLES;
+
+connection default;
+reap;
+SET DEBUG_SYNC= 'now SIGNAL optimize_completed';
+
+connection conn2;
+reap;
+
+disconnect conn2;
+connection default;
+
+DROP TABLE t1;

=== modified file 'Percona-Server/sql/ha_partition.cc'
--- Percona-Server/sql/ha_partition.cc	2013-02-14 16:03:49 +0000
+++ Percona-Server/sql/ha_partition.cc	2013-08-01 15:13:09 +0000
@@ -2872,6 +2872,12 @@
   ha_partition *new_handler;
 
   DBUG_ENTER("ha_partition::clone");
+
+  /* If this->table == NULL, then the current handler has been created but not
+  opened.  Prohibit cloning such handler.  */
+  if (!table)
+    DBUG_RETURN(NULL);
+
   new_handler= new (mem_root) ha_partition(ht, table_share, m_part_info,
                                            this, mem_root);
   /*

=== modified file 'Percona-Server/sql/handler.cc'
--- Percona-Server/sql/handler.cc	2013-06-27 15:35:20 +0000
+++ Percona-Server/sql/handler.cc	2013-08-01 15:13:09 +0000
@@ -2251,6 +2251,11 @@
 ****************************************************************************/
 handler *handler::clone(const char *name, MEM_ROOT *mem_root)
 {
+  /* If this->table == NULL, then the current handler has been created but not
+  opened.  Prohibit cloning such handler.  */
+  if (!table)
+    return NULL;
+
   handler *new_handler= get_new_handler(table->s, mem_root, ht);
   /*
     Allocate handler->ref here because otherwise ha_open will allocate it
@@ -2261,6 +2266,10 @@
      !(new_handler->ref= (uchar*) alloc_root(mem_root,
                                              ALIGN_SIZE(ref_length)*2)))
     new_handler= NULL;
+
+  if (new_handler)
+    new_handler->cloned = true;
+
   /*
     TODO: Implement a more efficient way to have more than one index open for
     the same table instance. The ha_open call is not cachable for clone.
@@ -2288,6 +2297,8 @@
 
 THD *handler::ha_thd(void) const
 {
+  if (unlikely(cloned))
+    return current_thd;
   DBUG_ASSERT(!table || !table->in_use || table->in_use == current_thd);
   return (table && table->in_use) ? table->in_use : current_thd;
 }

=== modified file 'Percona-Server/sql/handler.h'
--- Percona-Server/sql/handler.h	2013-01-22 16:32:44 +0000
+++ Percona-Server/sql/handler.h	2013-08-01 15:13:09 +0000
@@ -1399,7 +1399,8 @@
     locked(FALSE), implicit_emptied(0),
     pushed_cond(0), rows_read(0), rows_changed(0), next_insert_id(0), insert_id_for_cur_row(0),
     auto_inc_intervals_count(0),
-    m_psi(NULL)
+    m_psi(NULL),
+    cloned(false)
     {
       memset(index_rows_read, 0, sizeof(index_rows_read));
     }
@@ -2119,6 +2120,13 @@
   */
   virtual int delete_table(const char *name);
 private:
+
+  /**
+    If true, the current handler is a clone.  In that case certain invariants
+    such as table->in_use == current_thd do not hold.
+  */
+  bool cloned;
+
   /* Private helpers */
   inline void mark_trx_read_write();
 private:

=== modified file 'Percona-Server/sql/sql_show.cc'
--- Percona-Server/sql/sql_show.cc	2013-06-27 15:11:49 +0000
+++ Percona-Server/sql/sql_show.cc	2013-08-01 15:13:09 +0000
@@ -3743,37 +3743,43 @@
     it but rather clone it. */
     file = file->clone(tmp_table->s->normalized_path.str, thd->mem_root);
 
-    /**
-        TODO: InnoDB stat(file) checks file on short names within data dictionary
-        rather than using full path, because of that, temp files created in
-        TMPDIR will not have access/create time as it will not find the file
-
-        The fix is to patch InnoDB to use full path
-    */
-    file->info(HA_STATUS_VARIABLE | HA_STATUS_TIME | HA_STATUS_NO_LOCK);
-
-    table->field[5]->store((longlong) file->stats.records, TRUE);
-    table->field[5]->set_notnull();
-
-    table->field[6]->store((longlong) file->stats.mean_rec_length, TRUE);
-    table->field[7]->store((longlong) file->stats.data_file_length, TRUE);
-    table->field[8]->store((longlong) file->stats.index_file_length, TRUE);
-    if (file->stats.create_time)
-    {
-      thd->variables.time_zone->gmt_sec_to_TIME(&time,
-                                                (my_time_t) file->stats.create_time);
-      table->field[9]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
-      table->field[9]->set_notnull();
-    }
-    if (file->stats.update_time)
-    {
-      thd->variables.time_zone->gmt_sec_to_TIME(&time,
-                                                (my_time_t) file->stats.update_time);
-      table->field[10]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
-      table->field[10]->set_notnull();
-    }
-
-    file->close();
+    if (file) {
+
+      /**
+         TODO: InnoDB stat(file) checks file on short names within data
+         dictionary rather than using full path, because of that, temp files
+         created in TMPDIR will not have access/create time as it will not find
+         the file
+
+         The fix is to patch InnoDB to use full path
+      */
+      file->info(HA_STATUS_VARIABLE | HA_STATUS_TIME | HA_STATUS_NO_LOCK);
+
+      table->field[5]->store((longlong) file->stats.records, TRUE);
+      table->field[5]->set_notnull();
+
+      table->field[6]->store((longlong) file->stats.mean_rec_length, TRUE);
+      table->field[7]->store((longlong) file->stats.data_file_length, TRUE);
+      table->field[8]->store((longlong) file->stats.index_file_length, TRUE);
+      if (file->stats.create_time)
+      {
+        thd->variables.time_zone->gmt_sec_to_TIME(&time,
+                                                  (my_time_t)
+                                                  file->stats.create_time);
+        table->field[9]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
+        table->field[9]->set_notnull();
+      }
+      if (file->stats.update_time)
+      {
+        thd->variables.time_zone->gmt_sec_to_TIME(&time,
+                                                  (my_time_t)
+                                                  file->stats.update_time);
+        table->field[10]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
+        table->field[10]->set_notnull();
+      }
+
+      file->close();
+    }
   }
 
   DBUG_RETURN(schema_table_store_record(thd, table));
@@ -3823,17 +3829,13 @@
       }
 #endif
 
-      THD *t= tmp->in_use;
-      tmp->in_use= thd;
-
+      DEBUG_SYNC(thd, "before_store_temporary_table_record");
       if (store_temporary_table_record(thd_item, tables->table, tmp, thd->lex->select_lex.db, table_names_only)) {
-        tmp->in_use= t;
         mysql_mutex_unlock(&thd_item->LOCK_temporary_tables);
         mysql_mutex_unlock(&LOCK_thread_count); 
         DBUG_RETURN(1);
       }
 
-      tmp->in_use= t;
     }
     mysql_mutex_unlock(&thd_item->LOCK_temporary_tables);
   }

=== modified file 'Percona-Server/sql/sql_table.cc'
--- Percona-Server/sql/sql_table.cc	2013-06-26 07:01:13 +0000
+++ Percona-Server/sql/sql_table.cc	2013-08-01 15:13:09 +0000
@@ -7381,6 +7381,7 @@
     }
     prev_insert_id= to->file->next_insert_id;
     error=to->file->ha_write_row(to->record[0]);
+    DEBUG_SYNC(thd, "after_copy_data_between_tables_one_row");
     to->auto_increment_field_not_null= FALSE;
     if (error)
     {

