ha_archive.cc 28 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/* 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
32
  engine only does inserts. No replace, deletes, or updates. All reads are 
33 34 35 36 37 38 39 40 41 42 43 44
  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).

45 46 47 48 49 50 51 52 53 54 55 56
  A "meta" file is kept. All this file does is contain information on
  the number of rows. 

  No attempts at durability are made. You can corrupt your data. A repair
  method was added to repair the meta file that stores row information,
  but if your data file gets corrupted I haven't solved that. I could
  create a repair that would solve this, but do you want to take a 
  chance of loosing your data?

  Locks are row level, and you will get a consistant read. Transactions
  will be added later (they are not that hard to add at this
  stage). 
57 58 59 60 61 62 63 64 65 66

  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.

67
  Examples between MyISAM (packed) and Archive.
68 69 70 71 72 73 74 75 76 77 78

  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


79 80 81 82 83 84 85 86
  TODO:
   Add bzip optional support.
   Allow users to set compression level.
   Add truncate table command.
   Implement versioning, should be easy.
   Allow for errors, find a way to mark bad rows.
   Talk to the gzip guys, come up with a writable format so that updates are doable
     without switching to a block method.
87
   Add optional feature so that rows can be flushed at interval (which will cause less
88 89 90 91 92 93
     compression but may speed up ordered searches).
   Checkpoint the meta file to allow for faster rebuilds.
   Dirty open (right now the meta file is repaired if a crash occured).
   Transactions.
   Option to allow for dirty reads, this would lower the sync calls, which would make
     inserts a lot faster, but would mean highly arbitrary reads.
94 95 96

    -Brian
*/
97 98 99 100 101 102 103 104 105
/*
  Notes on file formats.
  The Meta file is layed out as:
  check - Just an int of 254 to make sure that the the file we are opening was
          never corrupted.
  version - The current version of the file format.
  rows - This is an unsigned long long which is the number of rows in the data
         file.
  check point - Reserved for future use
106 107
  dirty - Status of the file, whether or not its values are the latest. This
          flag is what causes a repair to occur
108 109 110 111 112 113

  The data file:
  check - Just an int of 254 to make sure that the the file we are opening was
          never corrupted.
  version - The current version of the file format.
  data - The data is stored in a "row +blobs" format.
114
*/
115 116 117 118 119 120 121

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

/* The file extension */
122 123 124 125 126 127 128 129 130 131 132 133
#define ARZ ".ARZ"               // The data file
#define ARN ".ARN"               // Files used during an optimize call
#define ARM ".ARM"               // Meta file
/*
  uchar + uchar + ulonglong + ulonglong + uchar
*/
#define META_BUFFER_SIZE 19      // Size of the data used in the meta file
/*
  uchar + uchar
*/
#define DATA_BUFFER_SIZE 2       // Size of the data used in the data file
#define ARCHIVE_CHECK_HEADER 254 // The number we use to determine corruption
134 135 136 137 138 139 140 141 142 143 144

/*
  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;
}

145 146 147 148 149
/*
  This method reads the header of a datafile and returns whether or not it was successful.
*/
int ha_archive::read_data_header(gzFile file_to_read)
{
150
  uchar data_buffer[DATA_BUFFER_SIZE];
151 152 153 154 155
  DBUG_ENTER("ha_archive::read_data_header");

  if (gzrewind(file_to_read) == -1)
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

156
  if (gzread(file_to_read, data_buffer, DATA_BUFFER_SIZE) != DATA_BUFFER_SIZE)
157
    DBUG_RETURN(errno ? errno : -1);
158 159 160 161 162 163
  
  DBUG_PRINT("ha_archive::read_data_header", ("Check %u", data_buffer[0]));
  DBUG_PRINT("ha_archive::read_data_header", ("Version %u", data_buffer[1]));
  
  if ((data_buffer[0] != (uchar)ARCHIVE_CHECK_HEADER) &&  
      (data_buffer[1] != (uchar)ARCHIVE_VERSION))
164 165 166 167
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

  DBUG_RETURN(0);
}
168 169

