ha_tokudb.cc 170 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

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

Zardosht Kasheff's avatar
Zardosht Kasheff committed
53
#include "hatoku_defines.h"
54 55 56
#include "ha_tokudb.h"
#include <mysql/plugin.h>

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

59
handlerton *tokudb_hton;
60 61

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

68

69 70
const char *ha_tokudb_ext = ".tokudb";

Rich Prohaska's avatar
Rich Prohaska committed
71
//static my_bool tokudb_shared_data = FALSE;
72 73 74 75 76
static u_int32_t tokudb_init_flags = 
    DB_CREATE | DB_THREAD | DB_PRIVATE | 
    DB_INIT_LOCK | 
    DB_INIT_MPOOL |
    DB_INIT_TXN | 
77 78
    0 | // disabled for 1.0.2 DB_INIT_LOG |
    0;  // disabled for 1.0.1 DB_RECOVER;
79
static u_int32_t tokudb_env_flags = DB_LOG_AUTOREMOVE;
Rich Prohaska's avatar
Rich Prohaska committed
80
//static u_int32_t tokudb_lock_type = DB_LOCK_DEFAULT;
81 82
//static ulong tokudb_log_buffer_size = 0;
//static ulong tokudb_log_file_size = 0;
83
static ulonglong tokudb_cache_size = 0;
84
static uint tokudb_cache_memory_percent = 50;
85
static char *tokudb_home;
86 87 88
//static char *tokudb_tmpdir;
static char *tokudb_data_dir;
static char *tokudb_log_dir;
Rich Prohaska's avatar
Rich Prohaska committed
89 90
//static long tokudb_lock_scan_time = 0;
//static ulong tokudb_region_size = 0;
91
//static ulong tokudb_cache_parts = 1;
92
static ulong tokudb_max_lock;
93
static ulong tokudb_debug;
94 95 96 97 98
#ifdef TOKUDB_VERSION
static char *tokudb_version = TOKUDB_VERSION;
#else
static char *tokudb_version;
#endif
99 100 101

static DB_ENV *db_env;

102 103 104
static const char tokudb_hton_name[] = "TokuDB";
static const int tokudb_hton_name_length = sizeof(tokudb_hton_name) - 1;

105
// thread variables
106

107 108
static MYSQL_THDVAR_BOOL(commit_sync, PLUGIN_VAR_THDLOCAL, "sync on txn commit", 
                         /* check */ NULL, /* update */ NULL, /* default*/ TRUE);
109 110

static void tokudb_print_error(const DB_ENV * db_env, const char *db_errpfx, const char *buffer);
111
static void tokudb_cleanup_log_files(void);
112 113 114 115 116 117 118 119
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 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
120
static uint tokudb_alter_table_flags(uint flags);
121
#if 0
122 123 124
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);
125
#endif
126
static bool tokudb_show_logs(THD * thd, stat_print_fn * stat_print);
127 128 129 130

static HASH tokudb_open_tables;
pthread_mutex_t tokudb_mutex;

131 132 133
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;
134 135
}

136
static int tokudb_init_func(void *p) {
137
    TOKUDB_DBUG_ENTER("tokudb_init_func");
138

139
    tokudb_hton = (handlerton *) p;
140

141 142
    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);
143

144
    tokudb_hton->state = SHOW_OPTION_YES;
145
    // tokudb_hton->flags= HTON_CAN_RECREATE;  // QQQ this came from skeleton
146
    tokudb_hton->flags = HTON_CLOSE_CURSORS_AT_COMMIT | HTON_FLUSH_AFTER_RENAME;
147
#ifdef DB_TYPE_TOKUDB
148 149 150
    tokudb_hton->db_type = DB_TYPE_TOKUDB;
#else
    tokudb_hton->db_type = DB_TYPE_UNKNOWN;
151 152
#endif

153 154
    tokudb_hton->create = tokudb_create_handler;
    tokudb_hton->close_connection = tokudb_close_connection;
155 156
#if 0
    tokudb_hton->savepoint_offset = sizeof(DB_TXN *);
157 158 159
    tokudb_hton->savepoint_set = tokudb_savepoint;
    tokudb_hton->savepoint_rollback = tokudb_rollback_to_savepoint;
    tokudb_hton->savepoint_release = tokudb_release_savepoint;
160
#endif
Zardosht Kasheff's avatar
Zardosht Kasheff committed
161 162
    tokudb_hton->commit = tokudb_commit;
    tokudb_hton->rollback = tokudb_rollback;
163 164 165
    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
166
    tokudb_hton->alter_table_flags = tokudb_alter_table_flags;
167
#if 0
168 169 170
    if (!tokudb_tmpdir)
        tokudb_tmpdir = mysql_tmpdir;
    DBUG_PRINT("info", ("tokudb_tmpdir: %s", tokudb_tmpdir));
171
#endif
172 173 174
    if (!tokudb_home)
        tokudb_home = mysql_real_data_home;
    DBUG_PRINT("info", ("tokudb_home: %s", tokudb_home));
175
#if 0
176
    if (!tokudb_log_buffer_size) { // QQQ
177 178 179 180 181 182 183
        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));
184
#endif
185 186 187
    int r;
    if ((r = db_env_create(&db_env, 0))) {
        DBUG_PRINT("info", ("db_env_create %d\n", r));
188
        goto error;
189 190
    }

Rich Prohaska's avatar
Rich Prohaska committed
191
    DBUG_PRINT("info", ("tokudb_env_flags: 0x%x\n", tokudb_env_flags));
192
    r = db_env->set_flags(db_env, tokudb_env_flags, 1);
193
    if (r) { // QQQ
Rich Prohaska's avatar
Rich Prohaska committed
194
        if (tokudb_debug & TOKUDB_DEBUG_INIT) 
195 196
            TOKUDB_TRACE("%s:WARNING: flags=%x r=%d\n", __FUNCTION__, tokudb_env_flags, r); 
        // goto error;
197
    }
198 199

    // config error handling
200
    db_env->set_errcall(db_env, tokudb_print_error);
201 202 203
    db_env->set_errpfx(db_env, "TokuDB");

    // config directories
204
#if 0
205 206
    DBUG_PRINT("info", ("tokudb_tmpdir: %s\n", tokudb_tmpdir));
    db_env->set_tmp_dir(db_env, tokudb_tmpdir);
207 208 209 210 211 212 213 214 215 216 217 218 219
#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);
220 221
    }

222
    // config the cache table
223 224 225 226
    if (tokudb_cache_size == 0) {
        unsigned long pagesize = my_getpagesize();
        unsigned long long npages = my_getphyspages();
        unsigned long long physmem = npages * pagesize;
227
        tokudb_cache_size = (ulonglong) (physmem * (tokudb_cache_memory_percent / 100.0));
228
    }
229 230
    if (tokudb_cache_size) {
        DBUG_PRINT("info", ("tokudb_cache_size: %lld\n", tokudb_cache_size));
231
        r = db_env->set_cachesize(db_env, tokudb_cache_size / (1024 * 1024L * 1024L), tokudb_cache_size % (1024L * 1024L * 1024L), 1);
232 233 234 235
        if (r) {
            DBUG_PRINT("info", ("set_cachesize %d\n", r));
            goto error; 
        }
236 237 238 239
    }
    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
240
        if (tokudb_debug & TOKUDB_DEBUG_INIT) 
241
            TOKUDB_TRACE("%s:tokudb_cache_size=%lld\n", __FUNCTION__, ((unsigned long long) gbytes << 30) + bytes);
242

243 244
#if 0
    // QQQ config the logs
245 246 247 248 249 250
    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);
251
#endif
252

253 254
    // config the locks
#if 0 // QQQ no lock types yet
255 256
    DBUG_PRINT("info", ("tokudb_lock_type: 0x%lx\n", tokudb_lock_type));
    db_env->set_lk_detect(db_env, tokudb_lock_type);
257 258 259 260 261 262 263 264 265
#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;
        }
    }
266

267 268 269 270 271 272 273
    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) {
274
        DBUG_PRINT("info", ("env->open %d\n", r));
275 276
        goto error;
    }
277

278
    DBUG_RETURN(FALSE);
279 280 281 282 283 284

error:
    if (db_env) {
        db_env->close(db_env, 0);
        db_env = 0;
    }
285 286 287 288
    DBUG_RETURN(TRUE);
}

static int tokudb_done_func(void *p) {
289
    TOKUDB_DBUG_ENTER("tokudb_done_func");
290 291 292 293 294 295
    int error = 0;

    if (tokudb_open_tables.records)
        error = 1;
    hash_free(&tokudb_open_tables);
    pthread_mutex_destroy(&tokudb_mutex);
296
    TOKUDB_DBUG_RETURN(0);
297 298 299 300 301 302 303
}

/** @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.
*/
304 305 306
static TOKUDB_SHARE *get_share(const char *table_name, TABLE * table) {
    TOKUDB_SHARE *share;
    uint length;
307

308 309 310 311 312 313
    pthread_mutex_lock(&tokudb_mutex);
    length = (uint) strlen(table_name);

    if (!(share = (TOKUDB_SHARE *) hash_search(&tokudb_open_tables, (uchar *) table_name, length))) {
        char *tmp_name;

Zardosht Kasheff's avatar
Zardosht Kasheff committed
314 315 316 317
        //
        // create share and fill it with all zeroes
        // hence, all pointers are initialized to NULL
        //
318 319 320 321 322
        if (!(share = (TOKUDB_SHARE *) 
            my_multi_malloc(MYF(MY_WME | MY_ZEROFILL), 
                            &share, sizeof(*share),
                            &tmp_name, length + 1, 
                            NullS))) {
323 324 325 326 327 328 329
            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);
330

Zardosht Kasheff's avatar
Zardosht Kasheff committed
331
        bzero((void *) share->key_file, sizeof(share->key_file));
332 333 334 335 336

        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);
337
    }
338
    pthread_mutex_unlock(&tokudb_mutex);
339

340
    return share;
341

342
  error:
343 344 345
    pthread_mutex_destroy(&share->mutex);
    my_free((uchar *) share, MYF(0));

346
    return NULL;
347 348
}

349 350 351 352 353 354 355 356 357 358
static int free_share(TOKUDB_SHARE * share, TABLE * table, uint hidden_primary_key, bool mutex_is_locked) {
    int error, result = 0;

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

Zardosht Kasheff's avatar
Zardosht Kasheff committed
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
        //
        // number of open DB's may not be equal to number of keys we have because add_index
        // may have added some. So, we loop through entire array and close any non-NULL value
        // It is imperative that we reset a DB to NULL once we are done with it.
        //
        for (uint i = 0; i < sizeof(share->key_file)/sizeof(share->key_file[0]); i++) {
            if (tokudb_debug & TOKUDB_DEBUG_OPEN) {
                TOKUDB_TRACE("dbclose:%p\n", share->key_file[i]);
            }
            if (share->key_file[i]) { 
                error = share->key_file[i]->close(share->key_file[i], 0);
                if (error) {
                    result = error;
                }
                share->key_file[i] = NULL;
            }
375 376
        }

Zardosht Kasheff's avatar
Zardosht Kasheff committed
377
        if (share->status_block && (error = share->status_block->close(share->status_block, 0))) {
378
            result = error;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
379 380
        }
        
381 382 383 384 385 386 387 388 389

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

392 393 394 395 396
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) {
397
    TOKUDB_DBUG_ENTER("tokudb_end");
398 399
    int error = 0;
    if (db_env) {
400 401
        if (tokudb_init_flags & DB_INIT_LOG)
            tokudb_cleanup_log_files();
402
        error = db_env->close(db_env, 0);       // Error is logged
Zardosht Kasheff's avatar
Zardosht Kasheff committed
403
        db_env = NULL;
404
    }
405
    TOKUDB_DBUG_RETURN(error);
406 407 408
}

static int tokudb_close_connection(handlerton * hton, THD * thd) {
409
    my_free(thd_data_get(thd, hton->slot), MYF(0));
410 411 412 413
    return 0;
}

bool tokudb_flush_logs(handlerton * hton) {
414
    TOKUDB_DBUG_ENTER("tokudb_flush_logs");
415 416
    int error;
    bool result = 0;
417 418 419 420 421 422 423 424 425
    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;
        }
426
    }
427
    TOKUDB_DBUG_RETURN(result);
428 429 430
}

static int tokudb_commit(handlerton * hton, THD * thd, bool all) {
431
    TOKUDB_DBUG_ENTER("tokudb_commit");
432
    DBUG_PRINT("trans", ("ending transaction %s", all ? "all" : "stmt"));
433
    u_int32_t syncflag = THDVAR(thd, commit_sync) ? 0 : DB_TXN_NOSYNC;
434
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
435
    DB_TXN **txn = all ? &trx->all : &trx->stmt;
436 437
    int error = 0;
    if (*txn) {
438
        if (tokudb_debug & TOKUDB_DEBUG_TXN) 
439
            TOKUDB_TRACE("commit:%d:%p\n", all, *txn);
440
        error = (*txn)->commit(*txn, syncflag);
441 442 443 444
        if (*txn == trx->sp_level)
            trx->sp_level = 0;
        *txn = 0;
    } else
445
        if (tokudb_debug & TOKUDB_DEBUG_TXN) 
446
            TOKUDB_TRACE("commit0\n");
447
    TOKUDB_DBUG_RETURN(error);
448 449 450
}

static int tokudb_rollback(handlerton * hton, THD * thd, bool all) {
451
    TOKUDB_DBUG_ENTER("tokudb_rollback");
452
    DBUG_PRINT("trans", ("aborting transaction %s", all ? "all" : "stmt"));
453
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
454
    DB_TXN **txn = all ? &trx->all : &trx->stmt;
455 456
    int error = 0;
    if (*txn) {
457
        if (tokudb_debug & TOKUDB_DEBUG_TXN)
458
            TOKUDB_TRACE("rollback:%p\n", *txn);
459 460 461 462 463
        error = (*txn)->abort(*txn);
	if (*txn == trx->sp_level)
	    trx->sp_level = 0;
	*txn = 0;
    } else
464
        if (tokudb_debug & TOKUDB_DEBUG_TXN) 
465
            TOKUDB_TRACE("abort0\n");
466
    TOKUDB_DBUG_RETURN(error);
467 468
}

469 470
#if 0

471
static int tokudb_savepoint(handlerton * hton, THD * thd, void *savepoint) {
472
    TOKUDB_DBUG_ENTER("tokudb_savepoint");
473 474
    int error;
    DB_TXN **save_txn = (DB_TXN **) savepoint;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
475
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
476 477 478
    if (!(error = db_env->txn_begin(db_env, trx->sp_level, save_txn, 0))) {
        trx->sp_level = *save_txn;
    }
479
    TOKUDB_DBUG_RETURN(error);
480 481 482
}

static int tokudb_rollback_to_savepoint(handlerton * hton, THD * thd, void *savepoint) {
483
    TOKUDB_DBUG_ENTER("tokudb_rollback_to_savepoint");
484 485
    int error;
    DB_TXN *parent, **save_txn = (DB_TXN **) savepoint;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
486
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
487 488 489 490 491
    parent = (*save_txn)->parent;
    if (!(error = (*save_txn)->abort(*save_txn))) {
        trx->sp_level = parent;
        error = tokudb_savepoint(hton, thd, savepoint);
    }
492
    TOKUDB_DBUG_RETURN(error);
493 494 495
}

static int tokudb_release_savepoint(handlerton * hton, THD * thd, void *savepoint) {
496
    TOKUDB_DBUG_ENTER("tokudb_release_savepoint");
497 498
    int error;
    DB_TXN *parent, **save_txn = (DB_TXN **) savepoint;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
499
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
500 501 502 503 504
    parent = (*save_txn)->parent;
    if (!(error = (*save_txn)->commit(*save_txn, 0))) {
        trx->sp_level = parent;
        *save_txn = 0;
    }
505
    TOKUDB_DBUG_RETURN(error);
506
}
507

508
#endif
509 510

static bool tokudb_show_logs(THD * thd, stat_print_fn * stat_print) {
511
    TOKUDB_DBUG_ENTER("tokudb_show_logs");
512 513 514 515 516 517 518 519 520
    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;

521 522
    error = db_env->log_archive(db_env, &all_logs, 0);
    if (error) {
523
        DBUG_PRINT("error", ("log_archive failed (error %d)", error));
524
        db_env->err(db_env, error, "log_archive");
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
        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;
549
    TOKUDB_DBUG_RETURN(error);
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
}

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) {
566
    TOKUDB_DBUG_ENTER("tokudb_cleanup_log_files");
567 568 569 570 571
    char **names;
    int error;

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

573
    if ((error = db_env->log_archive(db_env, &names, 0)) != 0) {
574
        DBUG_PRINT("error", ("log_archive failed (error %d)", error));
575
        db_env->err(db_env, error, "log_archive");
576 577
        DBUG_VOID_RETURN;
    }
578

579 580
    if (names) {
        char **np;
581
        for (np = names; *np; ++np) {
582 583
#if 1
            if (tokudb_debug)
584
                TOKUDB_TRACE("%s:cleanup:%s\n", __FUNCTION__, *np);
585 586 587
#else
            my_delete(*np, MYF(MY_WME));
#endif
588
        }
589

590 591
        free(names);
    }
592

593
    DBUG_VOID_RETURN;
594 595
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609
//
// *******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);

}


610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
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
636

Zardosht Kasheff's avatar
Zardosht Kasheff committed
637
#define HANDLE_INVALID_CURSOR() \
Zardosht Kasheff's avatar
Zardosht Kasheff committed
638 639 640 641 642
    if (cursor == NULL) { \
        error = last_cursor_error; \
        goto cleanup; \
    }

643 644
ha_tokudb::ha_tokudb(handlerton * hton, TABLE_SHARE * table_arg)
:  
Zardosht Kasheff's avatar
Zardosht Kasheff committed
645
    handler(hton, table_arg), alloc_ptr(0), rec_buff(0),
Zardosht Kasheff's avatar
Zardosht Kasheff committed
646
    // flags defined in sql\handler.h
647
    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 | 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
