Debian Codegraph @

src/main/org/h2/schema/TriggerObject.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.schema;
7
8 import java.lang.reflect.Method;
9 import java.sql.Connection;
10 import java.sql.ResultSet;
11 import java.sql.SQLException;
12 import java.util.Arrays;
13
14 import org.h2.api.ErrorCode;
15 import org.h2.api.Trigger;
16 import org.h2.engine.Constants;
17 import org.h2.engine.DbObject;
18 import org.h2.engine.SessionLocal;
19 import org.h2.jdbc.JdbcConnection;
20 import org.h2.jdbc.JdbcResultSet;
21 import org.h2.message.DbException;
22 import org.h2.message.Trace;
23 import org.h2.result.Row;
24 import org.h2.result.SimpleResult;
25 import org.h2.table.Column;
26 import org.h2.table.Table;
27 import org.h2.tools.TriggerAdapter;
28 import org.h2.util.JdbcUtils;
29 import org.h2.util.SourceCompiler;
30 import org.h2.util.StringUtils;
31 import org.h2.value.Value;
32 import org.h2.value.ValueToObjectConverter;
33
34 /**
35 *A trigger is created using the statement
36 * CREATE TRIGGER
37 */
38 public final class TriggerObject extends SchemaObject {
39
40 /**
41 * The default queue size.
42 */
43 public static final int DEFAULT_QUEUE_SIZE = 1024;
44
45 private boolean insteadOf;
46 private boolean before;
47 private int typeMask;
48 private boolean rowBased;
49 private boolean onRollback;
50 // TODO trigger: support queue and noWait = false as well
51 private int queueSize = DEFAULT_QUEUE_SIZE;
52 private boolean noWait;
53 private Table table;
54 private String triggerClassName;
55 private String triggerSource;
56 private Trigger triggerCallback;
57
58 public TriggerObject(Schema schema, int id, String name, Table table) {
59 super(schema, id, name, Trace.TRIGGER);
60 this.table = table;
61 setTemporary(table.isTemporary());
62 }
63
64 public void setBefore(boolean before) {
65 this.before = before;
66 }
67
68 public boolean isInsteadOf() {
69 return insteadOf;
70 }
71
72 public void setInsteadOf(boolean insteadOf) {
73 this.insteadOf = insteadOf;
74 }
75
76 private synchronized void load() {
77 if (triggerCallback != null) {
78 return;
79 }
80 try {
81 SessionLocal sysSession = database.getSystemSession();
82 Connection c2 = sysSession.createConnection(false);
83 Object obj;
84 if (triggerClassName != null) {
85 obj = JdbcUtils.loadUserClass(triggerClassName).getDeclaredConstructor().newInstance();
86 } else {
87 obj = loadFromSource();
88 }
89 triggerCallback = (Trigger) obj;
90 triggerCallback.init(c2, getSchema().getName(), getName(),
91 table.getName(), before, typeMask);
92 } catch (Throwable e) {
93 // try again later
94 triggerCallback = null;
95 throw DbException.get(ErrorCode.ERROR_CREATING_TRIGGER_OBJECT_3, e, getName(),
96 triggerClassName != null ? triggerClassName : "..source..", e.toString());
97 }
98 }
99
100 private Trigger loadFromSource() {
101 SourceCompiler compiler = database.getCompiler();
102 synchronized (compiler) {
103 String fullClassName = Constants.USER_PACKAGE + ".trigger." + getName();
104 compiler.setSource(fullClassName, triggerSource);
105 try {
106 if (SourceCompiler.isJavaxScriptSource(triggerSource)) {
107 return (Trigger) compiler.getCompiledScript(fullClassName).eval();
108 } else {
109 final Method m = compiler.getMethod(fullClassName);
110 if (m.getParameterTypes().length > 0) {
111 throw new IllegalStateException("No parameters are allowed for a trigger");
112 }
113 return (Trigger) m.invoke(null);
114 }
115 } catch (DbException e) {
116 throw e;
117 } catch (Exception e) {
118 throw DbException.get(ErrorCode.SYNTAX_ERROR_1, e, triggerSource);
119 }
120 }
121 }
122
123 /**
124 * Set the trigger class name and load the class if possible.
125 *
126 * @param triggerClassName the name of the trigger class
127 * @param force whether exceptions (due to missing class or access rights)
128 * should be ignored
129 */
130 public void setTriggerClassName(String triggerClassName, boolean force) {
131 this.setTriggerAction(triggerClassName, null, force);
132 }
133
134 /**
135 * Set the trigger source code and compile it if possible.
136 *
137 * @param source the source code of a method returning a {@link Trigger}
138 * @param force whether exceptions (due to syntax error)
139 * should be ignored
140 */
141 public void setTriggerSource(String source, boolean force) {
142 this.setTriggerAction(null, source, force);
143 }
144
145 private void setTriggerAction(String triggerClassName, String source, boolean force) {
146 this.triggerClassName = triggerClassName;
147 this.triggerSource = source;
148 try {
149 load();
150 } catch (DbException e) {
151 if (!force) {
152 throw e;
153 }
154 }
155 }
156
157 /**
158 * Call the trigger class if required. This method does nothing if the
159 * trigger is not defined for the given action. This method is called before
160 * or after any rows have been processed, once for each statement.
161 *
162 * @param session the session
163 * @param type the trigger type
164 * @param beforeAction if this method is called before applying the changes
165 */
166 public void fire(SessionLocal session, int type, boolean beforeAction) {
167 if (rowBased || before != beforeAction || (typeMask & type) == 0) {
168 return;
169 }
170 load();
171 Connection c2 = session.createConnection(false);
172 boolean old = false;
173 if (type != Trigger.SELECT) {
174 old = session.setCommitOrRollbackDisabled(true);
175 }
176 Value identity = session.getLastIdentity();
177 try {
178 if (triggerCallback instanceof TriggerAdapter) {
179 ((TriggerAdapter) triggerCallback).fire(c2, (ResultSet) null, (ResultSet) null);
180 } else {
181 triggerCallback.fire(c2, null, null);
182 }
183 } catch (Throwable e) {
184 throw getErrorExecutingTrigger(e);
185 } finally {
186 session.setLastIdentity(identity);
187 if (type != Trigger.SELECT) {
188 session.setCommitOrRollbackDisabled(old);
189 }
190 }
191 }
192
193 private static Object[] convertToObjectList(Row row, JdbcConnection conn) {
194 if (row == null) {
195 return null;
196 }
197 int len = row.getColumnCount();
198 Object[] list = new Object[len];
199 for (int i = 0; i < len; i++) {
200 list[i] = ValueToObjectConverter.valueToDefaultObject(row.getValue(i), conn, false);
201 }
202 return list;
203 }
204
205 /**
206 * Call the fire method of the user-defined trigger class if required. This
207 * method does nothing if the trigger is not defined for the given action.
208 * This method is called before or after a row is processed, possibly many
209 * times for each statement.
210 *
211 * @param session the session
212 * @param table the table
213 * @param oldRow the old row
214 * @param newRow the new row
215 * @param beforeAction true if this method is called before the operation is
216 * applied
217 * @param rollback when the operation occurred within a rollback
218 * @return true if no further action is required (for 'instead of' triggers)
219 */
220 public boolean fireRow(SessionLocal session, Table table, Row oldRow, Row newRow,
221 boolean beforeAction, boolean rollback) {
222 if (!rowBased || before != beforeAction) {
223 return false;
224 }
225 if (rollback && !onRollback) {
226 return false;
227 }
228 load();
229 boolean fire = false;
230 if ((typeMask & Trigger.INSERT) != 0) {
231 if (oldRow == null && newRow != null) {
232 fire = true;
233 }
234 }
235 if ((typeMask & Trigger.UPDATE) != 0) {
236 if (oldRow != null && newRow != null) {
237 fire = true;
238 }
239 }
240 if ((typeMask & Trigger.DELETE) != 0) {
241 if (oldRow != null && newRow == null) {
242 fire = true;
243 }
244 }
245 if (!fire) {
246 return false;
247 }
248 JdbcConnection c2 = session.createConnection(false);
249 boolean old = session.getAutoCommit();
250 boolean oldDisabled = session.setCommitOrRollbackDisabled(true);
251 Value identity = session.getLastIdentity();
252 try {
253 session.setAutoCommit(false);
254 if (triggerCallback instanceof TriggerAdapter) {
255 JdbcResultSet oldResultSet = oldRow != null ? createResultSet(c2, table, oldRow, false) : null;
256 JdbcResultSet newResultSet = newRow != null ? createResultSet(c2, table, newRow, before) : null;
257 try {
258 ((TriggerAdapter) triggerCallback).fire(c2, oldResultSet, newResultSet);
259 } catch (Throwable e) {
260 throw getErrorExecutingTrigger(e);
261 }
262 if (newResultSet != null) {
263 Value[] updatedList = newResultSet.getUpdateRow();
264 if (updatedList != null) {
265 boolean modified = false;
266 for (int i = 0, l = updatedList.length; i < l; i++) {
267 Value v = updatedList[i];
268 if (v != null) {
269 modified = true;
270 newRow.setValue(i, v);
271 }
272 }
273 if (modified) {
274 table.convertUpdateRow(session, newRow, true);
275 }
276 }
277 }
278 } else {
279 Object[] oldList = convertToObjectList(oldRow, c2);
280 Object[] newList = convertToObjectList(newRow, c2);
281 Object[] newListBackup = before && newList != null ? Arrays.copyOf(newList, newList.length) : null;
282 try {
283 triggerCallback.fire(c2, oldList, newList);
284 } catch (Throwable e) {
285 throw getErrorExecutingTrigger(e);
286 }
287 if (newListBackup != null) {
288 boolean modified = false;
289 for (int i = 0; i < newList.length; i++) {
290 Object o = newList[i];
291 if (o != newListBackup[i]) {
292 modified = true;
293 newRow.setValue(i, ValueToObjectConverter.objectToValue(session, o, Value.UNKNOWN));
294 }
295 }
296 if (modified) {
297 table.convertUpdateRow(session, newRow, true);
298 }
299 }
300 }
301 } catch (Exception e) {
302 if (onRollback) {
303 // ignore
304 } else {
305 throw DbException.convert(e);
306 }
307 } finally {
308 session.setLastIdentity(identity);
309 session.setCommitOrRollbackDisabled(oldDisabled);
310 session.setAutoCommit(old);
311 }
312 return insteadOf;
313 }
314
315 private static JdbcResultSet createResultSet(JdbcConnection conn, Table table, Row row, boolean updatable)
316 throws SQLException {
317 SimpleResult result = new SimpleResult(table.getSchema().getName(), table.getName());
318 for (Column c : table.getColumns()) {
319 result.addColumn(c.getName(), c.getType());
320 }
321 /*
322 * Old implementation works with and without next() invocation, so add
323 * the row twice for compatibility.
324 */
325 result.addRow(row.getValueList());
326 result.addRow(row.getValueList());
327 JdbcResultSet resultSet = new JdbcResultSet(conn, null, null, result, -1, false, false, updatable);
328 resultSet.next();
329 return resultSet;
330 }
331
332 private DbException getErrorExecutingTrigger(Throwable e) {
333 if (e instanceof DbException) {
334 return (DbException) e;
335 }
336 if (e instanceof SQLException) {
337 return DbException.convert(e);
338 }
339 return DbException.get(ErrorCode.ERROR_EXECUTING_TRIGGER_3, e, getName(),
340 triggerClassName != null ? triggerClassName : "..source..", e.toString());
341 }
342
343 /**
344 * Returns the trigger type.
345 *
346 * @return the trigger type
347 */
348 public int getTypeMask() {
349 return typeMask;
350 }
351
352 /**
353 * Set the trigger type.
354 *
355 * @param typeMask the type
356 */
357 public void setTypeMask(int typeMask) {
358 this.typeMask = typeMask;
359 }
360
361 public void setRowBased(boolean rowBased) {
362 this.rowBased = rowBased;
363 }
364
365 public boolean isRowBased() {
366 return rowBased;
367 }
368
369 public void setQueueSize(int size) {
370 this.queueSize = size;
371 }
372
373 public int getQueueSize() {
374 return queueSize;
375 }
376
377 public void setNoWait(boolean noWait) {
378 this.noWait = noWait;
379 }
380
381 public boolean isNoWait() {
382 return noWait;
383 }
384
385 public void setOnRollback(boolean onRollback) {
386 this.onRollback = onRollback;
387 }
388
389 public boolean isOnRollback() {
390 return onRollback;
391 }
392
393 @Override
394 public String getCreateSQLForCopy(Table targetTable, String quotedName) {
395 StringBuilder builder = new StringBuilder("CREATE FORCE TRIGGER ");
396 builder.append(quotedName);
397 if (insteadOf) {
398 builder.append(" INSTEAD OF ");
399 } else if (before) {
400 builder.append(" BEFORE ");
401 } else {
402 builder.append(" AFTER ");
403 }
404 getTypeNameList(builder).append(" ON ");
405 targetTable.getSQL(builder, DEFAULT_SQL_FLAGS);
406 if (rowBased) {
407 builder.append(" FOR EACH ROW");
408 }
409 if (noWait) {
410 builder.append(" NOWAIT");
411 } else {
412 builder.append(" QUEUE ").append(queueSize);
413 }
414 if (triggerClassName != null) {
415 StringUtils.quoteStringSQL(builder.append(" CALL "), triggerClassName);
416 } else {
417 StringUtils.quoteStringSQL(builder.append(" AS "), triggerSource);
418 }
419 return builder.toString();
420 }
421
422 /**
423 * Append the trigger types to the given string builder.
424 *
425 * @param builder the builder
426 * @return the passed string builder
427 */
428 public StringBuilder getTypeNameList(StringBuilder builder) {
429 boolean f = false;
430 if ((typeMask & Trigger.INSERT) != 0) {
431 f = true;
432 builder.append("INSERT");
433 }
434 if ((typeMask & Trigger.UPDATE) != 0) {
435 if (f) {
436 builder.append(", ");
437 }
438 f = true;
439 builder.append("UPDATE");
440 }
441 if ((typeMask & Trigger.DELETE) != 0) {
442 if (f) {
443 builder.append(", ");
444 }
445 f = true;
446 builder.append("DELETE");
447 }
448 if ((typeMask & Trigger.SELECT) != 0) {
449 if (f) {
450 builder.append(", ");
451 }
452 f = true;
453 builder.append("SELECT");
454 }
455 if (onRollback) {
456 if (f) {
457 builder.append(", ");
458 }
459 builder.append("ROLLBACK");
460 }
461 return builder;
462 }
463
464 @Override
465 public String getCreateSQL() {
466 return getCreateSQLForCopy(table, getSQL(DEFAULT_SQL_FLAGS));
467 }
468
469 @Override
470 public int getType() {
471 return DbObject.TRIGGER;
472 }
473
474 @Override
475 public void removeChildrenAndResources(SessionLocal session) {
476 table.removeTrigger(this);
477 database.removeMeta(session, getId());
478 if (triggerCallback != null) {
479 try {
480 triggerCallback.remove();
481 } catch (SQLException e) {
482 throw DbException.convert(e);
483 }
484 }
485 table = null;
486 triggerClassName = null;
487 triggerSource = null;
488 triggerCallback = null;
489 invalidate();
490 }
491
492 /**
493 * Get the table of this trigger.
494 *
495 * @return the table
496 */
497 public Table getTable() {
498 return table;
499 }
500
501 /**
502 * Check if this is a before trigger.
503 *
504 * @return true if it is
505 */
506 public boolean isBefore() {
507 return before;
508 }
509
510 /**
511 * Get the trigger class name.
512 *
513 * @return the class name
514 */
515 public String getTriggerClassName() {
516 return triggerClassName;
517 }
518
519 public String getTriggerSource() {
520 return triggerSource;
521 }
522
523 /**
524 * Close the trigger.
525 * @throws SQLException on failure
526 */
527 public void close() throws SQLException {
528 if (triggerCallback != null) {
529 triggerCallback.close();
530 }
531 }
532
533 /**
534 * Check whether this is a select trigger.
535 *
536 * @return true if it is
537 */
538 public boolean isSelectTrigger() {
539 return (typeMask & Trigger.SELECT) != 0;
540 }
541
542 }