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

/*
  Make sure to look at ha_tina.h for more details.

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
  First off, this is a play thing for me, there are a number of things
  wrong with it:
    *) It was designed for csv and therefore its performance is highly
       questionable.
    *) Indexes have not been implemented. This is because the files can
       be traded in and out of the table directory without having to worry
       about rebuilding anything.
    *) NULLs and "" are treated equally (like a spreadsheet).
    *) There was in the beginning no point to anyone seeing this other
       then me, so there is a good chance that I haven't quite documented
       it well.
    *) Less design, more "make it work"

  Now there are a few cool things with it:
    *) Errors can result in corrupted data files.
    *) Data files can be read by spreadsheets directly.
36 37 38 39 40 41 42 43 44

TODO:
 *) Move to a block system for larger files
 *) Error recovery, its all there, just need to finish it
 *) Document how the chains work.

 -Brian
*/

kent@mysql.com's avatar
kent@mysql.com committed
45
#ifdef USE_PRAGMA_IMPLEMENTATION
46 47 48 49
#pragma implementation        // gcc: Class implementation
#endif

#include "mysql_priv.h"
50

51 52
#include "ha_tina.h"

53
#include <mysql/plugin.h>
54

55 56 57 58 59 60 61 62 63
/*
  uchar + uchar + ulonglong + ulonglong + ulonglong + ulonglong + uchar
*/
#define META_BUFFER_SIZE sizeof(uchar) + sizeof(uchar) + sizeof(ulonglong) \
  + sizeof(ulonglong) + sizeof(ulonglong) + sizeof(ulonglong) + sizeof(uchar)
#define TINA_CHECK_HEADER 254 // The number we use to determine corruption

/* The file extension */
#define CSV_EXT ".CSV"               // The data file
64
#define CSN_EXT ".CSN"               // Files used during repair and update
65 66 67
#define CSM_EXT ".CSM"               // Meta file


68 69 70 71
static TINA_SHARE *get_share(const char *table_name, TABLE *table);
static int free_share(TINA_SHARE *share);
static int read_meta_file(File meta_file, ha_rows *rows);
static int write_meta_file(File meta_file, ha_rows rows, bool dirty);
72

73 74 75 76
/* Stuff for shares */
pthread_mutex_t tina_mutex;
static HASH tina_open_tables;
static int tina_init= 0;
77
static handler *tina_create_handler(TABLE_SHARE *table, MEM_ROOT *mem_root);
78
static int tina_init_func();
79

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
off_t Transparent_file::read_next()
{
  off_t bytes_read;

  /*
     No need to seek here, as the file managed by Transparent_file class
     always points to upper_bound byte
  */
  if ((bytes_read= my_read(filedes, buff, buff_size, MYF(0))) == MY_FILE_ERROR)
    return -1;

  /* end of file */
  if (!bytes_read)
    return -1;

  lower_bound= upper_bound;
  upper_bound+= bytes_read;

  return lower_bound;
}


char Transparent_file::get_value(off_t offset)
{
  off_t bytes_read;

  /* check boundaries */
  if ((lower_bound <= offset) && (offset < upper_bound))
    return buff[offset - lower_bound];
  else
  {
    VOID(my_seek(filedes, offset, MY_SEEK_SET, MYF(0)));
    /* read appropriate portion of the file */
    if ((bytes_read= my_read(filedes, buff, buff_size,
                             MYF(0))) == MY_FILE_ERROR)
      return 0;

    lower_bound= offset;
    upper_bound= lower_bound + bytes_read;

    /* end of file */
    if (upper_bound == offset)
      return 0;

    return buff[0];
  }
}
127
handlerton tina_hton;
128

129 130 131 132
/*****************************************************************************
 ** TINA tables
 *****************************************************************************/

133
/*
134
  Used for sorting chains with qsort().
135 136 137
*/
int sort_set (tina_set *a, tina_set *b)
{
138 139 140 141
  /*
    We assume that intervals do not intersect. So, it is enought to compare
    any two points. Here we take start of intervals for comparison.
  */
142
  return ( a->begin > b->begin ? 1 : ( a->begin < b->begin ? -1 : 0 ) );
143 144 145 146 147 148 149 150 151
}

static byte* tina_get_key(TINA_SHARE *share,uint *length,
                          my_bool not_used __attribute__((unused)))
{
  *length=share->table_name_length;
  return (byte*) share->table_name;
}

152 153 154 155 156 157 158 159
static int tina_init_func()
{
  if (!tina_init)
  {
    tina_init++;
    VOID(pthread_mutex_init(&tina_mutex,MY_MUTEX_INIT_FAST));
    (void) hash_init(&tina_open_tables,system_charset_info,32,0,0,
                     (hash_get_key) tina_get_key,0,0);
160
    bzero(&tina_hton, sizeof(handlerton));
161 162 163 164 165
    tina_hton.state= SHOW_OPTION_YES;
    tina_hton.db_type= DB_TYPE_CSV_DB;
    tina_hton.create= tina_create_handler;
    tina_hton.panic= tina_end;
    tina_hton.flags= HTON_CAN_RECREATE;
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
  }
  return 0;
}

static int tina_done_func()
{
  if (tina_init)
  {
    if (tina_open_tables.records)
    {
      return 1;
    }
    hash_free(&tina_open_tables);
    pthread_mutex_destroy(&tina_mutex);
    tina_init--;
  }
  return 0;
}
184

185

186 187 188 189 190 191
/*
  Simple lock controls.
*/
static TINA_SHARE *get_share(const char *table_name, TABLE *table)
{
  TINA_SHARE *share;
192
  char meta_file_name[FN_REFLEN];
193
  MY_STAT file_stat;                /* Stat information for the data file */
194 195 196
  char *tmp_name;
  uint length;

197 198 199
  if (!tina_init)
     tina_init_func();

200 201
  pthread_mutex_lock(&tina_mutex);
  length=(uint) strlen(table_name);
202 203 204 205 206

  /*
    If share is not present in the hash, create a new share and
    initialize its members.
  */
207 208
  if (!(share=(TINA_SHARE*) hash_search(&tina_open_tables,
                                        (byte*) table_name,
209
                                       length)))
210 211
  {
    if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
212 213
                         &share, sizeof(*share),
                         &tmp_name, length+1,
214
                         NullS))
215 216 217 218 219
    {
      pthread_mutex_unlock(&tina_mutex);
      return NULL;
    }

220
    share->use_count= 0;
221
    share->is_log_table= FALSE;