648
                    HA_FILE_BASED | HA_AUTO_PART_KEY | HA_TABLE_SCAN_ON_INDEX), 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
649
    added_rows(0), deleted_rows(0), last_dup_key((uint) - 1), using_ignore(0), last_cursor_error(0),range_lock_grabbed(false), primary_key_offsets(NULL) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
650
    transaction = NULL;
651
}
652

653 654 655
static const char *ha_tokudb_exts[] = {
    ha_tokudb_ext,
    NullS
656 657
};

Zardosht Kasheff's avatar
Zardosht Kasheff committed
658 659 660
/* 
 *  returns NULL terminated file extension string
 */
661
const char **ha_tokudb::bas_ext() const {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
662 663
    TOKUDB_DBUG_ENTER("ha_tokudb::bas_ext");
    DBUG_RETURN(ha_tokudb_exts);
664 665
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
666 667 668 669
//
// Returns a bit mask of capabilities of the key or its part specified by 
// the arguments. The capabilities are defined in sql/handler.h.
//
670
ulong ha_tokudb::index_flags(uint idx, uint part, bool all_parts) const {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
671
    TOKUDB_DBUG_ENTER("ha_tokudb::index_flags");
672
    ulong flags = (HA_READ_NEXT | HA_READ_PREV | HA_READ_ORDER | HA_KEYREAD_ONLY | HA_READ_RANGE);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
673
    DBUG_RETURN(flags);
674 675 676 677 678 679 680 681
}

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
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
/*
    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
737
    bzero((void *) byte_stream, sizeof(*byte_stream));
Yoni Fogel's avatar
Yoni Fogel committed
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801

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

802
static int tokudb_compare_two_keys(KEY *key, const DBT * new_key, const DBT * saved_key, bool cmp_prefix) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
803 804 805 806 807 808 809
    uchar new_key_inf_val = *(uchar *) new_key->data;
    uchar saved_key_inf_val = *(uchar *) saved_key->data;
    //
    // first byte is "infinity" byte
    //
    uchar *new_key_ptr = (uchar *)(new_key->data) + 1;
    uchar *saved_key_ptr = (uchar *)(saved_key->data) + 1;
810
    KEY_PART_INFO *key_part = key->key_part, *end = key_part + key->key_parts;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
811 812 813 814 815 816
    int ret_val;
    //
    // do not include the inf val at the beginning
    //
    uint new_key_length = new_key->size - sizeof(uchar);
    uint saved_key_length = saved_key->size - sizeof(uchar);
817 818

    //DBUG_DUMP("key_in_index", saved_key_ptr, saved_key->size);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
819
    for (; key_part != end && (int) new_key_length > 0 && (int) saved_key_length > 0; key_part++) {
820
        int cmp;
Yoni Fogel's avatar
Yoni Fogel committed
821 822
        uint new_key_field_length;
        uint saved_key_field_length;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
823
        if (key_part->field->null_bit) {
Yoni Fogel's avatar
Yoni Fogel committed
824
            assert(new_key_ptr   < (uchar *) new_key->data   + new_key->size);
825
            assert(saved_key_ptr < (uchar *) saved_key->data + saved_key->size);
Yoni Fogel's avatar
Yoni Fogel committed
826 827 828
            if (*new_key_ptr != *saved_key_ptr) {
                return ((int) *new_key_ptr - (int) *saved_key_ptr); }
            saved_key_ptr++;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
829
            new_key_length--;
830
            saved_key_length--;
Yoni Fogel's avatar
Yoni Fogel committed
831
            if (!*new_key_ptr++) { continue; }
832
        }
Yoni Fogel's avatar
Yoni Fogel committed
833 834
        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);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
835
        assert(new_key_length >= new_key_field_length);
Yoni Fogel's avatar
Yoni Fogel committed
836
        assert(saved_key_length >= saved_key_field_length);
837 838
        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
839
        new_key_ptr      += new_key_field_length;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
840
        new_key_length   -= new_key_field_length;
Yoni Fogel's avatar
Yoni Fogel committed
841 842
        saved_key_ptr    += saved_key_field_length;
        saved_key_length -= saved_key_field_length;
843
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
    if (cmp_prefix || (new_key_length == 0 && saved_key_length == 0) ) {
        ret_val = 0;
    }
    //
    // at this point, one SHOULD be 0
    //
    else if (new_key_length == 0 && saved_key_length > 0) {
        ret_val = (new_key_inf_val == COL_POS_INF ) ? 1 : -1; 
    }
    else if (new_key_length > 0 && saved_key_length == 0) {
        ret_val = (saved_key_inf_val == COL_POS_INF ) ? -1 : 1; 
    }
    //
    // this should never happen, perhaps we should assert(false)
    //
    else {
        ret_val = new_key_length - saved_key_length;
    }
    return ret_val;
863 864
}

865
static int tokudb_cmp_packed_key(DB *file, const DBT *keya, const DBT *keyb) {
866 867
    assert(file->app_private != 0);
    KEY *key = (KEY *) file->app_private;
868 869
    return tokudb_compare_two_keys(key, keya, keyb, false);
}
870

871 872 873 874 875 876 877 878 879 880 881
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);
882 883
}

884
#if 0
885
/* Compare key against row */
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
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;
912
    }
913 914
    return 0;                   // Identical keys
}
915
#endif
916

Zardosht Kasheff's avatar
Zardosht Kasheff committed
917 918 919 920 921 922
int primary_key_part_compare (const void* left, const void* right) {
    PRIM_KEY_PART_INFO* left_part= (PRIM_KEY_PART_INFO *)left;
    PRIM_KEY_PART_INFO* right_part = (PRIM_KEY_PART_INFO *)right;
    return left_part->offset - right_part->offset;
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
//
// struct that will be used as a context for smart DBT callbacks
// contains parameters needed to complete the smart DBT cursor call
//
typedef struct smart_dbt_info {
    ha_tokudb* ha; //instance to ha_tokudb needed for reading the row
    uchar* buf; // output buffer where row will be written
    uint keynr; // index into share->key_file that represents DB we are currently operating on
} *SMART_DBT_INFO;

//
// struct that will be used as a context for smart DBT callbacks
// ONLY for the function add_index
//
typedef struct smart_dbt_ai_info {
    ha_tokudb* ha; //instance to ha_tokudb needed for reading the row
    DBT* prim_key; // DBT to store the primary key
    uchar* buf; // buffer to unpack the row
} *SMART_DBT_AI_INFO;

static void smart_dbt_ai_callback (DBT const *key, DBT  const *row, void *context) {
    SMART_DBT_AI_INFO info = (SMART_DBT_AI_INFO)context;
    info->ha->unpack_row(info->buf,row,key);
    //
    // copy the key to prim_key
    //
    info->prim_key->size = key->size;
    memcpy(info->prim_key->data, key->data, key->size);
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
953 954 955 956 957 958 959 960 961 962 963
//
// smart DBT callback function for optimize
// in optimize, we want to flatten DB by doing
// a full table scan. Therefore, we don't
// want to actually do anything with the data, hence
// callback does nothing
//
static void smart_dbt_opt_callback (DBT const *key, DBT  const *row, void *context) {
}


Zardosht Kasheff's avatar
Zardosht Kasheff committed
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
//
// Smart DBT callback function in case where we have a covering index
//
static void smart_dbt_callback_keyread(DBT const *key, DBT  const *row, void *context) {
    SMART_DBT_INFO info = (SMART_DBT_INFO)context;
    info->ha->extract_hidden_primary_key(info->keynr, row, key);
    info->ha->read_key_only(info->buf,info->keynr,row,key);
}

//
// Smart DBT callback function in case where we do NOT have a covering index
//
static void smart_dbt_callback_rowread(DBT const *key, DBT  const *row, void *context) {
    SMART_DBT_INFO info = (SMART_DBT_INFO)context;
    info->ha->extract_hidden_primary_key(info->keynr, row, key);
    info->ha->read_primary_key(info->buf,info->keynr,row,key);
}

//
// Smart DBT callback function in c_getf_heavi, in case where we have a covering index, 
//
static void smart_dbt_callback_keyread_heavi(DBT const *key, DBT  const *row, void *context, int r_h) {
    smart_dbt_callback_keyread(key,row,context);
}

//
// Smart DBT callback function in c_getf_heavi, in case where we do NOT have a covering index
//
static void smart_dbt_callback_rowread_heavi(DBT const *key, DBT  const *row, void *context, int r_h) {
    smart_dbt_callback_rowread(key,row,context);
}
Zardosht Kasheff's avatar
Zardosht Kasheff committed
995

Zardosht Kasheff's avatar
Zardosht Kasheff committed
996 997 998 999 1000 1001 1002 1003 1004 1005
//
// Smart DBT callback function in records_in_range
//
static void smart_dbt_callback_ror_heavi(DBT const *key, DBT  const *row, void *context, int r_h) {
    DBT* copied_key = (DBT *)context;
    copied_key->size = key->size;
    memcpy(copied_key->data, key->data, key->size);
}


Zardosht Kasheff's avatar
Zardosht Kasheff committed
1006 1007 1008 1009 1010
//
// macro for Smart DBT callback function, 
// so we do not need to put this long line of code in multiple places
//
#define SMART_DBT_CALLBACK ( this->key_read ? smart_dbt_callback_keyread : smart_dbt_callback_rowread ) 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1011 1012


Zardosht Kasheff's avatar
Zardosht Kasheff committed
1013 1014 1015 1016
//
// macro that modifies read flag for cursor operations depending on whether
// we have preacquired lock or not
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1017
#define SET_READ_FLAG(flg) ((range_lock_grabbed || current_thd->options & OPTION_TABLE_LOCK) ? ((flg) | DB_PRELOCKED) : (flg))
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1018

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031

//
// This method retrieves the value of the auto increment column of a record in MySQL format
// This was basically taken from MyISAM
// Parameters:
//              type - the type of the auto increment column (e.g. int, float, double...)
//              offset - offset into the record where the auto increment column is stored
//      [in]    record - MySQL row whose auto increment value we want to extract
// Returns:
//      The value of the auto increment column in record
//
ulonglong retrieve_auto_increment(uint16 type, uint32 offset,const uchar *record)
{
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    const uchar *key;     /* Key */
    ulonglong   unsigned_autoinc;  /* Unsigned auto-increment */
    longlong      signed_autoinc;  /* Signed auto-increment */
    enum { unsigned_type, signed_type } autoinc_type;
    float float_tmp;   /* Temporary variable */
    double double_tmp; /* Temporary variable */

    key = ((uchar *) record) + offset;

    /* Set default autoincrement type */
    autoinc_type = unsigned_type;

    switch (type) {
    case HA_KEYTYPE_INT8:
        signed_autoinc   = (longlong) *(char*)key;
        autoinc_type     = signed_type;
        break;

    case HA_KEYTYPE_BINARY:
        unsigned_autoinc = (ulonglong) *(uchar*) key;
        break;

    case HA_KEYTYPE_SHORT_INT:
        signed_autoinc   = (longlong) sint2korr(key);
        autoinc_type     = signed_type;
        break;

    case HA_KEYTYPE_USHORT_INT:
        unsigned_autoinc = (ulonglong) uint2korr(key);
        break;

    case HA_KEYTYPE_LONG_INT:
        signed_autoinc   = (longlong) sint4korr(key);
        autoinc_type     = signed_type;
        break;

    case HA_KEYTYPE_ULONG_INT:
        unsigned_autoinc = (ulonglong) uint4korr(key);
        break;

    case HA_KEYTYPE_INT24:
        signed_autoinc   = (longlong) sint3korr(key);
        autoinc_type     = signed_type;
        break;

    case HA_KEYTYPE_UINT24:
        unsigned_autoinc = (ulonglong) uint3korr(key);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1079
    break;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

    case HA_KEYTYPE_LONGLONG:
        signed_autoinc   = sint8korr(key);
        autoinc_type     = signed_type;
        break;

    case HA_KEYTYPE_ULONGLONG:
        unsigned_autoinc = uint8korr(key);
        break;

    /* The remaining two cases should not be used but are included for 
       compatibility */
    case HA_KEYTYPE_FLOAT:                      
        float4get(float_tmp, key);  /* Note: float4get is a macro */
        signed_autoinc   = (longlong) float_tmp;
        autoinc_type     = signed_type;
        break;

    case HA_KEYTYPE_DOUBLE:
        float8get(double_tmp, key); /* Note: float8get is a macro */
        signed_autoinc   = (longlong) double_tmp;
        autoinc_type     = signed_type;
        break;

    default:
        DBUG_ASSERT(0);
        unsigned_autoinc = 0;
    }

    if (signed_autoinc < 0) {
        signed_autoinc = 0;
    }

    return autoinc_type == unsigned_type ?  
           unsigned_autoinc : (ulonglong) signed_autoinc;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1115 1116 1117
}


Zardosht Kasheff's avatar
Zardosht Kasheff committed
1118

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1119
inline uint get_null_offset(TABLE* table, Field* field) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
    return (uint) ((uchar*) field->null_ptr - (uchar*) table->record[0]);
}

inline bool
is_null_field( TABLE* table, Field* field, const uchar* record) {
	uint null_offset;
    bool ret_val;
	if (!field->null_ptr) {
		ret_val = false;
        goto exitpt;
	}
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1131
	null_offset = get_null_offset(table,field);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1132 1133 1134 1135 1136 1137 1138 1139 1140
    ret_val = (record[null_offset] & field->null_bit) ? true: false;

exitpt:
	return ret_val;
}




Zardosht Kasheff's avatar
Zardosht Kasheff committed
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
//
// 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;

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1152
    open_flags += DB_AUTO_COMMIT;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

    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));
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1173
    else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1174 1175
        (*ptr)->set_bt_compare(*ptr, tokudb_cmp_packed_key);    
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1176 1177 1178 1179 1180 1181
    
    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);

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    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
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
//
// 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
//
1206
int ha_tokudb::open(const char *name, int mode, uint test_if_locked) {
1207
    TOKUDB_DBUG_ENTER("ha_tokudb::open %p %s", this, name);
1208 1209 1210
    TOKUDB_OPEN();

    char name_buff[FN_REFLEN];
1211
    uint open_flags = (mode == O_RDONLY ? DB_RDONLY : 0) | DB_THREAD;
1212 1213 1214
    uint max_key_length;
    int error;

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1215 1216 1217
    transaction = NULL;
    cursor = NULL;

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1218
    open_flags += DB_AUTO_COMMIT;
1219

1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
    /* 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 */
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1231 1232
    // the "+ 1" is for the first byte that states +/- infinity
    max_key_length = table_share->max_key_length + MAX_REF_PARTS * 3 + sizeof(uchar);
1233 1234
    if (!(alloc_ptr =
          my_multi_malloc(MYF(MY_WME),
1235 1236 1237 1238
                          &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)))
1239
        TOKUDB_DBUG_RETURN(1);
1240 1241
    if (!(rec_buff = (uchar *) my_malloc((alloced_rec_buff_length = table_share->rec_buff_length), MYF(MY_WME)))) {
        my_free(alloc_ptr, MYF(0));
1242
        TOKUDB_DBUG_RETURN(1);
1243 1244 1245 1246 1247 1248
    }

    /* Init shared structure */
    if (!(share = get_share(name, table))) {
        my_free((char *) rec_buff, MYF(0));
        my_free(alloc_ptr, MYF(0));
1249
        TOKUDB_DBUG_RETURN(1);
1250
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
    /* Make sorted list of primary key parts, if they exist*/
    if (!hidden_primary_key) {
        uint num_prim_key_parts = table_share->key_info[table_share->primary_key].key_parts;
        primary_key_offsets = (PRIM_KEY_PART_INFO *)my_malloc(
            num_prim_key_parts*sizeof(*primary_key_offsets), 
            MYF(MY_WME)
            );
        
        if (!primary_key_offsets) {
            free_share(share, table, hidden_primary_key, 1);
            my_free((char *) rec_buff, MYF(0));
            my_free(alloc_ptr, MYF(0));
            TOKUDB_DBUG_RETURN(1);
        }
        for (uint i = 0; i < table_share->key_info[table_share->primary_key].key_parts; i++) {
            primary_key_offsets[i].offset = table_share->key_info[table_share->primary_key].key_part[i].offset;
            primary_key_offsets[i].part_index = i;
        }
        qsort(
            primary_key_offsets, // start of array
            num_prim_key_parts, //num elements
            sizeof(*primary_key_offsets), //size of each element
            primary_key_part_compare
            );
    }

1277 1278 1279 1280 1281
    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
1282
    if (tokudb_debug & TOKUDB_DEBUG_OPEN)
1283 1284
        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);
1285 1286
    if (!share->use_count++) {
        DBUG_PRINT("info", ("share->use_count %u", share->use_count));
Yoni Fogel's avatar
Yoni Fogel committed
1287
        DBT cmp_byte_stream;
1288

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1289
        if ((error = db_create(&share->file, db_env, 0))) {
1290 1291 1292
            free_share(share, table, hidden_primary_key, 1);
            my_free((char *) rec_buff, MYF(0));
            my_free(alloc_ptr, MYF(0));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1293
            if (primary_key_offsets) my_free(primary_key_offsets, MYF(0));
1294
            my_errno = error;
1295
            TOKUDB_DBUG_RETURN(1);
1296 1297 1298
        }

        if (!hidden_primary_key)
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1299
            share->file->app_private = (void *) (table_share->key_info + table_share->primary_key);
Yoni Fogel's avatar
Yoni Fogel committed
1300 1301 1302
        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
1303
            if ((error = tokutrace_db_get_cmp_byte_stream(share->file, &cmp_byte_stream))) {
Yoni Fogel's avatar
Yoni Fogel committed
1304 1305 1306
                free_share(share, table, hidden_primary_key, 1);
                my_free((char *) rec_buff, MYF(0));
                my_free(alloc_ptr, MYF(0));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1307
                if (primary_key_offsets) my_free(primary_key_offsets, MYF(0));
Yoni Fogel's avatar
Yoni Fogel committed
1308 1309 1310
                my_errno = error;
                TOKUDB_DBUG_RETURN(1);
            }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1311
            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
1312 1313 1314
            my_free(cmp_byte_stream.data, MYF(0));
        }
        else
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1315
            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
1316
        
1317
        char newname[strlen(name) + 32];
1318 1319
        make_name(newname, name, "main");
        fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1320
        if ((error = share->file->open(share->file, 0, name_buff, NULL, DB_BTREE, open_flags, 0))) {
1321 1322 1323
            free_share(share, table, hidden_primary_key, 1);
            my_free((char *) rec_buff, MYF(0));
            my_free(alloc_ptr, MYF(0));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1324
            if (primary_key_offsets) my_free(primary_key_offsets, MYF(0));
1325
            my_errno = error;
1326
            TOKUDB_DBUG_RETURN(1);
1327
        }
Rich Prohaska's avatar
Rich Prohaska committed
1328
        if (tokudb_debug & TOKUDB_DEBUG_OPEN)
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1329
            TOKUDB_TRACE("open:%s:file=%p\n", newname, share->file);
1330 1331

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

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1335 1336
        DB **ptr = share->key_file;
        for (uint i = 0; i < table_share->keys; i++, ptr++) {
1337
            if (i != primary_key) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1338
                if ((error = open_secondary_table(ptr,&table_share->key_info[i],name,mode,&share->key_type[i]))) {
1339
                    __close(1);
1340
                    TOKUDB_DBUG_RETURN(1);
1341 1342 1343 1344 1345 1346
                }
            }
        }
        /* Calculate pack_length of primary key */
        share->fixed_length_primary_key = 1;
        if (!hidden_primary_key) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1347 1348 1349 1350 1351 1352
            //
            // I realize this is incredibly confusing, and refactoring should take 
            // care of this, but we need to set the ref_length to start at 1, to account for
            // the "infinity byte" in keys.
            //
            ref_length = sizeof(uchar);
