/**
* 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 <http://www.gnu.org/licenses/>.
*/
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_HEADER);
if (sqlCommand instanceof SQLCommandNamed) {
sqlCommand = ((SQLCommandNamed) sqlCommand).getSQLCommandNumbered();
}
byte[] sqlBytes = toBytes(sqlCommand.getQuery());
buffer.writeInt(sqlBytes.length);
buffer.write(sqlBytes);
List<? extends Parameter> 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);
}
}
}