ha_archive.cc 31.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* 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 */

unknown's avatar
unknown committed
17
#ifdef USE_PRAGMA_IMPLEMENTATION
18 19 20
#pragma implementation        // gcc: Class implementation
#endif

21
#include "mysql_priv.h"
22 23

#include "ha_archive.h"
24
#include <my_dir.h>
25 26 27 28 29 30 31

/*
  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
  A "meta" file is kept alongside the data file. This file serves two purpose.
  The first purpose is to track the number of rows in the table. The second 
  purpose is to determine if the table was closed properly or not. When the 
  meta file is first opened it is marked as dirty. It is opened when the table 
  itself is opened for writing. When the table is closed the new count for rows 
  is written to the meta file and the file is marked as clean. If the meta file 
  is opened and it is marked as dirty, it is assumed that a crash occured. At 
  this point an error occurs and the user is told to rebuild the file.
  A rebuild scans the rows and rewrites the meta file. If corruption is found
  in the data file then the meta file is not repaired.
55

56
  At some point a recovery method for such a drastic case needs to be divised.
57

58
  Locks are row level, and you will get a consistant read. 
59 60 61 62 63 64 65 66 67 68

  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.

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

  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


81 82 83 84 85 86 87 88
  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.
89
   Add optional feature so that rows can be flushed at interval (which will cause less
90 91 92 93 94
     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).
   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.
95 96 97

    -Brian
*/
98 99 100 101 102 103 104 105 106
/*
  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
unknown's avatar
unknown committed
107 108
  dirty - Status of the file, whether or not its values are the latest. This
          flag is what causes a repair to occur
109 110 111 112 113 114

  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.
unknown's avatar
unknown committed
115
*/
116

117
/* If the archive storage engine has been inited */
118
static bool archive_inited= FALSE;
119 120 121 122 123
/* Variables for archive share methods */
pthread_mutex_t archive_mutex;
static HASH archive_open_tables;

/* The file extension */
124 125 126 127 128 129 130 131 132 133 134 135
#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
136

137
/* Static declarations for handerton */
unknown's avatar
unknown committed
138
static handler *archive_create_handler(TABLE_SHARE *table);
139 140


unknown's avatar
unknown committed
141
/* dummy handlerton - only to have something to return from archive_db_init */
142
handlerton archive_hton = {
143
  "ARCHIVE",
144 145 146 147
  SHOW_OPTION_YES,
  "Archive storage engine", 
  DB_TYPE_ARCHIVE_DB,
  archive_db_init,
unknown's avatar
unknown committed
148 149
  0,       /* slot */
  0,       /* savepoint size. */
150 151 152 153 154 155 156 157 158 159 160 161 162
  NULL,    /* close_connection */
  NULL,    /* savepoint */
  NULL,    /* rollback to savepoint */
  NULL,    /* releas savepoint */
  NULL,    /* commit */
  NULL,    /* rollback */
  NULL,    /* prepare */
  NULL,    /* recover */
  NULL,    /* commit_by_xid */
  NULL,    /* rollback_by_xid */
  NULL,    /* create_cursor_read_view */
  NULL,    /* set_cursor_read_view */
  NULL,    /* close_cursor_read_view */
163 164 165 166 167 168 169 170 171
  archive_create_handler,    /* Create a new handler */
  NULL,    /* Drop a database */
  archive_db_end,    /* Panic call */
  NULL,    /* Release temporary latches */
  NULL,    /* Update Statistics */
  NULL,    /* Start Consistent Snapshot */
  NULL,    /* Flush logs */
  NULL,    /* Show status */
  NULL,    /* Replication Report Sent Binlog */
172
  HTON_NO_FLAGS
unknown's avatar
unknown committed
173 174
};

unknown's avatar
unknown committed
175
static handler *archive_create_handler(TABLE_SHARE *table)
176 177 178
{
  return new ha_archive(table);
}
unknown's avatar
unknown committed
179

180 181 182 183 184 185 186 187 188 189
/*
  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;
}

190 191 192 193 194 195 196 197 198

/*
  Initialize the archive handler.

  SYNOPSIS
    archive_db_init()
    void

  RETURN
199 200
    FALSE       OK
    TRUE        Error
201 202
*/

