TABLE_LIST* find_dup_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list,
                           uint check_flag)
{
  TABLE_LIST *res= 0;
  const char *d_name, *t_name, *t_alias;
  DBUG_ENTER("find_dup_table");
  DBUG_PRINT("enter", ("table alias: %s", table->alias));

  /*
    If this function called for query which update table (INSERT/UPDATE/...)
    then we have in table->table pointer to TABLE object which we are
    updating even if it is VIEW so we need TABLE_LIST of this TABLE object
    to get right names (even if lower_case_table_names used).

    If this function called for CREATE command that we have not opened table
    (table->table equal to 0) and right names is in current TABLE_LIST
    object.
  */
  if (table->table)
  {
    /* All MyISAMMRG children are plain MyISAM tables. */
    DBUG_ASSERT(table->table->file->ht->db_type != DB_TYPE_MRG_MYISAM);

    table= table->find_underlying_table(table->table);
    /*
      as far as we have table->table we have to find real TABLE_LIST of
      it in underlying tables
    */
    DBUG_ASSERT(table);
  }
  d_name= table->db;
  t_name= table->table_name;
  t_alias= table->alias;

retry:
  DBUG_PRINT("info", ("real table: %s.%s", d_name, t_name));
  for (TABLE_LIST *tl= table_list; tl ; tl= tl->next_global, res= 0)
  {
    if (tl->select_lex && tl->select_lex->master_unit() &&
        tl->select_lex->master_unit()->executed)
    {
      /*
        There is no sense to check tables of already executed parts
        of the query
      */
      continue;
    }
    /*
      Table is unique if it is present only once in the global list
      of tables and once in the list of table locks.
    */
    if (! (res= find_table_in_global_list(tl, d_name, t_name)))
      break;
    tl= res;                       // We can continue search after this table

    /* Skip if same underlying table. */
    if (res->table && (res->table == table->table))
      continue;

    /* Skip if table is tmp table */
    if (check_flag & CHECK_DUP_SKIP_TEMP_TABLE &&
        res->table && res->table->s->tmp_table != NO_TMP_TABLE)
    {
      continue;
    }
    if (check_flag & CHECK_DUP_FOR_CREATE)
      DBUG_RETURN(res);

    /* Skip if table alias does not match. */
    if (check_flag & CHECK_DUP_ALLOW_DIFFERENT_ALIAS)
    {
      if (my_strcasecmp(table_alias_charset, t_alias, res->alias))
        continue;
    }

    /*
      If table is not excluded (could be a derived table) and table is not
      a prelocking placeholder then we found either a duplicate entry
      or a table that is part of a derived table (handled below).
      Examples are:
      INSERT INTO t1 SELECT * FROM t1;
      INSERT INTO t1 SELECT * FROM view_containing_t1;
    */
    if (res->select_lex &&
        !res->select_lex->exclude_from_table_unique_test &&
        !res->prelocking_placeholder)
      break;

    /*
      If we found entry of this table or table of SELECT which already
      processed in derived table or top select of multi-update/multi-delete
      (exclude_from_table_unique_test) or prelocking placeholder.
    */
    DBUG_PRINT("info",
               ("found same copy of table or table which we should skip"));
  }
  if (res && res->belong_to_derived)
  {
    /*
      We come here for queries of type:
      INSERT INTO t1 (SELECT tmp.a FROM (select * FROM t1) as tmp);

      Try to fix by materializing the derived table
    */
    TABLE_LIST *derived=  res->belong_to_derived;
    if (derived->is_merged_derived() && !derived->derived->is_excluded())
    {
      DBUG_PRINT("info",
                 ("convert merged to materialization to resolve the conflict"));
      derived->change_refs_to_fields();
      derived->set_materialized_derived();
      goto retry;
    }
  }
  DBUG_RETURN(res);
}


uint maria_get_pointer_length(ulonglong file_length, uint def)
{
  DBUG_ASSERT(def >= 2 && def <= 7);
  if (file_length)				/* If not default */
  {
#ifdef NOT_YET_READY_FOR_8_BYTE_POINTERS
    if (file_length >= (1ULL << 56))
      def=8;
    else
#endif
      if (file_length >= (1ULL << 48))
      def=7;
    else if (file_length >= (1ULL << 40))
      def=6;
    else if (file_length >= (1ULL << 32))
      def=5;
    else if (file_length >= (1ULL << 24))
      def=4;
    else if (file_length >= (1ULL << 16))
      def=3;
    else
      def=2;
  }
  return def;
}

MDEV-26351 segfault - (MARIA_HA *) 0x0 in ha_maria::extra

don't let Aria create a table that it cannot open


int _ma_initialize_data_file(MARIA_SHARE *share, File dfile)
{
  if (share->data_file_type == BLOCK_RECORD)
  {
    share->bitmap.block_size= share->base.block_size;
    share->bitmap.file.file = dfile;
    return _ma_bitmap_create_first(share);
  }
  return 0;
}


static int compare_columns(MARIA_COLUMNDEF **a_ptr, MARIA_COLUMNDEF **b_ptr)
{
  MARIA_COLUMNDEF *a= *a_ptr, *b= *b_ptr;
  enum en_fieldtype a_type, b_type;

  a_type= (a->type == FIELD_CHECK) ? FIELD_NORMAL : a->type;
  b_type= (b->type == FIELD_CHECK) ? FIELD_NORMAL : b->type;

  if (a_type == FIELD_NORMAL && !a->null_bit)
  {
    if (b_type != FIELD_NORMAL || b->null_bit)
      return -1;
    return sign((long) a->offset - (long) b->offset);
  }
  if (b_type == FIELD_NORMAL && !b->null_bit)
    return 1;
  if (a_type == b_type)
    return sign((long) a->offset - (long) b->offset);
  if (a_type == FIELD_NORMAL)
    return -1;
  if (b_type == FIELD_NORMAL)
    return 1;
  if (a_type == FIELD_SKIP_ZERO)
    return -1;
  if (b_type == FIELD_SKIP_ZERO)
    return 1;
  if (a->type != FIELD_BLOB && b->type != FIELD_BLOB)
    if (a->length != b->length)
      return sign((long) a->length - (long) b->length);
  if (a_type == FIELD_BLOB)
    return 1;
  if (b_type == FIELD_BLOB)
    return -1;
  return sign((long) a->offset - (long) b->offset);
}


int _ma_update_state_lsns(MARIA_SHARE *share, LSN lsn, TrID create_trid,
                          my_bool do_sync, my_bool update_create_rename_lsn)
{
  int res;
  DBUG_ENTER("_ma_update_state_lsns");
  mysql_mutex_lock(&share->intern_lock);
  res= _ma_update_state_lsns_sub(share, lsn, create_trid, do_sync,
                                 update_create_rename_lsn);
  mysql_mutex_unlock(&share->intern_lock);
  DBUG_RETURN(res);
}


int _ma_update_state_lsns_sub(MARIA_SHARE *share, LSN lsn, TrID create_trid,
                              my_bool do_sync,
                              my_bool update_create_rename_lsn)
{
  uchar buf[LSN_STORE_SIZE * 3], *ptr;
  uchar trid_buff[8];
  File file= share->kfile.file;
  DBUG_ASSERT(file >= 0);

  if (lsn == LSN_IMPOSSIBLE)
  {
    int res;
    LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 1];
    /* table name is logged only for information */
    log_array[TRANSLOG_INTERNAL_PARTS + 0].str=
      (uchar *)(share->open_file_name.str);
    log_array[TRANSLOG_INTERNAL_PARTS + 0].length=
      share->open_file_name.length + 1;
    if ((res= translog_write_record(&lsn, LOGREC_IMPORTED_TABLE,
                                    &dummy_transaction_object, NULL,
                                    (translog_size_t)
                                    log_array[TRANSLOG_INTERNAL_PARTS +
                                              0].length,
                                    sizeof(log_array)/sizeof(log_array[0]),
                                    log_array, NULL, NULL)))
      return res;
  }

  for (ptr= buf; ptr < (buf + sizeof(buf)); ptr+= LSN_STORE_SIZE)
    lsn_store(ptr, lsn);
  share->state.skip_redo_lsn= share->state.is_of_horizon= lsn;
  share->state.create_trid= create_trid;
  mi_int8store(trid_buff, create_trid);

  /*
    Update create_rename_lsn if update was requested or if the old one had an
    impossible value.
  */
  if (update_create_rename_lsn ||
      (share->state.create_rename_lsn > lsn && lsn != LSN_IMPOSSIBLE))
  {
    share->state.create_rename_lsn= lsn;
    if (share->id != 0)
    {
      /*
        If OP is the operation which is calling us, if table is later written,
        we could see in the log:
        FILE_ID ... REDO_OP ... REDO_INSERT.
        (that can happen in real life at least with OP=REPAIR).
        As FILE_ID will be ignored by Recovery because it is <
        create_rename_lsn, REDO_INSERT would be ignored too, wrongly.
        To avoid that, we force a LOGREC_FILE_ID to be logged at next write:
      */
      translog_deassign_id_from_share(share);
    }
  }
  else
    lsn_store(buf, share->state.create_rename_lsn);
  return (my_pwrite(file, buf, sizeof(buf),
                    sizeof(share->state.header) +
                    MARIA_FILE_CREATE_RENAME_LSN_OFFSET, MYF(MY_NABP)) ||
          my_pwrite(file, trid_buff, sizeof(trid_buff),
                    sizeof(share->state.header) +
                    MARIA_FILE_CREATE_TRID_OFFSET, MYF(MY_NABP)) ||
          (do_sync && mysql_file_sync(file, MYF(0))));
}


static inline int sign(long a)
{
  return a < 0 ? -1 : (a > 0 ? 1 : 0);
}


static ulonglong update_tot_length(ulonglong tot_length, ulonglong max_rows, uint length)
{
  ulonglong tot_length_part;

  if (tot_length == ULONGLONG_MAX)
    return ULONGLONG_MAX;

  tot_length_part= (max_rows/(ulong) ((maria_block_size -
                    MAX_KEYPAGE_HEADER_SIZE - KEYPAGE_CHECKSUM_SIZE)/
                    (length*2)));
  if (tot_length_part >=  ULONGLONG_MAX / maria_block_size)
    return ULONGLONG_MAX;

  if (tot_length > ULONGLONG_MAX - tot_length_part * maria_block_size)
    return ULONGLONG_MAX;

  return tot_length + tot_length_part * maria_block_size;
}


