ha_archive.cc 43.9 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"
unknown's avatar
unknown committed
22
#include <myisam.h>
23 24

#include "ha_archive.h"
25
#include <my_dir.h>
26

unknown's avatar
unknown committed
27 28
#include <mysql/plugin.h>

29 30 31 32 33 34
/*
  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
35
  engine only does inserts. No replace, deletes, or updates. All reads are 
unknown's avatar
unknown committed
36
  complete table scans. Compression is done through azip (bzip compresses
37
  better, but only marginally, if someone asks I could add support for
unknown's avatar
unknown committed
38
  it too, but beaware that it costs a lot more in CPU time then azip).
39 40 41
  
  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
unknown's avatar
unknown committed
42
  only if we have a read occur. azip handles compressing lots of records
43 44 45 46 47
  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).

48 49 50 51 52 53 54 55 56 57
  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.
58

59
  At some point a recovery method for such a drastic case needs to be divised.
60

61
  Locks are row level, and you will get a consistant read. 
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 
69
  to be any faster. 
70

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

  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


83 84 85 86 87
  TODO:
   Add bzip optional support.
   Allow users to set compression level.
   Implement versioning, should be easy.
   Allow for errors, find a way to mark bad rows.
88
   Add optional feature so that rows can be flushed at interval (which will cause less
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).
   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
  auto increment - MAX value for autoincrement
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
#define ARZ ".ARZ"               // The data file
#define ARN ".ARN"               // Files used during an optimize call
#define ARM ".ARM"               // Meta file
/*
128 129
  uchar + uchar + ulonglong + ulonglong + ulonglong + ulonglong + FN_REFLEN 
  + uchar
130
*/
131
#define META_BUFFER_SIZE sizeof(uchar) + sizeof(uchar) + sizeof(ulonglong) \
132 133
  + sizeof(ulonglong) + sizeof(ulonglong) + sizeof(ulonglong) + FN_REFLEN \
  + sizeof(uchar)
134

135 136 137 138 139
/*
  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
140

141
/* Static declarations for handerton */
unknown's avatar
unknown committed
142
static handler *archive_create_handler(TABLE_SHARE *table);
143
/*
144 145 146
  Number of rows that will force a bulk insert.
*/
#define ARCHIVE_MIN_ROWS_TO_USE_BULK_INSERT 2
147

unknown's avatar
unknown committed
148
handlerton archive_hton;
unknown's avatar
unknown committed
149

unknown's avatar
unknown committed
150
static handler *archive_create_handler(TABLE_SHARE *table)
151 152 153
{
  return new ha_archive(table);
}
unknown's avatar
unknown committed
154

155 156 157 158 159 160 161 162 163 164
/*
  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;
}

165 166 167 168 169 170 171 172 173

/*
  Initialize the archive handler.

  SYNOPSIS
    archive_db_init()
    void

  RETURN
174 175
    FALSE       OK
    TRUE        Error
176 177
*/

unknown's avatar
unknown committed
178
int archive_db_init()
179
{
180
  DBUG_ENTER("archive_db_init");
unknown's avatar
unknown committed
181 182
  if (archive_inited)
    DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
183 184 185 186 187 188 189

  archive_hton.state=SHOW_OPTION_YES;
  archive_hton.db_type=DB_TYPE_ARCHIVE_DB;
  archive_hton.create=archive_create_handler;
  archive_hton.panic=archive_db_end;
  archive_hton.flags=HTON_NO_FLAGS;

190 191
  if (pthread_mutex_init(&archive_mutex, MY_MUTEX_INIT_FAST))
    goto error;
unknown's avatar
unknown committed
192 193
  if (hash_init(&archive_open_tables, system_charset_info, 32, 0, 0,
                (hash_get_key) archive_get_key, 0, 0))
194 195 196 197 198 199 200 201 202 203
  {
    VOID(pthread_mutex_destroy(&archive_mutex));
  }
  else
  {
    archive_inited= TRUE;
    DBUG_RETURN(FALSE);
  }
error:
  DBUG_RETURN(TRUE);
204 205 206 207 208 209
}

/*
  Release the archive handler.

  SYNOPSIS
unknown's avatar
unknown committed
210
    archive_db_done()
211 212 213 214 215 216
    void

  RETURN
    FALSE       OK
*/

unknown's avatar
unknown committed
217
int archive_db_done()
218
{
219 220 221 222 223 224
  if (archive_inited)
  {
    hash_free(&archive_open_tables);
    VOID(pthread_mutex_destroy(&archive_mutex));
  }
  archive_inited= 0;
225
  return 0;
226 227
}

unknown's avatar
unknown committed
228 229 230 231 232 233

int archive_db_end(ha_panic_function type)
{
  return archive_db_done();
}

unknown's avatar
unknown committed
234
ha_archive::ha_archive(TABLE_SHARE *table_arg)
235 236 237 238 239 240
  :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() */
241
  ref_length = sizeof(my_off_t);
242
}
243

244 245 246
/*
  This method reads the header of a datafile and returns whether or not it was successful.
*/
unknown's avatar
unknown committed
247
int ha_archive::read_data_header(azio_stream *file_to_read)
248
{
249
  uchar data_buffer[DATA_BUFFER_SIZE];
250 251
  DBUG_ENTER("ha_archive::read_data_header");

unknown's avatar
unknown committed
252
  if (azrewind(file_to_read) == -1)
253 254
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

unknown's avatar
unknown committed
255
  if (azread(file_to_read, data_buffer, DATA_BUFFER_SIZE) != DATA_BUFFER_SIZE)
256
    DBUG_RETURN(errno ? errno : -1);
257 258 259 260 261 262
  
  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))
263 264 265 266
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

  DBUG_RETURN(0);
}
267 268