203
bool archive_db_init()
204
{
205 206 207
  DBUG_ENTER("archive_db_init");
  if (pthread_mutex_init(&archive_mutex, MY_MUTEX_INIT_FAST))
    goto error;
unknown's avatar
unknown committed
208 209
  if (hash_init(&archive_open_tables, system_charset_info, 32, 0, 0,
                (hash_get_key) archive_get_key, 0, 0))
210 211 212 213 214 215 216 217 218 219 220
  {
    VOID(pthread_mutex_destroy(&archive_mutex));
  }
  else
  {
    archive_inited= TRUE;
    DBUG_RETURN(FALSE);
  }
error:
  have_archive_db= SHOW_OPTION_DISABLED;	// If we couldn't use handler
  DBUG_RETURN(TRUE);
221 222 223 224 225 226 227 228 229 230 231 232 233
}

/*
  Release the archive handler.

  SYNOPSIS
    archive_db_end()
    void

  RETURN
    FALSE       OK
*/

234
int archive_db_end(ha_panic_function type)
235
{
236 237 238 239 240 241
  if (archive_inited)
  {
    hash_free(&archive_open_tables);
    VOID(pthread_mutex_destroy(&archive_mutex));
  }
  archive_inited= 0;
242
  return 0;
243 244
}

unknown's avatar
unknown committed
245
ha_archive::ha_archive(TABLE_SHARE *table_arg)
246 247 248 249 250 251
  :handler(&archive_hton, table_arg), delayed_insert(0), bulk_insert(0)
{
  /* Set our original buffer from pre-allocated memory */
  buffer.set((char *)byte_buffer, IO_SIZE, system_charset_info);

  /* The size of the offset value we will use for position() */
252 253
  ref_length = 2 << ((zlibCompileFlags() >> 6) & 3);
  DBUG_ASSERT(ref_length <= sizeof(z_off_t));
254
}
255

256 257 258 259 260
/*
  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)
{
261
  uchar data_buffer[DATA_BUFFER_SIZE];
262 263 264 265 266
  DBUG_ENTER("ha_archive::read_data_header");

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

267
  if (gzread(file_to_read, data_buffer, DATA_BUFFER_SIZE) != DATA_BUFFER_SIZE)
268
    DBUG_RETURN(errno ? errno : -1);
269 270 271 272 273 274
  
  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))
275 276 277 278
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

  DBUG_RETURN(0);
}
279 280

/*
281 282 283 284
  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)
{
285
  uchar data_buffer[DATA_BUFFER_SIZE];
286 287
  DBUG_ENTER("ha_archive::write_data_header");

288 289 290 291
  data_buffer[0]= (uchar)ARCHIVE_CHECK_HEADER;
  data_buffer[1]= (uchar)ARCHIVE_VERSION;

  if (gzwrite(file_to_write, &data_buffer, DATA_BUFFER_SIZE) != 
292
      DATA_BUFFER_SIZE)
293
    goto error;
294 295
  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]));
296 297 298 299 300 301 302 303 304 305

  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.
*/
306
int ha_archive::read_meta_file(File meta_file, ha_rows *rows)
307
{
308
  uchar meta_buffer[META_BUFFER_SIZE];
309 310 311 312 313
  ulonglong check_point;

  DBUG_ENTER("ha_archive::read_meta_file");

  VOID(my_seek(meta_file, 0, MY_SEEK_SET, MYF(0)));
314
  if (my_read(meta_file, (byte*)meta_buffer, META_BUFFER_SIZE, 0) != META_BUFFER_SIZE)
315 316 317 318 319
    DBUG_RETURN(-1);
  
  /*
    Parse out the meta data, we ignore version at the moment
  */
320
  *rows= (ha_rows)uint8korr(meta_buffer + 2);
321 322 323 324 325 326 327 328 329 330 331
  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);
332 333 334 335 336 337 338 339 340

  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.
341
  Upon ::open() we set to dirty, and upon ::close() we set to clean.
342
*/
343
int ha_archive::write_meta_file(File meta_file, ha_rows rows, bool dirty)
344
{
345 346 347
  uchar meta_buffer[META_BUFFER_SIZE];
  ulonglong check_point= 0; //Reserved for the future

348 349
  DBUG_ENTER("ha_archive::write_meta_file");

350 351
  meta_buffer[0]= (uchar)ARCHIVE_CHECK_HEADER;
  meta_buffer[1]= (uchar)ARCHIVE_VERSION;
352
  int8store(meta_buffer + 2, (ulonglong)rows); 
353 354 355 356
  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));