/*
170 171 172 173
  This method writes out the header of a datafile and returns whether or not it was successful.
*/
int ha_archive::write_data_header(gzFile file_to_write)
{
174
  uchar data_buffer[DATA_BUFFER_SIZE];
175 176
  DBUG_ENTER("ha_archive::write_data_header");

177 178 179 180 181
  data_buffer[0]= (uchar)ARCHIVE_CHECK_HEADER;
  data_buffer[1]= (uchar)ARCHIVE_VERSION;

  if (gzwrite(file_to_write, &data_buffer, DATA_BUFFER_SIZE) != 
      sizeof(DATA_BUFFER_SIZE))
182
    goto error;
183 184
  DBUG_PRINT("ha_archive::write_data_header", ("Check %u", (uint)data_buffer[0]));
  DBUG_PRINT("ha_archive::write_data_header", ("Version %u", (uint)data_buffer[1]));
185 186 187 188 189 190 191 192 193 194 195 196

  DBUG_RETURN(0);
error:
  DBUG_RETURN(errno);
}

/*
  This method reads the header of a meta file and returns whether or not it was successful.
  *rows will contain the current number of rows in the data file upon success.
*/
int ha_archive::read_meta_file(File meta_file, ulonglong *rows)
{
197
  uchar meta_buffer[META_BUFFER_SIZE];
198 199 200 201 202
  ulonglong check_point;

  DBUG_ENTER("ha_archive::read_meta_file");

  VOID(my_seek(meta_file, 0, MY_SEEK_SET, MYF(0)));
203
  if (my_read(meta_file, (byte*)meta_buffer, META_BUFFER_SIZE, 0) != META_BUFFER_SIZE)
204 205 206 207 208
    DBUG_RETURN(-1);
  
  /*
    Parse out the meta data, we ignore version at the moment
  */
209 210 211 212 213 214 215 216 217 218 219 220
  *rows= uint8korr(meta_buffer + 2);
  check_point= uint8korr(meta_buffer + 10);

  DBUG_PRINT("ha_archive::read_meta_file", ("Check %d", (uint)meta_buffer[0]));
  DBUG_PRINT("ha_archive::read_meta_file", ("Version %d", (uint)meta_buffer[1]));
  DBUG_PRINT("ha_archive::read_meta_file", ("Rows %lld", *rows));
  DBUG_PRINT("ha_archive::read_meta_file", ("Checkpoint %lld", check_point));
  DBUG_PRINT("ha_archive::read_meta_file", ("Dirty %d", (int)meta_buffer[18]));

  if ((meta_buffer[0] != (uchar)ARCHIVE_CHECK_HEADER) || 
      ((bool)meta_buffer[18] == TRUE))
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
221 222 223 224 225 226 227 228 229 230 231 232 233 234

  my_sync(meta_file, MYF(MY_WME));

  DBUG_RETURN(0);
}

/*
  This method writes out the header of a meta file and returns whether or not it was successful.
  By setting dirty you say whether or not the file represents the actual state of the data file.
  Upon ::open() we set to dirty, and upon ::close() we set to clean. If we determine during
  a read that the file was dirty we will force a rebuild of this file.
*/
int ha_archive::write_meta_file(File meta_file, ulonglong rows, bool dirty)
{
235 236 237
  uchar meta_buffer[META_BUFFER_SIZE];
  ulonglong check_point= 0; //Reserved for the future

238 239
  DBUG_ENTER("ha_archive::write_meta_file");

240 241 242 243 244 245 246 247 248 249
  meta_buffer[0]= (uchar)ARCHIVE_CHECK_HEADER;
  meta_buffer[1]= (uchar)ARCHIVE_VERSION;
  int8store(meta_buffer + 2, rows); 
  int8store(meta_buffer + 10, check_point); 
  *(meta_buffer + 18)= (uchar)dirty;
  DBUG_PRINT("ha_archive::write_meta_file", ("Check %d", (uint)ARCHIVE_CHECK_HEADER));
  DBUG_PRINT("ha_archive::write_meta_file", ("Version %d", (uint)ARCHIVE_VERSION));
  DBUG_PRINT("ha_archive::write_meta_file", ("Rows %llu", rows));
  DBUG_PRINT("ha_archive::write_meta_file", ("Checkpoint %llu", check_point));
  DBUG_PRINT("ha_archive::write_meta_file", ("Dirty %d", (uint)dirty));
250 251

  VOID(my_seek(meta_file, 0, MY_SEEK_SET, MYF(0)));
252
  if (my_write(meta_file, (byte *)meta_buffer, META_BUFFER_SIZE, 0) != META_BUFFER_SIZE)
253 254 255 256 257 258 259 260 261 262 263
    DBUG_RETURN(-1);
  
  my_sync(meta_file, MYF(MY_WME));

  DBUG_RETURN(0);
}