/*
269 270
  This method writes out the header of a datafile and returns whether or not it was successful.
*/
unknown's avatar
unknown committed
271
int ha_archive::write_data_header(azio_stream *file_to_write)
272
{
273
  uchar data_buffer[DATA_BUFFER_SIZE];
274 275
  DBUG_ENTER("ha_archive::write_data_header");

276 277 278
  data_buffer[0]= (uchar)ARCHIVE_CHECK_HEADER;
  data_buffer[1]= (uchar)ARCHIVE_VERSION;

unknown's avatar
unknown committed
279
  if (azwrite(file_to_write, &data_buffer, DATA_BUFFER_SIZE) != 
280
      DATA_BUFFER_SIZE)
281
    goto error;
282 283
  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]));
284 285 286 287 288 289 290 291 292 293

  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.
*/
294
int ha_archive::read_meta_file(File meta_file, ha_rows *rows, 
295
                               ulonglong *auto_increment,
296 297
                               ulonglong *forced_flushes,
                               char *real_path)
298
{
299
  uchar meta_buffer[META_BUFFER_SIZE];
300
  uchar *ptr= meta_buffer;
301 302 303 304 305
  ulonglong check_point;

  DBUG_ENTER("ha_archive::read_meta_file");

  VOID(my_seek(meta_file, 0, MY_SEEK_SET, MYF(0)));
306
  if (my_read(meta_file, (byte*)meta_buffer, META_BUFFER_SIZE, 0) != META_BUFFER_SIZE)
307 308 309 310 311
    DBUG_RETURN(-1);
  
  /*
    Parse out the meta data, we ignore version at the moment
  */
312 313 314 315 316 317 318 319

  ptr+= sizeof(uchar)*2; // Move past header
  *rows= (ha_rows)uint8korr(ptr);
  ptr+= sizeof(ulonglong); // Move past rows
  check_point= uint8korr(ptr);
  ptr+= sizeof(ulonglong); // Move past check_point
  *auto_increment= uint8korr(ptr);
  ptr+= sizeof(ulonglong); // Move past auto_increment
320 321
  *forced_flushes= uint8korr(ptr);
  ptr+= sizeof(ulonglong); // Move past forced_flush
322 323
  memmove(real_path, ptr, FN_REFLEN);
  ptr+= FN_REFLEN; // Move past the possible location of the file
324 325 326

  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]));
327 328 329
  DBUG_PRINT("ha_archive::read_meta_file", ("Rows %llu", *rows));
  DBUG_PRINT("ha_archive::read_meta_file", ("Checkpoint %llu", check_point));
  DBUG_PRINT("ha_archive::read_meta_file", ("Auto-Increment %llu", *auto_increment));
330
  DBUG_PRINT("ha_archive::read_meta_file", ("Forced Flushes %llu", *forced_flushes));
331
  DBUG_PRINT("ha_archive::read_meta_file", ("Real Path %s", real_path));
332
  DBUG_PRINT("ha_archive::read_meta_file", ("Dirty %d", (int)(*ptr)));
333 334

  if ((meta_buffer[0] != (uchar)ARCHIVE_CHECK_HEADER) || 
335
      ((bool)(*ptr)== TRUE))
336
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
337 338 339 340 341 342 343 344 345

  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.
346
  Upon ::open() we set to dirty, and upon ::close() we set to clean.
347
*/
348
int ha_archive::write_meta_file(File meta_file, ha_rows rows, 
349 350
                                ulonglong auto_increment, 
                                ulonglong forced_flushes, 
351
                                char *real_path,
352
                                bool dirty)
353
{
354
  uchar meta_buffer[META_BUFFER_SIZE];
355
  uchar *ptr= meta_buffer;
356 357
  ulonglong check_point= 0; //Reserved for the future

358 359
  DBUG_ENTER("ha_archive::write_meta_file");

360 361 362 363 364 365 366 367 368 369
  *ptr= (uchar)ARCHIVE_CHECK_HEADER;
  ptr += sizeof(uchar);
  *ptr= (uchar)ARCHIVE_VERSION;
  ptr += sizeof(uchar);
  int8store(ptr, (ulonglong)rows); 
  ptr += sizeof(ulonglong);
  int8store(ptr, check_point); 
  ptr += sizeof(ulonglong);
  int8store(ptr, auto_increment); 
  ptr += sizeof(ulonglong);
370 371
  int8store(ptr, forced_flushes); 
  ptr += sizeof(ulonglong);
372 373 374 375 376 377
  // No matter what, we pad with nulls
  if (real_path)
    strncpy((char *)ptr, real_path, FN_REFLEN);
  else
    bzero(ptr, FN_REFLEN);
  ptr += FN_REFLEN;
378 379 380 381 382
  *ptr= (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));
383
  DBUG_PRINT("ha_archive::write_meta_file", ("Rows %llu", (ulonglong)rows));
384
  DBUG_PRINT("ha_archive::write_meta_file", ("Checkpoint %llu", check_point));
385 386
  DBUG_PRINT("ha_archive::write_meta_file", ("Auto Increment %llu",
                                             auto_increment));
387 388
  DBUG_PRINT("ha_archive::write_meta_file", ("Forced Flushes %llu", 
                                            forced_flushes));
389 390
  DBUG_PRINT("ha_archive::write_meta_file", ("Real path %s", 
                                            real_path));
391
  DBUG_PRINT("ha_archive::write_meta_file", ("Dirty %d", (uint)dirty));
392 393

  VOID(my_seek(meta_file, 0, MY_SEEK_SET, MYF(0)));
394
  if (my_write(meta_file, (byte *)meta_buffer, META_BUFFER_SIZE, 0) != META_BUFFER_SIZE)
395 396 397 398 399 400 401 402 403 404
    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. 
405 406 407
  No matter what we try to get or create a share. This is so that a repair
  table operation can occur. 

408
  See ha_example.cc for a longer description.
409
*/
410 411
ARCHIVE_SHARE *ha_archive::get_share(const char *table_name, 
                                     TABLE *table, int *rc)