int maria_create(const char *name, enum data_file_type datafile_type,
                 uint keys,MARIA_KEYDEF *keydefs,
                 uint columns, MARIA_COLUMNDEF *columndef,
                 uint uniques, MARIA_UNIQUEDEF *uniquedefs,
                 MARIA_CREATE_INFO *ci,uint flags)
{
  register uint i,j;
  File UNINIT_VAR(dfile), UNINIT_VAR(file);
  int errpos,save_errno, create_mode= O_RDWR | O_TRUNC, res;
  myf create_flag;
  uint length,max_key_length,packed,pack_bytes,pointer,real_length_diff,
       key_length,info_length,key_segs,options,min_key_length,
       base_pos,long_varchar_count,
       unique_key_parts,fulltext_keys,offset, not_block_record_extra_length;
  uint max_field_lengths, extra_header_size, column_nr;
  uint internal_table= flags & HA_CREATE_INTERNAL_TABLE;
  ulong reclength, real_reclength,min_pack_length;
  char kfilename[FN_REFLEN], klinkname[FN_REFLEN], *klinkname_ptr= NullS;
  char dfilename[FN_REFLEN], dlinkname[FN_REFLEN], *dlinkname_ptr= 0;
  ulong pack_reclength;
  ulonglong tot_length,max_rows, tmp;
  enum en_fieldtype type;
  enum data_file_type org_datafile_type= datafile_type;
  MARIA_SHARE share;
  MARIA_KEYDEF *keydef,tmp_keydef;
  MARIA_UNIQUEDEF *uniquedef;
  HA_KEYSEG *keyseg,tmp_keyseg;
  MARIA_COLUMNDEF *column, *end_column;
  double *rec_per_key_part;
  ulong  *nulls_per_key_part;
  uint16 *column_array;
  my_off_t key_root[HA_MAX_POSSIBLE_KEY], kfile_size_before_extension;
  MARIA_CREATE_INFO tmp_create_info;
  my_bool tmp_table= FALSE; /* cache for presence of HA_OPTION_TMP_TABLE */
  my_bool forced_packed;
  myf     sync_dir=  0;
  uchar   *log_data= NULL;
  my_bool encrypted= maria_encrypt_tables && datafile_type == BLOCK_RECORD;
  my_bool insert_order= MY_TEST(flags & HA_PRESERVE_INSERT_ORDER);
  uint crypt_page_header_space= 0;
  DBUG_ENTER("maria_create");
  DBUG_PRINT("enter", ("keys: %u  columns: %u  uniques: %u  flags: %u",
                      keys, columns, uniques, flags));

  DBUG_ASSERT(maria_inited);

  if (!ci)
  {
    bzero((char*) &tmp_create_info,sizeof(tmp_create_info));
    ci=&tmp_create_info;
  }

  if (keys + uniques > MARIA_MAX_KEY)
  {
    DBUG_RETURN(my_errno=HA_WRONG_CREATE_OPTION);
  }
  errpos=0;
  options=0;
  bzero((uchar*) &share,sizeof(share));

  if (flags & HA_DONT_TOUCH_DATA)
  {
    /* We come here from recreate table */
    org_datafile_type= ci->org_data_file_type;
    if (!(ci->old_options & HA_OPTION_TEMP_COMPRESS_RECORD))
      options= (ci->old_options &
                (HA_OPTION_COMPRESS_RECORD | HA_OPTION_PACK_RECORD |
                 HA_OPTION_READ_ONLY_DATA | HA_OPTION_CHECKSUM |
                 HA_OPTION_TMP_TABLE | HA_OPTION_DELAY_KEY_WRITE |
                 HA_OPTION_LONG_BLOB_PTR | HA_OPTION_PAGE_CHECKSUM));
    else
    {
      /* Uncompressing rows */
      options= (ci->old_options &
                (HA_OPTION_CHECKSUM | HA_OPTION_TMP_TABLE |
                 HA_OPTION_DELAY_KEY_WRITE | HA_OPTION_LONG_BLOB_PTR |
                 HA_OPTION_PAGE_CHECKSUM));
    }
  }
  else
  {
    /* Transactional tables must be of type BLOCK_RECORD */
    if (ci->transactional)
      datafile_type= BLOCK_RECORD;
  }

  if (!(rec_per_key_part=
	(double*) my_malloc((keys + uniques)*HA_MAX_KEY_SEG*sizeof(double) +
                            (keys + uniques)*HA_MAX_KEY_SEG*sizeof(ulong) +
                            sizeof(uint16) * columns,
                            MYF(MY_WME | MY_ZEROFILL))))
    DBUG_RETURN(my_errno);
  nulls_per_key_part= (ulong*) (rec_per_key_part +
                                (keys + uniques) * HA_MAX_KEY_SEG);
  column_array= (uint16*) (nulls_per_key_part +
                           (keys + uniques) * HA_MAX_KEY_SEG);

  /* Start by checking fields and field-types used */
  long_varchar_count=packed= not_block_record_extra_length=
    pack_reclength= max_field_lengths= 0;
  reclength= min_pack_length= ci->null_bytes;
  forced_packed= 0;
  column_nr= 0;

  if (encrypted)
  {
    DBUG_ASSERT(datafile_type == BLOCK_RECORD);
    crypt_page_header_space= ma_crypt_get_data_page_header_space();
  }

  for (column= columndef, end_column= column + columns ;
       column != end_column ;
       column++)
  {
    /* Fill in not used struct parts */
    column->column_nr= column_nr++;
    column->offset= reclength;
    column->empty_pos= 0;
    column->empty_bit= 0;
    column->fill_length= column->length;
    if (column->null_bit)
      options|= HA_OPTION_NULL_FIELDS;

    reclength+= column->length;
    type= column->type;
    if (datafile_type == BLOCK_RECORD)
    {
      if (type == FIELD_SKIP_PRESPACE)
        type= column->type= FIELD_NORMAL; /* SKIP_PRESPACE not supported */
      if (type == FIELD_NORMAL &&
          column->length > FULL_PAGE_SIZE2(maria_block_size,
                                           crypt_page_header_space))
      {
        /* FIELD_NORMAL can't be split over many blocks, convert to a CHAR */
        type= column->type= FIELD_SKIP_ENDSPACE;
      }
    }

    if (type != FIELD_NORMAL && type != FIELD_CHECK)
    {
      column->empty_pos= packed/8;
      column->empty_bit= (1 << (packed & 7));
      if (type == FIELD_BLOB)
      {
        forced_packed= 1;
        packed++;
	share.base.blobs++;
	if (pack_reclength != INT_MAX32)
	{
	  if (column->length == 4+portable_sizeof_char_ptr)
	    pack_reclength= INT_MAX32;
	  else
          {
            /* Add max possible blob length */
	    pack_reclength+= (1 << ((column->length-
                                     portable_sizeof_char_ptr)*8));
          }
	}
        max_field_lengths+= (column->length - portable_sizeof_char_ptr);
      }
      else if (type == FIELD_SKIP_PRESPACE ||
	       type == FIELD_SKIP_ENDSPACE)
      {
        forced_packed= 1;
        max_field_lengths+= column->length > 255 ? 2 : 1;
        not_block_record_extra_length++;
        packed++;
      }
      else if (type == FIELD_VARCHAR)
      {
	pack_reclength++;
        not_block_record_extra_length++;
        max_field_lengths++;
        if (datafile_type != DYNAMIC_RECORD)
          packed++;
        column->fill_length= 1;
        options|= HA_OPTION_NULL_FIELDS;        /* Use ma_checksum() */

        /* We must test for 257 as length includes pack-length */
        if (MY_TEST(column->length >= 257))
	{
	  long_varchar_count++;
          max_field_lengths++;
          column->fill_length= 2;
	}
      }
      else if (type == FIELD_SKIP_ZERO)
        packed++;
      else
      {
        if (!column->null_bit)
          min_pack_length+= column->length;
        else
        {
          /* Only BLOCK_RECORD skips NULL fields for all field values */
          not_block_record_extra_length+= column->length;
        }
        column->empty_pos= 0;
        column->empty_bit= 0;
      }
    }
    else					/* FIELD_NORMAL */
    {
      if (!column->null_bit)
      {
        min_pack_length+= column->length;
        share.base.fixed_not_null_fields++;
        share.base.fixed_not_null_fields_length+= column->length;
      }
      else
        not_block_record_extra_length+= column->length;
    }
  }

  if (datafile_type == STATIC_RECORD && forced_packed)
  {
    /* Can't use fixed length records, revert to block records */
    datafile_type= BLOCK_RECORD;
  }

  if (datafile_type == NO_RECORD && uniques)
  {
    /* Can't do unique without data, revert to block records */
    datafile_type= BLOCK_RECORD;
  }

  if (encrypted)
  {
    /*
       datafile_type is set (finally?)
       update encryption that is only supported for BLOCK_RECORD
    */
    if (datafile_type != BLOCK_RECORD)
    {
      encrypted= FALSE;
      crypt_page_header_space= 0;
    }
  }

  if (datafile_type == DYNAMIC_RECORD)
    options|= HA_OPTION_PACK_RECORD;	/* Must use packed records */

  if (datafile_type == STATIC_RECORD || datafile_type == NO_RECORD)
  {
    /* We can't use checksum with static length rows */
    flags&= ~HA_CREATE_CHECKSUM;
    options&= ~HA_OPTION_CHECKSUM;
    min_pack_length= reclength;
    packed= 0;
  }
  else if (datafile_type != BLOCK_RECORD)
    min_pack_length+= not_block_record_extra_length;
  else
    min_pack_length+= 5;                        /* Min row overhead */

  if (flags & HA_CREATE_TMP_TABLE)
  {
    options|= HA_OPTION_TMP_TABLE;
    tmp_table= TRUE;
    create_mode|= O_NOFOLLOW | (internal_table ? 0 : O_EXCL);
    /* "CREATE TEMPORARY" tables are not crash-safe (dropped at restart) */
    ci->transactional= FALSE;
    flags&= ~HA_CREATE_PAGE_CHECKSUM;
  }
  share.base.null_bytes= ci->null_bytes;
  share.base.original_null_bytes= ci->null_bytes;
  share.base.born_transactional= ci->transactional;
  share.base.max_field_lengths= max_field_lengths;
  share.base.field_offsets= 0;                  /* for future */

  if (flags & HA_CREATE_CHECKSUM || (options & HA_OPTION_CHECKSUM))
  {
    options|= HA_OPTION_CHECKSUM;
    min_pack_length++;
    pack_reclength++;
  }
  if (pack_reclength < INT_MAX32)
    pack_reclength+= max_field_lengths + long_varchar_count;
  else
    pack_reclength= INT_MAX32;

  if (flags & HA_CREATE_DELAY_KEY_WRITE)
    options|= HA_OPTION_DELAY_KEY_WRITE;
  if (flags & HA_CREATE_RELIES_ON_SQL_LAYER)
    options|= HA_OPTION_RELIES_ON_SQL_LAYER;
  if (flags & HA_CREATE_PAGE_CHECKSUM)
    options|= HA_OPTION_PAGE_CHECKSUM;

  pack_bytes= (packed + 7) / 8;
  if (pack_reclength != INT_MAX32)
    pack_reclength+= reclength+pack_bytes +
      MY_TEST(test_all_bits(options, HA_OPTION_CHECKSUM |
                                     HA_OPTION_PACK_RECORD));
  min_pack_length+= pack_bytes;
  /* Calculate min possible row length for rows-in-block */
  extra_header_size= MAX_FIXED_HEADER_SIZE;
  if (ci->transactional)
  {
    extra_header_size= TRANS_MAX_FIXED_HEADER_SIZE;
    DBUG_PRINT("info",("creating a transactional table"));
  }
  share.base.min_block_length= (extra_header_size + share.base.null_bytes +
                                pack_bytes);
  if (!ci->data_file_length && ci->max_rows)
  {
    set_if_bigger(ci->max_rows, ci->reloc_rows);
    if (pack_reclength == INT_MAX32 ||
             (~(ulonglong) 0)/ci->max_rows < (ulonglong) pack_reclength)
      ci->data_file_length= ~(ulonglong) 0;
    else
    {
      ci->data_file_length= _ma_safe_mul(ci->max_rows, pack_reclength);
      if (datafile_type == BLOCK_RECORD)
      {
        /* Assume that blocks are only half full (very pessimistic!) */
        ci->data_file_length= _ma_safe_mul(ci->data_file_length, 2);
        set_if_bigger(ci->data_file_length, maria_block_size*2);
      }
    }
  }
  else if (!ci->max_rows)
  {
    if (datafile_type == BLOCK_RECORD)
    {
      uint rows_per_page=
          ((maria_block_size - PAGE_OVERHEAD_SIZE_RAW - crypt_page_header_space)
           / (min_pack_length + extra_header_size + DIR_ENTRY_SIZE));
      ulonglong data_file_length= ci->data_file_length;
      if (!data_file_length)
        data_file_length= ((((ulonglong) 1 << ((BLOCK_RECORD_POINTER_SIZE-1) *
                                               8))/2 -1) * maria_block_size);
      if (rows_per_page > 0)
      {
        set_if_smaller(rows_per_page, MAX_ROWS_PER_PAGE);
        ci->max_rows= (data_file_length / maria_block_size+1) * rows_per_page;
      }
      else
        ci->max_rows= data_file_length / (min_pack_length +
                                          extra_header_size +
                                          DIR_ENTRY_SIZE);
    }
    else
      ci->max_rows=(ha_rows) (ci->data_file_length/(min_pack_length +
                                                    ((options &
                                                      HA_OPTION_PACK_RECORD) ?
                                                     3 : 0)));
    set_if_smaller(ci->reloc_rows, ci->max_rows);
  }
  max_rows= (ulonglong) ci->max_rows;
  if (datafile_type == BLOCK_RECORD)
  {
    /*
      The + 1 is for record position withing page
      The * 2 is because we need one bit for knowing if there is transid's
      after the row pointer
    */
    pointer= maria_get_pointer_length((ci->data_file_length /
                                       maria_block_size) * 2, 4) + 1;
    set_if_smaller(pointer, BLOCK_RECORD_POINTER_SIZE);

    if (!max_rows)
      max_rows= (((((ulonglong) 1 << ((pointer-1)*8)) -1) * maria_block_size) /
                 min_pack_length / 2);
                                      }
  else
  {
    if (datafile_type == NO_RECORD)
      pointer= 0;
    else if (datafile_type != STATIC_RECORD)
      pointer= maria_get_pointer_length(ci->data_file_length,
                                        maria_data_pointer_size);
    else
      pointer= maria_get_pointer_length(ci->max_rows, maria_data_pointer_size);
    if (!max_rows)
      max_rows= ((((ulonglong) 1 << (pointer*8)) -1) / min_pack_length);
  }

  real_reclength=reclength;
  if (datafile_type == STATIC_RECORD)
  {
    if (reclength <= pointer)
      reclength=pointer+1;		/* reserve place for delete link */
  }
  else
    reclength+= long_varchar_count;	/* We need space for varchar! */

  max_key_length=0; tot_length=0 ; key_segs=0;
  fulltext_keys=0;
  share.state.rec_per_key_part=   rec_per_key_part;
  share.state.nulls_per_key_part= nulls_per_key_part;
  share.state.key_root=key_root;
  share.state.key_del= HA_OFFSET_ERROR;
  if (uniques)
    max_key_length= MARIA_UNIQUE_HASH_LENGTH + pointer;

  for (i=0, keydef=keydefs ; i < keys ; i++ , keydef++)
  {
    share.state.key_root[i]= HA_OFFSET_ERROR;
    length= real_length_diff= 0;
    min_key_length= key_length= pointer;

    if (keydef->key_alg == HA_KEY_ALG_RTREE)
      keydef->flag|= HA_RTREE_INDEX;            /* For easier tests */

    if (keydef->flag & HA_SPATIAL)
    {
#ifdef HAVE_SPATIAL
      /* BAR TODO to support 3D and more dimensions in the future */
      uint sp_segs=SPDIMS*2;
      keydef->flag=HA_SPATIAL;

      if (flags & HA_DONT_TOUCH_DATA)
      {
        /*
          Called by maria_chk - i.e. table structure was taken from
          MYI file and SPATIAL key *does have* additional sp_segs keysegs.
          keydef->seg here points right at the GEOMETRY segment,
          so we only need to decrease keydef->keysegs.
          (see maria_recreate_table() in _ma_check.c)
        */
        keydef->keysegs-=sp_segs-1;
      }

      for (j=0, keyseg=keydef->seg ; (int) j < keydef->keysegs ;
	   j++, keyseg++)
      {
        if (keyseg->type != HA_KEYTYPE_BINARY &&
	    keyseg->type != HA_KEYTYPE_VARBINARY1 &&
            keyseg->type != HA_KEYTYPE_VARBINARY2)
        {
          my_errno=HA_WRONG_CREATE_OPTION;
          goto err_no_lock;
        }
      }
      keydef->keysegs+=sp_segs;
      key_length+=SPLEN*sp_segs;
      length++;                              /* At least one length uchar */
      min_key_length++;
#else
      my_errno= HA_ERR_UNSUPPORTED;
      goto err_no_lock;
#endif /*HAVE_SPATIAL*/
    }
    else if (keydef->flag & HA_FULLTEXT)
    {
      keydef->flag=HA_FULLTEXT | HA_PACK_KEY | HA_VAR_LENGTH_KEY;
      options|=HA_OPTION_PACK_KEYS;             /* Using packed keys */

      for (j=0, keyseg=keydef->seg ; (int) j < keydef->keysegs ;
	   j++, keyseg++)
      {
        if (keyseg->type != HA_KEYTYPE_TEXT &&
	    keyseg->type != HA_KEYTYPE_VARTEXT1 &&
            keyseg->type != HA_KEYTYPE_VARTEXT2)
        {
          my_errno=HA_WRONG_CREATE_OPTION;
          goto err_no_lock;
        }
        if (!(keyseg->flag & HA_BLOB_PART) &&
	    (keyseg->type == HA_KEYTYPE_VARTEXT1 ||
             keyseg->type == HA_KEYTYPE_VARTEXT2))
        {
          /* Make a flag that this is a VARCHAR */
          keyseg->flag|= HA_VAR_LENGTH_PART;
          /* Store in bit_start number of bytes used to pack the length */
          keyseg->bit_start= ((keyseg->type == HA_KEYTYPE_VARTEXT1)?
                              1 : 2);
        }
      }

      fulltext_keys++;
      key_length+= HA_FT_MAXBYTELEN+HA_FT_WLEN;
      length++;                              /* At least one length uchar */
      min_key_length+= 1 + HA_FT_WLEN;
      real_length_diff=HA_FT_MAXBYTELEN-FT_MAX_WORD_LEN_FOR_SORT;
    }
    else
    {
      /* Test if prefix compression */
      if (keydef->flag & HA_PACK_KEY)
      {
	/* Can't use space_compression on number keys */
	if ((keydef->seg[0].flag & HA_SPACE_PACK) &&
	    keydef->seg[0].type == (int) HA_KEYTYPE_NUM)
	  keydef->seg[0].flag&= ~HA_SPACE_PACK;

	/* Only use HA_PACK_KEY when first segment is a variable length key */
	if (!(keydef->seg[0].flag & (HA_SPACE_PACK | HA_BLOB_PART |
				     HA_VAR_LENGTH_PART)))
	{
	  /* pack relative to previous key */
	  keydef->flag&= ~HA_PACK_KEY;
	  keydef->flag|= HA_BINARY_PACK_KEY | HA_VAR_LENGTH_KEY;
	}
	else
	{
	  keydef->seg[0].flag|=HA_PACK_KEY;	/* for easyer intern test */
	  keydef->flag|=HA_VAR_LENGTH_KEY;
	  options|=HA_OPTION_PACK_KEYS;		/* Using packed keys */
	}
      }
      if (keydef->flag & HA_BINARY_PACK_KEY)
	options|=HA_OPTION_PACK_KEYS;		/* Using packed keys */

      if (keydef->flag & HA_AUTO_KEY && ci->with_auto_increment)
	share.base.auto_key=i+1;
      for (j=0, keyseg=keydef->seg ; j < keydef->keysegs ; j++, keyseg++)
      {
	/* numbers are stored with high by first to make compression easier */
	switch (keyseg->type) {
	case HA_KEYTYPE_SHORT_INT:
	case HA_KEYTYPE_LONG_INT:
	case HA_KEYTYPE_FLOAT:
	case HA_KEYTYPE_DOUBLE:
	case HA_KEYTYPE_USHORT_INT:
	case HA_KEYTYPE_ULONG_INT:
	case HA_KEYTYPE_LONGLONG:
	case HA_KEYTYPE_ULONGLONG:
	case HA_KEYTYPE_INT24:
	case HA_KEYTYPE_UINT24:
	case HA_KEYTYPE_INT8:
	  keyseg->flag|= HA_SWAP_KEY;
          break;
        case HA_KEYTYPE_VARTEXT1:
        case HA_KEYTYPE_VARTEXT2:
        case HA_KEYTYPE_VARBINARY1:
        case HA_KEYTYPE_VARBINARY2:
          if (!(keyseg->flag & HA_BLOB_PART))
          {
            /* Make a flag that this is a VARCHAR */
            keyseg->flag|= HA_VAR_LENGTH_PART;
            /* Store in bit_start number of bytes used to pack the length */
            keyseg->bit_start= ((keyseg->type == HA_KEYTYPE_VARTEXT1 ||
                                 keyseg->type == HA_KEYTYPE_VARBINARY1) ?
                                1 : 2);
          }
          break;
	default:
	  break;
	}
	if (keyseg->flag & HA_SPACE_PACK)
	{
          DBUG_ASSERT(!(keyseg->flag & (HA_VAR_LENGTH_PART | HA_BLOB_PART)));
	  keydef->flag |= HA_SPACE_PACK_USED | HA_VAR_LENGTH_KEY;
	  options|=HA_OPTION_PACK_KEYS;		/* Using packed keys */
	  length++;				/* At least one length uchar */
          if (!keyseg->null_bit)
            min_key_length++;
          key_length+= keyseg->length;
	  if (keyseg->length >= 255)
	  {
            /* prefix may be 3 bytes */
	    length+= 2;
	  }
	}
	else if (keyseg->flag & (HA_VAR_LENGTH_PART | HA_BLOB_PART))
	{
          DBUG_ASSERT(!test_all_bits(keyseg->flag,
                                    (HA_VAR_LENGTH_PART | HA_BLOB_PART)));
	  keydef->flag|=HA_VAR_LENGTH_KEY;
	  length++;				/* At least one length uchar */
          if (!keyseg->null_bit)
            min_key_length++;
	  options|=HA_OPTION_PACK_KEYS;		/* Using packed keys */
          key_length+= keyseg->length;
	  if (keyseg->length >= 255)
	  {
            /* prefix may be 3 bytes */
	    length+= 2;
	  }
	}
        else
        {
          key_length+= keyseg->length;
          if (!keyseg->null_bit)
            min_key_length+= keyseg->length;
        }
	if (keyseg->null_bit)
	{
	  key_length++;
          /* min key part is 1 byte */
          min_key_length++;
	  options|=HA_OPTION_PACK_KEYS;
	  keyseg->flag|=HA_NULL_PART;
	  keydef->flag|=HA_VAR_LENGTH_KEY | HA_NULL_PART_KEY;
	}
      }
    } /* if HA_FULLTEXT */
    key_segs+=keydef->keysegs;
    if (keydef->keysegs > HA_MAX_KEY_SEG)
    {
      my_errno=HA_WRONG_CREATE_OPTION;
      goto err_no_lock;
    }
    /*
      key_segs may be 0 in the case when we only want to be able to
      add on row into the table. This can happen with some DISTINCT queries
      in MySQL
    */
    if ((keydef->flag & (HA_NOSAME | HA_NULL_PART_KEY)) == HA_NOSAME &&
	key_segs)
      share.state.rec_per_key_part[key_segs-1]=1L;
    length+=key_length;
    /*
      A key can't be longer than than half a index block (as we have
      to be able to put at least 2 keys on an index block for the key
      algorithms to work).
    */
    if (length > _ma_max_key_length())
    {
      my_errno=HA_WRONG_CREATE_OPTION;
      goto err_no_lock;
    }
    keydef->block_length= (uint16) maria_block_size;
    keydef->keylength= (uint16) key_length;
    keydef->minlength= (uint16) min_key_length;
    keydef->maxlength= (uint16) length;

    if (length > max_key_length)
      max_key_length= length;

    tot_length= update_tot_length(tot_length, max_rows, length);
  }

  unique_key_parts=0;
  for (i=0, uniquedef=uniquedefs ; i < uniques ; i++ , uniquedef++)
  {
    uniquedef->key=keys+i;
    unique_key_parts+=uniquedef->keysegs;
    share.state.key_root[keys+i]= HA_OFFSET_ERROR;

    tot_length= update_tot_length(tot_length, max_rows, MARIA_UNIQUE_HASH_LENGTH + pointer);
  }
  keys+=uniques;				/* Each unique has 1 key */
  key_segs+=uniques;				/* Each unique has 1 key seg */

  base_pos=(MARIA_STATE_INFO_SIZE + keys * MARIA_STATE_KEY_SIZE +
	    key_segs * MARIA_STATE_KEYSEG_SIZE);
  info_length= base_pos+(uint) (MARIA_BASE_INFO_SIZE+
                                keys * MARIA_KEYDEF_SIZE+
                                uniques * MARIA_UNIQUEDEF_SIZE +
                                (key_segs + unique_key_parts)*HA_KEYSEG_SIZE+
                                columns*(MARIA_COLUMNDEF_SIZE + 2));

  if (encrypted)
  {
    share.base.extra_options|= MA_EXTRA_OPTIONS_ENCRYPTED;

    /* store crypt data in info */
    info_length+= ma_crypt_get_file_length();
  }

  if (insert_order)
  {
    share.base.extra_options|= MA_EXTRA_OPTIONS_INSERT_ORDER;
  }

  share.state.state.key_file_length= MY_ALIGN(info_length, maria_block_size);
  DBUG_PRINT("info", ("info_length: %u", info_length));
  /* There are only 16 bits for the total header length. */
  if (share.state.state.key_file_length > 65535)
  {
    my_printf_error(HA_WRONG_CREATE_OPTION,
                    "Aria table '%s' has too many columns and/or "
                    "indexes and/or unique constraints.",
                    MYF(0), name + dirname_length(name));
    my_errno= HA_WRONG_CREATE_OPTION;
    goto err_no_lock;
  }

  bmove(share.state.header.file_version, maria_file_magic, 4);
  ci->old_options=options | (ci->old_options & HA_OPTION_TEMP_COMPRESS_RECORD ?
                             HA_OPTION_COMPRESS_RECORD |
                             HA_OPTION_TEMP_COMPRESS_RECORD: 0);
  mi_int2store(share.state.header.options,ci->old_options);
  mi_int2store(share.state.header.header_length,info_length);
  mi_int2store(share.state.header.state_info_length,MARIA_STATE_INFO_SIZE);
  mi_int2store(share.state.header.base_info_length,MARIA_BASE_INFO_SIZE);
  mi_int2store(share.state.header.base_pos,base_pos);
  share.state.header.data_file_type= share.data_file_type= datafile_type;
  share.state.header.org_data_file_type= org_datafile_type;
  share.state.header.not_used= 0;

  share.state.dellink = HA_OFFSET_ERROR;
  share.state.first_bitmap_with_space= 0;
#ifdef MARIA_EXTERNAL_LOCKING
  share.state.process=	(ulong) getpid();
#endif
  share.state.version=	(ulong) time((time_t*) 0);
  share.state.sortkey=  (ushort) ~0;
  share.state.auto_increment=ci->auto_increment;
  share.options=options;
  share.base.rec_reflength=pointer;
  share.base.block_size= maria_block_size;
  share.base.language= (ci->language ? ci->language :
                        default_charset_info->number);

  /*
    Get estimate for index file length (this may be wrong for FT keys)
    This is used for pointers to other key pages.
  */
  tmp= (tot_length / maria_block_size + keys * MARIA_INDEX_BLOCK_MARGIN);

  /*
    use maximum of key_file_length we calculated and key_file_length value we
    got from MAI file header (see also mariapack.c:save_state)
  */
  share.base.key_reflength=
    maria_get_pointer_length(MY_MAX(ci->key_file_length,tmp),3);
  share.base.keys= share.state.header.keys= keys;
  share.state.header.uniques= uniques;
  share.state.header.fulltext_keys= fulltext_keys;
  mi_int2store(share.state.header.key_parts,key_segs);
  mi_int2store(share.state.header.unique_key_parts,unique_key_parts);

  maria_set_all_keys_active(share.state.key_map, keys);

  share.base.keystart = share.state.state.key_file_length;
  share.base.max_key_block_length= maria_block_size;
  share.base.max_key_length=ALIGN_SIZE(max_key_length+4);
  share.base.records=ci->max_rows;
  share.base.reloc=  ci->reloc_rows;
  share.base.reclength=real_reclength;
  share.base.pack_reclength= reclength + MY_TEST(options & HA_OPTION_CHECKSUM);
  share.base.max_pack_length=pack_reclength;
  share.base.min_pack_length=min_pack_length;
  share.base.pack_bytes= pack_bytes;
  share.base.fields= columns;
  share.base.pack_fields= packed;

  if (share.data_file_type == BLOCK_RECORD)
  {
    /*
      we are going to create a first bitmap page, set data_file_length
      to reflect this, before the state goes to disk
    */
    share.state.state.data_file_length= maria_block_size;
    /* Add length of packed fields + length */
    share.base.pack_reclength+= share.base.max_field_lengths+3;
    share.base.max_pack_length= share.base.pack_reclength;

    /* Adjust max_pack_length, to be used if we have short rows */
    if (share.base.max_pack_length < maria_block_size)
    {
      share.base.max_pack_length+= FLAG_SIZE;
      if (ci->transactional)
        share.base.max_pack_length+= TRANSID_SIZE * 2;
    }
  }

  /* max_data_file_length and max_key_file_length are recalculated on open */
  if (tmp_table)
    share.base.max_data_file_length= (my_off_t) ci->data_file_length;
  else if (ci->transactional && translog_status == TRANSLOG_OK &&
           !maria_in_recovery)
  {
    /*
      we have checked translog_inited above, because maria_chk may call us
      (via maria_recreate_table()) and it does not have a log.
    */
    sync_dir= MY_SYNC_DIR;
    /*
      If crash between _ma_state_info_write_sub() and
      _ma_update_state__lsns_sub(), table should be ignored by Recovery (or
      old REDOs would fail), so we cannot let LSNs be 0:
    */
    share.state.skip_redo_lsn= share.state.is_of_horizon=
      share.state.create_rename_lsn= LSN_MAX;
  }

  if (datafile_type == DYNAMIC_RECORD)
  {
    share.base.min_block_length=
      (share.base.pack_reclength+3 < MARIA_EXTEND_BLOCK_LENGTH &&
       ! share.base.blobs) ?
      MY_MAX(share.base.pack_reclength,MARIA_MIN_BLOCK_LENGTH) :
      MARIA_EXTEND_BLOCK_LENGTH;
  }
  else if (datafile_type == STATIC_RECORD)
    share.base.min_block_length= share.base.pack_reclength;

  if (! (flags & HA_DONT_TOUCH_DATA))
    share.state.create_time= time((time_t*) 0);

  if (!internal_table)
    mysql_mutex_lock(&THR_LOCK_maria);

  /*
    NOTE: For test_if_reopen() we need a real path name. Hence we need
    MY_RETURN_REAL_PATH for every fn_format(filename, ...).
  */
  if (ci->index_file_name)
  {
    char *iext= strrchr(ci->index_file_name, '.');
    int have_iext= iext && !strcmp(iext, MARIA_NAME_IEXT);
    if (tmp_table)
    {
      char *path;
      /* chop off the table name, tempory tables use generated name */
      if ((path= strrchr(ci->index_file_name, FN_LIBCHAR)))
        *path= '\0';
      fn_format(kfilename, name, ci->index_file_name, MARIA_NAME_IEXT,
                MY_REPLACE_DIR | MY_UNPACK_FILENAME |
                MY_RETURN_REAL_PATH | MY_APPEND_EXT);
    }
    else
    {
      fn_format(kfilename, ci->index_file_name, "", MARIA_NAME_IEXT,
                MY_UNPACK_FILENAME | MY_RETURN_REAL_PATH |
                (have_iext ? MY_REPLACE_EXT : MY_APPEND_EXT));
    }
    fn_format(klinkname, name, "", MARIA_NAME_IEXT,
              MY_UNPACK_FILENAME|MY_APPEND_EXT);
    klinkname_ptr= klinkname;
    /*
      Don't create the table if the link or file exists to ensure that one
      doesn't accidently destroy another table.
      Don't sync dir now if the data file has the same path.
    */
    create_flag=
      (ci->data_file_name &&
       !strcmp(ci->index_file_name, ci->data_file_name)) ? 0 : sync_dir;
  }
  else
  {
    char *iext= strrchr(name, '.');
    int have_iext= iext && !strcmp(iext, MARIA_NAME_IEXT);
    fn_format(kfilename, name, "", MARIA_NAME_IEXT, MY_UNPACK_FILENAME |
              (internal_table ? 0 : MY_RETURN_REAL_PATH) |
              (have_iext ? MY_REPLACE_EXT : MY_APPEND_EXT));
    /*
      Replace the current file.
      Don't sync dir now if the data file has the same path.
    */
    create_flag=  (flags & HA_CREATE_KEEP_FILES) ? 0 : MY_DELETE_OLD;
    create_flag|= (!ci->data_file_name ? 0 : sync_dir);
  }

  /*
    If a MRG_MARIA table is in use, the mapped MARIA tables are open,
    but no entry is made in the table cache for them.
    A TRUNCATE command checks for the table in the cache only and could
    be fooled to believe, the table is not open.
    Pull the emergency brake in this situation. (Bug #8306)

    NOTE: The filename is compared against unique_file_name of every
    open table. Hence we need a real path here.
  */
  if (!internal_table && _ma_test_if_reopen(kfilename))
  {
    my_printf_error(HA_ERR_TABLE_EXIST, "Aria table '%s' is in use "
                    "(most likely by a MERGE table). Try FLUSH TABLES.",
                    MYF(0), name + dirname_length(name));
    my_errno= HA_ERR_TABLE_EXIST;
    goto err;
  }

  if ((file= mysql_file_create_with_symlink(key_file_kfile, klinkname_ptr,
                                            kfilename, 0, create_mode,
                                            MYF(MY_WME|create_flag))) < 0)
    goto err;
  errpos=1;

  DBUG_PRINT("info", ("write state info and base info"));
  if (_ma_state_info_write_sub(file, &share.state,
                               MA_STATE_INFO_WRITE_FULL_INFO) ||
      _ma_base_info_write(file, &share.base))
    goto err;
  DBUG_PRINT("info", ("base_pos: %d  base_info_size: %d",
                      base_pos, MARIA_BASE_INFO_SIZE));
  DBUG_ASSERT(mysql_file_tell(file,MYF(0)) == base_pos+ MARIA_BASE_INFO_SIZE);

  /* Write key and keyseg definitions */
  DBUG_PRINT("info", ("write key and keyseg definitions"));
  for (i=0 ; i < share.base.keys - uniques; i++)
  {
    uint sp_segs=(keydefs[i].flag & HA_SPATIAL) ? 2*SPDIMS : 0;

    if (_ma_keydef_write(file, &keydefs[i]))
      goto err;
    for (j=0 ; j < keydefs[i].keysegs-sp_segs ; j++)
      if (_ma_keyseg_write(file, &keydefs[i].seg[j]))
       goto err;
#ifdef HAVE_SPATIAL
    for (j=0 ; j < sp_segs ; j++)
    {
      HA_KEYSEG sseg;
      sseg.type=SPTYPE;
      sseg.language= 7;                         /* Binary */
      sseg.null_bit=0;
      sseg.bit_start=0;
      sseg.bit_length= 0;
      sseg.bit_pos= 0;
      sseg.length=SPLEN;
      sseg.null_pos=0;
      sseg.start=j*SPLEN;
      sseg.flag= HA_SWAP_KEY;
      if (_ma_keyseg_write(file, &sseg))
        goto err;
    }
#endif
  }
  /* Create extra keys for unique definitions */
  offset= real_reclength - uniques*MARIA_UNIQUE_HASH_LENGTH;
  bzero((char*) &tmp_keydef,sizeof(tmp_keydef));
  bzero((char*) &tmp_keyseg,sizeof(tmp_keyseg));
  for (i=0; i < uniques ; i++)
  {
    tmp_keydef.keysegs=1;
    tmp_keydef.flag=		HA_UNIQUE_CHECK;
    tmp_keydef.block_length=	(uint16) maria_block_size;
    tmp_keydef.keylength=	MARIA_UNIQUE_HASH_LENGTH + pointer;
    tmp_keydef.minlength=tmp_keydef.maxlength=tmp_keydef.keylength;
    tmp_keyseg.type=		MARIA_UNIQUE_HASH_TYPE;
    tmp_keyseg.length=		MARIA_UNIQUE_HASH_LENGTH;
    tmp_keyseg.start=		offset;
    offset+=			MARIA_UNIQUE_HASH_LENGTH;
    if (_ma_keydef_write(file,&tmp_keydef) ||
	_ma_keyseg_write(file,(&tmp_keyseg)))
      goto err;
  }

  /* Save unique definition */
  DBUG_PRINT("info", ("write unique definitions"));
  for (i=0 ; i < share.state.header.uniques ; i++)
  {
    HA_KEYSEG *keyseg_end;
    keyseg= uniquedefs[i].seg;
    if (_ma_uniquedef_write(file, &uniquedefs[i]))
      goto err;
    for (keyseg= uniquedefs[i].seg, keyseg_end= keyseg+ uniquedefs[i].keysegs;
         keyseg < keyseg_end;
         keyseg++)
    {
      switch (keyseg->type) {
      case HA_KEYTYPE_VARTEXT1:
      case HA_KEYTYPE_VARTEXT2:
      case HA_KEYTYPE_VARBINARY1:
      case HA_KEYTYPE_VARBINARY2:
        if (!(keyseg->flag & HA_BLOB_PART))
        {
          keyseg->flag|= HA_VAR_LENGTH_PART;
          keyseg->bit_start= ((keyseg->type == HA_KEYTYPE_VARTEXT1 ||
                               keyseg->type == HA_KEYTYPE_VARBINARY1) ?
                              1 : 2);
        }
        break;
      default:
        DBUG_ASSERT((keyseg->flag & HA_VAR_LENGTH_PART) == 0);
        break;
      }
      if (_ma_keyseg_write(file, keyseg))
	goto err;
    }
  }
  DBUG_PRINT("info", ("write field definitions"));
  if (datafile_type == BLOCK_RECORD)
  {
    /* Store columns in a more efficent order */
    MARIA_COLUMNDEF **col_order, **pos;
    if (!(col_order= (MARIA_COLUMNDEF**) my_malloc(share.base.fields *
                                                   sizeof(MARIA_COLUMNDEF*),
                                                   MYF(MY_WME))))
      goto err;
    for (column= columndef, pos= col_order ;
         column != end_column ;
         column++, pos++)
      *pos= column;
    qsort(col_order, share.base.fields, sizeof(*col_order),
          (qsort_cmp) compare_columns);
    for (i=0 ; i < share.base.fields ; i++)
    {
      column_array[col_order[i]->column_nr]= i;
      if (_ma_columndef_write(file, col_order[i]))
      {
        my_free(col_order);
        goto err;
      }
    }
    my_free(col_order);
  }
  else
  {
    for (i=0 ; i < share.base.fields ; i++)
    {
      column_array[i]= (uint16) i;
      if (_ma_columndef_write(file, &columndef[i]))
        goto err;
    }
  }
  if (_ma_column_nr_write(file, column_array, columns))
    goto err;

  if (encrypted)
  {
    if (ma_crypt_create(&share) ||
        ma_crypt_write(&share, file))
      goto err;
  }

  if ((kfile_size_before_extension= mysql_file_tell(file,MYF(0))) == MY_FILEPOS_ERROR)
    goto err;
#ifndef DBUG_OFF
  if (kfile_size_before_extension != info_length)
    DBUG_PRINT("warning",("info_length: %u  != used_length: %u",
			  info_length, (uint)kfile_size_before_extension));
#endif

  if (sync_dir)
  {
    /*
      we log the first bytes and then the size to which we extend; this is
      not log 1 KB of mostly zeroes if this is a small table.
    */
    char empty_string[]= "";
    LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 4];
    translog_size_t total_rec_length= 0;
    uint k;
    LSN lsn;
    log_array[TRANSLOG_INTERNAL_PARTS + 1].length= 1 + 2 + 2 +
      (uint) kfile_size_before_extension;
    /* we are needing maybe 64 kB, so don't use the stack */
    log_data= my_malloc(log_array[TRANSLOG_INTERNAL_PARTS + 1].length, MYF(0));
    if ((log_data == NULL) ||
        mysql_file_pread(file, 1 + 2 + 2 + log_data,
                 (size_t) kfile_size_before_extension, 0, MYF(MY_NABP)))
      goto err;
    /*
      remember if the data file was created or not, to know if Recovery can
      do it or not, in the future
    */
    log_data[0]= MY_TEST(flags & HA_DONT_TOUCH_DATA);
    int2store(log_data + 1, kfile_size_before_extension);
    int2store(log_data + 1 + 2, share.base.keystart);
    log_array[TRANSLOG_INTERNAL_PARTS + 0].str= (uchar *)name;
    /* we store the end-zero, for Recovery to just pass it to my_create() */
    log_array[TRANSLOG_INTERNAL_PARTS + 0].length= strlen(name) + 1;
    log_array[TRANSLOG_INTERNAL_PARTS + 1].str= log_data;
    /* symlink description is also needed for re-creation by Recovery: */
    {
      const char *s= ci->data_file_name ? ci->data_file_name : empty_string;
      log_array[TRANSLOG_INTERNAL_PARTS + 2].str= (uchar*)s;
      log_array[TRANSLOG_INTERNAL_PARTS + 2].length= strlen(s) + 1;
      s= ci->index_file_name ? ci->index_file_name : empty_string;
      log_array[TRANSLOG_INTERNAL_PARTS + 3].str= (uchar*)s;
      log_array[TRANSLOG_INTERNAL_PARTS + 3].length= strlen(s) + 1;
    }
    for (k= TRANSLOG_INTERNAL_PARTS;
         k < (sizeof(log_array)/sizeof(log_array[0])); k++)
      total_rec_length+= (translog_size_t) log_array[k].length;
    /**
       For this record to be of any use for Recovery, we need the upper
       MySQL layer to be crash-safe, which it is not now (that would require
       work using the ddl_log of sql/sql_table.cc); when it is, we should
       reconsider the moment of writing this log record (before or after op,
       under THR_LOCK_maria or not...), how to use it in Recovery.
       For now this record can serve when we apply logs to a backup,
       so we sync it. This happens before the data file is created. If the
       data file was created before, and we crashed before writing the log
       record, at restart the table may be used, so we would not have a
       trustable history in the log (impossible to apply this log to a
       backup). The way we do it, if we crash before writing the log record
       then there is no data file and the table cannot be used.
       @todo Note that in case of TRUNCATE TABLE we also come here; for
       Recovery to be able to finish TRUNCATE TABLE, instead of leaving a
       half-truncated table, we should log the record at start of
       maria_create(); for that we shouldn't write to the index file but to a
       buffer (DYNAMIC_STRING), put the buffer into the record, then put the
       buffer into the index file (so, change _ma_keydef_write() etc). That
       would also enable Recovery to finish a CREATE TABLE. The final result
       would be that we would be able to finish what the SQL layer has asked
       for: it would be atomic.
       When in CREATE/TRUNCATE (or DROP or RENAME or REPAIR) we have not
       called external_lock(), so have no TRN. It does not matter, as all
       these operations are non-transactional and sync their files.
    */
    if (unlikely(translog_write_record(&lsn,
                                       LOGREC_REDO_CREATE_TABLE,
                                       &dummy_transaction_object, NULL,
                                       total_rec_length,
                                       sizeof(log_array)/sizeof(log_array[0]),
                                       log_array, NULL, NULL) ||
                 translog_flush(lsn)))
      goto err;
    share.kfile.file= file;
    DBUG_EXECUTE_IF("maria_flush_whole_log",
                    {
                      DBUG_PRINT("maria_flush_whole_log", ("now"));
                      translog_flush(translog_get_horizon());
                    });
    DBUG_EXECUTE_IF("maria_crash_create_table",
                    {
                      DBUG_PRINT("maria_crash_create_table", ("now"));
                      DBUG_ABORT();
                    });
    /*
      store LSN into file, needed for Recovery to not be confused if a
      DROP+CREATE happened (applying REDOs to the wrong table).
    */
    if (_ma_update_state_lsns_sub(&share, lsn, trnman_get_min_safe_trid(),
                                  FALSE, TRUE))
      goto err;
    my_free(log_data);
  }

  if (!(flags & HA_DONT_TOUCH_DATA))
  {
    if (ci->data_file_name)
    {
      char *dext= strrchr(ci->data_file_name, '.');
      int have_dext= dext && !strcmp(dext, MARIA_NAME_DEXT);

      if (tmp_table)
      {
        char *path;
        /* chop off the table name, tempory tables use generated name */
        if ((path= strrchr(ci->data_file_name, FN_LIBCHAR)))
          *path= '\0';
        fn_format(dfilename, name, ci->data_file_name, MARIA_NAME_DEXT,
                  MY_REPLACE_DIR | MY_UNPACK_FILENAME | MY_APPEND_EXT);
      }
      else
      {
        fn_format(dfilename, ci->data_file_name, "", MARIA_NAME_DEXT,
                  MY_UNPACK_FILENAME |
                  (have_dext ? MY_REPLACE_EXT : MY_APPEND_EXT));
      }
      fn_format(dlinkname, name, "",MARIA_NAME_DEXT,
                MY_UNPACK_FILENAME | MY_APPEND_EXT);
      dlinkname_ptr= dlinkname;
      create_flag=0;
    }
    else
    {
      fn_format(dfilename,name,"", MARIA_NAME_DEXT,
                MY_UNPACK_FILENAME | MY_APPEND_EXT);
      create_flag= (flags & HA_CREATE_KEEP_FILES) ? 0 : MY_DELETE_OLD;
    }
    if ((dfile=
         mysql_file_create_with_symlink(key_file_dfile, dlinkname_ptr,
                                        dfilename, 0, create_mode,
                                        MYF(MY_WME | create_flag | sync_dir))) < 0)
      goto err;
    errpos=3;

    if (_ma_initialize_data_file(&share, dfile))
      goto err;
  }

	/* Enlarge files */
  DBUG_PRINT("info", ("enlarge to keystart: %lu",
                      (ulong) share.base.keystart));
  if (mysql_file_chsize(file,(ulong) share.base.keystart,0,MYF(0)))
    goto err;

  if (!internal_table && sync_dir && mysql_file_sync(file, MYF(0)))
    goto err;

  if (! (flags & HA_DONT_TOUCH_DATA))
  {
#ifdef USE_RELOC
    if (mysql_file_chsize(key_file_dfile, dfile,
                          share.base.min_pack_length*ci->reloc_rows,0,MYF(0)))
      goto err;
#endif
    if (!internal_table && sync_dir && mysql_file_sync(dfile, MYF(0)))
      goto err;
    if (mysql_file_close(dfile,MYF(0)))
      goto err;
  }
  if (!internal_table)
    mysql_mutex_unlock(&THR_LOCK_maria);
  res= 0;
  my_free((char*) rec_per_key_part);
  ma_crypt_free(&share);
  errpos=0;
  if (mysql_file_close(file,MYF(0)))
    res= my_errno;
  DBUG_RETURN(res);