/*
  We create the shared memory space that we will use for the open table. 
  See ha_example.cc for a longer description.
264
*/
265
ARCHIVE_SHARE *ha_archive::get_share(const char *table_name, TABLE *table)
266 267
{
  ARCHIVE_SHARE *share;
268
  char meta_file_name[FN_REFLEN];
269 270 271 272 273 274 275 276 277 278
  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)
    {
      VOID(pthread_mutex_init(&archive_mutex,MY_MUTEX_INIT_FAST));
279
      if (hash_init(&archive_open_tables,system_charset_info,32,0,0,
280 281 282 283 284 285
                       (hash_get_key) archive_get_key,0,0))
      {
        pthread_mutex_unlock(&LOCK_mysql_create_db);
        return NULL;
      }
      archive_init++;
286 287 288 289 290 291 292 293 294 295
    }
    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)))
  {
296
    if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
297 298
                          &share, sizeof(*share),
                          &tmp_name, length+1,
299
                          NullS)) 
300 301 302 303 304
    {
      pthread_mutex_unlock(&archive_mutex);
      return NULL;
    }

305 306 307
    share->use_count= 0;
    share->table_name_length= length;
    share->table_name= tmp_name;
308
    fn_format(share->data_file_name,table_name,"",ARZ,MY_REPLACE_EXT|MY_UNPACK_FILENAME);
309
    fn_format(meta_file_name,table_name,"",ARM,MY_REPLACE_EXT|MY_UNPACK_FILENAME);
310
    strmov(share->table_name,table_name);
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
    /*
      We will use this lock for rows.
    */
    VOID(pthread_mutex_init(&share->mutex,MY_MUTEX_INIT_FAST));
    if ((share->meta_file= my_open(meta_file_name, O_RDWR, MYF(0))) == -1)
      goto error;
    
    if (read_meta_file(share->meta_file, &share->rows_recorded))
    {
      /*
        The problem here is that for some reason, probably a crash, the meta
        file has been corrupted. So what do we do? Well we try to rebuild it
        ourself. Once that happens, we reread it, but if that fails we just
        call it quits and return an error.
      */
      if (rebuild_meta_file(share->table_name, share->meta_file))
        goto error;
      if (read_meta_file(share->meta_file, &share->rows_recorded))
        goto error;
    }
    /*
      After we read, we set the file to dirty. When we close, we will do the 
      opposite.
    */
    (void)write_meta_file(share->meta_file, share->rows_recorded, TRUE);
336
    /* 
337 338 339
      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.
340
    */
341
    if ((share->archive_write= gzopen(share->data_file_name, "ab")) == NULL)
342
      goto error2;
343
    if (my_hash_insert(&archive_open_tables, (byte*) share))
344
      goto error2;
345 346
    thr_lock_init(&share->lock);
    if (pthread_mutex_init(&share->mutex,MY_MUTEX_INIT_FAST))
347
      goto error3;
348 349 350 351 352 353
  }
  share->use_count++;
  pthread_mutex_unlock(&archive_mutex);

  return share;

354 355
error3:
  VOID(pthread_mutex_destroy(&share->mutex));