412 413
{
  ARCHIVE_SHARE *share;
414
  char meta_file_name[FN_REFLEN];
415 416
  uint length;
  char *tmp_name;
417
  DBUG_ENTER("ha_archive::get_share");
418 419 420 421 422 423 424 425

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

  if (!(share=(ARCHIVE_SHARE*) hash_search(&archive_open_tables,
                                           (byte*) table_name,
                                           length)))
  {
426
    if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
427 428
                          &share, sizeof(*share),
                          &tmp_name, length+1,
429
                          NullS)) 
430 431
    {
      pthread_mutex_unlock(&archive_mutex);
432 433
      *rc= HA_ERR_OUT_OF_MEM;
      DBUG_RETURN(NULL);
434 435
    }

436 437 438
    share->use_count= 0;
    share->table_name_length= length;
    share->table_name= tmp_name;
439
    share->crashed= FALSE;
440
    share->archive_write_open= FALSE;
441 442 443 444
    fn_format(share->data_file_name, table_name, "",
              ARZ,MY_REPLACE_EXT|MY_UNPACK_FILENAME);
    fn_format(meta_file_name, table_name, "", ARM,
              MY_REPLACE_EXT|MY_UNPACK_FILENAME);
445
    strmov(share->table_name,table_name);
446 447 448 449 450
    /*
      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)
451
      share->crashed= TRUE;
452 453
    DBUG_PRINT("info", ("archive opening (1) up write at %s", 
                        share->data_file_name));
454 455
    
    /*
456 457
      We read the meta file, but do not mark it dirty unless we actually do
      a write.
458
    */
459
    if (read_meta_file(share->meta_file, &share->rows_recorded, 
460
                       &share->auto_increment_value,
461 462
                       &share->forced_flushes,
                       share->real_path))
463
      share->crashed= TRUE;
464 465 466 467 468 469
    /*
      Since we now possibly no real_path, we will use it instead if it exists.
    */
    if (*share->real_path)
      fn_format(share->data_file_name, share->real_path, "", ARZ,
                MY_REPLACE_EXT|MY_UNPACK_FILENAME);
470
    VOID(my_hash_insert(&archive_open_tables, (byte*) share));
471
    thr_lock_init(&share->lock);
472 473
  }
  share->use_count++;
474 475 476 477 478
  DBUG_PRINT("info", ("archive table %.*s has %d open handles now", 
                      share->table_name_length, share->table_name,
                      share->use_count));
  if (share->crashed)
    *rc= HA_ERR_CRASHED_ON_USAGE;
479 480
  pthread_mutex_unlock(&archive_mutex);

481
  DBUG_RETURN(share);
482 483 484 485
}


/* 
486
  Free the share.
487 488
  See ha_example.cc for a description.
*/
489
int ha_archive::free_share(ARCHIVE_SHARE *share)
490 491
{
  int rc= 0;
492 493 494 495 496
  DBUG_ENTER("ha_archive::free_share");
  DBUG_PRINT("info", ("archive table %.*s has %d open handles on entrance", 
                      share->table_name_length, share->table_name,
                      share->use_count));

497 498 499 500 501
  pthread_mutex_lock(&archive_mutex);
  if (!--share->use_count)
  {
    hash_delete(&archive_open_tables, (byte*) share);
    thr_lock_delete(&share->lock);
502
    VOID(pthread_mutex_destroy(&share->mutex));
503 504 505 506 507 508 509 510 511 512 513
    /* 
      We need to make sure we don't reset the crashed state.
      If we open a crashed file, wee need to close it as crashed unless
      it has been repaired.
      Since we will close the data down after this, we go on and count
      the flush on close;
    */
    share->forced_flushes++;
    (void)write_meta_file(share->meta_file, share->rows_recorded,
                          share->auto_increment_value, 
                          share->forced_flushes, 
514
                          share->real_path, 
515
                          share->crashed ? TRUE :FALSE);
516
    if (share->archive_write_open)
517
      if (azclose(&(share->archive_write)))
518
        rc= 1;
519 520
    if (my_close(share->meta_file, MYF(0)))
      rc= 1;
unknown's avatar
unknown committed
521
    my_free((gptr) share, MYF(0));
522 523 524
  }
  pthread_mutex_unlock(&archive_mutex);

525
  DBUG_RETURN(rc);
526 527
}

528 529 530
int ha_archive::init_archive_writer()
{
  DBUG_ENTER("ha_archive::init_archive_writer");
531 532 533 534 535
  (void)write_meta_file(share->meta_file, share->rows_recorded,
                        share->auto_increment_value, 
                        share->forced_flushes, 
                        share->real_path,
                        TRUE);
536 537 538 539 540 541

  /* 
    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.
  */
542 543
  if (!(azopen(&(share->archive_write), share->data_file_name, 
               O_WRONLY|O_APPEND|O_BINARY)))
544
  {
545
    DBUG_PRINT("info", ("Could not open archive write file"));
546 547 548 549 550 551 552 553
    share->crashed= TRUE;
    DBUG_RETURN(1);
  }
  share->archive_write_open= TRUE;

  DBUG_RETURN(0);
}

554

unknown's avatar
unknown committed
555
/*
556 557
  We just implement one additional file extension.
*/
unknown's avatar
unknown committed
558 559 560 561 562 563
static const char *ha_archive_exts[] = {
  ARZ,
  ARM,
  NullS
};

564
const char **ha_archive::bas_ext() const
unknown's avatar
unknown committed
565 566 567
{
  return ha_archive_exts;
}
568 569 570 571 572 573 574 575