1353 1354 1355 1356
            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);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1357
            share->fixed_length_primary_key = (ref_length == table->key_info[primary_key].key_length + sizeof(uchar));
1358 1359 1360
            share->status |= STATUS_PRIMARY_KEY_INIT;
        }
        share->ref_length = ref_length;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1361

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1362
        error = get_status();
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1363
        if (error || share->version < HA_TOKU_VERSION) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1364 1365 1366
            __close(1);
            TOKUDB_DBUG_RETURN(1);
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
        //////////////////////
        u_int64_t num_rows = 0;
        int error = estimate_num_rows(share->file,&num_rows);
        //
        // estimate_num_rows should not fail under normal conditions
        //
        if (error == 0) {
            share->rows = num_rows;
        }
        else {
            __close(1);
            TOKUDB_DBUG_RETURN(1);
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1380 1381 1382 1383 1384 1385 1386
        //
        // initialize auto increment data
        //
        share->has_auto_inc = has_auto_increment_flag(&share->ai_field_index);
        if (share->has_auto_inc) {
            init_auto_increment();
        }
1387 1388 1389 1390
    }
    ref_length = share->ref_length;     // If second open
    pthread_mutex_unlock(&share->mutex);

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1391
    key_read = false;
1392
    stats.block_size = 1<<20;    // QQQ Tokudb DB block size
1393 1394
    share->fixed_length_row = !(table_share->db_create_options & HA_OPTION_PACK_RECORD);

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1395 1396
    init_hidden_prim_key_info();

1397 1398
    info(HA_STATUS_NO_LOCK | HA_STATUS_VARIABLE | HA_STATUS_CONST);

1399
    TOKUDB_DBUG_RETURN(0);
1400 1401
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
//
// estimate the number of rows in a DB
// Parameters:
//      [in]    db - DB whose number of rows will be estimated
//      [out]   num_rows - number of estimated rows in db
// Returns:
//      0 on success
//      error otherwise
//
int ha_tokudb::estimate_num_rows(DB* db, u_int64_t* num_rows) {
    DBT key;
    DBT data;
    int error = ENOSYS;
    DBC* crsr = NULL;
    u_int64_t less, equal, greater;
    int is_exact;
    bool do_commit = false;

    bzero((void *)&key, sizeof(key));
    bzero((void *)&data, sizeof(data));

    if (transaction == NULL) {
        error = db_env->txn_begin(db_env, 0, &transaction, 0);
        if (error) goto cleanup;
        do_commit = true;
    }
    
    error = db->cursor(db, transaction, &crsr, 0);
    if (error) { goto cleanup; }

    //
    // get the first element, then estimate number of records
    // by calling key_range64 on the first element
    //
    error = crsr->c_get(crsr, &key, &data, DB_FIRST);
    if (error == DB_NOTFOUND) {
        *num_rows = 0;
        error = 0;
        goto cleanup;
    }
    else if (error) { goto cleanup; }

    error = db->key_range64(
        db, 
        transaction, 
        &key, 
        &less,
        &equal,
        &greater,
        &is_exact
        );
    if (error) {
        goto cleanup;
    }


    *num_rows = equal + greater;
    error = 0;
cleanup:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1461
    if (do_commit) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1462 1463 1464
        transaction->commit(transaction, 0);
        transaction = NULL;
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1465 1466 1467 1468
    if (crsr != NULL) {
        crsr->c_close(crsr);
        crsr = NULL;
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1469 1470 1471
    return error;
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
//
// states if table has an auto increment column, if so, sets index where auto inc column is to index
// Parameters:
//      [out]   index - if auto inc exists, then this param is set to where it exists in table, if not, then unchanged
// Returns:
//      true if auto inc column exists, false otherwise
//
bool ha_tokudb::has_auto_increment_flag(uint* index) {
    //
    // check to see if we have auto increment field
    //
    bool ai_found = false;
    uint i = 0;
    for (Field ** field = table->field; *field; field++,i++) {
        if ((*field)->flags & AUTO_INCREMENT_FLAG) {
            ai_found = true;
            *index = i;
            break;
        }
    }
    return ai_found;
}
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1494

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
//
// helper function to write a piece of metadata in to status.tokudb
//
int ha_tokudb::write_metadata(DB* db, HA_METADATA_KEY curr_key_data, void* data, ulonglong size ){
    int error;
    DBT key;
    DBT value;
    DB_TXN* txn = NULL;
    //
    // transaction to be used for putting metadata into status.tokudb
    //
    error = db_env->txn_begin(db_env, 0, &txn, 0);
    if (error) { 
        goto cleanup;
    }

    bzero(&key, sizeof(key));
    bzero(&value, sizeof(value));
    key.data = &curr_key_data;
    key.size = sizeof(curr_key_data);
    value.data = data;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1516
    value.size = size;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
    error = db->put(db, txn, &key, &value, 0);
    if (error) { 
        goto cleanup; 
    }
    
    error = 0;
cleanup:
    if (txn) {
        if (!error) {
            txn->commit(txn, DB_TXN_NOSYNC);
        }
        else {
            txn->abort(txn);
        }
    }
    return error;
}



//
// Updates status.tokudb with a new max value used for the auto increment column
// Parameters:
//      [in]    db - this will always be status.tokudb
//              val - value to store
//  Returns:
//      0 on success, error otherwise
//
//
int ha_tokudb::update_max_auto_inc(DB* db, ulonglong val){
    return write_metadata(db,hatoku_max_ai,&val,sizeof(val));
}

//
// Writes the initial auto increment value, as specified by create table
// so if a user does "create table t1 (a int auto_increment, primary key (a)) auto_increment=100",
// then the value 100 will be stored here in val
// Parameters:
//      [in]    db - this will always be status.tokudb
//              val - value to store
//  Returns:
//      0 on success, error otherwise
//
//
int ha_tokudb::write_auto_inc_create(DB* db, ulonglong val){
    return write_metadata(db,hatoku_ai_create_value,&val,sizeof(val));
}
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1564 1565


Zardosht Kasheff's avatar
Zardosht Kasheff committed
1566 1567 1568
//
// Closes a handle to a table. 
//
1569
int ha_tokudb::close(void) {
1570
    TOKUDB_DBUG_ENTER("ha_tokudb::close %p", this);
1571
    TOKUDB_CLOSE();
1572
    TOKUDB_DBUG_RETURN(__close(0));
1573 1574 1575
}

int ha_tokudb::__close(int mutex_is_locked) {
1576
    TOKUDB_DBUG_ENTER("ha_tokudb::__close %p", this);
1577
    if (tokudb_debug & TOKUDB_DEBUG_OPEN) 
1578
        TOKUDB_TRACE("close:%p\n", this);
1579 1580
    my_free(rec_buff, MYF(MY_ALLOW_ZERO_PTR));
    my_free(alloc_ptr, MYF(MY_ALLOW_ZERO_PTR));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1581
    my_free(primary_key_offsets, MYF(MY_ALLOW_ZERO_PTR));
1582
    ha_tokudb::reset();         // current_row buffer
1583
    TOKUDB_DBUG_RETURN(free_share(share, table, hidden_primary_key, mutex_is_locked));
1584 1585
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1586 1587 1588 1589 1590 1591
//
// Reallocate record buffer (rec_buff) if needed
// If not needed, does nothing
// Parameters:
//          length - size of buffer required for rec_buff
//
1592 1593 1594 1595 1596 1597 1598 1599 1600
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;
1601 1602 1603
}

/* Calculate max length needed for row */
1604 1605 1606 1607 1608
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]);
1609
        length += blob->get_length((uchar *) (buf + field_offset(blob))) + 2;
1610 1611
    }
    return length;
1612 1613 1614 1615
}

/*
*/
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
//
// 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
//
1628

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1629
int ha_tokudb::pack_row(DBT * row, const uchar * record) {
1630
    uchar *ptr;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1631
    int r = ENOSYS;
1632
    bzero((void *) row, sizeof(*row));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1633 1634 1635 1636 1637 1638 1639 1640 1641
    uint curr_skip_index;

    KEY *key_info = table->key_info + primary_key;
    my_bitmap_map *old_map = dbug_tmp_use_all_columns(table, table->write_set);

    //
    // two cases, fixed length row, and variable length row
    // fixed length row is first below
    //
1642
    if (share->fixed_length_row) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
        if (hidden_primary_key) {
            row->data = (void *)record;
            row->size = table_share->reclength;
            r = 0;
            goto cleanup;
        }
        else {
            //
            // if the primary key is not hidden, then it is part of the record
            // because primary key information is already stored in the key
            // that will be passed to the fractal tree, we do not copy
            // components that belong to the primary key
            //
            if (fix_rec_buff_for_blob(table_share->reclength)) {
                r = HA_ERR_OUT_OF_MEM;
                goto cleanup;
            }

            uchar* tmp_dest = rec_buff;
            const uchar* tmp_src = record;
            uint i = 0;
            //
            // say we have 100 bytes in record, and bytes 25-50 and 75-90 belong to the primary key
            // this for loop will do a memcpy [0,25], [51,75] and [90,100]
            //
            for (i =0; i < key_info->key_parts; i++){
                uint curr_index = primary_key_offsets[i].part_index;
                uint bytes_to_copy = record + key_info->key_part[curr_index].offset - tmp_src;
                memcpy(tmp_dest,tmp_src, bytes_to_copy);
                tmp_dest += bytes_to_copy;
                tmp_src = record + key_info->key_part[curr_index].offset + key_info->key_part[curr_index].length;
            }
            memcpy(tmp_dest,tmp_src, record + table_share->reclength - tmp_src);
            tmp_dest += record + table_share->reclength - tmp_src;

            row->data = rec_buff;
            row->size = (size_t) (tmp_dest - rec_buff);

            r = 0;
            goto cleanup;
        }
1684
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1685
    
1686
    if (table_share->blob_fields) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1687 1688 1689 1690
        if (fix_rec_buff_for_blob(max_row_length(record))) {
            r = HA_ERR_OUT_OF_MEM;
            goto cleanup;
        }
1691 1692
    }

1693
    /* Copy null bits */
1694 1695 1696
    memcpy(rec_buff, record, table_share->null_bytes);
    ptr = rec_buff + table_share->null_bytes;

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1697 1698 1699 1700 1701
    //
    // assert that when the hidden primary key exists, primary_key_offsets is NULL
    //
    assert( (hidden_primary_key != 0) == (primary_key_offsets == NULL));
    curr_skip_index = 0;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1702
    for (Field ** field = table->field; *field; field++) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
        uint curr_field_offset = field_offset(*field);
        //
        // if the primary key is hidden, primary_key_offsets will be NULL and
        // this clause will not execute
        //
        if (primary_key_offsets) {
            uint curr_skip_offset = primary_key_offsets[curr_skip_index].offset;
            if (curr_skip_offset == curr_field_offset) {
                //
                // we have hit a field that is a portion of the primary key
                //
                uint curr_key_index = primary_key_offsets[curr_skip_index].part_index;
                curr_skip_index++;
                //
                // only choose to continue over the key if the key's length matches the field's length
                // otherwise, we may have a situation where the column is a varchar(10), the
                // key is only the first 3 characters, and we end up losing the last 7 bytes of the
                // column
                //
                if (table->key_info[primary_key].key_part[curr_key_index].length == (*field)->field_length) {
                    continue;
                }
            }
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1727 1728 1729
        if (is_null_field(table, *field, record)) {
            continue;
        }
1730
        ptr = (*field)->pack(ptr, (const uchar *)
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1731
                             (record + curr_field_offset));
1732
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1733

1734 1735
    row->data = rec_buff;
    row->size = (size_t) (ptr - rec_buff);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1736 1737 1738 1739 1740 1741
    r = 0;

cleanup:
    dbug_tmp_restore_column_map(table->write_set, old_map);

    return r;
1742 1743
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1744 1745 1746 1747 1748 1749
//
// 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
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1750
void ha_tokudb::unpack_row(uchar * record, DBT const *row, DBT const *key) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
    //
    // two cases, fixed length row, and variable length row
    // fixed length row is first below
    //
    if (share->fixed_length_row) {
        if (hidden_primary_key) {
            memcpy(record, (void *) row->data, table_share->reclength);
        }
        else {
            my_bitmap_map *old_map = dbug_tmp_use_all_columns(table, table->write_set);
            KEY *key_info = table_share->key_info + primary_key;

            uchar* tmp_dest = record;
            uchar* tmp_src = (uchar *)row->data;
            uint i = 0;

            //
            // unpack_key will fill in parts of record that are part of the primary key
            //
            unpack_key(record, key, primary_key);

            //
            // produces the opposite effect to what happened in pack_row
            // first we fill in the parts of record that are not part of the key
            //
            for (i =0; i < key_info->key_parts; i++){
                uint curr_index = primary_key_offsets[i].part_index;
                uint bytes_to_copy = record + key_info->key_part[curr_index].offset - tmp_dest;
                memcpy(tmp_dest,tmp_src, bytes_to_copy);
                tmp_src += bytes_to_copy;
                tmp_dest = record + key_info->key_part[curr_index].offset + key_info->key_part[curr_index].length;
            }
            memcpy(tmp_dest,tmp_src, record + table_share->reclength - tmp_dest);
            dbug_tmp_restore_column_map(table->write_set, old_map);
        }
    }
1787 1788 1789 1790 1791 1792
    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;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
        if (primary_key_offsets) {
            //
            // unpack_key will fill in parts of record that are part of the primary key
            //
            unpack_key(record, key, primary_key);
        }

        //
        // fill in parts of record that are not part of the key
        //
        uint curr_skip_index = 0;
        for (Field ** field = table->field; *field; field++) {
            uint curr_field_offset = field_offset(*field);
            if (primary_key_offsets) {
                uint curr_skip_offset = primary_key_offsets[curr_skip_index].offset;
                if (curr_skip_offset == curr_field_offset) {
                    //
                    // we have hit a field that is a portion of the primary key
                    //
                    uint curr_key_index = primary_key_offsets[curr_skip_index].part_index;
                    curr_skip_index++;
                    //
                    // only choose to continue over the key if the key's length matches the field's length
                    // otherwise, we may have a situation where the column is a varchar(10), the
                    // key is only the first 3 characters, and we end up losing the last 7 bytes of the
                    // column
                    //
                    if (table->key_info[primary_key].key_part[curr_key_index].length == (*field)->field_length) {
                        continue;
                    }
                }
            }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1825 1826 1827 1828 1829 1830
            //
            // null bytes MUST have been copied before doing this
            //
            if (is_null_field(table, *field, record)) {
                continue;
            }
1831
            ptr = (*field)->unpack(record + field_offset(*field), ptr);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1832
        }
1833 1834
        dbug_tmp_restore_column_map(table->write_set, old_map);
    }
1835 1836
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1837

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1838 1839 1840 1841 1842 1843 1844 1845
//
// 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
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1846
void ha_tokudb::unpack_key(uchar * record, DBT const *key, uint index) {
1847 1848
    KEY *key_info = table->key_info + index;
    KEY_PART_INFO *key_part = key_info->key_part, *end = key_part + key_info->key_parts;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1849
    uchar *pos = (uchar *) key->data + 1;
1850 1851 1852

    for (; key_part != end; key_part++) {
        if (key_part->null_bit) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1853
            if (*pos++ == NULL_COL_VAL) { // Null value
1854 1855 1856 1857 1858 1859 1860 1861 1862
                /*
                   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;
        }
1863 1864 1865
        /* tokutek change to make pack_key and unpack_key work for
           decimals */
        uint unpack_length = key_part->length;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1866
        pos = (uchar *) key_part->field->unpack_key(record + field_offset(key_part->field), pos,
1867
#if MYSQL_VERSION_ID < 50123
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1868
                                                    unpack_length);
1869
#else
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1870
                                                    unpack_length, table->s->db_low_byte_first);
1871
#endif
1872
    }
1873 1874
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1875

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1876 1877 1878 1879 1880
//
// 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
1881
//      [in]    key_info - holds data about the key, such as it's length and offset into record
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1882 1883 1884 1885 1886 1887 1888
//      [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
//
1889

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1890
DBT* ha_tokudb::create_dbt_key_from_key(DBT * key, KEY* key_info, uchar * buff, const uchar * record, bool* has_null, int key_length) {
1891 1892 1893 1894 1895
    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;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1896 1897 1898 1899 1900 1901 1902 1903 1904

    //
    // first put the "infinity" byte at beginning. States if missing columns are implicitly
    // positive infinity or negative infinity. For this, because we are creating key
    // from a row, there is no way that columns can be missing, so in practice,
    // this will be meaningless. Might as well put in a value
    //
    *buff++ = COL_NEG_INF;

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1905
    *has_null = false;
1906
    for (; key_part != end && key_length > 0; key_part++) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1907 1908 1909 1910 1911 1912
        //
        // 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) {
1913
            /* Store 0 if the key part is a NULL part */
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1914 1915 1916
            uint null_offset = (uint) ((char*) key_part->field->null_ptr
                            - (char*) table->record[0]);
            if (record[null_offset] & key_part->field->null_bit) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1917
                *buff++ = NULL_COL_VAL;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1918
                *has_null = true;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1919 1920 1921 1922 1923
                //
                // fractal tree does not handle this falg at the moment
                // so commenting out for now
                //
                //key->flags |= DB_DBT_DUPOK;
1924 1925
                continue;
            }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1926
            *buff++ = NONNULL_COL_VAL;        // Store NOT NULL marker
1927
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1928 1929 1930 1931 1932 1933
        //
        // 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)),
1934
#if MYSQL_VERSION_ID < 50123
1935
                                         key_part->length);
