Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#include "dgrid_config.h"
#include "dgrid_logger.h"
#include "dgridd_datastore_table.h"
#include "dgridd_datastore_table_index.h"
 
namespace DGrid {
 
// table row key
TableRowKeyItem::TableRowKeyItem(const TableRowKeyItem& o)
    :val(o.val), data_type(o.data_type), sort_order(o.sort_order)
{
}
 
TableRowKeyItem::TableRowKeyItem(const std::string& val, const FieldType data_type, const SortOrder sort_order)
    :val(val), data_type(data_type), sort_order(sort_order)
{
}
 
TableRowKeyItem::~TableRowKeyItem() {}
 
bool TableRowKeyItem::equal(const FieldType data_type, const std::string& a, const std::string& b)
{
    bool ret = false;
#warning TODO: упрощённая реализация, на P и N будет потеря точности и потенциальная ошибка сравнения 
    try {
        switch(data_type) {
            case FIELD_TYPE_INTEGER:
                ret = std::stoll(a) == std::stoll(b);
                break;
            case FIELD_TYPE_FLOAT:
                ret = std::stold(a) == std::stold(b);
                break;
            case FIELD_TYPE_NUMERIC:
            case FIELD_TYPE_PACKED:
                ret = std::stold(a) == std::stold(b);
                break;
            default:
                ret = a == b;
                break;
        }
    } catch (...) {
        writeLog(LOG_ERR, "Typed compare(equal) failed (%s) '%s' == '%s'", fieldType2string(data_type).c_str(), a.c_str(), b.c_str());
        ret = a == b;
    }
#ifdef TABLE_DEBUG
    writeLog(LOG_DEBUG, "equal (%s) '%s' == '%s' : %s", fieldType2string(data_type).c_str(), a.c_str(), b.c_str(), ret ? "true" : "false");
#endif
    return ret;
}
 
bool TableRowKeyItem::compare(const FieldType data_type, const std::string& a, const std::string& b)
{
    bool ret = false;
#warning TODO: упрощённая реализация, на P и N будет потеря точности и потенциальная ошибка сравнения 
    try {
        switch(data_type) {
            case FIELD_TYPE_INTEGER:
                ret = std::stoll(a) > std::stoll(b);
                break;
            case FIELD_TYPE_FLOAT:
                ret = std::stold(a) > std::stold(b);
                break;
            case FIELD_TYPE_NUMERIC:
            case FIELD_TYPE_PACKED:
                ret = std::stold(a) > std::stold(b);
                break;
            default:
                ret = a > b;
                break;
        }
    } catch (...) {
        writeLog(LOG_ERR, "Typed compare failed (%s) '%s' > '%s'", fieldType2string(data_type).c_str(), a.c_str(), b.c_str());
        ret = a > b;
    }
#ifdef TABLE_DEBUG
    writeLog(LOG_DEBUG, "compare (%s) '%s' > '%s' : %s", fieldType2string(data_type).c_str(), a.c_str(), b.c_str(), ret ? "true" : "false");
#endif
    return ret;
}
 
DataIndex::DataIndex(TableData* table, const TableKeyInfo& key_info) : table(table), key_info(key_info), valid(false) {}
DataIndex::~DataIndex() {}
bool DataIndex::isValid() { return valid; }
const std::string& DataIndex::name() const { return key_info.name; }
bool DataIndex::checkComponents(const std::vector<std::string>& components) const { return components == key_info.components; }
bool DataIndex::checkOrRebuild() { return valid || rebuild(); }
 
 
const std::string DataIndex_sorted::_type = "SORTED";
DataIndex_sorted::DataIndex_sorted(TableData* table, const TableKeyInfo& key_info) : DataIndex(table, key_info) {}
DataIndex_sorted::~DataIndex_sorted() {}
 
bool DataIndex_sorted::rebuild()
{
#warning TODO: unique sorted index support
    writeLog(LOG_DEBUG, "-- sorted index rebuild (%s)", key_info.name.c_str());
    if(!table) {
        writeLog(LOG_ERR, "null table pointer!");
        return false;
    }
    uint64_t data_cnt = table->rows_data.size();
    rows_index.resize(data_cnt);
    for(uint64_t i=0; i<data_cnt; i++) {
        TableRowData* row = table->rows_data[i].get();
        const TableRowKey& key = row->getKey(key_info.components);
        rows_index[i] = { key, i };
    }
    std::sort(rows_index.begin(), rows_index.end(), [](const sortedKeyItem& a, const sortedKeyItem& b) { return a.first < b.first; });
    valid = true;
    return valid;
}
 
void DataIndex_sorted::reset()
{
    writeLog(LOG_DEBUG, "-- sorted index reset (%s)", key_info.name.c_str());
    valid = false;
    rows_index.clear();
}
 
void DataIndex_sorted::removeRow(TableRowData* row)
{
    if(!valid) return;
}
 
bool DataIndex_sorted::search(const std::vector<std::string>& values, uint64_t& index)
{
    TableRowKey key;
    if(!checkOrRebuild())
        return false;
 
    return table->keyFromValues(key_info.components, values, key, false /* full key only */, true /* force componentes list */) &&
            bsearch(key, index);
}
 
bool DataIndex_sorted::bsearch(const TableRowKey& key, uint64_t& index)
{
    uint64_t l(0);
    uint64_t count = rows_index.size() - l;
    uint64_t step;
    while(count > 0) {
        step = count / 2;
        uint64_t mid = l + step;
#ifdef TABLE_DEBUG
        writeLog(LOG_DEBUG, "r comparing %lld", mid);
#endif
        if(key > rows_index[mid].first) {
            l = mid + 1;
            count -= step + 1;
        } else
            count = step;
    }
    index = l;
    return (l<rows_index.size() && key == rows_index[l].first);
}
 
const std::string DataIndex_hashed::_type = "HASHED";
DataIndex_hashed::DataIndex_hashed(TableData* table, const TableKeyInfo& key_info) : DataIndex(table, key_info) {}
DataIndex_hashed::~DataIndex_hashed() {}
 
bool DataIndex_hashed::rebuild()
{
    writeLog(LOG_DEBUG, "-- hashed index rebuild (%s)", key_info.name.c_str());
    if(!table) {
        writeLog(LOG_ERR, "%s: null table pointer!", __func__);
        return false;
    }
    uint64_t data_cnt = table->rows_data.size();
    for(uint64_t i=0; i<data_cnt; i++) {
        TableRowData* row = table->rows_data[i].get();
        if(row == nullptr)
            continue;
 
        const TableRowKey& key = row->getKey(key_info.components);
        if(rows_index.find(key) != rows_index.end()) {
            writeLog(LOG_WARNING, "%s: duplicated key found", __func__);
            return false;
        }
        rows_index.emplace(key, i);
    }
    valid = true;
    return valid;
}
 
void DataIndex_hashed::reset()
{
    writeLog(LOG_DEBUG, "-- hashed index reset (%s)", key_info.name.c_str());
    valid = false;
    rows_index.clear();
}
 
void DataIndex_hashed::removeRow(TableRowData* row)
{
    if(!valid) return;
    const TableRowKey& key = row->getKey(key_info.components);
    auto it = rows_index.find(key);
    if(it != rows_index.end())
        rows_index.erase(it);
}
 
bool DataIndex_hashed::search(const std::vector<std::string>& values, uint64_t& index)
{
    TableRowKey key;
    HashedRows::iterator it = rows_index.end();
    if(!checkOrRebuild())
        return false;
 
    if(table->keyFromValues(key_info.components, values, key, false /* full key only */, true /* force componentes list */)) {
        it = rows_index.find(key);
    }
    if(it != rows_index.end()) {
        index = it->second;
        return true;
    }
    return false;
}
 
} // namespace DGrid