357
  DBUG_PRINT("ha_archive::write_meta_file", ("Rows %llu", (ulonglong)rows));
358 359
  DBUG_PRINT("ha_archive::write_meta_file", ("Checkpoint %llu", check_point));
  DBUG_PRINT("ha_archive::write_meta_file", ("Dirty %d", (uint)dirty));
360 361

  VOID(my_seek(meta_file, 0, MY_SEEK_SET, MYF(0)));
362
  if (my_write(meta_file, (byte *)meta_buffer, META_BUFFER_SIZE, 0) != META_BUFFER_SIZE)
363 364 365 366 367 368 369 370 371 372
    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. 
373 374 375
  No matter what we try to get or create a share. This is so that a repair
  table operation can occur. 

376
  See ha_example.cc for a longer description.
377
*/
378
ARCHIVE_SHARE *ha_archive::get_share(const char *table_name, TABLE *table)
379 380
{
  ARCHIVE_SHARE *share;
381
  char meta_file_name[FN_REFLEN];
382 383 384 385 386 387 388 389 390 391
  uint length;
  char *tmp_name;

  pthread_mutex_lock(&archive_mutex);
  length=(uint) strlen(table_name);

  if (!(share=(ARCHIVE_SHARE*) hash_search(&archive_open_tables,
                                           (byte*) table_name,
                                           length)))
  {
392
    if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
393 394
                          &share, sizeof(*share),
                          &tmp_name, length+1,
395
                          NullS)) 
396 397 398 399 400
    {
      pthread_mutex_unlock(&archive_mutex);
      return NULL;
    }

401 402 403
    share->use_count= 0;
    share->table_name_length= length;
    share->table_name= tmp_name;
404
    share->crashed= FALSE;
405
    fn_format(share->data_file_name,table_name,"",ARZ,MY_REPLACE_EXT|MY_UNPACK_FILENAME);
406
    fn_format(meta_file_name,table_name,"",ARM,MY_REPLACE_EXT|MY_UNPACK_FILENAME);
407
    strmov(share->table_name,table_name);
408 409 410 411 412
    /*
      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)
413
      share->crashed= TRUE;
414 415 416
    
    /*
      After we read, we set the file to dirty. When we close, we will do the 
417 418
      opposite. If the meta file will not open we assume it is crashed and
      leave it up to the user to fix.
419
    */
420 421 422 423
    if (read_meta_file(share->meta_file, &share->rows_recorded))
      share->crashed= TRUE;
    else
      (void)write_meta_file(share->meta_file, share->rows_recorded, TRUE);
424

425
    /* 
426 427 428
      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.
429
    */
430
    if ((share->archive_write= gzopen(share->data_file_name, "ab")) == NULL)
431 432
      share->crashed= TRUE;
    VOID(my_hash_insert(&archive_open_tables, (byte*) share));
433
    thr_lock_init(&share->lock);
434 435 436 437 438 439 440 441 442
  }
  share->use_count++;
  pthread_mutex_unlock(&archive_mutex);

  return share;
}


/* 
443
  Free the share.
444 445
  See ha_example.cc for a description.
*/
446
int ha_archive::free_share(ARCHIVE_SHARE *share)
447 448 449 450 451 452 453
{
  int rc= 0;
  pthread_mutex_lock(&archive_mutex);
  if (!--share->use_count)
  {
    hash_delete(&archive_open_tables, (byte*) share);
    thr_lock_delete(&share->lock);
454 455
    VOID(pthread_mutex_destroy(&share->mutex));
    (void)write_meta_file(share->meta_file, share->rows_recorded, FALSE);
456
    if (gzclose(share->archive_write) == Z_ERRNO)
457
      rc= 1;
458 459
    if (my_close(share->meta_file, MYF(0)))
      rc= 1;
unknown's avatar
unknown committed
460
    my_free((gptr) share, MYF(0));
461 462 463 464 465 466 467
  }
  pthread_mutex_unlock(&archive_mutex);

  return rc;
}


unknown's avatar
unknown committed
468
/*
469 470
  We just implement one additional file extension.
*/
unknown's avatar
unknown committed
471 472 473 474 475 476
static const char *ha_archive_exts[] = {
  ARZ,
  ARM,
  NullS
};

477
const char **ha_archive::bas_ext() const
unknown's avatar
unknown committed
478 479 480
{
  return ha_archive_exts;
}
481 482 483 484 485 486 487 488 489 490 491 492