356 357 358
  thr_lock_delete(&share->lock);
  /* We close, but ignore errors since we already have errors */
  (void)gzclose(share->archive_write);
359 360
error2:
  my_close(share->meta_file,MYF(0));
361 362 363 364 365 366 367 368 369
error:
  pthread_mutex_unlock(&archive_mutex);
  my_free((gptr) share, MYF(0));

  return NULL;
}


/* 
370
  Free the share.
371 372
  See ha_example.cc for a description.
*/
373
int ha_archive::free_share(ARCHIVE_SHARE *share)
374 375 376 377 378 379 380
{
  int rc= 0;
  pthread_mutex_lock(&archive_mutex);
  if (!--share->use_count)
  {
    hash_delete(&archive_open_tables, (byte*) share);
    thr_lock_delete(&share->lock);
381 382
    VOID(pthread_mutex_destroy(&share->mutex));
    (void)write_meta_file(share->meta_file, share->rows_recorded, FALSE);
383
    if (gzclose(share->archive_write) == Z_ERRNO)
384
      rc= 1;
bar@mysql.com's avatar
bar@mysql.com committed
385
    my_free((gptr) share, MYF(0));
386 387 388 389 390 391 392 393 394 395 396
  }
  pthread_mutex_unlock(&archive_mutex);

  return rc;
}


/* 
  We just implement one additional file extension.
*/
const char **ha_archive::bas_ext() const
397
{ static const char *ext[]= { ARZ, ARN, ARM, NullS }; return ext; }
398 399 400 401 402 403 404 405 406 407 408 409


/* 
  When opening a file we:
  Create/get our shared structure.
  Init out lock.
  We open the file we will read from.
*/
int ha_archive::open(const char *name, int mode, uint test_if_locked)
{
  DBUG_ENTER("ha_archive::open");

410
  if (!(share= get_share(name, table)))
411 412 413
    DBUG_RETURN(1);
  thr_lock_data_init(&share->lock,&lock,NULL);

414 415 416
  if ((archive= gzopen(share->data_file_name, "rb")) == NULL)
  {
    (void)free_share(share); //We void since we already have an error
417
    DBUG_RETURN(errno ? errno : -1);
418
  }
419 420 421 422 423 424

  DBUG_RETURN(0);
}


/*
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
  Closes the file.

  SYNOPSIS
    close();
  
  IMPLEMENTATION:

  We first close this storage engines file handle to the archive and
  then remove our reference count to the table (and possibly free it
  as well).

  RETURN
    0  ok
    1  Error
*/

441 442
int ha_archive::close(void)
{
443
  int rc= 0;
444
  DBUG_ENTER("ha_archive::close");
445 446 447 448 449 450 451 452

  /* First close stream */
  if (gzclose(archive) == Z_ERRNO)
    rc= 1;
  /* then also close share */
  rc|= free_share(share);

  DBUG_RETURN(rc);
453 454 455 456
}


/*
457 458 459 460 461 462
  We create our data file here. The format is pretty simple. 
  You can read about the format of the data file above.
  Unlike other storage engines we do not "pack" our data. Since we 
  are about to do a general compression, packing would just be a waste of 
  CPU time. If the table has blobs they are written after the row in the order 
  of creation.
463 464 465 466
*/

int ha_archive::create(const char *name, TABLE *table_arg,
                       HA_CREATE_INFO *create_info)
