ha_tokudb.cc 131 KB
Newer Older
1
#ifdef USE_PRAGMA_IMPLEMENTATION
2
#pragma implementation          // gcc: Class implementation
3 4 5 6 7
#endif

#define MYSQL_SERVER 1
#include "mysql_priv.h"

8 9 10 11
#if !defined(HA_END_SPACE_KEY) || HA_END_SPACE_KEY != 0
#error
#endif

12 13 14 15
unsigned long my_getphyspages() {
    return sysconf(_SC_PHYS_PAGES);
}

16 17 18 19 20 21
#include <syscall.h>

unsigned int my_tid() {
    return syscall(__NR_gettid);
}

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
static inline void *thd_data_get(THD *thd, int slot) {
#if MYSQL_VERSION_ID <= 50123
    return thd->ha_data[slot];
#else
    return thd->ha_data[slot].ha_ptr;
#endif
}

static inline void thd_data_set(THD *thd, int slot, void *data) {
#if MYSQL_VERSION_ID <= 50123
    thd->ha_data[slot] = data;
#else
    thd->ha_data[slot].ha_ptr = data;
#endif
}

38 39 40 41 42
#undef PACKAGE
#undef VERSION
#undef HAVE_DTRACE
#undef _DTRACE_VERSION

43
//#include "tokudb_config.h"
44 45 46 47 48 49 50 51 52 53 54 55

/* We define DTRACE after mysql_priv.h in case it disabled dtrace in the main server */
#ifdef HAVE_DTRACE
#define _DTRACE_VERSION 1
#else
#endif

#include "tokudb_probes.h"

#include "ha_tokudb.h"
#include <mysql/plugin.h>

56
static handler *tokudb_create_handler(handlerton * hton, TABLE_SHARE * table, MEM_ROOT * mem_root);
57

58
handlerton *tokudb_hton;
59 60

typedef struct st_tokudb_trx_data {
61 62 63 64
    DB_TXN *all;
    DB_TXN *stmt;
    DB_TXN *sp_level;
    uint tokudb_lock_count;
65 66
} tokudb_trx_data;

67 68
// QQQ how to tune these?
#define HA_TOKUDB_ROWS_IN_TABLE 10000   /* to get optimization right */
69
#define HA_TOKUDB_RANGE_COUNT   100
70
#define HA_TOKUDB_MAX_ROWS      10000000        /* Max rows in table */
71 72 73 74 75 76
/* extra rows for estimate_rows_upper_bound() */
#define HA_TOKUDB_EXTRA_ROWS    100

/* Bits for share->status */
#define STATUS_PRIMARY_KEY_INIT 1
#define STATUS_ROW_COUNT_INIT   2
77
#define STATUS_TOKUDB_ANALYZE      4
78
#define STATUS_AUTO_INCREMENT_INIT 8
79

80
// tokudb debug tracing
Rich Prohaska's avatar
Rich Prohaska committed
81 82
#define TOKUDB_DEBUG_INIT 1
#define TOKUDB_DEBUG_OPEN 2
83 84 85 86 87
#define TOKUDB_DEBUG_ENTER 4
#define TOKUDB_DEBUG_RETURN 8
#define TOKUDB_DEBUG_ERROR 16
#define TOKUDB_DEBUG_TXN 32
#define TOKUDB_DEBUG_AUTO_INCREMENT 64
Yoni Fogel's avatar
Yoni Fogel committed
88
#define TOKUDB_DEBUG_SAVE_TRACE 128
89

