forked from stellar/stellar-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLedgerTxnDataSQL.cpp
492 lines (441 loc) · 15.9 KB
/
LedgerTxnDataSQL.cpp
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// Copyright 2018 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "crypto/KeyUtils.h"
#include "crypto/SecretKey.h"
#include "database/Database.h"
#include "database/DatabaseTypeSpecificOperation.h"
#include "ledger/LedgerTxnImpl.h"
#include "util/Decoder.h"
#include "util/Logging.h"
#include "util/types.h"
namespace stellar
{
std::shared_ptr<LedgerEntry const>
LedgerTxnRoot::Impl::loadData(LedgerKey const& key) const
{
std::string actIDStrKey = KeyUtils::toStrKey(key.data().accountID);
std::string dataName = decoder::encode_b64(key.data().dataName);
std::string dataValue;
soci::indicator dataValueIndicator;
LedgerEntry le;
le.data.type(DATA);
DataEntry& de = le.data.data();
std::string sql = "SELECT datavalue, lastmodified "
"FROM accountdata "
"WHERE accountid= :id AND dataname= :dataname";
auto prep = mDatabase.getPreparedStatement(sql);
auto& st = prep.statement();
st.exchange(soci::into(dataValue, dataValueIndicator));
st.exchange(soci::into(le.lastModifiedLedgerSeq));
st.exchange(soci::use(actIDStrKey));
st.exchange(soci::use(dataName));
st.define_and_bind();
st.execute(true);
if (!st.got_data())
{
return nullptr;
}
de.accountID = key.data().accountID;
de.dataName = key.data().dataName;
if (dataValueIndicator != soci::i_ok)
{
throw std::runtime_error("bad database state");
}
decoder::decode_b64(dataValue, de.dataValue);
return std::make_shared<LedgerEntry const>(std::move(le));
}
class BulkUpsertDataOperation : public DatabaseTypeSpecificOperation<void>
{
Database& mDB;
std::vector<std::string> mAccountIDs;
std::vector<std::string> mDataNames;
std::vector<std::string> mDataValues;
std::vector<int32_t> mLastModifieds;
void
accumulateEntry(LedgerEntry const& entry)
{
assert(entry.data.type() == DATA);
DataEntry const& data = entry.data.data();
mAccountIDs.emplace_back(KeyUtils::toStrKey(data.accountID));
mDataNames.emplace_back(decoder::encode_b64(data.dataName));
mDataValues.emplace_back(decoder::encode_b64(data.dataValue));
mLastModifieds.emplace_back(
unsignedToSigned(entry.lastModifiedLedgerSeq));
}
public:
BulkUpsertDataOperation(Database& DB,
std::vector<LedgerEntry> const& entries)
: mDB(DB)
{
for (auto const& e : entries)
{
accumulateEntry(e);
}
}
BulkUpsertDataOperation(Database& DB,
std::vector<EntryIterator> const& entryIter)
: mDB(DB)
{
for (auto const& e : entryIter)
{
assert(e.entryExists());
accumulateEntry(e.entry());
}
}
void
doSociGenericOperation()
{
std::string sql = "INSERT INTO accountdata ( "
"accountid, dataname, datavalue, lastmodified "
") VALUES ( "
":id, :v1, :v2, :v3 "
") ON CONFLICT (accountid, dataname) DO UPDATE SET "
"datavalue = excluded.datavalue, "
"lastmodified = excluded.lastmodified ";
auto prep = mDB.getPreparedStatement(sql);
soci::statement& st = prep.statement();
st.exchange(soci::use(mAccountIDs));
st.exchange(soci::use(mDataNames));
st.exchange(soci::use(mDataValues));
st.exchange(soci::use(mLastModifieds));
st.define_and_bind();
{
auto timer = mDB.getUpsertTimer("data");
st.execute(true);
}
if (static_cast<size_t>(st.get_affected_rows()) != mAccountIDs.size())
{
throw std::runtime_error("Could not update data in SQL");
}
}
void
doSqliteSpecificOperation(soci::sqlite3_session_backend* sq) override
{
doSociGenericOperation();
}
#ifdef USE_POSTGRES
void
doPostgresSpecificOperation(soci::postgresql_session_backend* pg) override
{
std::string strAccountIDs, strDataNames, strDataValues,
strLastModifieds;
PGconn* conn = pg->conn_;
marshalToPGArray(conn, strAccountIDs, mAccountIDs);
marshalToPGArray(conn, strDataNames, mDataNames);
marshalToPGArray(conn, strDataValues, mDataValues);
marshalToPGArray(conn, strLastModifieds, mLastModifieds);
std::string sql = "WITH r AS (SELECT "
"unnest(:ids::TEXT[]), "
"unnest(:v1::TEXT[]), "
"unnest(:v2::TEXT[]), "
"unnest(:v3::INT[]) "
")"
"INSERT INTO accountdata ( "
"accountid, dataname, datavalue, lastmodified "
") SELECT * FROM r "
"ON CONFLICT (accountid, dataname) DO UPDATE SET "
"datavalue = excluded.datavalue, "
"lastmodified = excluded.lastmodified ";
auto prep = mDB.getPreparedStatement(sql);
soci::statement& st = prep.statement();
st.exchange(soci::use(strAccountIDs));
st.exchange(soci::use(strDataNames));
st.exchange(soci::use(strDataValues));
st.exchange(soci::use(strLastModifieds));
st.define_and_bind();
{
auto timer = mDB.getUpsertTimer("data");
st.execute(true);
}
if (static_cast<size_t>(st.get_affected_rows()) != mAccountIDs.size())
{
throw std::runtime_error("Could not update data in SQL");
}
}
#endif
};
class BulkDeleteDataOperation : public DatabaseTypeSpecificOperation<void>
{
Database& mDB;
LedgerTxnConsistency mCons;
std::vector<std::string> mAccountIDs;
std::vector<std::string> mDataNames;
public:
BulkDeleteDataOperation(Database& DB, LedgerTxnConsistency cons,
std::vector<EntryIterator> const& entries)
: mDB(DB), mCons(cons)
{
for (auto const& e : entries)
{
assert(!e.entryExists());
assert(e.key().type() == DATA);
auto const& data = e.key().data();
mAccountIDs.emplace_back(KeyUtils::toStrKey(data.accountID));
mDataNames.emplace_back(decoder::encode_b64(data.dataName));
}
}
void
doSociGenericOperation()
{
std::string sql = "DELETE FROM accountdata WHERE accountid = :id AND "
" dataname = :v1 ";
auto prep = mDB.getPreparedStatement(sql);
soci::statement& st = prep.statement();
st.exchange(soci::use(mAccountIDs));
st.exchange(soci::use(mDataNames));
st.define_and_bind();
{
auto timer = mDB.getDeleteTimer("data");
st.execute(true);
}
if (static_cast<size_t>(st.get_affected_rows()) != mAccountIDs.size() &&
mCons == LedgerTxnConsistency::EXACT)
{
throw std::runtime_error("Could not update data in SQL");
}
}
void
doSqliteSpecificOperation(soci::sqlite3_session_backend* sq) override
{
doSociGenericOperation();
}
#ifdef USE_POSTGRES
void
doPostgresSpecificOperation(soci::postgresql_session_backend* pg) override
{
std::string strAccountIDs;
std::string strDataNames;
PGconn* conn = pg->conn_;
marshalToPGArray(conn, strAccountIDs, mAccountIDs);
marshalToPGArray(conn, strDataNames, mDataNames);
std::string sql =
"WITH r AS ( SELECT "
"unnest(:ids::TEXT[]),"
"unnest(:v1::TEXT[])"
" ) "
"DELETE FROM accountdata WHERE (accountid, dataname) IN "
"(SELECT * FROM r)";
auto prep = mDB.getPreparedStatement(sql);
soci::statement& st = prep.statement();
st.exchange(soci::use(strAccountIDs));
st.exchange(soci::use(strDataNames));
st.define_and_bind();
{
auto timer = mDB.getDeleteTimer("data");
st.execute(true);
}
if (static_cast<size_t>(st.get_affected_rows()) != mAccountIDs.size() &&
mCons == LedgerTxnConsistency::EXACT)
{
throw std::runtime_error("Could not update data in SQL");
}
}
#endif
};
void
LedgerTxnRoot::Impl::bulkUpsertAccountData(
std::vector<EntryIterator> const& entries)
{
BulkUpsertDataOperation op(mDatabase, entries);
mDatabase.doDatabaseTypeSpecificOperation(op);
}
void
LedgerTxnRoot::Impl::bulkDeleteAccountData(
std::vector<EntryIterator> const& entries, LedgerTxnConsistency cons)
{
BulkDeleteDataOperation op(mDatabase, cons, entries);
mDatabase.doDatabaseTypeSpecificOperation(op);
}
void
LedgerTxnRoot::Impl::dropData()
{
throwIfChild();
mEntryCache.clear();
mBestOffersCache.clear();
mDatabase.getSession() << "DROP TABLE IF EXISTS accountdata;";
mDatabase.getSession() << "CREATE TABLE accountdata"
"("
"accountid VARCHAR(56) NOT NULL,"
"dataname VARCHAR(64) NOT NULL,"
"datavalue VARCHAR(112) NOT NULL,"
"lastmodified INT NOT NULL,"
"PRIMARY KEY (accountid, dataname)"
");";
}
static std::vector<LedgerEntry>
loadDataToEncode(Database& db)
{
std::string accountID, dataName, dataValue;
uint32_t lastModified;
std::string sql = "SELECT accountid, dataname, datavalue, lastmodified "
"FROM accountdata";
auto prep = db.getPreparedStatement(sql);
auto& st = prep.statement();
st.exchange(soci::into(accountID));
st.exchange(soci::into(dataName));
st.exchange(soci::into(dataValue));
st.exchange(soci::into(lastModified));
st.define_and_bind();
st.execute(true);
std::vector<LedgerEntry> res;
while (st.got_data())
{
res.emplace_back();
auto& le = res.back();
le.data.type(DATA);
auto& de = le.data.data();
de.accountID = KeyUtils::fromStrKey<PublicKey>(accountID);
de.dataName = dataName;
decoder::decode_b64(dataValue, de.dataValue);
le.lastModifiedLedgerSeq = lastModified;
st.fetch();
}
return res;
}
void
LedgerTxnRoot::Impl::encodeDataNamesBase64()
{
throwIfChild();
mEntryCache.clear();
mBestOffersCache.clear();
CLOG(INFO, "Ledger")
<< "Loading all data entries from the accountdata table";
auto dataToEncode = loadDataToEncode(mDatabase);
// Note: The table must be recreated since dataname is part of the primary
// key, so there could be a collision when updating it
dropData();
if (!mDatabase.isSqlite())
{
auto& session = mDatabase.getSession();
session << "ALTER TABLE accountdata ALTER COLUMN dataname "
"SET DATA TYPE VARCHAR(88)";
}
if (!dataToEncode.empty())
{
BulkUpsertDataOperation op(mDatabase, dataToEncode);
mDatabase.doDatabaseTypeSpecificOperation(op);
CLOG(INFO, "Ledger")
<< "Wrote " << dataToEncode.size() << " data entries";
}
}
class BulkLoadDataOperation
: public DatabaseTypeSpecificOperation<std::vector<LedgerEntry>>
{
Database& mDb;
std::vector<std::string> mAccountIDs;
std::vector<std::string> mDataNames;
std::vector<LedgerEntry>
executeAndFetch(soci::statement& st)
{
std::string accountID, dataName, dataValue;
uint32_t lastModified;
st.exchange(soci::into(accountID));
st.exchange(soci::into(dataName));
st.exchange(soci::into(dataValue));
st.exchange(soci::into(lastModified));
st.define_and_bind();
{
auto timer = mDb.getSelectTimer("data");
st.execute(true);
}
std::vector<LedgerEntry> res;
while (st.got_data())
{
res.emplace_back();
auto& le = res.back();
le.data.type(DATA);
auto& de = le.data.data();
de.accountID = KeyUtils::fromStrKey<PublicKey>(accountID);
decoder::decode_b64(dataName, de.dataName);
decoder::decode_b64(dataValue, de.dataValue);
le.lastModifiedLedgerSeq = lastModified;
st.fetch();
}
return res;
}
public:
BulkLoadDataOperation(Database& db,
std::unordered_set<LedgerKey> const& keys)
: mDb(db)
{
mAccountIDs.reserve(keys.size());
mDataNames.reserve(keys.size());
for (auto const& k : keys)
{
assert(k.type() == DATA);
mAccountIDs.emplace_back(KeyUtils::toStrKey(k.data().accountID));
mDataNames.emplace_back(decoder::encode_b64(k.data().dataName));
}
}
virtual std::vector<LedgerEntry>
doSqliteSpecificOperation(soci::sqlite3_session_backend* sq) override
{
assert(mAccountIDs.size() == mDataNames.size());
std::vector<char const*> cstrAccountIDs;
std::vector<char const*> cstrDataNames;
cstrAccountIDs.reserve(mAccountIDs.size());
cstrDataNames.reserve(mDataNames.size());
for (size_t i = 0; i < mAccountIDs.size(); ++i)
{
cstrAccountIDs.emplace_back(mAccountIDs[i].c_str());
cstrDataNames.emplace_back(mDataNames[i].c_str());
}
std::string sqlJoin =
"SELECT x.value, y.value FROM "
"(SELECT rowid, value FROM carray(?, ?, 'char*') ORDER BY rowid) "
"AS x "
"INNER JOIN (SELECT rowid, value FROM carray(?, ?, 'char*') ORDER "
"BY rowid) AS y ON x.rowid = y.rowid";
std::string sql =
"WITH r AS (" + sqlJoin +
") SELECT accountid, dataname, datavalue, lastmodified "
"FROM accountdata WHERE (accountid, dataname) IN r";
auto prep = mDb.getPreparedStatement(sql);
auto sqliteStatement = dynamic_cast<soci::sqlite3_statement_backend*>(
prep.statement().get_backend());
auto st = sqliteStatement->stmt_;
sqlite3_reset(st);
sqlite3_bind_pointer(st, 1, cstrAccountIDs.data(), "carray", 0);
sqlite3_bind_int(st, 2, static_cast<int>(cstrAccountIDs.size()));
sqlite3_bind_pointer(st, 3, cstrDataNames.data(), "carray", 0);
sqlite3_bind_int(st, 4, static_cast<int>(cstrDataNames.size()));
return executeAndFetch(prep.statement());
}
#ifdef USE_POSTGRES
std::vector<LedgerEntry>
doPostgresSpecificOperation(soci::postgresql_session_backend* pg) override
{
assert(mAccountIDs.size() == mDataNames.size());
std::string strAccountIDs;
std::string strDataNames;
marshalToPGArray(pg->conn_, strAccountIDs, mAccountIDs);
marshalToPGArray(pg->conn_, strDataNames, mDataNames);
std::string sql =
"WITH r AS (SELECT unnest(:v1::TEXT[]), unnest(:v2::TEXT[])) "
"SELECT accountid, dataname, datavalue, lastmodified "
"FROM accountdata WHERE (accountid, dataname) IN (SELECT * FROM r)";
auto prep = mDb.getPreparedStatement(sql);
auto& st = prep.statement();
st.exchange(soci::use(strAccountIDs));
st.exchange(soci::use(strDataNames));
return executeAndFetch(st);
}
#endif
};
std::unordered_map<LedgerKey, std::shared_ptr<LedgerEntry const>>
LedgerTxnRoot::Impl::bulkLoadData(
std::unordered_set<LedgerKey> const& keys) const
{
if (!keys.empty())
{
BulkLoadDataOperation op(mDatabase, keys);
return populateLoadedEntries(
keys, mDatabase.doDatabaseTypeSpecificOperation(op));
}
else
{
return {};
}
}
}