467
{
468
  File create_file;  // We use to create the datafile and the metafile
469
  char name_buff[FN_REFLEN];
470
  int error;
471 472
  DBUG_ENTER("ha_archive::create");

473 474 475 476 477 478 479 480 481 482 483 484 485
  if ((create_file= my_create(fn_format(name_buff,name,"",ARM,
                                        MY_REPLACE_EXT|MY_UNPACK_FILENAME),0,
                              O_RDWR | O_TRUNC,MYF(MY_WME))) < 0)
  {
    error= my_errno;
    goto error;
  }
  write_meta_file(create_file, 0, FALSE);
  my_close(create_file,MYF(0));

  /* 
    We reuse name_buff since it is available.
  */
486 487 488 489 490
  if ((create_file= my_create(fn_format(name_buff,name,"",ARZ,
                                        MY_REPLACE_EXT|MY_UNPACK_FILENAME),0,
                              O_RDWR | O_TRUNC,MYF(MY_WME))) < 0)
  {
    error= my_errno;
491
    goto error;
492
  }
493 494
  if ((archive= gzdopen(create_file, "ab")) == NULL)
  {
495
    error= errno;
496
    delete_table(name);
497
    goto error;
498
  }
499
  if (write_data_header(archive))
500
  {
501 502
    gzclose(archive);
    goto error2;
503
  }
504 505 506 507

  if (gzclose(archive))
    goto error2;

508
  DBUG_RETURN(0);
509

510 511 512 513
error2:
    error= errno;
    delete_table(name);
error:
514 515
  /* Return error number, if we got one */
  DBUG_RETURN(error ? error : -1);
516 517
}

518

519
/* 
520
  Look at ha_archive::open() for an explanation of the row format.
521
  Here we just write out the row.
522 523 524 525 526

  Wondering about start_bulk_insert()? We don't implement it for
  archive since it optimizes for lots of writes. The only save
  for implementing start_bulk_insert() is that we could skip 
  setting dirty to true each time.
527 528 529 530
*/
int ha_archive::write_row(byte * buf)
{
  z_off_t written;
531
  Field_blob **field;
532 533 534
  DBUG_ENTER("ha_archive::write_row");

  statistic_increment(ha_write_count,&LOCK_status);
535 536
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT)
    table->timestamp_field->set_time();
537
  pthread_mutex_lock(&share->mutex);
538
  written= gzwrite(share->archive_write, buf, table->reclength);
539
  DBUG_PRINT("ha_archive::get_row", ("Wrote %d bytes expected %d", written, table->reclength));
540
  share->dirty= TRUE;
541
  if (written != table->reclength)
542 543 544 545 546
    goto error;
  /*
    We should probably mark the table as damagaged if the record is written
    but the blob fails.
  */
547
  for (field= table->blob_field ; *field ; field++)
548 549 550 551
  {
    char *ptr;
    uint32 size= (*field)->get_length();

552 553 554 555 556 557 558
    if (size)
    {
      (*field)->get_ptr(&ptr);
      written= gzwrite(share->archive_write, ptr, (unsigned)size);
      if (written != size)
        goto error;
    }
559
  }
560 561
  share->rows_recorded++;
  pthread_mutex_unlock(&share->mutex);
562 563

  DBUG_RETURN(0);
564 565 566
error:
  pthread_mutex_unlock(&share->mutex);
  DBUG_RETURN(errno ? errno : -1);
567 568 569 570 571 572 573 574
}


/*
  All calls that need to scan the table start with this method. If we are told
  that it is a table scan we rewind the file to the beginning, otherwise
  we assume the position will be set.
*/
575

576 577 578 579
int ha_archive::rnd_init(bool scan)
{
  DBUG_ENTER("ha_archive::rnd_init");
  int read; // gzread() returns int, and we use this to check the header
580

581
  /* We rewind the file so that we can read from the beginning if scan */
582
  if (scan)
583
  {
584
    scan_rows= share->rows_recorded;
585 586
    records= 0;

587 588 589 590
    /* 
      If dirty, we lock, and then reset/flush the data.
      I found that just calling gzflush() doesn't always work.
    */
591
    if (share->dirty == TRUE)
592
    {
593 594 595 596 597 598 599
      pthread_mutex_lock(&share->mutex);
      if (share->dirty == TRUE)
      {
        gzflush(share->archive_write, Z_SYNC_FLUSH);
        share->dirty= FALSE;
      }
      pthread_mutex_unlock(&share->mutex);
600
    }
601 602 603

    if (read_data_header(archive))
      DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
604 605
  }

606 607 608 609 610 611 612 613
  DBUG_RETURN(0);
}


