ha_tina.cc 28.2 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
*/

unknown's avatar
unknown committed
45
#ifdef USE_PRAGMA_IMPLEMENTATION
46 47 48 49
#pragma implementation        // gcc: Class implementation
#endif

#include "mysql_priv.h"
unknown's avatar
unknown committed
50

51 52
#include "ha_tina.h"

53
#include <mysql/plugin.h>
unknown's avatar
unknown committed
54

55 56 57 58
/* Stuff for shares */
pthread_mutex_t tina_mutex;
static HASH tina_open_tables;
static int tina_init= 0;
unknown's avatar
unknown committed
59
static handler *tina_create_handler(TABLE_SHARE *table);
unknown's avatar
unknown committed
60
static int tina_init_func();
61

62
handlerton tina_hton= {
unknown's avatar
unknown committed
63
  MYSQL_HANDLERTON_INTERFACE_VERSION,
64
  "CSV",
65 66 67
  SHOW_OPTION_YES,
  "CSV storage engine", 
  DB_TYPE_CSV_DB,
unknown's avatar
unknown committed
68
  (bool (*)()) tina_init_func,
69 70
  0,       /* slot */
  0,       /* savepoint size. */
71 72 73 74 75 76 77 78 79 80 81 82 83
  NULL,    /* close_connection */
  NULL,    /* savepoint */
  NULL,    /* rollback to savepoint */
  NULL,    /* release savepoint */
  NULL,    /* commit */
  NULL,    /* rollback */
  NULL,    /* prepare */
  NULL,    /* recover */
  NULL,    /* commit_by_xid */
  NULL,    /* rollback_by_xid */
  NULL,    /* create_cursor_read_view */
  NULL,    /* set_cursor_read_view */
  NULL,    /* close_cursor_read_view */
84 85 86 87 88 89
  tina_create_handler,    /* Create a new handler */
  NULL,    /* Drop a database */
  tina_end,    /* Panic call */
  NULL,    /* Start Consistent Snapshot */
  NULL,    /* Flush logs */
  NULL,    /* Show status */
unknown's avatar
unknown committed
90 91
  NULL,    /* Partition flags */
  NULL,    /* Alter table flags */
unknown's avatar
unknown committed
92
  NULL,    /* Alter Tablespace */
93
  NULL,    /* Fill FILES Table */
94 95 96
  HTON_CAN_RECREATE,
  NULL, /* binlog_func */
  NULL /* binlog_log_query */
97 98
};

99 100 101 102
/*****************************************************************************
 ** TINA tables
 *****************************************************************************/

103
/*
104
  Used for sorting chains with qsort().
105 106 107
*/
int sort_set (tina_set *a, tina_set *b)
{
108 109 110 111 112
  /*
    We assume that intervals do not intersect. So, it is enought to compare
    any two points. Here we take start of intervals for comparison.
  */
  return ( a->begin > b->begin ? -1 : ( a->begin < b->begin ? 1 : 0 ) );
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
}

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