222 223
    share->table_name_length= length;
    share->table_name= tmp_name;
224 225
    share->crashed= FALSE;
    share->rows_recorded= 0;
226 227
    share->update_file_opened= FALSE;
    share->tina_write_opened= FALSE;
228
    strmov(share->table_name, table_name);
229 230 231
    fn_format(share->data_file_name, table_name, "", CSV_EXT,
              MY_REPLACE_EXT|MY_UNPACK_FILENAME);
    fn_format(meta_file_name, table_name, "", CSM_EXT,
232
              MY_REPLACE_EXT|MY_UNPACK_FILENAME);
233 234 235 236 237

    if (my_stat(share->data_file_name, &file_stat, MYF(MY_WME)) == NULL)
      goto error;
    share->saved_data_file_length= file_stat.st_size;

238 239 240 241 242
    if (my_hash_insert(&tina_open_tables, (byte*) share))
      goto error;
    thr_lock_init(&share->lock);
    pthread_mutex_init(&share->mutex,MY_MUTEX_INIT_FAST);

243 244 245 246 247 248 249 250 251 252 253
    /*
      Open or create the meta file. In the latter case, we'll get
      an error during read_meta_file and mark the table as crashed.
      Usually this will result in auto-repair, and we will get a good
      meta-file in the end.
    */
    if ((share->meta_file= my_open(meta_file_name,
                                   O_RDWR|O_CREAT, MYF(0))) == -1)
      share->crashed= TRUE;

    /*
254
      If the meta file will not open we assume it is crashed and
255 256 257 258
      mark it as such.
    */
    if (read_meta_file(share->meta_file, &share->rows_recorded))
      share->crashed= TRUE;
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
  }
  share->use_count++;
  pthread_mutex_unlock(&tina_mutex);

  return share;

error2:
  thr_lock_delete(&share->lock);
  pthread_mutex_destroy(&share->mutex);
error:
  pthread_mutex_unlock(&tina_mutex);
  my_free((gptr) share, MYF(0));

  return NULL;
}


276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
/*
  Read CSV meta-file

  SYNOPSIS
    read_meta_file()
    meta_file   The meta-file filedes
    ha_rows     Pointer to the var we use to store rows count.
                These are read from the meta-file.

  DESCRIPTION

    Read the meta-file info. For now we are only interested in
    rows counf, crashed bit and magic number.

  RETURN
    0 - OK
292
    non-zero - error occurred
293 294
*/

295
static int read_meta_file(File meta_file, ha_rows *rows)
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
{
  uchar meta_buffer[META_BUFFER_SIZE];
  uchar *ptr= meta_buffer;

  DBUG_ENTER("ha_tina::read_meta_file");

  VOID(my_seek(meta_file, 0, MY_SEEK_SET, MYF(0)));
  if (my_read(meta_file, (byte*)meta_buffer, META_BUFFER_SIZE, 0)
      != META_BUFFER_SIZE)
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

  /*
    Parse out the meta data, we ignore version at the moment
  */

  ptr+= sizeof(uchar)*2; // Move past header
  *rows= (ha_rows)uint8korr(ptr);
  ptr+= sizeof(ulonglong); // Move past rows
  /*
    Move past check_point, auto_increment and forced_flushes fields.
    They are present in the format, but we do not use them yet.
  */
  ptr+= 3*sizeof(ulonglong);

  /* check crashed bit and magic number */
  if ((meta_buffer[0] != (uchar)TINA_CHECK_HEADER) ||
      ((bool)(*ptr)== TRUE))
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

  my_sync(meta_file, MYF(MY_WME));

  DBUG_RETURN(0);
}


/*
  Write CSV meta-file

  SYNOPSIS
    write_meta_file()
    meta_file   The meta-file filedes
    ha_rows     The number of rows we have in the datafile.
    dirty       A flag, which marks whether we have a corrupt table

  DESCRIPTION

    Write meta-info the the file. Only rows count, crashed bit and
    magic number matter now.

  RETURN
    0 - OK
347
    non-zero - error occurred
348 349
*/

350
static int write_meta_file(File meta_file, ha_rows rows, bool dirty)
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
{
  uchar meta_buffer[META_BUFFER_SIZE];
  uchar *ptr= meta_buffer;

  DBUG_ENTER("ha_tina::write_meta_file");

  *ptr= (uchar)TINA_CHECK_HEADER;
  ptr+= sizeof(uchar);
  *ptr= (uchar)TINA_VERSION;
  ptr+= sizeof(uchar);
  int8store(ptr, (ulonglong)rows);
  ptr+= sizeof(ulonglong);
  memset(ptr, 0, 3*sizeof(ulonglong));
  /*
     Skip over checkpoint, autoincrement and forced_flushes fields.
     We'll need them later.
  */
  ptr+= 3*sizeof(ulonglong);
  *ptr= (uchar)dirty;

  VOID(my_seek(meta_file, 0, MY_SEEK_SET, MYF(0)));
  if (my_write(meta_file, (byte *)meta_buffer, META_BUFFER_SIZE, 0)
      != META_BUFFER_SIZE)
    DBUG_RETURN(-1);

  my_sync(meta_file, MYF(MY_WME));

  DBUG_RETURN(0);
}

bool ha_tina::check_and_repair(THD *thd)
{
  HA_CHECK_OPT check_opt;
  DBUG_ENTER("ha_tina::check_and_repair");

  check_opt.init();

  DBUG_RETURN(repair(thd, &check_opt));
}


392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
int ha_tina::init_tina_writer()
{
  DBUG_ENTER("ha_tina::init_tina_writer");

  /*
    Mark the file as crashed. We will set the flag back when we close
    the file. In the case of the crash it will remain marked crashed,
    which enforce recovery.
  */
  (void)write_meta_file(share->meta_file, share->rows_recorded, TRUE);

  if ((share->tina_write_filedes=
        my_open(share->data_file_name, O_RDWR|O_APPEND, MYF(0))) == -1)
  {
    DBUG_PRINT("info", ("Could not open tina file writes"));
    share->crashed= TRUE;
    DBUG_RETURN(1);
  }
  share->tina_write_opened= TRUE;

  DBUG_RETURN(0);
}


416 417 418 419 420 421
bool ha_tina::is_crashed() const
{
  DBUG_ENTER("ha_tina::is_crashed");
  DBUG_RETURN(share->crashed);
}