1936
#else
1937
                                         key_part->length, table->s->db_low_byte_first);
1938
#endif
1939 1940 1941 1942 1943
        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
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
    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
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1957
//      [out]   has_null - says if the key has a NULL value for one of its columns
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1958 1959 1960 1961
//              key_length - currently set to MAX_KEY_LENGTH, is it size of buff?
// Returns:
//      the parameter key
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1962
DBT *ha_tokudb::create_dbt_key_from_table(DBT * key, uint keynr, uchar * buff, const uchar * record, bool* has_null, int key_length) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1963 1964 1965 1966 1967
    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;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1968
        *has_null = false;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1969 1970
        DBUG_RETURN(key);
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1971
    DBUG_RETURN(create_dbt_key_from_key(key, &table->key_info[keynr],buff,record, has_null, key_length));
1972 1973 1974
}


Zardosht Kasheff's avatar
Zardosht Kasheff committed
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
//
// 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
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1987
DBT *ha_tokudb::pack_key(DBT * key, uint keynr, uchar * buff, const uchar * key_ptr, uint key_length, uchar inf_byte) {
1988
    TOKUDB_DBUG_ENTER("ha_tokudb::pack_key");
1989 1990 1991 1992 1993 1994 1995 1996
    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;

Zardosht Kasheff's avatar
Zardosht Kasheff committed
1997 1998 1999 2000 2001 2002
    //
    // first put the "infinity" byte at beginning. States if missing columns are implicitly
    // positive infinity or negative infinity
    //
    *buff++ = inf_byte;

2003 2004 2005
    for (; key_part != end && (int) key_length > 0; key_part++) {
        uint offset = 0;
        if (key_part->null_bit) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2006 2007
            if (!(*key_ptr == 0)) {
                *buff++ = NULL_COL_VAL;
2008 2009 2010 2011
                key_length -= key_part->store_length;
                key_ptr += key_part->store_length;
                continue;
            }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2012
            *buff++ = NONNULL_COL_VAL;
2013 2014 2015
            offset = 1;         // Data is at key_ptr+1
        }
        buff = key_part->field->pack_key_from_key_image(buff, (uchar *) key_ptr + offset,
2016
#if MYSQL_VERSION_ID < 50123
2017
                                                        key_part->length);
2018
#else
2019
                                                        key_part->length, table->s->db_low_byte_first);
2020
#endif
2021 2022 2023 2024 2025 2026 2027
        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);
2028 2029
}

2030
int ha_tokudb::read_last() {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2031
    TOKUDB_DBUG_ENTER("ha_tokudb::read_last");
2032
    int do_commit = 0;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2033
    if (transaction == NULL) {
2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
        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
2045
        transaction = NULL;
2046
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2047
    TOKUDB_DBUG_RETURN(error);
2048 2049
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2050 2051 2052 2053 2054
//
// get max used hidden primary key value
//
void ha_tokudb::init_hidden_prim_key_info() {
    TOKUDB_DBUG_ENTER("ha_tokudb::init_prim_key_info");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2055
    pthread_mutex_lock(&share->mutex);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2056 2057 2058 2059 2060 2061
    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) {
            share->auto_ident = uint5korr(current_ident);
2062
        }
2063

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2064
        share->status |= STATUS_PRIMARY_KEY_INIT;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2065 2066
    }
    pthread_mutex_unlock(&share->mutex);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2067 2068
    DBUG_VOID_RETURN;
}
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2069

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2070 2071 2072 2073 2074


/** @brief
    Get metadata info stored in status.tokudb
    */
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2075
int ha_tokudb::get_status() {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2076
    TOKUDB_DBUG_ENTER("ha_tokudb::get_status");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2077 2078 2079 2080
    DB_TXN* txn = NULL;
    DBT key, value;
    HA_METADATA_KEY curr_key;
    int error;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
    //
    // open status.tokudb
    //
    if (!share->status_block) {
        char name_buff[FN_REFLEN];
        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);
        uint open_mode = (((table->db_stat & HA_READ_ONLY) ? DB_RDONLY : 0)
                          | DB_THREAD);
        if (tokudb_debug & TOKUDB_DEBUG_OPEN) {
            TOKUDB_TRACE("open:%s\n", newname);
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2094 2095 2096 2097 2098
        error = db_create(&share->status_block, db_env, 0);
        if (error) { goto cleanup; }

        error = share->status_block->open(share->status_block, NULL, name_buff, NULL, DB_BTREE, open_mode, 0);
        if (error) { goto cleanup; }
2099
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2100
    
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2101 2102 2103 2104 2105 2106 2107 2108
    //
    // transaction to be used for putting metadata into status.tokudb
    //
    bzero(&key, sizeof(key));
    bzero(&value, sizeof(value));
    key.data = &curr_key;
    key.size = sizeof(curr_key);
    value.flags = DB_DBT_MALLOC;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2109 2110
    error = db_env->txn_begin(db_env, 0, &txn, 0);
    if (error) { goto cleanup; }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129

    if (share->status_block) {
        int error;
        //
        // get version
        //
        curr_key = hatoku_version;
        error = share->status_block->get(
            share->status_block, 
            txn, 
            &key, 
            &value, 
            0
            );
        if (error == DB_NOTFOUND) {
            share->version = 0;
        }
        else if (error == 0 && value.size == sizeof(share->version)) {
            share->version = *(uint *)value.data;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2130 2131
            free(value.data);
            value.data = NULL;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2132 2133
        }
        else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2134
            goto cleanup;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
        }
        //
        // get capabilities
        //
        curr_key = hatoku_capabilities;
        error = share->status_block->get(
            share->status_block, 
            txn, 
            &key, 
            &value, 
            0
            );
        if (error == DB_NOTFOUND) {
            share->capabilities= 0;
        }
        else if (error == 0 && value.size == sizeof(share->version)) {
            share->capabilities= *(uint *)value.data;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2152 2153
            free(value.data);
            value.data = NULL;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2154 2155
        }
        else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2156
            goto cleanup;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2157 2158
        }
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
    error = 0;
cleanup:
    if (txn) {
        txn->commit(txn,0);
    }
    if (error) {
        if (share->status_block) {
            share->status_block->close(share->status_block, 0);
            share->status_block = NULL;
        }
    }
    TOKUDB_DBUG_RETURN(error);
2171 2172
}

2173 2174 2175
/** @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
2176
    This is used in filesort.cc. 
2177
*/
2178
ha_rows ha_tokudb::estimate_rows_upper_bound() {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2179
    TOKUDB_DBUG_ENTER("ha_tokudb::estimate_rows_upper_bound");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2180
    DBUG_RETURN(share->rows + HA_TOKUDB_EXTRA_ROWS);
2181
}
2182

2183
int ha_tokudb::cmp_ref(const uchar * ref1, const uchar * ref2) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2184
    if (hidden_primary_key) {
2185
        return memcmp(ref1, ref2, TOKUDB_HIDDEN_PRIMARY_KEY_LENGTH);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2186
    }    
2187 2188 2189 2190 2191
    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;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2192 2193 2194 2195 2196
    //
    // HACK until we get refactoring in. manually move up by infinity byte
    //
    ref1++;
    ref2++;
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
    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;
2207 2208
}

2209
bool ha_tokudb::check_if_incompatible_data(HA_CREATE_INFO * info, uint table_changes) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
    //
    // This is a horrendous hack for now, as copied by InnoDB.
    // This states that if the auto increment create field has changed,
    // via a "alter table foo auto_increment=new_val", that this
    // change is incompatible, and to rebuild the entire table
    // This will need to be fixed
    //
    if ((info->used_fields & HA_CREATE_USED_AUTO) &&
        info->auto_increment_value != 0) {

        return COMPATIBLE_DATA_NO;
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2222
    if (table_changes != IS_EQUAL_YES)
2223 2224 2225 2226
        return COMPATIBLE_DATA_NO;
    return COMPATIBLE_DATA_YES;
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2227 2228 2229 2230 2231 2232 2233 2234
//
// 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
//
2235
int ha_tokudb::write_row(uchar * record) {
2236
    TOKUDB_DBUG_ENTER("ha_tokudb::write_row");
2237 2238
    DBT row, prim_key, key;
    int error;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2239 2240
    THD *thd = NULL;
    u_int32_t put_flags;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2241
    bool has_null;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2242 2243
    DB_TXN* sub_trans = NULL;
    DB_TXN* txn = NULL;
2244

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2245 2246 2247 2248
    //
    // some crap that needs to be done because MySQL does not properly abstract
    // this work away from us, namely filling in auto increment and setting auto timestamp
    //
2249
    statistic_increment(table->in_use->status_var.ha_write_count, &LOCK_status);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2250
    if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT) {
2251
        table->timestamp_field->set_time();
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2252 2253
    }
    if (table->next_number_field && record == table->record[0]) {
2254
        update_auto_increment();
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2255
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278

    //
    // check to see if some value for the auto increment column that is bigger
    // than anything else til now is being used. If so, update the metadata to reflect it
    // the goal here is we never want to have a dup key error due to a bad increment
    // of the auto inc field.
    //
    if (share->has_auto_inc && record == table->record[0]) {
        pthread_mutex_lock(&share->mutex);
        ulonglong curr_auto_inc = retrieve_auto_increment(
            table->field[share->ai_field_index]->key_type(), 
            field_offset(table->field[share->ai_field_index]),
            record
            );
        if (curr_auto_inc > share->last_auto_increment) {
            error = update_max_auto_inc(share->status_block, curr_auto_inc);
            if (!error) {
                share->last_auto_increment = curr_auto_inc;
            }
        }
        pthread_mutex_unlock(&share->mutex);
    }

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2279
    if ((error = pack_row(&row, (const uchar *) record))){
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2280
        goto cleanup;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2281 2282 2283 2284 2285
    }
    
    if (hidden_primary_key) {
        get_auto_primary_key(current_ident);
    }
2286

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2287 2288 2289 2290 2291 2292 2293 2294
    if (using_ignore) {
        error = db_env->txn_begin(db_env, transaction, &sub_trans, 0);
        if (error) {
            goto cleanup;
        }
    }
    
    txn = using_ignore ? sub_trans : transaction;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2295 2296 2297 2298 2299
    //
    // first the primary key (because it must be unique, has highest chance of failure)
    //
    put_flags = share->key_type[primary_key];
    thd = ha_thd();
2300
    if (thd_test_options(thd, OPTION_RELAXED_UNIQUE_CHECKS)) {
2301
        put_flags = DB_YESOVERWRITE;
2302
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2303 2304
    error = share->file->put(
        share->file, 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2305
        txn, 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2306 2307 2308 2309
        create_dbt_key_from_table(&prim_key, primary_key, key_buff, record, &has_null), 
        &row, 
        put_flags
        );
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2310
    if (error) {
2311
        last_dup_key = primary_key;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321
        goto cleanup;
    }
    //
    // now insertion for rest of indexes
    //
    for (uint keynr = 0; keynr < table_share->keys; keynr++) {
        if (keynr == primary_key) {
            continue;
        }
        put_flags = share->key_type[keynr];
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2322 2323 2324
        create_dbt_key_from_table(&key, keynr, key_buff2, record, &has_null); 

        if (put_flags == DB_NOOVERWRITE && (has_null || thd_test_options(thd, OPTION_RELAXED_UNIQUE_CHECKS))) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2325 2326 2327 2328
            put_flags = DB_YESOVERWRITE;
        }
        error = share->key_file[keynr]->put(
            share->key_file[keynr], 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2329
            txn,
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2330
            &key,
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2331 2332 2333 2334 2335 2336 2337 2338
            &prim_key, 
            put_flags
            );
        //
        // We break if we hit an error, unless it is a dup key error
        // and MySQL told us to ignore duplicate key errors
        //
        if (error) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2339 2340
            last_dup_key = keynr;
            goto cleanup;
2341
        }
2342
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2343 2344 2345 2346 2347

    if (!error) {
        added_rows++;
    }
cleanup:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2348
    if (error == DB_KEYEXIST) {
2349
        error = HA_ERR_FOUND_DUPP_KEY;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2350
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361
    if (sub_trans) {
        // no point in recording error value of abort.
        // nothing we can do about it anyway and it is not what
        // we want to return.
        if (error) {
            sub_trans->abort(sub_trans);
        }
        else {
            error = sub_trans->commit(sub_trans, DB_TXN_NOSYNC);
        }
    }
2362
    TOKUDB_DBUG_RETURN(error);
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
}

/* 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;
        }
2383
    }
2384
    return 0;
2385 2386 2387 2388 2389 2390 2391
}


/*
  Update a row from one value to another.
  Clobbers key_buff2
*/
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2392
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) {
2393
    TOKUDB_DBUG_ENTER("update_primary_key");
2394 2395 2396 2397 2398 2399 2400
    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
2401
            if (!(error = pack_row(&row, new_row))) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2402
                if ((error = share->file->put(share->file, trans, new_key, &row, share->key_type[primary_key]))) {
2403 2404 2405 2406 2407
                    // Probably a duplicated key; restore old key and row if needed
                    last_dup_key = primary_key;
                }
            }
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2408 2409
    } 
    else {
2410
        // Primary key didn't change;  just update the row data
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2411
        if (!(error = pack_row(&row, new_row))) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2412
            error = share->file->put(share->file, trans, new_key, &row, 0);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2413
        }
2414
    }
2415
    TOKUDB_DBUG_RETURN(error);
2416 2417
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2418 2419 2420 2421 2422 2423 2424 2425 2426
//
// 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
//
2427
int ha_tokudb::update_row(const uchar * old_row, uchar * new_row) {
2428
    TOKUDB_DBUG_ENTER("update_row");
2429 2430 2431
    DBT prim_key, key, old_prim_key;
    int error;
    bool primary_key_changed;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2432 2433
    bool has_null;
    THD* thd = ha_thd();
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2434 2435
    DB_TXN* sub_trans = NULL;
    DB_TXN* txn = NULL;
2436 2437 2438

    LINT_INIT(error);
    statistic_increment(table->in_use->status_var.ha_update_count, &LOCK_status);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2439
    if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_UPDATE) {
2440
        table->timestamp_field->set_time();
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2441
    }
2442

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
    //
    // check to see if some value for the auto increment column that is bigger
    // than anything else til now is being used. If so, update the metadata to reflect it
    // the goal here is we never want to have a dup key error due to a bad increment
    // of the auto inc field.
    //
    if (share->has_auto_inc && new_row == table->record[0]) {
        pthread_mutex_lock(&share->mutex);
        ulonglong curr_auto_inc = retrieve_auto_increment(
            table->field[share->ai_field_index]->key_type(), 
            field_offset(table->field[share->ai_field_index]),
            new_row
            );
        if (curr_auto_inc > share->last_auto_increment) {
            error = update_max_auto_inc(share->status_block, curr_auto_inc);
            if (!error) {
                share->last_auto_increment = curr_auto_inc;
            }
        }
        pthread_mutex_unlock(&share->mutex);
    }



2467 2468 2469 2470 2471 2472
    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;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2473 2474
    } 
    else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2475
        create_dbt_key_from_table(&prim_key, primary_key, key_buff, new_row, &has_null);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2476
        if ((primary_key_changed = key_cmp(primary_key, old_row, new_row))) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2477
            create_dbt_key_from_table(&old_prim_key, primary_key, primary_key_buff, old_row, &has_null);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2478 2479
        }
        else {
2480
            old_prim_key = prim_key;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2481
        }
2482 2483
    }

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2484 2485 2486 2487 2488 2489 2490 2491
    if (using_ignore) {
        error = db_env->txn_begin(db_env, transaction, &sub_trans, 0);
        if (error) {
            goto cleanup;
        }
    }    
    txn = using_ignore ? sub_trans : transaction;

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2492
    /* Start by updating the primary key */
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2493
    error = update_primary_key(txn, primary_key_changed, old_row, &old_prim_key, new_row, &prim_key);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
    if (error) {
        last_dup_key = primary_key;
        goto cleanup;
    }
    // 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) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2504
            u_int32_t put_flags;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2505
            if ((error = remove_key(txn, keynr, old_row, &old_prim_key))) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2506 2507
                goto cleanup;
            }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2508
            create_dbt_key_from_table(&key, keynr, key_buff2, new_row, &has_null), 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2509 2510 2511 2512
            put_flags = share->key_type[keynr];
            if (put_flags == DB_NOOVERWRITE && (has_null || thd_test_options(thd, OPTION_RELAXED_UNIQUE_CHECKS))) {
                put_flags = DB_YESOVERWRITE;
            }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2513 2514
            error = share->key_file[keynr]->put(
                share->key_file[keynr], 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2515
                txn, 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2516
                &key,
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2517
                &prim_key, 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2518
                put_flags
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2519 2520 2521 2522 2523 2524
                );
            //
            // We break if we hit an error, unless it is a dup key error
            // and MySQL told us to ignore duplicate key errors
            //
            if (error) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2525 2526
                last_dup_key = keynr;
                goto cleanup;