/* 
  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");

493
  if (!(share= get_share(name, table)))
494
    DBUG_RETURN(HA_ERR_OUT_OF_MEM); // Not handled well by calling code!
495 496
  thr_lock_data_init(&share->lock,&lock,NULL);

497 498
  if ((archive= gzopen(share->data_file_name, "rb")) == NULL)
  {
499 500 501
    if (errno == EROFS || errno == EACCES)
      DBUG_RETURN(my_errno= errno);
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
502
  }
503 504 505 506 507 508

  DBUG_RETURN(0);
}


/*
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
  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
*/

525 526
int ha_archive::close(void)
{
527
  int rc= 0;
528
  DBUG_ENTER("ha_archive::close");
529 530 531 532 533 534 535 536

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

  DBUG_RETURN(rc);
537 538 539 540
}


/*
541 542 543 544 545 546
  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.
547 548 549 550
*/

int ha_archive::create(const char *name, TABLE *table_arg,
                       HA_CREATE_INFO *create_info)
551
{
552
  File create_file;  // We use to create the datafile and the metafile
553
  char name_buff[FN_REFLEN];
554
  int error;
555 556
  DBUG_ENTER("ha_archive::create");

557 558 559 560 561 562 563 564 565 566 567 568 569
  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.
  */
570 571 572 573 574
  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;
575
    goto error;
576
  }
577
  if ((archive= gzdopen(create_file, "wb")) == NULL)
578
  {
579
    error= errno;
580
    goto error2;
581
  }
582
  if (write_data_header(archive))
583
  {
584 585
    error= errno;
    goto error3;
586
  }
587 588

  if (gzclose(archive))
unknown's avatar
unknown committed
589
  {
590
    error= errno;
591
    goto error2;
592 593 594
  }

  my_close(create_file, MYF(0));
595

596
  DBUG_RETURN(0);
597

598 599 600
error3:
  /* We already have an error, so ignore results of gzclose. */
  (void)gzclose(archive);
601
error2:
602 603
  my_close(create_file, MYF(0));
  delete_table(name);
604
error:
605 606
  /* Return error number, if we got one */
  DBUG_RETURN(error ? error : -1);
607 608
}

609 610
/*
  This is where the actual row is written out.
611
*/
612
int ha_archive::real_write_row(byte *buf, gzFile writer)
613 614
{
  z_off_t written;
615
  uint *ptr, *end;
616
  DBUG_ENTER("ha_archive::real_write_row");
617

618 619
  written= gzwrite(writer, buf, table->s->reclength);
  DBUG_PRINT("ha_archive::real_write_row", ("Wrote %d bytes expected %d", written, table->s->reclength));
620
  if (!delayed_insert || !bulk_insert)
621 622
    share->dirty= TRUE;

623
  if (written != (z_off_t)table->s->reclength)
624
    DBUG_RETURN(errno ? errno : -1);
625 626 627 628
  /*
    We should probably mark the table as damagaged if the record is written
    but the blob fails.
  */
unknown's avatar
unknown committed
629
  for (ptr= table->s->blob_field, end= ptr + table->s->blob_fields ;
630 631
       ptr != end ;
       ptr++)
632
  {
633
    char *data_ptr;
634
    uint32 size= ((Field_blob*) table->field[*ptr])->get_length();
635

636 637
    if (size)
    {
638
      ((Field_blob*) table->field[*ptr])->get_ptr(&data_ptr);
639
      written= gzwrite(writer, data_ptr, (unsigned)size);
640
      if (written != (z_off_t)size)
641
        DBUG_RETURN(errno ? errno : -1);
642
    }
643
  }
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
  DBUG_RETURN(0);
}


/* 
  Look at ha_archive::open() for an explanation of the row format.
  Here we just write out the row.

  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.
*/
int ha_archive::write_row(byte *buf)
{
  int rc;
  DBUG_ENTER("ha_archive::write_row");

  if (share->crashed)
      DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

  statistic_increment(table->in_use->status_var.ha_write_count, &LOCK_status);
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT)
    table->timestamp_field->set_time();
  pthread_mutex_lock(&share->mutex);
669
  share->rows_recorded++;
670
  rc= real_write_row(buf, share->archive_write);
671
  pthread_mutex_unlock(&share->mutex);
672

673
  DBUG_RETURN(rc);