90 91 92
#define TOKUDB_TRACE(f, ...) \
    printf("%d:%s:%d:" f, my_tid(), __FILE__, __LINE__, ##__VA_ARGS__);

93
#define TOKUDB_DBUG_ENTER(f, ...)      \
94
{ \
95
    if (tokudb_debug & TOKUDB_DEBUG_ENTER) { \
96
        TOKUDB_TRACE(f "\n", ##__VA_ARGS__); \
97
    } \
98
} \
99
    DBUG_ENTER(__FUNCTION__);
100

101 102 103 104

#define TOKUDB_DBUG_RETURN(r) \
{ \
    int rr = (r); \
105 106 107
    if ((tokudb_debug & TOKUDB_DEBUG_RETURN) || (rr != 0 && (tokudb_debug & TOKUDB_DEBUG_ERROR))) { \
        TOKUDB_TRACE("%s:return %d\n", __FUNCTION__, rr); \
    } \
108 109
    DBUG_RETURN(rr); \
}
110

111 112
#define TOKUDB_DBUG_DUMP(s, p, len) \
{ \
113
    TOKUDB_TRACE("%s:%s", __FUNCTION__, s); \
114 115 116 117 118
    uint i;                                                             \
    for (i=0; i<len; i++) {                                             \
        printf("%2.2x", ((uchar*)p)[i]);                                \
    }                                                                   \
    printf("\n");                                                       \
119 120
}

121 122
const char *ha_tokudb_ext = ".tokudb";

Rich Prohaska's avatar
Rich Prohaska committed
123
//static my_bool tokudb_shared_data = FALSE;
124 125 126 127 128
static u_int32_t tokudb_init_flags = 
    DB_CREATE | DB_THREAD | DB_PRIVATE | 
    DB_INIT_LOCK | 
    DB_INIT_MPOOL |
    DB_INIT_TXN | 
129 130
    0 | // disabled for 1.0.2 DB_INIT_LOG |
    0;  // disabled for 1.0.1 DB_RECOVER;
131
static u_int32_t tokudb_env_flags = DB_LOG_AUTOREMOVE;
Rich Prohaska's avatar
Rich Prohaska committed
132
//static u_int32_t tokudb_lock_type = DB_LOCK_DEFAULT;
133 134
//static ulong tokudb_log_buffer_size = 0;
//static ulong tokudb_log_file_size = 0;
135
static ulonglong tokudb_cache_size = 0;
136
static uint tokudb_cache_memory_percent = 50;
137
static char *tokudb_home;
138 139 140
//static char *tokudb_tmpdir;
static char *tokudb_data_dir;
static char *tokudb_log_dir;
Rich Prohaska's avatar
Rich Prohaska committed
141 142
//static long tokudb_lock_scan_time = 0;
//static ulong tokudb_region_size = 0;
143
//static ulong tokudb_cache_parts = 1;
144
static ulong tokudb_trans_retry = 1;
145
static ulong tokudb_max_lock;
146
static ulong tokudb_debug;
147 148 149 150 151
#ifdef TOKUDB_VERSION
static char *tokudb_version = TOKUDB_VERSION;
#else
static char *tokudb_version;
#endif
152 153 154

static DB_ENV *db_env;

155 156 157
static const char tokudb_hton_name[] = "TokuDB";
static const int tokudb_hton_name_length = sizeof(tokudb_hton_name) - 1;

158
// thread variables
159

160 161
static MYSQL_THDVAR_BOOL(commit_sync, PLUGIN_VAR_THDLOCAL, "sync on txn commit", 
                         /* check */ NULL, /* update */ NULL, /* default*/ TRUE);
162 163

static void tokudb_print_error(const DB_ENV * db_env, const char *db_errpfx, const char *buffer);
164
static void tokudb_cleanup_log_files(void);
165 166 167 168 169 170 171 172 173 174
static TOKUDB_SHARE *get_share(const char *table_name, TABLE * table);
static int free_share(TOKUDB_SHARE * share, TABLE * table, uint hidden_primary_key, bool mutex_is_locked);
static int write_status(DB * status_block, char *buff, uint length);
static void update_status(TOKUDB_SHARE * share, TABLE * table);
static int tokudb_end(handlerton * hton, ha_panic_function type);
static bool tokudb_flush_logs(handlerton * hton);
static bool tokudb_show_status(handlerton * hton, THD * thd, stat_print_fn * print, enum ha_stat_type);
static int tokudb_close_connection(handlerton * hton, THD * thd);
static int tokudb_commit(handlerton * hton, THD * thd, bool all);
static int tokudb_rollback(handlerton * hton, THD * thd, bool all);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
175
static uint tokudb_alter_table_flags(uint flags);
176
#if 0
177 178 179
static int tokudb_rollback_to_savepoint(handlerton * hton, THD * thd, void *savepoint);
static int tokudb_savepoint(handlerton * hton, THD * thd, void *savepoint);
static int tokudb_release_savepoint(handlerton * hton, THD * thd, void *savepoint);
180
#endif
181
static bool tokudb_show_logs(THD * thd, stat_print_fn * stat_print);
182 183 184 185

static HASH tokudb_open_tables;
pthread_mutex_t tokudb_mutex;

186 187 188
static uchar *tokudb_get_key(TOKUDB_SHARE * share, size_t * length, my_bool not_used __attribute__ ((unused))) {
    *length = share->table_name_length;
    return (uchar *) share->table_name;
189 190
}

191
static int tokudb_init_func(void *p) {
192
    TOKUDB_DBUG_ENTER("tokudb_init_func");
193

194
    tokudb_hton = (handlerton *) p;
195

196 197
    VOID(pthread_mutex_init(&tokudb_mutex, MY_MUTEX_INIT_FAST));
    (void) hash_init(&tokudb_open_tables, system_charset_info, 32, 0, 0, (hash_get_key) tokudb_get_key, 0, 0);
198

199
    tokudb_hton->state = SHOW_OPTION_YES;
200
    // tokudb_hton->flags= HTON_CAN_RECREATE;  // QQQ this came from skeleton
201
    tokudb_hton->flags = HTON_CLOSE_CURSORS_AT_COMMIT | HTON_FLUSH_AFTER_RENAME;
202
#ifdef DB_TYPE_TOKUDB
203 204 205
    tokudb_hton->db_type = DB_TYPE_TOKUDB;
#else
    tokudb_hton->db_type = DB_TYPE_UNKNOWN;
206 207
#endif

208 209
    tokudb_hton->create = tokudb_create_handler;
    tokudb_hton->close_connection = tokudb_close_connection;
210 211
#if 0
    tokudb_hton->savepoint_offset = sizeof(DB_TXN *);
212 213 214
    tokudb_hton->savepoint_set = tokudb_savepoint;
    tokudb_hton->savepoint_rollback = tokudb_rollback_to_savepoint;
    tokudb_hton->savepoint_release = tokudb_release_savepoint;
215
#endif
216 217 218 219
    if (tokudb_init_flags & DB_INIT_TXN) {
        tokudb_hton->commit = tokudb_commit;
        tokudb_hton->rollback = tokudb_rollback;
    }
220 221 222
    tokudb_hton->panic = tokudb_end;
    tokudb_hton->flush_logs = tokudb_flush_logs;
    tokudb_hton->show_status = tokudb_show_status;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
223
    tokudb_hton->alter_table_flags = tokudb_alter_table_flags;
224
#if 0
225 226 227
    if (!tokudb_tmpdir)
        tokudb_tmpdir = mysql_tmpdir;
    DBUG_PRINT("info", ("tokudb_tmpdir: %s", tokudb_tmpdir));
228
#endif
229 230 231
    if (!tokudb_home)
        tokudb_home = mysql_real_data_home;
    DBUG_PRINT("info", ("tokudb_home: %s", tokudb_home));
232
#if 0
233
    if (!tokudb_log_buffer_size) { // QQQ
234 235 236 237 238 239 240
        tokudb_log_buffer_size = max(table_cache_size * 512, 32 * 1024);
        DBUG_PRINT("info", ("computing tokudb_log_buffer_size %ld\n", tokudb_log_buffer_size));
    }
    tokudb_log_file_size = tokudb_log_buffer_size * 4;
    tokudb_log_file_size = MY_ALIGN(tokudb_log_file_size, 1024 * 1024L);
    tokudb_log_file_size = max(tokudb_log_file_size, 10 * 1024 * 1024L);
    DBUG_PRINT("info", ("computing tokudb_log_file_size: %ld\n", tokudb_log_file_size));
241
#endif
242 243 244
    int r;
    if ((r = db_env_create(&db_env, 0))) {
        DBUG_PRINT("info", ("db_env_create %d\n", r));
245
        goto error;
246 247
    }

Rich Prohaska's avatar
Rich Prohaska committed
248
    DBUG_PRINT("info", ("tokudb_env_flags: 0x%x\n", tokudb_env_flags));
249
    r = db_env->set_flags(db_env, tokudb_env_flags, 1);
250
    if (r) { // QQQ
Rich Prohaska's avatar
Rich Prohaska committed
251
        if (tokudb_debug & TOKUDB_DEBUG_INIT) 
252 253
            TOKUDB_TRACE("%s:WARNING: flags=%x r=%d\n", __FUNCTION__, tokudb_env_flags, r); 
        // goto error;
254
    }
255 256

    // config error handling
257
    db_env->set_errcall(db_env, tokudb_print_error);
258 259 260
    db_env->set_errpfx(db_env, "TokuDB");

    // config directories
261
#if 0
262 263
    DBUG_PRINT("info", ("tokudb_tmpdir: %s\n", tokudb_tmpdir));
    db_env->set_tmp_dir(db_env, tokudb_tmpdir);
264 265 266 267 268 269 270 271 272 273 274 275 276
#endif

    {
    char *data_dir = tokudb_data_dir;
    if (data_dir == 0) 
        data_dir = mysql_data_home;
    DBUG_PRINT("info", ("tokudb_data_dir: %s\n", data_dir));
    db_env->set_data_dir(db_env, data_dir);
    }

    if (tokudb_log_dir) {
        DBUG_PRINT("info", ("tokudb_log_dir: %s\n", tokudb_log_dir));
        db_env->set_lg_dir(db_env, tokudb_log_dir);
277 278
    }

279
    // config the cache table
280 281 282 283
    if (tokudb_cache_size == 0) {
        unsigned long pagesize = my_getpagesize();
        unsigned long long npages = my_getphyspages();
        unsigned long long physmem = npages * pagesize;
284
        tokudb_cache_size = (ulonglong) (physmem * (tokudb_cache_memory_percent / 100.0));
285
    }
286 287
    if (tokudb_cache_size) {
        DBUG_PRINT("info", ("tokudb_cache_size: %lld\n", tokudb_cache_size));
288
        r = db_env->set_cachesize(db_env, tokudb_cache_size / (1024 * 1024L * 1024L), tokudb_cache_size % (1024L * 1024L * 1024L), 1);
289 290 291 292
        if (r) {
            DBUG_PRINT("info", ("set_cachesize %d\n", r));
            goto error; 
        }
293 294 295 296
    }
    u_int32_t gbytes, bytes; int parts;
    r = db_env->get_cachesize(db_env, &gbytes, &bytes, &parts);
    if (r == 0) 
Rich Prohaska's avatar
Rich Prohaska committed
297
        if (tokudb_debug & TOKUDB_DEBUG_INIT) 
298
            TOKUDB_TRACE("%s:tokudb_cache_size=%lld\n", __FUNCTION__, ((unsigned long long) gbytes << 30) + bytes);
299

300 301
#if 0
    // QQQ config the logs
302 303 304 305 306 307
    DBUG_PRINT("info", ("tokudb_log_file_size: %ld\n", tokudb_log_file_size));
    db_env->set_lg_max(db_env, tokudb_log_file_size);
    DBUG_PRINT("info", ("tokudb_log_buffer_size: %ld\n", tokudb_log_buffer_size));
    db_env->set_lg_bsize(db_env, tokudb_log_buffer_size);
    // DBUG_PRINT("info",("tokudb_region_size: %ld\n", tokudb_region_size));
    // db_env->set_lg_regionmax(db_env, tokudb_region_size);
308
#endif
309

310 311
    // config the locks
#if 0 // QQQ no lock types yet
312 313
    DBUG_PRINT("info", ("tokudb_lock_type: 0x%lx\n", tokudb_lock_type));
    db_env->set_lk_detect(db_env, tokudb_lock_type);
314 315 316 317 318 319 320 321 322
#endif
    if (tokudb_max_lock) {
        DBUG_PRINT("info",("tokudb_max_lock: %ld\n", tokudb_max_lock));
        r = db_env->set_lk_max_locks(db_env, tokudb_max_lock);
        if (r) {
            DBUG_PRINT("info", ("tokudb_set_max_locks %d\n", r));
            goto error;
        }
    }
323

324 325 326 327 328 329 330
    if (tokudb_debug & TOKUDB_DEBUG_INIT) TOKUDB_TRACE("%s:env open:flags=%x\n", __FUNCTION__, tokudb_init_flags);

    r = db_env->open(db_env, tokudb_home, tokudb_init_flags, 0666);

    if (tokudb_debug & TOKUDB_DEBUG_INIT) TOKUDB_TRACE("%s:env opened:return=%d\n", __FUNCTION__, r);

    if (r) {
331
        DBUG_PRINT("info", ("env->open %d\n", r));
332 333
        goto error;
    }
334

335
    DBUG_RETURN(FALSE);
336 337 338 339 340 341

error:
    if (db_env) {
        db_env->close(db_env, 0);
        db_env = 0;
    }
342 343 344 345
    DBUG_RETURN(TRUE);
}

static int tokudb_done_func(void *p) {
346
    TOKUDB_DBUG_ENTER("tokudb_done_func");
347 348 349 350 351 352
    int error = 0;

    if (tokudb_open_tables.records)
        error = 1;
    hash_free(&tokudb_open_tables);
    pthread_mutex_destroy(&tokudb_mutex);
353
    TOKUDB_DBUG_RETURN(0);
354 355 356 357 358 359 360
}

/** @brief
    Simple lock controls. The "share" it creates is a structure we will
    pass to each tokudb handler. Do you have to have one of these? Well, you have
    pieces that are used for locking, and they are needed to function.
*/
361 362 363
static TOKUDB_SHARE *get_share(const char *table_name, TABLE * table) {
    TOKUDB_SHARE *share;
    uint length;
364

365 366 367 368 369 370 371
    pthread_mutex_lock(&tokudb_mutex);
    length = (uint) strlen(table_name);

    if (!(share = (TOKUDB_SHARE *) hash_search(&tokudb_open_tables, (uchar *) table_name, length))) {
        ulong *rec_per_key;
        char *tmp_name;
        u_int32_t *key_type;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
372
        uint num_keys = table->s->keys;
373

374 375 376 377
        if (!(share = (TOKUDB_SHARE *) 
            my_multi_malloc(MYF(MY_WME | MY_ZEROFILL), 
                            &share, sizeof(*share),
                            &tmp_name, length + 1, 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
378 379
                            &rec_per_key, num_keys * sizeof(ha_rows), 
                            &key_type, (num_keys + 1) * sizeof(u_int32_t), 
380
                            NullS))) {
381 382 383 384 385 386 387
            pthread_mutex_unlock(&tokudb_mutex);
            return NULL;
        }
        share->use_count = 0;
        share->table_name_length = length;
        share->table_name = tmp_name;
        strmov(share->table_name, table_name);
388

389 390
        share->rec_per_key = rec_per_key;
        share->key_type = key_type;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
391
        bzero((void *) share->key_file, sizeof(share->key_file));
392 393 394 395 396

        if (my_hash_insert(&tokudb_open_tables, (uchar *) share))
            goto error;
        thr_lock_init(&share->lock);
        pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST);
397
    }
398
    pthread_mutex_unlock(&tokudb_mutex);
399

400
    return share;
401

402
  error:
403 404 405
    pthread_mutex_destroy(&share->mutex);
    my_free((uchar *) share, MYF(0));

406
    return NULL;
407 408
}

409 410
static int free_share(TOKUDB_SHARE * share, TABLE * table, uint hidden_primary_key, bool mutex_is_locked) {
    int error, result = 0;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
411
    uint num_keys = table->s->keys + test(hidden_primary_key);
412 413 414 415 416 417 418 419 420 421 422 423

    pthread_mutex_lock(&tokudb_mutex);

    if (mutex_is_locked)
        pthread_mutex_unlock(&share->mutex);
    if (!--share->use_count) {
        DBUG_PRINT("info", ("share->use_count %u", share->use_count));
        DB **key_file = share->key_file;

        /* this does share->file->close() implicitly */
        update_status(share, table);

Zardosht Kasheff's avatar
Zardosht Kasheff committed
424
        for (uint i = 0; i < num_keys; i++) {
425
            if (tokudb_debug & TOKUDB_DEBUG_OPEN)
426
                TOKUDB_TRACE("dbclose:%p\n", key_file[i]);
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
            if (key_file[i] && (error = key_file[i]->close(key_file[i], 0)))
                result = error;
        }

        if (share->status_block && (error = share->status_block->close(share->status_block, 0)))
            result = error;

        hash_delete(&tokudb_open_tables, (uchar *) share);
        thr_lock_delete(&share->lock);
        pthread_mutex_destroy(&share->mutex);
        my_free((uchar *) share, MYF(0));
    }
    pthread_mutex_unlock(&tokudb_mutex);

    return result;
442 443
}

444 445 446 447 448
static handler *tokudb_create_handler(handlerton * hton, TABLE_SHARE * table, MEM_ROOT * mem_root) {
    return new(mem_root) ha_tokudb(hton, table);
}

int tokudb_end(handlerton * hton, ha_panic_function type) {
449
    TOKUDB_DBUG_ENTER("tokudb_end");
450 451
    int error = 0;
    if (db_env) {
452 453
        if (tokudb_init_flags & DB_INIT_LOG)
            tokudb_cleanup_log_files();
454 455 456
        error = db_env->close(db_env, 0);       // Error is logged
        db_env = 0;
    }
457
    TOKUDB_DBUG_RETURN(error);
458 459 460
}

static int tokudb_close_connection(handlerton * hton, THD * thd) {
461
    my_free(thd_data_get(thd, hton->slot), MYF(0));
462 463 464 465
    return 0;
}

bool tokudb_flush_logs(handlerton * hton) {
466
    TOKUDB_DBUG_ENTER("tokudb_flush_logs");
467 468
    int error;
    bool result = 0;
469 470 471 472 473 474 475 476 477
    if (tokudb_init_flags & DB_INIT_LOG) {
        if ((error = db_env->log_flush(db_env, 0))) {
            my_error(ER_ERROR_DURING_FLUSH_LOGS, MYF(0), error);
            result = 1;
        }
        if ((error = db_env->txn_checkpoint(db_env, 0, 0, 0))) {
            my_error(ER_ERROR_DURING_CHECKPOINT, MYF(0), error);
            result = 1;
        }
478
    }
479
    TOKUDB_DBUG_RETURN(result);
480 481 482
}

static int tokudb_commit(handlerton * hton, THD * thd, bool all) {
483
    TOKUDB_DBUG_ENTER("tokudb_commit");
484
    DBUG_PRINT("trans", ("ending transaction %s", all ? "all" : "stmt"));
485
    u_int32_t syncflag = THDVAR(thd, commit_sync) ? 0 : DB_TXN_NOSYNC;
486
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
487
    DB_TXN **txn = all ? &trx->all : &trx->stmt;
488 489
    int error = 0;
    if (*txn) {
490
        if (tokudb_debug & TOKUDB_DEBUG_TXN) 
491
            TOKUDB_TRACE("commit:%d:%p\n", all, *txn);
492
        error = (*txn)->commit(*txn, syncflag);
493 494 495 496
        if (*txn == trx->sp_level)
            trx->sp_level = 0;
        *txn = 0;
    } else
497
        if (tokudb_debug & TOKUDB_DEBUG_TXN) 
498
            TOKUDB_TRACE("commit0\n");
499
    TOKUDB_DBUG_RETURN(error);
500 501 502
}

static int tokudb_rollback(handlerton * hton, THD * thd, bool all) {
503
    TOKUDB_DBUG_ENTER("tokudb_rollback");
504
    DBUG_PRINT("trans", ("aborting transaction %s", all ? "all" : "stmt"));
505
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
506
    DB_TXN **txn = all ? &trx->all : &trx->stmt;
507 508
    int error = 0;
    if (*txn) {
509
        if (tokudb_debug & TOKUDB_DEBUG_TXN)
510
            TOKUDB_TRACE("rollback:%p\n", *txn);
511 512 513 514 515
        error = (*txn)->abort(*txn);
	if (*txn == trx->sp_level)
	    trx->sp_level = 0;
	*txn = 0;
    } else
516
        if (tokudb_debug & TOKUDB_DEBUG_TXN) 
517
            TOKUDB_TRACE("abort0\n");
518
    TOKUDB_DBUG_RETURN(error);
519 520
}

521 522
#if 0

523
static int tokudb_savepoint(handlerton * hton, THD * thd, void *savepoint) {
524
    TOKUDB_DBUG_ENTER("tokudb_savepoint");
525 526 527 528 529 530
    int error;
    DB_TXN **save_txn = (DB_TXN **) savepoint;
    tokudb_trx_data *trx = (tokudb_trx_data *) thd->ha_data[hton->slot];
    if (!(error = db_env->txn_begin(db_env, trx->sp_level, save_txn, 0))) {
        trx->sp_level = *save_txn;
    }
531
    TOKUDB_DBUG_RETURN(error);
532 533 534
}

static int tokudb_rollback_to_savepoint(handlerton * hton, THD * thd, void *savepoint) {
535
    TOKUDB_DBUG_ENTER("tokudb_rollback_to_savepoint");
536 537 538 539 540 541 542 543
    int error;
    DB_TXN *parent, **save_txn = (DB_TXN **) savepoint;
    tokudb_trx_data *trx = (tokudb_trx_data *) thd->ha_data[hton->slot];
    parent = (*save_txn)->parent;
    if (!(error = (*save_txn)->abort(*save_txn))) {
        trx->sp_level = parent;
        error = tokudb_savepoint(hton, thd, savepoint);
    }
544
    TOKUDB_DBUG_RETURN(error);
545 546 547
}

static int tokudb_release_savepoint(handlerton * hton, THD * thd, void *savepoint) {
548
    TOKUDB_DBUG_ENTER("tokudb_release_savepoint");
549 550 551 552 553 554 555 556
    int error;
    DB_TXN *parent, **save_txn = (DB_TXN **) savepoint;
    tokudb_trx_data *trx = (tokudb_trx_data *) thd->ha_data[hton->slot];
    parent = (*save_txn)->parent;
    if (!(error = (*save_txn)->commit(*save_txn, 0))) {
        trx->sp_level = parent;
        *save_txn = 0;
    }
557
    TOKUDB_DBUG_RETURN(error);
558
}
559

560
#endif
561 562

static bool tokudb_show_logs(THD * thd, stat_print_fn * stat_print) {
563
    TOKUDB_DBUG_ENTER("tokudb_show_logs");
564 565 566 567 568 569 570 571 572
    char **all_logs, **free_logs, **a, **f;
    int error = 1;
    MEM_ROOT **root_ptr = my_pthread_getspecific_ptr(MEM_ROOT **, THR_MALLOC);
    MEM_ROOT show_logs_root, *old_mem_root = *root_ptr;

    init_sql_alloc(&show_logs_root, BDB_LOG_ALLOC_BLOCK_SIZE, BDB_LOG_ALLOC_BLOCK_SIZE);
    *root_ptr = &show_logs_root;
    all_logs = free_logs = 0;

573 574
    error = db_env->log_archive(db_env, &all_logs, 0);
    if (error) {
575
        DBUG_PRINT("error", ("log_archive failed (error %d)", error));
576
        db_env->err(db_env, error, "log_archive");
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
        if (error == DB_NOTFOUND)
            error = 0;          // No log files
        goto err;
    }
    /* Error is 0 here */
    if (all_logs) {
        for (a = all_logs, f = free_logs; *a; ++a) {
            if (f && *f && strcmp(*a, *f) == 0) {
                f++;
                if ((error = stat_print(thd, tokudb_hton_name, tokudb_hton_name_length, *a, strlen(*a), STRING_WITH_LEN(SHOW_LOG_STATUS_FREE))))
                    break;
            } else {
                if ((error = stat_print(thd, tokudb_hton_name, tokudb_hton_name_length, *a, strlen(*a), STRING_WITH_LEN(SHOW_LOG_STATUS_INUSE))))
                    break;
            }
        }
    }
  err:
    if (all_logs)
        free(all_logs);
    if (free_logs)
        free(free_logs);
    free_root(&show_logs_root, MYF(0));
    *root_ptr = old_mem_root;
601
    TOKUDB_DBUG_RETURN(error);
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
}

bool tokudb_show_status(handlerton * hton, THD * thd, stat_print_fn * stat_print, enum ha_stat_type stat_type) {
    switch (stat_type) {
    case HA_ENGINE_LOGS:
        return tokudb_show_logs(thd, stat_print);
    default:
        return FALSE;
    }
}

static void tokudb_print_error(const DB_ENV * db_env, const char *db_errpfx, const char *buffer) {
    sql_print_error("%s:  %s", db_errpfx, buffer);
}

void tokudb_cleanup_log_files(void) {
618
    TOKUDB_DBUG_ENTER("tokudb_cleanup_log_files");
619 620 621 622 623
    char **names;
    int error;

    if ((error = db_env->txn_checkpoint(db_env, 0, 0, 0)))
        my_error(ER_ERROR_DURING_CHECKPOINT, MYF(0), error);
624

625
    if ((error = db_env->log_archive(db_env, &names, 0)) != 0) {
626
        DBUG_PRINT("error", ("log_archive failed (error %d)", error));
627
        db_env->err(db_env, error, "log_archive");
628 629
        DBUG_VOID_RETURN;
    }
630

631 632
    if (names) {
        char **np;
633
        for (np = names; *np; ++np) {
634 635
#if 1
            if (tokudb_debug)
636
                TOKUDB_TRACE("%s:cleanup:%s\n", __FUNCTION__, *np);
637 638 639
#else
            my_delete(*np, MYF(MY_WME));
#endif
640
        }
641

642 643
        free(names);
    }
644

645
    DBUG_VOID_RETURN;
646 647
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
648 649 650 651 652 653 654 655 656 657 658 659 660 661
//
// *******NOTE*****
// If the flags HA_ONLINE_DROP_INDEX and HA_ONLINE_DROP_UNIQUE_INDEX
// are ever added, prepare_drop_index and final_drop_index will need to be modified
// so that the actual deletion of DB's is done in final_drop_index and not prepare_drop_index
//
static uint tokudb_alter_table_flags(uint flags)
{
    return (HA_ONLINE_ADD_INDEX_NO_WRITES| HA_ONLINE_DROP_INDEX_NO_WRITES |
            HA_ONLINE_ADD_UNIQUE_INDEX_NO_WRITES| HA_ONLINE_DROP_UNIQUE_INDEX_NO_WRITES);

}


662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
static int get_name_length(const char *name) {
    int n = 0;
    const char *newname = name;
    if (tokudb_data_dir) {
        n += strlen(tokudb_data_dir) + 1;
        if (strncmp("./", name, 2) == 0) 
            newname = name + 2;
    }
    n += strlen(newname);
    n += strlen(ha_tokudb_ext);
    return n;
}

static void make_name(char *newname, const char *tablename, const char *dictname) {
    const char *newtablename = tablename;
    char *nn = newname;
    if (tokudb_data_dir) {
        nn += sprintf(nn, "%s/", tokudb_data_dir);
        if (strncmp("./", tablename, 2) == 0)
            newtablename = tablename + 2;
    }
    nn += sprintf(nn, "%s%s", newtablename, ha_tokudb_ext);
    if (dictname)
        nn += sprintf(nn, "/%s%s", dictname, ha_tokudb_ext);
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
688

689 690
ha_tokudb::ha_tokudb(handlerton * hton, TABLE_SHARE * table_arg)
:  
Zardosht Kasheff's avatar
Zardosht Kasheff committed
691
    handler(hton, table_arg), alloc_ptr(0), rec_buff(0),
Zardosht Kasheff's avatar
Zardosht Kasheff committed
692
    // flags defined in sql\handler.h
693 694 695 696
    int_table_flags(HA_REC_NOT_IN_SEQ | HA_FAST_KEY_READ | HA_NULL_IN_KEY | HA_CAN_INDEX_BLOBS | HA_PRIMARY_KEY_IN_READ_INDEX | 
                    HA_FILE_BASED | HA_CAN_GEOMETRY | HA_AUTO_PART_KEY | HA_TABLE_SCAN_ON_INDEX), 
    changed_rows(0), last_dup_key((uint) - 1), version(0), using_ignore(0) {
}
697

698 699 700
static const char *ha_tokudb_exts[] = {
    ha_tokudb_ext,
    NullS
701 702
};

Zardosht Kasheff's avatar
Zardosht Kasheff committed
703 704 705
/* 
 *  returns NULL terminated file extension string
 */
706
const char **ha_tokudb::bas_ext() const {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
707 708
    TOKUDB_DBUG_ENTER("ha_tokudb::bas_ext");
    DBUG_RETURN(ha_tokudb_exts);
709 710
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
711 712 713 714
//
// Returns a bit mask of capabilities of the key or its part specified by 
// the arguments. The capabilities are defined in sql/handler.h.
//
715
ulong ha_tokudb::index_flags(uint idx, uint part, bool all_parts) const {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
716
    TOKUDB_DBUG_ENTER("ha_tokudb::index_flags");
717 718 719 720 721 722 723 724 725 726 727 728
    ulong flags = (HA_READ_NEXT | HA_READ_PREV | HA_READ_ORDER | HA_KEYREAD_ONLY | HA_READ_RANGE);
    for (uint i = all_parts ? 0 : part; i <= part; i++) {
        KEY_PART_INFO *key_part = table_share->key_info[idx].key_part + i;
        if (key_part->field->type() == FIELD_TYPE_BLOB) {
            /* We can't use BLOBS to shortcut sorts */
            flags &= ~(HA_READ_ORDER | HA_KEYREAD_ONLY | HA_READ_RANGE);
            break;
        }
        switch (key_part->field->key_type()) {
        case HA_KEYTYPE_TEXT:
        case HA_KEYTYPE_VARTEXT1:
        case HA_KEYTYPE_VARTEXT2:
729
            /* QQQ
730 731 732 733 734 735 736 737 738 739
               As BDB stores only one copy of equal strings, we can't use key read
               on these. Binary collations do support key read though.
             */
            if (!(key_part->field->charset()->state & MY_CS_BINSORT))
                flags &= ~HA_KEYREAD_ONLY;
            break;
        default:               // Keep compiler happy
            break;
        }
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
740
    DBUG_RETURN(flags);
741 742 743 744 745 746 747 748
}

static int tokudb_cmp_hidden_key(DB * file, const DBT * new_key, const DBT * saved_key) {
    ulonglong a = uint5korr((char *) new_key->data);
    ulonglong b = uint5korr((char *) saved_key->data);
    return a < b ? -1 : (a > b ? 1 : 0);
}

Yoni Fogel's avatar
Yoni Fogel committed
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
/*
    Things that are required for ALL data types:
        key_part->field->null_bit
        key_part->length
        key_part->field->packed_col_length(...)
            DEFAULT: virtual uint packed_col_length(const uchar *to, uint length)
                { return length;}
            All integer types use this.
            String types MIGHT use different one, espescially the varchars
        key_part->field->pack_cmp(...)
            DEFAULT: virtual int pack_cmp(...)
                { return cmp(a,b); }
            All integer types use the obvious one.
            Assume X byte bytestream, int =:
            ((u_int64_t)((u_int8_t)bytes[0])) << 0 | 
            ((u_int64_t)((u_int8_t)bytes[1])) << 8 | 
            ((u_int64_t)((u_int8_t)bytes[2])) << 16 | 
            ((u_int64_t)((u_int8_t)bytes[3])) << 24 | 
            ((u_int64_t)((u_int8_t)bytes[4])) << 32 | 
            ((u_int64_t)((u_int8_t)bytes[5])) << 40 | 
            ((u_int64_t)((u_int8_t)bytes[6])) << 48 | 
            ((u_int64_t)((u_int8_t)bytes[7])) << 56
            If the integer type is < 8 bytes, just skip the unneeded ones.
            Then compare the integers in the obvious way.
        Strings:
            Empty space differences at end are ignored.
            i.e. delete all empty space at end first, and then compare.
    Possible prerequisites:
        key_part->field->cmp
            NO DEFAULT
*/

typedef enum {
    TOKUTRACE_SIGNED_INTEGER   = 0,
    TOKUTRACE_UNSIGNED_INTEGER = 1,
    TOKUTRACE_CHAR = 2
} tokutrace_field_type;

typedef struct {
    tokutrace_field_type    type;
    bool                    null_bit;
    u_int32_t               length;
} tokutrace_field;

typedef struct {
    u_int16_t           version;
    u_int32_t           num_fields;
    tokutrace_field     fields[0];
} tokutrace_cmp_fun;

static int tokutrace_db_get_cmp_byte_stream(DB* db, DBT* byte_stream) {
    int r      = ENOSYS;
    void* data = NULL;
    KEY* key   = NULL;
    if (byte_stream->flags != DB_DBT_MALLOC) { return EINVAL; }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
804
    bzero((void *) byte_stream, sizeof(*byte_stream));
Yoni Fogel's avatar
Yoni Fogel committed
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 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 860 861 862 863 864 865 866 867 868

    u_int32_t num_fields = 0;
    if (!db->app_private) { num_fields = 1; }
    else {
        key = (KEY*)db->app_private;
        num_fields = key->key_parts;
    }
    size_t need_size = sizeof(tokutrace_cmp_fun) +
                       num_fields * sizeof(tokutrace_field);

    data = my_malloc(need_size, MYF(MY_FAE | MY_ZEROFILL | MY_WME));
    if (!data) { return ENOMEM; }

    tokutrace_cmp_fun* info = (tokutrace_cmp_fun*)data;
    info->version     = 1;
    info->num_fields  = num_fields;
    
    if (!db->app_private) {
        info->fields[0].type     = TOKUTRACE_UNSIGNED_INTEGER;
        info->fields[0].null_bit = false;
        info->fields[0].length   = 40 / 8;
        goto finish;
    }
    assert(db->app_private);
    assert(key);
    u_int32_t i;
    for (i = 0; i < num_fields; i++) {
        info->fields[i].null_bit = key->key_part[i].null_bit;
        info->fields[i].length   = key->key_part[i].length;
        enum_field_types type    = key->key_part[i].field->type();
        switch (type) {
#ifdef HAVE_LONG_LONG
            case (MYSQL_TYPE_LONGLONG):
#endif
            case (MYSQL_TYPE_LONG):
            case (MYSQL_TYPE_INT24):
            case (MYSQL_TYPE_SHORT):
            case (MYSQL_TYPE_TINY): {
                /* Integer */
                Field_num* field = static_cast<Field_num*>(key->key_part[i].field);
                if (field->unsigned_flag) {
                    info->fields[i].type = TOKUTRACE_UNSIGNED_INTEGER; }
                else {
                    info->fields[i].type = TOKUTRACE_SIGNED_INTEGER; }
                break;
            }
            default: {
                fprintf(stderr, "Cannot save cmp function for type %d.\n", type);
                r = ENOSYS;
                goto cleanup;
            }
        }
    }
finish:
    byte_stream->data = data;
    byte_stream->size = need_size;
    r = 0;
cleanup:
    if (r!=0) {
        if (data) { my_free(data, MYF(0)); }
    }
    return r;
}

869
static int tokudb_compare_two_keys(KEY *key, const DBT * new_key, const DBT * saved_key, bool cmp_prefix) {
870 871 872 873
    uchar *new_key_ptr = (uchar *) new_key->data;
    uchar *saved_key_ptr = (uchar *) saved_key->data;
    KEY_PART_INFO *key_part = key->key_part, *end = key_part + key->key_parts;
    uint key_length = new_key->size;
874
    uint saved_key_length = saved_key->size;
875 876

    //DBUG_DUMP("key_in_index", saved_key_ptr, saved_key->size);
877
    for (; key_part != end && (int) key_length > 0 && (int) saved_key_length > 0; key_part++) {
878
        int cmp;
Yoni Fogel's avatar
Yoni Fogel committed
879 880
        uint new_key_field_length;
        uint saved_key_field_length;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
881
        if (key_part->field->null_bit) {
Yoni Fogel's avatar
Yoni Fogel committed
882
            assert(new_key_ptr   < (uchar *) new_key->data   + new_key->size);
883
            assert(saved_key_ptr < (uchar *) saved_key->data + saved_key->size);
Yoni Fogel's avatar
Yoni Fogel committed
884 885 886
            if (*new_key_ptr != *saved_key_ptr) {
                return ((int) *new_key_ptr - (int) *saved_key_ptr); }
            saved_key_ptr++;
887
            key_length--;
888
            saved_key_length--;
Yoni Fogel's avatar
Yoni Fogel committed
889
            if (!*new_key_ptr++) { continue; }
890
        }
Yoni Fogel's avatar
Yoni Fogel committed
891 892 893 894
        new_key_field_length     = key_part->field->packed_col_length(new_key_ptr,   key_part->length);
        saved_key_field_length   = key_part->field->packed_col_length(saved_key_ptr, key_part->length);
        assert(      key_length >= new_key_field_length);
        assert(saved_key_length >= saved_key_field_length);
895 896
        if ((cmp = key_part->field->pack_cmp(new_key_ptr, saved_key_ptr, key_part->length, 0)))
            return cmp;
Yoni Fogel's avatar
Yoni Fogel committed
897 898 899 900
        new_key_ptr      += new_key_field_length;
        key_length       -= new_key_field_length;
        saved_key_ptr    += saved_key_field_length;
        saved_key_length -= saved_key_field_length;
901
    }
902
    return cmp_prefix ? 0 : key_length - saved_key_length;
903 904
}

905
static int tokudb_cmp_packed_key(DB *file, const DBT *keya, const DBT *keyb) {
906 907
    assert(file->app_private != 0);
    KEY *key = (KEY *) file->app_private;
908 909
    return tokudb_compare_two_keys(key, keya, keyb, false);
}
910

911 912 913 914 915 916 917 918 919 920 921
static int tokudb_cmp_primary_key(DB *file, const DBT *keya, const DBT *keyb) {
    assert(file->app_private != 0);
    KEY *key = (KEY *) file->api_internal;
    return tokudb_compare_two_keys(key, keya, keyb, false);
}

//TODO: QQQ Only do one direction for prefix.
static int tokudb_prefix_cmp_packed_key(DB *file, const DBT *keya, const DBT *keyb) {
    assert(file->app_private != 0);
    KEY *key = (KEY *) file->app_private;
    return tokudb_compare_two_keys(key, keya, keyb, true);
922 923
}

924
#if 0
925
/* Compare key against row */
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
static bool tokudb_key_cmp(TABLE * table, KEY * key_info, const uchar * key, uint key_length) {
    KEY_PART_INFO *key_part = key_info->key_part, *end = key_part + key_info->key_parts;

    for (; key_part != end && (int) key_length > 0; key_part++) {
        int cmp;
        uint length;
        if (key_part->null_bit) {
            key_length--;
            /*
               With the current usage, the following case will always be FALSE,
               because NULL keys are sorted before any other key
             */
            if (*key != (table->record[0][key_part->null_offset] & key_part->null_bit) ? 0 : 1)
                return 1;
            if (!*key++)        // Null value
                continue;
        }
        /*
           Last argument has to be 0 as we are also using this to function to see
           if a key like 'a  ' matched a row with 'a'
         */
        if ((cmp = key_part->field->pack_cmp(key, key_part->length, 0)))
            return cmp;
        length = key_part->field->packed_col_length(key, key_part->length);
        key += length;
        key_length -= length;
952
    }
953 954
    return 0;                   // Identical keys
}
955
#endif
956

Zardosht Kasheff's avatar
Zardosht Kasheff committed
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
//
// Open a secondary table, the key will be a secondary index, the data will be a primary key
//
int ha_tokudb::open_secondary_table(DB** ptr, KEY* key_info, const char* name, int mode, u_int32_t* key_type) {
    int error = ENOSYS;
    char part[MAX_ALIAS_NAME + 10];
    char name_buff[FN_REFLEN];
    uint open_flags = (mode == O_RDONLY ? DB_RDONLY : 0) | DB_THREAD;
    char newname[strlen(name) + 32];
    DBT cmp_byte_stream;

    if (tokudb_init_flags & DB_INIT_TXN)
        open_flags += DB_AUTO_COMMIT;

    if ((error = db_create(ptr, db_env, 0))) {
        my_errno = error;
        goto cleanup;
    }
    sprintf(part, "key-%s", key_info->name);
    make_name(newname, name, part);
    fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);
    *key_type = key_info->flags & HA_NOSAME ? DB_NOOVERWRITE : DB_YESOVERWRITE;
    (*ptr)->app_private = (void *) (key_info);
    if (tokudb_debug & TOKUDB_DEBUG_SAVE_TRACE) {
        bzero((void *) &cmp_byte_stream, sizeof(cmp_byte_stream));
        cmp_byte_stream.flags = DB_DBT_MALLOC;
        if ((error = tokutrace_db_get_cmp_byte_stream(*ptr, &cmp_byte_stream))) {
            my_errno = error;
            goto cleanup;
        }
        (*ptr)->set_bt_compare(*ptr, tokudb_cmp_packed_key);
        my_free(cmp_byte_stream.data, MYF(0));
    }
    else
        (*ptr)->set_bt_compare(*ptr, tokudb_cmp_packed_key);    
    if (!(key_info->flags & HA_NOSAME)) {
        DBUG_PRINT("info", ("Setting DB_DUP+DB_DUPSORT for key %s\n", key_info->name));
        (*ptr)->set_flags(*ptr, DB_DUP + DB_DUPSORT);
        (*ptr)->api_internal = share->file->app_private;
        (*ptr)->set_dup_compare(*ptr, hidden_primary_key ? tokudb_cmp_hidden_key : tokudb_cmp_primary_key);
    }
    if ((error = (*ptr)->open(*ptr, 0, name_buff, NULL, DB_BTREE, open_flags, 0))) {
        my_errno = error;
        goto cleanup;
    }
    if (tokudb_debug & TOKUDB_DEBUG_OPEN) {
        TOKUDB_TRACE("open:%s:file=%p\n", newname, *ptr);
    }
cleanup:
    return error;
}



Zardosht Kasheff's avatar
Zardosht Kasheff committed
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
//
// Creates and opens a handle to a table which already exists in a tokudb
// database.
// Parameters:
//      [in]   name - table name
//             mode - seems to specify if table is read only
//             test_if_locked - unused
// Returns:
//      0 on success
//      1 on error
//
1022
int ha_tokudb::open(const char *name, int mode, uint test_if_locked) {
1023
    TOKUDB_DBUG_ENTER("ha_tokudb::open %p %s", this, name);
1024 1025 1026
    TOKUDB_OPEN();

    char name_buff[FN_REFLEN];
1027
    uint open_flags = (mode == O_RDONLY ? DB_RDONLY : 0) | DB_THREAD;
1028 1029 1030
    uint max_key_length;
    int error;

1031 1032 1033
    if (tokudb_init_flags & DB_INIT_TXN)
        open_flags += DB_AUTO_COMMIT;

1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
    /* Open primary key */
    hidden_primary_key = 0;
    if ((primary_key = table_share->primary_key) >= MAX_KEY) {
        // No primary key
        primary_key = table_share->keys;
        key_used_on_scan = MAX_KEY;
        ref_length = hidden_primary_key = TOKUDB_HIDDEN_PRIMARY_KEY_LENGTH;
    } else
        key_used_on_scan = primary_key;

    /* Need some extra memory in case of packed keys */
    max_key_length = table_share->max_key_length + MAX_REF_PARTS * 3;
    if (!(alloc_ptr =
          my_multi_malloc(MYF(MY_WME),
1048 1049 1050 1051
                          &key_buff, max_key_length, 
                          &key_buff2, max_key_length, 
                          &primary_key_buff, (hidden_primary_key ? 0 : table_share->key_info[table_share->primary_key].key_length), 
                          NullS)))
1052
        TOKUDB_DBUG_RETURN(1);
1053 1054
    if (!(rec_buff = (uchar *) my_malloc((alloced_rec_buff_length = table_share->rec_buff_length), MYF(MY_WME)))) {
        my_free(alloc_ptr, MYF(0));
1055
        TOKUDB_DBUG_RETURN(1);
1056 1057 1058 1059 1060 1061
    }

    /* Init shared structure */
    if (!(share = get_share(name, table))) {
        my_free((char *) rec_buff, MYF(0));
        my_free(alloc_ptr, MYF(0));
1062
        TOKUDB_DBUG_RETURN(1);
1063 1064 1065 1066 1067 1068
    }
    thr_lock_data_init(&share->lock, &lock, NULL);
    bzero((void *) &current_row, sizeof(current_row));

    /* Fill in shared structure, if needed */
    pthread_mutex_lock(&share->mutex);
Rich Prohaska's avatar
Rich Prohaska committed
1069
    if (tokudb_debug & TOKUDB_DEBUG_OPEN)
1070 1071
        TOKUDB_TRACE("tokudbopen:%p:share=%p:file=%p:table=%p:table->s=%p:%d\n", 
                     this, share, share->file, table, table->s, share->use_count);
1072 1073
    if (!share->use_count++) {
        DBUG_PRINT("info", ("share->use_count %u", share->use_count));
Yoni Fogel's avatar
Yoni Fogel committed
1074
        DBT cmp_byte_stream;
1075

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1076
        if ((error = db_create(&share->file, db_env, 0))) {
1077 1078 1079 1080
            free_share(share, table, hidden_primary_key, 1);
            my_free((char *) rec_buff, MYF(0));
            my_free(alloc_ptr, MYF(0));
            my_errno = error;
1081
            TOKUDB_DBUG_RETURN(1);
1082 1083 1084
        }

        if (!hidden_primary_key)
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1085
            share->file->app_private = (void *) (table_share->key_info + table_share->primary_key);
Yoni Fogel's avatar
Yoni Fogel committed
1086 1087 1088
        if (tokudb_debug & TOKUDB_DEBUG_SAVE_TRACE) {
            bzero((void *) &cmp_byte_stream, sizeof(cmp_byte_stream));
            cmp_byte_stream.flags = DB_DBT_MALLOC;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1089
            if ((error = tokutrace_db_get_cmp_byte_stream(share->file, &cmp_byte_stream))) {
Yoni Fogel's avatar
Yoni Fogel committed
1090 1091 1092 1093 1094 1095
                free_share(share, table, hidden_primary_key, 1);
                my_free((char *) rec_buff, MYF(0));
                my_free(alloc_ptr, MYF(0));
                my_errno = error;
                TOKUDB_DBUG_RETURN(1);
            }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1096
            share->file->set_bt_compare(share->file, (hidden_primary_key ? tokudb_cmp_hidden_key : tokudb_cmp_packed_key));
Yoni Fogel's avatar
Yoni Fogel committed
1097 1098 1099
            my_free(cmp_byte_stream.data, MYF(0));
        }
        else
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1100
            share->file->set_bt_compare(share->file, (hidden_primary_key ? tokudb_cmp_hidden_key : tokudb_cmp_packed_key));
Yoni Fogel's avatar
Yoni Fogel committed
1101
        
1102
        char newname[strlen(name) + 32];
1103 1104
        make_name(newname, name, "main");
        fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1105
        if ((error = share->file->open(share->file, 0, name_buff, NULL, DB_BTREE, open_flags, 0))) {
1106 1107 1108 1109
            free_share(share, table, hidden_primary_key, 1);
            my_free((char *) rec_buff, MYF(0));
            my_free(alloc_ptr, MYF(0));
            my_errno = error;
1110
            TOKUDB_DBUG_RETURN(1);
1111
        }
Rich Prohaska's avatar
Rich Prohaska committed
1112
        if (tokudb_debug & TOKUDB_DEBUG_OPEN)
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1113
            TOKUDB_TRACE("open:%s:file=%p\n", newname, share->file);
1114 1115

        /* Open other keys;  These are part of the share structure */
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1116 1117
        share->key_file[primary_key] = share->file;
        share->key_type[primary_key] = hidden_primary_key ? 0 : DB_NOOVERWRITE;
1118

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1119 1120
        DB **ptr = share->key_file;
        for (uint i = 0; i < table_share->keys; i++, ptr++) {
1121
            if (i != primary_key) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1122
                if ((error = open_secondary_table(ptr,&table_share->key_info[i],name,mode,&share->key_type[i]))) {
1123
                    __close(1);
1124
                    TOKUDB_DBUG_RETURN(1);
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
                }
            }
        }
        /* Calculate pack_length of primary key */
        share->fixed_length_primary_key = 1;
        if (!hidden_primary_key) {
            ref_length = 0;
            KEY_PART_INFO *key_part = table->key_info[primary_key].key_part;
            KEY_PART_INFO *end = key_part + table->key_info[primary_key].key_parts;
            for (; key_part != end; key_part++)
                ref_length += key_part->field->max_packed_col_length(key_part->length);
            share->fixed_length_primary_key = (ref_length == table->key_info[primary_key].key_length);
            share->status |= STATUS_PRIMARY_KEY_INIT;
        }
        share->ref_length = ref_length;
    }
    ref_length = share->ref_length;     // If second open
    pthread_mutex_unlock(&share->mutex);

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1144 1145 1146
    transaction = NULL;
    cursor = NULL;
    key_read = false;
1147
    stats.block_size = 1<<20;    // QQQ Tokudb DB block size
1148 1149
    share->fixed_length_row = !(table_share->db_create_options & HA_OPTION_PACK_RECORD);

1150
    // QQQ what happens if get_status fails
1151 1152 1153
    get_status();
    info(HA_STATUS_NO_LOCK | HA_STATUS_VARIABLE | HA_STATUS_CONST);

1154
    TOKUDB_DBUG_RETURN(0);
1155 1156
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1157 1158 1159
//
// Closes a handle to a table. 
//
1160
int ha_tokudb::close(void) {
1161
    TOKUDB_DBUG_ENTER("ha_tokudb::close %p", this);
1162
    TOKUDB_CLOSE();
1163
    TOKUDB_DBUG_RETURN(__close(0));
1164 1165 1166
}

int ha_tokudb::__close(int mutex_is_locked) {
1167
    TOKUDB_DBUG_ENTER("ha_tokudb::__close %p", this);
1168
    if (tokudb_debug & TOKUDB_DEBUG_OPEN) 
1169
        TOKUDB_TRACE("close:%p\n", this);
1170 1171 1172
    my_free(rec_buff, MYF(MY_ALLOW_ZERO_PTR));
    my_free(alloc_ptr, MYF(MY_ALLOW_ZERO_PTR));
    ha_tokudb::reset();         // current_row buffer
1173
    TOKUDB_DBUG_RETURN(free_share(share, table, hidden_primary_key, mutex_is_locked));
1174 1175
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1176 1177 1178 1179 1180 1181
//
// Reallocate record buffer (rec_buff) if needed
// If not needed, does nothing
// Parameters:
//          length - size of buffer required for rec_buff
//
1182 1183 1184 1185 1186 1187 1188 1189 1190
bool ha_tokudb::fix_rec_buff_for_blob(ulong length) {
    if (!rec_buff || length > alloced_rec_buff_length) {
        uchar *newptr;
        if (!(newptr = (uchar *) my_realloc((void *) rec_buff, length, MYF(MY_ALLOW_ZERO_PTR))))
            return 1;
        rec_buff = newptr;
        alloced_rec_buff_length = length;
    }
    return 0;
1191 1192 1193
}

/* Calculate max length needed for row */
1194 1195 1196 1197 1198
ulong ha_tokudb::max_row_length(const uchar * buf) {
    ulong length = table_share->reclength + table_share->fields * 2;
    uint *ptr, *end;
    for (ptr = table_share->blob_field, end = ptr + table_share->blob_fields; ptr != end; ptr++) {
        Field_blob *blob = ((Field_blob *) table->field[*ptr]);
1199
        length += blob->get_length((uchar *) (buf + field_offset(blob))) + 2;
1200 1201
    }
    return length;
1202 1203 1204 1205
}

/*
*/
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
//
// take the row passed in as a DBT*, and convert it into a row in MySQL format in record
// Pack a row for storage.
// If the row is of fixed length, just store the  row 'as is'.
// If not, we will generate a packed row suitable for storage.
// This will only fail if we don't have enough memory to pack the row,
// which may only happen in rows with blobs, as the default row length is
// pre-allocated.
// Parameters:
//      [out]   row - row stored in DBT to be converted
//      [in]    record - row in MySQL format
//
1218

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1219
int ha_tokudb::pack_row(DBT * row, const uchar * record) {
1220 1221 1222 1223
    uchar *ptr;
    bzero((void *) row, sizeof(*row));
    if (share->fixed_length_row) {
        row->data = (void *) record;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1224
        row->size = table_share->reclength;
1225
        return 0;
1226
    }
1227 1228 1229 1230 1231
    if (table_share->blob_fields) {
        if (fix_rec_buff_for_blob(max_row_length(record)))
            return HA_ERR_OUT_OF_MEM;
    }

1232
    /* Copy null bits */
1233 1234 1235
    memcpy(rec_buff, record, table_share->null_bytes);
    ptr = rec_buff + table_share->null_bytes;

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1236
    for (Field ** field = table->field; *field; field++) {
1237
        ptr = (*field)->pack(ptr, (const uchar *)
1238
                             (record + field_offset(*field)));
1239
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1240

1241 1242 1243 1244 1245
    row->data = rec_buff;
    row->size = (size_t) (ptr - rec_buff);
    return 0;
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1246 1247 1248 1249 1250 1251
//
// take the row passed in as a DBT*, and convert it into a row in MySQL format in record
// Parameters:
//      [out]   record - row in MySQL format
//      [in]    row - row stored in DBT to be converted
//
1252 1253
void ha_tokudb::unpack_row(uchar * record, DBT * row) {
    if (share->fixed_length_row)
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1254
        memcpy(record, (void *) row->data, table_share->reclength);
1255 1256 1257 1258 1259 1260 1261
    else {
        /* Copy null bits */
        my_bitmap_map *old_map = dbug_tmp_use_all_columns(table, table->write_set);
        const uchar *ptr = (const uchar *) row->data;
        memcpy(record, ptr, table_share->null_bytes);
        ptr += table_share->null_bytes;
        for (Field ** field = table->field; *field; field++)
1262
            ptr = (*field)->unpack(record + field_offset(*field), ptr);
1263 1264
        dbug_tmp_restore_column_map(table->write_set, old_map);
    }
1265 1266
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1267 1268 1269 1270 1271 1272 1273 1274
//
// Store the key and the primary key into the row
// Parameters:
//      [out]   record - key stored in MySQL format
//      [in]    key - key stored in DBT to be converted
//              index -index into key_file that represents the DB 
//                  unpacking a key of
//
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
void ha_tokudb::unpack_key(uchar * record, DBT * key, uint index) {
    KEY *key_info = table->key_info + index;
    KEY_PART_INFO *key_part = key_info->key_part, *end = key_part + key_info->key_parts;
    uchar *pos = (uchar *) key->data;

    for (; key_part != end; key_part++) {
        if (key_part->null_bit) {
            if (!*pos++) {        // Null value
                /*
                   We don't need to reset the record data as we will not access it
                   if the null data is set
                 */
                record[key_part->null_offset] |= key_part->null_bit;
                continue;
            }
            record[key_part->null_offset] &= ~key_part->null_bit;
        }
1292 1293 1294 1295 1296 1297 1298
        /* tokutek change to make pack_key and unpack_key work for
           decimals */
        uint unpack_length = key_part->length;
        if (key_part->field->type() == MYSQL_TYPE_NEWDECIMAL) {
            Field_new_decimal *field_nd = (Field_new_decimal *) key_part->field;
            unpack_length += field_nd->precision << 8;
        }
1299
        pos = (uchar *) key_part->field->unpack_key(record + field_offset(key_part->field), pos,
1300
#if MYSQL_VERSION_ID < 50123
1301
                                                    unpack_length);
1302
#else
1303
                                                    unpack_length, table->s->db_low_byte_first);
1304
#endif
1305
    }
1306 1307
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1308

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1309 1310 1311 1312 1313
//
// Create a packed key from a row. This key will be written as such
// to the index tree.  This will never fail as the key buffer is pre-allocated.
// Parameters:
//      [out]   key - DBT that holds the key
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1314
//      [in]    key_info - holds data about the key, such as it's length and offset into record
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1315 1316 1317 1318 1319 1320 1321
//      [out]   buff - buffer that will hold the data for key (unless 
//                  we have a hidden primary key)
//      [in]    record - row from which to create the key
//              key_length - currently set to MAX_KEY_LENGTH, is it size of buff?
// Returns:
//      the parameter key
//
1322

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1323
DBT* ha_tokudb::create_dbt_key_from_key(DBT * key, KEY* key_info, uchar * buff, const uchar * record, int key_length) {
1324 1325 1326 1327 1328 1329
    KEY_PART_INFO *key_part = key_info->key_part;
    KEY_PART_INFO *end = key_part + key_info->key_parts;
    my_bitmap_map *old_map = dbug_tmp_use_all_columns(table, table->write_set);

    key->data = buff;
    for (; key_part != end && key_length > 0; key_part++) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1330 1331 1332 1333 1334 1335
        //
        // accessing key_part->field->null_bit instead off key_part->null_bit
        // because key_part->null_bit is not set in add_index
        // filed ticket 862 to look into this
        //
        if (key_part->field->null_bit) {
1336
            /* Store 0 if the key part is a NULL part */
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1337
            if (record[key_part->null_offset] & key_part->field->null_bit) {
1338
                *buff++ = 0;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1339 1340 1341 1342 1343
                //
                // fractal tree does not handle this falg at the moment
                // so commenting out for now
                //
                //key->flags |= DB_DBT_DUPOK;
1344 1345 1346 1347
                continue;
            }
            *buff++ = 1;        // Store NOT NULL marker
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1348 1349 1350 1351 1352 1353
        //
        // accessing field_offset(key_part->field) instead off key_part->offset
        // because key_part->offset is SET INCORRECTLY in add_index
        // filed ticket 862 to look into this
        //
        buff = key_part->field->pack_key(buff, (uchar *) (record + field_offset(key_part->field)),
1354
#if MYSQL_VERSION_ID < 50123
1355
                                         key_part->length);
1356
#else
1357
                                         key_part->length, table->s->db_low_byte_first);
1358
#endif
1359 1360 1361 1362 1363
        key_length -= key_part->length;
    }
    key->size = (buff - (uchar *) key->data);
    DBUG_DUMP("key", (uchar *) key->data, key->size);
    dbug_tmp_restore_column_map(table->write_set, old_map);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
    return key;
}


//
// Create a packed key from a row. This key will be written as such
// to the index tree.  This will never fail as the key buffer is pre-allocated.
// Parameters:
//      [out]   key - DBT that holds the key
//              keynr - index for which to create the key
//      [out]   buff - buffer that will hold the data for key (unless 
//                  we have a hidden primary key)
//      [in]    record - row from which to create the key
//              key_length - currently set to MAX_KEY_LENGTH, is it size of buff?
// Returns:
//      the parameter key
//
DBT *ha_tokudb::create_dbt_key_from_table(DBT * key, uint keynr, uchar * buff, const uchar * record, int key_length) {
    TOKUDB_DBUG_ENTER("ha_tokudb::create_dbt_key_from_table");
    bzero((void *) key, sizeof(*key));
    if (hidden_primary_key && keynr == primary_key) {
        key->data = current_ident;
        key->size = TOKUDB_HIDDEN_PRIMARY_KEY_LENGTH;
        DBUG_RETURN(key);
    }
    DBUG_RETURN(create_dbt_key_from_key(key, &table->key_info[keynr],buff,record,key_length));
1390 1391 1392
}


Zardosht Kasheff's avatar
Zardosht Kasheff committed
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
//
// Create a packed key from from a MySQL unpacked key (like the one that is
// sent from the index_read() This key is to be used to read a row
// Parameters:
//      [out]   key - DBT that holds the key
//              keynr - index for which to pack the key
//      [out]   buff - buffer that will hold the data for key
//      [in]    key_ptr - MySQL unpacked key
//              key_length - length of key_ptr
// Returns:
//      the parameter key
//
1405
DBT *ha_tokudb::pack_key(DBT * key, uint keynr, uchar * buff, const uchar * key_ptr, uint key_length) {
1406
    TOKUDB_DBUG_ENTER("ha_tokudb::pack_key");
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
    KEY *key_info = table->key_info + keynr;
    KEY_PART_INFO *key_part = key_info->key_part;
    KEY_PART_INFO *end = key_part + key_info->key_parts;
    my_bitmap_map *old_map = dbug_tmp_use_all_columns(table, table->write_set);

    bzero((void *) key, sizeof(*key));
    key->data = buff;

    for (; key_part != end && (int) key_length > 0; key_part++) {
        uint offset = 0;
        if (key_part->null_bit) {
            if (!(*buff++ = (*key_ptr == 0)))   // Store 0 if NULL
            {
                key_length -= key_part->store_length;
                key_ptr += key_part->store_length;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1422 1423 1424 1425 1426
                //
                // fractal tree does not handle this falg at the moment
                // so commenting out for now
                //
                //key->flags |= DB_DBT_DUPOK;
1427 1428 1429 1430 1431
                continue;
            }
            offset = 1;         // Data is at key_ptr+1
        }
        buff = key_part->field->pack_key_from_key_image(buff, (uchar *) key_ptr + offset,
1432
#if MYSQL_VERSION_ID < 50123
1433
                                                        key_part->length);
1434
#else
1435
                                                        key_part->length, table->s->db_low_byte_first);
1436
#endif
1437 1438 1439 1440 1441 1442 1443
        key_ptr += key_part->store_length;
        key_length -= key_part->store_length;
    }
    key->size = (buff - (uchar *) key->data);
    DBUG_DUMP("key", (uchar *) key->data, key->size);
    dbug_tmp_restore_column_map(table->write_set, old_map);
    DBUG_RETURN(key);
1444 1445
}

1446
int ha_tokudb::read_last() {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1447
    TOKUDB_DBUG_ENTER("ha_tokudb::read_last");
1448
    int do_commit = 0;
1449
    if (transaction == NULL && (tokudb_init_flags & DB_INIT_TXN)) {
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
        int r = db_env->txn_begin(db_env, 0, &transaction, 0);
        assert(r == 0);
        do_commit = 1;
    }
    int error = index_init(primary_key, 0);
    if (error == 0)
        error = index_last(table->record[1]);
    index_end();
    if (do_commit) {
        int r = transaction->commit(transaction, 0);
        assert(r == 0);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1461
        transaction = NULL;
1462
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1463
    TOKUDB_DBUG_RETURN(error);
1464 1465
}

1466 1467 1468 1469
/** @brief
    Get status information that is stored in the 'status' sub database
    and the max used value for the hidden primary key.
*/
1470
void ha_tokudb::get_status() {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1471
    TOKUDB_DBUG_ENTER("ha_tokudb::get_status");
1472

1473 1474
    if (!test_all_bits(share->status, (STATUS_PRIMARY_KEY_INIT | STATUS_ROW_COUNT_INIT))) {
        pthread_mutex_lock(&share->mutex);
1475 1476 1477 1478 1479
        if (!(share->status & STATUS_PRIMARY_KEY_INIT)) {
            (void) extra(HA_EXTRA_KEYREAD);
            int error = read_last();
            (void) extra(HA_EXTRA_NO_KEYREAD);
            if (error == 0) {
1480
                share->auto_ident = uint5korr(current_ident);
1481

1482 1483 1484 1485 1486 1487 1488
                // mysql may not initialize the next_number_field here
                // so we do this in the get_auto_increment method
                // index_last uses record[1]
                assert(table->next_number_field == 0);
                if (table->next_number_field) {
                    share->last_auto_increment = table->next_number_field->val_int_offset(table->s->rec_buff_length);
                    if (tokudb_debug & TOKUDB_DEBUG_AUTO_INCREMENT) 
1489
                        TOKUDB_TRACE("init auto increment:%lld\n", share->last_auto_increment);
1490
                }
1491
            }
1492
        }
1493

1494 1495
        if (!share->status_block) {
            char name_buff[FN_REFLEN];
1496 1497 1498
            char newname[get_name_length(share->table_name) + 32];
            make_name(newname, share->table_name, "status");
            fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);
1499 1500
            uint open_mode = (((table->db_stat & HA_READ_ONLY) ? DB_RDONLY : 0)
                              | DB_THREAD);
Rich Prohaska's avatar
Rich Prohaska committed
1501
            if (tokudb_debug & TOKUDB_DEBUG_OPEN)
1502
                TOKUDB_TRACE("open:%s\n", newname);
1503
            if (!db_create(&share->status_block, db_env, 0)) {
1504
                if (share->status_block->open(share->status_block, NULL, name_buff, NULL, DB_BTREE, open_mode, 0)) {
1505 1506 1507 1508 1509
                    share->status_block->close(share->status_block, 0);
                    share->status_block = 0;
                }
            }
        }
1510

1511 1512
        if (!(share->status & STATUS_ROW_COUNT_INIT) && share->status_block) {
            share->org_rows = share->rows = table_share->max_rows ? table_share->max_rows : HA_TOKUDB_MAX_ROWS;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1513
            DB_TXN *transaction = NULL;
1514 1515 1516
            int r = 0;
            if (tokudb_init_flags & DB_INIT_TXN)
                r = db_env->txn_begin(db_env, 0, &transaction, 0);
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
            if (r == 0) {
                r = share->status_block->cursor(share->status_block, transaction, &cursor, 0);
                if (r == 0) {
                    DBT row;
                    char rec_buff[64];
                    bzero((void *) &row, sizeof(row));
                    bzero((void *) &last_key, sizeof(last_key));
                    row.data = rec_buff;
                    row.ulen = sizeof(rec_buff);
                    row.flags = DB_DBT_USERMEM;
                    if (!cursor->c_get(cursor, &last_key, &row, DB_FIRST)) {
                        uint i;
                        uchar *pos = (uchar *) row.data;
                        share->org_rows = share->rows = uint4korr(pos);
1531
                        pos += 4;
1532 1533 1534 1535
                        for (i = 0; i < table_share->keys; i++) {
                            share->rec_per_key[i] = uint4korr(pos);
                            pos += 4;
                        }
1536
                    }
1537
                    cursor->c_close(cursor);
1538
                }
1539 1540 1541
                if (transaction) {
                    r = transaction->commit(transaction, 0);
                }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1542
                transaction = NULL;
1543
            }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1544
            cursor = NULL;
1545 1546 1547 1548
        }
        share->status |= STATUS_PRIMARY_KEY_INIT | STATUS_ROW_COUNT_INIT;
        pthread_mutex_unlock(&share->mutex);
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1549
    DBUG_VOID_RETURN;
1550 1551 1552
}

static int write_status(DB * status_block, char *buff, uint length) {
1553
    TOKUDB_DBUG_ENTER("write_status");
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
    DBT row, key;
    int error;
    const char *key_buff = "status";

    bzero((void *) &row, sizeof(row));
    bzero((void *) &key, sizeof(key));
    row.data = buff;
    key.data = (void *) key_buff;
    key.size = sizeof(key_buff);
    row.size = length;
    error = status_block->put(status_block, 0, &key, &row, 0);
1565
    TOKUDB_DBUG_RETURN(error);
1566 1567 1568
}

static void update_status(TOKUDB_SHARE * share, TABLE * table) {
1569
    TOKUDB_DBUG_ENTER("update_status");
1570 1571 1572 1573 1574 1575 1576 1577 1578
    if (share->rows != share->org_rows || (share->status & STATUS_TOKUDB_ANALYZE)) {
        pthread_mutex_lock(&share->mutex);
        if (!share->status_block) {
            /*
               Create sub database 'status' if it doesn't exist from before
               (This '*should*' always exist for table created with MySQL)
             */

            char name_buff[FN_REFLEN];
1579 1580 1581
            char newname[get_name_length(share->table_name) + 32];
            make_name(newname, share->table_name, "status");
            fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);
1582 1583 1584
            if (db_create(&share->status_block, db_env, 0))
                goto end;
            share->status_block->set_flags(share->status_block, 0);
1585
            if (share->status_block->open(share->status_block, NULL, name_buff, NULL, DB_BTREE, DB_THREAD | DB_CREATE, my_umask))
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
                goto end;
        }
        {
            char rec_buff[4 + MAX_KEY * 4], *pos = rec_buff;
            int4store(pos, share->rows);
            pos += 4;
            for (uint i = 0; i < table->s->keys; i++) {
                int4store(pos, share->rec_per_key[i]);
                pos += 4;
            }
            DBUG_PRINT("info", ("updating status for %s", share->table_name));
            (void) write_status(share->status_block, rec_buff, (uint) (pos - rec_buff));
            share->status &= ~STATUS_TOKUDB_ANALYZE;
            share->org_rows = share->rows;
        }
      end:
        pthread_mutex_unlock(&share->mutex);
    }
    DBUG_VOID_RETURN;
1605 1606 1607 1608 1609
}

/** @brief
    Return an estimated of the number of rows in the table.
    Used when sorting to allocate buffers and by the optimizer.
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1610
    This is used in filesort.cc. 
1611
*/
1612
ha_rows ha_tokudb::estimate_rows_upper_bound() {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1613 1614
    TOKUDB_DBUG_ENTER("ha_tokudb::estimate_rows_upper_bound");
    DBUG_RETURN(share->rows + HA_TOKUDB_EXTRA_ROWS);
1615
}
1616

1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
int ha_tokudb::cmp_ref(const uchar * ref1, const uchar * ref2) {
    if (hidden_primary_key)
        return memcmp(ref1, ref2, TOKUDB_HIDDEN_PRIMARY_KEY_LENGTH);

    int result;
    Field *field;
    KEY *key_info = table->key_info + table_share->primary_key;
    KEY_PART_INFO *key_part = key_info->key_part;
    KEY_PART_INFO *end = key_part + key_info->key_parts;

    for (; key_part != end; key_part++) {
        field = key_part->field;
        result = field->pack_cmp((const uchar *) ref1, (const uchar *) ref2, key_part->length, 0);
        if (result)
            return result;
        ref1 += field->packed_col_length((const uchar *) ref1, key_part->length);
        ref2 += field->packed_col_length((const uchar *) ref2, key_part->length);
    }

    return 0;
1637 1638
}

1639 1640 1641 1642 1643 1644
bool ha_tokudb::check_if_incompatible_data(HA_CREATE_INFO * info, uint table_changes) {
    if (table_changes < IS_EQUAL_YES)
        return COMPATIBLE_DATA_NO;
    return COMPATIBLE_DATA_YES;
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1645 1646 1647 1648 1649 1650 1651 1652
//
// Stores a row in the table, called when handling an INSERT query
// Parameters:
//      [in]    record - a row in MySQL format
// Returns:
//      0 on success
//      error otherwise
//
1653
int ha_tokudb::write_row(uchar * record) {
1654
    TOKUDB_DBUG_ENTER("ha_tokudb::write_row");
1655 1656 1657 1658
    DBT row, prim_key, key;
    int error;

    statistic_increment(table->in_use->status_var.ha_write_count, &LOCK_status);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1659
    if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT) {
1660
        table->timestamp_field->set_time();
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1661 1662
    }
    if (table->next_number_field && record == table->record[0]) {
1663
        update_auto_increment();
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1664 1665
    }
    if ((error = pack_row(&row, (const uchar *) record))){
1666
        TOKUDB_DBUG_RETURN(error);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1667 1668 1669 1670 1671
    }
    
    if (hidden_primary_key) {
        get_auto_primary_key(current_ident);
    }
1672

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1673
    u_int32_t put_flags = share->key_type[primary_key];
1674
    THD *thd = ha_thd();
1675
    if (thd_test_options(thd, OPTION_RELAXED_UNIQUE_CHECKS)) {
1676
        put_flags = DB_YESOVERWRITE;
1677
    }
1678

1679
    if (table_share->keys + test(hidden_primary_key) == 1) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1680
        error = share->file->put(share->file, transaction, create_dbt_key_from_table(&prim_key, primary_key, key_buff, record), &row, put_flags);
1681 1682 1683
        last_dup_key = primary_key;
    } else {
        DB_TXN *sub_trans = transaction;
1684
        /* QQQ Don't use sub transactions in temporary tables */
1685 1686
        for (uint retry = 0; retry < tokudb_trans_retry; retry++) {
            key_map changed_keys(0);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1687
            if (!(error = share->file->put(share->file, sub_trans, create_dbt_key_from_table(&prim_key, primary_key, key_buff, record), &row, put_flags))) {
1688 1689 1690 1691
                changed_keys.set_bit(primary_key);
                for (uint keynr = 0; keynr < table_share->keys; keynr++) {
                    if (keynr == primary_key)
                        continue;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1692
                    put_flags = share->key_type[keynr];
1693 1694
                    if (put_flags == DB_NOOVERWRITE && thd_test_options(thd, OPTION_RELAXED_UNIQUE_CHECKS))
                        put_flags = DB_YESOVERWRITE;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1695
                    if ((error = share->key_file[keynr]->put(share->key_file[keynr], sub_trans, create_dbt_key_from_table(&key, keynr, key_buff2, record), &prim_key, put_flags))) {
1696 1697 1698 1699 1700
                        last_dup_key = keynr;
                        break;
                    }
                    changed_keys.set_bit(keynr);
                }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1701 1702
            } 
            else {
1703
                last_dup_key = primary_key;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1704
            }
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
            if (error) {
                /* Remove inserted row */
                DBUG_PRINT("error", ("Got error %d", error));
                if (using_ignore) {
                    int new_error = 0;
                    if (!changed_keys.is_clear_all()) {
                        new_error = 0;
                        for (uint keynr = 0; keynr < table_share->keys + test(hidden_primary_key); keynr++) {
                            if (changed_keys.is_set(keynr)) {
                                if ((new_error = remove_key(sub_trans, keynr, record, &prim_key)))
                                    break;
                            }
                        }
                    }
                    if (new_error) {
                        error = new_error;      // This shouldn't happen
                        break;
                    }
                }
            }
1725
            if (error != DB_LOCK_DEADLOCK && error != DB_LOCK_NOTGRANTED)
1726 1727
                break;
        }
1728
    }
1729 1730 1731 1732
    if (error == DB_KEYEXIST)
        error = HA_ERR_FOUND_DUPP_KEY;
    else if (!error)
        changed_rows++;
1733
    TOKUDB_DBUG_RETURN(error);
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
}

/* Compare if a key in a row has changed */
int ha_tokudb::key_cmp(uint keynr, const uchar * old_row, const uchar * new_row) {
    KEY_PART_INFO *key_part = table->key_info[keynr].key_part;
    KEY_PART_INFO *end = key_part + table->key_info[keynr].key_parts;

    for (; key_part != end; key_part++) {
        if (key_part->null_bit) {
            if ((old_row[key_part->null_offset] & key_part->null_bit) != (new_row[key_part->null_offset] & key_part->null_bit))
                return 1;
        }
        if (key_part->key_part_flag & (HA_BLOB_PART | HA_VAR_LENGTH_PART)) {

            if (key_part->field->cmp_binary((uchar *) (old_row + key_part->offset), (uchar *) (new_row + key_part->offset), (ulong) key_part->length))
                return 1;
        } else {
            if (memcmp(old_row + key_part->offset, new_row + key_part->offset, key_part->length))
                return 1;
        }
1754
    }
1755
    return 0;
1756 1757 1758 1759 1760 1761 1762
}


/*
  Update a row from one value to another.
  Clobbers key_buff2
*/
1763
int ha_tokudb::update_primary_key(DB_TXN * trans, bool primary_key_changed, const uchar * old_row, DBT * old_key, const uchar * new_row, DBT * new_key, bool local_using_ignore) {
1764
    TOKUDB_DBUG_ENTER("update_primary_key");
1765 1766 1767 1768 1769 1770 1771
    DBT row;
    int error;

    if (primary_key_changed) {
        // Primary key changed or we are updating a key that can have duplicates.
        // Delete the old row and add a new one
        if (!(error = remove_key(trans, primary_key, old_row, old_key))) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1772
            if (!(error = pack_row(&row, new_row))) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1773
                if ((error = share->file->put(share->file, trans, new_key, &row, share->key_type[primary_key]))) {
1774 1775 1776 1777
                    // Probably a duplicated key; restore old key and row if needed
                    last_dup_key = primary_key;
                    if (local_using_ignore) {
                        int new_error;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1778
                        if ((new_error = pack_row(&row, old_row)) || (new_error = share->file->put(share->file, trans, old_key, &row, share->key_type[primary_key])))
1779 1780 1781 1782 1783 1784 1785
                            error = new_error;  // fatal error
                    }
                }
            }
        }
    } else {
        // Primary key didn't change;  just update the row data
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1786
        if (!(error = pack_row(&row, new_row)))
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1787
            error = share->file->put(share->file, trans, new_key, &row, 0);
1788
    }
1789
    TOKUDB_DBUG_RETURN(error);
1790 1791 1792 1793 1794 1795 1796
}

/*
  Restore changed keys, when a non-fatal error aborts the insert/update
  of one row.
  Clobbers keybuff2
*/
1797
int ha_tokudb::restore_keys(DB_TXN * trans, key_map * changed_keys, uint primary_key, const uchar * old_row, DBT * old_key, const uchar * new_row, DBT * new_key) {
1798
    TOKUDB_DBUG_ENTER("restore_keys");
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
    int error;
    DBT tmp_key;
    uint keynr;

    /* Restore the old primary key, and the old row, but don't ignore
       duplicate key failure */
    if ((error = update_primary_key(trans, TRUE, new_row, new_key, old_row, old_key, FALSE)))
        goto err;

    /* Remove the new key, and put back the old key
       changed_keys is a map of all non-primary keys that need to be
       rolled back.  The last key set in changed_keys is the one that
       triggered the duplicate key error (it wasn't inserted), so for
       that one just put back the old value. */
    if (!changed_keys->is_clear_all()) {
        for (keynr = 0; keynr < table_share->keys + test(hidden_primary_key); keynr++) {
            if (changed_keys->is_set(keynr)) {
                if (changed_keys->is_prefix(1) && (error = remove_key(trans, keynr, new_row, new_key)))
                    break;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1818
                if ((error = share->key_file[keynr]->put(share->key_file[keynr], trans, create_dbt_key_from_table(&tmp_key, keynr, key_buff2, old_row), old_key, share->key_type[keynr])))
1819 1820 1821
                    break;
            }
        }
1822
    }
1823 1824 1825

  err:
    DBUG_ASSERT(error != DB_KEYEXIST);
1826
    TOKUDB_DBUG_RETURN(error);
1827 1828
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1829 1830 1831 1832 1833 1834 1835 1836 1837
//
// Updates a row in the table, called when handling an UPDATE query
// Parameters:
//      [in]    old_row - row to be updated, in MySQL format
//      [in]    new_row - new row, in MySQL format
// Returns:
//      0 on success
//      error otherwise
//
1838
int ha_tokudb::update_row(const uchar * old_row, uchar * new_row) {
1839
    TOKUDB_DBUG_ENTER("update_row");
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
    DBT prim_key, key, old_prim_key;
    int error;
    DB_TXN *sub_trans;
    bool primary_key_changed;

    LINT_INIT(error);
    statistic_increment(table->in_use->status_var.ha_update_count, &LOCK_status);
    if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_UPDATE)
        table->timestamp_field->set_time();

    if (hidden_primary_key) {
        primary_key_changed = 0;
        bzero((void *) &prim_key, sizeof(prim_key));
        prim_key.data = (void *) current_ident;
        prim_key.size = TOKUDB_HIDDEN_PRIMARY_KEY_LENGTH;
        old_prim_key = prim_key;
    } else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1857
        create_dbt_key_from_table(&prim_key, primary_key, key_buff, new_row);
1858 1859

        if ((primary_key_changed = key_cmp(primary_key, old_row, new_row)))
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1860
            create_dbt_key_from_table(&old_prim_key, primary_key, primary_key_buff, old_row);
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
        else
            old_prim_key = prim_key;
    }

    sub_trans = transaction;
    for (uint retry = 0; retry < tokudb_trans_retry; retry++) {
        key_map changed_keys(0);
        /* Start by updating the primary key */
        if (!(error = update_primary_key(sub_trans, primary_key_changed, old_row, &old_prim_key, new_row, &prim_key, using_ignore))) {
            // Update all other keys
            for (uint keynr = 0; keynr < table_share->keys; keynr++) {
                if (keynr == primary_key)
                    continue;
                if (key_cmp(keynr, old_row, new_row) || primary_key_changed) {
                    if ((error = remove_key(sub_trans, keynr, old_row, &old_prim_key))) {
1876
                        TOKUDB_DBUG_RETURN(error);     // Fatal error
1877 1878
                    }
                    changed_keys.set_bit(keynr);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1879
                    if ((error = share->key_file[keynr]->put(share->key_file[keynr], sub_trans, create_dbt_key_from_table(&key, keynr, key_buff2, new_row), &prim_key, share->key_type[keynr]))) {
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
                        last_dup_key = keynr;
                        break;
                    }
                }
            }
        }
        if (error) {
            /* Remove inserted row */
            DBUG_PRINT("error", ("Got error %d", error));
            if (using_ignore) {
                int new_error = 0;
                if (!changed_keys.is_clear_all())
                    new_error = restore_keys(transaction, &changed_keys, primary_key, old_row, &old_prim_key, new_row, &prim_key);
                if (new_error) {
                    /* This shouldn't happen */
                    error = new_error;
                    break;
                }
            }
        }
1900
        if (error != DB_LOCK_DEADLOCK && error != DB_LOCK_NOTGRANTED)
1901 1902 1903 1904
            break;
    }
    if (error == DB_KEYEXIST)
        error = HA_ERR_FOUND_DUPP_KEY;
1905
    TOKUDB_DBUG_RETURN(error);
1906 1907
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
//
//
// Delete one key in key_file[keynr]
// This uses key_buff2, when keynr != primary key, so it's important that
// a function that calls this doesn't use this buffer for anything else.
// Parameters:
//      [in]    trans - transaction to be used for the delete
//              keynr - index for which a key needs to be deleted
//      [in]    record - row in MySQL format. Must delete a key for this row
//      [in]    prim_key - key for record in primary table
// Returns:
//      0 on success
//      error otherwise
//
1922
int ha_tokudb::remove_key(DB_TXN * trans, uint keynr, const uchar * record, DBT * prim_key) {
1923
    TOKUDB_DBUG_ENTER("ha_tokudb::remove_key");
1924 1925 1926
    int error;
    DBT key;
    DBUG_PRINT("enter", ("index: %d", keynr));
1927 1928
    DBUG_PRINT("primary", ("index: %d", primary_key));
    DBUG_DUMP("prim_key", (uchar *) prim_key->data, prim_key->size);
1929 1930 1931 1932

    if (keynr == active_index && cursor)
        error = cursor->c_del(cursor, 0);
    else if (keynr == primary_key || ((table->key_info[keynr].flags & (HA_NOSAME | HA_NULL_PART_KEY)) == HA_NOSAME)) {  // Unique key
1933
        DBUG_PRINT("Unique key", ("index: %d", keynr));
1934
        DBUG_ASSERT(keynr == primary_key || prim_key->data != key_buff2);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1935
        error = share->key_file[keynr]->del(share->key_file[keynr], trans, keynr == primary_key ? prim_key : create_dbt_key_from_table(&key, keynr, key_buff2, record), 0);
1936
    } else {
1937
        /* QQQ use toku_db_delboth(key_file[keynr], key, val, trans);
1938 1939 1940 1941 1942 1943
           To delete the not duplicated key, we need to open an cursor on the
           row to find the key to be delete and delete it.
           We will never come here with keynr = primary_key
         */
        DBUG_ASSERT(keynr != primary_key && prim_key->data != key_buff2);
        DBC *tmp_cursor;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1944 1945
        if (!(error = share->key_file[keynr]->cursor(share->key_file[keynr], trans, &tmp_cursor, 0))) {
            if (!(error = tmp_cursor->c_get(tmp_cursor, create_dbt_key_from_table(&key, keynr, key_buff2, record), prim_key, DB_GET_BOTH))) { 
1946
                DBUG_DUMP("cget key", (uchar *) key.data, key.size);
1947 1948 1949 1950 1951 1952 1953
                error = tmp_cursor->c_del(tmp_cursor, 0);
            }
            int result = tmp_cursor->c_close(tmp_cursor);
            if (!error)
                error = result;
        }
    }
1954
    TOKUDB_DBUG_RETURN(error);
1955 1956
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
//
// Delete all keys for new_record
// Parameters:
//      [in]    trans - transaction to be used for the delete
//      [in]    record - row in MySQL format. Must delete all keys for this row
//      [in]    prim_key - key for record in primary table
//      [in]    keys - array that states if a key is set, and hence needs 
//                  removal
// Returns:
//      0 on success
//      error otherwise
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1969
int ha_tokudb::remove_keys(DB_TXN * trans, const uchar * record, DBT * prim_key, key_map * keys) {
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
    int result = 0;
    for (uint keynr = 0; keynr < table_share->keys + test(hidden_primary_key); keynr++) {
        if (keys->is_set(keynr)) {
            int new_error = remove_key(trans, keynr, record, prim_key);
            if (new_error) {
                result = new_error;     // Return last error
                break;          // Let rollback correct things
            }
        }
    }
    return result;
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1983
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1984
// Deletes a row in the table, called when handling a DELETE query
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1985 1986 1987 1988 1989 1990
// Parameters:
//      [in]    record - row to be deleted, in MySQL format
// Returns:
//      0 on success
//      error otherwise
//
1991
int ha_tokudb::delete_row(const uchar * record) {
1992
    TOKUDB_DBUG_ENTER("ha_tokudb::delete_row");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1993 1994
    int error = ENOSYS;
    DBT prim_key;
1995 1996 1997
    key_map keys = table_share->keys_in_use;
    statistic_increment(table->in_use->status_var.ha_delete_count, &LOCK_status);

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1998
    create_dbt_key_from_table(&prim_key, primary_key, key_buff, record);
1999 2000 2001 2002 2003 2004 2005
    if (hidden_primary_key)
        keys.set_bit(primary_key);

    /* Subtransactions may be used in order to retry the delete in
       case we get a DB_LOCK_DEADLOCK error. */
    DB_TXN *sub_trans = transaction;
    for (uint retry = 0; retry < tokudb_trans_retry; retry++) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2006
        error = remove_keys(sub_trans, record, &prim_key, &keys);
2007 2008 2009 2010
        if (error) {
            DBUG_PRINT("error", ("Got error %d", error));
            break;              // No retry - return error
        }
2011
        if (error != DB_LOCK_DEADLOCK && error != DB_LOCK_NOTGRANTED)
2012
            break;
2013 2014
    }
#ifdef CANT_COUNT_DELETED_ROWS
2015 2016
    if (!error)
        changed_rows--;
2017
#endif
2018
    TOKUDB_DBUG_RETURN(error);
2019 2020
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2021 2022 2023 2024 2025 2026 2027 2028 2029
//
// Initializes local cursor on DB with index keynr
// Parameters:
//          keynr - key (index) number
//          sorted - 1 if result MUST be sorted according to index
// Returns:
//      0 on success
//      error otherwise
//
2030
int ha_tokudb::index_init(uint keynr, bool sorted) {
2031
    TOKUDB_DBUG_ENTER("ha_tokudb::index_init %p %d", this, keynr);
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
    int error;
    DBUG_PRINT("enter", ("table: '%s'  key: %d", table_share->table_name.str, keynr));

    /*
       Under some very rare conditions (like full joins) we may already have
       an active cursor at this point
     */
    if (cursor) {
        DBUG_PRINT("note", ("Closing active cursor"));
        cursor->c_close(cursor);
    }
    active_index = keynr;
    DBUG_ASSERT(keynr <= table->s->keys);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2045 2046
    DBUG_ASSERT(share->key_file[keynr]);
    if ((error = share->key_file[keynr]->cursor(share->key_file[keynr], transaction, &cursor, table->reginfo.lock_type > TL_WRITE_ALLOW_READ ? 0 : 0)))
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2047
        cursor = NULL;             // Safety
2048
    bzero((void *) &last_key, sizeof(last_key));
2049
    TOKUDB_DBUG_RETURN(error);
2050 2051
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2052 2053 2054
//
// closes the local cursor
//
2055
int ha_tokudb::index_end() {
2056
    TOKUDB_DBUG_ENTER("ha_tokudb::index_end %p", this);
2057 2058 2059 2060
    int error = 0;
    if (cursor) {
        DBUG_PRINT("enter", ("table: '%s'", table_share->table_name.str));
        error = cursor->c_close(cursor);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2061
        cursor = NULL;
2062
    }
2063
    active_index = MAX_KEY;
2064
    TOKUDB_DBUG_RETURN(error);
2065 2066
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
//
// The funtion read_row checks whether the row was obtained from the primary table or 
// from an index table. If it was obtained from an index table, it further dereferences on
// the main table. In the end, the read_row function will manage to return the actual row
// of interest in the buf parameter.
//
// Parameters:
//              error - result of preceding DB call
//      [out]   buf - buffer for the row, in MySQL format
//              keynr - index into key_file that represents DB we are currently operating on.
//      [in]    row - the row that has been read from the preceding DB call
//      [in]    found_key - key used to retrieve the row
//              read_next - if true, DB_NOTFOUND and DB_KEYEMPTY map to HA_ERR_END_OF_FILE, 
//                  else HA_ERR_KEY_NOT_FOUND, this is a bad parameter to have and this funcitonality
//                  should not be here
//
2083
int ha_tokudb::read_row(int error, uchar * buf, uint keynr, DBT * row, DBT * found_key, bool read_next) {
2084
    TOKUDB_DBUG_ENTER("ha_tokudb::read_row");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2085 2086 2087
    //
    // Disreputable error translation: this makes us all puke
    //
2088 2089 2090 2091
    if (error) {
        if (error == DB_NOTFOUND || error == DB_KEYEMPTY)
            error = read_next ? HA_ERR_END_OF_FILE : HA_ERR_KEY_NOT_FOUND;
        table->status = STATUS_NOT_FOUND;
2092
        TOKUDB_DBUG_RETURN(error);
2093
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2094
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2095
    // extract hidden primary key to current_ident
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2096 2097
    //
    if (hidden_primary_key) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2098 2099 2100 2101 2102 2103
        if (keynr == primary_key) {
            memcpy_fixed(current_ident, (char *) found_key->data, TOKUDB_HIDDEN_PRIMARY_KEY_LENGTH);
        }
        else {
            memcpy_fixed(current_ident, (char *) row->data, TOKUDB_HIDDEN_PRIMARY_KEY_LENGTH);
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2104
    }
2105
    table->status = 0;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2106 2107 2108 2109 2110 2111 2112 2113
    //
    // if the index shows that the table we read the row from was indexed on the primary key,
    // that means we have our row and can skip
    // this entire if clause. All that is required is to unpack row.
    // if the index shows that what we read was from a table that was NOT indexed on the 
    // primary key, then we must still retrieve the row, as the "row" value is indeed just
    // a primary key, whose row we must still read
    //
2114 2115
    if (keynr != primary_key) {
        if (key_read && found_key) {
2116
            // TOKUDB_DBUG_DUMP("key=", found_key->data, found_key->size);
2117
            unpack_key(buf, found_key, keynr);
2118
            if (!hidden_primary_key) {
2119
                // TOKUDB_DBUG_DUMP("row=", row->data, row->size);
2120
                unpack_key(buf, row, primary_key);
2121
            }
2122
            TOKUDB_DBUG_RETURN(0);
2123
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2124 2125 2126
        //
        // create a DBT that has the same data as row,
        //
2127 2128 2129 2130 2131
        DBT key;
        bzero((void *) &key, sizeof(key));
        key.data = key_buff;
        key.size = row->size;
        memcpy(key_buff, row->data, row->size);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2132 2133 2134
        //
        // Read the data into current_row
        //
2135
        current_row.flags = DB_DBT_REALLOC;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2136
        if ((error = share->file->get(share->file, transaction, &key, &current_row, 0))) {
2137
            table->status = STATUS_NOT_FOUND;
2138
            TOKUDB_DBUG_RETURN(error == DB_NOTFOUND ? HA_ERR_CRASHED : error);
2139 2140
        }
        row = &current_row;
2141 2142
        // TOKUDB_DBUG_DUMP("key=", key.data, key.size);
        // TOKUDB_DBUG_DUMP("row=", row->data, row->size);
2143 2144
    }
    unpack_row(buf, row);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2145
    if (found_key) { DBUG_DUMP("read row key", (uchar *) found_key->data, found_key->size); }
2146
    TOKUDB_DBUG_RETURN(0);
2147 2148
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
//
// This is only used to read whole keys
// According to InnoDB handlerton: Positions an index cursor to the index 
// specified in keynr. Fetches the row if any
// Parameters:
//      [out]        buf - buffer for the  returned row
//                   keynr - index to use
//      [in]         key - key value, according to InnoDB, if NULL, 
//                              position cursor at start or end of index,
//                              not sure if this is done now
//                     key_len - length of key
//                     find_flag - according to InnoDB, search flags from my_base.h
// Returns:
//      0 on success
//      HA_ERR_KEY_NOT_FOUND if not found (per InnoDB), 
//      error otherwise
//
2166
int ha_tokudb::index_read_idx(uchar * buf, uint keynr, const uchar * key, uint key_len, enum ha_rkey_function find_flag) {
2167
    TOKUDB_DBUG_ENTER("ha_tokudb::index_read_idx");
2168 2169 2170
    table->in_use->status_var.ha_read_key_count++;
    current_row.flags = DB_DBT_REALLOC;
    active_index = MAX_KEY;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2171
    TOKUDB_DBUG_RETURN(read_row(share->key_file[keynr]->get(share->key_file[keynr], transaction, pack_key(&last_key, keynr, key_buff, key, key_len), &current_row, 0), buf, keynr, &current_row, &last_key, 0));
2172 2173
}

Yoni Fogel's avatar
Yoni Fogel committed
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
//TODO: QQQ Function to tell if a key+keylen is the entire key (loop through the schema), see comparison function for ideas.
/*
if (full_key) {
    switch (find_flag) {
        case (HA_READ_PREFIX): //Synonym for HA_READ_KEY_EXACT
        case (HA_READ_KEY_EXACT):
            Just c_get DB_SET, return.
        case (HA_READ_AFTER_KEY):
            c_get DB_SET_RANGE.  If EQUAL to query, then do DB_NEXT (or is it DB_NEXT_NODUP?)
        case (HA_READ_KEY_OR_NEXT):
            c_get DB_SET_RANGE
        case (HA_READ_BEFORE_KEY):
            c_get DB_SET_RANGE, then do DB_PREV (or is it DB_PREV_NODUP)?
        case (HA_READ_KEY_OR_PREV):
            c_get DB_SET_RANGE.  If NOT EQUAL to query, then do DB_PREV (or is it DB_PREV_NODUP?)
        case (HA_READ_PREFIX_LAST_OR_PREV):
            c_get DB_SET_RANGE.  If NOT EQUAL to query, then do DB_PREV (or is it DB_PREV_NODUP?)
            if if WAS equal to the query, then
                if (NO_DUP db, just return it) else:
                do DB_NEXT_NODUP
                if found, do DB_PREV and return
                else      do DB_LAST and return
        case (HA_READ_PREFIX_LAST):
            c_get DB_SET.  if !found, return NOT FOUND
            if (NO_DUP db, just return it) else:
                do c_get DB_NEXT_NODUP
                    if found, do DB_PREV and return.
                    else      do DB_LAST and return.
        default: Crash a lot.
     }
else {
// Not full key
    switch (find_flag) {
        case (HA_READ_PREFIX): //Synonym for HA_READ_KEY_EXACT
        case (HA_READ_KEY_EXACT):
            c_get DB_SET_RANGE, then check a prefix
        case (HA_READ_AFTER_KEY):
            c_get DB_SET_RANGE, then:
                while (found && query is prefix of 'dbtfound') do:
                    c_get DB_NEXT_NODUP (Definitely NEXT_NODUP since we care about key only).
        case (HA_READ_KEY_OR_NEXT):
            c_get SET_RANGE
        case (HA_READ_BEFORE_KEY):
            c_get DB_SET_RANGE, then do DB_PREV (or is it DB_PREV_NODUP)?
        case (HA_READ_KEY_OR_PREV):
            c_get DB_SET_RANGE.  If query not a prefix of found, then DB_PREV (or is it DB_PREV_NODUP?)
        case (HA_READ_PREFIX_LAST_OR_PREV):
            c_get DB_SET_RANGE, then:
                if (found && query is prefix of whatever found) do:
                    c_get DB_NEXT till not prefix (and return the one that was)
                if (found originally but was not prefix of whatever found) do:
                    c_get DB_PREV
        case (HA_READ_PREFIX_LAST):
            c_get DB_SET_RANGE.  if !found, or query not prefix of what found, return NOT FOUND
            whlie query is prefix of whatfound, do c_get DB_NEXT till not.. then return the last one that was.
        default: Crash a lot.
     }
}
Note that sometimes if not found, will need things like DB_FIRST or DB_LAST
TODO: QQQ maybe need to pass true/1 as last parameter of read_row (this would make it
return END_OF_FILE instead of just NOT_FOUND
*/
2236

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
//
// According to InnoDB handlerton: Positions an index cursor to the index 
// specified in keynr. Fetches the row if any
// Parameters:
//      [out]       buf - buffer for the  returned row
//      [in]         key - key value, according to InnoDB, if NULL, 
//                              position cursor at start or end of index,
//                              not sure if this is done now
//                    key_len - length of key
//                    find_flag - according to InnoDB, search flags from my_base.h
// Returns:
//      0 on success
//      HA_ERR_KEY_NOT_FOUND if not found (per InnoDB), 
//          we seem to return HA_ERR_END_OF_FILE if find_flag != HA_READ_KEY_EXACT
//          TODO: investigate this for correctness
//      error otherwise
//
2254 2255
int ha_tokudb::index_read(uchar * buf, const uchar * key, uint key_len, enum ha_rkey_function find_flag) {
    TOKUDB_DBUG_ENTER("ha_tokudb::index_read %p find %d", this, find_flag);
2256
    // TOKUDB_DBUG_DUMP("key=", key, key_len);
2257 2258 2259 2260 2261 2262 2263
    DBT row;
    int error;

    table->in_use->status_var.ha_read_key_count++;
    bzero((void *) &row, sizeof(row));
    pack_key(&last_key, active_index, key_buff, key, key_len);

2264
    switch (find_flag) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2265
    case HA_READ_KEY_EXACT: /* Find first record else error */
2266 2267 2268 2269 2270 2271 2272
        error = cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE);
        if (error == 0) {
            DBT orig_key;
            pack_key(&orig_key, active_index, key_buff2, key, key_len);
            if (tokudb_prefix_cmp_packed_key(share->key_file[active_index], &orig_key, &last_key))
                error = DB_NOTFOUND;
        }
2273
        break;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2274
    case HA_READ_AFTER_KEY: /* Find next rec. after key-record */
2275 2276 2277
        error = cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE);
        if (error == 0) {
            DBT orig_key;
Yoni Fogel's avatar
Yoni Fogel committed
2278
            pack_key(&orig_key, active_index, key_buff2, key, key_len);
2279
            for (;;) {
2280
                if (tokudb_prefix_cmp_packed_key(share->key_file[active_index], &orig_key, &last_key) != 0)
2281
                    break;
Yoni Fogel's avatar
Yoni Fogel committed
2282
                error = cursor->c_get(cursor, &last_key, &row, DB_NEXT_NODUP);
2283 2284 2285
                if (error != 0)
                    break;
            }
2286
        }
2287
        break;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2288
    case HA_READ_BEFORE_KEY: /* Find next rec. before key-record */
2289 2290 2291
        error = cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE);
        if (error == 0)
            error = cursor->c_get(cursor, &last_key, &row, DB_PREV);
Yoni Fogel's avatar
Yoni Fogel committed
2292
        else if (error == DB_NOTFOUND)
2293 2294
            error = cursor->c_get(cursor, &last_key, &row, DB_LAST);
        break;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2295
    case HA_READ_KEY_OR_NEXT: /* Record or next record */
2296 2297
        error = cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE);
        break;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2298
    case HA_READ_KEY_OR_PREV: /* Record or previous */
2299
        error = cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE);
2300 2301 2302
        if (error == 0) {
            DBT orig_key; 
            pack_key(&orig_key, active_index, key_buff2, key, key_len);
2303
            if (tokudb_prefix_cmp_packed_key(share->key_file[active_index], &orig_key, &last_key) != 0)
2304
                error = cursor->c_get(cursor, &last_key, &row, DB_PREV);
Yoni Fogel's avatar
Yoni Fogel committed
2305 2306
        }
        else if (error == DB_NOTFOUND)
2307
            error = cursor->c_get(cursor, &last_key, &row, DB_LAST);
2308
        break;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2309
    case HA_READ_PREFIX_LAST_OR_PREV: /* Last or prev key with the same prefix */
2310 2311 2312
        error = cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE);
        if (error == 0) {
            DBT orig_key;
Yoni Fogel's avatar
Yoni Fogel committed
2313
            pack_key(&orig_key, active_index, key_buff2, key, key_len);
2314
            for (;;) {
2315
                if (tokudb_prefix_cmp_packed_key(share->key_file[active_index], &orig_key, &last_key) != 0)
2316
                    break;
Yoni Fogel's avatar
Yoni Fogel committed
2317
                error = cursor->c_get(cursor, &last_key, &row, DB_NEXT_NODUP);
2318 2319 2320 2321 2322
                if (error != 0)
                    break;
            }
            if (error == 0)
                error = cursor->c_get(cursor, &last_key, &row, DB_PREV);
Yoni Fogel's avatar
Yoni Fogel committed
2323 2324
            else if (error == DB_NOTFOUND)
                error = cursor->c_get(cursor, &last_key, &row, DB_LAST);
2325
        }
Yoni Fogel's avatar
Yoni Fogel committed
2326 2327
        else if (error == DB_NOTFOUND)
            error = cursor->c_get(cursor, &last_key, &row, DB_LAST);
2328 2329
        break;
    default:
2330
        TOKUDB_TRACE("unsupported:%d\n", find_flag);
2331
        error = HA_ERR_UNSUPPORTED;
2332
        break;
2333
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2334
    error = read_row(error, buf, active_index, &row, &last_key, 0);
2335
    if (error && (tokudb_debug & TOKUDB_DEBUG_ERROR))
2336
        TOKUDB_TRACE("error:%d:%d\n", error, find_flag);
2337
    TOKUDB_DBUG_RETURN(error);
2338 2339
}

2340
#if 0
2341 2342 2343 2344
/*
  Read last key is solved by reading the next key and then reading
  the previous key
*/
2345
int ha_tokudb::index_read_last(uchar * buf, const uchar * key, uint key_len) {
2346
    TOKUDB_DBUG_ENTER("ha_tokudb::index_read_last");
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357
    DBT row;
    int error;
    KEY *key_info = &table->key_info[active_index];

    statistic_increment(table->in_use->status_var.ha_read_key_count, &LOCK_status);
    bzero((void *) &row, sizeof(row));

    /* read of partial key */
    pack_key(&last_key, active_index, key_buff, key, key_len);
    /* Store for compare */
    memcpy(key_buff2, key_buff, (key_len = last_key.size));
2358
    assert(0);
2359 2360 2361 2362 2363 2364
    key_info->handler.bdb_return_if_eq = 1;
    error = read_row(cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE), buf, active_index, &row, (DBT *) 0, 0);
    key_info->handler.bdb_return_if_eq = 0;
    bzero((void *) &row, sizeof(row));
    if (read_row(cursor->c_get(cursor, &last_key, &row, DB_PREV), buf, active_index, &row, &last_key, 1) || tokudb_key_cmp(table, key_info, key_buff2, key_len))
        error = HA_ERR_KEY_NOT_FOUND;
2365
    TOKUDB_DBUG_RETURN(error);
2366
}
2367
#endif
2368

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2369 2370 2371 2372 2373 2374 2375 2376 2377
//
// Reads the next row from the active index (cursor) into buf, and advances cursor
// Parameters:
//      [out]   buf - buffer for the next row, in MySQL format
// Returns:
//      0 on success
//      HA_ERR_END_OF_FILE if not found
//      error otherwise
//
2378
int ha_tokudb::index_next(uchar * buf) {
2379
    TOKUDB_DBUG_ENTER("ha_tokudb::index_next");
2380 2381 2382
    DBT row;
    statistic_increment(table->in_use->status_var.ha_read_next_count, &LOCK_status);
    bzero((void *) &row, sizeof(row));
2383
    TOKUDB_DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_NEXT), buf, active_index, &row, &last_key, 1));
2384 2385
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
//
// Reads the next row matching to the key, on success, advances cursor
// Parameters:
//      [out]   buf - buffer for the next row, in MySQL format
//      [in]     key - key value
//                keylen - length of key
// Returns:
//      0 on success
//      HA_ERR_END_OF_FILE if not found
//      error otherwise
//
2397
int ha_tokudb::index_next_same(uchar * buf, const uchar * key, uint keylen) {
2398
    TOKUDB_DBUG_ENTER("ha_tokudb::index_next_same %p", this);
2399 2400 2401 2402
    DBT row;
    int error;
    statistic_increment(table->in_use->status_var.ha_read_next_count, &LOCK_status);
    bzero((void *) &row, sizeof(row));
Rich Prohaska's avatar
Rich Prohaska committed
2403 2404 2405 2406 2407 2408
    /* QQQ NEXT_DUP on nodup returns EINVAL for tokudb */
    if (keylen == table->key_info[active_index].key_length && 
        !(table->key_info[active_index].flags & HA_NOSAME) && 
        !(table->key_info[active_index].flags & HA_END_SPACE_KEY)) {

        error = cursor->c_get(cursor, &last_key, &row, DB_NEXT_DUP);
2409 2410
        error = read_row(error, buf, active_index, &row, &last_key, 1);
    } else {
2411 2412 2413 2414
        error = read_row(cursor->c_get(cursor, &last_key, &row, DB_NEXT), buf, active_index, &row, &last_key, 1);
        if (!error &&::key_cmp_if_same(table, key, active_index, keylen))
            error = HA_ERR_END_OF_FILE;
    }
2415
    TOKUDB_DBUG_RETURN(error);
2416 2417
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2418 2419 2420 2421 2422 2423 2424 2425 2426
//
// Reads the previous row from the active index (cursor) into buf, and advances cursor
// Parameters:
//      [out]   buf - buffer for the next row, in MySQL format
// Returns:
//      0 on success
//      HA_ERR_END_OF_FILE if not found
//      error otherwise
//
2427
int ha_tokudb::index_prev(uchar * buf) {
2428
    TOKUDB_DBUG_ENTER("ha_tokudb::index_prev");
2429 2430 2431
    DBT row;
    statistic_increment(table->in_use->status_var.ha_read_prev_count, &LOCK_status);
    bzero((void *) &row, sizeof(row));
2432
    TOKUDB_DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_PREV), buf, active_index, &row, &last_key, 1));