/* 
  When opening a file we:
  Create/get our shared structure.
  Init out lock.
  We open the file we will read from.
*/
576
int ha_archive::open(const char *name, int mode, uint open_options)
577
{
578
  int rc= 0;
579 580
  DBUG_ENTER("ha_archive::open");

581
  DBUG_PRINT("info", ("archive table was opened for crash: %s", 
582 583 584 585 586 587 588 589 590 591 592 593 594
                      (open_options & HA_OPEN_FOR_REPAIR) ? "yes" : "no"));
  share= get_share(name, table, &rc);

  if (rc == HA_ERR_CRASHED_ON_USAGE && !(open_options & HA_OPEN_FOR_REPAIR))
  {
    free_share(share);
    DBUG_RETURN(rc);
  }
  else if (rc == HA_ERR_OUT_OF_MEM)
  {
    DBUG_RETURN(rc);
  }

595 596
  thr_lock_data_init(&share->lock,&lock,NULL);

597
  DBUG_PRINT("info", ("archive data_file_name %s", share->data_file_name));
unknown's avatar
unknown committed
598
  if (!(azopen(&archive, share->data_file_name, O_RDONLY|O_BINARY)))
599
  {
600 601 602
    if (errno == EROFS || errno == EACCES)
      DBUG_RETURN(my_errno= errno);
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
603
  }
604

605 606 607 608
  DBUG_PRINT("info", ("archive table was crashed %s", 
                      rc == HA_ERR_CRASHED_ON_USAGE ? "yes" : "no"));
  if (rc == HA_ERR_CRASHED_ON_USAGE && open_options & HA_OPEN_FOR_REPAIR)
  {
609
    DBUG_RETURN(0);
610 611 612
  }
  else
    DBUG_RETURN(rc);
613 614 615 616
}


/*
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
  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
*/

633 634
int ha_archive::close(void)
{
635
  int rc= 0;
636
  DBUG_ENTER("ha_archive::close");
637 638

  /* First close stream */
unknown's avatar
unknown committed
639
  if (azclose(&archive))
640 641 642 643 644
    rc= 1;
  /* then also close share */
  rc|= free_share(share);

  DBUG_RETURN(rc);
645 646 647 648
}


/*
649 650 651 652 653 654
  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.
655 656 657 658
*/

int ha_archive::create(const char *name, TABLE *table_arg,
                       HA_CREATE_INFO *create_info)
659
{
660
  File create_file;  // We use to create the datafile and the metafile
661
  char name_buff[FN_REFLEN];
662
  int error;
663 664
  DBUG_ENTER("ha_archive::create");

665 666 667 668
  auto_increment_value= (create_info->auto_increment_value ?
                   create_info->auto_increment_value -1 :
                   (ulonglong) 0);

669 670 671 672 673 674 675
  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;
  }
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694

  for (uint key= 0; key < table_arg->s->keys; key++)
  {
    KEY *pos= table_arg->key_info+key;
    KEY_PART_INFO *key_part=     pos->key_part;
    KEY_PART_INFO *key_part_end= key_part + pos->key_parts;

    for (; key_part != key_part_end; key_part++)
    {
      Field *field= key_part->field;

      if (!(field->flags & AUTO_INCREMENT_FLAG))
      {
        error= -1;
        goto error;
      }
    }
  }

695 696 697
  write_meta_file(create_file, 0, auto_increment_value, 0, 
                  (char *)create_info->data_file_name,
                  FALSE);
698 699 700 701 702
  my_close(create_file,MYF(0));

  /* 
    We reuse name_buff since it is available.
  */
703
  if (create_info->data_file_name)
704
  {
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
    char linkname[FN_REFLEN];
    DBUG_PRINT("info", ("archive will create stream file %s", 
                        create_info->data_file_name));
                        
    fn_format(name_buff, create_info->data_file_name, "", ARZ,
              MY_REPLACE_EXT|MY_UNPACK_FILENAME);
    fn_format(linkname, name, "", ARZ,
              MY_UNPACK_FILENAME | MY_APPEND_EXT);
    if ((create_file= my_create_with_symlink(linkname, name_buff, 0,
                                O_RDWR | O_TRUNC,MYF(MY_WME))) < 0)
    {
      error= my_errno;
      goto error;
    }
  }
  else
  {
    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;
      goto error;
    }
729
  }
unknown's avatar
unknown committed
730
  if (!azdopen(&archive, create_file, O_WRONLY|O_BINARY))
731
  {
732
    error= errno;
733
    goto error2;
734
  }
unknown's avatar
unknown committed
735
  if (write_data_header(&archive))
736
  {
737 738
    error= errno;
    goto error3;
739
  }
740

unknown's avatar
unknown committed
741
  if (azclose(&archive))
unknown's avatar
unknown committed
742
  {
743
    error= errno;
744
    goto error2;
745 746
  }

747
  DBUG_RETURN(0);
748

749
error3:
unknown's avatar
unknown committed
750 751
  /* We already have an error, so ignore results of azclose. */
  (void)azclose(&archive);
752
error2:
753 754
  my_close(create_file, MYF(0));
  delete_table(name);
755
error:
756 757
  /* Return error number, if we got one */
  DBUG_RETURN(error ? error : -1);
758 759
}