err:
  if (!internal_table)
    mysql_mutex_unlock(&THR_LOCK_maria);

err_no_lock:
  save_errno=my_errno;
  switch (errpos) {
  case 3:
    mysql_file_close(dfile, MYF(0));
    if (! (flags & HA_DONT_TOUCH_DATA))
    {
      mysql_file_delete(key_file_dfile, dfilename, MYF(sync_dir));
      if (dlinkname_ptr)
        mysql_file_delete(key_file_dfile, dlinkname_ptr, MYF(sync_dir));
    }
    /* fall through */
  case 1:
    mysql_file_close(file, MYF(0));
    if (! (flags & HA_DONT_TOUCH_DATA))
    {
      mysql_file_delete(key_file_kfile, kfilename, MYF(sync_dir));
      if (klinkname_ptr)
        mysql_file_delete(key_file_kfile, klinkname_ptr, MYF(sync_dir));
    }
  }
  ma_crypt_free(&share);
  my_free(log_data);
  my_free(rec_per_key_part);
  DBUG_RETURN(my_errno=save_errno);		/* return the fatal errno */
}


static int rr_from_tempfile(READ_RECORD *info)
{
  int tmp;
  for (;;)
  {
    if (my_b_read(info->io_cache,info->ref_pos,info->ref_length))
      return -1;					/* End of file */
    if (!(tmp= info->table->file->ha_rnd_pos(info->record,info->ref_pos)))
      break;
    /* The following is extremely unlikely to happen */
    if (tmp == HA_ERR_RECORD_DELETED ||
        (tmp == HA_ERR_KEY_NOT_FOUND && info->ignore_not_found_rows))
      continue;
    tmp= rr_handle_error(info, tmp);
    break;
  }
  return tmp;
} /* rr_from_tempfile */