2433 2434
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2435 2436 2437 2438 2439 2440 2441 2442 2443
//
// Reads the first row from the active index (cursor) into buf, and advances cursor
// Parameters:
//      [out]   buf - buffer for the next row, in MySQL format
// Returns:
//      0 on success
//      HA_ERR_END_OF_FILE if not found
//      error otherwise
//
2444
int ha_tokudb::index_first(uchar * buf) {
2445
    TOKUDB_DBUG_ENTER("ha_tokudb::index_first");
2446 2447 2448
    DBT row;
    statistic_increment(table->in_use->status_var.ha_read_first_count, &LOCK_status);
    bzero((void *) &row, sizeof(row));
2449
    TOKUDB_DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_FIRST), buf, active_index, &row, &last_key, 1));
2450 2451
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2452 2453 2454 2455 2456 2457 2458 2459 2460
//
// Reads the last row from the active index (cursor) into buf, and advances cursor
// Parameters:
//      [out]   buf - buffer for the next row, in MySQL format
// Returns:
//      0 on success
//      HA_ERR_END_OF_FILE if not found
//      error otherwise
//
2461
int ha_tokudb::index_last(uchar * buf) {
2462
    TOKUDB_DBUG_ENTER("ha_tokudb::index_last");
2463 2464 2465
    DBT row;
    statistic_increment(table->in_use->status_var.ha_read_last_count, &LOCK_status);
    bzero((void *) &row, sizeof(row));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2466
    TOKUDB_DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_LAST), buf, active_index, &row, &last_key, 1));
