diff --git a/services/lib/src/DatabaseManagerBase.h b/services/lib/src/DatabaseManagerBase.h --- a/services/lib/src/DatabaseManagerBase.h +++ b/services/lib/src/DatabaseManagerBase.h @@ -25,6 +25,9 @@ innerFindItem(Aws::DynamoDB::Model::GetItemRequest &request); void innerRemoveItem(const Item &item); + void innerBatchWriteItem( + const std::string &tableName, + std::vector &writeRequests); }; template diff --git a/services/lib/src/DatabaseManagerBase.cpp b/services/lib/src/DatabaseManagerBase.cpp --- a/services/lib/src/DatabaseManagerBase.cpp +++ b/services/lib/src/DatabaseManagerBase.cpp @@ -3,6 +3,8 @@ #include "Item.h" #include +#include +#include #include #include @@ -42,6 +44,46 @@ } } +void DatabaseManagerBase::innerBatchWriteItem( + const std::string &tableName, + std::vector &writeRequests) { + Aws::DynamoDB::Model::BatchWriteItemOutcome outcome; + // We don't need to split write requests if the size is smaller or equal + // to MAX_DYNAMODB_BATCH_ITEMS + if (writeRequests.size() <= MAX_DYNAMODB_BATCH_ITEMS) { + Aws::DynamoDB::Model::BatchWriteItemRequest writeRequest; + writeRequest.AddRequestItems(tableName, writeRequests); + outcome = getDynamoDBClient()->BatchWriteItem(writeRequest); + if (!outcome.IsSuccess()) { + throw std::runtime_error(outcome.GetError().GetMessage()); + } + return; + } + // Split write requests to chunks by MAX_DYNAMODB_BATCH_ITEMS size and write + // them by batch + std::vector writeRequestsChunk; + std::vector::iterator chunkPositionStart, + chunkPositionEnd; + for (int i = 0; i < writeRequests.size(); i += MAX_DYNAMODB_BATCH_ITEMS) { + chunkPositionStart = writeRequests.begin() + i; + if ((i + MAX_DYNAMODB_BATCH_ITEMS) > writeRequests.size()) { + chunkPositionEnd = writeRequests.end(); + } else { + chunkPositionEnd = writeRequests.end() - + (writeRequests.size() - i - MAX_DYNAMODB_BATCH_ITEMS); + } + writeRequestsChunk = std::vector( + chunkPositionStart, chunkPositionEnd); + + Aws::DynamoDB::Model::BatchWriteItemRequest writeBatchRequest; + writeBatchRequest.AddRequestItems(tableName, writeRequestsChunk); + outcome = getDynamoDBClient()->BatchWriteItem(writeBatchRequest); + if (!outcome.IsSuccess()) { + throw std::runtime_error(outcome.GetError().GetMessage()); + } + } +} + } // namespace database } // namespace network } // namespace comm