/*
  Reloads the mmap file.
*/
int get_mmap(TINA_SHARE *share, int write)
{
  DBUG_ENTER("ha_tina::get_mmap");
128 129
  if (share->mapped_file && my_munmap(share->mapped_file,
                                      share->file_stat.st_size))
130 131 132 133 134
    DBUG_RETURN(1);

  if (my_fstat(share->data_file, &share->file_stat, MYF(MY_WME)) == -1)
    DBUG_RETURN(1);

135
  if (share->file_stat.st_size)
136 137
  {
    if (write)
138 139 140
      share->mapped_file= (byte *)my_mmap(NULL, share->file_stat.st_size,
                                          PROT_READ|PROT_WRITE, MAP_SHARED,
                                          share->data_file, 0);
141
    else
142 143 144
      share->mapped_file= (byte *)my_mmap(NULL, share->file_stat.st_size,
                                          PROT_READ, MAP_PRIVATE,
                                          share->data_file, 0);
145
    if ((share->mapped_file == MAP_FAILED))
146 147 148 149 150 151 152 153 154 155 156 157
    {
      /*
        Bad idea you think? See the problem is that nothing actually checks
        the return value of ::rnd_init(), so tossing an error is about
        it for us.
        Never going to happen right? :)
      */
      my_message(errno, "Woops, blew up opening a mapped file", 0);
      DBUG_ASSERT(0);
      DBUG_RETURN(1);
    }
  }
158
  else
159 160 161 162 163
    share->mapped_file= NULL;

  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

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

193 194 195 196 197 198 199 200 201
/*
  Simple lock controls.
*/
static TINA_SHARE *get_share(const char *table_name, TABLE *table)
{
  TINA_SHARE *share;
  char *tmp_name;
  uint length;

202 203 204
  if (!tina_init)
     tina_init_func();

205 206
  pthread_mutex_lock(&tina_mutex);
  length=(uint) strlen(table_name);
207 208 209 210 211

  /*
    If share is not present in the hash, create a new share and
    initialize its members.
  */
212 213 214 215 216 217
  if (!(share=(TINA_SHARE*) hash_search(&tina_open_tables,
                                        (byte*) table_name,
                                        length)))
  {
    char data_file_name[FN_REFLEN];
    if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
218 219
                         &share, sizeof(*share),
                         &tmp_name, length+1,
220
                         NullS))
221 222 223 224 225
    {
      pthread_mutex_unlock(&tina_mutex);
      return NULL;
    }

226
    share->use_count= 0;
227
    share->is_log_table= FALSE;
228 229 230 231 232
    share->table_name_length= length;
    share->table_name= tmp_name;
    strmov(share->table_name, table_name);
    fn_format(data_file_name, table_name, "", ".CSV",
              MY_REPLACE_EXT|MY_UNPACK_FILENAME);
233 234 235 236 237
    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);

unknown's avatar
unknown committed
238 239
    if ((share->data_file= my_open(data_file_name, O_RDWR|O_APPEND,
                                   MYF(0))) == -1)
240 241
      goto error2;

242 243 244 245
    /*
      We only use share->data_file for writing, so we scan to
      the end to append
    */
246 247 248
    if (my_seek(share->data_file, 0, SEEK_END, MYF(0)) == MY_FILEPOS_ERROR)
      goto error2;

249
    share->mapped_file= NULL; // We don't know the state as we just allocated it
250 251
    if (get_mmap(share, 0) > 0)
      goto error3;
252 253 254

    /* init file length value used by readers */
    share->saved_data_file_length= share->file_stat.st_size;
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
  }
  share->use_count++;
  pthread_mutex_unlock(&tina_mutex);

  return share;

error3:
  my_close(share->data_file,MYF(0));
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;
}


274
/*
275 276 277 278 279 280 281 282 283
  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){
    /* Drop the mapped file */
284
    if (share->mapped_file)
285
      my_munmap(share->mapped_file, share->file_stat.st_size);
286 287 288 289 290 291 292 293 294 295 296
    result_code= my_close(share->data_file,MYF(0));
    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);
}

297
int tina_end(ha_panic_function type)
unknown's avatar
unknown committed
298
{
unknown's avatar
unknown committed
299
  return tina_done_func();
unknown's avatar
unknown committed
300
}
301

302
/*
303 304 305
  Finds the end of a line.
  Currently only supports files written on a UNIX OS.
*/
306
byte * find_eoln(byte *data, off_t begin, off_t end)
307
{
308
  for (off_t x= begin; x < end; x++)
309 310 311 312 313 314
    if (data[x] == '\n')
      return data + x;

  return 0;
}

315

unknown's avatar
unknown committed
316
static handler *tina_create_handler(TABLE_SHARE *table)
317 318 319 320 321
{
  return new ha_tina(table);
}


unknown's avatar
unknown committed
322
ha_tina::ha_tina(TABLE_SHARE *table_arg)
323 324
  :handler(&tina_hton, table_arg),
  /*
unknown's avatar
unknown committed
325 326
    These definitions are found in handler.h
    They are not probably completely right.
327
  */
328 329 330
  current_position(0), next_position(0), local_saved_data_file_length(0),
  chain_alloced(0), chain_size(DEFAULT_CHAIN_LENGTH),
  records_is_known(0)
