Debian Codegraph @

src/main/org/h2/result/UpdatableRow.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.result;
7
8 import java.sql.DatabaseMetaData;
9 import java.sql.PreparedStatement;
10 import java.sql.ResultSet;
11 import java.sql.SQLException;
12 import java.util.ArrayList;
13
14 import org.h2.api.ErrorCode;
15 import org.h2.engine.Constants;
16 import org.h2.engine.Session;
17 import org.h2.engine.SessionRemote;
18 import org.h2.jdbc.JdbcConnection;
19 import org.h2.jdbc.JdbcResultSet;
20 import org.h2.message.DbException;
21 import org.h2.util.JdbcUtils;
22 import org.h2.util.StringUtils;
23 import org.h2.util.Utils;
24 import org.h2.value.Value;
25 import org.h2.value.ValueNull;
26 import org.h2.value.ValueToObjectConverter;
27
28 /**
29 * This class is used for updatable result sets. An updatable row provides
30 * functions to update the current row in a result set.
31 */
32 public class UpdatableRow {
33
34 private final JdbcConnection conn;
35 private final ResultInterface result;
36 private final int columnCount;
37 private String schemaName;
38 private String tableName;
39 private ArrayList<String> key;
40 private boolean isUpdatable;
41
42 /**
43 * Construct a new object that is linked to the result set. The constructor
44 * reads the database meta data to find out if the result set is updatable.
45 *
46 * @param conn the database connection
47 * @param result the result
48 * @throws SQLException on failure
49 */
50 public UpdatableRow(JdbcConnection conn, ResultInterface result)
51 throws SQLException {
52 this.conn = conn;
53 this.result = result;
54 columnCount = result.getVisibleColumnCount();
55 if (columnCount == 0) {
56 return;
57 }
58 for (int i = 0; i < columnCount; i++) {
59 String t = result.getTableName(i);
60 String s = result.getSchemaName(i);
61 if (t == null || s == null) {
62 return;
63 }
64 if (tableName == null) {
65 tableName = t;
66 } else if (!tableName.equals(t)) {
67 return;
68 }
69 if (schemaName == null) {
70 schemaName = s;
71 } else if (!schemaName.equals(s)) {
72 return;
73 }
74 }
75 String type = "BASE TABLE";
76 Session session = conn.getSession();
77 if (session instanceof SessionRemote
78 && ((SessionRemote) session).getClientVersion() <= Constants.TCP_PROTOCOL_VERSION_19) {
79 type = "TABLE";
80 }
81 final DatabaseMetaData meta = conn.getMetaData();
82 ResultSet rs = meta.getTables(null,
83 StringUtils.escapeMetaDataPattern(schemaName),
84 StringUtils.escapeMetaDataPattern(tableName),
85 new String[] { type });
86 if (!rs.next()) {
87 return;
88 }
89 String table = rs.getString("TABLE_NAME");
90 // if the table name in the database meta data is lower case,
91 // but the table in the result set meta data is not, then the column
92 // in the database meta data is also lower case
93 boolean toUpper = !table.equals(tableName) && table.equalsIgnoreCase(tableName);
94 key = Utils.newSmallArrayList();
95 rs = meta.getPrimaryKeys(null,
96 StringUtils.escapeMetaDataPattern(schemaName),
97 tableName);
98 while (rs.next()) {
99 String c = rs.getString("COLUMN_NAME");
100 key.add(toUpper ? StringUtils.toUpperEnglish(c) : c);
101 }
102 if (isIndexUsable(key)) {
103 isUpdatable = true;
104 return;
105 }
106 key.clear();
107 rs = meta.getIndexInfo(null,
108 StringUtils.escapeMetaDataPattern(schemaName),
109 tableName, true, true);
110 while (rs.next()) {
111 int pos = rs.getShort("ORDINAL_POSITION");
112 if (pos == 1) {
113 // check the last key if there was any
114 if (isIndexUsable(key)) {
115 isUpdatable = true;
116 return;
117 }
118 key.clear();
119 }
120 String c = rs.getString("COLUMN_NAME");
121 key.add(toUpper ? StringUtils.toUpperEnglish(c) : c);
122 }
123 if (isIndexUsable(key)) {
124 isUpdatable = true;
125 return;
126 }
127 key = null;
128 }
129
130 private boolean isIndexUsable(ArrayList<String> indexColumns) {
131 if (indexColumns.isEmpty()) {
132 return false;
133 }
134 for (String c : indexColumns) {
135 if (findColumnIndex(c) < 0) {
136 return false;
137 }
138 }
139 return true;
140 }
141
142 /**
143 * Check if this result set is updatable.
144 *
145 * @return true if it is
146 */
147 public boolean isUpdatable() {
148 return isUpdatable;
149 }
150
151 private int findColumnIndex(String columnName) {
152 for (int i = 0; i < columnCount; i++) {
153 String col = result.getColumnName(i);
154 if (col.equals(columnName)) {
155 return i;
156 }
157 }
158 return -1;
159 }
160
161 private int getColumnIndex(String columnName) {
162 int index = findColumnIndex(columnName);
163 if (index < 0) {
164 throw DbException.get(ErrorCode.COLUMN_NOT_FOUND_1, columnName);
165 }
166 return index;
167 }
168
169 private void appendColumnList(StringBuilder builder, boolean set) {
170 for (int i = 0; i < columnCount; i++) {
171 if (i > 0) {
172 builder.append(',');
173 }
174 String col = result.getColumnName(i);
175 StringUtils.quoteIdentifier(builder, col);
176 if (set) {
177 builder.append("=? ");
178 }
179 }
180 }
181
182 private void appendKeyCondition(StringBuilder builder) {
183 builder.append(" WHERE ");
184 for (int i = 0; i < key.size(); i++) {
185 if (i > 0) {
186 builder.append(" AND ");
187 }
188 StringUtils.quoteIdentifier(builder, key.get(i)).append("=?");
189 }
190 }
191
192 private void setKey(PreparedStatement prep, int start, Value[] current) throws SQLException {
193 for (int i = 0, size = key.size(); i < size; i++) {
194 String col = key.get(i);
195 int idx = getColumnIndex(col);
196 Value v = current[idx];
197 if (v == null || v == ValueNull.INSTANCE) {
198 // rows with a unique key containing NULL are not supported,
199 // as multiple such rows could exist
200 throw DbException.get(ErrorCode.NO_DATA_AVAILABLE);
201 }
202 JdbcUtils.set(prep, start + i, v, conn);
203 }
204 }
205
206 // public boolean isRowDeleted(Value[] row) throws SQLException {
207 // StringBuilder buff = new StringBuilder();
208 // buff.append("SELECT COUNT(*) FROM ").
209 // append(StringUtils.quoteIdentifier(tableName));
210 // appendKeyCondition(buff);
211 // PreparedStatement prep = conn.prepareStatement(buff.toString());
212 // setKey(prep, 1, row);
213 // ResultSet rs = prep.executeQuery();
214 // rs.next();
215 // return rs.getInt(1) == 0;
216 // }
217
218 private void appendTableName(StringBuilder builder) {
219 if (schemaName != null && schemaName.length() > 0) {
220 StringUtils.quoteIdentifier(builder, schemaName).append('.');
221 }
222 StringUtils.quoteIdentifier(builder, tableName);
223 }
224
225 /**
226 * Re-reads a row from the database and updates the values in the array.
227 *
228 * @param row the values that contain the key
229 * @return the row
230 * @throws SQLException on failure
231 */
232 public Value[] readRow(Value[] row) throws SQLException {
233 StringBuilder builder = new StringBuilder("SELECT ");
234 appendColumnList(builder, false);
235 builder.append(" FROM ");
236 appendTableName(builder);
237 appendKeyCondition(builder);
238 PreparedStatement prep = conn.prepareStatement(builder.toString());
239 setKey(prep, 1, row);
240 JdbcResultSet rs = (JdbcResultSet) prep.executeQuery();
241 if (!rs.next()) {
242 throw DbException.get(ErrorCode.NO_DATA_AVAILABLE);
243 }
244 Value[] newRow = new Value[columnCount];
245 for (int i = 0; i < columnCount; i++) {
246 newRow[i] = ValueToObjectConverter.readValue(conn.getSession(), rs, i + 1);
247 }
248 return newRow;
249 }
250
251 /**
252 * Delete the given row in the database.
253 *
254 * @param current the row
255 * @throws SQLException if this row has already been deleted
256 */
257 public void deleteRow(Value[] current) throws SQLException {
258 StringBuilder builder = new StringBuilder("DELETE FROM ");
259 appendTableName(builder);
260 appendKeyCondition(builder);
261 PreparedStatement prep = conn.prepareStatement(builder.toString());
262 setKey(prep, 1, current);
263 int count = prep.executeUpdate();
264 if (count != 1) {
265 // the row has already been deleted
266 throw DbException.get(ErrorCode.NO_DATA_AVAILABLE);
267 }
268 }
269
270 /**
271 * Update a row in the database.
272 *
273 * @param current the old row
274 * @param updateRow the new row
275 * @throws SQLException if the row has been deleted
276 */
277 public void updateRow(Value[] current, Value[] updateRow) throws SQLException {
278 StringBuilder builder = new StringBuilder("UPDATE ");
279 appendTableName(builder);
280 builder.append(" SET ");
281 appendColumnList(builder, true);
282 // TODO updatable result set: we could add all current values to the
283 // where clause
284 // - like this optimistic ('no') locking is possible
285 appendKeyCondition(builder);
286 PreparedStatement prep = conn.prepareStatement(builder.toString());
287 int j = 1;
288 for (int i = 0; i < columnCount; i++) {
289 Value v = updateRow[i];
290 if (v == null) {
291 v = current[i];
292 }
293 JdbcUtils.set(prep, j++, v, conn);
294 }
295 setKey(prep, j, current);
296 int count = prep.executeUpdate();
297 if (count != 1) {
298 // the row has been deleted
299 throw DbException.get(ErrorCode.NO_DATA_AVAILABLE);
300 }
301 }
302
303 /**
304 * Insert a new row into the database.
305 *
306 * @param row the new row
307 * @throws SQLException if the row could not be inserted
308 */
309 public void insertRow(Value[] row) throws SQLException {
310 StringBuilder builder = new StringBuilder("INSERT INTO ");
311 appendTableName(builder);
312 builder.append('(');
313 appendColumnList(builder, false);
314 builder.append(")VALUES(");
315 for (int i = 0; i < columnCount; i++) {
316 if (i > 0) {
317 builder.append(',');
318 }
319 Value v = row[i];
320 if (v == null) {
321 builder.append("DEFAULT");
322 } else {
323 builder.append('?');
324 }
325 }
326 builder.append(')');
327 PreparedStatement prep = conn.prepareStatement(builder.toString());
328 for (int i = 0, j = 0; i < columnCount; i++) {
329 Value v = row[i];
330 if (v != null) {
331 JdbcUtils.set(prep, j++ + 1, v, conn);
332 }
333 }
334 int count = prep.executeUpdate();
335 if (count != 1) {
336 throw DbException.get(ErrorCode.NO_DATA_AVAILABLE);
337 }
338 }
339
340 }