MDEV-26351 segfault - (MARIA_HA *) 0x0 in ha_maria::extra

use the correct check. before invoking handler methods we
need to know that the table was opened, not only created.


static int rr_unpack_from_buffer(READ_RECORD *info)
{
  if (info->cache_pos == info->cache_end)
    return -1;                      /* End of buffer */
  (*info->unpack)(info->addon_field, info->cache_pos,
                  info->cache_end);
  info->cache_pos+= info->ref_length;
  return 0;
}


static int rr_quick(READ_RECORD *info)
{
  int tmp;
  while ((tmp= info->select->quick->get_next()))
  {
    if (info->thd->killed || (tmp != HA_ERR_RECORD_DELETED))
    {
      tmp= rr_handle_error(info, tmp);
      break;
    }
  }
  return tmp;
}


void free_cache(READ_RECORD *info)
{
  if (info->cache)
  {
    my_free_lock(info->cache);
    info->cache=0;
  }
}


static int rr_unpack_from_tempfile(READ_RECORD *info)
{
  if (my_b_read(info->io_cache, info->rec_buf, info->ref_length))
    return -1;
  (*info->unpack)(info->addon_field, info->rec_buf,
                  info->rec_buf + info->ref_length);

  return 0;
}


int rr_from_pointers(READ_RECORD *info)
{
  int tmp;
  uchar *cache_pos;

  for (;;)
  {
    if (info->cache_pos == info->cache_end)
      return -1;					/* End of file */
    cache_pos= info->cache_pos;
    info->cache_pos+= info->ref_length;

    if (!(tmp= info->table->file->ha_rnd_pos(info->record,cache_pos)))
      break;

    /* The following is extremely unlikely to happen */
    if (tmp == HA_ERR_RECORD_DELETED ||
        (tmp == HA_ERR_KEY_NOT_FOUND && info->ignore_not_found_rows))
      continue;
    tmp= rr_handle_error(info, tmp);
    break;
  }
  return tmp;
}