760 761
/*
  This is where the actual row is written out.
762
*/
unknown's avatar
unknown committed
763
int ha_archive::real_write_row(byte *buf, azio_stream *writer)
764
{
765
  my_off_t written;
766
  uint *ptr, *end;
767
  DBUG_ENTER("ha_archive::real_write_row");
768

unknown's avatar
unknown committed
769
  written= azwrite(writer, buf, table->s->reclength);
770 771
  DBUG_PRINT("ha_archive::real_write_row", ("Wrote %d bytes expected %d", 
                                            written, table->s->reclength));
772
  if (!delayed_insert || !bulk_insert)
773 774
    share->dirty= TRUE;

775
  if (written != (my_off_t)table->s->reclength)
776
    DBUG_RETURN(errno ? errno : -1);
777 778 779 780
  /*
    We should probably mark the table as damagaged if the record is written
    but the blob fails.
  */
unknown's avatar
unknown committed
781
  for (ptr= table->s->blob_field, end= ptr + table->s->blob_fields ;
782 783
       ptr != end ;
       ptr++)
784
  {
785
    char *data_ptr;
786
    uint32 size= ((Field_blob*) table->field[*ptr])->get_length();
787

788 789
    if (size)
    {
790
      ((Field_blob*) table->field[*ptr])->get_ptr(&data_ptr);
unknown's avatar
unknown committed
791
      written= azwrite(writer, data_ptr, (unsigned)size);
792
      if (written != (my_off_t)size)
793
        DBUG_RETURN(errno ? errno : -1);
794
    }
795
  }
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
  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;
812 813
  byte *read_buf= NULL;
  ulonglong temp_auto;
814 815 816 817 818
  DBUG_ENTER("ha_archive::write_row");

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

unknown's avatar
unknown committed
819
  ha_statistic_increment(&SSV::ha_write_count);
820 821 822
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT)
    table->timestamp_field->set_time();
  pthread_mutex_lock(&share->mutex);
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859

  if (table->next_number_field)
  {
    KEY *mkey= &table->s->key_info[0]; // We only support one key right now
    update_auto_increment();
    temp_auto= table->next_number_field->val_int();

    /*
      Bad news, this will cause a search for the unique value which is very 
      expensive since we will have to do a table scan which will lock up 
      all other writers during this period. This could perhaps be optimized 
      in the future.
    */
    if (temp_auto == share->auto_increment_value && 
        mkey->flags & HA_NOSAME)
    {
      rc= HA_ERR_FOUND_DUPP_KEY;
      goto error;
    }

    if (temp_auto < share->auto_increment_value && 
        mkey->flags & HA_NOSAME)
    {
      /* 
        First we create a buffer that we can use for reading rows, and can pass
        to get_row().
      */
      if (!(read_buf= (byte*) my_malloc(table->s->reclength, MYF(MY_WME))))
      {
        rc= HA_ERR_OUT_OF_MEM;
        goto error;
      }
       /* 
         All of the buffer must be written out or we won't see all of the
         data 
       */
      azflush(&(share->archive_write), Z_SYNC_FLUSH);
860
      share->forced_flushes++;
861 862 863 864 865 866 867 868 869 870 871 872
      /*
        Set the position of the local read thread to the beginning postion.
      */
      if (read_data_header(&archive))
      {
        rc= HA_ERR_CRASHED_ON_USAGE;
        goto error;
      }

      /*
        Now we read and check all of the rows.
        if (!memcmp(table->next_number_field->ptr, mfield->ptr, mfield->max_length()))
873 874
        if ((longlong)temp_auto == 
            mfield->val_int((char*)(read_buf + mfield->offset())))
875 876 877 878 879
      */
      Field *mfield= table->next_number_field;

      while (!(get_row(&archive, read_buf)))
      {
880 881
        if (!memcmp(read_buf + mfield->offset(), table->next_number_field->ptr,
                    mfield->max_length()))
882 883 884 885 886 887 888 889
        {
          rc= HA_ERR_FOUND_DUPP_KEY;
          goto error;
        }
      }
    }
    else
    {
890 891
      if (temp_auto > share->auto_increment_value)
        auto_increment_value= share->auto_increment_value= temp_auto;
892 893 894 895 896 897 898
    }
  }

  /*
    Notice that the global auto_increment has been increased.
    In case of a failed row write, we will never try to reuse the value.
  */
899 900 901
  if (!share->archive_write_open)
    if (init_archive_writer())
      DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
902

903
  share->rows_recorded++;
unknown's avatar
unknown committed
904
  rc= real_write_row(buf, &(share->archive_write));
905
error:
906
  pthread_mutex_unlock(&share->mutex);
907
  if (read_buf)
908
    my_free((gptr) read_buf, MYF(0));
909

910
  DBUG_RETURN(rc);
911 912
}

913 914 915

ulonglong ha_archive::get_auto_increment()
{
916
  return share->auto_increment_value + 1;
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
}

/* Initialized at each key walk (called multiple times unlike rnd_init()) */
int ha_archive::index_init(uint keynr, bool sorted)
{
  DBUG_ENTER("ha_archive::index_init");
  active_index= keynr;
  DBUG_RETURN(0);
}


/*
  No indexes, so if we get a request for an index search since we tell
  the optimizer that we have unique indexes, we scan
*/
int ha_archive::index_read(byte *buf, const byte *key,
                             uint key_len, enum ha_rkey_function find_flag)
{
  int rc;
  DBUG_ENTER("ha_archive::index_read");
  rc= index_read_idx(buf, active_index, key, key_len, find_flag);
  DBUG_RETURN(rc);
}


int ha_archive::index_read_idx(byte *buf, uint index, const byte *key,
                                 uint key_len, enum ha_rkey_function find_flag)
{
  int rc= 0;
  bool found= 0;
  KEY *mkey= &table->s->key_info[index];
948 949 950
  current_k_offset= mkey->key_part->offset;
  current_key= key;
  current_key_len= key_len;
951 952 953 954 955 956 957 958 959 960


  DBUG_ENTER("ha_archive::index_read_idx");

  /* 
    All of the buffer must be written out or we won't see all of the
    data 
  */
  pthread_mutex_lock(&share->mutex);
  azflush(&(share->archive_write), Z_SYNC_FLUSH);
961
  share->forced_flushes++;
962 963 964 965 966 967 968 969 970 971 972 973 974
  pthread_mutex_unlock(&share->mutex);

  /*
    Set the position of the local read thread to the beginning postion.
  */
  if (read_data_header(&archive))
  {
    rc= HA_ERR_CRASHED_ON_USAGE;
    goto error;
  }

  while (!(get_row(&archive, buf)))
  {
975
    if (!memcmp(current_key, buf + current_k_offset, current_key_len))
976 977 978 979 980 981 982 983 984 985 986 987 988
    {
      found= 1;
      break;
    }
  }

  if (found)
    DBUG_RETURN(0);

error:
  DBUG_RETURN(rc ? rc : HA_ERR_END_OF_FILE);
}