/*
  This is the method that is used to read a row. It assumes that the row is 
  positioned where you want it.
*/
614
int ha_archive::get_row(gzFile file_to_read, byte *buf)
615 616 617 618
{
  int read; // Bytes read, gzread() returns int
  char *last;
  size_t total_blob_length= 0;
619
  Field_blob **field;
620
  DBUG_ENTER("ha_archive::get_row");
621

622
  read= gzread(file_to_read, buf, table->reclength);
623
  DBUG_PRINT("ha_archive::get_row", ("Read %d bytes expected %d", read, table->reclength));
624 625 626

  if (read == Z_STREAM_ERROR)
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
627 628 629 630 631 632

  /* If we read nothing we are at the end of the file */
  if (read == 0)
    DBUG_RETURN(HA_ERR_END_OF_FILE);

  /* If the record is the wrong size, the file is probably damaged */
633
  if ((ulong) read != table->reclength)
634 635 636
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

  /* Calculate blob length, we use this for our buffer */
637
  for (field=table->blob_field; *field ; field++)
638 639 640 641
    total_blob_length += (*field)->get_length();

  /* Adjust our row buffer if we need be */
  buffer.alloc(total_blob_length);
642
  last= (char *)buffer.ptr();
643

644
  /* Loop through our blobs and read them */
645
  for (field=table->blob_field; *field ; field++)
646 647
  {
    size_t size= (*field)->get_length();
648 649 650 651 652 653 654 655
    if (size)
    {
      read= gzread(file_to_read, last, size);
      if ((size_t) read != size)
        DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
      (*field)->set_ptr(size, last);
      last += size;
    }
656 657 658 659
  }
  DBUG_RETURN(0);
}

660

661 662 663 664
/* 
  Called during ORDER BY. Its position is either from being called sequentially
  or by having had ha_archive::rnd_pos() called before it is called.
*/
665

666 667 668
int ha_archive::rnd_next(byte *buf)
{
  int rc;
669
  DBUG_ENTER("ha_archive::rnd_next");
670

671 672 673 674
  if (!scan_rows)
    DBUG_RETURN(HA_ERR_END_OF_FILE);
  scan_rows--;

675
  statistic_increment(ha_read_rnd_next_count,&LOCK_status);
676
  current_position= gztell(archive);
677 678 679
  rc= get_row(archive, buf);


680
  if (rc != HA_ERR_END_OF_FILE)
681 682 683 684 685 686 687 688 689 690 691
    records++;

  DBUG_RETURN(rc);
}


/* 
  Thanks to the table flag HA_REC_NOT_IN_SEQ this will be called after
  each call to ha_archive::rnd_next() if an ordering of the rows is
  needed.
*/
692

693 694 695 696 697 698 699 700 701
void ha_archive::position(const byte *record)
{
  DBUG_ENTER("ha_archive::position");
  ha_store_ptr(ref, ref_length, current_position);
  DBUG_VOID_RETURN;
}


/*
702 703 704 705
  This is called after a table scan for each row if the results of the
  scan need to be ordered. It will take *pos and use it to move the
  cursor in the file so that the next row that is called is the
  correctly ordered row.
706
*/
707

708 709 710 711
int ha_archive::rnd_pos(byte * buf, byte *pos)
{
  DBUG_ENTER("ha_archive::rnd_pos");
  statistic_increment(ha_read_rnd_count,&LOCK_status);
712
  current_position= ha_get_ptr(pos, ref_length);
713 714
  z_off_t seek= gzseek(archive, current_position, SEEK_SET);

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
  DBUG_RETURN(get_row(archive, buf));
}