674 675 676 677 678 679 680
}

/*
  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.
*/
681

682 683 684
int ha_archive::rnd_init(bool scan)
{
  DBUG_ENTER("ha_archive::rnd_init");
685 686 687
  
  if (share->crashed)
      DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
688

689
  /* We rewind the file so that we can read from the beginning if scan */
690
  if (scan)
691
  {
692
    scan_rows= share->rows_recorded;
693 694
    records= 0;

695 696 697 698
    /* 
      If dirty, we lock, and then reset/flush the data.
      I found that just calling gzflush() doesn't always work.
    */
699
    if (share->dirty == TRUE)
700
    {
701 702 703 704 705 706 707
      pthread_mutex_lock(&share->mutex);
      if (share->dirty == TRUE)
      {
        gzflush(share->archive_write, Z_SYNC_FLUSH);
        share->dirty= FALSE;
      }
      pthread_mutex_unlock(&share->mutex);
708
    }
709 710 711

    if (read_data_header(archive))
      DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
712 713
  }

714 715 716 717 718 719 720 721
  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.
*/
722
int ha_archive::get_row(gzFile file_to_read, byte *buf)
723 724
{
  int read; // Bytes read, gzread() returns int
725
  uint *ptr, *end;
726 727
  char *last;
  size_t total_blob_length= 0;
728
  DBUG_ENTER("ha_archive::get_row");
729

730 731
  read= gzread(file_to_read, buf, table->s->reclength);
  DBUG_PRINT("ha_archive::get_row", ("Read %d bytes expected %d", read, table->s->reclength));
732 733 734

  if (read == Z_STREAM_ERROR)
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
735 736 737 738 739

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

740 741 742
  /* 
    If the record is the wrong size, the file is probably damaged, unless 
    we are dealing with a delayed insert or a bulk insert.
743
  */
744
  if ((ulong) read != table->s->reclength)
745
    DBUG_RETURN(HA_ERR_END_OF_FILE);
746 747

  /* Calculate blob length, we use this for our buffer */
748 749 750 751
  for (ptr= table->s->blob_field, end=ptr + table->s->blob_fields ;
       ptr != end ;
       ptr++)
    total_blob_length += ((Field_blob*) table->field[*ptr])->get_length();
752 753 754

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

757
  /* Loop through our blobs and read them */
758 759 760
  for (ptr= table->s->blob_field, end=ptr + table->s->blob_fields ;
       ptr != end ;
       ptr++)
761
  {
762
    size_t size= ((Field_blob*) table->field[*ptr])->get_length();
763 764 765 766
    if (size)
    {
      read= gzread(file_to_read, last, size);
      if ((size_t) read != size)
767
        DBUG_RETURN(HA_ERR_END_OF_FILE);
768
      ((Field_blob*) table->field[*ptr])->set_ptr(size, last);
769 770
      last += size;
    }
771 772 773 774
  }
  DBUG_RETURN(0);
}

775

776 777 778 779
/* 
  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.
*/
780

781 782 783
int ha_archive::rnd_next(byte *buf)
{
  int rc;
784
  DBUG_ENTER("ha_archive::rnd_next");
785

786 787 788
  if (share->crashed)
      DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

789 790 791 792
  if (!scan_rows)
    DBUG_RETURN(HA_ERR_END_OF_FILE);
  scan_rows--;

793 794
  statistic_increment(table->in_use->status_var.ha_read_rnd_next_count,
		      &LOCK_status);
795
  current_position= gztell(archive);
796 797 798
  rc= get_row(archive, buf);


799
  if (rc != HA_ERR_END_OF_FILE)
800 801 802 803 804 805
    records++;

  DBUG_RETURN(rc);
}


806
/*
807 808 809 810
  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.
*/
811

812 813 814
void ha_archive::position(const byte *record)
{
  DBUG_ENTER("ha_archive::position");
815
  my_store_ptr(ref, ref_length, current_position);
816 817 818 819 820
  DBUG_VOID_RETURN;
}


/*
821 822 823 824
  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.
825
*/
826

827 828 829
int ha_archive::rnd_pos(byte * buf, byte *pos)
{
  DBUG_ENTER("ha_archive::rnd_pos");
830 831
  statistic_increment(table->in_use->status_var.ha_read_rnd_next_count,
		      &LOCK_status);
832
  current_position= (z_off_t)my_get_ptr(pos, ref_length);
833
  (void)gzseek(archive, current_position, SEEK_SET);
834

835 836 837 838
  DBUG_RETURN(get_row(archive, buf));
}

/*
839
  This method repairs the meta file. It does this by walking the datafile and 
840 841
  rewriting the meta file. Currently it does this by calling optimize with
  the extended flag.
842
*/
843
int ha_archive::repair(THD* thd, HA_CHECK_OPT* check_opt)
844
{
845
  DBUG_ENTER("ha_archive::repair");
846 847
  check_opt->flags= T_EXTEND;
  int rc= optimize(thd, check_opt);
848

849 850
  if (rc)
    DBUG_RETURN(HA_ERR_CRASHED_ON_REPAIR);
851

852
  share->crashed= FALSE;
853
  DBUG_RETURN(0);
854 855
}

856 857 858
/*
  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. 
859
*/
860 861 862
int ha_archive::optimize(THD* thd, HA_CHECK_OPT* check_opt)
{
  DBUG_ENTER("ha_archive::optimize");
863 864
  int rc;
  gzFile writer;
865 866
  char writer_filename[FN_REFLEN];

867 868
  /* Flush any waiting data */
  gzflush(share->archive_write, Z_SYNC_FLUSH);
869

870
  /* Lets create a file to contain the new data */
871 872
  fn_format(writer_filename, share->table_name, "", ARN, 
            MY_REPLACE_EXT|MY_UNPACK_FILENAME);
873 874

  if ((writer= gzopen(writer_filename, "wb")) == NULL)
875 876 877 878 879 880 881 882
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE); 

  /* 
    An extended rebuild is a lot more effort. We open up each row and re-record it. 
    Any dead rows are removed (aka rows that may have been partially recorded). 
  */

  if (check_opt->flags == T_EXTEND)
883
  {
884
    byte *buf; 
885

886 887 888 889 890 891 892 893 894
    /* 
      First we create a buffer that we can use for reading rows, and can pass
      to get_row().
    */
    if (!(buf= (byte*) my_malloc(table->s->reclength, MYF(MY_WME))))
    {
      rc= HA_ERR_OUT_OF_MEM;
      goto error;
    }
895

896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
    /*
      Now we will rewind the archive file so that we are positioned at the 
      start of the file.
    */
    rc= read_data_header(archive);
    
    /*
      Assuming now error from rewinding the archive file, we now write out the 
      new header for out data file.
    */
    if (!rc)
      rc= write_data_header(writer);

    /* 
      On success of writing out the new header, we now fetch each row and
      insert it into the new archive file. 
    */
    if (!rc)
914 915
    {
      share->rows_recorded= 0;
916
      while (!(rc= get_row(archive, buf)))
917
      {
918
        real_write_row(buf, writer);
919 920 921
        share->rows_recorded++;
      }
    }
922

unknown's avatar
unknown committed
923
    my_free((char*)buf, MYF(0));
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
    if (rc && rc != HA_ERR_END_OF_FILE)
      goto error;
  } 
  else
  {
    /* 
      The quick method is to just read the data raw, and then compress it directly.
    */
    int read; // Bytes read, gzread() returns int
    char block[IO_SIZE];
    if (gzrewind(archive) == -1)
    {
      rc= HA_ERR_CRASHED_ON_USAGE;
      goto error;
    }

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

  gzflush(writer, Z_SYNC_FLUSH);
  gzclose(share->archive_write);
  share->archive_write= writer; 
947 948 949 950 951

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

  DBUG_RETURN(0); 

952 953 954 955 956
error:
  gzclose(writer);

  DBUG_RETURN(rc); 
}
957 958 959 960 961 962 963 964

/* 
  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)
{
965 966 967 968 969
  if (lock_type == TL_WRITE_DELAYED)
    delayed_insert= TRUE;
  else
    delayed_insert= FALSE;

970 971
  if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK) 
  {
972 973 974 975 976 977 978 979 980
    /* 
      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
981
        && !thd->tablespace_op)
982 983 984 985 986 987 988 989 990 991
      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. 
    */

992
    if (lock_type == TL_READ_NO_INSERT && !thd->in_lock_tables) 
993 994 995 996 997 998 999 1000 1001 1002
      lock_type = TL_READ;

    lock.type=lock_type;
  }

  *to++= &lock;

  return to;
}