422
/*
423 424 425 426 427 428 429 430
  Free lock controls.
*/
static int free_share(TINA_SHARE *share)
{
  DBUG_ENTER("ha_tina::free_share");
  pthread_mutex_lock(&tina_mutex);
  int result_code= 0;
  if (!--share->use_count){
431 432 433 434 435
    /* Write the meta file. Mark it as crashed if needed. */
    (void)write_meta_file(share->meta_file, share->rows_recorded,
                          share->crashed ? TRUE :FALSE);
    if (my_close(share->meta_file, MYF(0)))
      result_code= 1;
436 437 438 439 440 441 442
    if (share->tina_write_opened)
    {
      if (my_close(share->tina_write_filedes, MYF(0)))
        result_code= 1;
      share->tina_write_opened= FALSE;
    }

443 444 445 446 447 448 449 450 451 452
    hash_delete(&tina_open_tables, (byte*) share);
    thr_lock_delete(&share->lock);
    pthread_mutex_destroy(&share->mutex);
    my_free((gptr) share, MYF(0));
  }
  pthread_mutex_unlock(&tina_mutex);

  DBUG_RETURN(result_code);
}

453
int tina_end(ha_panic_function type)
454
{
455
  return tina_done_func();
456
}
457

458

459
/*
460 461 462 463 464 465 466
  This function finds the end of a line and returns the length
  of the line ending.

  We support three kinds of line endings:
  '\r'     --  Old Mac OS line ending
  '\n'     --  Traditional Unix and Mac OS X line ending
  '\r''\n' --  DOS\Windows line ending
467
*/
468

469 470
off_t find_eoln_buff(Transparent_file *data_buff, off_t begin,
                     off_t end, int *eoln_len)
471
{
reggie@big_geek's avatar
reggie@big_geek committed
472
  *eoln_len= 0;
473

474
  for (off_t x= begin; x < end; x++)
475 476
  {
    /* Unix (includes Mac OS X) */
477
    if (data_buff->get_value(x) == '\n')
478
      *eoln_len= 1;
reggie@big_geek's avatar
reggie@big_geek committed
479
    else
480
      if (data_buff->get_value(x) == '\r') // Mac or Dos
481
      {
482 483 484 485 486
        /* old Mac line ending */
        if (x + 1 == end || (data_buff->get_value(x + 1) != '\n'))
          *eoln_len= 1;
        else // DOS style ending
          *eoln_len= 2;
487
      }
488 489 490

    if (*eoln_len)  // end of line was found
      return x;
491
  }
492 493 494 495

  return 0;
}

496

497
static handler *tina_create_handler(TABLE_SHARE *table, MEM_ROOT *mem_root)
498
{
499
  return new (mem_root) ha_tina(table);
500 501 502
}


503
ha_tina::ha_tina(TABLE_SHARE *table_arg)
504 505
  :handler(&tina_hton, table_arg),
  /*
506 507
    These definitions are found in handler.h
    They are not probably completely right.
508
  */
509
  current_position(0), next_position(0), local_saved_data_file_length(0),
510
  file_buff(0), chain_alloced(0), chain_size(DEFAULT_CHAIN_LENGTH),
511
  records_is_known(0)
512 513
{
  /* Set our original buffers from pre-allocated memory */
514
  buffer.set((char*)byte_buffer, IO_SIZE, system_charset_info);
515
  chain= chain_buffer;
516
  file_buff= new Transparent_file();
517 518
}

519

520 521 522
/*
  Encode a buffer into the quoted format.
*/
523

524
int ha_tina::encode_quote(byte *buf)
525 526
{
  char attribute_buffer[1024];
527 528
  String attribute(attribute_buffer, sizeof(attribute_buffer),
                   &my_charset_bin);
529

monty@mysql.com's avatar
monty@mysql.com committed
530
  my_bitmap_map *org_bitmap= dbug_tmp_use_all_columns(table, table->read_set);
531 532 533 534 535 536
  buffer.length(0);
  for (Field **field=table->field ; *field ; field++)
  {
    const char *ptr;
    const char *end_ptr;

537 538 539 540 541 542 543 544 545 546 547 548 549 550
    /*
      Write an empty string to the buffer in case of a NULL value.
      Basically this is a safety check, as no one ensures that the
      field content is cleaned up every time we use Field::set_null()
      in the code.
    */
    if ((*field)->is_null())
      ptr= end_ptr= 0;
    else
    {
      (*field)->val_str(&attribute,&attribute);
      ptr= attribute.ptr();
      end_ptr= attribute.length() + ptr;
    }
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

    buffer.append('"');

    while (ptr < end_ptr) 
    {
      if (*ptr == '"')
      {
        buffer.append('\\');
        buffer.append('"');
        *ptr++;
      }
      else if (*ptr == '\r')
      {
        buffer.append('\\');
        buffer.append('r');
        *ptr++;
      }
      else if (*ptr == '\\')
      {
        buffer.append('\\');
        buffer.append('\\');
        *ptr++;
      }
      else if (*ptr == '\n')
      {
        buffer.append('\\');
        buffer.append('n');
        *ptr++;
      }
      else
        buffer.append(*ptr++);
    }
    buffer.append('"');
    buffer.append(',');
  }
  // Remove the comma, add a line feed
  buffer.length(buffer.length() - 1);
  buffer.append('\n');
  //buffer.replace(buffer.length(), 0, "\n", 1);

monty@mysql.com's avatar
monty@mysql.com committed
591
  dbug_tmp_restore_column_map(table->read_set, org_bitmap);
592 593 594 595
  return (buffer.length());
}

/*
596
  chain_append() adds delete positions to the chain that we use to keep
597
  track of space. Then the chain will be used to cleanup "holes", occurred
598
  due to deletes and updates.
599 600 601 602 603
*/
int ha_tina::chain_append()
{
  if ( chain_ptr != chain && (chain_ptr -1)->end == current_position)
    (chain_ptr -1)->end= next_position;
604
  else
605 606 607 608 609 610 611 612 613
  {
    /* We set up for the next position */
    if ((off_t)(chain_ptr - chain) == (chain_size -1))
    {
      off_t location= chain_ptr - chain;
      chain_size += DEFAULT_CHAIN_LENGTH;
      if (chain_alloced)
      {
        /* Must cast since my_malloc unlike malloc doesn't have a void ptr */
614 615
        if ((chain= (tina_set *) my_realloc((gptr)chain,
                                            chain_size, MYF(MY_WME))) == NULL)
616 617 618 619
          return -1;
      }
      else
      {
620 621
        tina_set *ptr= (tina_set *) my_malloc(chain_size * sizeof(tina_set),
                                              MYF(MY_WME));
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
        memcpy(ptr, chain, DEFAULT_CHAIN_LENGTH * sizeof(tina_set));
        chain= ptr;
        chain_alloced++;
      }
      chain_ptr= chain + location;
    }
    chain_ptr->begin= current_position;
    chain_ptr->end= next_position;
    chain_ptr++;
  }

  return 0;
}