/*
  This method rebuilds the meta file. It does this by walking the datafile and 
  rewriting the meta file.
*/
int ha_archive::rebuild_meta_file(char *table_name, File meta_file)
{
  int rc;
  byte *buf; 
  ulonglong rows_recorded= 0;
  gzFile rebuild_file;            /* Archive file we are working with */
  char data_file_name[FN_REFLEN];
  DBUG_ENTER("ha_archive::rebuild_meta_file");

  /*
    Open up the meta file to recreate it.
  */
  fn_format(data_file_name, table_name, "", ARZ,
            MY_REPLACE_EXT|MY_UNPACK_FILENAME);
  if ((rebuild_file= gzopen(data_file_name, "rb")) == NULL)
    DBUG_RETURN(errno ? errno : -1);

  if (rc= read_data_header(rebuild_file))
    goto error;

  /*
    We malloc up the buffer we will use for counting the rows. 
    I know, this malloc'ing memory but this should be a very 
    rare event.
  */
  if (!(buf= (byte*) my_malloc(table->rec_buff_length > sizeof(ulonglong) +1 ? 
                               table->rec_buff_length : sizeof(ulonglong) +1 ,
                               MYF(MY_WME))))
  {
    rc= HA_ERR_CRASHED_ON_USAGE;
    goto error;
  }

  while (!(rc= get_row(rebuild_file, buf)))
    rows_recorded++;

  /* 
    Only if we reach the end of the file do we assume we can rewrite.
    At this point we reset rc to a non-message state.
  */
  if (rc == HA_ERR_END_OF_FILE)
  {
    (void)write_meta_file(meta_file, rows_recorded, FALSE);
    rc= 0;
  }

  my_free((gptr) buf, MYF(0));
error:
  gzclose(rebuild_file);

  DBUG_RETURN(rc);
773 774
}

775 776 777
/*
  The table can become fragmented if data was inserted, read, and then
  inserted again. What we do is open up the file and recompress it completely. 
778
*/
779 780 781 782 783 784 785 786 787
int ha_archive::optimize(THD* thd, HA_CHECK_OPT* check_opt)
{
  DBUG_ENTER("ha_archive::optimize");
  int read; // Bytes read, gzread() returns int
  gzFile reader, writer;
  char block[IO_SIZE];
  char writer_filename[FN_REFLEN];

  /* Lets create a file to contain the new data */
788 789
  fn_format(writer_filename, share->table_name, "", ARN, 
            MY_REPLACE_EXT|MY_UNPACK_FILENAME);
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823

  /* Closing will cause all data waiting to be flushed, to be flushed */
  gzclose(share->archive_write);

  if ((reader= gzopen(share->data_file_name, "rb")) == NULL)
    DBUG_RETURN(-1); 

  if ((writer= gzopen(writer_filename, "wb")) == NULL)
  {
    gzclose(reader);
    DBUG_RETURN(-1); 
  }

  while (read= gzread(reader, block, IO_SIZE))
    gzwrite(writer, block, read);

  gzclose(reader);
  gzclose(writer);

  my_rename(writer_filename,share->data_file_name,MYF(0));

  /* 
    We reopen the file in case some IO is waiting to go through.
    In theory the table is closed right after this operation,
    but it is possible for IO to still happen.
    I may be being a bit too paranoid right here.
  */
  if ((share->archive_write= gzopen(share->data_file_name, "ab")) == NULL)
    DBUG_RETURN(errno ? errno : -1);
  share->dirty= FALSE;

  DBUG_RETURN(0); 
}

824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840

/*
  No transactions yet, so this is pretty dull.
*/
int ha_archive::external_lock(THD *thd, int lock_type)
{
  DBUG_ENTER("ha_archive::external_lock");
  DBUG_RETURN(0);
}