bool init_read_record_idx(READ_RECORD *info, THD *thd, TABLE *table,
                          bool print_error, uint idx, bool reverse)
{
  int error= 0;
  DBUG_ENTER("init_read_record_idx");

  empty_record(table);
  bzero((char*) info,sizeof(*info));
  info->thd= thd;
  info->table= table;
  info->record= table->record[0];
  info->print_error= print_error;
  info->unlock_row= rr_unlock_row;

  table->status=0;			/* And it's always found */
  if (!table->file->inited &&
      (error= table->file->ha_index_init(idx, 1)))
  {
    if (print_error)
      table->file->print_error(error, MYF(0));
  }

  /* read_record will be changed to rr_index in rr_index_first */
  info->read_record= reverse ? rr_index_last : rr_index_first;
  DBUG_RETURN(error != 0);
}


static int rr_index_last(READ_RECORD *info)
{
  int tmp= info->table->file->ha_index_last(info->record);
  info->read_record= rr_index_desc;
  if (tmp)
    tmp= rr_handle_error(info, tmp);
  return tmp;
}


static int rr_handle_error(READ_RECORD *info, int error)
{
  if (info->thd->killed)
  {
    info->thd->send_kill_message();
    return 1;
  }

  if (error == HA_ERR_END_OF_FILE)
    error= -1;
  else
  {
    if (info->print_error)
      info->table->file->print_error(error, MYF(0));
    if (error < 0)                            // Fix negative BDB errno
      error= 1;
  }
  return error;
}