2527 2528 2529
            }
        }
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2530 2531 2532



Zardosht Kasheff's avatar
Zardosht Kasheff committed
2533 2534
cleanup:
    if (error == DB_KEYEXIST) {
2535
        error = HA_ERR_FOUND_DUPP_KEY;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2536
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547
    if (sub_trans) {
        // no point in recording error value of abort.
        // nothing we can do about it anyway and it is not what
        // we want to return.
        if (error) {
            sub_trans->abort(sub_trans);
        }
        else {
            error = sub_trans->commit(sub_trans, DB_TXN_NOSYNC);
        }
    }
2548
    TOKUDB_DBUG_RETURN(error);
2549 2550
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
//
//
// 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
//
2565
int ha_tokudb::remove_key(DB_TXN * trans, uint keynr, const uchar * record, DBT * prim_key) {
2566
    TOKUDB_DBUG_ENTER("ha_tokudb::remove_key");
2567 2568
    int error;
    DBT key;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2569
    bool has_null;
2570
    DBUG_PRINT("enter", ("index: %d", keynr));
2571 2572
    DBUG_PRINT("primary", ("index: %d", primary_key));
    DBUG_DUMP("prim_key", (uchar *) prim_key->data, prim_key->size);
2573

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2574
    if (keynr == active_index && cursor) {
2575
        error = cursor->c_del(cursor, 0);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2576
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2577
    else if (keynr == primary_key) {  // Unique key
2578
        DBUG_PRINT("Unique key", ("index: %d", keynr));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589
        error = share->key_file[keynr]->del(share->key_file[keynr], trans, prim_key , 0);
    } 
    else {
        create_dbt_key_from_table(&key, keynr, key_buff2, record, &has_null);
        error = share->key_file[keynr]->delboth(
            share->key_file[keynr],
            trans,
            &key,
            prim_key,
            DB_DELETE_ANY
            );
2590
    }
2591
    TOKUDB_DBUG_RETURN(error);
2592 2593
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605
//
// 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
2606
int ha_tokudb::remove_keys(DB_TXN * trans, const uchar * record, DBT * prim_key, key_map * keys) {
2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
    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
2620
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2621
// Deletes a row in the table, called when handling a DELETE query
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2622 2623 2624 2625 2626 2627
// Parameters:
//      [in]    record - row to be deleted, in MySQL format
// Returns:
//      0 on success
//      error otherwise
//
2628
int ha_tokudb::delete_row(const uchar * record) {
2629
    TOKUDB_DBUG_ENTER("ha_tokudb::delete_row");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2630 2631
    int error = ENOSYS;
    DBT prim_key;
2632
    key_map keys = table_share->keys_in_use;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2633
    bool has_null;
2634 2635
    statistic_increment(table->in_use->status_var.ha_delete_count, &LOCK_status);

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2636
    create_dbt_key_from_table(&prim_key, primary_key, key_buff, record, &has_null);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2637
    if (hidden_primary_key) {
2638
        keys.set_bit(primary_key);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2639
    }
2640 2641 2642
    /* Subtransactions may be used in order to retry the delete in
       case we get a DB_LOCK_DEADLOCK error. */
    DB_TXN *sub_trans = transaction;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2643 2644 2645
    error = remove_keys(sub_trans, record, &prim_key, &keys);
    if (error) {
        DBUG_PRINT("error", ("Got error %d", error));
2646
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2647
    else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2648 2649
        deleted_rows++;
    }
2650
    TOKUDB_DBUG_RETURN(error);
2651 2652
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
//
// Notification that a scan of entire secondary table is about
// to take place. Will pre acquire table read lock
// Returns:
//      0 on success
//      error otherwise
//
int ha_tokudb::prepare_index_scan() {
    int error;
    DB* db = share->key_file[active_index];
    error = db->pre_acquire_read_lock(
        db, 
        transaction, 
        db->dbt_neg_infty(), db->dbt_neg_infty(), 
        db->dbt_pos_infty(), db->dbt_pos_infty()
        );
    if (error) { last_cursor_error = error; goto cleanup; }

    range_lock_grabbed = true;
    error = 0;
cleanup:
    return error;
}


Zardosht Kasheff's avatar
Zardosht Kasheff committed
2678 2679 2680 2681 2682 2683 2684 2685 2686
//
// 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
//
2687
int ha_tokudb::index_init(uint keynr, bool sorted) {
2688
    TOKUDB_DBUG_ENTER("ha_tokudb::index_init %p %d", this, keynr);
2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700
    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;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2701
    last_cursor_error = 0;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2702
    range_lock_grabbed = false;
2703
    DBUG_ASSERT(keynr <= table->s->keys);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2704
    DBUG_ASSERT(share->key_file[keynr]);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2705
    if ((error = share->key_file[keynr]->cursor(share->key_file[keynr], transaction, &cursor, 0))) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2706
        last_cursor_error = error;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2707
        cursor = NULL;             // Safety
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2708
    }
2709
    bzero((void *) &last_key, sizeof(last_key));
2710
    TOKUDB_DBUG_RETURN(error);
2711 2712
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2713 2714 2715
//
// closes the local cursor
//
2716
int ha_tokudb::index_end() {
2717
    TOKUDB_DBUG_ENTER("ha_tokudb::index_end %p", this);
2718
    int error = 0;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2719
    range_lock_grabbed = false;
2720 2721 2722
    if (cursor) {
        DBUG_PRINT("enter", ("table: '%s'", table_share->table_name.str));
        error = cursor->c_close(cursor);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2723
        cursor = NULL;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2724
        last_cursor_error = 0;
2725
    }
2726
    active_index = MAX_KEY;
2727
    TOKUDB_DBUG_RETURN(error);
2728 2729
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2730 2731 2732

int ha_tokudb::handle_cursor_error(int error, int err_to_return, uint keynr) {
    TOKUDB_DBUG_ENTER("ha_tokudb::handle_cursor_error");
2733
    if (error) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2734
        last_cursor_error = error;
2735
        table->status = STATUS_NOT_FOUND;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2736 2737 2738
        cursor->c_close(cursor);
        cursor = NULL;
        if (error == DB_NOTFOUND || error == DB_KEYEMPTY) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2739 2740
            error = err_to_return;
            if ((share->key_file[keynr]->cursor(share->key_file[keynr], transaction, &cursor, 0))) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2741 2742 2743
                cursor = NULL;             // Safety
            }
        }
2744
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
    TOKUDB_DBUG_RETURN(error);
}


//
// Helper function for read_row and smart_dbt_callback_xxx functions
// When using a hidden primary key, upon reading a row, 
// we set the current_ident field to whatever the primary key we retrieved
// was
//
void ha_tokudb::extract_hidden_primary_key(uint keynr, DBT const *row, DBT const *found_key) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2756
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2757
    // extract hidden primary key to current_ident
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2758 2759
    //
    if (hidden_primary_key) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2760 2761 2762 2763 2764 2765
        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
2766
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
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 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
}

//
// Reads the contents of row and found_key, DBT's retrieved from the DB associated to keynr, into buf
// This function assumes that we are using a covering index, as a result, if keynr is the primary key,
// we do not read row into buf
// Parameters:
//      [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
//
void ha_tokudb::read_key_only(uchar * buf, uint keynr, DBT const *row, DBT const *found_key) {
    TOKUDB_DBUG_ENTER("ha_tokudb::read_key_only");
    table->status = 0;
    unpack_key(buf, found_key, keynr);
    if (!hidden_primary_key && (keynr != primary_key)) {
        unpack_key(buf, row, primary_key);
    }
    DBUG_VOID_RETURN;
}

//
// Helper function used to try to retrieve the entire row
// If keynr is associated with the main table, reads contents of found_key and row into buf, otherwise,
// makes copy of primary key and saves it to last_key. This can later be used to retrieve the entire row
// Parameters:
//      [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
//
void ha_tokudb::read_primary_key(uchar * buf, uint keynr, DBT const *row, DBT const *found_key) {
    TOKUDB_DBUG_ENTER("ha_tokudb::read_primary_key");
    table->status = 0;
    if (keynr != primary_key) {
        //
        // create a DBT that has the same data as row,
        //
        bzero((void *) &last_key, sizeof(last_key));
        last_key.data = key_buff;
        last_key.size = row->size;
        memcpy(key_buff, row->data, row->size);
    }
    else {
        unpack_row(buf, row, found_key);
    }
    if (found_key) { DBUG_DUMP("read row key", (uchar *) found_key->data, found_key->size); }
    DBUG_VOID_RETURN;
}

//
// This function reads an entire row into buf. This function also assumes that
// the key needed to retrieve the row is stored in the member variable last_key
// Parameters:
//      [out]   buf - buffer for the row, in MySQL format
// Returns:
//      0 on success, error otherwise
//
int ha_tokudb::read_full_row(uchar * buf) {
    TOKUDB_DBUG_ENTER("ha_tokudb::read_full_row");
    int error;
    //
    // Read the data into current_row, assumes key is stored in this->last_key
    //
    current_row.flags = DB_DBT_REALLOC;
    if ((error = share->file->get(share->file, transaction, &last_key, &current_row, 0))) {
        table->status = STATUS_NOT_FOUND;
        TOKUDB_DBUG_RETURN(error == DB_NOTFOUND ? HA_ERR_CRASHED : error);
    }
    unpack_row(buf, &current_row, &last_key);

    TOKUDB_DBUG_RETURN(0);
}


//
// 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:
//      [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
//
int ha_tokudb::read_row(uchar * buf, uint keynr, DBT const *row, DBT const *found_key) {
    TOKUDB_DBUG_ENTER("ha_tokudb::read_row");
    int error;

    extract_hidden_primary_key(keynr, row, found_key);

2861
    table->status = 0;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2862 2863 2864 2865 2866 2867 2868 2869
    //
    // 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
    //
2870 2871
    if (keynr != primary_key) {
        if (key_read && found_key) {
2872
            // TOKUDB_DBUG_DUMP("key=", found_key->data, found_key->size);
2873
            unpack_key(buf, found_key, keynr);
2874
            if (!hidden_primary_key) {
2875
                // TOKUDB_DBUG_DUMP("row=", row->data, row->size);
2876
                unpack_key(buf, row, primary_key);
2877
            }
2878
            TOKUDB_DBUG_RETURN(0);
2879
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2880 2881 2882
        //
        // create a DBT that has the same data as row,
        //
2883 2884 2885 2886 2887
        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
2888 2889 2890
        //
        // Read the data into current_row
        //
2891
        current_row.flags = DB_DBT_REALLOC;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2892
        if ((error = share->file->get(share->file, transaction, &key, &current_row, 0))) {
2893
            table->status = STATUS_NOT_FOUND;
2894
            TOKUDB_DBUG_RETURN(error == DB_NOTFOUND ? HA_ERR_CRASHED : error);
2895
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2896 2897 2898
        unpack_row(buf, &current_row, &key);
    }
    else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2899 2900 2901 2902 2903 2904
        if (key_read && !hidden_primary_key) {
            unpack_key(buf, found_key, keynr);
        }
        else {
            unpack_row(buf, row, found_key);
        }
2905
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2906
    if (found_key) { DBUG_DUMP("read row key", (uchar *) found_key->data, found_key->size); }
2907
    TOKUDB_DBUG_RETURN(0);
2908 2909
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926
//
// 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
//
2927
int ha_tokudb::index_read_idx(uchar * buf, uint keynr, const uchar * key, uint key_len, enum ha_rkey_function find_flag) {
2928
    TOKUDB_DBUG_ENTER("ha_tokudb::index_read_idx");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2929
    int error;
2930 2931 2932
    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
2933

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2934
    error = share->key_file[keynr]->get(share->key_file[keynr], transaction, pack_key(&last_key, keynr, key_buff, key, key_len, COL_NEG_INF), &current_row, 0);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2935 2936 2937 2938 2939 2940 2941
    if (error == DB_NOTFOUND || error == DB_KEYEMPTY) {
        error = HA_ERR_KEY_NOT_FOUND;
        goto cleanup;
    }
    if (!error) {
        error = read_row(buf, keynr, &current_row, &last_key);
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2942
cleanup:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2943
    TOKUDB_DBUG_RETURN(error);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2944 2945
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2946

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044
//
// context information for the heaviside functions.
// Context information includes data necessary
// to perform comparisons
//
typedef struct heavi_info {
    DB        *db;
    const DBT *key;
} *HEAVI_INFO;

//
// effect:
//  heaviside function used for HA_READ_AFTER_KEY.
//  to use this heaviside function in ha_read_after_key, use direction>0
//  the stored key (in heavi_info) contains a prefix of the columns in the candidate
//  keys. only the columns in the stored key will be used for comparison.
//
// parameters:
//  [in]    key - candidate key in db that is being compared
//  [in]    value - candidate value, unused
//  [in]    extra_h - a heavi_info that contains information necessary for
//              the comparison
// returns:
//  >0 : candidate key > stored key
//  <0 : otherwise
// examples:
//  columns: (a,b,c,d)
//  stored key = (3,4) (only a,b)
//  candidate keys have (a,b,c,d)
//  (3,2,1,1) < (3,4)
//  (3,4,1,1) == (3,4)
//  (3,5,1,1) > (3,4)
//
static int after_key_heavi(const DBT *key, const DBT *value, void *extra_h) {
    HEAVI_INFO info = (HEAVI_INFO)extra_h;
    int cmp = tokudb_prefix_cmp_packed_key(info->db, key, info->key);
    return cmp>0 ? 1 : -1;
}

//
// effect:
//  heaviside function used for HA_READ_PREFIX_LAST_OR_PREV.
//  to use this heaviside function in HA_READ_PREFIX_LAST_OR_PREV, use direction<0
//  the stored key (in heavi_info) contains a prefix of the columns in the candidate
//  keys. only the columns in the stored key will be used for comparison.
//
// parameters:
//  [in]    key - candidate key in db that is being compared
//  [in]    value - candidate value, unused
//  [in]    extra_h - a heavi_info that contains information necessary for
//              the comparison
// returns:
//  >0 : candidate key > stored key
//  0  : candidate key == stored key
//  <0 : candidate key < stored key
// examples:
//  columns: (a,b,c,d)
//  stored key = (3,4) (only a,b)
//  candidate keys have (a,b,c,d)
//  (3,2,1,1) < (3,4)
//  (3,4,1,1) == (3,4)
//  (3,5,1,1) > (3,4)
//
static int prefix_last_or_prev_heavi(const DBT *key, const DBT *value, void *extra_h) {
    HEAVI_INFO info = (HEAVI_INFO)extra_h;
    int cmp = tokudb_prefix_cmp_packed_key(info->db, key, info->key);
    return cmp;
}

//
// effect:
//  heaviside function used for HA_READ_BEFORE_KEY.
//  to use this heaviside function in HA_READ_BEFORE_KEY, use direction<0
//  the stored key (in heavi_info) contains a prefix of the columns in the candidate
//  keys. only the columns in the stored key will be used for comparison.
//
// parameters:
//  [in]    key - candidate key in db that is being compared
//  [in]    value - candidate value, unused
//  [in]    extra_h - a heavi_info that contains information necessary for
//              the comparison
// returns:
//  <0 : candidate key < stored key
//  >0 : otherwise
// examples:
//  columns: (a,b,c,d)
//  stored key = (3,4) (only a,b)
//  candidate keys have (a,b,c,d)
//  (3,2,1,1) < (3,4)
//  (3,4,1,1) == (3,4)
//  (3,5,1,1) > (3,4)
//
static int before_key_heavi(const DBT *key, const DBT *value, void *extra_h) {
    HEAVI_INFO info = (HEAVI_INFO)extra_h;
    int cmp = tokudb_prefix_cmp_packed_key(info->db, key, info->key);
    return (cmp<0) ? -1 : 1;
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061
//
// 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
//
3062 3063
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);
3064
    // TOKUDB_DBUG_DUMP("key=", key, key_len);
3065 3066
    DBT row;
    int error;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3067 3068 3069
    struct smart_dbt_info info;
    struct heavi_info heavi_info;
    bool do_read_row = true;
3070

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3071
    HANDLE_INVALID_CURSOR();
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3072

3073 3074
    table->in_use->status_var.ha_read_key_count++;
    bzero((void *) &row, sizeof(row));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3075
    pack_key(&last_key, active_index, key_buff, key, key_len, COL_NEG_INF);
3076

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3077 3078 3079 3080
    info.ha = this;
    info.buf = buf;
    info.keynr = active_index;

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3081 3082
    heavi_info.db = share->key_file[active_index];
    heavi_info.key = &last_key;
3083
    switch (find_flag) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3084
    case HA_READ_KEY_EXACT: /* Find first record else error */
3085 3086 3087
        error = cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE);
        if (error == 0) {
            DBT orig_key;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3088
            pack_key(&orig_key, active_index, key_buff2, key, key_len, COL_NEG_INF);
3089 3090 3091
            if (tokudb_prefix_cmp_packed_key(share->key_file[active_index], &orig_key, &last_key))
                error = DB_NOTFOUND;
        }
3092
        break;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3093
    case HA_READ_AFTER_KEY: /* Find next rec. after key-record */
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3094 3095 3096 3097 3098 3099 3100
        error = cursor->c_getf_heavi(
            cursor, 0, 
            key_read ? smart_dbt_callback_keyread_heavi : smart_dbt_callback_rowread_heavi, &info,
            after_key_heavi, &heavi_info, 
            1
            );
        do_read_row = false;
3101
        break;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3102
    case HA_READ_BEFORE_KEY: /* Find next rec. before key-record */
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3103 3104 3105 3106 3107 3108 3109
        error = cursor->c_getf_heavi(
            cursor, 0, 
            key_read ? smart_dbt_callback_keyread_heavi : smart_dbt_callback_rowread_heavi, &info,
            before_key_heavi, &heavi_info, 
            -1
            );
        do_read_row = false;
3110
        break;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3111
    case HA_READ_KEY_OR_NEXT: /* Record or next record */
3112 3113
        error = cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE);
        break;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3114
    case HA_READ_KEY_OR_PREV: /* Record or previous */
3115
        error = cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE);
3116 3117
        if (error == 0) {
            DBT orig_key; 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3118
            pack_key(&orig_key, active_index, key_buff2, key, key_len, COL_NEG_INF);
3119
            if (tokudb_prefix_cmp_packed_key(share->key_file[active_index], &orig_key, &last_key) != 0)
3120
                error = cursor->c_get(cursor, &last_key, &row, DB_PREV);
Yoni Fogel's avatar
Yoni Fogel committed
3121 3122
        }
        else if (error == DB_NOTFOUND)
3123
            error = cursor->c_get(cursor, &last_key, &row, DB_LAST);
3124
        break;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3125
    case HA_READ_PREFIX_LAST_OR_PREV: /* Last or prev key with the same prefix */
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3126 3127 3128 3129 3130 3131 3132
        error = cursor->c_getf_heavi(
            cursor, 0, 
            key_read ? smart_dbt_callback_keyread_heavi : smart_dbt_callback_rowread_heavi, &info,
            prefix_last_or_prev_heavi, &heavi_info, 
            -1
            );
        do_read_row = false;
3133 3134
        break;
    default:
3135
        TOKUDB_TRACE("unsupported:%d\n", find_flag);
3136
        error = HA_ERR_UNSUPPORTED;
3137
        break;
3138
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3139 3140 3141
    error = handle_cursor_error(error,HA_ERR_KEY_NOT_FOUND,active_index);
    if (!error && do_read_row) {
        error = read_row(buf, active_index, &row, &last_key);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3142
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3143 3144
    else if (!error && !key_read && active_index != primary_key) {
        error = read_full_row(buf);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3145
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3146 3147 3148 3149 3150
    
    if (error && (tokudb_debug & TOKUDB_DEBUG_ERROR)) {
        TOKUDB_TRACE("error:%d:%d\n", error, find_flag);
    }
cleanup:
3151
    TOKUDB_DBUG_RETURN(error);
3152 3153
}

3154 3155


Zardosht Kasheff's avatar
Zardosht Kasheff committed
3156 3157 3158 3159 3160 3161 3162 3163 3164
//
// 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
//
3165
int ha_tokudb::index_next(uchar * buf) {
3166
    TOKUDB_DBUG_ENTER("ha_tokudb::index_next");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3167
    int error; 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3168 3169 3170
    struct smart_dbt_info info;
    u_int32_t flags = SET_READ_FLAG(0);
    HANDLE_INVALID_CURSOR();
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3171
    
3172
    statistic_increment(table->in_use->status_var.ha_read_next_count, &LOCK_status);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184

    info.ha = this;
    info.buf = buf;
    info.keynr = active_index;
    error = handle_cursor_error(cursor->c_getf_next(cursor, flags, SMART_DBT_CALLBACK, &info), HA_ERR_END_OF_FILE,active_index);
    //
    // still need to get entire contents of the row if operation done on
    // secondary DB and it was NOT a covering index
    //
    if (!error && !key_read && (active_index != primary_key) ) {
        error = read_full_row(buf);
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3185
cleanup:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3186
    TOKUDB_DBUG_RETURN(error);
3187 3188
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199
//
// 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
//
3200
int ha_tokudb::index_next_same(uchar * buf, const uchar * key, uint keylen) {
3201
    TOKUDB_DBUG_ENTER("ha_tokudb::index_next_same %p", this);
3202
    int error;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3203 3204
    struct smart_dbt_info info;
    HANDLE_INVALID_CURSOR();
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3205
    
3206
    statistic_increment(table->in_use->status_var.ha_read_next_count, &LOCK_status);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3207 3208 3209
    info.ha = this;
    info.buf = buf;
    info.keynr = active_index;
Rich Prohaska's avatar
Rich Prohaska committed
3210 3211 3212 3213 3214
    /* 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)) {

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3215 3216 3217 3218 3219
        u_int32_t flags = SET_READ_FLAG(0);
        error = handle_cursor_error(cursor->c_getf_next_dup(cursor, flags, SMART_DBT_CALLBACK, &info),HA_ERR_END_OF_FILE,active_index);
        if (!error && !key_read && active_index != primary_key) {
            error = read_full_row(buf);
        }
3220
    } else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3221 3222 3223 3224 3225
        u_int32_t flags = SET_READ_FLAG(0);
        error = handle_cursor_error(cursor->c_getf_next(cursor, flags, SMART_DBT_CALLBACK, &info),HA_ERR_END_OF_FILE,active_index);
        if (!error && !key_read && active_index != primary_key) {
            error = read_full_row(buf);
        }
3226 3227 3228
        if (!error &&::key_cmp_if_same(table, key, active_index, keylen))
            error = HA_ERR_END_OF_FILE;
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3229
cleanup:
3230
    TOKUDB_DBUG_RETURN(error);
3231 3232
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3233 3234 3235 3236 3237 3238 3239 3240 3241
//
// 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
//
3242
int ha_tokudb::index_prev(uchar * buf) {
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
    TOKUDB_DBUG_ENTER("ha_tokudb::index_next");
    int error; 
    struct smart_dbt_info info;
    u_int32_t flags = SET_READ_FLAG(0);
    HANDLE_INVALID_CURSOR();
    
    statistic_increment(table->in_use->status_var.ha_read_next_count, &LOCK_status);

    info.ha = this;
    info.buf = buf;
    info.keynr = active_index;
    error = handle_cursor_error(cursor->c_getf_prev(cursor, flags, SMART_DBT_CALLBACK, &info),HA_ERR_END_OF_FILE,active_index);
    //
    // still need to get entire contents of the row if operation done on
    // secondary DB and it was NOT a covering index
    //
    if (!error && !key_read && (active_index != primary_key) ) {
        error = read_full_row(buf);
    }

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3263
cleanup:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3264
    TOKUDB_DBUG_RETURN(error);
3265 3266
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3267 3268 3269 3270 3271 3272 3273 3274 3275
//
// 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
//
3276
int ha_tokudb::index_first(uchar * buf) {
3277
    TOKUDB_DBUG_ENTER("ha_tokudb::index_first");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3278
    int error;
3279
    DBT row;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3280
    HANDLE_INVALID_CURSOR();
3281 3282
    statistic_increment(table->in_use->status_var.ha_read_first_count, &LOCK_status);
    bzero((void *) &row, sizeof(row));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3283 3284 3285 3286 3287 3288

    error = handle_cursor_error(cursor->c_get(cursor, &last_key, &row, DB_FIRST),HA_ERR_END_OF_FILE,active_index);
    if (!error) {
        error = read_row(buf, active_index, &row, &last_key);
    }

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3289
cleanup:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3290
    TOKUDB_DBUG_RETURN(error);
3291 3292
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3293 3294 3295 3296 3297 3298 3299 3300 3301
//
// 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
//
3302
int ha_tokudb::index_last(uchar * buf) {
3303
    TOKUDB_DBUG_ENTER("ha_tokudb::index_last");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3304
    int error;
3305
    DBT row;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3306
    HANDLE_INVALID_CURSOR();
3307 3308
    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
3309 3310 3311 3312 3313

    error = handle_cursor_error(cursor->c_get(cursor, &last_key, &row, DB_LAST),HA_ERR_END_OF_FILE,active_index);
    if (!error) {
        error = read_row(buf, active_index, &row, &last_key);
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3314
cleanup:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3315
    TOKUDB_DBUG_RETURN(error);
3316 3317
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3318 3319 3320 3321 3322 3323 3324 3325
//
// 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
//
3326
int ha_tokudb::rnd_init(bool scan) {
3327
    TOKUDB_DBUG_ENTER("ha_tokudb::rnd_init");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3328
    int error;
3329
    current_row.flags = DB_DBT_REALLOC;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3330
    range_lock_grabbed = false;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3331 3332 3333
    if (scan) {
        DB* db = share->key_file[primary_key];
        error = db->pre_acquire_read_lock(db, transaction, db->dbt_neg_infty(), NULL, db->dbt_pos_infty(), NULL);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3334
        if (error) { last_cursor_error = error; goto cleanup; }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3335 3336
    }
    error = index_init(primary_key, 0);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3337 3338 3339
    if (error) { goto cleanup;}

    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3340
    // only want to set range_lock_grabbed to true after index_init
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3341 3342 3343 3344
    // successfully executed for two reasons:
    // 1) index_init will reset it to false anyway
    // 2) if it fails, we don't want prelocking on,
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3345
    if (scan) { range_lock_grabbed = true; }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3346
    error = 0;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3347 3348
cleanup:
    TOKUDB_DBUG_RETURN(error);
3349 3350
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3351 3352 3353
//
// End a scan of the table
//
3354
int ha_tokudb::rnd_end() {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3355
    TOKUDB_DBUG_ENTER("ha_tokudb::rnd_end");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3356
    range_lock_grabbed = false;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3357
    TOKUDB_DBUG_RETURN(index_end());
3358 3359
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3360

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3361 3362 3363 3364 3365 3366 3367 3368 3369
//
// 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
//
3370
int ha_tokudb::rnd_next(uchar * buf) {
3371
    TOKUDB_DBUG_ENTER("ha_tokudb::ha_tokudb::rnd_next");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3372
    int error;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3373 3374
    u_int32_t flags = SET_READ_FLAG(0);
    struct smart_dbt_info info;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3375

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3376
    HANDLE_INVALID_CURSOR();
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3377 3378 3379 3380
    //
    // The reason we do not just call index_next is that index_next 
    // increments a different variable than we do here
    //
3381
    statistic_increment(table->in_use->status_var.ha_read_rnd_next_count, &LOCK_status);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3382 3383 3384 3385 3386 3387

    info.ha = this;
    info.buf = buf;
    info.keynr = primary_key;
    
    error = handle_cursor_error(cursor->c_getf_next(cursor, flags, SMART_DBT_CALLBACK, &info),HA_ERR_END_OF_FILE,primary_key);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3388
cleanup:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3389
    TOKUDB_DBUG_RETURN(error);
3390 3391 3392 3393
}


DBT *ha_tokudb::get_pos(DBT * to, uchar * pos) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3394
    TOKUDB_DBUG_ENTER("ha_tokudb::get_pos");
3395 3396 3397
    /* We don't need to set app_data here */
    bzero((void *) to, sizeof(*to));

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3398 3399 3400
    //
    // this should really be done through pack_key functions
    //
3401 3402 3403 3404
    to->data = pos;
    if (share->fixed_length_primary_key)
        to->size = ref_length;
    else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3405 3406 3407 3408
        //
        // move up infinity byte
        //
        pos++;
3409 3410 3411
        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;

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3412
        for (; key_part != end; key_part++) {
3413
            pos += key_part->field->packed_col_length(pos, key_part->length);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3414
        }
3415 3416 3417
        to->size = (uint) (pos - (uchar *) to->data);
    }
    DBUG_DUMP("key", (const uchar *) to->data, to->size);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3418
    DBUG_RETURN(to);
3419 3420
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3421
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3422
// Retrieves a row with based on the primary key saved in pos
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3423 3424 3425 3426 3427
// Returns:
//      0 on success
//      HA_ERR_KEY_NOT_FOUND if not found
//      error otherwise
//
3428
int ha_tokudb::rnd_pos(uchar * buf, uchar * pos) {
3429
    TOKUDB_DBUG_ENTER("ha_tokudb::rnd_pos");
3430
    DBT db_pos;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3431
    int error;
3432 3433
    statistic_increment(table->in_use->status_var.ha_read_rnd_count, &LOCK_status);
    active_index = MAX_KEY;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3434
    DBT* key = get_pos(&db_pos, pos); 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445
    error = share->file->get(share->file, transaction, key, &current_row, 0);
    if (error == DB_NOTFOUND || error == DB_KEYEMPTY) {
        error = HA_ERR_KEY_NOT_FOUND;
        goto cleanup;
    }    

    if (!error) {
        error = read_row(buf, primary_key, &current_row, key);
    }
cleanup:
    TOKUDB_DBUG_RETURN(error);
3446 3447
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3448 3449 3450 3451 3452 3453 3454

int ha_tokudb::read_range_first(
    const key_range *start_key,
    const key_range *end_key,
    bool eq_range, 
    bool sorted) 
{
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3455 3456 3457 3458 3459 3460
    TOKUDB_DBUG_ENTER("ha_tokudb::read_range_first");
    int error;
    DBT start_dbt_key;
    const DBT* start_dbt_data = NULL;
    DBT end_dbt_key;
    const DBT* end_dbt_data = NULL;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3461 3462
    uchar start_key_buff [table_share->max_key_length + MAX_REF_PARTS * 3 + sizeof(uchar)];
    uchar end_key_buff [table_share->max_key_length + MAX_REF_PARTS * 3 + sizeof(uchar)];
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3463 3464
    bzero((void *) &start_dbt_key, sizeof(start_dbt_key));
    bzero((void *) &end_dbt_key, sizeof(end_dbt_key));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3465
    range_lock_grabbed = false;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3466 3467 3468 3469 3470


    if (start_key) {
        switch (start_key->flag) {
        case HA_READ_AFTER_KEY:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3471
            pack_key(&start_dbt_key, active_index, start_key_buff, start_key->key, start_key->length, COL_POS_INF);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3472 3473 3474
            start_dbt_data = share->key_file[active_index]->dbt_pos_infty();
            break;
        default:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3475
            pack_key(&start_dbt_key, active_index, start_key_buff, start_key->key, start_key->length, COL_NEG_INF);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486
            start_dbt_data = share->key_file[active_index]->dbt_neg_infty();
            break;
        }
    }
    else {
        start_dbt_data = share->key_file[active_index]->dbt_neg_infty();
    }

    if (end_key) {
        switch (end_key->flag) {
        case HA_READ_BEFORE_KEY:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3487
            pack_key(&end_dbt_key, active_index, end_key_buff, end_key->key, end_key->length, COL_NEG_INF);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3488 3489 3490
            end_dbt_data = share->key_file[active_index]->dbt_neg_infty();
            break;
        default:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3491
            pack_key(&end_dbt_key, active_index, end_key_buff, end_key->key, end_key->length, COL_POS_INF);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510
            end_dbt_data = share->key_file[active_index]->dbt_pos_infty();
            break;
        }
        
    }
    else {
        end_dbt_data = share->key_file[active_index]->dbt_pos_infty();
    }

    

    error = share->key_file[active_index]->pre_acquire_read_lock(
        share->key_file[active_index], 
        transaction, 
        start_key ? &start_dbt_key : share->key_file[active_index]->dbt_neg_infty(), 
        start_dbt_data, 
        end_key ? &end_dbt_key : share->key_file[active_index]->dbt_pos_infty(), 
        end_dbt_data
        );
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521
    if (error){ 
        last_cursor_error = error;
        //
        // cursor should be initialized here, but in case it is not, we still check
        //
        if (cursor) {
            cursor->c_close(cursor);
            cursor = NULL;
        }
        goto cleanup; 
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3522
    range_lock_grabbed = true;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3523 3524 3525 3526
    error = handler::read_range_first(start_key, end_key, eq_range, sorted);

cleanup:
    TOKUDB_DBUG_RETURN(error);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3527 3528 3529
}
int ha_tokudb::read_range_next()
{
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3530 3531 3532 3533
    TOKUDB_DBUG_ENTER("ha_tokudb::read_range_next");
    int error;
    error = handler::read_range_next();
    if (error) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3534
        range_lock_grabbed = false;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3535 3536
    }
    TOKUDB_DBUG_RETURN(error);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3537 3538 3539 3540
}



3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561
/*
  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
*/
3562
void ha_tokudb::position(const uchar * record) {
3563
    TOKUDB_DBUG_ENTER("ha_tokudb::position");
3564 3565 3566 3567
    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);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3568 3569 3570 3571
    } 
    else {
        bool has_null;    
        create_dbt_key_from_table(&key, primary_key, ref, record, &has_null);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3572
        if (key.size < ref_length) {
3573
            bzero(ref + key.size, ref_length - key.size);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3574
        }
3575 3576 3577 3578
    }
    DBUG_VOID_RETURN;
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3579 3580 3581 3582 3583 3584
//
// Per InnoDB: Returns statistics information of the table to the MySQL interpreter,
// in various fields of the handle object. 
// Return:
//      0, always success
//
3585
int ha_tokudb::info(uint flag) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3586
    TOKUDB_DBUG_ENTER("ha_tokudb::info %p %d %lld", this, flag, share->rows);
3587 3588
    if (flag & HA_STATUS_VARIABLE) {
        // Just to get optimizations right
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3589
        stats.records = share->rows;
3590 3591
        stats.deleted = 0;
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3592
    if ((flag & HA_STATUS_CONST)) {
3593
        for (uint i = 0; i < table_share->keys; i++) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3594
            table->key_info[i].rec_per_key[table->key_info[i].key_parts - 1] = 0;
3595 3596 3597 3598 3599
        }
    }
    /* 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;
3600
    TOKUDB_DBUG_RETURN(0);
3601 3602
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3603 3604 3605
//
//  Per InnoDB: Tells something additional to the handler about how to do things.
//
3606
int ha_tokudb::extra(enum ha_extra_function operation) {
3607
    TOKUDB_DBUG_ENTER("extra %p %d", this, operation);
3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626
    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;
    }
3627
    TOKUDB_DBUG_RETURN(0);
3628 3629 3630
}

int ha_tokudb::reset(void) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3631
    TOKUDB_DBUG_ENTER("ha_tokudb::reset");
3632 3633 3634 3635 3636 3637 3638 3639 3640
    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
3641
    TOKUDB_DBUG_RETURN(0);
3642 3643
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688

//
// helper function that iterates through all DB's 
// and grabs a lock (either read or write, but not both)
// Parameters:
//      [in]    trans - transaction to be used to pre acquire the lock
//              lt - type of lock to get, either lock_read or lock_write
//  Returns:
//      0 on success
//      error otherwise
//
int ha_tokudb::acquire_table_lock (DB_TXN* trans, TABLE_LOCK_TYPE lt) {
    int error = ENOSYS;
    uint curr_num_DBs = table->s->keys + test(hidden_primary_key);
    if (lt == lock_read) {
        for (uint i = 0; i < curr_num_DBs; i++) {
            DB* db = share->key_file[i];
            error = db->pre_acquire_read_lock(
                db, 
                trans, 
                db->dbt_neg_infty(), db->dbt_neg_infty(), 
                db->dbt_pos_infty(), db->dbt_pos_infty()
                );
            if (error) { goto cleanup; }
        }
    }
    else if (lt == lock_write) {
        for (uint i = 0; i < curr_num_DBs; i++) {
            DB* db = share->key_file[i];
            error = db->pre_acquire_table_lock(db, trans);
            if (error) { goto cleanup; }
        }
    }
    else {
        error = ENOSYS;
        goto cleanup;
    }

    error = 0;
cleanup:
    return error;
}



3689 3690 3691 3692 3693 3694 3695 3696
/*
  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
3697 3698 3699 3700 3701 3702 3703 3704
//
// Parameters:
//      [in]    thd - handle to the user thread
//              lock_type - the type of lock
// Returns:
//      0 on success
//      error otherwise
//
3705
int ha_tokudb::external_lock(THD * thd, int lock_type) {
3706
    TOKUDB_DBUG_ENTER("ha_tokudb::external_lock %d", thd_sql_command(thd));
3707
    // QQQ this is here to allow experiments without transactions
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3708 3709 3710
    int error = 0;
    tokudb_trx_data *trx = NULL;
    trx = (tokudb_trx_data *) thd_data_get(thd, tokudb_hton->slot);
3711
    if (!trx) {
3712
        trx = (tokudb_trx_data *)
3713
            my_malloc(sizeof(*trx), MYF(MY_ZEROFILL));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3714
        if (!trx) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3715 3716
            error = 1;
            goto cleanup;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3717
        }
3718
        thd_data_set(thd, tokudb_hton->slot, trx);
3719
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3720
    if (trx->all == 0) {
3721
        trx->sp_level = 0;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3722
    }
3723 3724 3725
    if (lock_type != F_UNLCK) {
        if (!trx->tokudb_lock_count++) {
            DBUG_ASSERT(trx->stmt == 0);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3726
            transaction = NULL;    // Safety
3727 3728
            /* First table lock, start transaction */
            if ((thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN | OPTION_TABLE_LOCK)) && !trx->all) {
3729
                /* QQQ We have to start a master transaction */
3730 3731 3732
                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
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3733
                    goto cleanup;
3734
                }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3735
                if (tokudb_debug & TOKUDB_DEBUG_TXN) {
3736
                    TOKUDB_TRACE("master:%p\n", trx->all);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3737
                }
3738 3739
                trx->sp_level = trx->all;
                trans_register_ha(thd, TRUE, tokudb_hton);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3740
                if (thd->in_lock_tables) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3741 3742 3743 3744 3745 3746 3747
                    //
                    // grab table locks
                    // For the command "Lock tables foo read, bar read"
                    // This statement is grabbing the locks for the table
                    // foo. The locks for bar will be grabbed when 
                    // trx->tokudb_lock_count has been initialized
                    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3748
                    if (lock.type <= TL_READ_NO_INSERT) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3749 3750
                        error = acquire_table_lock(trx->all,lock_read);
                    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3751
                    else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3752 3753 3754 3755
                        error = acquire_table_lock(trx->all,lock_write);
                    }
                    // Don't create stmt trans
                    if (error) {trx->tokudb_lock_count--;}
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3756
                    goto cleanup;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3757
                }
3758 3759
            }
            DBUG_PRINT("trans", ("starting transaction stmt"));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3760 3761
            if (trx->stmt) { 
                if (tokudb_debug & TOKUDB_DEBUG_TXN) {
3762
                    TOKUDB_TRACE("warning:stmt=%p\n", trx->stmt);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3763 3764
                }
            }
3765 3766 3767
            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
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3768
                goto cleanup;
3769
            }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3770
            if (tokudb_debug & TOKUDB_DEBUG_TXN) {
3771
                TOKUDB_TRACE("stmt:%p:%p\n", trx->sp_level, trx->stmt);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3772
            }
3773 3774
            trans_register_ha(thd, FALSE, tokudb_hton);
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3775 3776 3777 3778 3779 3780 3781 3782 3783 3784
        else {
            if (thd->in_lock_tables) {
                assert(trx->all != NULL);
                //
                // For the command "Lock tables foo read, bar read"
                // This statement is grabbing the locks for the table
                // bar. The locks for foo will be grabbed when 
                // trx->tokudb_lock_count is 0 and we are initializing
                // trx->all above
                //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3785
                if (lock.type <= TL_READ_NO_INSERT) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3786 3787
                    error = acquire_table_lock(trx->all,lock_read);
                }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3788
                else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3789 3790 3791 3792 3793
                    error = acquire_table_lock(trx->all,lock_write);
                }
                if (error) {trx->tokudb_lock_count--; goto cleanup;}
            }
        }
3794
        transaction = trx->stmt;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3795 3796
    }
    else {
3797
        lock.type = TL_UNLOCK;  // Unlocked
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810

        pthread_mutex_lock(&share->mutex);
        // hate dealing with comparison of signed vs unsigned, so doing this
        if (deleted_rows > added_rows && share->rows < (deleted_rows - added_rows)) {
            share->rows = 0;
        }
        else {
            share->rows += (added_rows - deleted_rows);
        }
        pthread_mutex_unlock(&share->mutex);
        added_rows = 0;
        deleted_rows = 0;

3811 3812 3813 3814 3815 3816 3817 3818 3819
        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
3820
                if (tokudb_debug & TOKUDB_DEBUG_TXN)
3821
                    TOKUDB_TRACE("commit:%p:%d\n", trx->stmt, error);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3822
                trx->stmt = NULL;
3823 3824
            }
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3825
        transaction = NULL;