2467 2468
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2469 2470 2471 2472 2473 2474 2475 2476
//
// Initialize a scan of the table (which is why index_init is called on primary_key)
// Parameters:
//          scan - unused
// Returns:
//      0 on success
//      error otherwise
//
2477
int ha_tokudb::rnd_init(bool scan) {
2478
    TOKUDB_DBUG_ENTER("ha_tokudb::rnd_init");
2479
    current_row.flags = DB_DBT_REALLOC;
2480
    TOKUDB_DBUG_RETURN(index_init(primary_key, 0));
2481 2482
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2483 2484 2485
//
// End a scan of the table
//
2486
int ha_tokudb::rnd_end() {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2487 2488
    TOKUDB_DBUG_ENTER("ha_tokudb::rnd_end");
    TOKUDB_DBUG_RETURN(index_end());
2489 2490
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2491 2492 2493 2494 2495 2496 2497 2498 2499
//
// Read the next row in a table scan
// Parameters:
//      [out]   buf - buffer for the next row, in MySQL format
// Returns:
//      0 on success
//      HA_ERR_END_OF_FILE if not found
//      error otherwise
//
2500
int ha_tokudb::rnd_next(uchar * buf) {
2501
    TOKUDB_DBUG_ENTER("ha_tokudb::ha_tokudb::rnd_next");
2502
    DBT row;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2503 2504 2505 2506
    //
    // The reason we do not just call index_next is that index_next 
    // increments a different variable than we do here
    //
2507 2508
    statistic_increment(table->in_use->status_var.ha_read_rnd_next_count, &LOCK_status);
    bzero((void *) &row, sizeof(row));
2509
    DBUG_DUMP("last_key", (uchar *) last_key.data, last_key.size);
2510
    TOKUDB_DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_NEXT), buf, primary_key, &row, &last_key, 1));
