3 * Copyright © 2014 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, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package info.globalcode.sql.dk.batch;
20 import info.globalcode.sql.dk.Parameter;
21 import info.globalcode.sql.dk.SQLCommand;
22 import info.globalcode.sql.dk.SQLCommandNamed;
23 import java.io.DataOutputStream;
24 import java.io.IOException;
25 import java.io.OutputStream;
26 import static info.globalcode.sql.dk.batch.BatchConstants.*;
27 import java.io.ByteArrayOutputStream;
28 import java.sql.SQLException;
29 import java.util.List;
33 * @author Ing. František Kučera (frantovo.cz)
35 public class BatchEncoder {
37 public int encode(SQLCommand sqlCommand, OutputStream out) throws BatchException {
39 ByteArrayOutputStream bufferAOS = new ByteArrayOutputStream();
40 DataOutputStream buffer = new DataOutputStream(bufferAOS);
42 buffer.write(BATCH_START);
44 if (sqlCommand instanceof SQLCommandNamed) {
45 sqlCommand = ((SQLCommandNamed) sqlCommand).getSQLCommandNumbered();
48 byte[] sqlBytes = toBytes(sqlCommand.getQuery());
49 buffer.writeInt(sqlBytes.length);
50 buffer.write(sqlBytes);
52 List<? extends Parameter> parameters = sqlCommand.getParameters();
54 buffer.writeInt(parameters.size());
56 for (Parameter p : parameters) {
57 buffer.writeInt(p.getType().getCode());
58 byte[] value = toBytes((String) p.getValue()); // parameters are encoded before any preprocessing
59 buffer.writeInt(value.length);
64 bufferAOS.writeTo(out);
66 return bufferAOS.size();
67 } catch (IOException e) {
68 throw new BatchException("Unable to write SQL command: " + sqlCommand, e);
69 } catch (SQLException e) {
70 throw new BatchException("Unable to converd named SQL command to numbered: " + sqlCommand, e);
74 private static byte[] toBytes(String s) {
78 return s.getBytes(CHARSET);