<commit_before>/* Copyright (C) 2003 MySQL AB

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#ifdef __GNUC__
#pragma implementation        // gcc: Class implementation
#endif

#include <mysql_priv.h>

#ifdef HAVE_ARCHIVE_DB
#include "ha_archive.h"

/*
  First, if you want to understand storage engines you should look at 
  ha_example.cc and ha_example.h. 
  This example was written as a test case for a customer who needed
  a storage engine without indexes that could compress data very well.
  So, welcome to a completely compressed storage engine. This storage
  engine only does inserts. No replace, deletes, or updates. All reads are 
  complete table scans. Compression is done through gzip (bzip compresses
  better, but only marginally, if someone asks I could add support for
  it too, but beaware that it costs a lot more in CPU time then gzip).
  
  We keep a file pointer open for each instance of ha_archive for each read
  but for writes we keep one open file handle just for that. We flush it
  only if we have a read occur. gzip handles compressing lots of records
  at once much better then doing lots of little records between writes.
  It is possible to not lock on writes but this would then mean we couldn't
  handle bulk inserts as well (that is if someone was trying to read at
  the same time since we would want to flush).

  No attempts at durability are made. You can corrupt your data.

  For performance as far as table scans go it is quite fast. I don't have
  good numbers but locally it has out performed both Innodb and MyISAM. For
  Innodb the question will be if the table can be fit into the buffer
  pool. For MyISAM its a question of how much the file system caches the
  MyISAM file. With enough free memory MyISAM is faster. Its only when the OS
  doesn't have enough memory to cache entire table that archive turns out 
  to be any faster. For writes it is always a bit slower then MyISAM. It has no
  internal limits though for row length.

  Examples between MyISAM (packed) and Archive.

  Table with 76695844 identical rows:
  29680807 a_archive.ARZ
  920350317 a.MYD


  Table with 8991478 rows (all of Slashdot's comments):
  1922964506 comment_archive.ARZ
  2944970297 comment_text.MYD


  TODO:
   Add bzip optional support.
   Allow users to set compression level.
   Add truncate table command.
   Implement versioning, should be easy.
   Implement optimize so we can fix broken tables.
   Allow for errors, find a way to mark bad rows.
   See if during an optimize you can make the table smaller.
   Talk to the gzip guys, come up with a writable format so that updates are doable
     without switching to a block method.
   Add optional feature so that rows can be flushed at interval (which will cause less
   compression but may speed up ordered searches).

    -Brian
*/

/* Variables for archive share methods */
pthread_mutex_t archive_mutex;
static HASH archive_open_tables;
static int archive_init= 0;

/* The file extension */
#define ARZ ".ARZ"

/*
  Used for hash table that tracks open tables.
*/
static byte* archive_get_key(ARCHIVE_SHARE *share,uint *length,
                             my_bool not_used __attribute__((unused)))
{
  *length=share->table_name_length;
  return (byte*) share->table_name;
}


/*
  Example of simple lock controls.
  See ha_example.cc for a description.
*/
static ARCHIVE_SHARE *get_share(const char *table_name, TABLE *table)
{
  ARCHIVE_SHARE *share;
  uint length;
  char *tmp_name;

  if (!archive_init)
  {
    /* Hijack a mutex for init'ing the storage engine */
    pthread_mutex_lock(&LOCK_mysql_create_db);
    if (!archive_init)
    {
      archive_init++;
      VOID(pthread_mutex_init(&archive_mutex,MY_MUTEX_INIT_FAST));
      (void) hash_init(&archive_open_tables,system_charset_info,32,0,0,
                       (hash_get_key) archive_get_key,0,0);
    }
    pthread_mutex_unlock(&LOCK_mysql_create_db);
  }
  pthread_mutex_lock(&archive_mutex);
  length=(uint) strlen(table_name);

  if (!(share=(ARCHIVE_SHARE*) hash_search(&archive_open_tables,
                                           (byte*) table_name,
                                           length)))
  {
    if (!(share=(ARCHIVE_SHARE *)
          my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
                          &share, sizeof(*share),
                          &tmp_name, length+1,
                          NullS))) 
    {
      pthread_mutex_unlock(&archive_mutex);
      return NULL;
    }

    share->use_count=0;
    share->table_name_length=length;
    share->table_name=tmp_name;
    fn_format(share->data_file_name,table_name,"",ARZ,MY_REPLACE_EXT|MY_UNPACK_FILENAME);
    strmov(share->table_name,table_name);
    /* 
      It is expensive to open and close the data files and since you can't have
      a gzip file that can be both read and written we keep a writer open
      that is shared amoung all open tables.
    */
    if ((share->archive_write= gzopen(share->data_file_name, "ab")) == NULL)
      goto error;
    if (my_hash_insert(&archive_open_tables, (byte*) share))
      goto error;
    thr_lock_init(&share->lock);
    if (pthread_mutex_init(&share->mutex,MY_MUTEX_INIT_FAST))
      goto error2;
  }
  share->use_count++;
  pthread_mutex_unlock(&archive_mutex);

  return share;

