fb-cpp 0.0.2
A modern C++ wrapper for the Firebird database API
Loading...
Searching...
No Matches
Blob.cpp
1/*
2 * MIT License
3 *
4 * Copyright (c) 2025 Adriano dos Santos Fernandes
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to do so, subject to the
11 * following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25#include "Blob.h"
26#include "Attachment.h"
27#include "Client.h"
28#include "Transaction.h"
29#include "firebird/impl/inf_pub.h"
30#include <cstdint>
31#include <cstring>
32#include <limits>
33#include <vector>
34
35using namespace fbcpp;
36using namespace fbcpp::impl;
37
38Blob::Blob(Attachment& attachment, Transaction& transaction, const BlobOptions& options)
39 : attachment{attachment},
40 transaction{transaction},
41 statusWrapper{attachment.getClient()}
42{
43 assert(attachment.isValid());
44 assert(transaction.isValid());
45
46 const auto preparedBpb = prepareBpb(options);
47
48 handle.reset(attachment.getHandle()->createBlob(&statusWrapper, transaction.getHandle().get(), &id.id,
49 static_cast<unsigned>(preparedBpb.size()), preparedBpb.data()));
50}
51
52Blob::Blob(Attachment& attachment, Transaction& transaction, const BlobId& blobId, const BlobOptions& options)
53 : attachment{attachment},
54 transaction{transaction},
55 id{blobId},
56 statusWrapper{attachment.getClient()}
57{
58 assert(attachment.isValid());
59 assert(transaction.isValid());
60
61 const auto preparedBpb = prepareBpb(options);
62
63 handle.reset(attachment.getHandle()->openBlob(&statusWrapper, transaction.getHandle().get(), &id.id,
64 static_cast<unsigned>(preparedBpb.size()), preparedBpb.data()));
65}
66
67std::vector<std::uint8_t> Blob::prepareBpb(const BlobOptions& options)
68{
69 // IXpbBuilder::BPB only exists since Firebird 4, so the BPB is built by hand to work with Firebird 3 clients.
70
71 const auto& userBpb = options.getBpb();
72 std::vector<std::uint8_t> bpb(userBpb.begin(), userBpb.end());
73
74 const auto addInt = [&](std::uint8_t tag, int value)
75 {
76 if (bpb.empty())
77 bpb.push_back(isc_bpb_version1);
78
79 const auto unsignedValue = static_cast<unsigned>(value);
80
81 bpb.push_back(tag);
82 bpb.push_back(4u);
83
84 for (unsigned shift = 0u; shift < 32u; shift += 8u)
85 bpb.push_back(static_cast<std::uint8_t>((unsignedValue >> shift) & 0xFFu));
86 };
87
88 if (const auto type = options.getType(); type.has_value())
89 addInt(isc_bpb_type, static_cast<int>(type.value()));
90
91 if (const auto sourceType = options.getSourceType(); sourceType.has_value())
92 addInt(isc_bpb_source_type, static_cast<int>(sourceType.value()));
93
94 if (const auto targetType = options.getTargetType(); targetType.has_value())
95 addInt(isc_bpb_target_type, static_cast<int>(targetType.value()));
96
97 if (const auto sourceCharSet = options.getSourceCharSet(); sourceCharSet.has_value())
98 addInt(isc_bpb_source_interp, static_cast<int>(sourceCharSet.value()));
99
100 if (const auto targetCharSet = options.getTargetCharSet(); targetCharSet.has_value())
101 addInt(isc_bpb_target_interp, static_cast<int>(targetCharSet.value()));
102
103 if (const auto storage = options.getStorage(); storage.has_value())
104 addInt(isc_bpb_storage, static_cast<int>(storage.value()));
105
106 return bpb;
107}
108
110{
111 assert(isValid());
112
113 const std::uint8_t items[] = {isc_info_blob_total_length};
114 std::uint8_t buffer[16]{};
115
116 handle->getInfo(&statusWrapper, sizeof(items), items, sizeof(buffer), buffer);
117
118 const auto* ptr = buffer;
119 const auto* end = buffer + sizeof(buffer);
120
121 while (ptr < end)
122 {
123 const auto item = *ptr++;
124
125 if (item == isc_info_end)
126 break;
127
128 if (item == isc_info_truncated)
129 throw FbCppException("Blob::getLength truncated response");
130
131 if (item == isc_info_error)
132 throw FbCppException("Blob::getLength error response");
133
134 if (ptr + 2 > end)
135 throw FbCppException("Blob::getLength malformed response");
136
137 const auto itemLength = static_cast<std::uint16_t>((ptr[0]) | (ptr[1] << 8));
138 ptr += 2;
139
140 if (ptr + itemLength > end)
141 throw FbCppException("Blob::getLength invalid length");
142
143 if (item == isc_info_blob_total_length)
144 {
145 unsigned result = 0;
146
147 for (std::uint16_t i = 0; i < itemLength; ++i)
148 result |= static_cast<unsigned>(ptr[i]) << (8u * i);
149
150 return result;
151 }
152
153 ptr += itemLength;
154 }
155
156 throw FbCppException("Blob::getLength value not found");
157}
158
159unsigned Blob::read(std::span<std::byte> buffer)
160{
161 assert(isValid());
162
163 unsigned totalRead = 0;
164 const unsigned maxChunkSize = std::numeric_limits<std::uint16_t>::max();
165
166 while (!buffer.empty())
167 {
168 const auto chunkSize = buffer.size() < maxChunkSize ? buffer.size() : maxChunkSize;
169 const auto chunk = buffer.first(chunkSize);
170 const auto readNow = readSegment(chunk);
171
172 if (readNow == 0)
173 break;
174
175 totalRead += readNow;
176 buffer = buffer.subspan(readNow);
177 }
178
179 return totalRead;
180}
181
182unsigned Blob::readSegment(std::span<std::byte> buffer)
183{
184 assert(isValid());
185
186 if (buffer.empty())
187 return 0;
188
189 unsigned segmentLength = 0;
190 const auto result =
191 handle->getSegment(&statusWrapper, static_cast<unsigned>(buffer.size()), buffer.data(), &segmentLength);
192
193 switch (result)
194 {
195 case fb::IStatus::RESULT_OK:
196 case fb::IStatus::RESULT_SEGMENT:
197 return segmentLength;
198
199 case fb::IStatus::RESULT_NO_DATA:
200 return 0;
201
202 default:
203 return 0;
204 }
205}
206
207void Blob::write(std::span<const std::byte> buffer)
208{
209 assert(isValid());
210
211 const unsigned maxChunkSize = std::numeric_limits<std::uint16_t>::max();
212
213 while (!buffer.empty())
214 {
215 const auto chunkSize = buffer.size() < maxChunkSize ? buffer.size() : maxChunkSize;
216 const auto chunk = buffer.first(chunkSize);
217 writeSegment(chunk);
218 buffer = buffer.subspan(chunkSize);
219 }
220}
221
222void Blob::writeSegment(std::span<const std::byte> buffer)
223{
224 assert(isValid());
225
226 if (buffer.empty())
227 return;
228
229 if (buffer.size() > std::numeric_limits<unsigned>::max())
230 throw FbCppException("Segment too large");
231
232 handle->putSegment(&statusWrapper, static_cast<unsigned>(buffer.size()), buffer.data());
233}
234
235int Blob::seek(BlobSeekMode mode, int offset)
236{
237 assert(isValid());
238 return handle->seek(&statusWrapper, static_cast<int>(mode), offset);
239}
240
242{
243 assert(isValid());
244
245 handle->cancel(&statusWrapper);
246 handle.release();
247}
248
250{
251 assert(isValid());
252
253 handle->close(&statusWrapper);
254 handle.release();
255}
Represents a connection to a Firebird database.
Definition Attachment.h:220
FbRef< fb::IAttachment > getHandle() noexcept
Returns the internal Firebird IAttachment handle.
Definition Attachment.h:296
bool isValid() noexcept
Returns whether the Attachment object is valid.
Definition Attachment.h:280
Represents a Firebird blob identifier.
Definition Blob.h:53
Additional options used when creating or opening blobs.
Definition Blob.h:104
const std::optional< BlobType > getSourceType() const
Retrieves the source blob subtype.
Definition Blob.h:152
const std::optional< BlobType > getType() const
Retrieves the blob type to be used for blob operations.
Definition Blob.h:135
const std::optional< BlobType > getTargetType() const
Retrieves the target blob subtype.
Definition Blob.h:169
const std::optional< BlobStorage > getStorage() const
Retrieves the blob storage mode.
Definition Blob.h:220
const std::vector< std::uint8_t > & getBpb() const noexcept
Retrieves the blob parameter block (BPB) used during blob operations.
Definition Blob.h:109
const std::optional< std::int16_t > getTargetCharSet() const
Retrieves the target character set identifier.
Definition Blob.h:203
const std::optional< std::int16_t > getSourceCharSet() const
Retrieves the source character set identifier.
Definition Blob.h:186
bool isValid() const noexcept
Returns whether the blob handle is valid.
Definition Blob.h:330
unsigned read(std::span< std::byte > buffer)
Reads data from the blob into the provided buffer.
Definition Blob.cpp:159
unsigned getLength()
Retrieves the length of the blob in bytes.
Definition Blob.cpp:109
void cancel()
Cancels any changes performed on the blob and releases the handle.
Definition Blob.cpp:241
void write(std::span< const std::byte > buffer)
Writes data from the buffer into the blob.
Definition Blob.cpp:207
int seek(BlobSeekMode mode, int offset)
Repositions the blob read/write cursor.
Definition Blob.cpp:235
unsigned readSegment(std::span< std::byte > buffer)
Reads a single segment from the blob into the provided buffer.
Definition Blob.cpp:182
Blob(Attachment &attachment, Transaction &transaction, const BlobOptions &options={})
Creates and opens a new blob for writing.
Definition Blob.cpp:38
void writeSegment(std::span< const std::byte > buffer)
Writes a single segment from the buffer into the blob.
Definition Blob.cpp:222
void close()
Closes the blob and finalizes any pending changes.
Definition Blob.cpp:249
Base exception class for all fb-cpp exceptions.
Definition Exception.h:231
T * release() noexcept
Relinquishes ownership of the pointer without releasing it and returns it.
Definition SmartPtrs.h:130
Represents a transaction in one or more Firebird databases.
bool isValid() noexcept
Returns whether the Transaction object is valid.
FbRef< fb::ITransaction > getHandle() noexcept
Returns the internal Firebird ITransaction handle.
fb-cpp namespace.
Definition Array.h:43
BlobSeekMode
Defines the origin used when repositioning a blob.
Definition Blob.h:248