331 332
{
  /* Set our original buffers from pre-allocated memory */
333
  buffer.set((char*)byte_buffer, IO_SIZE, system_charset_info);
334 335 336
  chain= chain_buffer;
}

337

338 339 340
/*
  Encode a buffer into the quoted format.
*/
unknown's avatar
unknown committed
341

342
int ha_tina::encode_quote(byte *buf)
343 344 345 346 347 348 349 350 351 352
{
  char attribute_buffer[1024];
  String attribute(attribute_buffer, sizeof(attribute_buffer), &my_charset_bin);

  buffer.length(0);
  for (Field **field=table->field ; *field ; field++)
  {
    const char *ptr;
    const char *end_ptr;

353 354 355 356 357 358 359 360 361 362 363 364 365 366
    /*
      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;
    }
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 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410

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

  return (buffer.length());
}

/*
411 412 413
  chain_append() adds delete positions to the chain that we use to keep
  track of space. Then the chain will be used to cleanup "holes", occured
  due to deletes and updates.
414 415 416 417 418
*/
int ha_tina::chain_append()
{
  if ( chain_ptr != chain && (chain_ptr -1)->end == current_position)
    (chain_ptr -1)->end= next_position;
419
  else
420 421 422 423 424 425 426 427 428
  {
    /* 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 */
429 430
        if ((chain= (tina_set *) my_realloc((gptr)chain,
                                            chain_size, MYF(MY_WME))) == NULL)
431 432 433 434
          return -1;
      }
      else
      {
435 436
        tina_set *ptr= (tina_set *) my_malloc(chain_size * sizeof(tina_set),
                                              MYF(MY_WME));
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
        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;
}


452
/*
453 454 455 456
  Scans for a row.
*/
int ha_tina::find_current_row(byte *buf)
{
457
  byte *mapped_ptr;
458 459 460
  byte *end_ptr;
  DBUG_ENTER("ha_tina::find_current_row");

461 462 463 464 465 466
  mapped_ptr= (byte *)share->mapped_file + current_position;

  /*
    We do not read further then local_saved_data_file_length in order
    not to conflict with undergoing concurrent insert.
  */
467
  if ((end_ptr=  find_eoln(share->mapped_file, current_position,
468
                           local_saved_data_file_length)) == 0)
469 470 471 472 473 474 475 476
    DBUG_RETURN(HA_ERR_END_OF_FILE);

  for (Field **field=table->field ; *field ; field++)
  {
    buffer.length(0);
    mapped_ptr++; // Increment past the first quote
    for(;mapped_ptr != end_ptr; mapped_ptr++)
    {
477 478 479 480
      // Need to convert line feeds!
      if (*mapped_ptr == '"' &&
          (((mapped_ptr[1] == ',') && (mapped_ptr[2] == '"')) ||
           (mapped_ptr == end_ptr -1 )))
481 482 483
      {
        mapped_ptr += 2; // Move past the , and the "
        break;
484 485
      }
      if (*mapped_ptr == '\\' && mapped_ptr != (end_ptr - 1))
486 487 488 489 490 491 492 493 494 495 496 497 498
      {
        mapped_ptr++;
        if (*mapped_ptr == 'r')
          buffer.append('\r');
        else if (*mapped_ptr == 'n' )
          buffer.append('\n');
        else if ((*mapped_ptr == '\\') || (*mapped_ptr == '"'))
          buffer.append(*mapped_ptr);
        else  /* This could only happed with an externally created file */
        {
          buffer.append('\\');
          buffer.append(*mapped_ptr);
        }
499
      }
500 501 502 503 504 505 506
      else
        buffer.append(*mapped_ptr);
    }
    (*field)->store(buffer.ptr(), buffer.length(), system_charset_info);
  }
  next_position= (end_ptr - share->mapped_file)+1;
  /* Maybe use \N for null? */
507
  memset(buf, 0, table->s->null_bytes); /* We do not implement nulls! */
508 509 510 511 512 513 514 515

  DBUG_RETURN(0);
}

/*
  If frm_error() is called in table.cc this is called to find out what file
  extensions exist for this handler.
*/
unknown's avatar
unknown committed
516 517 518 519 520
static const char *ha_tina_exts[] = {
  ".CSV",
  NullS
};

521
const char **ha_tina::bas_ext() const
unknown's avatar
unknown committed
522 523 524
{
  return ha_tina_exts;
}
525

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 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 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
/*
  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 */
  share->saved_data_file_length= share->file_stat.st_size;
}


606 607 608 609
bool ha_tina::check_if_locking_is_allowed(uint sql_command,
                                          ulong type, TABLE *table,
                                          uint count,
                                          bool called_by_logger_thread)
610 611 612 613 614 615 616
{
  /*
    Deny locking of the log tables, which is incompatible with
    concurrent insert. Unless called from a logger THD:
    general_log_thd or slow_log_thd.
  */
  if (table->s->log_table &&
617 618 619 620
      sql_command != SQLCOM_TRUNCATE &&
      !(sql_command == SQLCOM_FLUSH &&
        type & REFRESH_LOG) &&
      !called_by_logger_thread &&
621 622 623 624 625 626 627 628 629 630 631 632 633
      (table->reginfo.lock_type >= TL_READ_NO_INSERT))
  {
    /*
      The check  >= TL_READ_NO_INSERT denies all write locks
      plus the only read lock (TL_READ_NO_INSERT itself)
    */
    table->reginfo.lock_type == TL_READ_NO_INSERT ?
      my_error(ER_CANT_READ_LOCK_LOG_TABLE, MYF(0)) :
        my_error(ER_CANT_WRITE_LOCK_LOG_TABLE, MYF(0));
    return FALSE;
  }
  return TRUE;
}
634

635
/*
636 637 638 639 640 641 642 643 644 645
  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.
*/
int ha_tina::open(const char *name, int mode, uint test_if_locked)
{
  DBUG_ENTER("ha_tina::open");

  if (!(share= get_share(name, table)))
    DBUG_RETURN(1);
646 647 648 649 650 651 652

  /*
    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);
653 654
  ref_length=sizeof(off_t);

655 656 657 658
  share->lock.get_status= tina_get_status;
  share->lock.update_status= tina_update_status;
  share->lock.check_status= tina_check_status;

659 660 661 662 663 664 665 666 667 668 669 670 671 672
  DBUG_RETURN(0);
}


/*
  Close a database file. We remove ourselves from the shared strucutre.
  If it is empty we destroy it and free the mapped file.
*/
int ha_tina::close(void)
{
  DBUG_ENTER("ha_tina::close");
  DBUG_RETURN(free_share(share));
}

673
/*
674 675 676 677 678 679 680 681 682
  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");

683
  ha_statistic_increment(&SSV::ha_write_count);
684

685 686
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT)
    table->timestamp_field->set_time();
687 688 689

  size= encode_quote(buf);

690 691
  if (my_write(share->data_file, (byte*)buffer.ptr(), size,
               MYF(MY_WME | MY_NABP)))
692 693
    DBUG_RETURN(-1);

694 695
  /*
    Ok, this is means that we will be doing potentially bad things
696 697 698 699 700
    during a bulk insert on some OS'es. What we need is a cleanup
    call for ::write_row that would let us fix up everything after the bulk
    insert. The archive handler does this with an extra mutx call, which
    might be a solution for this.
  */
701
  if (get_mmap(share, 0) > 0)
702
    DBUG_RETURN(-1);
703 704 705 706 707 708 709 710 711 712 713 714

  /* update local copy of the max position to see our own changes */
  local_saved_data_file_length= share->file_stat.st_size;

  /* update status for the log tables */
  if (share->is_log_table)
  {
    pthread_mutex_lock(&share->mutex);
    update_status();
    pthread_mutex_unlock(&share->mutex);
  }

715
  records++;
716 717 718 719
  DBUG_RETURN(0);
}


720
/*
721
  This is called for an update.
722
  Make sure you put in code to increment the auto increment, also
723 724 725 726 727 728 729 730 731 732
  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");

733
  ha_statistic_increment(&SSV::ha_read_rnd_next_count);
734

735 736
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_UPDATE)
    table->timestamp_field->set_time();
737 738 739 740 741 742

  size= encode_quote(new_data);

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

743 744
  if (my_write(share->data_file, (byte*)buffer.ptr(), size,
               MYF(MY_WME | MY_NABP)))
745
    DBUG_RETURN(-1);
746 747 748 749 750 751 752

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

  /* update local copy of the max position to see our own changes */
  local_saved_data_file_length= share->file_stat.st_size;

753 754 755 756
  DBUG_RETURN(0);
}


757 758 759 760 761 762 763 764
/*
  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).
765 766 767 768
*/
int ha_tina::delete_row(const byte * buf)
{
  DBUG_ENTER("ha_tina::delete_row");
769
  ha_statistic_increment(&SSV::ha_delete_count);
770 771 772 773 774 775

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

  --records;

776 777 778
  /* DELETE should never happen on the log table */
  DBUG_ASSERT(!share->is_log_table);

779 780 781 782
  DBUG_RETURN(0);
}


783 784
/*
  All table scans call this first.
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
  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

808 809
  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.
810 811 812 813 814 815 816 817 818 819
  The ::info() call is just for the optimizer.

*/

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

  current_position= next_position= 0;
  records= 0;
820
  records_is_known= 0;
821
  chain_ptr= chain;
822
#ifdef HAVE_MADVISE
823
  if (scan)
824 825
    (void) madvise(share->mapped_file, share->file_stat.st_size,
                   MADV_SEQUENTIAL);
unknown's avatar
unknown committed
826
#endif
827 828 829 830 831

  DBUG_RETURN(0);
}