3826
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3827
cleanup:
3828
    TOKUDB_DBUG_RETURN(error);
3829 3830 3831 3832 3833 3834 3835 3836 3837
}


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

3838
int ha_tokudb::start_stmt(THD * thd, thr_lock_type lock_type) {
3839
    TOKUDB_DBUG_ENTER("ha_tokudb::start_stmt");
3840
    int error = 0;
3841
    tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, tokudb_hton->slot);
3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853
    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;
3854
    TOKUDB_DBUG_RETURN(error);
3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884
}

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

3885
THR_LOCK_DATA **ha_tokudb::store_lock(THD * thd, THR_LOCK_DATA ** to, enum thr_lock_type lock_type) {
3886
    TOKUDB_DBUG_ENTER("ha_tokudb::store_lock, lock_type=%d cmd=%d", lock_type, thd_sql_command(thd));
3887 3888
    if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK) {
        /* If we are not doing a LOCK TABLE, then allow multiple writers */
3889 3890
        if ((lock_type >= TL_WRITE_CONCURRENT_INSERT && lock_type <= TL_WRITE) && 
            !thd->in_lock_tables && thd_sql_command(thd) != SQLCOM_TRUNCATE) {
3891
            lock_type = TL_WRITE_ALLOW_WRITE;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3892
        }
3893
        lock.type = lock_type;
3894
    }