/* 
  Below is an example of how to setup row level locking.
*/
THR_LOCK_DATA **ha_archive::store_lock(THD *thd,
                                       THR_LOCK_DATA **to,
                                       enum thr_lock_type lock_type)
{
841 842
  if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK) 
  {
843 844 845 846 847 848 849 850 851
    /* 
      Here is where we get into the guts of a row level lock.
      If TL_UNLOCK is set 
      If we are not doing a LOCK TABLE or DISCARD/IMPORT
      TABLESPACE, then allow multiple writers 
    */

    if ((lock_type >= TL_WRITE_CONCURRENT_INSERT &&
         lock_type <= TL_WRITE) && !thd->in_lock_tables
852
        && !thd->tablespace_op)
853 854 855 856 857 858 859 860 861 862
      lock_type = TL_WRITE_ALLOW_WRITE;

    /* 
      In queries of type INSERT INTO t1 SELECT ... FROM t2 ...
      MySQL would use the lock TL_READ_NO_INSERT on t2, and that
      would conflict with TL_WRITE_ALLOW_WRITE, blocking all inserts
      to t2. Convert the lock to a normal read lock to allow
      concurrent inserts to t2. 
    */

863
    if (lock_type == TL_READ_NO_INSERT && !thd->in_lock_tables) 
864 865 866 867 868 869 870 871 872 873 874
      lock_type = TL_READ;

    lock.type=lock_type;
  }

  *to++= &lock;

  return to;
}


875 876 877 878 879 880 881 882 883 884 885
/******************************************************************************

  Everything below here is default, please look at ha_example.cc for 
  descriptions.

 ******************************************************************************/

int ha_archive::update_row(const byte * old_data, byte * new_data)
{

  DBUG_ENTER("ha_archive::update_row");
886
  DBUG_RETURN(HA_ERR_WRONG_COMMAND);
887 888 889 890 891
}

int ha_archive::delete_row(const byte * buf)
{
  DBUG_ENTER("ha_archive::delete_row");
892
  DBUG_RETURN(HA_ERR_WRONG_COMMAND);
893 894 895 896 897 898 899 900
}

int ha_archive::index_read(byte * buf, const byte * key,
                           uint key_len __attribute__((unused)),
                           enum ha_rkey_function find_flag
                           __attribute__((unused)))
{
  DBUG_ENTER("ha_archive::index_read");
901
  DBUG_RETURN(HA_ERR_WRONG_COMMAND);
902 903 904 905 906 907 908 909
}

int ha_archive::index_read_idx(byte * buf, uint index, const byte * key,
                               uint key_len __attribute__((unused)),
                               enum ha_rkey_function find_flag
                               __attribute__((unused)))
{
  DBUG_ENTER("ha_archive::index_read_idx");
910
  DBUG_RETURN(HA_ERR_WRONG_COMMAND);
911 912 913 914 915 916
}


int ha_archive::index_next(byte * buf)
{
  DBUG_ENTER("ha_archive::index_next");
917
  DBUG_RETURN(HA_ERR_WRONG_COMMAND);
918 919 920 921 922
}

int ha_archive::index_prev(byte * buf)
{
  DBUG_ENTER("ha_archive::index_prev");
923
  DBUG_RETURN(HA_ERR_WRONG_COMMAND);
924 925 926 927 928
}

int ha_archive::index_first(byte * buf)
{
  DBUG_ENTER("ha_archive::index_first");
929
  DBUG_RETURN(HA_ERR_WRONG_COMMAND);
930 931 932 933 934
}

int ha_archive::index_last(byte * buf)
{
  DBUG_ENTER("ha_archive::index_last");
935
  DBUG_RETURN(HA_ERR_WRONG_COMMAND);
936 937 938 939 940 941
}


void ha_archive::info(uint flag)
{
  DBUG_ENTER("ha_archive::info");
942

943
  /* This is a lie, but you don't want the optimizer to see zero or 1 */
944 945
  records= share->rows_recorded;
  deleted= 0;
946

947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
  DBUG_VOID_RETURN;
}

int ha_archive::extra(enum ha_extra_function operation)
{
  DBUG_ENTER("ha_archive::extra");
  DBUG_RETURN(0);
}

int ha_archive::reset(void)
{
  DBUG_ENTER("ha_archive::reset");
  DBUG_RETURN(0);
}

962 963
ha_rows ha_archive::records_in_range(uint inx, key_range *min_key,
                                     key_range *max_key)
964 965
{
  DBUG_ENTER("ha_archive::records_in_range ");
966
  DBUG_RETURN(records); // HA_ERR_WRONG_COMMAND 
967 968
}
#endif /* HAVE_ARCHIVE_DB */