2511 2512 2513 2514
}


DBT *ha_tokudb::get_pos(DBT * to, uchar * pos) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2515
    TOKUDB_DBUG_ENTER("ha_tokudb::get_pos");
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
    /* We don't need to set app_data here */
    bzero((void *) to, sizeof(*to));

    to->data = pos;
    if (share->fixed_length_primary_key)
        to->size = ref_length;
    else {
        KEY_PART_INFO *key_part = table->key_info[primary_key].key_part;
        KEY_PART_INFO *end = key_part + table->key_info[primary_key].key_parts;

        for (; key_part != end; key_part++)
            pos += key_part->field->packed_col_length(pos, key_part->length);
        to->size = (uint) (pos - (uchar *) to->data);
    }
    DBUG_DUMP("key", (const uchar *) to->data, to->size);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2531
    DBUG_RETURN(to);
2532 2533
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2534
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2535
// Retrieves a row with based on the primary key saved in pos
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2536 2537 2538 2539 2540
// Returns:
//      0 on success
//      HA_ERR_KEY_NOT_FOUND if not found
//      error otherwise
//
2541
int ha_tokudb::rnd_pos(uchar * buf, uchar * pos) {
2542
    TOKUDB_DBUG_ENTER("ha_tokudb::rnd_pos");
2543 2544 2545
    DBT db_pos;
    statistic_increment(table->in_use->status_var.ha_read_rnd_count, &LOCK_status);
    active_index = MAX_KEY;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2546
    DBT* key = get_pos(&db_pos, pos); 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2547
    TOKUDB_DBUG_RETURN(read_row(share->file->get(share->file, transaction, key, &current_row, 0), buf, primary_key, &current_row, key, 0));
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
}