error2:
  thr_lock_delete(&share->lock);
  /* We close, but ignore errors since we already have errors */
  (void)gzclose(share->archive_write);
error:
  pthread_mutex_unlock(&archive_mutex);
  my_free((gptr) share, MYF(0));

  return NULL;
}


/* 
  Free lock controls.
  See ha_example.cc for a description.
*/
static int free_share(ARCHIVE_SHARE *share)
{
  int rc= 0;
  pthread_mutex_lock(&archive_mutex);
  if (!--share->use_count)
  {
    hash_delete(&archive_open_tables, (byte*) share);
    thr_lock_delete(&share->lock);
    pthread_mutex_destroy(&share->mutex);
    my_free((gptr) share, MYF(0));
    if (gzclose(share->archive_write) == Z_ERRNO)
      rc= -1;
  }
  pthread_mutex_unlock(&archive_mutex);

  return rc;
}


/* 
  We just implement one additional file extension.
*/
const char **ha_archive::bas_ext() const
{ static const char *ext[]= { ARZ, NullS }; return ext; }


/* 
  When opening a file we:
  Create/get our shared structure.<commit_msg>ha_archive.cc:   Memory was used after it has been alreay freed.   This led to server crash on FreeBSD.<commit_after>/* Copyright (C) 2003 MySQL AB

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#ifdef __GNUC__
#pragma implementation        // gcc: Class implementation
#endif

#include <mysql_priv.h>

#ifdef HAVE_ARCHIVE_DB
#include "ha_archive.h"

/*
  First, if you want to understand storage engines you should look at 
  ha_example.cc and ha_example.h. 
  This example was written as a test case for a customer who needed
  a storage engine without indexes that could compress data very well.
  So, welcome to a completely compressed storage engine. This storage
  engine only does inserts. No replace, deletes, or updates. All reads are 
  complete table scans. Compression is done through gzip (bzip compresses
  better, but only marginally, if someone asks I could add support for
  it too, but beaware that it costs a lot more in CPU time then gzip).
  
  We keep a file pointer open for each instance of ha_archive for each read
  but for writes we keep one open file handle just for that. We flush it
  only if we have a read occur. gzip handles compressing lots of records
  at once much better then doing lots of little records between writes.
  It is possible to not lock on writes but this would then mean we couldn't
  handle bulk inserts as well (that is if someone was trying to read at
  the same time since we would want to flush).

  No attempts at durability are made. You can corrupt your data.

  For performance as far as table scans go it is quite fast. I don't have
  good numbers but locally it has out performed both Innodb and MyISAM. For
  Innodb the question will be if the table can be fit into the buffer
  pool. For MyISAM its a question of how much the file system caches the
  MyISAM file. With enough free memory MyISAM is faster. Its only when the OS
  doesn't have enough memory to cache entire table that archive turns out 
  to be any faster. For writes it is always a bit slower then MyISAM. It has no
  internal limits though for row length.

  Examples between MyISAM (packed) and Archive.

  Table with 76695844 identical rows:
  29680807 a_archive.ARZ
  920350317 a.MYD


  Table with 8991478 rows (all of Slashdot's comments):
  1922964506 comment_archive.ARZ
  2944970297 comment_text.MYD


  TODO:
   Add bzip optional support.
   Allow users to set compression level.
   Add truncate table command.
   Implement versioning, should be easy.
   Implement optimize so we can fix broken tables.
   Allow for errors, find a way to mark bad rows.
   See if during an optimize you can make the table smaller.
   Talk to the gzip guys, come up with a writable format so that updates are doable
     without switching to a block method.
   Add optional feature so that rows can be flushed at interval (which will cause less
   compression but may speed up ordered searches).

    -Brian
*/