989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007

int ha_archive::index_next(byte * buf) 
{ 
  bool found= 0;

  DBUG_ENTER("ha_archive::index_next");

  while (!(get_row(&archive, buf)))
  {
    if (!memcmp(current_key, buf+current_k_offset, current_key_len))
    {
      found= 1;
      break;
    }
  }

  DBUG_RETURN(found ? 0 : HA_ERR_END_OF_FILE); 
}

1008 1009 1010 1011 1012
/*
  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.
*/
1013

1014 1015 1016
int ha_archive::rnd_init(bool scan)
{
  DBUG_ENTER("ha_archive::rnd_init");
1017 1018 1019
  
  if (share->crashed)
      DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
1020

1021
  /* We rewind the file so that we can read from the beginning if scan */
1022
  if (scan)
1023
  {
1024
    scan_rows= share->rows_recorded;
1025
    DBUG_PRINT("info", ("archive will retrieve %llu rows", scan_rows));
1026 1027
    records= 0;

1028 1029
    /* 
      If dirty, we lock, and then reset/flush the data.
unknown's avatar
unknown committed
1030
      I found that just calling azflush() doesn't always work.
1031
    */
1032
    if (share->dirty == TRUE)
1033
    {
1034 1035 1036
      pthread_mutex_lock(&share->mutex);
      if (share->dirty == TRUE)
      {
1037
        DBUG_PRINT("info", ("archive flushing out rows for scan"));
unknown's avatar
unknown committed
1038
        azflush(&(share->archive_write), Z_SYNC_FLUSH);
1039
        share->forced_flushes++;
1040 1041 1042
        share->dirty= FALSE;
      }
      pthread_mutex_unlock(&share->mutex);
1043
    }
1044

unknown's avatar
unknown committed
1045
    if (read_data_header(&archive))
1046
      DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
1047 1048
  }

1049 1050 1051 1052 1053 1054 1055 1056
  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.
*/
unknown's avatar
unknown committed
1057
int ha_archive::get_row(azio_stream *file_to_read, byte *buf)
1058
{
unknown's avatar
unknown committed
1059
  int read; // Bytes read, azread() returns int
1060
  uint *ptr, *end;
1061 1062
  char *last;
  size_t total_blob_length= 0;
1063
  DBUG_ENTER("ha_archive::get_row");
1064

unknown's avatar
unknown committed
1065
  read= azread(file_to_read, buf, table->s->reclength);
1066 1067
  DBUG_PRINT("ha_archive::get_row", ("Read %d bytes expected %d", read, 
                                     table->s->reclength));
1068 1069 1070

  if (read == Z_STREAM_ERROR)
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
1071 1072 1073 1074 1075

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

1076 1077 1078
  /* 
    If the record is the wrong size, the file is probably damaged, unless 
    we are dealing with a delayed insert or a bulk insert.
1079
  */
1080
  if ((ulong) read != table->s->reclength)
1081
    DBUG_RETURN(HA_ERR_END_OF_FILE);
1082 1083

  /* Calculate blob length, we use this for our buffer */
1084 1085 1086
  for (ptr= table->s->blob_field, end=ptr + table->s->blob_fields ;
       ptr != end ;
       ptr++)
1087 1088 1089 1090
  {
    if (ha_get_bit_in_read_set(((Field_blob*) table->field[*ptr])->fieldnr))
      total_blob_length += ((Field_blob*) table->field[*ptr])->get_length();
  }
1091 1092 1093

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

1096
  /* Loop through our blobs and read them */
1097 1098 1099
  for (ptr= table->s->blob_field, end=ptr + table->s->blob_fields ;
       ptr != end ;
       ptr++)
1100
  {
1101
    size_t size= ((Field_blob*) table->field[*ptr])->get_length();
1102 1103
    if (size)
    {
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
      if (ha_get_bit_in_read_set(((Field_blob*) table->field[*ptr])->fieldnr))
      {
        read= azread(file_to_read, last, size);
        if ((size_t) read != size)
          DBUG_RETURN(HA_ERR_END_OF_FILE);
        ((Field_blob*) table->field[*ptr])->set_ptr(size, last);
        last += size;
      }
      else
      {
        (void)azseek(file_to_read, size, SEEK_CUR);
      }
1116
    }
1117 1118 1119 1120
  }
  DBUG_RETURN(0);
}

1121

1122 1123 1124 1125
/* 
  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.
*/
1126

1127 1128 1129
int ha_archive::rnd_next(byte *buf)
{
  int rc;
1130
  DBUG_ENTER("ha_archive::rnd_next");
1131

1132 1133 1134
  if (share->crashed)
      DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

1135 1136 1137 1138
  if (!scan_rows)
    DBUG_RETURN(HA_ERR_END_OF_FILE);
  scan_rows--;

unknown's avatar
unknown committed
1139
  ha_statistic_increment(&SSV::ha_read_rnd_next_count);
unknown's avatar
unknown committed
1140 1141
  current_position= aztell(&archive);
  rc= get_row(&archive, buf);
1142 1143


1144
  if (rc != HA_ERR_END_OF_FILE)
1145 1146 1147 1148 1149 1150
    records++;

  DBUG_RETURN(rc);
}


1151
/*
1152 1153 1154 1155
  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.
*/
1156

1157 1158 1159
void ha_archive::position(const byte *record)
{
  DBUG_ENTER("ha_archive::position");
1160
  my_store_ptr(ref, ref_length, current_position);
1161 1162 1163 1164 1165
  DBUG_VOID_RETURN;
}


/*
1166 1167 1168 1169
  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.
1170
*/
1171

1172 1173 1174
int ha_archive::rnd_pos(byte * buf, byte *pos)
{
  DBUG_ENTER("ha_archive::rnd_pos");
unknown's avatar
unknown committed
1175
  ha_statistic_increment(&SSV::ha_read_rnd_next_count);
1176
  current_position= (my_off_t)my_get_ptr(pos, ref_length);
unknown's avatar
unknown committed
1177
  (void)azseek(&archive, current_position, SEEK_SET);
1178

unknown's avatar
unknown committed
1179
  DBUG_RETURN(get_row(&archive, buf));
1180 1181 1182
}

/*
1183
  This method repairs the meta file. It does this by walking the datafile and 
1184 1185
  rewriting the meta file. Currently it does this by calling optimize with
  the extended flag.
1186
*/
1187
int ha_archive::repair(THD* thd, HA_CHECK_OPT* check_opt)
1188
{
1189
  DBUG_ENTER("ha_archive::repair");
1190 1191
  check_opt->flags= T_EXTEND;
  int rc= optimize(thd, check_opt);
1192

1193 1194
  if (rc)
    DBUG_RETURN(HA_ERR_CRASHED_ON_REPAIR);
1195

1196
  share->crashed= FALSE;
1197
  DBUG_RETURN(0);
1198 1199
}

1200 1201 1202
/*
  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. 
1203
*/
1204 1205 1206
int ha_archive::optimize(THD* thd, HA_CHECK_OPT* check_opt)
{
  DBUG_ENTER("ha_archive::optimize");
1207
  int rc= 0;
unknown's avatar
unknown committed
1208
  azio_stream writer;
1209 1210
  char writer_filename[FN_REFLEN];

1211 1212 1213 1214
  /* Open up the writer if we haven't yet */
  if (!share->archive_write_open)
    init_archive_writer();

1215
  /* Flush any waiting data */
unknown's avatar
unknown committed
1216
  azflush(&(share->archive_write), Z_SYNC_FLUSH);
1217
  share->forced_flushes++;
1218

1219
  /* Lets create a file to contain the new data */
1220 1221
  fn_format(writer_filename, share->table_name, "", ARN, 
            MY_REPLACE_EXT|MY_UNPACK_FILENAME);
1222

unknown's avatar
unknown committed
1223
  if (!(azopen(&writer, writer_filename, O_CREAT|O_WRONLY|O_TRUNC|O_BINARY)))
1224 1225 1226 1227 1228 1229 1230 1231
    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)
1232
  {
unknown's avatar
unknown committed
1233
    DBUG_PRINT("info", ("archive extended rebuild"));
1234
    byte *buf; 
1235

1236 1237 1238 1239 1240 1241 1242 1243 1244
    /* 
      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;
    }
1245

1246 1247 1248 1249
    /*
      Now we will rewind the archive file so that we are positioned at the 
      start of the file.
    */
unknown's avatar
unknown committed
1250
    rc= read_data_header(&archive);
1251 1252 1253 1254 1255 1256
    
    /*
      Assuming now error from rewinding the archive file, we now write out the 
      new header for out data file.
    */
    if (!rc)
unknown's avatar
unknown committed
1257
      rc= write_data_header(&writer);
1258 1259 1260 1261 1262 1263

    /* 
      On success of writing out the new header, we now fetch each row and
      insert it into the new archive file. 
    */
    if (!rc)
1264 1265
    {
      share->rows_recorded= 0;
1266
      auto_increment_value= share->auto_increment_value= 0;
unknown's avatar
unknown committed
1267
      while (!(rc= get_row(&archive, buf)))
1268
      {
unknown's avatar
unknown committed
1269
        real_write_row(buf, &writer);
1270 1271 1272
        if (table->found_next_number_field)
        {
          Field *field= table->found_next_number_field;
1273 1274 1275
          ulonglong auto_value=
            (ulonglong) field->val_int((char*)(buf + field->offset()));
          if (share->auto_increment_value < auto_value)
1276
            auto_increment_value= share->auto_increment_value=
1277
              auto_value;
1278
        }
1279 1280 1281
        share->rows_recorded++;
      }
    }
1282
    DBUG_PRINT("info", ("recovered %llu archive rows", share->rows_recorded));
1283

unknown's avatar
unknown committed
1284
    my_free((char*)buf, MYF(0));
1285 1286 1287 1288 1289
    if (rc && rc != HA_ERR_END_OF_FILE)
      goto error;
  } 
  else
  {
unknown's avatar
unknown committed
1290
    DBUG_PRINT("info", ("archive quick rebuild"));
1291 1292 1293
    /* 
      The quick method is to just read the data raw, and then compress it directly.
    */
unknown's avatar
unknown committed
1294
    int read; // Bytes read, azread() returns int
1295
    char block[IO_SIZE];
unknown's avatar
unknown committed
1296
    if (azrewind(&archive) == -1)
1297 1298
    {
      rc= HA_ERR_CRASHED_ON_USAGE;
unknown's avatar
unknown committed
1299
      DBUG_PRINT("info", ("archive HA_ERR_CRASHED_ON_USAGE"));
1300 1301 1302
      goto error;
    }

1303
    while ((read= azread(&archive, block, IO_SIZE)) > 0)
unknown's avatar
unknown committed
1304
      azwrite(&writer, block, read);
1305 1306
  }

unknown's avatar
unknown committed
1307
  azclose(&writer);
1308
  share->dirty= FALSE;
1309
  share->forced_flushes= 0;
1310 1311
  
  // now we close both our writer and our reader for the rename
1312
  azclose(&(share->archive_write));
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
  azclose(&archive);

  // make the file we just wrote be our data file
  rc = my_rename(writer_filename,share->data_file_name,MYF(0));

  /*
    now open the shared writer back up
    we don't check rc here because we want to open the file back up even
    if the optimize failed but we will return rc below so that we will
    know it failed.
1323
    We also need to reopen our read descriptor since it has changed.
1324
  */
1325
  DBUG_PRINT("info", ("Reopening archive data file"));
1326 1327 1328
  if (!azopen(&(share->archive_write), share->data_file_name,
               O_WRONLY|O_APPEND|O_BINARY) ||
      !azopen(&archive, share->data_file_name, O_RDONLY|O_BINARY))
unknown's avatar
unknown committed
1329 1330 1331
  {
    DBUG_PRINT("info", ("Could not open archive write file"));
    rc= HA_ERR_CRASHED_ON_USAGE;
1332 1333
  }

1334
  DBUG_RETURN(rc);
1335
error:
unknown's avatar
unknown committed
1336
  azclose(&writer);
1337 1338 1339

  DBUG_RETURN(rc); 
}
1340 1341 1342 1343 1344 1345 1346 1347

