Debian Codegraph @

src/main/org/h2/value/ValueBlob.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.value;
7
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.Reader;
11 import java.nio.charset.StandardCharsets;
12
13 import org.h2.engine.CastDataProvider;
14 import org.h2.engine.Constants;
15 import org.h2.engine.SysProperties;
16 import org.h2.message.DbException;
17 import org.h2.store.DataHandler;
18 import org.h2.store.FileStore;
19 import org.h2.store.FileStoreOutputStream;
20 import org.h2.store.LobStorageInterface;
21 import org.h2.util.Bits;
22 import org.h2.util.IOUtils;
23 import org.h2.util.MathUtils;
24 import org.h2.util.StringUtils;
25 import org.h2.util.Utils;
26 import org.h2.value.lob.LobData;
27 import org.h2.value.lob.LobDataDatabase;
28 import org.h2.value.lob.LobDataFetchOnDemand;
29 import org.h2.value.lob.LobDataFile;
30 import org.h2.value.lob.LobDataInMemory;
31
32 /**
33 * Implementation of the BINARY LARGE OBJECT data type.
34 */
35 public final class ValueBlob extends ValueLob {
36
37 /**
38 * Creates a small BLOB value that can be stored in the row directly.
39 *
40 * @param data
41 * the data
42 * @return the BLOB
43 */
44 public static ValueBlob createSmall(byte[] data) {
45 return new ValueBlob(new LobDataInMemory(data), data.length);
46 }
47
48 /**
49 * Create a temporary BLOB value from a stream.
50 *
51 * @param in
52 * the input stream
53 * @param length
54 * the number of characters to read, or -1 for no limit
55 * @param handler
56 * the data handler
57 * @return the lob value
58 */
59 public static ValueBlob createTempBlob(InputStream in, long length, DataHandler handler) {
60 try {
61 long remaining = Long.MAX_VALUE;
62 if (length >= 0 && length < remaining) {
63 remaining = length;
64 }
65 int len = ValueLob.getBufferSize(handler, remaining);
66 byte[] buff;
67 if (len >= Integer.MAX_VALUE) {
68 buff = IOUtils.readBytesAndClose(in, -1);
69 len = buff.length;
70 } else {
71 buff = Utils.newBytes(len);
72 len = IOUtils.readFully(in, buff, len);
73 }
74 if (len <= handler.getMaxLengthInplaceLob()) {
75 return ValueBlob.createSmall(Utils.copyBytes(buff, len));
76 }
77 return createTemporary(handler, buff, len, in, remaining);
78 } catch (IOException e) {
79 throw DbException.convertIOException(e, null);
80 }
81 }
82
83 /**
84 * Create a BLOB in a temporary file.
85 */
86 private static ValueBlob createTemporary(DataHandler handler, byte[] buff, int len, InputStream in, long remaining)
87 throws IOException {
88 String fileName = ValueLob.createTempLobFileName(handler);
89 FileStore tempFile = handler.openFile(fileName, "rw", false);
90 tempFile.autoDelete();
91 long tmpPrecision = 0;
92 try (FileStoreOutputStream out = new FileStoreOutputStream(tempFile, null)) {
93 while (true) {
94 tmpPrecision += len;
95 out.write(buff, 0, len);
96 remaining -= len;
97 if (remaining <= 0) {
98 break;
99 }
100 len = ValueLob.getBufferSize(handler, remaining);
101 len = IOUtils.readFully(in, buff, len);
102 if (len <= 0) {
103 break;
104 }
105 }
106 }
107 return new ValueBlob(new LobDataFile(handler, fileName, tempFile), tmpPrecision);
108 }
109
110 public ValueBlob(LobData lobData, long octetLength) {
111 super(lobData, octetLength, -1L);
112 }
113
114 @Override
115 public int getValueType() {
116 return BLOB;
117 }
118
119 @Override
120 public String getString() {
121 long p = charLength;
122 if (p >= 0L) {
123 if (p > Constants.MAX_STRING_LENGTH) {
124 throw getStringTooLong(p);
125 }
126 return readString((int) p);
127 }
128 // 1 Java character may be encoded with up to 3 bytes
129 if (octetLength > Constants.MAX_STRING_LENGTH * 3L) {
130 throw getStringTooLong(charLength());
131 }
132 String s;
133 if (lobData instanceof LobDataInMemory) {
134 s = new String(((LobDataInMemory) lobData).getSmall(), StandardCharsets.UTF_8);
135 } else {
136 s = readString(Integer.MAX_VALUE);
137 }
138 charLength = p = s.length();
139 if (p > Constants.MAX_STRING_LENGTH) {
140 throw getStringTooLong(p);
141 }
142 return s;
143 }
144
145 @Override
146 byte[] getBytesInternal() {
147 if (octetLength > Constants.MAX_STRING_LENGTH) {
148 throw getBinaryTooLong(octetLength);
149 }
150 return readBytes((int) octetLength);
151 }
152
153 @Override
154 public InputStream getInputStream() {
155 return lobData.getInputStream(octetLength);
156 }
157
158 @Override
159 public InputStream getInputStream(long oneBasedOffset, long length) {
160 long p = octetLength;
161 return rangeInputStream(lobData.getInputStream(p), oneBasedOffset, length, p);
162 }
163
164 @Override
165 public Reader getReader(long oneBasedOffset, long length) {
166 return rangeReader(getReader(), oneBasedOffset, length, -1L);
167 }
168
169 @Override
170 public int compareTypeSafe(Value v, CompareMode mode, CastDataProvider provider) {
171 if (v == this) {
172 return 0;
173 }
174 ValueBlob v2 = (ValueBlob) v;
175 LobData lobData = this.lobData, lobData2 = v2.lobData;
176 if (lobData.getClass() == lobData2.getClass()) {
177 if (lobData instanceof LobDataInMemory) {
178 return Bits.compareNotNullUnsigned(((LobDataInMemory) lobData).getSmall(),
179 ((LobDataInMemory) lobData2).getSmall());
180 } else if (lobData instanceof LobDataDatabase) {
181 if (((LobDataDatabase) lobData).getLobId() == ((LobDataDatabase) lobData2).getLobId()) {
182 return 0;
183 }
184 } else if (lobData instanceof LobDataFetchOnDemand) {
185 if (((LobDataFetchOnDemand) lobData).getLobId() == ((LobDataFetchOnDemand) lobData2).getLobId()) {
186 return 0;
187 }
188 }
189 }
190 return compare(this, v2);
191 }
192
193 /**
194 * Compares two BLOB values directly.
195 *
196 * @param v1
197 * first BLOB value
198 * @param v2
199 * second BLOB value
200 * @return result of comparison
201 */
202 private static int compare(ValueBlob v1, ValueBlob v2) {
203 long minPrec = Math.min(v1.octetLength, v2.octetLength);
204 try (InputStream is1 = v1.getInputStream(); InputStream is2 = v2.getInputStream()) {
205 byte[] buf1 = new byte[BLOCK_COMPARISON_SIZE];
206 byte[] buf2 = new byte[BLOCK_COMPARISON_SIZE];
207 for (; minPrec >= BLOCK_COMPARISON_SIZE; minPrec -= BLOCK_COMPARISON_SIZE) {
208 if (IOUtils.readFully(is1, buf1, BLOCK_COMPARISON_SIZE) != BLOCK_COMPARISON_SIZE
209 || IOUtils.readFully(is2, buf2, BLOCK_COMPARISON_SIZE) != BLOCK_COMPARISON_SIZE) {
210 throw DbException.getUnsupportedException("Invalid LOB");
211 }
212 int cmp = Bits.compareNotNullUnsigned(buf1, buf2);
213 if (cmp != 0) {
214 return cmp;
215 }
216 }
217 for (;;) {
218 int c1 = is1.read(), c2 = is2.read();
219 if (c1 < 0) {
220 return c2 < 0 ? 0 : -1;
221 }
222 if (c2 < 0) {
223 return 1;
224 }
225 if (c1 != c2) {
226 return (c1 & 0xFF) < (c2 & 0xFF) ? -1 : 1;
227 }
228 }
229 } catch (IOException ex) {
230 throw DbException.convert(ex);
231 }
232 }
233
234 @Override
235 public StringBuilder getSQL(StringBuilder builder, int sqlFlags) {
236 if ((sqlFlags & REPLACE_LOBS_FOR_TRACE) != 0
237 && (!(lobData instanceof LobDataInMemory) || octetLength > SysProperties.MAX_TRACE_DATA_LENGTH)) {
238 builder.append("CAST(REPEAT(CHAR(0), ").append(octetLength).append(") AS BINARY VARYING");
239 formatLobDataComment(builder);
240 } else {
241 if ((sqlFlags & (REPLACE_LOBS_FOR_TRACE | NO_CASTS)) == 0) {
242 builder.append("CAST(X'");
243 StringUtils.convertBytesToHex(builder, getBytesNoCopy()).append("' AS BINARY LARGE OBJECT(")
244 .append(octetLength).append("))");
245 } else {
246 builder.append("X'");
247 StringUtils.convertBytesToHex(builder, getBytesNoCopy()).append('\'');
248 }
249 }
250 return builder;
251 }
252
253 /**
254 * Convert the precision to the requested value.
255 *
256 * @param precision
257 * the new precision
258 * @return the truncated or this value
259 */
260 ValueBlob convertPrecision(long precision) {
261 if (this.octetLength <= precision) {
262 return this;
263 }
264 ValueBlob lob;
265 DataHandler handler = lobData.getDataHandler();
266 if (handler != null) {
267 lob = createTempBlob(getInputStream(), precision, handler);
268 } else {
269 try {
270 lob = createSmall(IOUtils.readBytesAndClose(getInputStream(), MathUtils.convertLongToInt(precision)));
271 } catch (IOException e) {
272 throw DbException.convertIOException(e, null);
273 }
274 }
275 return lob;
276 }
277
278 @Override
279 public ValueLob copy(DataHandler database, int tableId) {
280 if (lobData instanceof LobDataInMemory) {
281 byte[] small = ((LobDataInMemory) lobData).getSmall();
282 if (small.length > database.getMaxLengthInplaceLob()) {
283 LobStorageInterface s = database.getLobStorage();
284 ValueBlob v = s.createBlob(getInputStream(), octetLength);
285 ValueLob v2 = v.copy(database, tableId);
286 v.remove();
287 return v2;
288 }
289 return this;
290 } else if (lobData instanceof LobDataDatabase) {
291 return database.getLobStorage().copyLob(this, tableId);
292 } else {
293 throw new UnsupportedOperationException();
294 }
295 }
296
297 @Override
298 public long charLength() {
299 long p = charLength;
300 if (p < 0L) {
301 if (lobData instanceof LobDataInMemory) {
302 p = new String(((LobDataInMemory) lobData).getSmall(), StandardCharsets.UTF_8).length();
303 } else {
304 try (Reader r = getReader()) {
305 p = 0L;
306 for (;;) {
307 p += r.skip(Long.MAX_VALUE);
308 if (r.read() < 0) {
309 break;
310 }
311 p++;
312 }
313 } catch (IOException e) {
314 throw DbException.convertIOException(e, null);
315 }
316 }
317 charLength = p;
318 }
319 return p;
320 }
321
322 @Override
323 public long octetLength() {
324 return octetLength;
325 }
326
327 }