1003 1004 1005 1006

/*
  Hints for optimizer, see ha_tina for more information
*/
1007 1008 1009
void ha_archive::info(uint flag)
{
  DBUG_ENTER("ha_archive::info");
1010 1011 1012 1013
  /* 
    This should be an accurate number now, though bulk and delayed inserts can
    cause the number to be inaccurate.
  */
1014 1015
  records= share->rows_recorded;
  deleted= 0;
1016 1017 1018 1019 1020 1021 1022
  /* Costs quite a bit more to get all information */
  if (flag & HA_STATUS_TIME)
  {
    MY_STAT file_stat;  // Stat information for the data file

    VOID(my_stat(share->data_file_name, &file_stat, MYF(MY_WME)));

1023
    mean_rec_length= table->s->reclength + buffer.alloced_length();
unknown's avatar
unknown committed
1024
    data_file_length= file_stat.st_size;
1025 1026
    create_time= file_stat.st_ctime;
    update_time= file_stat.st_mtime;
unknown's avatar
unknown committed
1027
    max_data_file_length= share->rows_recorded * mean_rec_length;
1028 1029 1030
  }
  delete_length= 0;
  index_file_length=0;
1031

1032 1033
  DBUG_VOID_RETURN;
}
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043


/*
  This method tells us that a bulk insert operation is about to occur. We set
  a flag which will keep write_row from saying that its data is dirty. This in
  turn will keep selects from causing a sync to occur.
  Basically, yet another optimizations to keep compression working well.
*/
void ha_archive::start_bulk_insert(ha_rows rows)
{
1044
  DBUG_ENTER("ha_archive::start_bulk_insert");
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
  bulk_insert= TRUE;
  DBUG_VOID_RETURN;
}