637
/*
638 639 640 641
  Scans for a row.
*/
int ha_tina::find_current_row(byte *buf)
{
642
  off_t end_offset, curr_offset= current_position;
reggie@big_geek's avatar
reggie@big_geek committed
643
  int eoln_len;
644
  my_bitmap_map *org_bitmap;
645 646
  DBUG_ENTER("ha_tina::find_current_row");

647 648 649 650
  /*
    We do not read further then local_saved_data_file_length in order
    not to conflict with undergoing concurrent insert.
  */
651 652 653
  if ((end_offset=
        find_eoln_buff(file_buff, current_position,
                       local_saved_data_file_length, &eoln_len)) == 0)
654 655
    DBUG_RETURN(HA_ERR_END_OF_FILE);

656 657 658
  /* Avoid asserts in ::store() for columns that are not going to be updated */
  org_bitmap= dbug_tmp_use_all_columns(table, table->write_set);

659 660 661
  for (Field **field=table->field ; *field ; field++)
  {
    buffer.length(0);
662 663
    if (file_buff->get_value(curr_offset) == '"')
      curr_offset++; // Incrementpast the first quote
664
    else
monty@mysql.com's avatar
monty@mysql.com committed
665 666
    {
      dbug_tmp_restore_column_map(table->write_set, org_bitmap);
667
      DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
monty@mysql.com's avatar
monty@mysql.com committed
668
    }
669
    for(;curr_offset != end_offset; curr_offset++)
670
    {
671
      // Need to convert line feeds!
672 673 674 675
      if (file_buff->get_value(curr_offset) == '"' &&
          (((file_buff->get_value(curr_offset + 1) == ',') &&
            (file_buff->get_value(curr_offset + 2) == '"')) ||
           (curr_offset == end_offset -1 )))
676
      {
677
        curr_offset+= 2; // Move past the , and the "
678
        break;
679
      }
680 681
      if (file_buff->get_value(curr_offset) == '\\' &&
          curr_offset != (end_offset - 1))
682
      {
683 684
        curr_offset++;
        if (file_buff->get_value(curr_offset) == 'r')
685
          buffer.append('\r');
686
        else if (file_buff->get_value(curr_offset) == 'n' )
687
          buffer.append('\n');
688 689 690
        else if ((file_buff->get_value(curr_offset) == '\\') ||
                 (file_buff->get_value(curr_offset) == '"'))
          buffer.append(file_buff->get_value(curr_offset));
691 692 693
        else  /* This could only happed with an externally created file */
        {
          buffer.append('\\');
694
          buffer.append(file_buff->get_value(curr_offset));
695
        }
696
      }
697 698 699 700 701 702
      else // ordinary symbol
      {
        /*
          We are at final symbol and no last quote was found =>
          we are working with a damaged file.
        */
703
        if (curr_offset == end_offset - 1)
monty@mysql.com's avatar
monty@mysql.com committed
704 705
        {
          dbug_tmp_restore_column_map(table->write_set, org_bitmap);
706
          DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
monty@mysql.com's avatar
monty@mysql.com committed
707
        }
708
        buffer.append(file_buff->get_value(curr_offset));
709
      }
710
    }
711 712
    if (bitmap_is_set(table->read_set, (*field)->field_index))
      (*field)->store(buffer.ptr(), buffer.length(), system_charset_info);
713
  }
714
  next_position= end_offset + eoln_len;
715
  /* Maybe use \N for null? */
716
  memset(buf, 0, table->s->null_bytes); /* We do not implement nulls! */
monty@mysql.com's avatar
monty@mysql.com committed
717
  dbug_tmp_restore_column_map(table->write_set, org_bitmap);
718 719 720 721 722 723 724 725

  DBUG_RETURN(0);
}

/*
  If frm_error() is called in table.cc this is called to find out what file
  extensions exist for this handler.
*/
726
static const char *ha_tina_exts[] = {
727 728
  CSV_EXT,
  CSM_EXT,
729 730 731
  NullS
};

732
const char **ha_tina::bas_ext() const
733 734 735
{
  return ha_tina_exts;
}
736

737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
/*
  Three functions below are needed to enable concurrent insert functionality
  for CSV engine. For more details see mysys/thr_lock.c
*/

void tina_get_status(void* param, int concurrent_insert)
{
  ha_tina *tina= (ha_tina*) param;
  tina->get_status();
}

void tina_update_status(void* param)
{
  ha_tina *tina= (ha_tina*) param;
  tina->update_status();
}

/* this should exist and return 0 for concurrent insert to work */
my_bool tina_check_status(void* param)
{
  return 0;
}

/*
  Save the state of the table

  SYNOPSIS
    get_status()

  DESCRIPTION
    This function is used to retrieve the file length. During the lock
    phase of concurrent insert. For more details see comment to
    ha_tina::update_status below.
*/

void ha_tina::get_status()
{
  if (share->is_log_table)
  {
    /*
      We have to use mutex to follow pthreads memory visibility
      rules for share->saved_data_file_length
    */
    pthread_mutex_lock(&share->mutex);
    local_saved_data_file_length= share->saved_data_file_length;
    pthread_mutex_unlock(&share->mutex);
    return;
  }
  local_saved_data_file_length= share->saved_data_file_length;
}


/*
  Correct the state of the table. Called by unlock routines
  before the write lock is released.

  SYNOPSIS
    update_status()

  DESCRIPTION
    When we employ concurrent insert lock, we save current length of the file
    during the lock phase. We do not read further saved value, as we don't
    want to interfere with undergoing concurrent insert. Writers update file
    length info during unlock with update_status().

  NOTE
    For log tables concurrent insert works different. The reason is that
    log tables are always opened and locked. And as they do not unlock
    tables, the file length after writes should be updated in a different
    way. For this purpose we need is_log_table flag. When this flag is set
    we call update_status() explicitly after each row write.
*/

void ha_tina::update_status()
{
  /* correct local_saved_data_file_length for writers */
813
  share->saved_data_file_length= local_saved_data_file_length;
814 815 816
}


817 818 819
bool ha_tina::check_if_locking_is_allowed(uint sql_command,
                                          ulong type, TABLE *table,
                                          uint count,
820
                                          bool called_by_privileged_thread)