/*
  Set a reference to the current record in (ref,ref_length).

  SYNOPSIS
  ha_tokudb::position()
  record                      The current record buffer

  DESCRIPTION
  The BDB handler stores the primary key in (ref,ref_length).
  There is either an explicit primary key, or an implicit (hidden)
  primary key.
  During open(), 'ref_length' is calculated as the maximum primary
  key length. When an actual key is shorter than that, the rest of
  the buffer must be cleared out. The row cannot be identified, if
  garbage follows behind the end of the key. There is no length
  field for the current key, so that the whole ref_length is used
  for comparison.

  RETURN
  nothing
*/
2571
void ha_tokudb::position(const uchar * record) {
2572
    TOKUDB_DBUG_ENTER("ha_tokudb::position");
2573 2574 2575 2576 2577
    DBT key;
    if (hidden_primary_key) {
        DBUG_ASSERT(ref_length == TOKUDB_HIDDEN_PRIMARY_KEY_LENGTH);
        memcpy_fixed(ref, (char *) current_ident, TOKUDB_HIDDEN_PRIMARY_KEY_LENGTH);
    } else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2578
        create_dbt_key_from_table(&key, primary_key, ref, record);
2579 2580 2581 2582 2583 2584
        if (key.size < ref_length)
            bzero(ref + key.size, ref_length - key.size);
    }
    DBUG_VOID_RETURN;
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2585 2586 2587 2588 2589 2590
//
// Per InnoDB: Returns statistics information of the table to the MySQL interpreter,
// in various fields of the handle object. 
// Return:
//      0, always success
//
2591
int ha_tokudb::info(uint flag) {
2592
    TOKUDB_DBUG_ENTER("ha_tokudb::info %p %d %lld %ld", this, flag, share->rows, changed_rows);
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
    if (flag & HA_STATUS_VARIABLE) {
        // Just to get optimizations right
        stats.records = share->rows + changed_rows;
        stats.deleted = 0;
    }
    if ((flag & HA_STATUS_CONST) || version != share->version) {
        version = share->version;
        for (uint i = 0; i < table_share->keys; i++) {
            table->key_info[i].rec_per_key[table->key_info[i].key_parts - 1] = share->rec_per_key[i];
        }
    }
    /* Don't return key if we got an error for the internal primary key */
    if (flag & HA_STATUS_ERRKEY && last_dup_key < table_share->keys)
        errkey = last_dup_key;
2607
    TOKUDB_DBUG_RETURN(0);
2608 2609
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2610 2611 2612
//
//  Per InnoDB: Tells something additional to the handler about how to do things.
//
2613
int ha_tokudb::extra(enum ha_extra_function operation) {
2614
    TOKUDB_DBUG_ENTER("extra %p %d", this, operation);
2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633
    switch (operation) {
    case HA_EXTRA_RESET_STATE:
        reset();
        break;
    case HA_EXTRA_KEYREAD:
        key_read = 1;           // Query satisfied with key
        break;
    case HA_EXTRA_NO_KEYREAD:
        key_read = 0;
        break;
    case HA_EXTRA_IGNORE_DUP_KEY:
        using_ignore = 1;
        break;
    case HA_EXTRA_NO_IGNORE_DUP_KEY:
        using_ignore = 0;
        break;
    default:
        break;
    }
2634
    TOKUDB_DBUG_RETURN(0);
2635 2636 2637
}

int ha_tokudb::reset(void) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2638
    TOKUDB_DBUG_ENTER("ha_tokudb::reset");
2639 2640 2641 2642 2643 2644 2645 2646 2647
    key_read = 0;
    using_ignore = 0;
    if (current_row.flags & (DB_DBT_MALLOC | DB_DBT_REALLOC)) {
        current_row.flags = 0;
        if (current_row.data) {
            free(current_row.data);
            current_row.data = 0;
        }
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2648
    TOKUDB_DBUG_RETURN(0);
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
}

/*
  As MySQL will execute an external lock for every new table it uses
  we can use this to start the transactions.
  If we are in auto_commit mode we just need to start a transaction
  for the statement to be able to rollback the statement.
  If not, we have to start a master transaction if there doesn't exist
  one from before.
*/
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2659 2660 2661 2662 2663 2664 2665 2666
//
// Parameters:
//      [in]    thd - handle to the user thread
//              lock_type - the type of lock
// Returns:
//      0 on success
//      error otherwise
//
2667
int ha_tokudb::external_lock(THD * thd, int lock_type) {
2668
    TOKUDB_DBUG_ENTER("ha_tokudb::external_lock");
2669 2670 2671
    // QQQ this is here to allow experiments without transactions
    if ((tokudb_init_flags & DB_INIT_TXN) == 0) 
        TOKUDB_DBUG_RETURN(0);
2672
    int error = 0;
2673
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, tokudb_hton->slot);
2674
    if (!trx) {
2675
        trx = (tokudb_trx_data *)
2676 2677
            my_malloc(sizeof(*trx), MYF(MY_ZEROFILL));
        if (!trx)
2678
            TOKUDB_DBUG_RETURN(1);
2679
        thd_data_set(thd, tokudb_hton->slot, trx);
2680 2681 2682 2683 2684 2685
    }
    if (trx->all == 0)
        trx->sp_level = 0;
    if (lock_type != F_UNLCK) {
        if (!trx->tokudb_lock_count++) {
            DBUG_ASSERT(trx->stmt == 0);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2686
            transaction = NULL;    // Safety
2687 2688
            /* First table lock, start transaction */
            if ((thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN | OPTION_TABLE_LOCK)) && !trx->all) {
2689
                /* QQQ We have to start a master transaction */
2690 2691 2692
                DBUG_PRINT("trans", ("starting transaction all:  options: 0x%lx", (ulong) thd->options));
                if ((error = db_env->txn_begin(db_env, NULL, &trx->all, 0))) {
                    trx->tokudb_lock_count--;      // We didn't get the lock
2693
                    TOKUDB_DBUG_RETURN(error);
2694
                }
2695
                if (tokudb_debug & TOKUDB_DEBUG_TXN)
2696
                    TOKUDB_TRACE("master:%p\n", trx->all);
2697 2698 2699
                trx->sp_level = trx->all;
                trans_register_ha(thd, TRUE, tokudb_hton);
                if (thd->in_lock_tables)
2700
                    TOKUDB_DBUG_RETURN(0);     // Don't create stmt trans
2701 2702
            }
            DBUG_PRINT("trans", ("starting transaction stmt"));
2703
	    if (trx->stmt) 
2704
                if (tokudb_debug & TOKUDB_DEBUG_TXN) 
2705
                    TOKUDB_TRACE("warning:stmt=%p\n", trx->stmt);
2706 2707 2708
            if ((error = db_env->txn_begin(db_env, trx->sp_level, &trx->stmt, 0))) {
                /* We leave the possible master transaction open */
                trx->tokudb_lock_count--;  // We didn't get the lock
2709
                TOKUDB_DBUG_RETURN(error);
2710
            }
2711
            if (tokudb_debug & TOKUDB_DEBUG_TXN)
2712
                TOKUDB_TRACE("stmt:%p:%p\n", trx->sp_level, trx->stmt);
2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728
            trans_register_ha(thd, FALSE, tokudb_hton);
        }
        transaction = trx->stmt;
    } else {
        lock.type = TL_UNLOCK;  // Unlocked
        thread_safe_add(share->rows, changed_rows, &share->mutex);
        changed_rows = 0;
        if (!--trx->tokudb_lock_count) {
            if (trx->stmt) {
                /*
                   F_UNLCK is done without a transaction commit / rollback.
                   This happens if the thread didn't update any rows
                   We must in this case commit the work to keep the row locks
                 */
                DBUG_PRINT("trans", ("commiting non-updating transaction"));
                error = trx->stmt->commit(trx->stmt, 0);
Rich Prohaska's avatar
Rich Prohaska committed
2729
                if (tokudb_debug & TOKUDB_DEBUG_TXN)
2730
                    TOKUDB_TRACE("commit:%p:%d\n", trx->stmt, error);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2731
                trx->stmt = transaction = NULL;
2732 2733
            }
        }
2734
    }
