1/* Copyright (c) 2000-2002, 2005-2007 MySQL AB
2 Use is subject to license terms
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; version 2 of the License.
7
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */
16
17#include "heapdef.h"
18
19 /* Read prev record for key */
20
21
22int heap_rprev(HP_INFO *info, uchar *record)
23{
24 uchar *pos;
25 HP_SHARE *share=info->s;
26 HP_KEYDEF *keyinfo;
27 DBUG_ENTER("heap_rprev");
28
29 if (info->lastinx < 0)
30 DBUG_RETURN(my_errno=HA_ERR_WRONG_INDEX);
31 keyinfo = share->keydef + info->lastinx;
32 if (keyinfo->algorithm == HA_KEY_ALG_BTREE)
33 {
34 heap_rb_param custom_arg;
35
36 /* If no active record and last was not deleted */
37 if (!(info->update & (HA_STATE_AKTIV | HA_STATE_NO_KEY |
38 HA_STATE_DELETED)))
39 {
40 if (info->update & HA_STATE_PREV_FOUND)
41 pos= 0; /* Can't search before first row */
42 else
43 {
44 /* Last was 'next' after last record; search after last record */
45 pos= tree_search_edge(&keyinfo->rb_tree, info->parents,
46 &info->last_pos, offsetof(TREE_ELEMENT, right));
47 }
48 }
49 else if (info->last_pos)
50 pos = tree_search_next(&keyinfo->rb_tree, &info->last_pos,
51 offsetof(TREE_ELEMENT, right),
52 offsetof(TREE_ELEMENT, left));
53 else
54 {
55 custom_arg.keyseg = keyinfo->seg;
56 custom_arg.key_length = keyinfo->length;
57 custom_arg.search_flag = SEARCH_SAME;
58 info->last_find_flag= HA_READ_KEY_OR_PREV;
59 pos = tree_search_key(&keyinfo->rb_tree, info->lastkey, info->parents,
60 &info->last_pos, info->last_find_flag, &custom_arg);
61 }
62 if (pos)
63 {
64 memcpy(&pos, pos + (*keyinfo->get_key_length)(keyinfo, pos),
65 sizeof(uchar*));
66 info->current_ptr = pos;
67 }
68 else
69 {
70 my_errno = HA_ERR_KEY_NOT_FOUND;
71 }
72 }
73 else
74 {
75 if (info->current_ptr || (info->update & HA_STATE_NEXT_FOUND))
76 {
77 if ((info->update & HA_STATE_DELETED))
78 pos= hp_search(info, share->keydef + info->lastinx, info->lastkey, 3);
79 else
80 pos= hp_search(info, share->keydef + info->lastinx, info->lastkey, 2);
81 }
82 else
83 {
84 pos=0; /* Read next after last */
85 my_errno=HA_ERR_KEY_NOT_FOUND;
86 }
87 }
88 if (!pos)
89 {
90 info->update=HA_STATE_PREV_FOUND; /* For heap_rprev */
91 if (my_errno == HA_ERR_KEY_NOT_FOUND)
92 my_errno=HA_ERR_END_OF_FILE;
93 DBUG_RETURN(my_errno);
94 }
95 memcpy(record,pos,(size_t) share->reclength);
96 info->update=HA_STATE_AKTIV | HA_STATE_PREV_FOUND;
97 DBUG_RETURN(0);
98}
99