821
{
822
  if (!called_by_privileged_thread)
823 824
    return check_if_log_table_locking_is_allowed(sql_command, type, table);

825 826
  return TRUE;
}
827

828
/*
829 830 831 832
  Open a database file. Keep in mind that tables are caches, so
  this will not be called for every request. Any sort of positions
  that need to be reset should be kept in the ::extra() call.
*/
833
int ha_tina::open(const char *name, int mode, uint open_options)
834 835 836 837
{
  DBUG_ENTER("ha_tina::open");

  if (!(share= get_share(name, table)))
838
    DBUG_RETURN(HA_ERR_OUT_OF_MEM);
839

840
  if (share->crashed && !(open_options & HA_OPEN_FOR_REPAIR))
841 842
  {
    free_share(share);
843
    DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);
844
  }
845

846 847 848
  if ((data_file= my_open(share->data_file_name, O_RDONLY, MYF(0))) == -1)
    DBUG_RETURN(0);

849 850 851 852 853 854
  /*
    Init locking. Pass handler object to the locking routines,
    so that they could save/update local_saved_data_file_length value
    during locking. This is needed to enable concurrent inserts.
  */
  thr_lock_data_init(&share->lock, &lock, (void*) this);
855 856
  ref_length=sizeof(off_t);

857 858 859 860
  share->lock.get_status= tina_get_status;
  share->lock.update_status= tina_update_status;
  share->lock.check_status= tina_check_status;

861 862 863 864 865 866
  DBUG_RETURN(0);
}


/*
  Close a database file. We remove ourselves from the shared strucutre.
867
  If it is empty we destroy it.
868 869 870
*/
int ha_tina::close(void)
{
871
  int rc= 0;
872
  DBUG_ENTER("ha_tina::close");
873 874
  rc= my_close(data_file, MYF(0));
  DBUG_RETURN(free_share(share) || rc);
875 876
}

877
/*
878 879 880 881 882 883 884 885 886
  This is an INSERT. At the moment this handler just seeks to the end
  of the file and appends the data. In an error case it really should
  just truncate to the original position (this is not done yet).
*/
int ha_tina::write_row(byte * buf)
{
  int size;
  DBUG_ENTER("ha_tina::write_row");

887 888 889
  if (share->crashed)
      DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

890
  ha_statistic_increment(&SSV::ha_write_count);
891

892 893
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT)
    table->timestamp_field->set_time();
894 895 896

  size= encode_quote(buf);

897 898 899
  if (!share->tina_write_opened)
    if (init_tina_writer())
      DBUG_RETURN(-1);
900

901
   /* use pwrite, as concurrent reader could have changed the position */
petr@mysql.com's avatar
petr@mysql.com committed
902
  if (my_write(share->tina_write_filedes, (byte*)buffer.ptr(), size,
903
               MYF(MY_WME | MY_NABP)))
904
    DBUG_RETURN(-1);
905 906

  /* update local copy of the max position to see our own changes */
907
  local_saved_data_file_length+= size;
908

909 910 911
  /* update shared info */
  pthread_mutex_lock(&share->mutex);
  share->rows_recorded++;
912 913 914
  /* update status for the log tables */
  if (share->is_log_table)
    update_status();
915
  pthread_mutex_unlock(&share->mutex);
916

917
  stats.records++;
918 919 920 921
  DBUG_RETURN(0);
}


922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
int ha_tina::open_update_temp_file_if_needed()
{
  char updated_fname[FN_REFLEN];

  if (!share->update_file_opened)
  {
    if ((update_temp_file=
           my_create(fn_format(updated_fname, share->table_name,
                               "", CSN_EXT,
                               MY_REPLACE_EXT | MY_UNPACK_FILENAME),
                     0, O_RDWR | O_TRUNC, MYF(MY_WME))) < 0)
      return 1;
    share->update_file_opened= TRUE;
  }
  return 0;
}

939
/*
940
  This is called for an update.
941
  Make sure you put in code to increment the auto increment, also
942 943 944 945 946 947 948 949 950 951
  update any timestamp data. Currently auto increment is not being
  fixed since autoincrements have yet to be added to this table handler.
  This will be called in a table scan right before the previous ::rnd_next()
  call.
*/
int ha_tina::update_row(const byte * old_data, byte * new_data)
{
  int size;
  DBUG_ENTER("ha_tina::update_row");

952
  ha_statistic_increment(&SSV::ha_read_rnd_next_count);
953

954 955
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_UPDATE)
    table->timestamp_field->set_time();
956 957 958 959 960 961

  size= encode_quote(new_data);

  if (chain_append())
    DBUG_RETURN(-1);

962 963 964 965
  if (open_update_temp_file_if_needed())
    DBUG_RETURN(-1);

  if (my_write(update_temp_file, (byte*)buffer.ptr(), size,
966
               MYF(MY_WME | MY_NABP)))
967
    DBUG_RETURN(-1);
968 969 970 971

  /* UPDATE should never happen on the log tables */
  DBUG_ASSERT(!share->is_log_table);

972 973 974 975
  DBUG_RETURN(0);
}


976 977 978 979 980 981 982 983
/*
  Deletes a row. First the database will find the row, and then call this
  method. In the case of a table scan, the previous call to this will be
  the ::rnd_next() that found this row.
  The exception to this is an ORDER BY. This will cause the table handler
  to walk the table noting the positions of all rows that match a query.
  The table will then be deleted/positioned based on the ORDER (so RANDOM,
  DESC, ASC).
984 985 986 987
*/
int ha_tina::delete_row(const byte * buf)
{
  DBUG_ENTER("ha_tina::delete_row");
988
  ha_statistic_increment(&SSV::ha_delete_count);
989 990 991 992

  if (chain_append())
    DBUG_RETURN(-1);

993
  stats.records--;
994

995 996 997
  /* DELETE should never happen on the log table */
  DBUG_ASSERT(!share->is_log_table);

998 999 1000 1001
  DBUG_RETURN(0);
}