3895
    *to++ = &lock;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3896
    DBUG_RETURN(to);
3897 3898 3899 3900
}


static int create_sub_table(const char *table_name, const char *sub_name, DBTYPE type, int flags) {
3901
    TOKUDB_DBUG_ENTER("create_sub_table");
3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918
    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;
3919
    TOKUDB_DBUG_RETURN(error);
3920 3921
}

3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937
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;
}

3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951
#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);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988
            } 
            else {
                if (tokudb_debug & TOKUDB_DEBUG_OPEN) {
                    TOKUDB_TRACE("removing:%s\n", fname);
                }
                //
                // if clause checks if the file is a .tokudb file
                //
                if (strlen(fname) >= strlen (ha_tokudb_ext) &&
                    strcmp(fname + (strlen(fname) - strlen(ha_tokudb_ext)), ha_tokudb_ext) == 0) 
                {
                    //
                    // if this fails under low memory conditions, gracefully exit and return error
                    // user will be notified that something went wrong, and he will
                    // have to deal with it
                    //
                    DB* db = NULL;
                    error = db_create(&db, db_env, 0);
                    if (error) {
                        break;
                    }
                    //
                    // it is ok to do db->remove on any .tokudb file, because any such
                    // file was created with db->open
                    //
                    db->remove(db, fname, NULL, 0);
                }
                else {
                    //
                    // in case we have some file that is not .tokudb, we just delete it
                    //
                    error = unlink(fname);
                    if (error != 0) {
                        error = errno;
                        break;
                    }
                }
3989 3990 3991 3992 3993 3994 3995 3996
            }
        }
        closedir(d);
        if (error == 0) {
            error = rmdir(dname);
            if (error != 0)
                error = errno;
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3997 3998
    } 
    else {
3999
        error = errno;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4000
    }
4001 4002 4003
    return error;
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4004 4005 4006 4007 4008 4009 4010 4011 4012 4013
//
// 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
//
4014
int ha_tokudb::create(const char *name, TABLE * form, HA_CREATE_INFO * create_info) {
4015
    TOKUDB_DBUG_ENTER("ha_tokudb::create");
4016 4017
    char name_buff[FN_REFLEN];
    int error;
4018
    char dirname[get_name_length(name) + 32];
4019
    char newname[get_name_length(name) + 32];
4020

4021
    uint i;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4022 4023 4024 4025

    //
    // tracing information about what type of table we are creating
    //
4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043
    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);
            }
        }
    }

4044

4045
    // a table is a directory of dictionaries
4046 4047
    make_name(dirname, name, 0);
    error = mkdirpath(dirname, 0777);
4048
    if (error != 0) {
4049
        TOKUDB_DBUG_RETURN(errno);
4050
    }
4051

4052 4053
    make_name(newname, name, "main");
    fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);
4054 4055

    /* Create the main table that will hold the real rows */
4056
    error = create_sub_table(name_buff, NULL, DB_BTREE, 0);
Rich Prohaska's avatar
Rich Prohaska committed
4057
    if (tokudb_debug & TOKUDB_DEBUG_OPEN)
4058
        TOKUDB_TRACE("create:%s:error=%d\n", newname, error);
4059 4060 4061 4062
    if (error) {
        rmall(dirname);
        TOKUDB_DBUG_RETURN(error);
    }
4063 4064 4065 4066

    primary_key = form->s->primary_key;

    /* Create the keys */
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4067
    char part[MAX_ALIAS_NAME + 10];
4068 4069
    for (uint i = 0; i < form->s->keys; i++) {
        if (i != primary_key) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4070
            sprintf(part, "key-%s", form->s->key_info[i].name);
4071 4072
            make_name(newname, name, part);
            fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4073
            error = create_sub_table(name_buff, NULL, DB_BTREE, DB_DUP + DB_DUPSORT);
Rich Prohaska's avatar
Rich Prohaska committed
4074
            if (tokudb_debug & TOKUDB_DEBUG_OPEN)
4075
                TOKUDB_TRACE("create:%s:flags=%ld:error=%d\n", newname, form->key_info[i].flags, error);
4076 4077 4078 4079
            if (error) {
                rmall(dirname);
                TOKUDB_DBUG_RETURN(error);
            }
4080 4081
        }
    }
4082

4083

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4084
    /* Create status.tokudb and save relevant metadata */
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4085
    DB *status_block = NULL;
4086
    if (!(error = (db_create(&status_block, db_env, 0)))) {
4087 4088
        make_name(newname, name, "status");
        fn_format(name_buff, newname, "", 0, MY_UNPACK_FILENAME);
4089

4090
        if (!(error = (status_block->open(status_block, NULL, name_buff, NULL, DB_BTREE, DB_CREATE, 0)))) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4091 4092
            uint version = HA_TOKU_VERSION;
            uint capabilities = HA_TOKU_CAP;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4093 4094
            
            error = write_metadata(status_block, hatoku_version,&version,sizeof(version));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4095
            if (error) { goto quit_status; }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4096 4097

            error = write_metadata(status_block, hatoku_capabilities,&capabilities,sizeof(capabilities));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4098
            if (error) { goto quit_status; }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4099 4100 4101 4102

            error = write_auto_inc_create(status_block, create_info->auto_increment_value);
            if (error) { goto quit_status; }

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4103
        quit_status:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4104
            status_block->close(status_block, 0);
4105
        }
Rich Prohaska's avatar
Rich Prohaska committed
4106
        if (tokudb_debug & TOKUDB_DEBUG_OPEN)
4107
            TOKUDB_TRACE("create:%s:error=%d\n", newname, error);
Rich Prohaska's avatar
Rich Prohaska committed
4108

4109
    }
4110 4111 4112

    if (error)
        rmall(dirname);
4113
    TOKUDB_DBUG_RETURN(error);
4114 4115
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4116 4117 4118 4119 4120 4121 4122 4123
//
// Drops table
// Parameters:
//      [in]    name - name of table to be deleted
// Returns:
//      0 on success
//      error otherwise
//
4124
int ha_tokudb::delete_table(const char *name) {
4125
    TOKUDB_DBUG_ENTER("ha_tokudb::delete_table");
4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147
    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;
4148
#else
4149
    // remove all of the dictionaries in the table directory 
4150 4151
    char newname[(tokudb_data_dir ? strlen(tokudb_data_dir) : 0) + strlen(name) + 32];
    make_name(newname, name, 0);
4152 4153
    error = rmall(newname);
    my_errno = error;
4154
#endif
4155
    TOKUDB_DBUG_RETURN(error);
4156 4157 4158
}


Zardosht Kasheff's avatar
Zardosht Kasheff committed
4159 4160 4161 4162 4163 4164 4165 4166 4167
//
// 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
//
4168
int ha_tokudb::rename_table(const char *from, const char *to) {
4169
    TOKUDB_DBUG_ENTER("%s %s %s", __FUNCTION__, from, to);
4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181
    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);
    }
4182
#else
4183 4184 4185 4186 4187 4188
    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);
4189 4190 4191
    error = rename(newfrom, newto);
    if (error != 0)
        error = my_errno = errno;
4192
#endif
4193
    TOKUDB_DBUG_RETURN(error);
4194 4195 4196 4197
}


/*
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4198
  Returns estimate on number of seeks it will take to read through the table
4199 4200 4201
  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.
*/
4202
/// QQQ why divide by 3
4203
double ha_tokudb::scan_time() {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4204 4205 4206
    TOKUDB_DBUG_ENTER("ha_tokudb::scan_time");
    double ret_val = stats.records / 3;
    DBUG_RETURN(ret_val);
4207 4208
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249
//
// Calculate the time it takes to read a set of ranges through an index
// This enables us to optimize reads for clustered indexes.
// Implementation pulled from InnoDB
// Parameters:
//          index - index to use
//          ranges - number of ranges
//          rows - estimated number of rows in the range
// Returns:
//      estimated time measured in disk seeks
//
double ha_tokudb::read_time(
	uint	index,
	uint	ranges,
	ha_rows rows
	)
{
    double total_scan;
    double ret_val; 

    if (index != primary_key) {
        ret_val = handler::read_time(index, ranges, rows);
        goto cleanup;
    }

    total_scan = scan_time();

    if (stats.records < rows) {
        ret_val = total_scan;
        goto cleanup;
    }

    //
    // one disk seek per range plus the proportional scan time of the rows
    //
    ret_val = (ranges + (double) rows / (double) stats.records * total_scan);
cleanup:
    return ret_val;
}


Zardosht Kasheff's avatar
Zardosht Kasheff committed
4250
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261
// 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
4262
//
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4263
ha_rows ha_tokudb::records_in_range(uint keynr, key_range* start_key, key_range* end_key) {
4264
    TOKUDB_DBUG_ENTER("ha_tokudb::records_in_range");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4265
    DBT key, after_key;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4266
    ha_rows ret_val = HA_TOKUDB_RANGE_COUNT;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4267
    DB *kfile = share->key_file[keynr];
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4268 4269 4270
    u_int64_t less, equal, greater;
    u_int64_t start_rows, end_rows, rows;
    int is_exact;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4271
    int error;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283
    struct heavi_info heavi_info;
    DBC* tmp_cursor = NULL;
    u_int64_t after_key_less, after_key_equal, after_key_greater;
    heavi_info.db = kfile;
    heavi_info.key = &key;
    after_key.data = key_buff2;

    error = kfile->cursor(kfile, transaction, &tmp_cursor, 0);
    if (error) {
        ret_val = HA_TOKUDB_RANGE_COUNT;
        goto cleanup;
    }
4284

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4285
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4286
    // get start_rows and end_rows values so that we can estimate range
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4287 4288 4289 4290
    // when calling key_range64, the only value we can trust is the value for less
    // The reason is that the key being passed in may be a prefix of keys in the DB
    // As a result, equal may be 0 and greater may actually be equal+greater
    // So, we call key_range64 on the key, and the key that is after it.
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4291 4292
    //
    if (start_key) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4293
        pack_key(&key, keynr, key_buff, start_key->key, start_key->length, COL_NEG_INF); 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4294
        error = kfile->key_range64(
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4295 4296
            kfile, 
            transaction, 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4297
            &key,
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4298 4299 4300 4301
            &less,
            &equal,
            &greater,
            &is_exact
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4302 4303 4304 4305 4306 4307
            );
        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
4308
            start_rows= less;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4309 4310
        }
        else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342
            error = tmp_cursor->c_getf_heavi(
                tmp_cursor, 
                0, 
                smart_dbt_callback_ror_heavi, 
                &after_key,
                after_key_heavi, 
                &heavi_info, 
                1
                );
            if (error && error != DB_NOTFOUND) {
                ret_val = HA_TOKUDB_RANGE_COUNT;
                goto cleanup;
            }
            else if (error == DB_NOTFOUND) {
                start_rows = stats.records;
            }
            else {
                error = kfile->key_range64(
                    kfile, 
                    transaction, 
                    &after_key,
                    &after_key_less,
                    &after_key_equal,
                    &after_key_greater,
                    &is_exact
                    );
                if (error) {
                    ret_val = HA_TOKUDB_RANGE_COUNT;
                    goto cleanup;
                }
                start_rows = after_key_less;
            }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4343
        }