/* 
  Other side of start_bulk_insert, is end_bulk_insert. Here we turn off the bulk insert
  flag, and set the share dirty so that the next select will call sync for us.
*/
int ha_archive::end_bulk_insert()
{
1056
  DBUG_ENTER("ha_archive::end_bulk_insert");
1057 1058 1059 1060
  bulk_insert= FALSE;
  share->dirty= TRUE;
  DBUG_RETURN(0);
}
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

/*
  We cancel a truncate command. The only way to delete an archive table is to drop it.
  This is done for security reasons. In a later version we will enable this by 
  allowing the user to select a different row format.
*/
int ha_archive::delete_all_rows()
{
  DBUG_ENTER("ha_archive::delete_all_rows");
  DBUG_RETURN(0);
}
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148

/*
  We just return state if asked.
*/
bool ha_archive::is_crashed() const 
{
  return share->crashed; 
}

/*
  Simple scan of the tables to make sure everything is ok.
*/

int ha_archive::check(THD* thd, HA_CHECK_OPT* check_opt)
{
  int rc= 0;
  byte *buf; 
  const char *old_proc_info=thd->proc_info;
  ha_rows count= share->rows_recorded;
  DBUG_ENTER("ha_archive::check");

  thd->proc_info= "Checking table";
  /* Flush any waiting data */
  gzflush(share->archive_write, Z_SYNC_FLUSH);

  /* 
    First we create a buffer that we can use for reading rows, and can pass
    to get_row().
  */
  if (!(buf= (byte*) my_malloc(table->s->reclength, MYF(MY_WME))))
    rc= HA_ERR_OUT_OF_MEM;

  /*
    Now we will rewind the archive file so that we are positioned at the 
    start of the file.
  */
  if (!rc)
    read_data_header(archive);

  if (!rc)
    while (!(rc= get_row(archive, buf)))
      count--;

  my_free((char*)buf, MYF(0));

  thd->proc_info= old_proc_info;

  if ((rc && rc != HA_ERR_END_OF_FILE) || count)  
  {
    share->crashed= FALSE;
    DBUG_RETURN(HA_ADMIN_CORRUPT);
  }
  else
  {
    DBUG_RETURN(HA_ADMIN_OK);
  }
}

/*
  Check and repair the table if needed.
*/
bool ha_archive::check_and_repair(THD *thd) 
{
  HA_CHECK_OPT check_opt;
  DBUG_ENTER("ha_archive::check_and_repair");

  check_opt.init();

  if (check(thd, &check_opt) == HA_ADMIN_CORRUPT)
  {
    DBUG_RETURN(repair(thd, &check_opt));
  }
  else
  {
    DBUG_RETURN(HA_ADMIN_OK);
  }
}