/* 
  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)
{
1348 1349 1350 1351 1352
  if (lock_type == TL_WRITE_DELAYED)
    delayed_insert= TRUE;
  else
    delayed_insert= FALSE;

1353 1354
  if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK) 
  {
1355 1356 1357 1358 1359 1360 1361 1362
    /* 
      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 &&
unknown's avatar
unknown committed
1363 1364
         lock_type <= TL_WRITE) && !thd_in_lock_tables(thd)
        && !thd_tablespace_op(thd))
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
      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. 
    */

unknown's avatar
unknown committed
1375
    if (lock_type == TL_READ_NO_INSERT && !thd_in_lock_tables(thd)) 
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
      lock_type = TL_READ;

    lock.type=lock_type;
  }

  *to++= &lock;

  return to;
}

1386 1387 1388 1389 1390
void ha_archive::update_create_info(HA_CREATE_INFO *create_info)
{
  ha_archive::info(HA_STATUS_AUTO | HA_STATUS_CONST);
  if (!(create_info->used_fields & HA_CREATE_USED_AUTO))
  {
1391
    create_info->auto_increment_value= auto_increment_value;
1392
  }
1393 1394
  if (*share->real_path)
    create_info->data_file_name= share->real_path;
1395 1396
}

1397 1398 1399 1400