/*
832 833 834 835
  ::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:
836
  0Foo  Dog  Friend
837 838 839 840 841 842 843
  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 :)
844 845 846 847 848
*/
int ha_tina::rnd_next(byte *buf)
{
  DBUG_ENTER("ha_tina::rnd_next");

849
  ha_statistic_increment(&SSV::ha_read_rnd_next_count);
850 851

  current_position= next_position;
852
  if (!share->mapped_file)
853
    DBUG_RETURN(HA_ERR_END_OF_FILE);
854
  if (HA_ERR_END_OF_FILE == find_current_row(buf) )
855 856 857 858 859 860 861 862
    DBUG_RETURN(HA_ERR_END_OF_FILE);

  records++;
  DBUG_RETURN(0);
}

/*
  In the case of an order by rows will need to be sorted.
863
  ::position() is called after each call to ::rnd_next(),
864
  the data it stores is to a byte array. You can store this
865 866 867
  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
868 869 870 871 872
  where something other then a number is stored.
*/
void ha_tina::position(const byte *record)
{
  DBUG_ENTER("ha_tina::position");
unknown's avatar
unknown committed
873
  my_store_ptr(ref, ref_length, current_position);
874 875 876 877
  DBUG_VOID_RETURN;
}


878 879
/*
  Used to fetch a row from a posiion stored with ::position().
unknown's avatar
unknown committed
880
  my_get_ptr() retrieves the data for you.
881 882 883 884 885
*/