2735
    TOKUDB_DBUG_RETURN(error);
2736 2737 2738 2739 2740 2741 2742 2743 2744
}


/*
  When using LOCK TABLE's external_lock is only called when the actual
  TABLE LOCK is done.
  Under LOCK TABLES, each used tables will force a call to start_stmt.
*/

2745
int ha_tokudb::start_stmt(THD * thd, thr_lock_type lock_type) {
2746
    TOKUDB_DBUG_ENTER("ha_tokudb::start_stmt");
2747 2748
    if (!(tokudb_init_flags & DB_INIT_TXN)) 
        TOKUDB_DBUG_RETURN(0);
2749
    int error = 0;
2750
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, tokudb_hton->slot);
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
    DBUG_ASSERT(trx);
    /*
       note that trx->stmt may have been already initialized as start_stmt()
       is called for *each table* not for each storage engine,
       and there could be many bdb tables referenced in the query
     */
    if (!trx->stmt) {
        DBUG_PRINT("trans", ("starting transaction stmt"));
        error = db_env->txn_begin(db_env, trx->sp_level, &trx->stmt, 0);
        trans_register_ha(thd, FALSE, tokudb_hton);
    }
    transaction = trx->stmt;
2763
    TOKUDB_DBUG_RETURN(error);
2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793
}

/*
  The idea with handler::store_lock() is the following:

  The statement decided which locks we should need for the table
  for updates/deletes/inserts we get WRITE locks, for SELECT... we get
  read locks.

  Before adding the lock into the table lock handler (see thr_lock.c)
  mysqld calls store lock with the requested locks.  Store lock can now
  modify a write lock to a read lock (or some other lock), ignore the
  lock (if we don't want to use MySQL table locks at all) or add locks
  for many tables (like we do when we are using a MERGE handler).

  Tokudb DB changes all WRITE locks to TL_WRITE_ALLOW_WRITE (which
  signals that we are doing WRITES, but we are still allowing other
  reader's and writer's.

  When releasing locks, store_lock() are also called. In this case one
  usually doesn't have to do anything.

  In some exceptional cases MySQL may send a request for a TL_IGNORE;
  This means that we are requesting the same lock as last time and this
  should also be ignored. (This may happen when someone does a flush
  table when we have opened a part of the tables, in which case mysqld
  closes and reopens the tables and tries to get the same locks at last
  time).  In the future we will probably try to remove this.
*/

2794
THR_LOCK_DATA **ha_tokudb::store_lock(THD * thd, THR_LOCK_DATA ** to, enum thr_lock_type lock_type) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2795
    TOKUDB_DBUG_ENTER("ha_tokudb::store_lock");
2796 2797 2798 2799 2800
    if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK) {
        /* If we are not doing a LOCK TABLE, then allow multiple writers */
        if ((lock_type >= TL_WRITE_CONCURRENT_INSERT && lock_type <= TL_WRITE) && !thd->in_lock_tables)
            lock_type = TL_WRITE_ALLOW_WRITE;
        lock.type = lock_type;
2801
    }
2802
    *to++ = &lock;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2803
    DBUG_RETURN(to);
2804 2805 2806 2807
}


static int create_sub_table(const char *table_name, const char *sub_name, DBTYPE type, int flags) {
2808
    TOKUDB_DBUG_ENTER("create_sub_table");
2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825
    int error;
    DB *file;
    DBUG_PRINT("enter", ("sub_name: %s  flags: %d", sub_name, flags));

    if (!(error = db_create(&file, db_env, 0))) {
        file->set_flags(file, flags);
        error = (file->open(file, NULL, table_name, sub_name, type, DB_THREAD | DB_CREATE, my_umask));
        if (error) {
            DBUG_PRINT("error", ("Got error: %d when opening table '%s'", error, table_name));
            (void) file->remove(file, table_name, NULL, 0);
        } else
            (void) file->close(file, 0);
    } else {
        DBUG_PRINT("error", ("Got error: %d when creating table", error));
    }
    if (error)
        my_errno = error;
2826
    TOKUDB_DBUG_RETURN(error);
2827 2828
}

2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844
static int mkdirpath(char *name, mode_t mode) {
    int r = mkdir(name, mode);
    if (r == -1 && errno == ENOENT) {
        char parent[strlen(name)+1];
        strcpy(parent, name);
        char *cp = strrchr(parent, '/');
        if (cp) {
            *cp = 0;
            r = mkdir(parent, 0755);
            if (r == 0)
                r = mkdir(name, mode);
        }
    }
    return r;
}

2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858
#include <dirent.h>

static int rmall(const char *dname) {
    int error = 0;
    DIR *d = opendir(dname);
    if (d) {
        struct dirent *dirent;
        while ((dirent = readdir(d)) != 0) {
            if (0 == strcmp(dirent->d_name, ".") || 0 == strcmp(dirent->d_name, ".."))
                continue;
            char fname[strlen(dname) + 1 + strlen(dirent->d_name) + 1];
            sprintf(fname, "%s/%s", dname, dirent->d_name);
            if (dirent->d_type == DT_DIR) {
                error = rmall(fname);
Rich Prohaska's avatar
Rich Prohaska committed
2859 2860
            } else {
                if (tokudb_debug & TOKUDB_DEBUG_OPEN)
2861
                    TOKUDB_TRACE("unlink:%s\n", fname);
2862
                error = unlink(fname);
Rich Prohaska's avatar
Rich Prohaska committed
2863
            }
2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879
            if (error != 0) {
                error = errno;
                break;
            }
        }
        closedir(d);
        if (error == 0) {
            error = rmdir(dname);
            if (error != 0)
                error = errno;
        }
    } else
        error = errno;
    return error;
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889
//
// Creates a new table
// Parameters:
//      [in]    name - table name
//      [in]    form - info on table, columns and indexes
//      [in]    create_info - more info on table, CURRENTLY UNUSED
// Returns:
//      0 on success
//      error otherwise
//
2890
int ha_tokudb::create(const char *name, TABLE * form, HA_CREATE_INFO * create_info) {
2891
    TOKUDB_DBUG_ENTER("ha_tokudb::create");
2892 2893
    char name_buff[FN_REFLEN];
    int error;
2894
    char dirname[get_name_length(name) + 32];
2895
    char newname[get_name_length(name) + 32];
2896

2897
    uint i;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2898 2899 2900 2901

    //
    // tracing information about what type of table we are creating
    //
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919
    if (tokudb_debug & TOKUDB_DEBUG_OPEN) {
        for (i = 0; i < form->s->fields; i++) {
            Field *field = form->s->field[i];
            TOKUDB_TRACE("field:%d:%s:type=%d:flags=%x\n", i, field->field_name, field->type(), field->flags);
        }
        for (i = 0; i < form->s->keys; i++) {
            KEY *key = &form->s->key_info[i];
            TOKUDB_TRACE("key:%d:%s:%d\n", i, key->name, key->key_parts);
            uint p;
            for (p = 0; p < key->key_parts; p++) {
                KEY_PART_INFO *key_part = &key->key_part[p];
                Field *field = key_part->field;
                TOKUDB_TRACE("key:%d:%d:length=%d:%s:type=%d:flags=%x\n",
                             i, p, key_part->length, field->field_name, field->type(), field->flags);
            }
        }
    }

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2920 2921
    //
    // check if auto increment is properly defined
2922 2923
    // tokudb only supports auto increment on the first field in the primary key
    // or the first field in the row
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2924
    //
2925 2926 2927
    int pk_found = 0;
    int ai_found = 0;
    for (i = 0; i < form->s->keys; i++) {
2928
        KEY *key = &form->s->key_info[i];
2929 2930
        int is_primary = (strcmp(key->name, "PRIMARY") == 0);
        if (is_primary) pk_found = 1;
2931
        uint p;
2932
        for (p = 0; p < key->key_parts; p++) {
2933 2934
            KEY_PART_INFO *key_part = &key->key_part[p];
            Field *field = key_part->field;
2935 2936 2937 2938
            if (field->flags & AUTO_INCREMENT_FLAG) {
                ai_found = 1;
                if (is_primary && p > 0) 
                    TOKUDB_DBUG_RETURN(HA_ERR_UNSUPPORTED);
2939
            }
2940
        }
2941 2942 2943 2944 2945 2946 2947
    }

    if (!pk_found && ai_found) {
        Field *field = form->s->field[0];
        if (!(field->flags & AUTO_INCREMENT_FLAG))
            TOKUDB_DBUG_RETURN(HA_ERR_UNSUPPORTED);
    }
2948

2949
    // a table is a directory of dictionaries
2950 2951
    make_name(dirname, name, 0);
    error = mkdirpath(dirname, 0777);
2952
    if (error != 0) {
2953
        TOKUDB_DBUG_RETURN(errno);
2954
    }
2955

2956 2957
    make_name(newname, name, "main");
    fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);
2958 2959

    /* Create the main table that will hold the real rows */
2960
    error = create_sub_table(name_buff, NULL, DB_BTREE, 0);
Rich Prohaska's avatar
Rich Prohaska committed
2961
    if (tokudb_debug & TOKUDB_DEBUG_OPEN)
2962
        TOKUDB_TRACE("create:%s:error=%d\n", newname, error);
2963 2964 2965 2966
    if (error) {
        rmall(dirname);
        TOKUDB_DBUG_RETURN(error);
    }
2967 2968 2969 2970

    primary_key = form->s->primary_key;

    /* Create the keys */
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2971
    char part[MAX_ALIAS_NAME + 10];
2972 2973
    for (uint i = 0; i < form->s->keys; i++) {
        if (i != primary_key) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2974
            sprintf(part, "key-%s", form->s->key_info[i].name);
2975 2976
            make_name(newname, name, part);
            fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);
2977
            error = create_sub_table(name_buff, NULL, DB_BTREE, (form->key_info[i].flags & HA_NOSAME) ? 0 : DB_DUP + DB_DUPSORT);
Rich Prohaska's avatar
Rich Prohaska committed
2978
            if (tokudb_debug & TOKUDB_DEBUG_OPEN)
2979
                TOKUDB_TRACE("create:%s:flags=%ld:error=%d\n", newname, form->key_info[i].flags, error);
2980 2981 2982 2983
            if (error) {
                rmall(dirname);
                TOKUDB_DBUG_RETURN(error);
            }
2984 2985
        }
    }
2986

2987
    /* Create the status block to save information from last status command */
2988 2989
    /* QQQ Is DB_BTREE the best option here ? (QUEUE can't be used in sub tables) */
    // QQQ what is the status DB used for?
2990 2991 2992

    DB *status_block;
    if (!(error = (db_create(&status_block, db_env, 0)))) {
2993 2994
        make_name(newname, name, "status");
        fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);
2995

2996
        if (!(error = (status_block->open(status_block, NULL, name_buff, NULL, DB_BTREE, DB_CREATE, 0)))) {
2997 2998 2999 3000 3001 3002
            char rec_buff[4 + MAX_KEY * 4];
            uint length = 4 + form->s->keys * 4;
            bzero(rec_buff, length);
            error = write_status(status_block, rec_buff, length);
            status_block->close(status_block, 0);
        }
Rich Prohaska's avatar
Rich Prohaska committed
3003
        if (tokudb_debug & TOKUDB_DEBUG_OPEN)
3004
            TOKUDB_TRACE("create:%s:error=%d\n", newname, error);
Rich Prohaska's avatar
Rich Prohaska committed
3005

3006
    }
3007 3008 3009

    if (error)
        rmall(dirname);
3010
    TOKUDB_DBUG_RETURN(error);
3011 3012
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3013 3014 3015 3016 3017 3018 3019 3020
//
// Drops table
// Parameters:
//      [in]    name - name of table to be deleted
// Returns:
//      0 on success
//      error otherwise
//
3021
int ha_tokudb::delete_table(const char *name) {
3022
    TOKUDB_DBUG_ENTER("ha_tokudb::delete_table");
3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044
    int error;
#if 0 // QQQ single file per table
    char name_buff[FN_REFLEN];
    char newname[strlen(name) + 32];

    sprintf(newname, "%s/main", name);
    fn_format(name_buff, newname, "", ha_tokudb_ext, MY_UNPACK_FILENAME | MY_APPEND_EXT);
    error = db_create(&file, db_env, 0);
    if (error != 0)
        goto exit;
    error = file->remove(file, name_buff, NULL, 0);

    sprintf(newname, "%s/status", name);
    fn_format(name_buff, newname, "", ha_tokudb_ext, MY_UNPACK_FILENAME | MY_APPEND_EXT);
    error = db_create(&file, db_env, 0);
    if (error != 0)
        goto exit;
    error = file->remove(file, name_buff, NULL, 0);

  exit:
    file = 0;                   // Safety
    my_errno = error;
3045
#else
3046
    // remove all of the dictionaries in the table directory 
3047 3048
    char newname[(tokudb_data_dir ? strlen(tokudb_data_dir) : 0) + strlen(name) + 32];
    make_name(newname, name, 0);
3049 3050
    error = rmall(newname);
    my_errno = error;
3051
#endif
3052
    TOKUDB_DBUG_RETURN(error);
3053 3054 3055
}


Zardosht Kasheff's avatar
Zardosht Kasheff committed
3056 3057 3058 3059 3060 3061 3062 3063 3064
//
// renames table from "from" to "to"
// Parameters:
//      [in]    name - old name of table
//      [in]    to - new name of table
// Returns:
//      0 on success
//      error otherwise
//
3065
int ha_tokudb::rename_table(const char *from, const char *to) {
3066
    TOKUDB_DBUG_ENTER("%s %s %s", __FUNCTION__, from, to);
3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078
    int error;
#if 0 // QQQ single file per table
    char from_buff[FN_REFLEN];
    char to_buff[FN_REFLEN];

    if ((error = db_create(&file, db_env, 0)))
        my_errno = error;
    else {
        /* On should not do a file->close() after rename returns */
        error = file->rename(file,
                             fn_format(from_buff, from, "", ha_tokudb_ext, MY_UNPACK_FILENAME | MY_APPEND_EXT), NULL, fn_format(to_buff, to, "", ha_tokudb_ext, MY_UNPACK_FILENAME | MY_APPEND_EXT), 0);
    }
3079
#else
3080 3081 3082 3083 3084 3085
    int n = get_name_length(from) + 32;
    char newfrom[n];
    make_name(newfrom, from, 0);
    n = get_name_length(to) + 32;
    char newto[n];
    make_name(newto, to, 0);
3086 3087 3088
    error = rename(newfrom, newto);
    if (error != 0)
        error = my_errno = errno;
3089
#endif
3090
    TOKUDB_DBUG_RETURN(error);
3091 3092 3093 3094
}


/*
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3095
  Returns estimate on number of seeks it will take to read through the table
3096 3097 3098
  This is to be comparable to the number returned by records_in_range so
  that we can decide if we should scan the table or use keys.
*/
3099
/// QQQ why divide by 3
3100
double ha_tokudb::scan_time() {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3101 3102 3103
    TOKUDB_DBUG_ENTER("ha_tokudb::scan_time");
    double ret_val = stats.records / 3;
    DBUG_RETURN(ret_val);
3104 3105
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3106
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117
// Estimates the number of index records in a range. In case of errors, return
//   HA_TOKUDB_RANGE_COUNT instead of HA_POS_ERROR. This was behavior
//   when we got the handlerton from MySQL.
// Parameters:
//              keynr -index to use 
//      [in]    start_key - low end of the range
//      [in]    end_key - high end of the range
// Returns:
//      0 - There are no matching keys in the given range
//      number > 0 - There are approximately number matching rows in the range
//      HA_POS_ERROR - Something is wrong with the index tree
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3118
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3119
ha_rows ha_tokudb::records_in_range(uint keynr, key_range* start_key, key_range* end_key) {
3120
    TOKUDB_DBUG_ENTER("ha_tokudb::records_in_range");
3121
    DBT key;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3122
    ha_rows ret_val = HA_TOKUDB_RANGE_COUNT;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3123
    DB *kfile = share->key_file[keynr];
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3124 3125 3126
    u_int64_t less, equal, greater;
    u_int64_t start_rows, end_rows, rows;
    int is_exact;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3127
    int error;
3128

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3129
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3130
    // get start_rows and end_rows values so that we can estimate range
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3131 3132
    //
    if (start_key) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3133
        error = kfile->key_range64(
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3134 3135 3136
            kfile, 
            transaction, 
            pack_key(&key, keynr, key_buff, start_key->key, start_key->length), 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3137 3138 3139 3140
            &less,
            &equal,
            &greater,
            &is_exact
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3141 3142 3143 3144 3145 3146
            );
        if (error) {
            ret_val = HA_TOKUDB_RANGE_COUNT;
            goto cleanup;
        }
        if (start_key->flag == HA_READ_KEY_EXACT) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3147
            start_rows= less;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3148 3149
        }
        else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3150
            start_rows = less + equal;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3151
        }
3152
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3153
    else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3154
        start_rows= 0;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3155 3156 3157
    }

    if (end_key) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3158
        error = kfile->key_range64(
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3159 3160 3161
            kfile, 
            transaction, 
            pack_key(&key, keynr, key_buff, end_key->key, end_key->length), 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3162 3163 3164 3165
            &less,
            &equal,
            &greater,
            &is_exact
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3166 3167 3168 3169 3170 3171
            );
        if (error) {
            ret_val = HA_TOKUDB_RANGE_COUNT;
            goto cleanup;
        }
        if (end_key->flag == HA_READ_BEFORE_KEY) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3172
            end_rows= less;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3173 3174
        }
        else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3175
            end_rows= less + equal;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3176 3177 3178
        }
    }
    else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3179
        end_rows = stats.records;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3180 3181
    }

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3182 3183
    rows = end_rows - start_rows;

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3184
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3185 3186
    // MySQL thinks a return value of 0 means there are exactly 0 rows
    // Therefore, always return non-zero so this assumption is not made
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3187
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3188
    ret_val = (ha_rows) (rows <= 1 ? 1 : rows);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3189 3190