1002 1003
/*
  All table scans call this first.
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
  The order of a table scan is:

  ha_tina::store_lock
  ha_tina::external_lock
  ha_tina::info
  ha_tina::rnd_init
  ha_tina::extra
  ENUM HA_EXTRA_CACHE   Cash record in HA_rrnd()
  ha_tina::rnd_next
  ha_tina::rnd_next
  ha_tina::rnd_next
  ha_tina::rnd_next
  ha_tina::rnd_next
  ha_tina::rnd_next
  ha_tina::rnd_next
  ha_tina::rnd_next
  ha_tina::rnd_next
  ha_tina::extra
  ENUM HA_EXTRA_NO_CACHE   End cacheing of records (def)
  ha_tina::external_lock
  ha_tina::extra
  ENUM HA_EXTRA_RESET   Reset database to after open

1027 1028
  Each call to ::rnd_next() represents a row returned in the can. When no more
  rows can be returned, rnd_next() returns a value of HA_ERR_END_OF_FILE.
1029 1030 1031 1032 1033 1034 1035 1036
  The ::info() call is just for the optimizer.

*/

int ha_tina::rnd_init(bool scan)
{
  DBUG_ENTER("ha_tina::rnd_init");

1037 1038
  /* set buffer to the beginning of the file */
  file_buff->init_buff(data_file);
1039 1040 1041
  if (share->crashed)
      DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

1042
  current_position= next_position= 0;
1043
  stats.records= 0;
1044
  records_is_known= 0;
1045 1046 1047 1048 1049 1050
  chain_ptr= chain;

  DBUG_RETURN(0);
}

/*
1051 1052 1053 1054
  ::rnd_next() does all the heavy lifting for a table scan. You will need to
  populate *buf with the correct field data. You can walk the field to
  determine at what position you should store the data (take a look at how
  ::find_current_row() works). The structure is something like:
1055
  0Foo  Dog  Friend
1056 1057 1058 1059 1060 1061 1062
  The first offset is for the first attribute. All space before that is
  reserved for null count.
  Basically this works as a mask for which rows are nulled (compared to just
  empty).
  This table handler doesn't do nulls and does not know the difference between
  NULL and "". This is ok since this table handler is for spreadsheets and
  they don't know about them either :)
1063 1064 1065
*/
int ha_tina::rnd_next(byte *buf)
{
1066
  int rc;
1067 1068
  DBUG_ENTER("ha_tina::rnd_next");

1069 1070 1071
  if (share->crashed)
      DBUG_RETURN(HA_ERR_CRASHED_ON_USAGE);

1072
  ha_statistic_increment(&SSV::ha_read_rnd_next_count);
1073 1074

  current_position= next_position;
1075 1076 1077

  /* don't scan an empty file */
  if (!local_saved_data_file_length)
1078
    DBUG_RETURN(HA_ERR_END_OF_FILE);
1079

1080 1081
  if ((rc= find_current_row(buf)))
    DBUG_RETURN(rc);
1082

1083
  stats.records++;
1084 1085 1086 1087 1088
  DBUG_RETURN(0);
}

/*
  In the case of an order by rows will need to be sorted.
1089
  ::position() is called after each call to ::rnd_next(),
1090
  the data it stores is to a byte array. You can store this
1091 1092 1093
  data via my_store_ptr(). ref_length is a variable defined to the
  class that is the sizeof() of position being stored. In our case
  its just a position. Look at the bdb code if you want to see a case
1094 1095 1096 1097 1098
  where something other then a number is stored.
*/
void ha_tina::position(const byte *record)
{
  DBUG_ENTER("ha_tina::position");
serg@serg.mylan's avatar
serg@serg.mylan committed
1099
  my_store_ptr(ref, ref_length, current_position);
1100 1101 1102 1103
  DBUG_VOID_RETURN;
}


1104 1105
/*
  Used to fetch a row from a posiion stored with ::position().
serg@serg.mylan's avatar
serg@serg.mylan committed
1106
  my_get_ptr() retrieves the data for you.
1107 1108 1109 1110 1111
*/

int ha_tina::rnd_pos(byte * buf, byte *pos)
{
  DBUG_ENTER("ha_tina::rnd_pos");
1112
  ha_statistic_increment(&SSV::ha_read_rnd_next_count);
1113
  current_position= (off_t)my_get_ptr(pos,ref_length);
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
  DBUG_RETURN(find_current_row(buf));
}

/*
  ::info() is used to return information to the optimizer.
  Currently this table handler doesn't implement most of the fields
  really needed. SHOW also makes use of this data
*/
void ha_tina::info(uint flag)
{
  DBUG_ENTER("ha_tina::info");
  /* This is a lie, but you don't want the optimizer to see zero or 1 */
1126 1127
  if (!records_is_known && stats.records < 2) 
    stats.records= 2;
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
  DBUG_VOID_RETURN;
}

/*
  Grab bag of flags that are sent to the able handler every so often.
  HA_EXTRA_RESET and HA_EXTRA_RESET_STATE are the most frequently called.
  You are not required to implement any of these.
*/
int ha_tina::extra(enum ha_extra_function operation)
{
  DBUG_ENTER("ha_tina::extra");
1139 1140 1141 1142 1143 1144
 if (operation == HA_EXTRA_MARK_AS_LOG_TABLE)
 {
   pthread_mutex_lock(&share->mutex);
   share->is_log_table= TRUE;
   pthread_mutex_unlock(&share->mutex);
 }
1145 1146 1147
  DBUG_RETURN(0);
}

1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
/*
  Set end_pos to the last valid byte of continuous area, closest
  to the given "hole", stored in the buffer. "Valid" here means,
  not listed in the chain of deleted records ("holes").
*/
bool ha_tina::get_write_pos(off_t *end_pos, tina_set *closest_hole)
{
  if (closest_hole == chain_ptr) /* no more chains */
    *end_pos= file_buff->end();
  else
    *end_pos= min(file_buff->end(),
                  closest_hole->begin);
  return (closest_hole != chain_ptr) && (*end_pos == closest_hole->begin);
}