/*
  Hints for optimizer, see ha_tina for more information
*/
1401 1402 1403
void ha_archive::info(uint flag)
{
  DBUG_ENTER("ha_archive::info");
1404 1405 1406 1407
  /* 
    This should be an accurate number now, though bulk and delayed inserts can
    cause the number to be inaccurate.
  */
1408 1409
  records= share->rows_recorded;
  deleted= 0;
1410 1411 1412 1413 1414 1415 1416
  /* 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)));

1417
    mean_rec_length= table->s->reclength + buffer.alloced_length();
unknown's avatar
unknown committed
1418
    data_file_length= file_stat.st_size;
1419 1420
    create_time= file_stat.st_ctime;
    update_time= file_stat.st_mtime;
unknown's avatar
unknown committed
1421
    max_data_file_length= share->rows_recorded * mean_rec_length;
1422 1423 1424
  }
  delete_length= 0;
  index_file_length=0;
1425

1426 1427 1428
  if (flag & HA_STATUS_AUTO)
    auto_increment_value= share->auto_increment_value;

1429 1430
  DBUG_VOID_RETURN;
}
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440


/*
  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)
{
1441
  DBUG_ENTER("ha_archive::start_bulk_insert");
1442 1443
  if (!rows || rows >= ARCHIVE_MIN_ROWS_TO_USE_BULK_INSERT)
    bulk_insert= TRUE;
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
  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()
{
1454
  DBUG_ENTER("ha_archive::end_bulk_insert");
1455 1456 1457 1458
  bulk_insert= FALSE;
  share->dirty= TRUE;
  DBUG_RETURN(0);
}
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469

/*
  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);
}
1470 1471 1472 1473 1474 1475

/*
  We just return state if asked.
*/
bool ha_archive::is_crashed() const 
{
1476 1477
  DBUG_ENTER("ha_archive::is_crashed");
  DBUG_RETURN(share->crashed); 
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
}

/*
  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; 
unknown's avatar
unknown committed
1488
  const char *old_proc_info;
1489 1490 1491
  ha_rows count= share->rows_recorded;
  DBUG_ENTER("ha_archive::check");

unknown's avatar
unknown committed
1492
  old_proc_info= thd_proc_info(thd, "Checking table");
1493
  /* Flush any waiting data */
unknown's avatar
unknown committed
1494
  azflush(&(share->archive_write), Z_SYNC_FLUSH);
1495
  share->forced_flushes++;
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508

  /* 
    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)
unknown's avatar
unknown committed
1509
    read_data_header(&archive);
1510 1511

  if (!rc)
unknown's avatar
unknown committed
1512
    while (!(rc= get_row(&archive, buf)))
1513 1514 1515 1516
      count--;

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

unknown's avatar
unknown committed
1517
  thd_proc_info(thd, old_proc_info);
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539

  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();

1540
  DBUG_RETURN(repair(thd, &check_opt));
1541
}
unknown's avatar
unknown committed
1542

unknown's avatar
unknown committed
1543 1544
struct st_mysql_storage_engine archive_storage_engine=
{ MYSQL_HANDLERTON_INTERFACE_VERSION, &archive_hton };
unknown's avatar
unknown committed
1545 1546 1547 1548

mysql_declare_plugin(archive)
{
  MYSQL_STORAGE_ENGINE_PLUGIN,
unknown's avatar
unknown committed
1549 1550
  &archive_storage_engine,
  "ARCHIVE",
unknown's avatar
unknown committed
1551
  "Brian Aker, MySQL AB",
unknown's avatar
unknown committed
1552 1553
  "Archive storage engine",
  archive_db_init, /* Plugin Init */
unknown's avatar
unknown committed
1554 1555 1556 1557
  archive_db_done, /* Plugin Deinit */
  0x0100 /* 1.0 */,
}
mysql_declare_plugin_end;
unknown's avatar
unknown committed
1558