01: /*
02: * PostgresBlobFormatter.java
03: *
04: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
05: *
06: * Copyright 2002-2008, Thomas Kellerer
07: * No part of this code maybe reused without the permission of the author
08: *
09: * To contact the author please send an email to: support@sql-workbench.net
10: *
11: */
12: package workbench.storage;
13:
14: import java.sql.SQLException;
15:
16: /**
17: * A class to format a byte[] array to be used as a literal in a SQL
18: * statement for Postgres.
19: *
20: * PG accepts binary contents as octal Strings, e.g.
21: * \001\002\004
22: *
23: * See also: http://www.postgresql.org/docs/8.2/static/datatype-binary.html
24: *
25: * @author support@sql-workbench.net
26: */
27: public class PostgresBlobFormatter implements BlobLiteralFormatter {
28:
29: public PostgresBlobFormatter() {
30: }
31:
32: public CharSequence getBlobLiteral(Object value)
33: throws SQLException {
34: if (value == null)
35: return null;
36: if (value instanceof byte[]) {
37: byte[] buffer = (byte[]) value;
38: StringBuilder result = new StringBuilder(
39: buffer.length * 4 + 2);
40: result.append('\'');
41: for (int i = 0; i < buffer.length; i++) {
42: result.append('\\');
43: result.append('\\');
44: int c = (buffer[i] < 0 ? 256 + buffer[i] : buffer[i]);
45: String s = Integer.toOctalString(c);
46: if (s.length() == 1) {
47: result.append('0');
48: result.append('0');
49: } else if (s.length() == 2) {
50: result.append('0');
51: }
52: result.append(s);
53: }
54: result.append('\'');
55: return result;
56: }
57: return value.toString();
58: }
59: }
|