1164
/*
1165 1166 1167 1168
  Called after each table scan. In particular after deletes,
  and updates. In the last case we employ chain of deleted
  slots to clean up all of the dead space we have collected while
  performing deletes/updates.
1169 1170 1171
*/
int ha_tina::rnd_end()
{
1172 1173
  char updated_fname[FN_REFLEN];
  off_t file_buffer_start= 0;
1174 1175
  DBUG_ENTER("ha_tina::rnd_end");

1176 1177
  records_is_known= 1;

1178 1179
  if ((chain_ptr - chain)  > 0)
  {
1180
    tina_set *ptr= chain;
1181

1182
    /*
1183 1184
      Re-read the beginning of a file (as the buffer should point to the
      end of file after the scan).
1185
    */
1186
    file_buff->init_buff(data_file);
1187 1188

    /*
1189 1190
      The sort is needed when there were updates/deletes with random orders.
      It sorts so that we move the firts blocks to the beginning.
1191
    */
1192 1193
    qsort(chain, (size_t)(chain_ptr - chain), sizeof(tina_set),
          (qsort_cmp)sort_set);
1194 1195 1196 1197 1198 1199 1200 1201 1202

    off_t write_begin= 0, write_end;

    /* create the file to write updated table if it wasn't yet created */
    if (open_update_temp_file_if_needed())
      DBUG_RETURN(-1);

    /* write the file with updated info */
    while ((file_buffer_start != -1))     // while not end of file
1203
    {
1204 1205 1206 1207 1208
      bool in_hole= get_write_pos(&write_end, ptr);

      /* if there is something to write, write it */
      if ((write_end - write_begin) &&
          (my_write(update_temp_file,
petr@mysql.com's avatar
petr@mysql.com committed
1209 1210
                    (byte*)(file_buff->ptr() +
                            (write_begin - file_buff->start())),
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
                    write_end - write_begin, MYF_RW)))
        goto error;

      if (in_hole)
      {
        /* skip hole */
        while (file_buff->end() <= ptr->end && file_buffer_start != -1)
          file_buffer_start= file_buff->read_next();
        write_begin= ptr->end;
        ptr++;
      }
      else
        write_begin= write_end;

      if (write_end == file_buff->end())
        file_buffer_start= file_buff->read_next(); /* shift the buffer */

1228 1229
    }

petr@mysql.com's avatar
petr@mysql.com committed
1230 1231
    if (my_sync(update_temp_file, MYF(MY_WME)) ||
        my_close(update_temp_file, MYF(0)))
1232 1233
      DBUG_RETURN(-1);

1234
    share->update_file_opened= FALSE;
1235

1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
    if (share->tina_write_opened)
    {
      if (my_close(share->tina_write_filedes, MYF(0)))
        DBUG_RETURN(-1);
      /*
        Mark that the writer fd is closed, so that init_tina_writer()
        will reopen it later.
      */
      share->tina_write_opened= FALSE;
    }

    /*
      Close opened fildes's. Then move updated file in place
      of the old datafile.
    */
    if (my_close(data_file, MYF(0)) ||
        my_rename(fn_format(updated_fname, share->table_name, "", CSN_EXT,
                            MY_REPLACE_EXT | MY_UNPACK_FILENAME),
                  share->data_file_name, MYF(0)))
1255 1256
      DBUG_RETURN(-1);

petr@mysql.com's avatar
petr@mysql.com committed
1257 1258
    /* Open the file again */
    if (((data_file= my_open(share->data_file_name, O_RDONLY, MYF(0))) == -1))
1259
      DBUG_RETURN(-1);
1260 1261 1262 1263 1264 1265
    /*
      The datafile is consistent at this point and the write filedes is
      closed, so nothing worrying will happen to it in case of a crash.
      Here we record this fact to the meta-file.
    */
    (void)write_meta_file(share->meta_file, share->rows_recorded, FALSE);
1266 1267 1268
  }

  DBUG_RETURN(0);
1269 1270 1271 1272
error:
  my_close(update_temp_file, MYF(0));
  share->update_file_opened= FALSE;
  DBUG_RETURN(-1);
1273 1274
}

1275

1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
/*
  Repair CSV table in the case, it is crashed.

  SYNOPSIS
    repair()
    thd         The thread, performing repair
    check_opt   The options for repair. We do not use it currently.

  DESCRIPTION
    If the file is empty, change # of rows in the file and complete recovery.
    Otherwise, scan the table looking for bad rows. If none were found,
    we mark file as a good one and return. If a bad row was encountered,
    we truncate the datafile up to the last good row.

   TODO: Make repair more clever - it should try to recover subsequent
         rows (after the first bad one) as well.
*/

1294 1295 1296 1297 1298 1299 1300
int ha_tina::repair(THD* thd, HA_CHECK_OPT* check_opt)
{
  char repaired_fname[FN_REFLEN];
  byte *buf;
  File repair_file;
  int rc;
  ha_rows rows_repaired= 0;
1301
  off_t write_begin= 0, write_end;
1302 1303 1304
  DBUG_ENTER("ha_tina::repair");

  /* empty file */
1305
  if (!share->saved_data_file_length)
1306 1307 1308 1309 1310
  {
    share->rows_recorded= 0;
    goto end;
  }

1311 1312
  /* Don't assert in field::val() functions */
  table->use_all_columns();
1313 1314 1315
  if (!(buf= (byte*) my_malloc(table->s->reclength, MYF(MY_WME))))
    DBUG_RETURN(HA_ERR_OUT_OF_MEM);

1316 1317 1318
  /* position buffer to the start of the file */
  file_buff->init_buff(data_file);

1319 1320 1321 1322 1323
  /*
    Local_saved_data_file_length is initialized during the lock phase.
    Sometimes this is not getting executed before ::repair (e.g. for
    the log tables). We set it manually here.
  */
1324
  local_saved_data_file_length= share->saved_data_file_length;
1325 1326 1327
  /* set current position to the beginning of the file */
  current_position= next_position= 0;

1328 1329 1330 1331 1332 1333 1334 1335 1336
  /* Read the file row-by-row. If everything is ok, repair is not needed. */
  while (!(rc= find_current_row(buf)))
  {
    rows_repaired++;
    current_position= next_position;
  }

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

1337 1338 1339
  if (rc == HA_ERR_END_OF_FILE)
  {
    /*
1340 1341 1342
      All rows were read ok until end of file, the file does not need repair.
      If rows_recorded != rows_repaired, we should update rows_recorded value
      to the current amount of rows.
1343 1344
    */
    share->rows_recorded= rows_repaired;
1345
    goto end;
1346
  }
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357

  /*
    Otherwise we've encountered a bad row => repair is needed.
    Let us create a temporary file.
  */
  if ((repair_file= my_create(fn_format(repaired_fname, share->table_name,
                                        "", CSN_EXT,
                                        MY_REPLACE_EXT|MY_UNPACK_FILENAME),
                           0, O_RDWR | O_TRUNC,MYF(MY_WME))) < 0)
    DBUG_RETURN(HA_ERR_CRASHED_ON_REPAIR);

1358 1359 1360
  file_buff->init_buff(data_file);


1361
  /* we just truncated the file up to the first bad row. update rows count. */
1362 1363
  share->rows_recorded= rows_repaired;

1364 1365 1366 1367 1368
  /* write repaired file */
  while (1)
  {
    write_end= min(file_buff->end(), current_position);
    if ((write_end - write_begin) &&
petr@mysql.com's avatar
petr@mysql.com committed
1369
        (my_write(repair_file, (byte*)file_buff->ptr(),
1370 1371 1372 1373 1374 1375 1376 1377 1378
                  write_end - write_begin, MYF_RW)))
      DBUG_RETURN(-1);

    write_begin= write_end;
    if (write_end== current_position)
      break;
    else
      file_buff->read_next(); /* shift the buffer */
  }
1379 1380

  /*
1381 1382 1383 1384
    Close the files and rename repaired file to the datafile.
    We have to close the files, as on Windows one cannot rename
    a file, which descriptor is still open. EACCES will be returned
    when trying to delete the "to"-file in my_rename().
1385
  */
1386 1387
  if (my_close(data_file,MYF(0)) || my_close(repair_file, MYF(0)) ||
      my_rename(repaired_fname, share->data_file_name, MYF(0)))
1388 1389 1390
    DBUG_RETURN(-1);

  /* Open the file again, it should now be repaired */
1391 1392
  if ((data_file= my_open(share->data_file_name, O_RDWR|O_APPEND,
                          MYF(0))) == -1)
1393 1394
     DBUG_RETURN(-1);

1395 1396
  /* Set new file size. The file size will be updated by ::update_status() */
  local_saved_data_file_length= (size_t) current_position;
1397 1398 1399 1400 1401 1402 1403

end:
  share->crashed= FALSE;
  DBUG_RETURN(HA_ADMIN_OK);
}