/* Variables for archive share methods */
pthread_mutex_t archive_mutex;
static HASH archive_open_tables;
static int archive_init= 0;

/* The file extension */
#define ARZ ".ARZ"

/*
  Used for hash table that tracks open tables.
*/
static byte* archive_get_key(ARCHIVE_SHARE *share,uint *length,
                             my_bool not_used __attribute__((unused)))
{
  *length=share->table_name_length;
  return (byte*) share->table_name;
}


/*
  Example of simple lock controls.
  See ha_example.cc for a description.
*/
static ARCHIVE_SHARE *get_share(const char *table_name, TABLE *table)
{
  ARCHIVE_SHARE *share;
  uint length;
  char *tmp_name;

  if (!archive_init)
  {
    /* Hijack a mutex for init'ing the storage engine */
    pthread_mutex_lock(&LOCK_mysql_create_db);
    if (!archive_init)
    {
      archive_init++;
      VOID(pthread_mutex_init(&archive_mutex,MY_MUTEX_INIT_FAST));
      (void) hash_init(&archive_open_tables,system_charset_info,32,0,0,
                       (hash_get_key) archive_get_key,0,0);
    }
    pthread_mutex_unlock(&LOCK_mysql_create_db);
  }
  pthread_mutex_lock(&archive_mutex);
  length=(uint) strlen(table_name);

  if (!(share=(ARCHIVE_SHARE*) hash_search(&archive_open_tables,
                                           (byte*) table_name,
                                           length)))
  {
    if (!(share=(ARCHIVE_SHARE *)
          my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
                          &share, sizeof(*share),
                          &tmp_name, length+1,
                          NullS))) 
    {
      pthread_mutex_unlock(&archive_mutex);
      return NULL;
    }

    share->use_count=0;
    share->table_name_length=length;
    share->table_name=tmp_name;
    fn_format(share->data_file_name,table_name,"",ARZ,MY_REPLACE_EXT|MY_UNPACK_FILENAME);
    strmov(share->table_name,table_name);
    /* 
      It is expensive to open and close the data files and since you can't have
      a gzip file that can be both read and written we keep a writer open
      that is shared amoung all open tables.
    */
    if ((share->archive_write= gzopen(share->data_file_name, "ab")) == NULL)
      goto error;
    if (my_hash_insert(&archive_open_tables, (byte*) share))
      goto error;
    thr_lock_init(&share->lock);
    if (pthread_mutex_init(&share->mutex,MY_MUTEX_INIT_FAST))
      goto error2;
  }
  share->use_count++;
  pthread_mutex_unlock(&archive_mutex);

  return share;

error2:
  thr_lock_delete(&share->lock);
  /* We close, but ignore errors since we already have errors */
  (void)gzclose(share->archive_write);
error:
  pthread_mutex_unlock(&archive_mutex);
  my_free((gptr) share, MYF(0));

  return NULL;
}


/* 
  Free lock controls.
  See ha_example.cc for a description.
*/
static int free_share(ARCHIVE_SHARE *share)
{
  int rc= 0;
  pthread_mutex_lock(&archive_mutex);
  if (!--share->use_count)
  {
    hash_delete(&archive_open_tables, (byte*) share);
    thr_lock_delete(&share->lock);
    pthread_mutex_destroy(&share->mutex);
    if (gzclose(share->archive_write) == Z_ERRNO)
      rc= -1;
    my_free((gptr) share, MYF(0));
  }
  pthread_mutex_unlock(&archive_mutex);

  return rc;
}


/* 
  We just implement one additional file extension.
*/
const char **ha_archive::bas_ext() const
{ static const char *ext[]= { ARZ, NullS }; return ext; }


/* 
  When opening a file we:
  Create/get our shared structure.
{'fraction_non_alphanumeric': 0.07296753806377478, 'fraction_numerical': 0.01235277219189888, 'mean_word_length': 3.2793484941610327, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3071343', 'n_tokens_mistral': 4266, 'n_tokens_neox': 4064, 'n_words': 1635}