drizzle
C++ MySQL-protocol-compatible database server
Loading...
Searching...
No Matches
drizzled/cursor.cc
1/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2 * vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3 *
4 * Copyright (C) 2008 Sun Microsystems, Inc.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; version 2 of the License.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
25
26#include <config.h>
27#include <fcntl.h>
28#include <drizzled/error.h>
29#include <drizzled/field/epoch.h>
30#include <drizzled/gettext.h>
31#include <drizzled/internal/my_sys.h>
32#include <drizzled/item/empty_string.h>
33#include <drizzled/item/int.h>
34#include <drizzled/lock.h>
35#include <drizzled/message/table.h>
36#include <drizzled/optimizer/cost_vector.h>
37#include <drizzled/plugin/client.h>
38#include <drizzled/plugin/event_observer.h>
39#include <drizzled/plugin/storage_engine.h>
40#include <drizzled/probes.h>
41#include <drizzled/session.h>
42#include <drizzled/sql_base.h>
43#include <drizzled/sql_parse.h>
44#include <drizzled/transaction_services.h>
45#include <drizzled/key.h>
46#include <drizzled/sql_lex.h>
47#include <drizzled/resource_context.h>
48#include <drizzled/statistics_variables.h>
49#include <drizzled/system_variables.h>
50#include "drizzled/probes.h"
51#include <drizzled/key_part_info.h>
52
53using namespace std;
54
55namespace drizzled {
56
57/****************************************************************************
58** General Cursor functions
59****************************************************************************/
60Cursor::Cursor(plugin::StorageEngine &engine_arg,
61 Table &arg)
62 : table(arg),
63 engine(engine_arg),
64 estimation_rows_to_insert(0),
65 ref(0),
66 key_used_on_scan(MAX_KEY), active_index(MAX_KEY),
67 ref_length(sizeof(internal::my_off_t)),
68 inited(NONE),
69 locked(false),
70 next_insert_id(0), insert_id_for_cur_row(0)
71{ }
72
73Cursor::~Cursor()
74{
75 assert(not locked);
76 /* TODO: assert(inited == NONE); */
77}
78
79
80/*
81 * @note this only used in
82 * optimizer::QuickRangeSelect::init_ror_merged_scan(bool reuse_handler) as
83 * of the writing of this comment. -Brian
84 */
85Cursor *Cursor::clone(memory::Root *mem_root)
86{
87 Cursor *new_handler= getTable()->getMutableShare()->db_type()->getCursor(*getTable());
88 /*
89 Allocate Cursor->ref here because otherwise ha_open will allocate it
90 on this->table->mem_root and we will not be able to reclaim that memory
91 when the clone Cursor object is destroyed.
92 */
93 new_handler->ref= mem_root->alloc(ALIGN_SIZE(ref_length)*2);
94 identifier::Table identifier(*getTable());
95 return new_handler->ha_open(identifier, getTable()->getDBStat(), HA_OPEN_IGNORE_IF_LOCKED) ? NULL : new_handler;
96}
97
98/*
99 DESCRIPTION
100 given a buffer with a key value, and a map of keyparts
101 that are present in this value, returns the length of the value
102*/
103uint32_t Cursor::calculate_key_len(uint32_t key_position, key_part_map keypart_map_arg)
104{
105 /* works only with key prefixes */
106 assert(((keypart_map_arg + 1) & keypart_map_arg) == 0);
107
108 const KeyPartInfo *key_part_found= getTable()->getShare()->getKeyInfo(key_position).key_part;
109 const KeyPartInfo *end_key_part_found= key_part_found + getTable()->getShare()->getKeyInfo(key_position).key_parts;
110 uint32_t length= 0;
111
112 while (key_part_found < end_key_part_found && keypart_map_arg)
113 {
114 length+= key_part_found->store_length;
115 keypart_map_arg >>= 1;
116 key_part_found++;
117 }
118 return length;
119}
120
121int Cursor::startIndexScan(uint32_t idx, bool sorted)
122{
123 int result;
124 assert(inited == NONE);
125 if (!(result= doStartIndexScan(idx, sorted)))
126 inited=INDEX;
127 end_range= NULL;
128 return result;
129}
130
131int Cursor::endIndexScan()
132{
133 assert(inited==INDEX);
134 inited=NONE;
135 end_range= NULL;
136 return(doEndIndexScan());
137}
138
139int Cursor::startTableScan(bool scan)
140{
141 int result;
142 assert(inited==NONE || (inited==RND && scan));
143 inited= (result= doStartTableScan(scan)) ? NONE: RND;
144
145 return result;
146}
147
148int Cursor::endTableScan()
149{
150 assert(inited==RND);
151 inited=NONE;
152 return(doEndTableScan());
153}
154
155int Cursor::ha_index_or_rnd_end()
156{
157 return inited == INDEX ? endIndexScan() : inited == RND ? endTableScan() : 0;
158}
159
160void Cursor::ha_start_bulk_insert(ha_rows rows)
161{
162 estimation_rows_to_insert= rows;
163 start_bulk_insert(rows);
164}
165
166int Cursor::ha_end_bulk_insert()
167{
168 estimation_rows_to_insert= 0;
169 return end_bulk_insert();
170}
171
172const key_map *Cursor::keys_to_use_for_scanning()
173{
174 return &key_map_empty;
175}
176
177bool Cursor::has_transactions()
178{
179 return (getEngine()->participatesInSqlTransaction());
180}
181
182void Cursor::ha_statistic_increment(uint64_t system_status_var::*offset) const
183{
184 (getTable()->in_use->status_var.*offset)++;
185}
186
187void **Cursor::ha_data(Session *session) const
188{
189 return session->getEngineData(getEngine());
190}
191
192bool Cursor::is_fatal_error(int error, uint32_t flags)
193{
194 if (!error ||
195 ((flags & HA_CHECK_DUP_KEY) &&
196 (error == HA_ERR_FOUND_DUPP_KEY ||
197 error == HA_ERR_FOUND_DUPP_UNIQUE)))
198 return false;
199 return true;
200}
201
202
203ha_rows Cursor::records() { return stats.records; }
204uint64_t Cursor::tableSize() { return stats.index_file_length + stats.data_file_length; }
205uint64_t Cursor::rowSize() { return getTable()->getRecordLength() + getTable()->sizeFields(); }
206
207int Cursor::doOpen(const identifier::Table &identifier, int mode, uint32_t test_if_locked)
208{
209 return open(identifier.getPath().c_str(), mode, test_if_locked);
210}
211
218int Cursor::ha_open(const identifier::Table &identifier,
219 int mode,
220 int test_if_locked)
221{
222 int error;
223
224 if ((error= doOpen(identifier, mode, test_if_locked)))
225 {
226 if ((error == EACCES || error == EROFS) && mode == O_RDWR &&
227 (getTable()->db_stat & HA_TRY_READ_ONLY))
228 {
229 getTable()->db_stat|=HA_READ_ONLY;
230 error= doOpen(identifier, O_RDONLY,test_if_locked);
231 }
232 }
233 if (error)
234 {
235 errno= error; /* Safeguard */
236 }
237 else
238 {
239 if (getTable()->getShare()->db_options_in_use & HA_OPTION_READ_ONLY_DATA)
240 getTable()->db_stat|=HA_READ_ONLY;
241 (void) extra(HA_EXTRA_NO_READCHECK); // Not needed in SQL
242
243 /* ref is already allocated for us if we're called from Cursor::clone() */
244 if (!ref)
245 ref= getTable()->alloc(ALIGN_SIZE(ref_length)*2);
246 dup_ref=ref+ALIGN_SIZE(ref_length);
247 }
248 return error;
249}
250
257int Cursor::read_first_row(unsigned char * buf, uint32_t primary_key)
258{
259 int error;
260
261 ha_statistic_increment(&system_status_var::ha_read_first_count);
262
263 /*
264 If there is very few deleted rows in the table, find the first row by
265 scanning the table.
266 @todo remove the test for HA_READ_ORDER
267 */
268 if (stats.deleted < 10 || primary_key >= MAX_KEY ||
269 !(getTable()->index_flags(primary_key) & HA_READ_ORDER))
270 {
271 error= startTableScan(1);
272 if (error == 0)
273 {
274 while ((error= rnd_next(buf)) == HA_ERR_RECORD_DELETED) ;
275 (void) endTableScan();
276 }
277 }
278 else
279 {
280 /* Find the first row through the primary key */
281 error= startIndexScan(primary_key, 0);
282 if (error == 0)
283 {
284 error=index_first(buf);
285 (void) endIndexScan();
286 }
287 }
288 return error;
289}
290
302inline uint64_t
304{
305 if (variables->auto_increment_increment == 1)
306 return (nr+1); // optimization of the formula below
307 nr= (((nr+ variables->auto_increment_increment -
308 variables->auto_increment_offset)) /
309 (uint64_t) variables->auto_increment_increment);
310 return (nr* (uint64_t) variables->auto_increment_increment +
311 variables->auto_increment_offset);
312}
313
314
315void Cursor::adjust_next_insert_id_after_explicit_value(uint64_t nr)
316{
317 /*
318 If we have set Session::next_insert_id previously and plan to insert an
319 explicitely-specified value larger than this, we need to increase
320 Session::next_insert_id to be greater than the explicit value.
321 */
322 if ((next_insert_id > 0) && (nr >= next_insert_id))
323 set_next_insert_id(compute_next_insert_id(nr, &getTable()->in_use->variables));
324}
325
326
342inline uint64_t
344{
345 if (DRIZZLE_UNLIKELY(nr < variables->auto_increment_offset))
346 {
347 /*
348 There's nothing good we can do here. That is a pathological case, where
349 the offset is larger than the column's max possible value, i.e. not even
350 the first sequence value may be inserted. User will receive warning.
351 */
352 return nr;
353 }
354 if (variables->auto_increment_increment == 1)
355 return nr; // optimization of the formula below
356 nr= (((nr - variables->auto_increment_offset)) /
357 (uint64_t) variables->auto_increment_increment);
358 return (nr * (uint64_t) variables->auto_increment_increment +
359 variables->auto_increment_offset);
360}
361
362
423
424#define AUTO_INC_DEFAULT_NB_ROWS 1 // Some prefer 1024 here
425#define AUTO_INC_DEFAULT_NB_MAX_BITS 16
426#define AUTO_INC_DEFAULT_NB_MAX ((1 << AUTO_INC_DEFAULT_NB_MAX_BITS) - 1)
427
428int Cursor::update_auto_increment()
429{
430 uint64_t nr, nb_reserved_values;
431 bool append= false;
432 Session *session= getTable()->in_use;
433 drizzle_system_variables *variables= &session->variables;
434
435 /*
436 next_insert_id is a "cursor" into the reserved interval, it may go greater
437 than the interval, but not smaller.
438 */
439 assert(next_insert_id >= auto_inc_interval_for_cur_row.minimum());
440
441 /* We check if auto_increment_field_not_null is false
442 for an auto increment column, not a magic value like NULL is.
443 same as sql_mode=NO_AUTO_VALUE_ON_ZERO */
444
445 if ((nr= getTable()->next_number_field->val_int()) != 0
446 || getTable()->auto_increment_field_not_null)
447 {
448 /*
449 Update next_insert_id if we had already generated a value in this
450 statement (case of INSERT VALUES(null),(3763),(null):
451 the last NULL needs to insert 3764, not the value of the first NULL plus
452 1).
453 */
454 adjust_next_insert_id_after_explicit_value(nr);
455 insert_id_for_cur_row= 0; // didn't generate anything
456
457 return 0;
458 }
459
460 if ((nr= next_insert_id) >= auto_inc_interval_for_cur_row.maximum())
461 {
462 {
463 /*
464 Cursor::estimation_rows_to_insert was set by
465 Cursor::ha_start_bulk_insert(); if 0 it means "unknown".
466 */
467 uint32_t nb_already_reserved_intervals= 0;
468 uint64_t nb_desired_values;
469 /*
470 If an estimation was given to the engine:
471 - use it.
472 - if we already reserved numbers, it means the estimation was
473 not accurate, then we'll reserve 2*AUTO_INC_DEFAULT_NB_ROWS the 2nd
474 time, twice that the 3rd time etc.
475 If no estimation was given, use those increasing defaults from the
476 start, starting from AUTO_INC_DEFAULT_NB_ROWS.
477 Don't go beyond a max to not reserve "way too much" (because
478 reservation means potentially losing unused values).
479 */
480 if (nb_already_reserved_intervals == 0 &&
481 (estimation_rows_to_insert > 0))
482 nb_desired_values= estimation_rows_to_insert;
483 else /* go with the increasing defaults */
484 {
485 /* avoid overflow in formula, with this if() */
486 if (nb_already_reserved_intervals <= AUTO_INC_DEFAULT_NB_MAX_BITS)
487 {
488 nb_desired_values= AUTO_INC_DEFAULT_NB_ROWS *
489 (1 << nb_already_reserved_intervals);
490 set_if_smaller(nb_desired_values, (uint64_t)AUTO_INC_DEFAULT_NB_MAX);
491 }
492 else
493 nb_desired_values= AUTO_INC_DEFAULT_NB_MAX;
494 }
495 /* This call ignores all its parameters but nr, currently */
496 get_auto_increment(variables->auto_increment_offset,
497 variables->auto_increment_increment,
498 nb_desired_values, &nr,
499 &nb_reserved_values);
500 if (nr == ~(uint64_t) 0)
501 return HA_ERR_AUTOINC_READ_FAILED; // Mark failure
502
503 /*
504 That rounding below should not be needed when all engines actually
505 respect offset and increment in get_auto_increment(). But they don't
506 so we still do it. Wonder if for the not-first-in-index we should do
507 it. Hope that this rounding didn't push us out of the interval; even
508 if it did we cannot do anything about it (calling the engine again
509 will not help as we inserted no row).
510 */
511 nr= compute_next_insert_id(nr-1, variables);
512 }
513
514 if (getTable()->getShare()->next_number_keypart == 0)
515 {
516 /* We must defer the appending until "nr" has been possibly truncated */
517 append= true;
518 }
519 }
520
521 if (DRIZZLE_UNLIKELY(getTable()->next_number_field->store((int64_t) nr, true)))
522 {
523 /*
524 first test if the query was aborted due to strict mode constraints
525 */
526 if (session->getKilled() == Session::KILL_BAD_DATA)
527 return HA_ERR_AUTOINC_ERANGE;
528
529 /*
530 field refused this value (overflow) and truncated it, use the result of
531 the truncation (which is going to be inserted); however we try to
532 decrease it to honour auto_increment_* variables.
533 That will shift the left bound of the reserved interval, we don't
534 bother shifting the right bound (anyway any other value from this
535 interval will cause a duplicate key).
536 */
537 nr= prev_insert_id(getTable()->next_number_field->val_int(), variables);
538 if (DRIZZLE_UNLIKELY(getTable()->next_number_field->store((int64_t) nr, true)))
539 nr= getTable()->next_number_field->val_int();
540 }
541 if (append)
542 auto_inc_interval_for_cur_row.replace(nr, nb_reserved_values, variables->auto_increment_increment);
543
544 /*
545 Record this autogenerated value. If the caller then
546 succeeds to insert this value, it will call
547 record_first_successful_insert_id_in_cur_stmt()
548 which will set first_successful_insert_id_in_cur_stmt if it's not
549 already set.
550 */
551 insert_id_for_cur_row= nr;
552 /*
553 Set next insert id to point to next auto-increment value to be able to
554 handle multi-row statements.
555 */
556 set_next_insert_id(compute_next_insert_id(nr, variables));
557
558 return 0;
559}
560
561
577
579{
580 release_auto_increment();
582 auto_inc_interval_for_cur_row.replace(0, 0, 0);
584}
585
586void Cursor::drop_table()
587{
588 close();
589}
590
591int Cursor::ha_check(Session*)
592{
593 return HA_ADMIN_OK;
594}
595
600
601inline
602void
604{
605 /*
606 * If the cursor has not context for execution then there should be no
607 * possible resource to gain (and if there is... then there is a bug such
608 * that in_use should have been set.
609 */
610 if (not getTable()->in_use)
611 return;
612
613 /*
614 When a storage engine method is called, the transaction must
615 have been started, unless it's a DDL call, for which the
616 storage engine starts the transaction internally, and commits
617 it internally, without registering in the ha_list.
618 Unfortunately here we can't know know for sure if the engine
619 has registered the transaction or not, so we must check.
620 */
621 ResourceContext& resource_context= getTable()->in_use->getResourceContext(*getEngine());
622 if (resource_context.isStarted())
623 resource_context.markModifiedData();
624}
625
626
636
637int
639{
641
642 int result= delete_all_rows();
643
644 if (result == 0)
645 {
652 Session& session= *getTable()->in_use;
653 TransactionServices::truncateTable(session, *getTable());
654 }
655
656 return result;
657}
658
659
665
666int
668{
670
671 return reset_auto_increment(value);
672}
673
674
680
681int
683{
685
686 return analyze(session);
687}
688
694
695int
697{
699
700 return disable_indexes(mode);
701}
702
703
709
710int
712{
714
715 return enable_indexes(mode);
716}
717
718
724
726{
728 return discard_or_import_tablespace(discard);
729}
730
736
738{
740 return drop_table();
741}
742
743int Cursor::index_next_same(unsigned char *buf, const unsigned char *key, uint32_t keylen)
744{
745 int error= index_next(buf);
746 if (error)
747 return error;
748
749 ptrdiff_t ptrdiff= buf - getTable()->getInsertRecord();
750 unsigned char *save_record_0= NULL;
751 KeyInfo *key_info= NULL;
752 KeyPartInfo *key_part;
753 KeyPartInfo *key_part_end= NULL;
754
755 /*
756 key_cmp_if_same() compares table->getInsertRecord() against 'key'.
757 In parts it uses table->getInsertRecord() directly, in parts it uses
758 field objects with their local pointers into table->getInsertRecord().
759 If 'buf' is distinct from table->getInsertRecord(), we need to move
760 all record references. This is table->getInsertRecord() itself and
761 the field pointers of the fields used in this key.
762 */
763 if (ptrdiff)
764 {
765 save_record_0= getTable()->getInsertRecord();
766 getTable()->record[0]= buf;
767 key_info= getTable()->key_info + active_index;
768 key_part= key_info->key_part;
769 key_part_end= key_part + key_info->key_parts;
770 for (; key_part < key_part_end; key_part++)
771 {
772 assert(key_part->field);
773 key_part->field->move_field_offset(ptrdiff);
774 }
775 }
776
777 if (key_cmp_if_same(getTable(), key, active_index, keylen))
778 {
779 getTable()->status=STATUS_NOT_FOUND;
780 error= HA_ERR_END_OF_FILE;
781 }
782
783 /* Move back if necessary. */
784 if (ptrdiff)
785 {
786 getTable()->record[0]= save_record_0;
787 for (key_part= key_info->key_part; key_part < key_part_end; key_part++)
788 key_part->field->move_field_offset(-ptrdiff);
789 }
790 return error;
791}
792
793
794/****************************************************************************
795** Some general functions that isn't in the Cursor class
796****************************************************************************/
797
818
819double Cursor::index_only_read_time(uint32_t keynr, double key_records)
820{
821 uint32_t keys_per_block= (stats.block_size/2/
822 (getTable()->key_info[keynr].key_length + ref_length) + 1);
823 return ((double) (key_records + keys_per_block-1) /
824 (double) keys_per_block);
825}
826
827
828/****************************************************************************
829 * Default MRR implementation (MRR to non-MRR converter)
830 ***************************************************************************/
831
862
863ha_rows
864Cursor::multi_range_read_info_const(uint32_t keyno, RANGE_SEQ_IF *seq,
865 void *seq_init_param,
866 uint32_t ,
867 uint32_t *bufsz, uint32_t *flags, optimizer::CostVector *cost)
868{
869 KEY_MULTI_RANGE range;
870 range_seq_t seq_it;
871 ha_rows rows, total_rows= 0;
872 uint32_t n_ranges=0;
873
874 /* Default MRR implementation doesn't need buffer */
875 *bufsz= 0;
876
877 seq_it= seq->init(seq_init_param, n_ranges, *flags);
878 while (!seq->next(seq_it, &range))
879 {
880 n_ranges++;
881 key_range *min_endp, *max_endp;
882 {
883 min_endp= range.start_key.length? &range.start_key : NULL;
884 max_endp= range.end_key.length? &range.end_key : NULL;
885 }
886 if ((range.range_flag & UNIQUE_RANGE) && !(range.range_flag & NULL_RANGE))
887 rows= 1; /* there can be at most one row */
888 else
889 {
890 if (HA_POS_ERROR == (rows= this->records_in_range(keyno, min_endp,
891 max_endp)))
892 {
893 /* Can't scan one range => can't do MRR scan at all */
894 total_rows= HA_POS_ERROR;
895 break;
896 }
897 }
898 total_rows += rows;
899 }
900
901 if (total_rows != HA_POS_ERROR)
902 {
903 /* The following calculation is the same as in multi_range_read_info(): */
904 *flags |= HA_MRR_USE_DEFAULT_IMPL;
905 cost->zero();
906 cost->setAvgIOCost(1); /* assume random seeks */
907 if ((*flags & HA_MRR_INDEX_ONLY) && total_rows > 2)
908 cost->setIOCount(index_only_read_time(keyno, (uint32_t)total_rows));
909 else
910 cost->setIOCount(read_time(keyno, n_ranges, total_rows));
911 cost->setCpuCost((double) total_rows / TIME_FOR_COMPARE + 0.01);
912 }
913 return total_rows;
914}
915
916
950
951int Cursor::multi_range_read_info(uint32_t keyno, uint32_t n_ranges, uint32_t n_rows,
952 uint32_t *bufsz, uint32_t *flags, optimizer::CostVector *cost)
953{
954 *bufsz= 0; /* Default implementation doesn't need a buffer */
955
956 *flags |= HA_MRR_USE_DEFAULT_IMPL;
957
958 cost->zero();
959 cost->setAvgIOCost(1); /* assume random seeks */
960
961 /* Produce the same cost as non-MRR code does */
962 if (*flags & HA_MRR_INDEX_ONLY)
963 cost->setIOCount(index_only_read_time(keyno, n_rows));
964 else
965 cost->setIOCount(read_time(keyno, n_ranges, n_rows));
966 return 0;
967}
968
969
1010
1011int
1012Cursor::multi_range_read_init(RANGE_SEQ_IF *seq_funcs, void *seq_init_param,
1013 uint32_t n_ranges, uint32_t mode)
1014{
1015 mrr_iter= seq_funcs->init(seq_init_param, n_ranges, mode);
1016 mrr_funcs= *seq_funcs;
1017 mrr_is_output_sorted= test(mode & HA_MRR_SORTED);
1018 mrr_have_range= false;
1019
1020 return 0;
1021}
1022
1023
1036
1037int Cursor::multi_range_read_next(char **range_info)
1038{
1039 int result= 0;
1040 int range_res= 0;
1041
1042 if (not mrr_have_range)
1043 {
1044 mrr_have_range= true;
1045 goto start;
1046 }
1047
1048 do
1049 {
1050 /* Save a call if there can be only one row in range. */
1051 if (mrr_cur_range.range_flag != (UNIQUE_RANGE | EQ_RANGE))
1052 {
1053 result= read_range_next();
1054 /* On success or non-EOF errors jump to the end. */
1055 if (result != HA_ERR_END_OF_FILE)
1056 break;
1057 }
1058 else
1059 {
1061 goto scan_it_again;
1062 /*
1063 We need to set this for the last range only, but checking this
1064 condition is more expensive than just setting the result code.
1065 */
1066 result= HA_ERR_END_OF_FILE;
1067 }
1068
1069start:
1070 /* Try the next range(s) until one matches a record. */
1071 while (!(range_res= mrr_funcs.next(mrr_iter, &mrr_cur_range)))
1072 {
1073scan_it_again:
1074 result= read_range_first(mrr_cur_range.start_key.keypart_map ?
1075 &mrr_cur_range.start_key : 0,
1076 mrr_cur_range.end_key.keypart_map ?
1077 &mrr_cur_range.end_key : 0,
1078 test(mrr_cur_range.range_flag & EQ_RANGE),
1079 mrr_is_output_sorted);
1080 if (result != HA_ERR_END_OF_FILE)
1081 break;
1082 }
1083 }
1084 while ((result == HA_ERR_END_OF_FILE) && !range_res);
1085
1086 *range_info= mrr_cur_range.ptr;
1087 return result;
1088}
1089
1090
1091/* **************************************************************************
1092 * DS-MRR implementation ends
1093 ***************************************************************************/
1094
1114 const key_range *end_key,
1115 bool eq_range_arg,
1116 bool )
1117{
1118 int result;
1119
1120 eq_range= eq_range_arg;
1121 end_range= 0;
1122 if (end_key)
1123 {
1124 end_range= &save_end_range;
1125 save_end_range= *end_key;
1126 key_compare_result_on_equal= ((end_key->flag == HA_READ_BEFORE_KEY) ? 1 :
1127 (end_key->flag == HA_READ_AFTER_KEY) ? -1 : 0);
1128 }
1129 range_key_part= getTable()->key_info[active_index].key_part;
1130
1131 if (!start_key) // Read first record
1132 result= index_first(getTable()->getInsertRecord());
1133 else
1134 result= index_read_map(getTable()->getInsertRecord(),
1135 start_key->key,
1136 start_key->keypart_map,
1137 start_key->flag);
1138 if (result)
1139 return((result == HA_ERR_KEY_NOT_FOUND)
1140 ? HA_ERR_END_OF_FILE
1141 : result);
1142
1143 return (compare_key(end_range) <= 0 ? 0 : HA_ERR_END_OF_FILE);
1144}
1145
1146
1161{
1162 int result;
1163
1164 if (eq_range)
1165 {
1166 /* We trust that index_next_same always gives a row in range */
1167 return(index_next_same(getTable()->getInsertRecord(),
1168 end_range->key,
1169 end_range->length));
1170 }
1171 result= index_next(getTable()->getInsertRecord());
1172 if (result)
1173 return result;
1174 return(compare_key(end_range) <= 0 ? 0 : HA_ERR_END_OF_FILE);
1175}
1176
1177
1194{
1195 int cmp;
1196 if (not range)
1197 return 0; // No max range
1198 cmp= key_cmp(range_key_part, range->key, range->length);
1199 if (!cmp)
1200 cmp= key_compare_result_on_equal;
1201 return cmp;
1202}
1203
1204int Cursor::index_read_idx_map(unsigned char * buf, uint32_t index,
1205 const unsigned char * key,
1206 key_part_map keypart_map,
1207 enum ha_rkey_function find_flag)
1208{
1209 int error, error1;
1210 error= doStartIndexScan(index, 0);
1211 if (!error)
1212 {
1213 error= index_read_map(buf, key, keypart_map, find_flag);
1214 error1= doEndIndexScan();
1215 }
1216 return error ? error : error1;
1217}
1218
1219static bool log_row_for_replication(Table* table,
1220 const unsigned char *before_record,
1221 const unsigned char *after_record)
1222{
1223 Session *const session= table->in_use;
1224
1225 if (table->getShare()->getType() || not TransactionServices::shouldConstructMessages())
1226 return false;
1227
1228 bool result= false;
1229
1230 switch (session->lex().sql_command)
1231 {
1232 case SQLCOM_CREATE_TABLE:
1233 /*
1234 * We are in a CREATE TABLE ... SELECT statement
1235 * and the kernel has already created the table
1236 * and put a CreateTableStatement in the active
1237 * Transaction message. Here, we add a new InsertRecord
1238 * to a new Transaction message (because the above
1239 * CREATE TABLE will commit the transaction containing
1240 * it).
1241 */
1242 result= TransactionServices::insertRecord(*session, *table);
1243 break;
1244 case SQLCOM_REPLACE:
1245 case SQLCOM_REPLACE_SELECT:
1246 /*
1247 * This is a total hack because of the code that is
1248 * in write_record() in sql_insert.cc. During
1249 * a REPLACE statement, a call to insertRecord() is
1250 * called. If it fails, then a call to deleteRecord()
1251 * is called, followed by a repeat of the original
1252 * call to insertRecord(). So, log_row_for_replication
1253 * could be called multiple times for a REPLACE
1254 * statement. The below looks at the values of before_record
1255 * and after_record to determine which call to this
1256 * function is for the delete or the insert, since NULL
1257 * is passed for after_record for the delete and NULL is
1258 * passed for before_record for the insert...
1259 *
1260 * In addition, there is an optimization that allows an
1261 * engine to convert the above delete + insert into an
1262 * update, so we must also check for this case below...
1263 */
1264 if (after_record == NULL)
1265 {
1266 /*
1267 * The storage engine is passed the record in table->record[1]
1268 * as the row to delete (this is the conflicting row), so
1269 * we need to notify TransactionService to use that row.
1270 */
1271 TransactionServices::deleteRecord(*session, *table, true);
1272 /*
1273 * We set the "current" statement message to NULL. This triggers
1274 * the replication services component to generate a new statement
1275 * message for the inserted record which will come next.
1276 */
1277 TransactionServices::finalizeStatementMessage(*session->getStatementMessage(), *session);
1278 }
1279 else
1280 {
1281 if (before_record == NULL)
1282 result= TransactionServices::insertRecord(*session, *table);
1283 else
1284 TransactionServices::updateRecord(*session, *table, before_record, after_record);
1285 }
1286 break;
1287 case SQLCOM_INSERT:
1288 case SQLCOM_INSERT_SELECT:
1289 case SQLCOM_LOAD:
1290 /*
1291 * The else block below represents an
1292 * INSERT ... ON DUPLICATE KEY UPDATE that
1293 * has hit a key conflict and actually done
1294 * an update.
1295 */
1296 if (before_record == NULL)
1297 result= TransactionServices::insertRecord(*session, *table);
1298 else
1299 TransactionServices::updateRecord(*session, *table, before_record, after_record);
1300 break;
1301
1302 case SQLCOM_UPDATE:
1303 TransactionServices::updateRecord(*session, *table, before_record, after_record);
1304 break;
1305
1306 case SQLCOM_DELETE:
1307 TransactionServices::deleteRecord(*session, *table);
1308 break;
1309 default:
1310 break;
1311 }
1312
1313 return result;
1314}
1315
1316int Cursor::ha_external_lock(Session *session, int lock_type)
1317{
1318 /*
1319 Whether this is lock or unlock, this should be true, and is to verify that
1320 if get_auto_increment() was called (thus may have reserved intervals or
1321 taken a table lock), ha_release_auto_increment() was too.
1322 */
1323 assert(next_insert_id == 0);
1324
1325 if (DRIZZLE_CURSOR_RDLOCK_START_ENABLED() ||
1326 DRIZZLE_CURSOR_WRLOCK_START_ENABLED() ||
1327 DRIZZLE_CURSOR_UNLOCK_START_ENABLED())
1328 {
1329 if (lock_type == F_RDLCK)
1330 {
1331 DRIZZLE_CURSOR_RDLOCK_START(getTable()->getShare()->getSchemaName(),
1332 getTable()->getShare()->getTableName());
1333 }
1334 else if (lock_type == F_WRLCK)
1335 {
1336 DRIZZLE_CURSOR_WRLOCK_START(getTable()->getShare()->getSchemaName(),
1337 getTable()->getShare()->getTableName());
1338 }
1339 else if (lock_type == F_UNLCK)
1340 {
1341 DRIZZLE_CURSOR_UNLOCK_START(getTable()->getShare()->getSchemaName(),
1342 getTable()->getShare()->getTableName());
1343 }
1344 }
1345
1346 /*
1347 We cache the table flags if the locking succeeded. Otherwise, we
1348 keep them as they were when they were fetched in ha_open().
1349 */
1350
1351 int error= external_lock(session, lock_type);
1352
1353 if (DRIZZLE_CURSOR_RDLOCK_DONE_ENABLED() ||
1354 DRIZZLE_CURSOR_WRLOCK_DONE_ENABLED() ||
1355 DRIZZLE_CURSOR_UNLOCK_DONE_ENABLED())
1356 {
1357 if (lock_type == F_RDLCK)
1358 {
1359 DRIZZLE_CURSOR_RDLOCK_DONE(error);
1360 }
1361 else if (lock_type == F_WRLCK)
1362 {
1363 DRIZZLE_CURSOR_WRLOCK_DONE(error);
1364 }
1365 else if (lock_type == F_UNLCK)
1366 {
1367 DRIZZLE_CURSOR_UNLOCK_DONE(error);
1368 }
1369 }
1370
1371 return error;
1372}
1373
1374
1379{
1380 /* Check that we have called all proper deallocation functions */
1381 assert(! getTable()->getShare()->all_set.none());
1382 assert(getTable()->key_read == 0);
1383 /* ensure that ha_index_end / endTableScan has been called */
1384 assert(inited == NONE);
1385 /* Free cache used by filesort */
1386 getTable()->free_io_cache();
1387 /* reset the bitmaps to point to defaults */
1388 getTable()->default_column_bitmaps();
1389 return(reset());
1390}
1391
1392
1393int Cursor::insertRecord(unsigned char *buf)
1394{
1395 int error;
1396
1397 /*
1398 * If we have a timestamp column, update it to the current time
1399 *
1400 * @TODO Technically, the below two lines can be take even further out of the
1401 * Cursor interface and into the fill_record() method.
1402 */
1403 if (getTable()->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT)
1404 {
1405 getTable()->timestamp_field->set_time();
1406 }
1407
1408 DRIZZLE_INSERT_ROW_START(getTable()->getShare()->getSchemaName(), getTable()->getShare()->getTableName());
1409 setTransactionReadWrite();
1410
1411 if (DRIZZLE_UNLIKELY(plugin::EventObserver::beforeInsertRecord(*getTable(), buf)))
1412 {
1413 error= ER_EVENT_OBSERVER_PLUGIN;
1414 }
1415 else
1416 {
1417 error= doInsertRecord(buf);
1418 if (DRIZZLE_UNLIKELY(plugin::EventObserver::afterInsertRecord(*getTable(), buf, error)))
1419 {
1420 error= ER_EVENT_OBSERVER_PLUGIN;
1421 }
1422 }
1423
1424 ha_statistic_increment(&system_status_var::ha_write_count);
1425
1426 DRIZZLE_INSERT_ROW_DONE(error);
1427
1428 if (DRIZZLE_UNLIKELY(error))
1429 {
1430 return error;
1431 }
1432
1433 if (DRIZZLE_UNLIKELY(log_row_for_replication(getTable(), NULL, buf)))
1434 return HA_ERR_LOG_ROW_FOR_REPLICATION_FAILED;
1435
1436 return 0;
1437}
1438
1439
1440int Cursor::updateRecord(const unsigned char *old_data, unsigned char *new_data)
1441{
1442 int error;
1443
1444 /*
1445 Some storage engines require that the new record is in getInsertRecord()
1446 (and the old record is in getUpdateRecord()).
1447 */
1448 assert(new_data == getTable()->getInsertRecord());
1449
1450 DRIZZLE_UPDATE_ROW_START(getTable()->getShare()->getSchemaName(), getTable()->getShare()->getTableName());
1451 setTransactionReadWrite();
1452 if (DRIZZLE_UNLIKELY(plugin::EventObserver::beforeUpdateRecord(*getTable(), old_data, new_data)))
1453 {
1454 error= ER_EVENT_OBSERVER_PLUGIN;
1455 }
1456 else
1457 {
1458 if (getTable()->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_UPDATE)
1459 {
1460 getTable()->timestamp_field->set_time();
1461 }
1462
1463 error= doUpdateRecord(old_data, new_data);
1464 if (DRIZZLE_UNLIKELY(plugin::EventObserver::afterUpdateRecord(*getTable(), old_data, new_data, error)))
1465 {
1466 error= ER_EVENT_OBSERVER_PLUGIN;
1467 }
1468 }
1469
1470 ha_statistic_increment(&system_status_var::ha_update_count);
1471
1472 DRIZZLE_UPDATE_ROW_DONE(error);
1473
1474 if (DRIZZLE_UNLIKELY(error))
1475 {
1476 return error;
1477 }
1478
1479 if (DRIZZLE_UNLIKELY(log_row_for_replication(getTable(), old_data, new_data)))
1480 return HA_ERR_LOG_ROW_FOR_REPLICATION_FAILED;
1481
1482 return 0;
1483}
1484TableShare *Cursor::getShare()
1485{
1486 return getTable()->getMutableShare();
1487}
1488
1489int Cursor::deleteRecord(const unsigned char *buf)
1490{
1491 int error;
1492
1493 DRIZZLE_DELETE_ROW_START(getTable()->getShare()->getSchemaName(), getTable()->getShare()->getTableName());
1494 setTransactionReadWrite();
1495 if (DRIZZLE_UNLIKELY(plugin::EventObserver::beforeDeleteRecord(*getTable(), buf)))
1496 {
1497 error= ER_EVENT_OBSERVER_PLUGIN;
1498 }
1499 else
1500 {
1501 error= doDeleteRecord(buf);
1502 if (DRIZZLE_UNLIKELY(plugin::EventObserver::afterDeleteRecord(*getTable(), buf, error)))
1503 {
1504 error= ER_EVENT_OBSERVER_PLUGIN;
1505 }
1506 }
1507
1508 ha_statistic_increment(&system_status_var::ha_delete_count);
1509
1510 DRIZZLE_DELETE_ROW_DONE(error);
1511
1512 if (DRIZZLE_UNLIKELY(error))
1513 return error;
1514
1515 if (DRIZZLE_UNLIKELY(log_row_for_replication(getTable(), buf, NULL)))
1516 return HA_ERR_LOG_ROW_FOR_REPLICATION_FAILED;
1517
1518 return 0;
1519}
1520
1521} /* namespace drizzled */
virtual int multi_range_read_init(RANGE_SEQ_IF *seq, void *seq_init_param, uint32_t n_ranges, uint32_t mode)
KEY_MULTI_RANGE mrr_cur_range
virtual bool is_fatal_error(int error, uint32_t flags)
virtual ha_rows records()
uint64_t insert_id_for_cur_row
int ha_enable_indexes(uint32_t mode)
int compare_key(key_range *range)
virtual int read_range_first(const key_range *start_key, const key_range *end_key, bool eq_range, bool sorted)
int ha_open(const identifier::Table &identifier, int mode, int test_if_locked)
virtual double index_only_read_time(uint32_t keynr, double records)
virtual int delete_all_rows(void)
virtual int index_read_map(unsigned char *buf, const unsigned char *key, key_part_map keypart_map, enum ha_rkey_function find_flag)
Positions an index cursor to the index specified in the handle. Fetches the row if available....
virtual bool was_semi_consistent_read()
int ha_reset_auto_increment(uint64_t value)
int ha_external_lock(Session *session, int lock_type)
int ha_discard_or_import_tablespace(bool discard)
virtual int reset()
int ha_disable_indexes(uint32_t mode)
virtual ha_rows multi_range_read_info_const(uint32_t keyno, RANGE_SEQ_IF *seq, void *seq_init_param, uint32_t n_ranges, uint32_t *bufsz, uint32_t *flags, optimizer::CostVector *cost)
virtual int multi_range_read_info(uint32_t keyno, uint32_t n_ranges, uint32_t keys, uint32_t *bufsz, uint32_t *flags, optimizer::CostVector *cost)
virtual int reset_auto_increment(uint64_t)
virtual int external_lock(Session *, int)
virtual int index_read_idx_map(unsigned char *buf, uint32_t index, const unsigned char *key, key_part_map keypart_map, enum ha_rkey_function find_flag)
Positions an index cursor to the index specified in the handle. Fetches the row if available....
virtual int read_first_row(unsigned char *buf, uint32_t primary_key)
Discrete_interval auto_inc_interval_for_cur_row
int ha_analyze(Session *)
virtual int read_range_next()
virtual int multi_range_read_next(char **range_info)
static bool insertRecord(Session &, Table &in_table)
static void finalizeStatementMessage(message::Statement &, Session &)
static void deleteRecord(Session &, Table &, bool use_update_record=false)
static void truncateTable(Session &, Table &)
#define TIME_FOR_COMPARE
TODO: Rename this file - func.h is stupid.
uint64_t compute_next_insert_id(uint64_t nr, drizzle_system_variables *variables)
uint64_t prev_insert_id(uint64_t nr, drizzle_system_variables *variables)
int key_cmp(KeyPartInfo *key_part, const unsigned char *key, uint32_t key_length)
bool key_cmp_if_same(Table *table, const unsigned char *key, uint32_t idx, uint32_t key_length)
STL namespace.