/*
1404
  DELETE without WHERE calls this
1405
*/
1406

1407 1408
int ha_tina::delete_all_rows()
{
monty@mysql.com's avatar
monty@mysql.com committed
1409
  int rc;
1410 1411
  DBUG_ENTER("ha_tina::delete_all_rows");

1412
  if (!records_is_known)
monty@mysql.com's avatar
monty@mysql.com committed
1413
    DBUG_RETURN(my_errno=HA_ERR_WRONG_COMMAND);
1414

1415 1416 1417
  if (!share->tina_write_opened)
    if (init_tina_writer())
      DBUG_RETURN(-1);
1418 1419

  /* Truncate the file to zero size */
1420
  rc= my_chsize(share->tina_write_filedes, 0, 0, MYF(MY_WME));
1421

1422
  stats.records=0;
1423 1424 1425
  DBUG_RETURN(rc);
}

1426
/*
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
  Called by the database to lock the table. Keep in mind that this
  is an internal lock.
*/
THR_LOCK_DATA **ha_tina::store_lock(THD *thd,
                                    THR_LOCK_DATA **to,
                                    enum thr_lock_type lock_type)
{
  if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK)
    lock.type=lock_type;
  *to++= &lock;
  return to;
}

/* 
  Create a table. You do not want to leave the table open after a call to
  this (the database will call ::open() if it needs to).
*/

1445 1446
int ha_tina::create(const char *name, TABLE *table_arg,
                    HA_CREATE_INFO *create_info)
1447 1448 1449 1450 1451
{
  char name_buff[FN_REFLEN];
  File create_file;
  DBUG_ENTER("ha_tina::create");

1452 1453 1454 1455 1456 1457 1458 1459 1460
  if ((create_file= my_create(fn_format(name_buff, name, "", CSM_EXT,
                                        MY_REPLACE_EXT|MY_UNPACK_FILENAME), 0,
                              O_RDWR | O_TRUNC,MYF(MY_WME))) < 0)
    DBUG_RETURN(-1);

  write_meta_file(create_file, 0, FALSE);
  my_close(create_file, MYF(0));

  if ((create_file= my_create(fn_format(name_buff, name, "", CSV_EXT,
1461
                                        MY_REPLACE_EXT|MY_UNPACK_FILENAME),0,
1462
                              O_RDWR | O_TRUNC,MYF(MY_WME))) < 0)
1463 1464
    DBUG_RETURN(-1);

1465
  my_close(create_file, MYF(0));
1466 1467 1468

  DBUG_RETURN(0);
}
1469

1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
int ha_tina::check(THD* thd, HA_CHECK_OPT* check_opt)
{
  int rc= 0;
  byte *buf;
  const char *old_proc_info;
  ha_rows count= share->rows_recorded;
  DBUG_ENTER("ha_tina::check");

  old_proc_info= thd_proc_info(thd, "Checking table");
  if (!(buf= (byte*) my_malloc(table->s->reclength, MYF(MY_WME))))
    DBUG_RETURN(HA_ERR_OUT_OF_MEM);

1482 1483 1484
  /* position buffer to the start of the file */
  file_buff->init_buff(data_file);

1485 1486 1487 1488 1489
  /*
    Local_saved_data_file_length is initialized during the lock phase.
    Check does not use store_lock in certain cases. So, we set it
    manually here.
  */
1490
  local_saved_data_file_length= share->saved_data_file_length;
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
  /* set current position to the beginning of the file */
  current_position= next_position= 0;
  /* Read the file row-by-row. If everything is ok, repair is not needed. */
  while (!(rc= find_current_row(buf)))
  {
    count--;
    current_position= next_position;
  }

  my_free((char*)buf, MYF(0));
  thd_proc_info(thd, old_proc_info);

  if ((rc != HA_ERR_END_OF_FILE) || count)
  {
1505
    share->crashed= TRUE;
1506 1507 1508 1509 1510 1511 1512
    DBUG_RETURN(HA_ADMIN_CORRUPT);
  }
  else
    DBUG_RETURN(HA_ADMIN_OK);
}


1513 1514 1515 1516 1517 1518
bool ha_tina::check_if_incompatible_data(HA_CREATE_INFO *info,
					   uint table_changes)
{
  return COMPATIBLE_DATA_YES;
}

1519 1520
struct st_mysql_storage_engine csv_storage_engine=
{ MYSQL_HANDLERTON_INTERFACE_VERSION, &tina_hton };
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
1521 1522

mysql_declare_plugin(csv)
1523 1524
{
  MYSQL_STORAGE_ENGINE_PLUGIN,
1525 1526
  &csv_storage_engine,
  "CSV",
1527
  "Brian Aker, MySQL AB",
1528
  "CSV storage engine",
1529
  tina_init_func, /* Plugin Init */
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
1530 1531
  tina_done_func, /* Plugin Deinit */
  0x0100 /* 1.0 */,
1532
  0
1533 1534
}
mysql_declare_plugin_end;
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
1535