static int rr_index_desc(READ_RECORD *info)
{
  int tmp= info->table->file->ha_index_prev(info->record);
  if (tmp)
    tmp= rr_handle_error(info, tmp);
  return tmp;
}


static int init_rr_cache(THD *thd, READ_RECORD *info)
{
  uint rec_cache_size;
  DBUG_ENTER("init_rr_cache");

  info->struct_length= 3+MAX_REFLENGTH;
  info->reclength= ALIGN_SIZE(info->table->s->reclength+1);
  if (info->reclength < info->struct_length)
    info->reclength= ALIGN_SIZE(info->struct_length);

  info->error_offset= info->table->s->reclength;
  info->cache_records= (thd->variables.read_rnd_buff_size /
                        (info->reclength+info->struct_length));
  rec_cache_size= info->cache_records*info->reclength;
  info->rec_cache_size= info->cache_records*info->ref_length;

  // We have to allocate one more byte to use uint3korr (see comments for it)
  if (info->cache_records <= 2 ||
      !(info->cache=(uchar*) my_malloc_lock(rec_cache_size+info->cache_records*
					   info->struct_length+1,
					   MYF(MY_THREAD_SPECIFIC))))
    DBUG_RETURN(1);
#ifdef HAVE_valgrind
  // Avoid warnings in qsort
  bzero(info->cache,rec_cache_size+info->cache_records* info->struct_length+1);
#endif
  DBUG_PRINT("info",("Allocated buffert for %d records",info->cache_records));
  info->read_positions=info->cache+rec_cache_size;
  info->cache_pos=info->cache_end=info->cache;
  DBUG_RETURN(0);
} /* init_rr_cache */


static int rr_from_cache(READ_RECORD *info)
{
  uint i;
  ulong length;
  my_off_t rest_of_file;
  int16 error;
  uchar *position,*ref_position,*record_pos;
  ulong record;

  for (;;)
  {
    if (info->cache_pos != info->cache_end)
    {
      if (info->cache_pos[info->error_offset])
      {
	shortget(error,info->cache_pos);
	if (info->print_error)
	  info->table->file->print_error(error,MYF(0));
      }
      else
      {
	error=0;
	memcpy(info->record,info->cache_pos,
               (size_t) info->table->s->reclength);
      }
      info->cache_pos+=info->reclength;
      return ((int) error);
    }
    length=info->rec_cache_size;
    rest_of_file=info->io_cache->end_of_file - my_b_tell(info->io_cache);
    if ((my_off_t) length > rest_of_file)
      length= (ulong) rest_of_file;
    if (!length || my_b_read(info->io_cache,info->cache,length))
    {
      DBUG_PRINT("info",("Found end of file"));
      return -1;			/* End of file */
    }

    length/=info->ref_length;
    position=info->cache;
    ref_position=info->read_positions;
    for (i=0 ; i < length ; i++,position+=info->ref_length)
    {
      memcpy(ref_position,position,(size_t) info->ref_length);
      ref_position+=MAX_REFLENGTH;
      int3store(ref_position,(long) i);
      ref_position+=3;
    }
    my_qsort(info->read_positions, length, info->struct_length,
             (qsort_cmp) rr_cmp);

    position=info->read_positions;
    for (i=0 ; i < length ; i++)
    {
      memcpy(info->ref_pos,position,(size_t) info->ref_length);
      position+=MAX_REFLENGTH;
      record=uint3korr(position);
      position+=3;
      record_pos=info->cache+record*info->reclength;
      if ((error=(int16) info->table->file->ha_rnd_pos(record_pos,info->ref_pos)))
      {
	record_pos[info->error_offset]=1;
	shortstore(record_pos,error);
	DBUG_PRINT("error",("Got error: %d:%d when reading row",
			    my_errno, error));
      }
      else
	record_pos[info->error_offset]=0;
    }
    info->cache_end=(info->cache_pos=info->cache)+length*info->reclength;
  }
} /* rr_from_cache */


static int rr_cmp(uchar *a,uchar *b)
{
  if (a[0] != b[0])
    return (int) a[0] - (int) b[0];
  if (a[1] != b[1])
    return (int) a[1] - (int) b[1];
  if (a[2] != b[2])
    return (int) a[2] - (int) b[2];
#if MAX_REFLENGTH == 4
  return (int) a[3] - (int) b[3];
#else
  if (a[3] != b[3])
    return (int) a[3] - (int) b[3];
  if (a[4] != b[4])
    return (int) a[4] - (int) b[4];
  if (a[5] != b[5])
    return (int) a[5] - (int) b[5];
  if (a[6] != b[6])
    return (int) a[6] - (int) b[6];
  return (int) a[7] - (int) b[7];
#endif
}


static int rr_index_first(READ_RECORD *info)
{
  int tmp;
  // tell handler that we are doing an index scan
  if ((tmp = info->table->file->prepare_index_scan()))
  {
    tmp= rr_handle_error(info, tmp);
    return tmp;
  }

  tmp= info->table->file->ha_index_first(info->record);
  info->read_record= rr_index;
  if (tmp)
    tmp= rr_handle_error(info, tmp);
  return tmp;
}


void end_read_record(READ_RECORD *info)
{
  /* free cache if used */
  free_cache(info);
  if (info->table)
  {
    if (info->table->db_stat) // if opened
      (void) info->table->file->extra(HA_EXTRA_NO_CACHE);
    if (info->read_record != rr_quick) // otherwise quick_range does it
      (void) info->table->file->ha_index_or_rnd_end();
    info->table=0;
  }
}


bool init_read_record(READ_RECORD *info,THD *thd, TABLE *table,
		      SQL_SELECT *select,
                      SORT_INFO *filesort,
		      int use_record_cache, bool print_error,
                      bool disable_rr_cache)
{
  IO_CACHE *tempfile;
  SORT_ADDON_FIELD *addon_field= filesort ? filesort->addon_field : 0;
  DBUG_ENTER("init_read_record");

  bzero((char*) info,sizeof(*info));
  info->thd=thd;
  info->table=table;
  info->forms= &info->table;		/* Only one table */
  info->addon_field= addon_field;

  if ((table->s->tmp_table == INTERNAL_TMP_TABLE) &&
      !addon_field)
    (void) table->file->extra(HA_EXTRA_MMAP);

  if (addon_field)
  {
    info->rec_buf=    (uchar*) filesort->addon_buf.str;
    info->ref_length= filesort->addon_buf.length;
    info->unpack=     filesort->unpack;
  }
  else
  {
    empty_record(table);
    info->record= table->record[0];
    info->ref_length= table->file->ref_length;
  }
  info->select=select;
  info->print_error=print_error;
  info->unlock_row= rr_unlock_row;
  info->ignore_not_found_rows= 0;
  table->status= 0;			/* Rows are always found */

  tempfile= 0;
  if (select && my_b_inited(&select->file))
    tempfile= &select->file;
  else if (filesort && my_b_inited(&filesort->io_cache))
    tempfile= &filesort->io_cache;

  if (tempfile && !(select && select->quick))
  {
    DBUG_PRINT("info",("using rr_from_tempfile"));
    info->read_record= (addon_field ?
                        rr_unpack_from_tempfile : rr_from_tempfile);
    info->io_cache= tempfile;
    reinit_io_cache(info->io_cache,READ_CACHE,0L,0,0);
    info->ref_pos=table->file->ref;
    if (!table->file->inited)
      if (table->file->ha_rnd_init_with_error(0))
        DBUG_RETURN(1);

    /*
      addon_field is checked because if we use addon fields,
      it doesn't make sense to use cache - we don't read from the table
      and filesort->io_cache is read sequentially
    */
    if (!disable_rr_cache &&
        !addon_field &&
	thd->variables.read_rnd_buff_size &&
	!(table->file->ha_table_flags() & HA_FAST_KEY_READ) &&
	(table->db_stat & HA_READ_ONLY ||
	 table->reginfo.lock_type <= TL_READ_NO_INSERT) &&
	(ulonglong) table->s->reclength* (table->file->stats.records+
                                          table->file->stats.deleted) >
	(ulonglong) MIN_FILE_LENGTH_TO_USE_ROW_CACHE &&
	info->io_cache->end_of_file/info->ref_length * table->s->reclength >
	(my_off_t) MIN_ROWS_TO_USE_TABLE_CACHE &&
	!table->s->blob_fields &&
        info->ref_length <= MAX_REFLENGTH)
    {
      if (! init_rr_cache(thd, info))
      {
	DBUG_PRINT("info",("using rr_from_cache"));
	info->read_record=rr_from_cache;
      }
    }
  }
  else if (select && select->quick)
  {
    DBUG_PRINT("info",("using rr_quick"));
    info->read_record=rr_quick;
  }
  else if (filesort && filesort->record_pointers)
  {
    DBUG_PRINT("info",("using record_pointers"));
    if (table->file->ha_rnd_init_with_error(0))
      DBUG_RETURN(1);
    info->cache_pos= filesort->record_pointers;
    info->cache_end= (info->cache_pos+
                      filesort->return_rows * info->ref_length);
    info->read_record= (addon_field ?
                        rr_unpack_from_buffer : rr_from_pointers);
  }
  else if (table->file->keyread_enabled())
  {
    int error;
    info->read_record= rr_index_first;
    if (!table->file->inited &&
        (error= table->file->ha_index_init(table->file->keyread, 1)))
    {
      if (print_error)
        table->file->print_error(error, MYF(0));
      DBUG_RETURN(1);
    }
  }
  else
  {
    DBUG_PRINT("info",("using rr_sequential"));
    info->read_record=rr_sequential;
    if (table->file->ha_rnd_init_with_error(1))
      DBUG_RETURN(1);
    /* We can use record cache if we don't update dynamic length tables */
    if (!table->no_cache &&
	(use_record_cache > 0 ||
	 (int) table->reginfo.lock_type <= (int) TL_READ_HIGH_PRIORITY ||
	 !(table->s->db_options_in_use & HA_OPTION_PACK_RECORD) ||
	 (use_record_cache < 0 &&
	  !(table->file->ha_table_flags() & HA_NOT_DELETE_WITH_CACHE))))
      (void) table->file->extra_opt(HA_EXTRA_CACHE,
                                    thd->variables.read_buff_size);
  }
  /* Condition pushdown to storage engine */
  if ((table->file->ha_table_flags() & HA_CAN_TABLE_CONDITION_PUSHDOWN) &&
      select && select->cond &&
      (select->cond->used_tables() & table->map) &&
      !table->file->pushed_cond)
    table->file->cond_push(select->cond);

  DBUG_RETURN(0);
} /* init_read_record */