cleanup:
    TOKUDB_DBUG_RETURN(ret_val);
3191 3192
}

3193
void ha_tokudb::get_auto_increment(ulonglong offset, ulonglong increment, ulonglong nb_desired_values, ulonglong * first_value, ulonglong * nb_reserved_values) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3194
    TOKUDB_DBUG_ENTER("ha_tokudb::get_auto_increment");
3195 3196
    ulonglong nr;

3197
    pthread_mutex_lock(&share->mutex);
3198 3199 3200 3201 3202
    if (!(share->status & STATUS_AUTO_INCREMENT_INIT)) {
        share->status |= STATUS_AUTO_INCREMENT_INIT;
        int error = read_last();
        if (error == 0) {
            share->last_auto_increment = table->next_number_field->val_int_offset(table->s->rec_buff_length);
3203
            if (tokudb_debug & TOKUDB_DEBUG_AUTO_INCREMENT) 
3204
                TOKUDB_TRACE("init auto increment:%lld\n", share->last_auto_increment);
3205 3206
        }
    }
3207 3208
    nr = share->last_auto_increment + increment;
    share->last_auto_increment = nr + nb_desired_values - 1;
3209
    pthread_mutex_unlock(&share->mutex);
3210

3211
    if (tokudb_debug & TOKUDB_DEBUG_AUTO_INCREMENT)
3212 3213
        TOKUDB_TRACE("get_auto_increment(%lld,%lld,%lld):got:%lld:%lld\n",
                     offset, increment, nb_desired_values, nr, nb_desired_values);
3214
    *first_value = nr;
3215
    *nb_reserved_values = nb_desired_values;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3216
    DBUG_VOID_RETURN;
3217 3218
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241
//
// Adds indexes to the table. Takes the array of KEY passed in key_info, and creates
// DB's that will go at the end of share->key_file. THE IMPLICIT ASSUMPTION HERE is
// that the table will be modified and that these added keys will be appended to the end
// of the array table->key_info
// Parameters:
//      [in]    table_arg - table that is being modified, seems to be identical to this->table
//      [in]    key_info - array of KEY's to be added
//              num_of_keys - number of keys to be added, number of elements in key_info
//  Returns:
//      0 on success, error otherwise
//
int ha_tokudb::add_index(TABLE *table_arg, KEY *key_info, uint num_of_keys) {
    TOKUDB_DBUG_ENTER("ha_tokudb::add_index");
    char name_buff[FN_REFLEN];
    int error;
    char newname[share->table_name_length + 32];
    uint curr_index = 0;
    DBC* tmp_cursor = NULL;
    int cursor_ret_val = 0;
    DBT current_primary_key;
    DBT row;
    DB_TXN* txn = NULL;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3242
    uchar tmp_key_buff[2*table_arg->s->rec_buff_length];
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
    //
    // these variables are for error handling
    //
    uint num_files_created = 0;
    uint num_DB_opened = 0;
    
    //
    // in unpack_row, MySQL passes a buffer that is this long,
    // so this length should be good enough for us as well
    //
    uchar tmp_record[table_arg->s->rec_buff_length];
    bzero((void *) &current_primary_key, sizeof(current_primary_key));
    bzero((void *) &row, sizeof(row));
    //
    // first create all the DB's files
    //
    char part[MAX_ALIAS_NAME + 10];
    for (uint i = 0; i < num_of_keys; i++) {
        sprintf(part, "key-%s", key_info[i].name);
        make_name(newname, share->table_name, part);
        fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);
        error = create_sub_table(name_buff, NULL, DB_BTREE, (key_info[i].flags & HA_NOSAME) ? 0 : DB_DUP + DB_DUPSORT);
        if (tokudb_debug & TOKUDB_DEBUG_OPEN) {
            TOKUDB_TRACE("create:%s:flags=%ld:error=%d\n", newname, key_info[i].flags, error);
        }
        if (error) { goto cleanup; }
        num_files_created++;
    }

    //
    // open all the DB files and set the appropriate variables in share
    // they go to the end of share->key_file
    //
    curr_index = table_arg->s->keys;
    for (uint i = 0; i < num_of_keys; i++, curr_index++) {
        error = open_secondary_table(
            &share->key_file[curr_index], 
            &key_info[i],
            share->table_name,
            0,
            &share->key_type[curr_index]
            );
        if (error) { goto cleanup; }
        num_DB_opened++;
    }
    

    //
    // scan primary table, create each secondary key, add to each DB
    //
    
    error = db_env->txn_begin(db_env, 0, &txn, 0);
    assert(error == 0);
    if ((error = share->file->cursor(share->file, txn, &tmp_cursor, 0))) {
        tmp_cursor = NULL;             // Safety
        goto cleanup;
    }

    //
    // for each element in the primary table, insert the proper key value pair in each secondary table
    // that is created
    //
    cursor_ret_val = tmp_cursor->c_get(tmp_cursor, &current_primary_key, &row, DB_NEXT);
    while (cursor_ret_val != DB_NOTFOUND) {
        if (cursor_ret_val) {
            error = cursor_ret_val;
            goto cleanup;
        }
        unpack_row(tmp_record, &row);
        for (uint i = 0; i < num_of_keys; i++) {
            DBT secondary_key;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3314
            create_dbt_key_from_key(&secondary_key,&key_info[i], tmp_key_buff, tmp_record);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326
            uint curr_index = i + table_arg->s->keys;
            u_int32_t put_flags = share->key_type[curr_index];
            
            error = share->key_file[curr_index]->put(share->key_file[curr_index], NULL, &secondary_key, &current_primary_key, put_flags);
            if (error) {
                //
                // in the case of any error anywhere, we can just nuke all the files created, so we dont need
                // to be tricky and try to roll back changes. That is why we commit the transaction,
                // which should be fast. The DB is going to go away anyway, so no pt in trying to keep
                // it in a good state.
                //
                txn->commit(txn, 0);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3327 3328 3329 3330 3331 3332 3333 3334
                //
                // found a duplicate in a no_dup DB
                //
                if ( (error == DB_KEYEXIST) && (key_info[i].flags & HA_NOSAME)) {
                    error = HA_ERR_FOUND_DUPP_KEY;
                    last_dup_key = i;
                    memcpy(table_arg->record[0], tmp_record, table_arg->s->rec_buff_length);
                }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441
                goto cleanup;
            }
        }
        cursor_ret_val = tmp_cursor->c_get(tmp_cursor, &current_primary_key, &row, DB_NEXT);
    }
    error = txn->commit(txn, 0);
    assert(error == 0);
    tmp_cursor->c_close(tmp_cursor);
    
    error = 0;
cleanup:
    if (error) {
        //
        // We need to delete all the files that may have been created
        // The DB's must be closed and removed
        //
        for (uint i = table_arg->s->keys; i < table_arg->s->keys + num_DB_opened; i++) {
            share->key_file[i]->close(share->key_file[i], 0);
            share->key_file[i] = NULL;
        }
        for (uint i = 0; i < num_files_created; i++) {
            DB* tmp;
            sprintf(part, "key-%s", key_info[i].name);
            make_name(newname, share->table_name, part);
            fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);
            if (!(db_create(&tmp, db_env, 0))) {
                tmp->remove(tmp, name_buff, NULL, 0);
            }
        }
    }
    TOKUDB_DBUG_RETURN(error);
}

//
// Prepares to drop indexes to the table. For each value, i, in the array key_num,
// table->key_info[i] is a key that is to be dropped.
//  ***********NOTE*******************
// Although prepare_drop_index is supposed to just get the DB's ready for removal,
// and not actually do the removal, we are doing it here and not in final_drop_index
// For the flags we expose in alter_table_flags, namely xxx_NO_WRITES, this is allowed
// Changes for "future-proofing" this so that it works when we have the equivalent flags
// that are not NO_WRITES are not worth it at the moments
// Parameters:
//      [in]    table_arg - table that is being modified, seems to be identical to this->table
//      [in]    key_num - array of indexes that specify which keys of the array table->key_info
//                  are to be dropped
//              num_of_keys - size of array, key_num
//  Returns:
//      0 on success, error otherwise
//
int ha_tokudb::prepare_drop_index(TABLE *table_arg, uint *key_num, uint num_of_keys) {
    TOKUDB_DBUG_ENTER("ha_tokudb::prepare_drop_index");
    int error;
    char name_buff[FN_REFLEN];
    char newname[share->table_name_length + 32];
    char part[MAX_ALIAS_NAME + 10];
    DB** dbs_to_remove = NULL;

    //
    // we allocate an array of DB's here to get ready for removal
    // We do this so that all potential memory allocation errors that may occur
    // will do so BEFORE we go about dropping any indexes. This way, we
    // can fail gracefully without losing integrity of data in such cases. If on
    // on the other hand, we started removing DB's, and in the middle, 
    // one failed, it is not immedietely obvious how one would rollback
    //
    dbs_to_remove = (DB **)my_malloc(sizeof(*dbs_to_remove)*num_of_keys, MYF(MY_ZEROFILL));
    if (dbs_to_remove == NULL) {
        error = ENOMEM; 
        goto cleanup;
    }
    for (uint i = 0; i < num_of_keys; i++) {
        error = db_create(&dbs_to_remove[i], db_env, 0);
        if (error) {
            goto cleanup;
        }
    }    
    
    for (uint i = 0; i < num_of_keys; i++) {
        uint curr_index = key_num[i];
        share->key_file[curr_index]->close(share->key_file[curr_index],0);
        share->key_file[curr_index] = NULL;
        
        sprintf(part, "key-%s", table_arg->key_info[curr_index].name);
        make_name(newname, share->table_name, part);
        fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);

        dbs_to_remove[i]->remove(dbs_to_remove[i], name_buff, NULL, 0);
    }
cleanup:
    my_free(dbs_to_remove, MYF(MY_ALLOW_ZERO_PTR));
    TOKUDB_DBUG_RETURN(error);
}


//  ***********NOTE*******************
// Although prepare_drop_index is supposed to just get the DB's ready for removal,
// and not actually do the removal, we are doing it here and not in final_drop_index
// For the flags we expose in alter_table_flags, namely xxx_NO_WRITES, this is allowed
// Changes for "future-proofing" this so that it works when we have the equivalent flags
// that are not NO_WRITES are not worth it at the moments, therefore, we can make
// this function just return
int ha_tokudb::final_drop_index(TABLE *table_arg) {
    TOKUDB_DBUG_ENTER("ha_tokudb::final_drop_index");
    TOKUDB_DBUG_RETURN(0);
}

3442
void ha_tokudb::print_error(int error, myf errflag) {
3443
    if (error == DB_LOCK_DEADLOCK)
3444
        error = HA_ERR_LOCK_DEADLOCK;
3445
    if (error == DB_LOCK_NOTGRANTED)
3446
        error = HA_ERR_LOCK_WAIT_TIMEOUT;
3447 3448 3449
    handler::print_error(error, errflag);
}

3450
#if 0 // QQQ use default
3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481
int ha_tokudb::analyze(THD * thd, HA_CHECK_OPT * check_opt) {
    uint i;
    DB_BTREE_STAT *stat = 0;
    DB_TXN_STAT *txn_stat_ptr = 0;
    tokudb_trx_data *trx = (tokudb_trx_data *) thd->ha_data[tokudb_hton->slot];
    DBUG_ASSERT(trx);

    for (i = 0; i < table_share->keys; i++) {
        if (stat) {
            free(stat);
            stat = 0;
        }
        if ((key_file[i]->stat) (key_file[i], trx->all, (void *) &stat, 0))
            goto err;
        share->rec_per_key[i] = (stat->bt_ndata / (stat->bt_nkeys ? stat->bt_nkeys : 1));
    }
    /* A hidden primary key is not in key_file[] */
    if (hidden_primary_key) {
        if (stat) {
            free(stat);
            stat = 0;
        }
        if ((file->stat) (file, trx->all, (void *) &stat, 0))
            goto err;
    }
    pthread_mutex_lock(&share->mutex);
    share->rows = stat->bt_ndata;
    share->status |= STATUS_TOKUDB_ANALYZE;        // Save status on close
    share->version++;           // Update stat in table
    pthread_mutex_unlock(&share->mutex);
    update_status(share, table);        // Write status to file
3482
    if (stat)
3483 3484 3485 3486
        free(stat);
    return ((share->status & STATUS_TOKUDB_ANALYZE) ? HA_ADMIN_FAILED : HA_ADMIN_OK);

  err:
3487
    if (stat)
3488 3489
        free(stat);
    return HA_ADMIN_FAILED;
3490
}
3491
#endif
3492

3493
#if 0 // QQQ use default
3494 3495
int ha_tokudb::optimize(THD * thd, HA_CHECK_OPT * check_opt) {
    return ha_tokudb::analyze(thd, check_opt);
3496
}
3497
#endif
3498

3499
#if 0 // QQQ use default
3500
int ha_tokudb::check(THD * thd, HA_CHECK_OPT * check_opt) {
3501
    TOKUDB_DBUG_ENTER("ha_tokudb::check");
3502
    TOKUDB_DBUG_RETURN(HA_ADMIN_NOT_IMPLEMENTED);
3503
    // look in old_ha_tokudb.cc for a start of an implementation
3504
}
3505
#endif
3506

3507 3508 3509 3510 3511 3512
ulong ha_tokudb::field_offset(Field *field) {
    if (table->record[0] <= field->ptr && field->ptr < table->record[1])
        return field->offset(table->record[0]);
    assert(0);
    return 0;
}
3513

3514
struct st_mysql_storage_engine storage_engine_structure = { MYSQL_HANDLERTON_INTERFACE_VERSION };
3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525

// options flags
//   PLUGIN_VAR_THDLOCAL  Variable is per-connection
//   PLUGIN_VAR_READONLY  Server variable is read only
//   PLUGIN_VAR_NOSYSVAR  Not a server variable
//   PLUGIN_VAR_NOCMDOPT  Not a command line option
//   PLUGIN_VAR_NOCMDARG  No argument for cmd line
//   PLUGIN_VAR_RQCMDARG  Argument required for cmd line
//   PLUGIN_VAR_OPCMDARG  Argument optional for cmd line
//   PLUGIN_VAR_MEMALLOC  String needs memory allocated

3526 3527 3528

// system variables

Rich Prohaska's avatar
Rich Prohaska committed
3529 3530
static MYSQL_SYSVAR_ULONGLONG(cache_size, tokudb_cache_size, PLUGIN_VAR_READONLY, "TokuDB cache table size", NULL, NULL, 0, 0, ~0LL, 0);

3531 3532
static MYSQL_SYSVAR_UINT(cache_memory_percent, tokudb_cache_memory_percent, PLUGIN_VAR_READONLY, "Default percent of physical memory in the TokuDB cache table", NULL, NULL, tokudb_cache_memory_percent, 0, 100, 0);

Rich Prohaska's avatar
Rich Prohaska committed
3533 3534
static MYSQL_SYSVAR_ULONG(max_lock, tokudb_max_lock, PLUGIN_VAR_READONLY, "TokuDB Max Locks", NULL, NULL, 8 * 1024, 0, ~0L, 0);

3535
static MYSQL_SYSVAR_ULONG(debug, tokudb_debug, PLUGIN_VAR_READONLY, "TokuDB Debug", NULL, NULL, 0, 0, ~0L, 0);
3536

3537
static MYSQL_SYSVAR_STR(log_dir, tokudb_log_dir, PLUGIN_VAR_READONLY, "TokuDB Log Directory", NULL, NULL, NULL);
3538

3539
static MYSQL_SYSVAR_STR(data_dir, tokudb_data_dir, PLUGIN_VAR_READONLY, "TokuDB Data Directory", NULL, NULL, NULL);
3540

3541 3542
static MYSQL_SYSVAR_STR(version, tokudb_version, PLUGIN_VAR_READONLY, "TokuDB Version", NULL, NULL, NULL);

3543 3544
static MYSQL_SYSVAR_UINT(init_flags, tokudb_init_flags, PLUGIN_VAR_READONLY, "Sets TokuDB DB_ENV->open flags", NULL, NULL, tokudb_init_flags, 0, ~0, 0);

3545 3546
#if 0

3547
static MYSQL_SYSVAR_ULONG(cache_parts, tokudb_cache_parts, PLUGIN_VAR_READONLY, "Sets TokuDB set_cache_parts", NULL, NULL, 0, 0, ~0L, 0);
3548 3549 3550

// this is really a u_int32_t
// ? use MYSQL_SYSVAR_SET
3551
static MYSQL_SYSVAR_UINT(env_flags, tokudb_env_flags, PLUGIN_VAR_READONLY, "Sets TokuDB env_flags", NULL, NULL, DB_LOG_AUTOREMOVE, 0, ~0, 0);
3552

3553
static MYSQL_SYSVAR_STR(home, tokudb_home, PLUGIN_VAR_READONLY, "Sets TokuDB env->open home", NULL, NULL, NULL);
3554 3555 3556 3557 3558

// this is really a u_int32_t
//? use MYSQL_SYSVAR_SET

// this looks to be unused
3559
static MYSQL_SYSVAR_LONG(lock_scan_time, tokudb_lock_scan_time, PLUGIN_VAR_READONLY, "Tokudb Lock Scan Time (UNUSED)", NULL, NULL, 0, 0, ~0L, 0);
3560 3561 3562

// this is really a u_int32_t
//? use MYSQL_SYSVAR_ENUM
3563 3564 3565 3566 3567 3568 3569 3570 3571
static MYSQL_SYSVAR_UINT(lock_type, tokudb_lock_type, PLUGIN_VAR_READONLY, "Sets set_lk_detect", NULL, NULL, DB_LOCK_DEFAULT, 0, ~0, 0);

static MYSQL_SYSVAR_ULONG(log_buffer_size, tokudb_log_buffer_size, PLUGIN_VAR_READONLY, "Tokudb Log Buffer Size", NULL, NULL, 0, 0, ~0L, 0);

static MYSQL_SYSVAR_ULONG(region_size, tokudb_region_size, PLUGIN_VAR_READONLY, "Tokudb Region Size", NULL, NULL, 128 * 1024, 0, ~0L, 0);

static MYSQL_SYSVAR_BOOL(shared_data, tokudb_shared_data, PLUGIN_VAR_READONLY, "Tokudb Shared Data", NULL, NULL, FALSE);

static MYSQL_SYSVAR_STR(tmpdir, tokudb_tmpdir, PLUGIN_VAR_READONLY, "Tokudb Tmp Dir", NULL, NULL, NULL);
3572
#endif
3573

3574 3575
static struct st_mysql_sys_var *tokudb_system_variables[] = {
    MYSQL_SYSVAR(cache_size),
3576
    MYSQL_SYSVAR(cache_memory_percent),
3577
    MYSQL_SYSVAR(max_lock),
3578 3579
    MYSQL_SYSVAR(data_dir),
    MYSQL_SYSVAR(log_dir),
3580
    MYSQL_SYSVAR(debug),
3581
    MYSQL_SYSVAR(commit_sync),
3582
    MYSQL_SYSVAR(version),
3583
    MYSQL_SYSVAR(init_flags),
3584
#if 0
3585
    MYSQL_SYSVAR(cache_parts),
3586 3587 3588 3589 3590 3591 3592 3593
    MYSQL_SYSVAR(env_flags),
    MYSQL_SYSVAR(home),
    MYSQL_SYSVAR(lock_scan_time),
    MYSQL_SYSVAR(lock_type),
    MYSQL_SYSVAR(log_buffer_size),
    MYSQL_SYSVAR(region_size),
    MYSQL_SYSVAR(shared_data),
    MYSQL_SYSVAR(tmpdir),
3594
#endif
3595
    NULL
3596 3597
};

3598
mysql_declare_plugin(tokudb) {
3599 3600 3601 3602
    MYSQL_STORAGE_ENGINE_PLUGIN, 
    &storage_engine_structure, 
    "TokuDB", 
    "Tokutek Inc", 
3603
    "Fractal trees, transactions, row level locks",
3604
    PLUGIN_LICENSE_PROPRIETARY,        /* QQQ license? */
3605
    tokudb_init_func,          /* plugin init */
3606
    tokudb_done_func,          /* plugin deinit */
3607 3608
    0x0200,                    /* QQQ 2.0 */
    NULL,                      /* status variables */
3609
    tokudb_system_variables,   /* system variables */
3610
    NULL                       /* config options */
3611 3612
}
mysql_declare_plugin_end;