diff -r 1336bb9a4499 -r d273d7c6dc0c java/sql-dk/src/info/globalcode/sql/dk/batch/BatchEncoder.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/java/sql-dk/src/info/globalcode/sql/dk/batch/BatchEncoder.java Wed Jan 08 14:33:51 2014 +0100 @@ -0,0 +1,81 @@ +/** + * SQL-DK + * Copyright © 2014 František Kučera (frantovo.cz) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package info.globalcode.sql.dk.batch; + +import info.globalcode.sql.dk.Parameter; +import info.globalcode.sql.dk.SQLCommand; +import info.globalcode.sql.dk.SQLCommandNamed; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import static info.globalcode.sql.dk.batch.BatchConstants.*; +import java.io.ByteArrayOutputStream; +import java.sql.SQLException; +import java.util.List; + +/** + * + * @author Ing. František Kučera (frantovo.cz) + */ +public class BatchEncoder { + + public int encode(SQLCommand sqlCommand, OutputStream out) throws BatchException { + try { + ByteArrayOutputStream bufferAOS = new ByteArrayOutputStream(); + DataOutputStream buffer = new DataOutputStream(bufferAOS); + + buffer.write(BATCH_START); + + byte[] sqlBytes = toBytes(sqlCommand.getQuery()); + buffer.writeInt(sqlBytes.length); + buffer.write(sqlBytes); + + if (sqlCommand instanceof SQLCommandNamed) { + sqlCommand = ((SQLCommandNamed) sqlCommand).getSQLCommandNumbered(); + } + + List parameters = sqlCommand.getParameters(); + + buffer.writeInt(parameters.size()); + + for (Parameter p : parameters) { + buffer.writeInt(p.getType().getCode()); + byte[] value = toBytes((String) p.getValue()); // parameters are encoded before any preprocessing + buffer.writeInt(value.length); + buffer.write(value); + } + + buffer.flush(); + bufferAOS.writeTo(out); + out.flush(); + return bufferAOS.size(); + } catch (IOException e) { + throw new BatchException("Unable to write SQL command: " + sqlCommand, e); + } catch (SQLException e) { + throw new BatchException("Unable to converd named SQL command to numbered: " + sqlCommand, e); + } + } + + private static byte[] toBytes(String s) { + if (s == null) { + return new byte[]{}; + } else { + return s.getBytes(CHARSET); + } + } +}