4344
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4345
    else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4346
        start_rows= 0;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4347 4348 4349
    }

    if (end_key) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4350
        pack_key(&key, keynr, key_buff, end_key->key, end_key->length, COL_NEG_INF);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4351
        error = kfile->key_range64(
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4352 4353
            kfile, 
            transaction, 
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4354
            &key,
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4355 4356 4357 4358
            &less,
            &equal,
            &greater,
            &is_exact
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4359 4360 4361 4362 4363 4364
            );
        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
4365
            end_rows= less;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4366 4367
        }
        else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399
            error = tmp_cursor->c_getf_heavi(
                tmp_cursor, 
                0, 
                smart_dbt_callback_ror_heavi, 
                &after_key,
                after_key_heavi, 
                &heavi_info, 
                1
                );
            if (error && error != DB_NOTFOUND) {
                ret_val = HA_TOKUDB_RANGE_COUNT;
                goto cleanup;
            }
            else if (error == DB_NOTFOUND) {
                end_rows = stats.records;
            }
            else {
                error = kfile->key_range64(
                    kfile, 
                    transaction, 
                    &after_key,
                    &after_key_less,
                    &after_key_equal,
                    &after_key_greater,
                    &is_exact
                    );
                if (error) {
                    ret_val = HA_TOKUDB_RANGE_COUNT;
                    goto cleanup;
                }
                end_rows= after_key_less;
            }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4400 4401 4402
        }
    }
    else {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4403
        end_rows = stats.records;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4404 4405
    }

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4406
    rows = (end_rows > start_rows) ? end_rows - start_rows : 1;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4407

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4408
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4409 4410
    // 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
4411
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4412
    ret_val = (ha_rows) (rows <= 1 ? 1 : rows);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4413
cleanup:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4414 4415 4416 4417
    if (tmp_cursor) {
        tmp_cursor->c_close(tmp_cursor);
        tmp_cursor = NULL;
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4418
    TOKUDB_DBUG_RETURN(ret_val);
4419 4420
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456

//
// initializes the auto increment data needed
//
void ha_tokudb::init_auto_increment() {
    DBT key;
    DBT value;
    int error;
    HA_METADATA_KEY key_val = hatoku_max_ai;
    bzero(&key, sizeof(key));
    bzero(&value, sizeof(value));
    key.data = &key_val;
    key.size = sizeof(key_val);
    value.flags = DB_DBT_MALLOC;
    DB_TXN* txn = NULL;

    error = db_env->txn_begin(db_env, 0, &txn, 0);
    if (error) {
        share->last_auto_increment = 0;    
    }
    else {
        //
        // First retrieve hatoku_max_ai, which is max value used by auto increment
        // column so far, the max value could have been auto generated (e.g. insert (NULL))
        // or it could have been manually inserted by user (e.g. insert (345))
        //
        error = share->status_block->get(
            share->status_block, 
            txn, 
            &key, 
            &value, 
            0
            );
        
        if (error == 0 && value.size == sizeof(share->last_auto_increment)) {
            share->last_auto_increment = *(uint *)value.data;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4457 4458
            free(value.data);
            value.data = NULL;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478
        }
        else {
            share->last_auto_increment = 0;
        }
        //
        // Now retrieve the initial auto increment value, as specified by create table
        // so if a user does "create table t1 (a int auto_increment, primary key (a)) auto_increment=100",
        // then the value 100 should be stored here
        //
        key_val = hatoku_ai_create_value;
        error = share->status_block->get(
            share->status_block, 
            txn, 
            &key, 
            &value, 
            0
            );
        
        if (error == 0 && value.size == sizeof(share->auto_inc_create_value)) {
            share->auto_inc_create_value = *(uint *)value.data;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4479 4480
            free(value.data);
            value.data = NULL;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492
        }
        else {
            share->auto_inc_create_value = 0;
        }

        txn->commit(txn,DB_TXN_NOSYNC);
    }
    if (tokudb_debug & TOKUDB_DEBUG_AUTO_INCREMENT) {
        TOKUDB_TRACE("init auto increment:%lld\n", share->last_auto_increment);
    }
}

4493
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
4494
    TOKUDB_DBUG_ENTER("ha_tokudb::get_auto_increment");
4495 4496
    ulonglong nr;

4497
    pthread_mutex_lock(&share->mutex);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4498 4499 4500 4501

    if (share->auto_inc_create_value > share->last_auto_increment) {
        nr = share->auto_inc_create_value;
        share->last_auto_increment = share->auto_inc_create_value;
4502
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4503 4504 4505 4506 4507
    else {
        nr = share->last_auto_increment + increment;
    }
    update_max_auto_inc(share->status_block, nr + (nb_desired_values - 1)*increment);
    share->last_auto_increment = nr + (nb_desired_values - 1)*increment;
4508

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4509
    if (tokudb_debug & TOKUDB_DEBUG_AUTO_INCREMENT) {
4510 4511
        TOKUDB_TRACE("get_auto_increment(%lld,%lld,%lld):got:%lld:%lld\n",
                     offset, increment, nb_desired_values, nr, nb_desired_values);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4512
    }
4513
    *first_value = nr;
4514
    *nb_reserved_values = nb_desired_values;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4515
    pthread_mutex_unlock(&share->mutex);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4516
    DBUG_VOID_RETURN;
4517 4518
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4519 4520 4521 4522
bool ha_tokudb::is_auto_inc_singleton(){
    return false;
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544
//
// 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;
    DB_TXN* txn = NULL;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4545
    uchar tmp_key_buff[2*table_arg->s->rec_buff_length];
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4546
    uchar tmp_prim_key_buff[2*table_arg->s->rec_buff_length];
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4547
    THD* thd = ha_thd();
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4548

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4549
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4550 4551 4552 4553
    // number of DB files we have open currently, before add_index is executed
    //
    uint curr_num_DBs = table_arg->s->keys + test(hidden_primary_key);
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564
    // 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));
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4565
    current_primary_key.data = tmp_prim_key_buff;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581

    //
    // The files for secondary tables are derived from the name of keys
    // If we try to add a key with the same name as an already existing key,
    // We can crash. So here we check if any of the keys added has the same
    // name of an existing key, and if so, we fail gracefully
    //
    for (uint i = 0; i < num_of_keys; i++) {
        for (uint j = 0; j < table_arg->s->keys; j++) {
            if (strcmp(key_info[i].name, table_arg->s->key_info[j].name) == 0) {
                error = HA_ERR_WRONG_COMMAND;
                goto cleanup;
            }
        }
    }
    
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4582 4583 4584 4585 4586 4587 4588 4589
    //
    // 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);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4590
        error = create_sub_table(name_buff, NULL, DB_BTREE, DB_DUP + DB_DUPSORT);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601
        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
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4602
    curr_index = curr_num_DBs;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621
    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);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642

    //
    // grab some locks to make this go faster
    // first a global read lock on the main DB, because
    // we intend to scan the entire thing
    //
    error = share->file->pre_acquire_read_lock(
        share->file, 
        txn, 
        share->file->dbt_neg_infty(), 
        NULL, 
        share->file->dbt_pos_infty(), 
        NULL
        );
    if (error) { txn->commit(txn, 0); goto cleanup; }

    //
    // now grab a table write lock for secondary tables we
    // are creating
    //
    for (uint i = 0; i < num_of_keys; i++) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4643
        uint curr_index = i + curr_num_DBs;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4644 4645 4646 4647 4648 4649 4650
        error = share->key_file[curr_index]->pre_acquire_table_lock(
            share->key_file[curr_index],
            txn
            );
        if (error) { txn->commit(txn, 0); goto cleanup; }
    }

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4651 4652 4653 4654 4655 4656 4657 4658 4659
    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
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4660 4661 4662 4663 4664 4665
    struct smart_dbt_ai_info info;
    info.ha = this;
    info.prim_key = &current_primary_key;
    info.buf = tmp_record;

    cursor_ret_val = tmp_cursor->c_getf_next(tmp_cursor, DB_PRELOCKED, smart_dbt_ai_callback, &info);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4666 4667 4668 4669 4670
    while (cursor_ret_val != DB_NOTFOUND) {
        if (cursor_ret_val) {
            error = cursor_ret_val;
            goto cleanup;
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4671 4672


Zardosht Kasheff's avatar
Zardosht Kasheff committed
4673 4674
        for (uint i = 0; i < num_of_keys; i++) {
            DBT secondary_key;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4675 4676
            bool has_null = false;
            create_dbt_key_from_key(&secondary_key,&key_info[i], tmp_key_buff, tmp_record, &has_null);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4677
            uint curr_index = i + curr_num_DBs;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4678
            u_int32_t put_flags = share->key_type[curr_index];
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4679 4680 4681
            if (put_flags == DB_NOOVERWRITE && (has_null || thd_test_options(thd, OPTION_RELAXED_UNIQUE_CHECKS))) {
                put_flags = DB_YESOVERWRITE;
            }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4682
            
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4683
            error = share->key_file[curr_index]->put(share->key_file[curr_index], txn, &secondary_key, &current_primary_key, put_flags);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4684 4685 4686 4687 4688 4689 4690 4691
            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
4692 4693 4694 4695 4696 4697 4698 4699
                //
                // 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
4700 4701 4702
                goto cleanup;
            }
        }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4703
        cursor_ret_val = tmp_cursor->c_getf_next(tmp_cursor, DB_PRELOCKED, smart_dbt_ai_callback, &info);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4704
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730
    tmp_cursor->c_close(tmp_cursor);
    tmp_cursor = NULL;

    //
    // Now flatten the new DB's created
    //
    for (uint i = 0; i < num_of_keys; i++) {
        uint curr_index = i + curr_num_DBs;
        if ((error = share->key_file[curr_index]->cursor(share->key_file[curr_index], txn, &tmp_cursor, 0))) {
            tmp_cursor = NULL;             // Safety
            goto cleanup;
        }
        error = 0;
        while (error != DB_NOTFOUND) {
            error = tmp_cursor->c_getf_next(tmp_cursor, DB_PRELOCKED, smart_dbt_opt_callback, NULL);
            if (error && error != DB_NOTFOUND) {
                tmp_cursor->c_close(tmp_cursor);
                txn->commit(txn, 0);
                goto cleanup;
            }
        }
        
        tmp_cursor->c_close(tmp_cursor);
        tmp_cursor = NULL;
    }

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4731 4732 4733 4734 4735 4736 4737 4738 4739 4740
    error = txn->commit(txn, 0);
    assert(error == 0);
    
    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
        //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4741
        for (uint i = curr_num_DBs; i < curr_num_DBs + num_DB_opened; i++) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831
            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);
}

4832
void ha_tokudb::print_error(int error, myf errflag) {
4833
    if (error == DB_LOCK_DEADLOCK)
4834
        error = HA_ERR_LOCK_DEADLOCK;
4835
    if (error == DB_LOCK_NOTGRANTED)
4836
        error = HA_ERR_LOCK_WAIT_TIMEOUT;
4837 4838 4839
    handler::print_error(error, errflag);
}

4840
#if 0 // QQQ use default
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4841 4842 4843 4844
//
// This function will probably need to be redone from scratch
// if we ever choose to implement it
//
4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874
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->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
4875
    if (stat)
4876 4877 4878 4879
        free(stat);
    return ((share->status & STATUS_TOKUDB_ANALYZE) ? HA_ADMIN_FAILED : HA_ADMIN_OK);

  err:
4880
    if (stat)
4881 4882
        free(stat);
    return HA_ADMIN_FAILED;
4883
}
4884
#endif
4885

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4886 4887 4888
//
// flatten all DB's in this table, to do so, just do a full scan on every DB
//
4889
int ha_tokudb::optimize(THD * thd, HA_CHECK_OPT * check_opt) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4890
    TOKUDB_DBUG_ENTER("ha_tokudb::optimize");
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4891 4892
    int error;
    DBC* tmp_cursor = NULL;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4893 4894 4895
    tokudb_trx_data *trx = NULL;
    DB_TXN* txn = NULL;
    bool do_commit = false;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4896
    uint curr_num_DBs = table->s->keys + test(hidden_primary_key);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916

    trx = (tokudb_trx_data *) thd_data_get(thd, tokudb_hton->slot);
    if (trx == NULL) {
        error = HA_ERR_UNSUPPORTED;
        goto cleanup;
    }

    //
    // optimize may be called without a valid transaction, so we have to do this
    // in order to get a valid transaction
    // this is a bit hacky, but it is the best we have right now
    //
    txn = trx->stmt ? trx->stmt : trx->sp_level;
    if (txn == NULL) {        
        error = db_env->txn_begin(db_env, NULL, &txn, 0);
        if (error) {
            goto cleanup;
        }
        do_commit = true;
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4917 4918 4919
    //
    // prelock so each scan goes faster
    //
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4920
    error = acquire_table_lock(txn,lock_read);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4921 4922 4923 4924 4925 4926 4927 4928 4929
    if (error) {
        goto cleanup;
    }

    //
    // for each DB, scan through entire table and do nothing
    //
    for (uint i = 0; i < curr_num_DBs; i++) {
        error = 0;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4930
        if ((error = share->file->cursor(share->file, txn, &tmp_cursor, 0))) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944
            tmp_cursor = NULL;
            goto cleanup;
        }
        while (error != DB_NOTFOUND) {
            error = tmp_cursor->c_getf_next(tmp_cursor, DB_PRELOCKED, smart_dbt_opt_callback, NULL);
            if (error && error != DB_NOTFOUND) {
                goto cleanup;
            }
        }
        tmp_cursor->c_close(tmp_cursor);
    }

    error = 0;
cleanup:
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4945 4946 4947
    if (do_commit) {
        error = txn->commit(txn, 0);
    }
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4948
    TOKUDB_DBUG_RETURN(error);
4949 4950
}

4951 4952 4953 4954 4955 4956
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;
}
4957

4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975
// delete all rows from a table
//
// effects: delete all of the rows in the main dictionary and all of the
// indices.  this must be atomic, so we use the statement transaction
// for all of the truncate operations.
// locks:  if we have an exclusive table write lock, all of the concurrency
// issues go away.
// returns: 0 if success

int ha_tokudb::delete_all_rows() {
    TOKUDB_DBUG_ENTER("delete_all_rows");
    int error = 0;

    // truncate all dictionaries
    uint curr_num_DBs = table->s->keys + test(hidden_primary_key);
    for (uint i = 0; i < curr_num_DBs; i++) {
        DB *db = share->key_file[i];
        u_int32_t row_count = 0;
4976
        error = db->truncate(db, transaction, &row_count, 0);
4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990
        if (error) 
            break;
        // do something with the row_count?
        if (tokudb_debug)
            TOKUDB_TRACE("row_count=%u\n", row_count);
    }

    // zap the row count
    if (error == 0)
        share->rows = 0;

    TOKUDB_DBUG_RETURN(error);
}

4991
struct st_mysql_storage_engine storage_engine_structure = { MYSQL_HANDLERTON_INTERFACE_VERSION };
4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002

// 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

5003 5004 5005

// system variables

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

5008 5009
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
5010 5011
static MYSQL_SYSVAR_ULONG(max_lock, tokudb_max_lock, PLUGIN_VAR_READONLY, "TokuDB Max Locks", NULL, NULL, 8 * 1024, 0, ~0L, 0);

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

5014
static MYSQL_SYSVAR_STR(log_dir, tokudb_log_dir, PLUGIN_VAR_READONLY, "TokuDB Log Directory", NULL, NULL, NULL);
5015

5016
static MYSQL_SYSVAR_STR(data_dir, tokudb_data_dir, PLUGIN_VAR_READONLY, "TokuDB Data Directory", NULL, NULL, NULL);
5017

5018 5019
static MYSQL_SYSVAR_STR(version, tokudb_version, PLUGIN_VAR_READONLY, "TokuDB Version", NULL, NULL, NULL);

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

5022 5023
#if 0

5024
static MYSQL_SYSVAR_ULONG(cache_parts, tokudb_cache_parts, PLUGIN_VAR_READONLY, "Sets TokuDB set_cache_parts", NULL, NULL, 0, 0, ~0L, 0);
5025 5026 5027

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

5030
static MYSQL_SYSVAR_STR(home, tokudb_home, PLUGIN_VAR_READONLY, "Sets TokuDB env->open home", NULL, NULL, NULL);
5031 5032 5033 5034 5035

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

// this looks to be unused
5036
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);
5037 5038 5039

// this is really a u_int32_t
//? use MYSQL_SYSVAR_ENUM
5040 5041 5042 5043 5044 5045 5046 5047 5048
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);
5049
#endif
5050

5051 5052
static struct st_mysql_sys_var *tokudb_system_variables[] = {
    MYSQL_SYSVAR(cache_size),
5053
    MYSQL_SYSVAR(cache_memory_percent),
5054
    MYSQL_SYSVAR(max_lock),
5055 5056
    MYSQL_SYSVAR(data_dir),
    MYSQL_SYSVAR(log_dir),
5057
    MYSQL_SYSVAR(debug),
5058
    MYSQL_SYSVAR(commit_sync),
5059
    MYSQL_SYSVAR(version),
5060
    MYSQL_SYSVAR(init_flags),
5061
#if 0
5062
    MYSQL_SYSVAR(cache_parts),
5063 5064 5065 5066 5067 5068 5069 5070
    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),
5071
#endif
5072
    NULL
5073 5074
};

5075
mysql_declare_plugin(tokudb) {
5076 5077 5078 5079
    MYSQL_STORAGE_ENGINE_PLUGIN, 
    &storage_engine_structure, 
    "TokuDB", 
    "Tokutek Inc", 
5080
    "Fractal trees, transactions, row level locks",
5081
    PLUGIN_LICENSE_PROPRIETARY,        /* QQQ license? */
5082
    tokudb_init_func,          /* plugin init */
5083
    tokudb_done_func,          /* plugin deinit */
5084 5085
    0x0200,                    /* QQQ 2.0 */
    NULL,                      /* status variables */
5086
    tokudb_system_variables,   /* system variables */
5087
    NULL                       /* config options */
5088 5089
}
mysql_declare_plugin_end;