drizzle
C++ MySQL-protocol-compatible database server
Loading...
Searching...
No Matches
wiredtiger_cursor.cc
1
2#include "config.h"
3#include <drizzled/field/varstring.h>
4#include <drizzled/key_part_info.h>
5#include <drizzled/table.h>
6#include <drizzled/thr_lock.h>
7
8#include "wiredtiger_drizzle.h"
9#include "wt_to_drizzle_error.h"
10
11#include <string>
12#include <sstream>
13
14#define _TO_STR(s) #s
15#define TO_STR(s) _TO_STR(s)
16#define SOURCE_LOCATION "in " __FILE__ ":" TO_STR(__LINE__)
17
18using namespace drizzled;
19using namespace std;
20
21#include <boost/thread/mutex.hpp>
22static boost::mutex wt_share_mutex;
23
24/*****************************************************************************
25** WIREDTIGER tables
26*****************************************************************************/
27
28WiredTigerCursor::WiredTigerCursor(plugin::StorageEngine &engine_arg,
29 Table &table_arg)
30 :Cursor(engine_arg, table_arg), records_changed(0), key_stat_version(0),
31 internal_table(0), wt_session(NULL), wt_cursor(NULL), key_fields(NULL),
32 index_key_fields(NULL), index_value_fields(NULL), table_uri()
33{
34}
35
36/*
37 Hash index statistics is updated (copied from HP_KEYDEF::hash_buckets to
38 rec_per_key) after 1/MEMORY_STATS_UPDATE_THRESHOLD fraction of table records
39 have been inserted/updated/deleted. delete_all_rows() and table flush cause
40 immediate update.
41
42 NOTE
43 hash index statistics must be updated when number of table records changes
44 from 0 to non-zero value and vice versa. Otherwise records_in_range may
45 erroneously return 0 and 'range' may miss records.
46*/
47#define MEMORY_STATS_UPDATE_THRESHOLD 10
48
49int WiredTigerCursor::open_table_cursor()
50{
51 if (wt_cursor == NULL)
52 {
53 int ret= 0;
54 wt_session= get_wt_session(*getTable()->getSession());
55 ret = wt_session->open_cursor(wt_session, table_uri.c_str(),
56 NULL, "append,raw", &wt_cursor);
57 if (ret != 0)
58 return wt_to_drizzle_error(ret);
59 }
60
61 return 0;
62}
63
64void WiredTigerCursor::reopen_cursor_if_needed()
65{
66 if (wt_cursor != NULL
67 && wt_cursor->session != get_wt_session(*getTable()->getSession()))
68 {
69 string uri(wt_cursor->uri);
70 if (wt_cursor != NULL)
71 wt_cursor->close(wt_cursor);
72 wt_session= get_wt_session(*getTable()->getSession());
73 int ret = wt_session->open_cursor(wt_session, uri.c_str(),
74 NULL, "append,raw", &wt_cursor);
75 assert(ret==0);
76 }
77}
78
79int WiredTigerCursor::setupTableURI(
80 const drizzled::identifier::Table &identifier)
81{
82 table_uri.assign("table:");
83 table_uri.append(identifier.getPath());
84 return 0;
85}
86
87static unsigned int get_first_unique_index(drizzled::Table &table)
88{
89 for (uint32_t k= 0; k < table.getShare()->keys; k++)
90 {
91 if (table.key_info[k].flags & HA_NOSAME)
92 {
93 return k;
94 }
95 }
96
97 return MAX_KEY;
98}
99
100int WiredTigerCursor::setupKeyFields(uint32_t keynr, bool recreate)
101{
102 const drizzled::KeyInfo *key_info= getTable()->key_info + keynr;
103
104 if (key_fields != NULL) {
105 if (recreate) {
106 delete key_fields;
107 key_fields = NULL;
108 } else
109 return 0;
110 }
111
112 // Create a vector to hold the set of fields that belong to the primary
113 // index (aka the key). Use a vector, because we need to remember the
114 // order for packing/unpacking. Don't use the
115 // TableShare::fieldInPrimaryKey API because it doesn't cache results and
116 // doesn't use a unique index if no explicit primary is chosen.
117 key_fields = new std::vector<int32_t>();
118 message::Table *tableMessage = getShare()->getTableMessage();
119 const message::Table::Index *primary = NULL;
120 for (int indexnr= 0; indexnr < tableMessage->indexes_size() ; indexnr++)
121 {
122 const message::Table::Index &index = tableMessage->indexes(indexnr);
123 if (index.is_primary()) {
124 primary = &index;
125 break;
126 } else if (index.is_unique()) {
127 primary = &index;
128 }
129 }
130
131 if (primary && keynr == 0)
132 {
133 for (int partnr= 0; partnr < primary->index_part_size(); partnr++)
134 {
135 const message::Table::Index::IndexPart part= primary->index_part(partnr);
136 key_fields->push_back(part.fieldnr());
137 }
138 return 0;
139 }
140
141 if (getShare()->hasPrimaryKey() == false)
142 return 0;
143
144 uint32_t first_unique= get_first_unique_index(*getTable());
145 errmsg_printf(error::INSPECT, "wiredtiger: first uniq=%d keynr=%d\n", first_unique, keynr);
146
147 if (first_unique == MAX_KEY || first_unique != keynr)
148 return 0;
149
150 if (key_info != NULL)
151 {
152 KeyPartInfo *key_part= key_info->key_part;
153 KeyPartInfo *end= key_part + key_info->key_parts;
154
155 for(; key_part != end; key_part++)
156 {
157 errmsg_printf(error::INSPECT, "wiredtiger: index %d field %d\n", keynr, key_part->fieldnr);
158 key_fields->push_back(key_part->fieldnr - 1);
159 }
160 }
161
162 return 0;
163}
164
165int WiredTigerCursor::doOpen(const drizzled::identifier::Table &identifier, int /*mode*/, uint32_t /*test_if_locked*/)
166{
167 int ret = 0;
168 wt_session= get_wt_session(*getTable()->getSession());
169
170 if ((ret = setupTableURI(identifier)) != 0)
171 return ret;
172
173 wt_cursor= NULL;
174
175 share= get_share(identifier);
176 lock.init(&share->lock);
177
178 // Setup key and value packing buffers.
179 key_buf.memsize = value_buf.memsize =
180 getTable()->getRecordLength() + getTable()->sizeFields();
181 key_buf.data = key_buf.mem = malloc(key_buf.memsize);
182 value_buf.data = value_buf.mem = malloc(value_buf.memsize);
183
184 // A row reference is the raw packed WiredTiger key, prefixed with its
185 // length. The packed key can never be larger than the packing buffer.
186 ref_length= sizeof(uint32_t) + key_buf.memsize;
187
188 // Setup a buffer for creating NULL WT_ITEMs. If there is only a single
189 // column (that supports NULL), we will need record length + 1 bytes.
190 null_buf.memsize = getTable()->getRecordLength() + 1;
191 null_buf.data = null_buf.mem = malloc(null_buf.memsize);
192
193 return ret;
194}
195
196int WiredTigerCursor::close(void)
197{
198 free_share();
199
200 if (wt_cursor != NULL)
201 {
202 wt_cursor->close(wt_cursor);
203 wt_cursor= NULL;
204 }
205
206 if (key_buf.mem != NULL) {
207 free(key_buf.mem);
208 key_buf.data = key_buf.mem = NULL;
209 }
210 if (value_buf.mem != NULL) {
211 free(value_buf.mem);
212 value_buf.data = value_buf.mem = NULL;
213 }
214 if (null_buf.mem != NULL) {
215 free(null_buf.mem);
216 null_buf.data = null_buf.mem = NULL;
217 }
218 if (key_fields != NULL) {
219 delete key_fields;
220 key_fields = NULL;
221 }
222 return 0;
223}
224
225
226/*
227 Create a copy of this table
228
229 DESCRIPTION
230 Do same as default implementation but use file->s->name instead of
231 table->getShare()->path. This is needed by Windows where the clone() call sees
232 '/'-delimited path in table->getShare()->path, while ha_peap::open() was called
233 with '\'-delimited path.
234*/
235
236Cursor *WiredTigerCursor::clone(memory::Root *)
237{
238#if 0
239 Cursor *new_handler= getTable()->getMutableShare()->db_type()->getCursor(*getTable());
240 identifier::Table identifier(*getTable());
241
242 if (new_handler && !new_handler->ha_open(identifier, getTable()->db_stat,
243 HA_OPEN_IGNORE_IF_LOCKED))
244 return new_handler;
245#endif
246 return NULL;
247}
248
249
250const char *WiredTigerCursor::index_type(uint32_t )
251{
252 return ("BTREE");
253}
254
255WiredTigerTableShare *WiredTigerCursor::get_share(const identifier::Table &identifier)
256{
257 boost::mutex::scoped_lock scopedLock(wt_share_mutex);
258
259 WiredTigerEngine *a_engine= static_cast<WiredTigerEngine *>(getEngine());
260 share= a_engine->findOpenTable(identifier);
261
262 if (!share)
263 {
264 share= new WiredTigerTableShare(identifier);
265
266 if (share == NULL)
267 return(NULL);
268
269 if (getTable()->found_next_number_field)
270 share->auto_increment_value.fetch_and_store(
271 getInitialAutoIncrementValue());
272
273 a_engine->addOpenTable(identifier, share);
274 thr_lock_init(&share->lock);
275 }
276 share->use_count++;
277
278 return(share);
279}
280
281int WiredTigerCursor::free_share()
282{
283 boost::mutex::scoped_lock scopedLock(wt_share_mutex);
284
285 if (!--share->use_count)
286 {
287 WiredTigerEngine *a_engine= static_cast<WiredTigerEngine *>(getEngine());
288 a_engine->deleteOpenTable(getTable()->getShare()->getTableIdentifier());
289 delete share;
290 }
291
292 return 0;
293}
294
295
297 THR_LOCK_DATA **to,
298 thr_lock_type lock_type)
299{
300 reopen_cursor_if_needed();
301
302 if (lock_type != TL_UNLOCK)
303 {
304 /* ib_savepoint_take(*get_trx(session), statement_savepoint_name.c_str(),
305 statement_savepoint_name.length());*/
306 }
307
308 /* the below is adapted from ha_innodb.cc */
309
310 const uint32_t sql_command = session->getSqlCommand();
311
312 if (sql_command == SQLCOM_DROP_TABLE) {
313
314 /* MySQL calls this function in DROP Table though this table
315 handle may belong to another session that is running a query.
316 Let us in that case skip any changes to the prebuilt struct. */
317
318 } else if (lock_type == TL_READ_WITH_SHARED_LOCKS
319 || lock_type == TL_READ_NO_INSERT
320 || (lock_type != TL_IGNORE
321 && sql_command != SQLCOM_SELECT)) {
322
323 /* The OR cases above are in this order:
324 1) MySQL is doing LOCK TABLES ... READ LOCAL, or we
325 are processing a stored procedure or function, or
326 2) (we do not know when TL_READ_HIGH_PRIORITY is used), or
327 3) this is a SELECT ... IN SHARE MODE, or
328 4) we are doing a complex SQL statement like
329 INSERT INTO ... SELECT ... and the logical logging (MySQL
330 binlog) requires the use of a locking read, or
331 MySQL is doing LOCK TABLES ... READ.
332 5) we let InnoDB do locking reads for all SQL statements that
333 are not simple SELECTs; note that select_lock_type in this
334 case may get strengthened in ::external_lock() to LOCK_X.
335 Note that we MUST use a locking read in all data modifying
336 SQL statements, because otherwise the execution would not be
337 serializable, and also the results from the update could be
338 unexpected if an obsolete consistent read view would be
339 used. */
340
341 enum_tx_isolation isolation_level= session->getTxIsolation();
342
343 if (isolation_level != ISO_SERIALIZABLE
344 && (lock_type == TL_READ || lock_type == TL_READ_NO_INSERT)
345 && (sql_command == SQLCOM_INSERT_SELECT
346 || sql_command == SQLCOM_UPDATE
347 || sql_command == SQLCOM_CREATE_TABLE)) {
348
349 /* If we either have innobase_locks_unsafe_for_binlog
350 option set or this session is using READ COMMITTED
351 isolation level and isolation level of the transaction
352 is not set to serializable and MySQL is doing
353 INSERT INTO...SELECT or UPDATE ... = (SELECT ...) or
354 CREATE ... SELECT... without FOR UPDATE or
355 IN SHARE MODE in select, then we use consistent
356 read for select. */
357
358 // ib_lock_mode= IB_LOCK_NONE;
359 } else if (sql_command == SQLCOM_CHECKSUM) {
360 /* Use consistent read for checksum table */
361
362 // ib_lock_mode= IB_LOCK_NONE;
363 } else {
364 // ib_lock_mode= IB_LOCK_S;
365 }
366
367 } else if (lock_type != TL_IGNORE) {
368
369 /* We set possible LOCK_X value in external_lock, not yet
370 here even if this would be SELECT ... FOR UPDATE */
371 // ib_lock_mode= IB_LOCK_NONE;
372 }
373
374 if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK) {
375
376 /* If we are not doing a LOCK TABLE, DISCARD/IMPORT
377 TABLESPACE or TRUNCATE TABLE then allow multiple
378 writers. Note that ALTER TABLE uses a TL_WRITE_ALLOW_READ
379 < TL_WRITE_CONCURRENT_INSERT.
380 */
381
382 if ((lock_type >= TL_WRITE_CONCURRENT_INSERT
383 && lock_type <= TL_WRITE)
384 && ! session->doing_tablespace_operation()
385 && sql_command != SQLCOM_TRUNCATE
386 && sql_command != SQLCOM_CREATE_TABLE) {
387
388 lock_type = TL_WRITE_ALLOW_WRITE;
389 }
390
391 /* In queries of type INSERT INTO t1 SELECT ... FROM t2 ...
392 MySQL would use the lock TL_READ_NO_INSERT on t2, and that
393 would conflict with TL_WRITE_ALLOW_WRITE, blocking all inserts
394 to t2. Convert the lock to a normal read lock to allow
395 concurrent inserts to t2.
396 */
397
398 if (lock_type == TL_READ_NO_INSERT) {
399
400 lock_type = TL_READ;
401 }
402
403 lock.type = lock_type;
404 }
405
406 *to++= &lock;
407
408 return to;
409}
410
411
412/*
413 Compute which keys to use for scanning
414
415 SYNOPSIS
416 set_keys_for_scanning()
417 no parameter
418
419 DESCRIPTION
420 Set the bitmap btree_keys, which is used when the upper layers ask
421 which keys to use for scanning. For each btree index the
422 corresponding bit is set.
423
424 RETURN
425 void
426*/
427
428void WiredTigerCursor::set_keys_for_scanning(void)
429{
430 errmsg_printf(error::INSPECT, "WiredTigerCursor::set_keys_for_scanning\n");
431}
432
433void WiredTigerCursor::update_key_stats()
434{
435 errmsg_printf(error::INSPECT, "WiredTigerCursor::update_key_stats\n");
436}
437
438int WiredTigerCursor::packIndex(const char *format, WT_ITEM *buf,
439 key_range *data, KeyInfo *keyInfo)
440{
441 int ret = 0;
442 WT_PACK_STREAM *packedKey;
443
444 if ((ret = wiredtiger_pack_start(wt_session, format,
445 buf->mem, buf->memsize, &packedKey)) != 0) {
446 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
447 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
448 }
449
450 // TODO: This sets the field offset to the start of the key buffer,
451 // I'm not sure if that is correct.
452 ptrdiff_t row_offset= data->key - (getTable()->getInsertRecord() + 1);
453 for (unsigned int offset = 0; offset < keyInfo->key_parts; offset++) {
454 KeyPartInfo &ip = keyInfo->key_part[offset];
455 // Innodb manually unpacks these fields, using knowledge of the MySQL
456 // data format (see
457 // plugin/innobase/row/row0sel.cc:row_sel_convert_mysql_key_to_innobase.
458 ret = packField(ip.field, packedKey, row_offset);
459 row_offset += ip.store_length;
460 }
461
462 size_t packed_size;
463 if ((ret = wiredtiger_pack_close(packedKey, &packed_size)) != 0) {
464 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
465 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
466 }
467 buf->size = packed_size;
468 return 0;
469}
470
471int WiredTigerCursor::packRecord(WT_ITEM *kBuf, WT_ITEM *vBuf,
472 const unsigned char *data)
473{
474 int ret = 0;
475 WT_PACK_STREAM *packedKey, *packedValue;
476
477 // No primary means we have a column store - don't set a key explicitly.
478 if (!key_fields->empty()) {
479 if ((ret = wiredtiger_pack_start(wt_session, wt_cursor->key_format,
480 kBuf->mem, kBuf->memsize, &packedKey)) != 0) {
481 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
482 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
483 }
484 }
485
486 if ((ret = wiredtiger_pack_start(wt_session, wt_cursor->value_format,
487 vBuf->mem, vBuf->memsize, &packedValue)) != 0) {
488 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
489 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
490 }
491 return recordPacker(packedKey, packedValue, (unsigned char *)data,
492 &(kBuf->size), &(vBuf->size), true);
493
494}
495
496int WiredTigerCursor::unpackRecord(WT_ITEM *kBuf, WT_ITEM *vBuf,
497 unsigned char *data)
498{
499 int ret = 0;
500 WT_PACK_STREAM *packedKey = NULL;
501 WT_PACK_STREAM *packedValue = NULL;
502 if (!key_fields->empty()) {
503 if ((ret = wiredtiger_unpack_start(wt_session, wt_cursor->key_format,
504 kBuf->data, kBuf->size, &packedKey)) != 0) {
505 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record unpack failure " SOURCE_LOCATION);
506 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
507 }
508 }
509 if ((ret = wiredtiger_unpack_start(wt_session, wt_cursor->value_format,
510 vBuf->data, vBuf->size, &packedValue)) != 0) {
511 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record unpack failure " SOURCE_LOCATION);
512 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
513 }
514 return recordPacker(packedKey, packedValue, data, NULL, NULL, false);
515}
516
517// Shared logic between record pack and unpack. If packing the resulting sizes
518// will be returned in the size parameters, otherwise they are unused.
519int WiredTigerCursor::recordPacker(
520 WT_PACK_STREAM *packedKey, WT_PACK_STREAM *packedValue,
521 unsigned char *data, size_t *keySize, size_t *valueSize, bool packing)
522{
523 int colnr= 0;
524 int ret = 0;
525 Field **fields = getTable()->getFields();
526 ptrdiff_t row_offset= data - (*fields)->getTable()->getInsertRecord();
527 // Retrieve the primary key fields first - they may be in a different
528 // order to the field array.
529 if (active_index == 0 || active_index == MAX_KEY) {
530 for (std::vector<int32_t>::iterator it = key_fields->begin();
531 it != key_fields->end(); ++it) {
532 if (packing)
533 ret = packField(fields[*it], packedKey, row_offset);
534 else
535 ret = unpackField(fields[*it], packedKey, row_offset);
536 if (ret != 0)
537 return ret;
538 }
539
540 for (Field **field= fields; *field; field++, colnr++)
541 {
542 if (find(key_fields->begin(), key_fields->end(), colnr) !=
543 key_fields->end())
544 continue;
545 if (packing)
546 ret = packField(*field, packedValue, row_offset);
547 else
548 ret = unpackField(*field, packedValue, row_offset);
549 if (ret != 0)
550 return ret;
551 }
552 } else {
553 // For non primary index lookups
554 assert(index_key_fields != NULL && index_value_fields != NULL);
555 for (std::vector<int32_t>::iterator it = index_key_fields->begin();
556 it != index_key_fields->end(); ++it) {
557 if (packing)
558 ret = packField(fields[*it], packedKey, row_offset);
559 else {
560 errmsg_printf(error::INSPECT, "wiredtiger: unpacking index key: %d\n", *it);
561 ret = unpackField(fields[*it], packedKey, row_offset);
562 }
563 if (ret != 0)
564 return ret;
565 }
566 for (std::vector<int32_t>::iterator it = index_value_fields->begin();
567 it != index_value_fields->end(); ++it) {
568 if (packing)
569 ret = packField(fields[*it], packedValue, row_offset);
570 else
571 ret = unpackField(fields[*it], packedValue, row_offset);
572 if (ret != 0)
573 return ret;
574 }
575 /*
576 const drizzled::KeyInfo *key_info = getTable()->key_info + active_index;
577 KeyPartInfo *key_part= key_info->key_part;
578 KeyPartInfo *end= key_part + key_info->key_parts;
579
580 for(; key_part != end; key_part++)
581 {
582 Field *field= key_part->field;
583 if (packing)
584 ret = packField(field, packedKey, row_offset);
585 else
586 ret = unpackField(field, packedKey, row_offset);
587 if (ret != 0)
588 return ret;
589 }
590 */
591 }
592
593 size_t packed_size;
594 if (!key_fields->empty()) {
595 if ((ret = wiredtiger_pack_close(packedKey, &packed_size)) != 0) {
596 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
597 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
598 }
599 if (packing)
600 *keySize = packed_size;
601 }
602 if ((ret = wiredtiger_pack_close(packedValue, &packed_size)) != 0) {
603 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
604 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
605 }
606 if (packing)
607 *valueSize = packed_size;
608
609 return ret;
610}
611
612int WiredTigerCursor::getFieldEncoding(Field *field, char * const type)
613{
614 switch (field->type())
615 {
616 case DRIZZLE_TYPE_VARCHAR:
617 *type = 'u';
618 break;
619 case DRIZZLE_TYPE_ENUM:
620 *type = 'H';
621 break;
622 case DRIZZLE_TYPE_TIMESTAMP:
623 *type = 'Q';
624 break;
625 case DRIZZLE_TYPE_LONG:
626 *type = 'l';
627 break;
628 case DRIZZLE_TYPE_DATE:
629 case DRIZZLE_TYPE_LONGLONG:
630 *type = 'q';
631 break;
632 case DRIZZLE_TYPE_DOUBLE:
633 case DRIZZLE_TYPE_NULL:
634 case DRIZZLE_TYPE_DATETIME:
635 case DRIZZLE_TYPE_DECIMAL:
636 case DRIZZLE_TYPE_BLOB:
637 case DRIZZLE_TYPE_TIME:
638 case DRIZZLE_TYPE_BOOLEAN:
639 case DRIZZLE_TYPE_UUID:
640 case DRIZZLE_TYPE_MICROTIME:
641 case DRIZZLE_TYPE_IPV6:
642 default:
643 my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "Column Type");
644 return(HA_ERR_UNSUPPORTED);
645 break;
646 }
647 return 0;
648}
649
650int WiredTigerCursor::packField(
651 Field *field, WT_PACK_STREAM *packer, ptrdiff_t row_offset)
652{
653 int ret;
654 String str;
655 WT_ITEM item;
656 field->move_field_offset(row_offset);
657
658 /* Nullable columns are encoded as a WT_ITEM with a leading marker byte
659 (0 = NULL, 1 = value follows), so the item is never empty. WiredTiger
660 omits the length prefix for the last 'u' item in a format, and a
661 zero-length trailing item cannot be unpacked. */
662 bool nullable = field->real_maybe_null();
663 WT_PACK_STREAM *real_packer = packer;
664 WT_PACK_STREAM *null_packer;
665 if (field->is_null()) {
666 ((unsigned char *)null_buf.mem)[0] = 0;
667 null_buf.size = 1;
668 if ((ret = wiredtiger_pack_item(real_packer, &null_buf)) != 0) {
669 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
670 field->move_field_offset(-row_offset);
671 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
672 }
673 goto done;
674 }
675 char null_format[2];
676 if (nullable)
677 {
678 ret = getFieldEncoding(field, &null_format[0]);
679 if (ret != 0) {
680 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
681 field->move_field_offset(-row_offset);
682 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
683 }
684 null_format[1] = 0;
685 ((unsigned char *)null_buf.mem)[0] = 1;
686 // TODO: it'd be nice to re-use the null_packer memory.
687 if ((ret = wiredtiger_pack_start(wt_session, null_format,
688 (unsigned char *)null_buf.mem + 1, null_buf.memsize - 1,
689 &null_packer)) != 0) {
690 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
691 field->move_field_offset(-row_offset);
692 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
693 }
694 real_packer = null_packer;
695 }
696
697 switch (field->type())
698 {
699 case DRIZZLE_TYPE_VARCHAR:
700 // To get around the length bytes (1 or 2) at field->ptr
701 // we can use Field_varstring::val_str to a String
702 // to get a pointer to the real string without copying it.
703 field->setReadSet();
704 field->val_str_internal(&str);
705 item.data = str.ptr();
706 item.size = str.length();
707 if ((ret = wiredtiger_pack_item(real_packer, &item)) != 0) {
708 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
709 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
710 }
711 break;
712 case DRIZZLE_TYPE_ENUM:
713 if ((ret = wiredtiger_pack_uint(
714 real_packer, *(uint16_t *)field->ptr)) != 0) {
715 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
716 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
717 }
718 break;
719 case DRIZZLE_TYPE_TIMESTAMP:
720 if ((ret = wiredtiger_pack_uint(
721 real_packer, *(uint64_t *)field->ptr)) != 0) {
722 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
723 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
724 }
725 break;
726 case DRIZZLE_TYPE_LONG:
727 if ((ret = wiredtiger_pack_int(
728 real_packer, *(int32_t *)field->ptr)) != 0) {
729 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
730 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
731 }
732 break;
733 case DRIZZLE_TYPE_DATE:
734 case DRIZZLE_TYPE_LONGLONG:
735 if ((ret = wiredtiger_pack_int(
736 real_packer, *(int64_t *)field->ptr)) != 0) {
737 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
738 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
739 }
740 break;
741 case DRIZZLE_TYPE_DOUBLE:
742 case DRIZZLE_TYPE_NULL:
743 case DRIZZLE_TYPE_DATETIME:
744 case DRIZZLE_TYPE_DECIMAL:
745 case DRIZZLE_TYPE_BLOB:
746 case DRIZZLE_TYPE_TIME:
747 case DRIZZLE_TYPE_BOOLEAN:
748 case DRIZZLE_TYPE_UUID:
749 case DRIZZLE_TYPE_MICROTIME:
750 case DRIZZLE_TYPE_IPV6:
751 default:
752 my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "Column Type");
753 return(HA_ERR_UNSUPPORTED);
754 }
755
756 if (nullable)
757 {
758 // Close out packing the NULL item.
759 size_t packedSize;
760 if ((ret = wiredtiger_pack_close(null_packer, &packedSize)) != 0) {
761 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
762 field->move_field_offset(-row_offset);
763 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
764 }
765 null_buf.size = packedSize + 1; /* marker byte plus packed value */
766 // Add the packed NULL item to the encoded entry.
767 if ((ret = wiredtiger_pack_item(packer, &null_buf)) != 0) {
768 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
769 field->move_field_offset(-row_offset);
770 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
771 }
772 }
773
774done:
775 field->move_field_offset(-row_offset);
776 return ret;
777}
778
779int WiredTigerCursor::unpackField(
780 Field *field, WT_PACK_STREAM *unpacker, ptrdiff_t row_offset)
781{
782 int ret;
783 String str;
784 WT_ITEM item;
785 uint64_t u;
786 int64_t i;
787
788 if (!field->isReadSet())
789 field->setReadSet();
790
791 field->move_field_offset(row_offset);
792 field->setWriteSet();
793
794 /* Nullable columns carry a leading marker byte in their WT_ITEM:
795 0 = NULL, 1 = packed value follows. See packField(). */
796 bool nullable = field->real_maybe_null();
797 WT_PACK_STREAM *real_unpacker = unpacker;
798 WT_PACK_STREAM *null_unpacker;
799 char null_format[2];
800 if (nullable)
801 {
802 ret = getFieldEncoding(field, &null_format[0]);
803 if (ret != 0) {
804 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record unpack failure " SOURCE_LOCATION);
805 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
806 }
807 null_format[1] = 0;
808 // Retrieve the NULL-packed version of the item.
809 WT_ITEM null_item;
810 if ((ret = wiredtiger_unpack_item(unpacker, &null_item)) != 0) {
811 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record unpack failure " SOURCE_LOCATION);
812 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
813 }
814 if (null_item.size == 0 ||
815 ((const unsigned char *)null_item.data)[0] == 0) {
816 field->set_null();
817 goto done;
818 }
819 field->set_notnull();
820 if (null_item.size == 1) {
821 /* A marker with no payload: only a zero-length VARCHAR packs to
822 nothing, and zero bytes cannot go through an unpack stream. */
823 field->store("", 0, &my_charset_bin);
824 goto done;
825 }
826 // TODO: it'd be nice to re-use the null_unpacker memory.
827 if ((ret = wiredtiger_unpack_start(wt_session, null_format,
828 (const unsigned char *)null_item.data + 1,
829 null_item.size - 1, &null_unpacker)) != 0) {
830 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record unpack failure " SOURCE_LOCATION);
831 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
832 }
833 real_unpacker = null_unpacker;
834 }
835
836 switch (field->type())
837 {
838 case DRIZZLE_TYPE_VARCHAR:
839 if ((ret = wiredtiger_unpack_item(real_unpacker, &item)) != 0) {
840 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record unpack failure " SOURCE_LOCATION);
841 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
842 }
843 field->store((const char *)item.data, item.size, &my_charset_bin);
844 break;
845 case DRIZZLE_TYPE_ENUM:
846 if ((ret = wiredtiger_unpack_uint(real_unpacker, &u)) != 0) {
847 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record unpack failure " SOURCE_LOCATION);
848 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
849 }
850 *(uint16_t *)field->ptr = (uint16_t)u;
851 break;
852 case DRIZZLE_TYPE_TIMESTAMP:
853 if ((ret = wiredtiger_unpack_uint(real_unpacker, &u)) != 0) {
854 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record unpack failure " SOURCE_LOCATION);
855 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
856 }
857 *(uint64_t *)field->ptr = u;
858 break;
859 case DRIZZLE_TYPE_LONG:
860 if ((ret = wiredtiger_unpack_int(real_unpacker, &i)) != 0) {
861 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record unpack failure " SOURCE_LOCATION);
862 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
863 }
864 *(int32_t *)field->ptr = (int32_t)i;
865 break;
866 case DRIZZLE_TYPE_DATE:
867 case DRIZZLE_TYPE_LONGLONG:
868 if ((ret = wiredtiger_unpack_int(real_unpacker, &i)) != 0) {
869 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record unpack failure " SOURCE_LOCATION);
870 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
871 }
872 *(int64_t *)field->ptr = i;
873 break;
874 case DRIZZLE_TYPE_DOUBLE:
875 case DRIZZLE_TYPE_NULL:
876 case DRIZZLE_TYPE_DATETIME:
877 case DRIZZLE_TYPE_DECIMAL:
878 case DRIZZLE_TYPE_BLOB:
879 case DRIZZLE_TYPE_TIME:
880 case DRIZZLE_TYPE_BOOLEAN:
881 case DRIZZLE_TYPE_UUID:
882 case DRIZZLE_TYPE_MICROTIME:
883 case DRIZZLE_TYPE_IPV6:
884 default:
885 my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "Column Type");
886 return(HA_ERR_UNSUPPORTED);
887 }
888
889 if (nullable)
890 {
891 if ((ret = wiredtiger_pack_close(null_unpacker, NULL)) != 0) {
892 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record unpack failure " SOURCE_LOCATION);
893 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
894 }
895 }
896done:
897 field->move_field_offset(-row_offset);
898
899 return 0;
900}
901
902int WiredTigerCursor::doInsertRecord(unsigned char *buf)
903{
904 int r= 0;
905
906 r= open_table_cursor();
907
908 if (r != 0)
909 return r;
910
911 r= setupKeyFields(0, true);
912
913 errmsg_printf(error::INSPECT, "wiredtiger: key=%s value=%s\n", wt_cursor->key_format, wt_cursor->value_format);
914
915 reopen_cursor_if_needed();
916 int res;
917 if (getTable()->next_number_field && buf == getTable()->getInsertRecord())
918 {
919 if ((res= update_auto_increment()))
920 return res;
921 }
922 int ret = packRecord(&key_buf, &value_buf, buf);
923 if (ret != 0)
924 return ret;
925
926 if (!key_fields->empty())
927 wt_cursor->set_key(wt_cursor, &key_buf);
928 wt_cursor->set_value(wt_cursor, &value_buf);
929 ret = wt_cursor->insert(wt_cursor);
930 if (ret == WT_DUPLICATE_KEY) {
931 if (opt_flag & WT_WRITE_CAN_REPLACE)
932 ret = wt_cursor->update(wt_cursor);
933 else
934 /* Be cautious with returning this error, since
935 mysql could re-enter the storage layer to get
936 duplicated key info, the operation requires a
937 valid table handle and/or transaction information,
938 which might not always be available in the error
939 handling stage. */
940 return (HA_ERR_FOUND_DUPP_KEY);
941 }
942
943 if (ret == 0)
944 return 0;
945 else
946 return ret;
947}
948
949int WiredTigerCursor::doUpdateRecord(const unsigned char *, unsigned char * new_data)
950{
951 int ret = packRecord(&key_buf, &value_buf, new_data);
952 if (ret != 0)
953 return ret;
954
955 if (!key_fields->empty())
956 wt_cursor->set_key(wt_cursor, &key_buf);
957 wt_cursor->set_value(wt_cursor, &value_buf);
958 if ((ret = wt_cursor->update(wt_cursor)) != 0) {
959 if (!(opt_flag & READ_CHECK_USED) && ret == WT_NOTFOUND)
960 ret = wt_cursor->insert(wt_cursor);
961 if (ret != 0)
962 return ret;
963 }
964 return 0;
965}
966
967int WiredTigerCursor::doDeleteRecord(const unsigned char *)
968{
969 int ret;
970
971 ret = wt_cursor->remove(wt_cursor);
972
973 return wt_to_drizzle_error(ret);
974}
975
977{
978 int ret=0;
979
980 active_index= idx;
981
982 if (idx == 0)
983 {
984 /* primary key == normal table cursor */
985 ret= open_table_cursor();
986
987 if (ret != 0)
988 return ret;
989
990 reopen_cursor_if_needed();
991
992 ret= setupKeyFields(0, true);
993
994 if (ret != 0)
995 return ret;
996 }
997 else
998 {
999 KeyInfo key_info = getShare()->getKeyInfo(active_index);
1000
1001 wt_session= get_wt_session(*getTable()->getSession());
1002
1003 /* Setup the field vectors for decoding keys and values. */
1004 if (index_key_fields != NULL)
1005 delete index_key_fields;
1006 index_key_fields = new std::vector<int32_t>();
1007 if (index_value_fields != NULL)
1008 delete index_value_fields;
1009 index_value_fields = new std::vector<int32_t>();
1010
1011 unsigned int idx_colnr;
1012 for (idx_colnr = 0;
1013 idx_colnr < key_info.key_parts;
1014 ++idx_colnr) {
1015 // Danger Will Robinson: The key_part[idx_colnr].fieldnr does not match
1016 // up with the table field index. I'm not sure what it means, but it
1017 // should not be used here.
1018 errmsg_printf(error::INSPECT, "WiredTigerCursor::doStartIndexScan adding field: %d\n",
1019 key_info.key_part[idx_colnr].field->position());
1020 index_key_fields->push_back(key_info.key_part[idx_colnr].field->position());
1021 }
1022
1023 string index_uri("index:");
1024 index_uri.append(share->table_identifier.getPath());
1025 index_uri.append(":");
1026 index_uri.append(key_info.name);
1027 /*
1028 * Create a projection using the fields, so lookups include the
1029 * primary key fields.
1030 */
1031 index_uri.append("(");
1032 int colnr= 0;
1033 int skip;
1034 Field **fields = getTable()->getFields();
1035 for (Field **field= fields; *field; field++, colnr++) {
1036 // Check to see if the field is in the index key, if so skip it.
1037 skip = 0;
1038 for (idx_colnr = 0;
1039 skip == 0 && idx_colnr < key_info.key_parts;
1040 ++idx_colnr) {
1041 // TODO: Do I really need to check the name?
1042 if (key_info.key_part[idx_colnr].field->position() == (*field)->position())
1043 skip = 1;
1044 }
1045 if (skip)
1046 continue;
1047 errmsg_printf(error::INSPECT, "WiredTigerCursor::doStartIndexScan adding value field: %d\n", colnr);
1048 index_value_fields->push_back(colnr);
1049 index_uri.append((*field)->field_name).append(",");
1050 }
1051 index_uri.append(")");
1052
1053 errmsg_printf(error::INSPECT, "WiredTiger::doStartIndexScan %d %s\n",
1054 idx, index_uri.c_str());
1055
1056 if (wt_cursor)
1057 wt_cursor->close(wt_cursor);
1058
1059 ret = wt_session->open_cursor(wt_session, index_uri.c_str(),
1060 NULL, "append,raw", &wt_cursor);
1061 if (ret != 0)
1062 return wt_to_drizzle_error(ret);
1063 }
1064
1065 return ret;
1066}
1067
1068int WiredTigerCursor::doEndIndexScan()
1069{
1070 active_index= MAX_KEY;
1071 wt_cursor->close(wt_cursor);
1072 if (index_key_fields != NULL)
1073 delete index_key_fields;
1074 if (index_value_fields != NULL)
1075 delete index_value_fields;
1076
1077 wt_cursor= NULL;
1078 index_key_fields = NULL;
1079 index_value_fields = NULL;
1080 return 0;
1081}
1082
1083
1084int WiredTigerCursor::wt_pack_from_index_buf(WT_ITEM *kBuf,
1085 const drizzled::KeyInfo *key_info,
1086 const unsigned char *key_ptr,
1087 uint32_t key_len)
1088{
1089 int ret = 0;
1090 WT_PACK_STREAM *packedKey;
1091 WT_ITEM item;
1092
1093 if ((ret = wiredtiger_pack_start(wt_session, wt_cursor->key_format,
1094 kBuf->mem, kBuf->memsize, &packedKey)) != 0) {
1095 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
1096 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
1097 }
1098
1099 KeyPartInfo *key_part= key_info->key_part;
1100 KeyPartInfo *end= key_part + key_info->key_parts;
1101 const unsigned char *buff= key_ptr;
1102
1103 for(; key_part != end && buff < key_ptr + key_len; key_part++)
1104 {
1105 Field *field= key_part->field;
1106 bool is_null= false;
1107 WT_PACK_STREAM *real_packer= packedKey;
1108 // WT_PACK_STREAM *null_packer;
1109
1110 if (key_part->null_bit)
1111 {
1112 is_null= *buff;
1113
1114 if (is_null)
1115 {
1116 // FIXME
1117 }
1118 buff++;
1119 }
1120
1121 int length;
1122
1123 switch (field->type())
1124 {
1125 case DRIZZLE_TYPE_VARCHAR:
1126 if (is_null)
1127 {
1128 buff+= key_part->length + 2; /* 2 bytes length */
1129 continue;
1130 }
1131
1132 length= *buff + (*(buff + 1) << 8);
1133 buff+=2;
1134
1135 item.data = buff;
1136 item.size = length;
1137 if ((ret = wiredtiger_pack_item(real_packer, &item)) != 0) {
1138 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
1139 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
1140 }
1141
1142 buff+= key_part->length;
1143 break;
1144 case DRIZZLE_TYPE_ENUM:
1145 if ((ret = wiredtiger_pack_uint(
1146 real_packer, *(uint16_t *)buff)) != 0) {
1147 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
1148 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
1149 }
1150 assert(key_part->length == sizeof(uint16_t));
1151 buff+= key_part->length;
1152 break;
1153/* case DRIZZLE_TYPE_DATE:
1154 if ((ret = wiredtiger_pack_uint(
1155 real_packer, *(uint32_t*)buff)) != 0) {
1156 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
1157 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
1158 }
1159 assert(key_part->length == sizeof(uint32_t));
1160 buff+= key_part->length;
1161 break;*/
1162 case DRIZZLE_TYPE_TIMESTAMP:
1163 if ((ret = wiredtiger_pack_uint(
1164 real_packer, *(uint64_t *)buff)) != 0) {
1165 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
1166 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
1167 }
1168 assert(key_part->length == sizeof(uint64_t));
1169 buff+= key_part->length;
1170 break;
1171 case DRIZZLE_TYPE_LONG:
1172 if ((ret = wiredtiger_pack_int(
1173 real_packer, *(int32_t *)buff)) != 0) {
1174 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
1175 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
1176 }
1177 assert(key_part->length == sizeof(int32_t));
1178 buff+= key_part->length;
1179 break;
1180 case DRIZZLE_TYPE_DATE:
1181 case DRIZZLE_TYPE_LONGLONG:
1182 if ((ret = wiredtiger_pack_int(
1183 real_packer, *(int64_t *)buff)) != 0) {
1184 my_error(ER_KEY_NOT_FOUND, MYF(0), "Record pack failure");
1185 return(HA_ERR_UNSUPPORTED); // TODO: reasonable?
1186 }
1187 assert(key_part->length == sizeof(int64_t));
1188 buff+= key_part->length;
1189 break;
1190 case DRIZZLE_TYPE_DOUBLE:
1191 case DRIZZLE_TYPE_NULL:
1192 case DRIZZLE_TYPE_DATETIME:
1193 case DRIZZLE_TYPE_DECIMAL:
1194 case DRIZZLE_TYPE_BLOB:
1195 case DRIZZLE_TYPE_TIME:
1196 case DRIZZLE_TYPE_BOOLEAN:
1197 case DRIZZLE_TYPE_UUID:
1198 case DRIZZLE_TYPE_MICROTIME:
1199 case DRIZZLE_TYPE_IPV6:
1200 default:
1201 my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "Column Type");
1202 return(HA_ERR_UNSUPPORTED);
1203 }
1204 }
1205
1206 assert(buff == key_ptr + key_len);
1207
1208 return 0;
1209}
1210
1211int WiredTigerCursor::index_read(unsigned char *buf,
1212 const unsigned char *key_ptr,
1213 uint32_t key_len,
1214 drizzled::ha_rkey_function find_flag)
1215{
1216 int exact;
1217 int r= wt_pack_from_index_buf(&key_buf, getTable()->key_info + active_index,
1218 key_ptr, key_len);
1219 WT_ITEM row_key, row_value;
1220
1221 if (r != 0)
1222 return r;
1223
1224 wt_cursor->set_key(wt_cursor, &key_buf);
1225 r= wt_cursor->search_near(wt_cursor, &exact);
1226
1227 if (r != 0)
1228 {
1229 getTable()->status= STATUS_NOT_FOUND;
1230 return r; // FIXME
1231 }
1232
1233 getTable()->status= 0;
1234
1235 if (exact != 0 && find_flag == HA_READ_KEY_EXACT)
1236 {
1237 getTable()->status= STATUS_NOT_FOUND;
1238 return 0;
1239 }
1240
1241
1242 switch (exact) {
1243 case -1: /* returned key smaller than search key */
1244 break;
1245 case 0: /* Exact match */
1246 break;
1247 case 1: /* returned key larger than search key */
1248 break;
1249 }
1250
1251 if (!key_fields->empty()) // pretty sure always true
1252 wt_cursor->get_key(wt_cursor, &row_key);
1253 wt_cursor->get_value(wt_cursor, &row_value);
1254
1255 return unpackRecord(&row_key, &row_value, buf);
1256}
1257
1258int WiredTigerCursor::index_next(unsigned char * buf)
1259{
1260 errmsg_printf(error::INSPECT, "WiredTigerCursor::index_next\n");
1261 return rnd_next(buf);
1262}
1263
1264int WiredTigerCursor::index_prev(unsigned char * buf)
1265{
1266 errmsg_printf(error::INSPECT, "WiredTigerCursor::index_prev\n");
1267 int ret;
1268 WT_ITEM row_key, row_value;
1269
1270 if ((ret = wt_cursor->prev(wt_cursor)) != 0) {
1271 if (ret == WT_NOTFOUND)
1272 return HA_ERR_END_OF_FILE;
1273 else
1274 return wt_to_drizzle_error(ret);
1275 }
1276 if (!key_fields->empty())
1277 wt_cursor->get_key(wt_cursor, &row_key);
1278 wt_cursor->get_value(wt_cursor, &row_value);
1279 return unpackRecord(&row_key, &row_value, buf);
1280}
1281
1282int WiredTigerCursor::index_first(unsigned char * buf)
1283{
1284 errmsg_printf(error::INSPECT, "WiredTigerCursor::index_first\n");
1285 wt_cursor->reset(wt_cursor);
1286 return index_next(buf);
1287}
1288
1289int WiredTigerCursor::index_last(unsigned char * buf)
1290{
1291 errmsg_printf(error::INSPECT, "WiredTigerCursor::index_last\n");
1292 wt_cursor->reset(wt_cursor);
1293 return index_prev(buf);
1294}
1295
1297{
1298 int r= 0;
1299
1300 r= open_table_cursor();
1301 reopen_cursor_if_needed();
1302
1303 if (scan && wt_cursor != NULL)
1304 wt_cursor->reset(wt_cursor);
1305
1306 r= setupKeyFields(0, true);
1307
1308 return r;
1309}
1310
1311int WiredTigerCursor::rnd_next(unsigned char *buf)
1312{
1313 int ret;
1314 WT_ITEM row_key, row_value;
1315
1316 if ((ret = wt_cursor->next(wt_cursor)) != 0) {
1317 if (ret == WT_NOTFOUND)
1318 return HA_ERR_END_OF_FILE;
1319 else
1320 return wt_to_drizzle_error(ret);
1321 }
1322 if (!key_fields->empty())
1323 wt_cursor->get_key(wt_cursor, &row_key);
1324 wt_cursor->get_value(wt_cursor, &row_value);
1325 return unpackRecord(&row_key, &row_value, buf);
1326}
1327
1328int WiredTigerCursor::rnd_pos(unsigned char * buf, unsigned char *pos)
1329{
1330 int ret;
1331 WT_ITEM row_key, row_value;
1332 uint32_t key_size;
1333
1334 memcpy(&key_size, pos, sizeof(key_size));
1335 row_key.data = pos + sizeof(key_size);
1336 row_key.size = key_size;
1337
1338 reopen_cursor_if_needed();
1339 wt_cursor->set_key(wt_cursor, &row_key);
1340 if ((ret = wt_cursor->search(wt_cursor)) != 0)
1341 return wt_to_drizzle_error(ret);
1342
1343 wt_cursor->get_key(wt_cursor, &row_key);
1344 wt_cursor->get_value(wt_cursor, &row_value);
1345 return unpackRecord(&row_key, &row_value, buf);
1346}
1347
1348void WiredTigerCursor::position(const unsigned char *)
1349{
1350 WT_ITEM row_key;
1351 uint32_t key_size= 0;
1352
1353 if (wt_cursor != NULL && wt_cursor->get_key(wt_cursor, &row_key) == 0)
1354 {
1355 key_size= row_key.size;
1356 memcpy(ref + sizeof(key_size), row_key.data, key_size);
1357 }
1358 memcpy(ref, &key_size, sizeof(key_size));
1359}
1360
1361int WiredTigerCursor::info(uint32_t flag)
1362{
1363 WT_CURSOR *stat_cursor;
1364 const char *desc, *pvalue;
1365 uint64_t value;
1366 int ret = 0;
1367 // TODO: Getting stats is expensive, should probably cache results and
1368 // only update once every N iterations.
1369 if (flag & HA_STATUS_VARIABLE)
1370 {
1371 /* TODO: HACK! This gets called a lot, don't hammer on stats. */
1372 if (stats.records < 50000) {
1373 reopen_cursor_if_needed();
1374 string stat_uri("statistics:");
1375 stat_uri.append(table_uri);
1376 /* Statistics are best-effort: if they cannot be read the estimates
1377 below still get a usable floor, and the query must not fail. */
1378 if (wt_session->open_cursor(wt_session, stat_uri.c_str(),
1379 NULL, "", &stat_cursor) == 0)
1380 {
1381 stat_cursor->set_key(stat_cursor, WT_STAT_DSRC_BTREE_ENTRIES);
1382 if (stat_cursor->search(stat_cursor) == 0 &&
1383 stat_cursor->get_value(stat_cursor, &desc, &pvalue, &value) == 0)
1384 stats.records= value;
1385
1386 stat_cursor->set_key(stat_cursor, WT_STAT_DSRC_BTREE_COLUMN_DELETED);
1387 if (stat_cursor->search(stat_cursor) == 0 &&
1388 stat_cursor->get_value(stat_cursor, &desc, &pvalue, &value) == 0)
1389 stats.deleted= value;
1390
1391 stat_cursor->close(stat_cursor);
1392 }
1393
1394 if (stats.records < 2)
1395 stats.records= 2;
1396
1397 // TODO: How to retrieve these? Don't want to stat the file each time.
1398 stats.data_file_length= stats.records * 40;
1399 stats.index_file_length= stats.records * 10;
1400
1401 stats.mean_rec_length= stats.data_file_length / stats.records;
1402 }
1403 }
1404
1405 if (flag & HA_STATUS_AUTO) {
1406 stats.auto_increment_value= 1;
1407 }
1408
1409 if (flag & HA_STATUS_ERRKEY)
1410 errmsg_printf(error::INSPECT, "WiredTigerCursor::info(flag & HA_STATUS_ERRKEY)\n");
1411
1412
1413 if (flag & HA_STATUS_CONST)
1414 {
1415 for (unsigned int i = 0; i < getTable()->getShare()->sizeKeys(); i++)
1416 {
1417 const char* index_name= getTable()->key_info[i].name;
1418 ha_rows rec_per_key;
1419
1420 for (unsigned int j=0; j < getTable()->key_info[i].key_parts; j++)
1421 {
1422 string index_stat_uri("statistics:");
1423 index_stat_uri.append(table_uri).append(":");
1424 index_stat_uri.append(index_name);
1425 rec_per_key = 0;
1426 if (wt_session->open_cursor(wt_session, index_stat_uri.c_str(),
1427 NULL, "", &stat_cursor) == 0)
1428 {
1429 stat_cursor->set_key(stat_cursor, WT_STAT_DSRC_BTREE_ENTRIES);
1430 if (stat_cursor->search(stat_cursor) == 0 &&
1431 stat_cursor->get_value(stat_cursor, &desc, &pvalue, &value) == 0)
1432 rec_per_key = value;
1433 stat_cursor->close(stat_cursor);
1434 }
1435
1436 /* We import this heuristic from ha_innodb, which says
1437 that MySQL favours table scans too much over index searches,
1438 so we pretend our index selectivity is 2 times better. */
1439
1440 rec_per_key= rec_per_key / 2;
1441
1442 if (rec_per_key == 0)
1443 rec_per_key= 1;
1444
1445 getTable()->key_info[i].rec_per_key[j]=
1446 rec_per_key >= ~(ulong) 0 ? ~(ulong) 0 :
1447 (ulong) rec_per_key;
1448 }
1449
1450 }
1451 }
1452 return wt_to_drizzle_error(ret);
1453}
1454
1455int WiredTigerCursor::extra(enum ha_extra_function operation)
1456{
1457 switch (operation)
1458 {
1459 case HA_EXTRA_READCHECK:
1460 opt_flag |= READ_CHECK_USED; /* Readcheck */
1461 break;
1462 case HA_EXTRA_NO_READCHECK:
1463 opt_flag &= ~READ_CHECK_USED; /* No readcheck */
1464 break;
1465 case HA_EXTRA_FLUSH:
1466 break;
1467 case HA_EXTRA_IGNORE_DUP_KEY: /* TODO: Confirm this is correct. */
1468 case HA_EXTRA_INSERT_WITH_UPDATE: /* TODO: Confirm this is correct. */
1469 case HA_EXTRA_WRITE_CAN_REPLACE:
1470 opt_flag |= WT_WRITE_CAN_REPLACE;
1471 break;
1472 case HA_EXTRA_NO_IGNORE_DUP_KEY:
1473 case HA_EXTRA_WRITE_CANNOT_REPLACE:
1474 opt_flag &= ~WT_WRITE_CAN_REPLACE;
1475 break;
1476 case HA_EXTRA_CACHE: /* The record cache is obsolete, ignore this. */
1477 case HA_EXTRA_NO_CACHE: /* The record cache is obsolete, ignore this. */
1478 break;
1479 default:
1480 errmsg_printf(error::INSPECT, "WiredTigerCursor::extra(operation=%d)\n", operation);
1481 break;
1482 }
1483 return 0;
1484}
1485
1486
1488{
1489 errmsg_printf(error::INSPECT, "WiredTigerCursor::reset\n");
1490 return 0;
1491}
1492
1493
1495{
1496 int r;
1497 identifier::Table identifier= getTable()->getShare()->getTableIdentifier();
1498
1499 if (getTable()->in_use->getSqlCommand() == SQLCOM_TRUNCATE)
1500 {
1501 wt_cursor->close(wt_cursor);
1502
1503 r= wt_session->truncate(wt_session, table_uri.c_str(), NULL, NULL, NULL);
1504
1505 wt_session->open_cursor(wt_session, table_uri.c_str(),
1506 NULL, "append,raw", &wt_cursor);
1507 }
1508 else
1509 {
1510 WT_CURSOR *start;
1511 WT_CURSOR *stop;
1512
1513 int ret = wt_session->open_cursor(wt_session, table_uri.c_str(),
1514 NULL, NULL, &start);
1515 if (ret)
1516 return HA_ERR_GENERIC;
1517
1518 int ret2 = wt_session->open_cursor(wt_session, table_uri.c_str(),
1519 NULL, NULL, &stop);
1520 if (ret2)
1521 {
1522 start->close(start);
1523 return HA_ERR_GENERIC;
1524 }
1525
1526 ret = start->next(start);
1527 ret2 = stop->prev(stop);
1528
1529 /* An empty table means there is nothing to delete. */
1530 if (ret == WT_NOTFOUND || ret2 == WT_NOTFOUND)
1531 {
1532 start->close(start);
1533 stop->close(stop);
1534 return 0;
1535 }
1536
1537 if (ret != 0 || ret2 != 0)
1538 {
1539 start->close(start);
1540 stop->close(stop);
1541 return wt_to_drizzle_error(ret != 0 ? ret : ret2);
1542 }
1543
1544 r= wt_session->truncate(wt_session, NULL, start, stop, NULL);
1545 start->close(start);
1546 stop->close(stop);
1547 }
1548
1549 return wt_to_drizzle_error(r);
1550}
1551
1552/*
1553 Disable indexes.
1554
1555 SYNOPSIS
1556 disable_indexes()
1557 mode mode of operation:
1558 HA_KEY_SWITCH_NONUNIQ disable all non-unique keys
1559 HA_KEY_SWITCH_ALL disable all keys
1560 HA_KEY_SWITCH_NONUNIQ_SAVE dis. non-uni. and make persistent
1561 HA_KEY_SWITCH_ALL_SAVE dis. all keys and make persistent
1562
1563 DESCRIPTION
1564 Disable indexes and clear keys to use for scanning.
1565
1566 IMPLEMENTATION
1567 HA_KEY_SWITCH_NONUNIQ is not implemented.
1568 HA_KEY_SWITCH_NONUNIQ_SAVE is not implemented with HEAP.
1569 HA_KEY_SWITCH_ALL_SAVE is not implemented with HEAP.
1570
1571 RETURN
1572 0 ok
1573 HA_ERR_WRONG_COMMAND mode not implemented.
1574*/
1575
1576int WiredTigerCursor::disable_indexes(uint32_t mode)
1577{
1578 errmsg_printf(error::INSPECT, "WiredTigerCursor::disable_indexes\n");
1579#if 0
1580 int error;
1581
1582 if (mode == HA_KEY_SWITCH_ALL)
1583 {
1584 if (!(error= wiredtiger_disable_indexes(file)))
1585 set_keys_for_scanning();
1586 }
1587 else
1588 {
1589 /* mode not implemented */
1590 error= HA_ERR_WRONG_COMMAND;
1591 }
1592 return error;
1593#else
1594 WT_UNUSED(mode);
1595 return 0;
1596#endif
1597}
1598
1599
1600/*
1601 Enable indexes.
1602
1603 SYNOPSIS
1604 enable_indexes()
1605 mode mode of operation:
1606 HA_KEY_SWITCH_NONUNIQ enable all non-unique keys
1607 HA_KEY_SWITCH_ALL enable all keys
1608 HA_KEY_SWITCH_NONUNIQ_SAVE en. non-uni. and make persistent
1609 HA_KEY_SWITCH_ALL_SAVE en. all keys and make persistent
1610
1611 DESCRIPTION
1612 Enable indexes and set keys to use for scanning.
1613 The indexes might have been disabled by disable_index() before.
1614 The function works only if both data and indexes are empty,
1615 since the wiredtiger storage engine cannot repair the indexes.
1616 To be sure, call Cursor::delete_all_rows() before.
1617
1618 IMPLEMENTATION
1619 HA_KEY_SWITCH_NONUNIQ is not implemented.
1620 HA_KEY_SWITCH_NONUNIQ_SAVE is not implemented with HEAP.
1621 HA_KEY_SWITCH_ALL_SAVE is not implemented with HEAP.
1622
1623 RETURN
1624 0 ok
1625 HA_ERR_CRASHED data or index is non-empty. Delete all rows and retry.
1626 HA_ERR_WRONG_COMMAND mode not implemented.
1627*/
1628
1629int WiredTigerCursor::enable_indexes(uint32_t mode)
1630{
1631 errmsg_printf(error::INSPECT, "WiredTigerCursor::enable_indexes\n");
1632#if 0
1633 int error;
1634
1635 if (mode == HA_KEY_SWITCH_ALL)
1636 {
1637 if (!(error= wiredtiger_enable_indexes(file)))
1638 set_keys_for_scanning();
1639 }
1640 else
1641 {
1642 /* mode not implemented */
1643 error= HA_ERR_WRONG_COMMAND;
1644 }
1645 return error;
1646#else
1647 WT_UNUSED(mode);
1648 return 0;
1649#endif
1650}
1651
1652
1653/*
1654 Test if indexes are disabled.
1655
1656 SYNOPSIS
1657 indexes_are_disabled()
1658 no parameters
1659
1660 RETURN
1661 0 indexes are not disabled
1662 1 all indexes are disabled
1663 [2 non-unique indexes are disabled - NOT YET IMPLEMENTED]
1664*/
1665
1666int WiredTigerCursor::indexes_are_disabled()
1667{
1668 errmsg_printf(error::INSPECT, "WiredTigerCursor::indexes_are_disabled\n");
1669 return 0;
1670}
1671
1672void WiredTigerCursor::drop_table()
1673{
1674 errmsg_printf(error::INSPECT, "WiredTigerCursor::drop_table\n");
1675}
1676
1677/*********************************************************************/
1680#if 1
1682 key_range *)
1683{
1684 /* The MySQL optimizer seems to believe an estimate of 0 rows is
1685 always accurate and may return the result 'Empty set' based on that.
1686 The accuracy is not guaranteed, and even if it were, for a locking
1687 read we should anyway perform the search to set the next-key lock.
1688 Add 1 to the value to make sure MySQL does not make the assumption! */
1689 errmsg_printf(error::INSPECT, "WiredTigerCursor::records_in_range\n");
1690 ha_rows count = (ha_rows)1;
1691 return count;
1692}
1693#else
1694ha_rows WiredTigerCursor::records_in_range(uint32_t inx, key_range *min_key,
1695 key_range *max_key)
1696{
1697 int ret;
1698 KeyInfo *keyInfo= &getTable()->key_info[inx];
1699
1700 reopen_cursor_if_needed();
1701 string idx_uri(table_uri);
1702 if (strncmp(keyInfo->name, "PRIMARY", strlen("PRIMARY")) != 0)
1703 idx_uri.append(":").append(keyInfo->name);
1704 WT_CURSOR *idx_cursor;
1705 wt_session->open_cursor(wt_session, idx_uri.c_str(),
1706 NULL, "raw", &idx_cursor);
1707 WT_ITEM packedMinKey, packedMaxKey;
1708 packedMinKey.mem = packedMaxKey.mem = NULL;
1709 // Pack the input keys into WiredTiger format.
1710 if (min_key != NULL) {
1711 packedMinKey.data = packedMinKey.mem = malloc(keyInfo->key_length);
1712 packedMinKey.memsize = keyInfo->key_length;
1713 packIndex(wt_cursor->key_format, &packedMinKey, min_key, keyInfo);
1714 idx_cursor->set_key(idx_cursor, &packedMinKey);
1715 ret = idx_cursor->search(idx_cursor);
1716 if (ret == WT_NOTFOUND && min_key->flag == HA_READ_KEY_EXACT)
1717 goto done;
1718 if (ret == WT_NOTFOUND && min_key->flag == HA_READ_KEY_OR_PREV)
1719 idx_cursor->prev(idx_cursor);
1720 }
1721 if (max_key != NULL) {
1722 packedMaxKey.mem = malloc(keyInfo->key_length);
1723 packedMaxKey.size = keyInfo->key_length;
1724 packIndex(wt_cursor->key_format, &packedMaxKey, max_key, keyInfo);
1725 }
1726 WT_ITEM currKey;
1727 do {
1728 ++count;
1729 idx_cursor->next(idx_cursor);
1730 idx_cursor->get_key(idx_cursor, &currKey);
1731 //TODO: Is this comparison correct?
1732 } while (memcmp(currKey.data, packedMaxKey.mem, currKey.size) < 0);
1733done:
1734 idx_cursor->close(idx_cursor);
1735 if (packedMinKey.mem != NULL)
1736 free(packedMinKey.mem);
1737 if (packedMaxKey.mem != NULL)
1738 free(packedMaxKey.mem);
1739 return count;
1740}
1741#endif
1742
1743void WiredTigerCursor::get_auto_increment(uint64_t, uint64_t, uint64_t,
1744 uint64_t *first_value,
1745 uint64_t *nb_reserved_values)
1746{
1747fetch:
1748 *first_value= share->auto_increment_value.fetch_and_increment();
1749 if (*first_value == 0)
1750 {
1751 /* if it's zero, then we skip it... why? because of ass.
1752 set auto-inc to -1 and the sequence is:
1753 -1, 1.
1754 Zero is still "magic".
1755 */
1756 share->auto_increment_value.compare_and_swap(1, 0);
1757 goto fetch;
1758 }
1759 *nb_reserved_values= 1;
1760}
1761
1762int WiredTigerCursor::cmp_ref(const unsigned char *ref1, const unsigned char *ref2)
1763{
1764 uint32_t size1, size2;
1765
1766 memcpy(&size1, ref1, sizeof(size1));
1767 memcpy(&size2, ref2, sizeof(size2));
1768
1769 int r= memcmp(ref1 + sizeof(size1), ref2 + sizeof(size2),
1770 size1 < size2 ? size1 : size2);
1771 if (r != 0)
1772 return r;
1773
1774 return (size1 < size2) ? -1 : (size1 > size2) ? 1 : 0;
1775}
1776
1777uint64_t WiredTigerCursor::getInitialAutoIncrementValue()
1778{
1779 uint64_t nr = 0;
1780 uint64_t defaultVal = getTable()->getShare()->getTableMessage()->
1781 options().auto_increment_value();
1782
1783 setupKeyFields(0, false);
1784 // TODO: Don't record this as a lookup in the statistics.
1785 //(void) extra(HA_EXTRA_KEYREAD);
1786 getTable()->mark_columns_used_by_index_no_reset(
1787 getTable()->getShare()->next_number_index);
1788
1789 // Retrieve the last used ID from the table, if the table already exists.
1790 open_table_cursor();
1791 reopen_cursor_if_needed();
1792 if (wt_cursor->reset(wt_cursor) == 0 &&
1793 wt_cursor->prev(wt_cursor) == 0) {
1794 // Logically we don't need to retrieve the value here, but if we don't
1795 // it's not simple to find the field that contains the primary key we are
1796 // looking for.
1797 WT_ITEM row_key, row_value;
1798 wt_cursor->get_key(wt_cursor, &row_key);
1799 wt_cursor->get_value(wt_cursor, &row_value);
1800 unpackRecord(&row_key, &row_value, getTable()->getInsertRecord());
1801 nr= ((uint64_t) getTable()->found_next_number_field->val_int_offset(0));
1802 ++nr; // We found the largest used, get the next one.
1803 }
1804
1805 if (defaultVal > nr)
1806 nr = defaultVal;
1807
1808 return nr;
1809}
THR_LOCK_DATA ** store_lock(Session *, THR_LOCK_DATA **, thr_lock_type)
drizzled::ha_rows records_in_range(uint32_t inx, drizzled::key_range *min_key, drizzled::key_range *max_key)
int doStartIndexScan(uint32_t idx, bool)
int doStartTableScan(bool scan)
int ha_open(const identifier::Table &identifier, int mode, int test_if_locked)
unsigned char * ptr
Definition field.h:73
Convert from decimal to binary representation.
Definition common_fwd.h:215
TODO: Rename this file - func.h is stupid.
STL namespace.