int ha_tina::rnd_pos(byte * buf, byte *pos)
{
  DBUG_ENTER("ha_tina::rnd_pos");
886
  ha_statistic_increment(&SSV::ha_read_rnd_next_count);
unknown's avatar
unknown committed
887
  current_position= my_get_ptr(pos,ref_length);
888 889 890 891 892 893 894 895 896 897 898 899
  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 */
900
  if (!records_is_known && records < 2) 
901 902 903 904 905 906 907 908 909 910 911 912
    records= 2;
  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");
913 914 915 916 917 918
 if (operation == HA_EXTRA_MARK_AS_LOG_TABLE)
 {
   pthread_mutex_lock(&share->mutex);
   share->is_log_table= TRUE;
   pthread_mutex_unlock(&share->mutex);
 }
919 920 921 922
  DBUG_RETURN(0);
}

/*
923 924 925 926
  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.
927 928 929 930 931
*/
int ha_tina::rnd_end()
{
  DBUG_ENTER("ha_tina::rnd_end");

932 933
  records_is_known= 1;

934 935 936 937
  /* First position will be truncate position, second will be increment */
  if ((chain_ptr - chain)  > 0)
  {
    tina_set *ptr;
938
    size_t length;
939

940
    /*
941 942 943
      Setting up writable map, this will contain all of the data after the
      get_mmap call that we have added to the file.
    */
944
    if (get_mmap(share, 1) > 0)
945 946 947 948 949 950 951 952
      DBUG_RETURN(-1);
    length= share->file_stat.st_size;

    /*
      The sort handles updates/deletes with random orders.
      It also sorts so that we move the final blocks to the
      beginning so that we move the smallest amount of data possible.
    */
953 954
    qsort(chain, (size_t)(chain_ptr - chain), sizeof(tina_set),
          (qsort_cmp)sort_set);
955 956
    for (ptr= chain; ptr < chain_ptr; ptr++)
    {
957 958
      memmove(share->mapped_file + ptr->begin, share->mapped_file + ptr->end,
              length - (size_t)ptr->end);
959 960 961
      length= length - (size_t)(ptr->end - ptr->begin);
    }

962 963
    /* Unmap the file before the new size is set */
    if (my_munmap(share->mapped_file, share->file_stat.st_size))
964
      DBUG_RETURN(-1);
965 966
    /* We set it to null so that get_mmap() won't try to unmap it */
    share->mapped_file= NULL;
967

968 969
    /* Set the file to the new size */
    if (my_chsize(share->data_file, length, 0, MYF(MY_WME)))
970 971
      DBUG_RETURN(-1);

972
    if (get_mmap(share, 0) > 0)
973 974 975 976 977 978
      DBUG_RETURN(-1);
  }

  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
979

980
/* 
unknown's avatar
unknown committed
981
  DELETE without WHERE calls this
982
*/
unknown's avatar
unknown committed
983

984 985 986 987
int ha_tina::delete_all_rows()
{
  DBUG_ENTER("ha_tina::delete_all_rows");

988 989 990
  if (!records_is_known)
    return (my_errno=HA_ERR_WRONG_COMMAND);

991 992 993 994 995 996 997
  /* Unmap the file before the new size is set */
  if (share->mapped_file && my_munmap(share->mapped_file,
                                      share->file_stat.st_size))
    DBUG_RETURN(-1);
  share->mapped_file= NULL;

  /* Truncate the file to zero size */
998 999
  int rc= my_chsize(share->data_file, 0, 0, MYF(MY_WME));

1000
  if (get_mmap(share, 0) > 0)
1001 1002
    DBUG_RETURN(-1);

1003
  records=0;
1004 1005 1006
  DBUG_RETURN(rc);
}

1007
/*
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
  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).
*/

1026 1027
int ha_tina::create(const char *name, TABLE *table_arg,
                    HA_CREATE_INFO *create_info)
1028 1029 1030 1031 1032
{
  char name_buff[FN_REFLEN];
  File create_file;
  DBUG_ENTER("ha_tina::create");

1033 1034
  if ((create_file= my_create(fn_format(name_buff, name, "", ".CSV",
                                        MY_REPLACE_EXT|MY_UNPACK_FILENAME),0,
1035
                              O_RDWR | O_TRUNC,MYF(MY_WME))) < 0)
1036 1037 1038 1039 1040 1041
    DBUG_RETURN(-1);

  my_close(create_file,MYF(0));

  DBUG_RETURN(0);
}
unknown's avatar
unknown committed
1042

1043 1044 1045 1046 1047 1048
bool ha_tina::check_if_incompatible_data(HA_CREATE_INFO *info,
					   uint table_changes)
{
  return COMPATIBLE_DATA_YES;
}

unknown's avatar
unknown committed
1049 1050 1051 1052 1053 1054 1055 1056
mysql_declare_plugin
{
  MYSQL_STORAGE_ENGINE_PLUGIN,
  &tina_hton,
  tina_hton.name,
  "Brian Aker, MySQL AB",
  "CSV Storage Engine",
  tina_init_func, /* Plugin Init */
unknown's avatar
unknown committed
1057 1058
  tina_done_func, /* Plugin Deinit */
  0x0100 /* 1.0 */,
unknown's avatar
unknown committed
1059 1060 1061
}
mysql_declare_plugin_end;