com.databasesandlife.util.jooq.PostgresXmlDomElementBinding Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-common Show documentation
Show all versions of java-common Show documentation
Utility classes developed at Adrian Smith Software (A.S.S.)
The newest version!
package com.databasesandlife.util.jooq;
import com.databasesandlife.util.DomParser;
import com.databasesandlife.util.gwtsafe.ConfigurationException;
import org.jooq.*;
import org.jooq.conf.ParamType;
import org.jooq.impl.DSL;
import org.w3c.dom.Element;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Types;
import static com.databasesandlife.util.gwtsafe.ConfigurationException.prefixExceptionMessage;
/**
* Binding to allow PostgreSQL XML columns to be mapped to/from DOM {@link org.w3c.dom.Element} objects.
*/
public class PostgresXmlDomElementBinding
implements Binding {
@Override
public Converter converter() {
return new Converter<>() {
@Override public Class fromType() {
return XML.class;
}
@Override public Class toType() {
return Element.class;
}
@Override public Element from(XML db) {
try {
if (db == null || db.data().equals("null")) return null;
return DomParser.from(db.data());
}
catch (ConfigurationException e) {
throw new RuntimeException(prefixExceptionMessage("While parsing XML from DB '"+db.data()+"'", e));
}
}
@Override public XML to(Element java) {
if (java == null) return null;
return XML.valueOf(DomParser.formatXml(java));
}
};
}
@Override
public void sql(BindingSQLContext ctx) {
// Depending on how you generate your SQL, you may need to explicitly distinguish
// between jOOQ generating bind variables or inlined literals.
if (ctx.render().paramType() == ParamType.INLINED)
ctx.render().visit(DSL.inline(ctx.convert(converter()).value())).sql("::xml");
else
ctx.render().sql("?::xml");
}
@Override
public void register(BindingRegisterContext ctx) throws SQLException {
ctx.statement().registerOutParameter(ctx.index(), Types.VARCHAR);
}
@Override
public void set(BindingSetStatementContext ctx) throws SQLException {
var value = ctx.convert(converter()).value();
ctx.statement().setString(ctx.index(), value == null ? null : value.data());
}
@Override
public void get(BindingGetResultSetContext ctx) throws SQLException {
ctx.convert(converter()).value(XML.valueOf(ctx.resultSet().getString(ctx.index())));
}
@Override
public void get(BindingGetStatementContext ctx) throws SQLException {
ctx.convert(converter()).value(XML.valueOf(ctx.statement().getString(ctx.index())));
}
// The below methods aren't needed in PostgreSQL:
@Override
public void set(BindingSetSQLOutputContext ctx) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void get(BindingGetSQLInputContext ctx) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
}