static int rr_index(READ_RECORD *info)
{
  int tmp= info->table->file->ha_index_next(info->record);
  if (tmp)
    tmp= rr_handle_error(info, tmp);
  return tmp;
}


int rr_sequential(READ_RECORD *info)
{
  int tmp;
  while ((tmp= info->table->file->ha_rnd_next(info->record)))
  {
    /*
      rnd_next can return RECORD_DELETED for MyISAM when one thread is
      reading and another deleting without locks.
    */
    if (info->thd->killed || (tmp != HA_ERR_RECORD_DELETED))
    {
      tmp= rr_handle_error(info, tmp);
      break;
    }
  }
  return tmp;
}


bool st_select_lex::inc_in_sum_expr()
{
  in_sum_expr++;
  return 0;
}

MDEV-25636: Bug report: abortion in sql/sql_parse.cc:6294

The asserion failure was caused by this query

  select /*id=1*/ from t1
  where
   col= ( select /*id=2*/ from ... where corr_cond1
          union
          select /*id=4*/ from ... where corr_cond2)

Here,
- select with id=2 was correlated due to corr_cond1.
- select with id=4 was initially correlated due to corr_cond2, but then
  the optimizer optimized away the correlation, making the select with id=4
  uncorrelated.

However, since select with id=2 remained correlated, the execution had to
re-compute the whole UNION. When it tried to execute select with id=4, it
hit an assertion  (join buffer already free'd).

This is because select with id=4 has freed its execution structures after
it has been executed once. The select is uncorrelated, so it did not expect
it would need to be executed for the second time.

Fixed this by adding this logic in
st_select_lex::optimize_unflattened_subqueries():

  If a member of a UNION is correlated, mark all its members as
  correlated, so that they are prepared to be executed multiple times.


void st_select_lex::alloc_index_hints (THD *thd)
{
  index_hints= new (thd->mem_root) List<Index_hint>();
}


bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
{
  return add_to_list(thd, order_list, item, asc);
}


void lex_init(void)
{
  uint i;
  DBUG_ENTER("lex_init");
  for (i=0 ; i < array_elements(symbols) ; i++)
    symbols[i].length=(uchar) strlen(symbols[i].name);
  for (i=0 ; i < array_elements(sql_functions) ; i++)
    sql_functions[i].length=(uchar) strlen(sql_functions[i].name);

  DBUG_VOID_RETURN;
}


void st_select_lex::remap_tables(TABLE_LIST *derived, table_map map,
                                 uint tablenr, SELECT_LEX *parent_lex)
{
  bool first_table= TRUE;
  TABLE_LIST *tl;
  table_map first_map;
  uint first_tablenr;

  if (derived && derived->table)
  {
    first_map= derived->table->map;
    first_tablenr= derived->table->tablenr;
  }
  else
  {
    first_map= map;
    map<<= 1;
    first_tablenr= tablenr++;
  }
  /*
    Assign table bit/table number.
    To the first table of the subselect the table bit/tablenr of the
    derived table is assigned. The rest of tables are getting bits
    sequentially, starting from the provided table map/tablenr.
  */
  List_iterator<TABLE_LIST> ti(leaf_tables);
  while ((tl= ti++))
  {
    if (first_table)
    {
      first_table= FALSE;
      tl->table->set_table_map(first_map, first_tablenr);
    }
    else
    {
      tl->table->set_table_map(map, tablenr);
      tablenr++;
      map<<= 1;
    }
    SELECT_LEX *old_sl= tl->select_lex;
    tl->select_lex= parent_lex;
    for(TABLE_LIST *emb= tl->embedding;
        emb && emb->select_lex == old_sl;
        emb= emb->embedding)
      emb->select_lex= parent_lex;
  }
}


void lex_unlock_plugins(LEX *lex)
{
  DBUG_ENTER("lex_unlock_plugins");

  /* release used plugins */
  if (lex->plugins.elements) /* No function call and no mutex if no plugins. */
  {
    plugin_unlock_list(0, (plugin_ref*)lex->plugins.buffer,
                       lex->plugins.elements);
  }
  reset_dynamic(&lex->plugins);
  DBUG_VOID_RETURN;
}


void st_select_lex_node::add_slave(st_select_lex_node *slave_arg)
{
  for (; slave; slave= slave->next)
    if (slave == slave_arg)
      return;

  if (slave)
  {
    st_select_lex_node *slave_arg_slave= slave_arg->slave;
    /* Insert in the front of list of slaves if any. */
    slave_arg->include_neighbour(slave);
    /* include_neighbour() sets slave_arg->slave=0, restore it. */
    slave_arg->slave= slave_arg_slave;
    /* Count on include_neighbour() setting the master. */
    DBUG_ASSERT(slave_arg->master == this);
  }
  else
  {
    slave= slave_arg;
    slave_arg->master= this;
  }
}


bool LEX::can_be_merged()
{
  // TODO: do not forget implement case when select_lex.table_list.elements==0

  /* find non VIEW subqueries/unions */
  bool selects_allow_merge= (select_lex.next_select() == 0 &&
                             !(select_lex.uncacheable &
                               UNCACHEABLE_RAND));
  if (selects_allow_merge)
  {
    for (SELECT_LEX_UNIT *tmp_unit= select_lex.first_inner_unit();
         tmp_unit;
         tmp_unit= tmp_unit->next_unit())
    {
      if (tmp_unit->first_select()->parent_lex == this &&
          (tmp_unit->item != 0 &&
           (tmp_unit->item->place() != IN_WHERE &&
            tmp_unit->item->place() != IN_ON &&
            tmp_unit->item->place() != SELECT_LIST)))
      {
        selects_allow_merge= 0;
        break;
      }
    }
  }

  return (selects_allow_merge &&
	  select_lex.group_list.elements == 0 &&
	  select_lex.having == 0 &&
          select_lex.with_sum_func == 0 &&
	  select_lex.table_list.elements >= 1 &&
	  !(select_lex.options & SELECT_DISTINCT) &&
          select_lex.select_limit == 0);
}


uint8 LEX::get_effective_with_check(TABLE_LIST *view)
{
  if (view->select_lex->master_unit() == &unit &&
      which_check_option_applicable())
    return (uint8)view->with_check;
  return VIEW_CHECK_NONE;
}


void lex_free(void)
{					// Call this when daemon ends
  DBUG_ENTER("lex_free");
  DBUG_VOID_RETURN;
}


int my_wc_mb_utf8_escape_single_quote_and_backslash(CHARSET_INFO *cs,
                                                    my_wc_t wc,
                                                    uchar *str, uchar *end)
{
  return my_wc_mb_utf8_escape(cs, wc, str, end, '\'', '\\');
}


void LEX::set_trg_event_type_for_tables()
{
  uint8 new_trg_event_map= 0;
  DBUG_ENTER("LEX::set_trg_event_type_for_tables");

  /*
    Some auxiliary operations
    (e.g. GRANT processing) create TABLE_LIST instances outside
    the parser. Additionally, some commands (e.g. OPTIMIZE) change
    the lock type for a table only after parsing is done. Luckily,
    these do not fire triggers and do not need to pre-load them.
    For these TABLE_LISTs set_trg_event_type is never called, and
    trg_event_map is always empty. That means that the pre-locking
    algorithm will ignore triggers defined on these tables, if
    any, and the execution will either fail with an assert in
    sql_trigger.cc or with an error that a used table was not
    pre-locked, in case of a production build.

    TODO: this usage pattern creates unnecessary module dependencies
    and should be rewritten to go through the parser.
    Table list instances created outside the parser in most cases
    refer to mysql.* system tables. It is not allowed to have
    a trigger on a system table, but keeping track of
    initialization provides extra safety in case this limitation
    is circumvented.
  */

  switch (sql_command) {
  case SQLCOM_LOCK_TABLES:
  /*
    On a LOCK TABLE, all triggers must be pre-loaded for this TABLE_LIST
    when opening an associated TABLE.
  */
    new_trg_event_map= static_cast<uint8>
                        (1 << static_cast<int>(TRG_EVENT_INSERT)) |
                      static_cast<uint8>
                        (1 << static_cast<int>(TRG_EVENT_UPDATE)) |
                      static_cast<uint8>
                        (1 << static_cast<int>(TRG_EVENT_DELETE));
    break;
  /*
    Basic INSERT. If there is an additional ON DUPLIATE KEY UPDATE
    clause, it will be handled later in this method.
  */
  case SQLCOM_INSERT:                           /* fall through */
  case SQLCOM_INSERT_SELECT:
  /*
    LOAD DATA ... INFILE is expected to fire BEFORE/AFTER INSERT
    triggers.
    If the statement also has REPLACE clause, it will be
    handled later in this method.
  */
  case SQLCOM_LOAD:                             /* fall through */
  /*
    REPLACE is semantically equivalent to INSERT. In case
    of a primary or unique key conflict, it deletes the old
    record and inserts a new one. So we also may need to
    fire ON DELETE triggers. This functionality is handled
    later in this method.
  */
  case SQLCOM_REPLACE:                          /* fall through */
  case SQLCOM_REPLACE_SELECT:
  /*
    CREATE TABLE ... SELECT defaults to INSERT if the table or
    view already exists. REPLACE option of CREATE TABLE ...
    REPLACE SELECT is handled later in this method.
  */
  case SQLCOM_CREATE_TABLE:
    new_trg_event_map|= static_cast<uint8>
                          (1 << static_cast<int>(TRG_EVENT_INSERT));
    break;
  /* Basic update and multi-update */
  case SQLCOM_UPDATE:                           /* fall through */
  case SQLCOM_UPDATE_MULTI:
    new_trg_event_map|= static_cast<uint8>
                          (1 << static_cast<int>(TRG_EVENT_UPDATE));
    break;
  /* Basic delete and multi-delete */
  case SQLCOM_DELETE:                           /* fall through */
  case SQLCOM_DELETE_MULTI:
    new_trg_event_map|= static_cast<uint8>
                          (1 << static_cast<int>(TRG_EVENT_DELETE));
    break;
  default:
    break;
  }

  switch (duplicates) {
  case DUP_UPDATE:
    new_trg_event_map|= static_cast<uint8>
                          (1 << static_cast<int>(TRG_EVENT_UPDATE));
    break;
  case DUP_REPLACE:
    new_trg_event_map|= static_cast<uint8>
                          (1 << static_cast<int>(TRG_EVENT_DELETE));
    break;
  case DUP_ERROR:
  default:
    break;
  }

  /*
    Do not iterate over sub-selects, only the tables in the outermost
    SELECT_LEX can be modified, if any.
  */
  TABLE_LIST *tables= select_lex.get_table_list();

  while (tables)
  {
    /*
      This is a fast check to filter out statements that do
      not change data, or tables  on the right side, in case of
      INSERT .. SELECT, CREATE TABLE .. SELECT and so on.
      Here we also filter out OPTIMIZE statement and non-updateable
      views, for which lock_type is TL_UNLOCK or TL_READ after
      parsing.
    */
    if (static_cast<int>(tables->lock_type) >=
        static_cast<int>(TL_WRITE_ALLOW_WRITE))
      tables->trg_event_map= new_trg_event_map;
    tables= tables->next_local;
  }
  DBUG_VOID_RETURN;
}


bool st_select_lex::save_leaf_tables(THD *thd)
{
  Query_arena *arena, backup;
  arena= thd->activate_stmt_arena_if_needed(&backup);

  List_iterator_fast<TABLE_LIST> li(leaf_tables);
  TABLE_LIST *table;
  while ((table= li++))
  {
    if (leaf_tables_exec.push_back(table, thd->mem_root))
      return 1;
    table->tablenr_exec= table->get_tablenr();
    table->map_exec= table->get_map();
    if (join && (join->select_options & SELECT_DESCRIBE))
      table->maybe_null_exec= 0;
    else
      table->maybe_null_exec= table->table?  table->table->maybe_null: 0;
  }
  if (arena)
    thd->restore_active_arena(arena, &backup);

  return 0;
}


bool st_select_lex::add_index_hint (THD *thd, char *str, uint length)
{
  return index_hints->push_front(new (thd->mem_root)
                                 Index_hint(current_index_hint_type,
                                            current_index_hint_clause,
                                            str, length), thd->mem_root);
}


void LEX::reset_arena_for_set_stmt(Query_arena *backup)
{
  DBUG_ENTER("LEX::reset_arena_for_set_stmt");
  DBUG_ASSERT(arena_for_set_stmt);
  thd->restore_active_arena(arena_for_set_stmt, backup);
  DBUG_PRINT("info", ("mem_root: %p  arena: %p",
                      arena_for_set_stmt->mem_root,
                      arena_for_set_stmt));
  DBUG_VOID_RETURN;
}


Item *st_select_lex::build_cond_for_grouping_fields(THD *thd, Item *cond,
						    bool no_top_clones)
{
  if (cond->get_extraction_flag() == FULL_EXTRACTION_FL)
  {
    if (no_top_clones)
      return cond;
    cond->clear_extraction_flag();
    return cond->build_clone(thd, thd->mem_root);
  }
  if (cond->type() == Item::COND_ITEM)
  {
    bool cond_and= false;
    Item_cond *new_cond;
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
    {
      cond_and= true;
      new_cond=  new (thd->mem_root) Item_cond_and(thd);
    }
    else
      new_cond= new (thd->mem_root) Item_cond_or(thd);
    if (!new_cond)
      return 0;
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
    Item *item;
    while ((item=li++))
    {
      if (item->get_extraction_flag() == NO_EXTRACTION_FL)
      {
	DBUG_ASSERT(cond_and);
	item->clear_extraction_flag();
	continue;
      }
      Item *fix= build_cond_for_grouping_fields(thd, item,
						no_top_clones & cond_and);
      if (!fix)
      {
	if (cond_and)
	  continue;
	break;
      }
      new_cond->argument_list()->push_back(fix, thd->mem_root);
    }

    if (!cond_and && item)
    {
      while((item= li++))
	item->clear_extraction_flag();
      return 0;
    }
    switch (new_cond->argument_list()->elements)
    {
    case 0:
      return 0;
    case 1:
      return new_cond->argument_list()->head();
    default:
      return new_cond;
    }
  }
  return 0;
}


Lex_input_stream::unescape(CHARSET_INFO *cs, char *to,
                           const char *str, const char *end,
                           int sep)
{
  return my_unescape(cs, to, str, end, sep, m_thd->backslash_escapes());
}


void LEX::free_arena_for_set_stmt()
{
  DBUG_ENTER("LEX::free_arena_for_set_stmt");
  if (!arena_for_set_stmt)
    return;
  DBUG_PRINT("info", ("mem_root: %p  arena: %p",
                      arena_for_set_stmt->mem_root,
                      arena_for_set_stmt));
  arena_for_set_stmt->free_items();
  delete(arena_for_set_stmt);
  free_root(mem_root_for_set_stmt, MYF(MY_KEEP_PREALLOC));
  arena_for_set_stmt= 0;
  DBUG_VOID_RETURN;
}


void st_select_lex::init_query()
{
  st_select_lex_node::init_query();
  table_list.empty();
  top_join_list.empty();
  join_list= &top_join_list;
  embedding= 0;
  leaf_tables_prep.empty();
  leaf_tables.empty();
  item_list.empty();
  min_max_opt_list.empty();
  join= 0;
  having= prep_having= where= prep_where= 0;
  cond_pushed_into_where= cond_pushed_into_having= 0;
  olap= UNSPECIFIED_OLAP_TYPE;
  having_fix_field= 0;
  having_fix_field_for_pushed_cond= 0;
  context.select_lex= this;
  context.init();
  /*
    Add the name resolution context of the current (sub)query to the
    stack of contexts for the whole query.
    TODO:
    push_context may return an error if there is no memory for a new
    element in the stack, however this method has no return value,
    thus push_context should be moved to a place where query
    initialization is checked for failure.
  */
  parent_lex->push_context(&context, parent_lex->thd->mem_root);
  cond_count= between_count= with_wild= 0;
  max_equal_elems= 0;
  ref_pointer_array.reset();
  select_n_where_fields= 0;
  select_n_reserved= 0;
  select_n_having_items= 0;
  n_sum_items= 0;
  n_child_sum_items= 0;
  hidden_bit_fields= 0;
  fields_in_window_functions= 0;
  subquery_in_having= explicit_limit= 0;
  is_item_list_lookup= 0;
  changed_elements= 0;
  first_natural_join_processing= 1;
  first_cond_optimization= 1;
  parsing_place= NO_MATTER;
  exclude_from_table_unique_test= no_wrap_view_item= FALSE;
  nest_level= 0;
  link_next= 0;
  prep_leaf_list_state= UNINIT;
  have_merged_subqueries= FALSE;
  bzero((char*) expr_cache_may_be_used, sizeof(expr_cache_may_be_used));
  select_list_tables= 0;
  m_non_agg_field_used= false;
  m_agg_func_used= false;
  window_specs.empty();
  window_funcs.empty();
}


int my_wc_mb_utf8_escape(CHARSET_INFO *cs, my_wc_t wc, uchar *str, uchar *end,
                         my_wc_t sep, my_wc_t escape)
{
  DBUG_ASSERT(escape == 0 || escape == '\\');
  DBUG_ASSERT(sep == '"' || sep == '\'');
  switch (wc) {
  case 0:      return my_wc_mb_utf8_opt_escape(cs, wc, escape, '0', str, end);
  case '\t':   return my_wc_mb_utf8_opt_escape(cs, wc, escape, 't', str, end);
  case '\r':   return my_wc_mb_utf8_opt_escape(cs, wc, escape, 'r', str, end);
  case '\n':   return my_wc_mb_utf8_opt_escape(cs, wc, escape, 'n', str, end);
  case '\032': return my_wc_mb_utf8_opt_escape(cs, wc, escape, 'Z', str, end);
  case '\'':
  case '\"':
    if (wc == sep)
      return my_wc_mb_utf8_with_escape(cs, wc, wc, str, end);
  }
  return my_charset_utf8_handler.wc_mb(cs, wc, str, end); // No escaping needed
}


bool st_select_lex::is_merged_child_of(st_select_lex *ancestor)
{
  bool all_merged= TRUE;
  for (SELECT_LEX *sl= this; sl && sl!=ancestor;
       sl=sl->outer_select())
  {
    Item *subs= sl->master_unit()->item;
    if (subs && subs->type() == Item::SUBSELECT_ITEM &&
        ((Item_subselect*)subs)->substype() == Item_subselect::IN_SUBS &&
        ((Item_in_subselect*)subs)->test_strategy(SUBS_SEMI_JOIN))
    {
      continue;
    }

    if (sl->master_unit()->derived &&
      sl->master_unit()->derived->is_merged_derived())
    {
      continue;
    }
    all_merged= FALSE;
    break;
  }
  return all_merged;
}


void st_select_lex_unit::exclude_level()
{
  SELECT_LEX_UNIT *units= 0, **units_last= &units;
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
  {
    // unlink current level from global SELECTs list
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
      sl->link_next->link_prev= sl->link_prev;

    // bring up underlay levels
    SELECT_LEX_UNIT **last= 0;
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
    {
      u->master= master;
      last= (SELECT_LEX_UNIT**)&(u->next);
    }
    if (last)
    {
      (*units_last)= sl->first_inner_unit();
      units_last= last;
    }
  }
  if (units)
  {
    // include brought up levels in place of current
    (*prev)= units;
    (*units_last)= (SELECT_LEX_UNIT*)next;
    if (next)
      next->prev= (SELECT_LEX_NODE**)units_last;
    units->prev= prev;
  }
  else
  {
    // exclude currect unit from list of nodes
    (*prev)= next;
    if (next)
      next->prev= prev;
  }
  // Mark it excluded
  prev= NULL;
}


void st_select_lex_node::exclude_from_tree()
{
  if ((*prev= next))
    next->prev= prev;
}


st_select_lex* st_select_lex::outer_select()
{
  return (st_select_lex*) master->get_master();
}


void Lex_input_stream::body_utf8_append_escape(THD *thd,
                                               const LEX_STRING *txt,
                                               CHARSET_INFO *cs,
                                               const char *end_ptr,
                                               my_wc_t sep)
{
  DBUG_ASSERT(sep == '\'' || sep == '"');
  if (!m_cpp_utf8_processed_ptr)
    return;
  uint errors;
  /**
    We previously alloced m_body_utf8 to be able to store the query with all
    strings properly escaped. See get_body_utf8_maximum_length().
    So here we have guaranteedly enough space to append any string literal
    with escaping. Passing txt->length*2 as "available space" is always safe.
    For better safety purposes we could calculate get_body_utf8_maximum_length()
    every time we append a string, but this would affect performance negatively,
    so let's check that we don't get beyond the allocated buffer in
    debug build only.
  */
  DBUG_ASSERT(m_body_utf8 + get_body_utf8_maximum_length(thd) >=
              m_body_utf8_ptr + txt->length * 2);
  uint32 cnv_length= my_convert_using_func(m_body_utf8_ptr, txt->length * 2,
                                           &my_charset_utf8_general_ci,
                                           get_escape_func(thd, sep),
                                           txt->str, txt->length,
                                           cs, cs->cset->mb_wc,
                                           &errors);
  m_body_utf8_ptr+= cnv_length;
  *m_body_utf8_ptr= 0;
  m_cpp_utf8_processed_ptr= end_ptr;
}


bool is_keyword(const char *name, uint len)
{
  DBUG_ASSERT(len != 0);
  return get_hash_symbol(name,len,0)!=0;
}


void Query_tables_list::reset_query_tables_list(bool init)
{
  sql_command= SQLCOM_END;
  if (!init && query_tables)
  {
    TABLE_LIST *table= query_tables;
    for (;;)
    {
      delete table->view;
      if (query_tables_last == &table->next_global ||
          !(table= table->next_global))
        break;
    }
  }
  query_tables= 0;
  query_tables_last= &query_tables;
  query_tables_own_last= 0;
  if (init)
  {
    /*
      We delay real initialization of hash (and therefore related
      memory allocation) until first insertion into this hash.
    */
    my_hash_clear(&sroutines);
  }
  else if (sroutines.records)
  {
    /* Non-zero sroutines.records means that hash was initialized. */
    my_hash_reset(&sroutines);
  }
  sroutines_list.empty();
  sroutines_list_own_last= sroutines_list.next;
  sroutines_list_own_elements= 0;
  binlog_stmt_flags= 0;
  stmt_accessed_table_flag= 0;
}


bool Lex_input_stream::init(THD *thd,
			    char* buff,
			    unsigned int length)
{
  DBUG_EXECUTE_IF("bug42064_simulate_oom",
                  DBUG_SET("+d,simulate_out_of_memory"););

  m_cpp_buf= (char*) thd->alloc(length + 1);

  DBUG_EXECUTE_IF("bug42064_simulate_oom",
                  DBUG_SET("-d,bug42064_simulate_oom"););

  if (m_cpp_buf == NULL)
    return TRUE;

  m_thd= thd;
  reset(buff, length);

  return FALSE;
}


void st_select_lex_unit::exclude_tree()
{
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
  {
    // unlink current level from global SELECTs list
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
      sl->link_next->link_prev= sl->link_prev;

    // unlink underlay levels
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
    {
      u->exclude_level();
    }
  }
  // exclude currect unit from list of nodes
  (*prev)= next;
  if (next)
    next->prev= prev;
}