sqldk-relpipe convergence: integer type (relpipe already support signed integers)
3 * Copyright © 2013 František Kučera (frantovo.cz)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 3 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package info.globalcode.sql.dk.formatting;
19 import info.globalcode.sql.dk.Parameter;
20 import info.globalcode.sql.dk.Xmlns;
21 import info.globalcode.sql.dk.configuration.DatabaseDefinition;
22 import static info.globalcode.sql.dk.Functions.notNull;
23 import info.globalcode.sql.dk.NamedParameter;
24 import info.globalcode.sql.dk.configuration.PropertyDeclaration;
25 import java.sql.Array;
26 import java.sql.ResultSet;
27 import java.sql.SQLException;
28 import java.sql.SQLXML;
29 import java.sql.Types;
30 import java.util.ArrayList;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.LinkedHashMap;
34 import java.util.List;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
38 import javax.xml.namespace.QName;
42 * Prints machine-readable output – XML document containing resultsets and updates count. Good
43 * choice for further processing – e.g. XSL transformation.</p>
46 * XML format is defined in the <a href="https://relational-pipes.globalcode.info/">Relational
47 * pipes</a> specification.
50 * @author Ing. František Kučera (frantovo.cz)
52 @PropertyDeclaration(name = XmlFormatter.PROPERTY_LABELED_COLUMNS, defaultValue = "false", type = Boolean.class, description = "whether to add 'label' attribute to each 'column' element")
53 public class XmlFormatter extends AbstractXmlFormatter {
55 private static final String XML_ELEMENT_RELATION = "relation";
56 private static final String XML_ELEMENT_NAME = "name";
57 private static final String XML_ELEMENT_RECORD = "record";
58 private static final String XML_ELEMENT_ATTRIBUTE = "attribute";
59 private static final String XML_ATTRIBUTE_NAME = "name";
60 private static final String XML_ATTRIBUTE_TYPE = "type";
61 private static final String XML_ATTRIBUTE_STATEMENT = "statement";
62 private static final String XML_NS_PREFIX_SQLDK = "sql-dk";
64 private static final String RELPIPE_TYPE_BOOLEAN = "boolean";
65 private static final String RELPIPE_TYPE_INTEGER = "integer";
66 private static final String RELPIPE_TYPE_STRING = "string";
67 private static final Map<Integer, String> RELPIPE_TYPES;
70 Map<Integer, String> m = new HashMap<>();
71 m.put(Types.BOOLEAN, RELPIPE_TYPE_BOOLEAN);
72 m.put(Types.BIT, RELPIPE_TYPE_BOOLEAN); // TODO: relpipe "boolean" can not be null in the current version
73 m.put(Types.INTEGER, RELPIPE_TYPE_INTEGER);
74 // TODO: add more types when supported in Relational pipes
75 m.put(Types.CHAR, RELPIPE_TYPE_STRING);
76 m.put(Types.VARCHAR, RELPIPE_TYPE_STRING);
77 RELPIPE_TYPES = Collections.unmodifiableMap(m);
80 public static final String NAME = "xml"; // bash-completion:formatter
81 public static final String PROPERTY_LABELED_COLUMNS = "labeledColumns";
82 private static final Logger log = Logger.getLogger(XmlFormatter.class.getName());
83 private final boolean labeledColumns;
85 private String currentDatabaseName;
86 private int statementCounter;
89 public XmlFormatter(FormatterContext formatterContext) {
90 super(formatterContext);
91 labeledColumns = formatterContext.getProperties().getBoolean(PROPERTY_LABELED_COLUMNS, false);
94 private QName qname(String localPart) {
95 return new QName(Xmlns.RELPIPE, localPart);
98 private QName qnameDK(String localPart) {
99 return new QName(Xmlns.SQLDK, localPart, XML_NS_PREFIX_SQLDK);
103 public void writeStartBatch() {
104 super.writeStartBatch();
105 printStartDocument();
106 Map<QName, String> attributes = new LinkedHashMap<>(2);
107 attributes.put(qname("xmlns"), Xmlns.RELPIPE);
108 attributes.put(new QName(null, XML_NS_PREFIX_SQLDK, "xmlns"), Xmlns.SQLDK);
109 printStartElement(qname("relpipe"), attributes);
110 statementCounter = 0;
115 public void writeEndBatch() {
116 super.writeEndBatch();
122 public void writeStartDatabase(DatabaseDefinition databaseDefinition) {
123 super.writeStartDatabase(databaseDefinition);
124 currentDatabaseName = databaseDefinition.getName();
125 Map<QName, String> attributes = databaseDefinition.getName() == null ? null : singleAttribute(qname("name"), databaseDefinition.getName());
126 printEmptyElement(qnameDK("database-start"), attributes);
130 public void writeEndDatabase() {
131 super.writeEndDatabase();
132 Map<QName, String> attributes = currentDatabaseName == null ? null : singleAttribute(qname("name"), currentDatabaseName);
133 printEmptyElement(qnameDK("database-end"), attributes);
136 private String getCurrentStatementName() {
137 return "s" + statementCounter;
141 public void writeStartStatement() {
142 super.writeStartStatement();
144 printEmptyElement(qnameDK("statement-start"), singleAttribute(qname("id"), getCurrentStatementName()));
148 public void writeEndStatement() {
149 super.writeEndStatement();
150 printEmptyElement(qnameDK("statement-end"), singleAttribute(qname("id"), getCurrentStatementName()));
154 public void writeQuery(String sql) {
155 super.writeQuery(sql);
156 printTextElement(qnameDK("sql"), singleAttribute(qname(XML_ATTRIBUTE_STATEMENT), getCurrentStatementName()), sql);
160 public void writeParameters(List<? extends Parameter> parameters) {
161 super.writeParameters(parameters);
163 if (parameters != null && parameters.size() > 0) {
165 printStartElement(qnameDK("parameters"), singleAttribute(qname(XML_ATTRIBUTE_STATEMENT), getCurrentStatementName()));
167 for (Parameter p : notNull(parameters)) {
169 Map<QName, String> attributes = new LinkedHashMap<>(2);
170 if (p instanceof NamedParameter) {
171 attributes.put(qname(XML_ATTRIBUTE_NAME), ((NamedParameter) p).getName());
173 attributes.put(qname(XML_ATTRIBUTE_TYPE), p.getType().name());
175 printTextElement(qnameDK("parameter"), attributes, String.valueOf(p.getValue()));
185 public void writeStartResultSet(ColumnsHeader header) {
186 super.writeStartResultSet(header);
187 printStartElement(qname(XML_ELEMENT_RELATION), singleAttribute(qnameDK(XML_ATTRIBUTE_STATEMENT), getCurrentStatementName()));
188 printTextElement(qname(XML_ELEMENT_NAME), null, getCurrentRelationName());
190 printStartElement(qname("attributes-metadata"));
191 for (ColumnDescriptor cd : header.getColumnDescriptors()) {
192 Map<QName, String> attributes = new LinkedHashMap<>(6);
194 attributes.put(qname(XML_ATTRIBUTE_NAME), cd.getLabel());
195 attributes.put(qname(XML_ATTRIBUTE_TYPE), toRelpipeType(cd.getType()));
197 attributes.put(qnameDK("tableName"), cd.getTableName());
198 attributes.put(qnameDK("columnName"), cd.getName());
199 attributes.put(qnameDK("jdbcTypeName"), cd.getTypeName());
200 attributes.put(qnameDK("jdbcType"), String.valueOf(cd.getType()));
202 printEmptyElement(qname("attribute-metadata"), attributes);
208 * @param jdbcType value from {@linkplain Types}
211 private String toRelpipeType(int jdbcType) {
212 return RELPIPE_TYPES.getOrDefault(jdbcType, RELPIPE_TYPE_STRING);
216 public void writeEndResultSet() {
217 super.writeEndResultSet();
222 public void writeStartRow() {
223 super.writeStartRow();
224 printStartElement(qname(XML_ELEMENT_RECORD));
228 public void writeColumnValue(Object value) {
229 super.writeColumnValue(value);
231 Map<QName, String> attributes = null;
232 if (labeledColumns) {
233 attributes = new LinkedHashMap<>(2);
234 attributes.put(qname(XML_ATTRIBUTE_NAME), getCurrentColumnsHeader().getColumnDescriptors().get(getCurrentColumnsCount() - 1).getLabel());
235 attributes.put(qname(XML_ATTRIBUTE_TYPE), toRelpipeType(getCurrentColumnsHeader().getColumnDescriptors().get(getCurrentColumnsCount() - 1).getType()));
239 if (attributes == null) {
240 attributes = new LinkedHashMap<>(2);
242 // TODO: synchronize syntax with Relational pipes (after adding support of null values)
243 attributes.put(qnameDK("null"), "true");
244 printEmptyElement(qname(XML_ELEMENT_ATTRIBUTE), attributes);
245 } else if (value instanceof Array) {
247 Array sqlArray = (Array) value;
249 Object[] array = (Object[]) sqlArray.getArray();
250 printStartElement(qname(XML_ELEMENT_ATTRIBUTE), attributes);
253 } catch (SQLException e) {
254 // FIXME: rewrite array formatting, remember array mode, don't try sqlArray.getArray() again and again if it has failed
255 log.log(Level.SEVERE, "Unable to format array", e);
257 ResultSet arrayResultSet = sqlArray.getResultSet();
258 //int columnCount = arrayResultSet.getMetaData().getColumnCount();
259 ArrayList<Object> arrayList = new ArrayList<>();
260 while (arrayResultSet.next()) {
261 arrayList.add(arrayResultSet.getObject(2));
262 // for (int i = 1; i <= columnCount; i++) {
263 // log.log(Level.INFO, "Array column {0} = {1}", new Object[]{i, arrayResultSet.getObject(i)});
267 printStartElement(qname(XML_ELEMENT_ATTRIBUTE), attributes);
268 // FIXME: instanceof SQLXML, see below
269 printArray(arrayList.toArray());
272 } catch (SQLException e2) {
273 // FIXME: fix logging, error recovery
274 log.log(Level.SEVERE, "Second level fuck up !!!", e2);
277 writeColumnValue(String.valueOf(value));
280 } else if (value instanceof SQLXML) { // FIXME: move to separate method, to AbstractFormatter?
281 SQLXML xml = (SQLXML) value;
282 // TODO: parse DOM/SAX and transplant XML, don't escape (optional)
284 printTextElement(qname(XML_ELEMENT_ATTRIBUTE), attributes, xml.getString());
285 } catch (SQLException e) {
286 log.log(Level.SEVERE, "Unable to format XML", e);
287 writeColumnValue(String.valueOf(value));
290 printTextElement(qname(XML_ELEMENT_ATTRIBUTE), attributes, toString(value));
294 private void printArray(Object[] array) {
295 // TODO: synchronize array syntax with Relational pipes
296 printStartElement(qnameDK("array"));
297 for (Object o : array) {
298 if (o instanceof Object[]) {
299 printStartElement(qnameDK("item"));
300 printArray((Object[]) o);
303 printTextElement(qnameDK("item"), null, String.valueOf(o));
310 public void writeEndRow() {
316 public void writeUpdatesResult(int updatedRowsCount) {
317 super.writeUpdatesResult(updatedRowsCount);
318 printTextElement(qnameDK("updatedRecords"), singleAttribute(qnameDK(XML_ATTRIBUTE_STATEMENT), getCurrentStatementName()), String.valueOf(updatedRowsCount));
321 protected String toString(Object value) {
322 return String.valueOf(value);