Debian Codegraph @

src/test/org/h2/samples/UpdatableView.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.samples;
7
8 import java.sql.Connection;
9 import java.sql.DriverManager;
10 import java.sql.PreparedStatement;
11 import java.sql.ResultSet;
12 import java.sql.SQLException;
13 import java.sql.Statement;
14 import java.sql.Types;
15
16 import org.h2.tools.TriggerAdapter;
17
18 /**
19 * This sample application shows how to use triggers to create updatable views.
20 */
21 public class UpdatableView extends TriggerAdapter {
22
23 private PreparedStatement prepDelete, prepInsert;
24
25 /**
26 * This method is called when executing this sample application from the
27 * command line.
28 *
29 * @param args ignored
30 * @throws Exception on failure
31 */
32 public static void main(String... args) throws Exception {
33 Class.forName("org.h2.Driver");
34 try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:")) {
35 Statement stat;
36 stat = conn.createStatement();
37
38 // Create the table TEST_TABLE and the view TEST_VIEW that simply
39 // selects everything from the TEST_TABLE.
40 stat.execute("CREATE TABLE TEST_TABLE"
41 + "(ID BIGINT GENERATED BY DEFAULT AS IDENTITY DEFAULT ON NULL PRIMARY KEY, NAME VARCHAR)");
42 stat.execute("CREATE VIEW TEST_VIEW AS TABLE TEST_TABLE");
43
44 // Create the INSTEAD OF trigger that is called whenever the data in
45 // the view is modified. This trigger makes the view updatable.
46 stat.execute(
47 "CREATE TRIGGER T_TEST_VIEW INSTEAD OF INSERT, UPDATE, DELETE ON TEST_VIEW FOR EACH ROW CALL \""
48 + UpdatableView.class.getName() + '"');
49
50 // Test an INSERT operation and check that generated keys from the
51 // source table are returned as expected.
52 stat.execute("INSERT INTO TEST_VIEW(NAME) VALUES 'Hello', 'World'", new String[] { "ID" });
53 try (ResultSet rs = stat.getGeneratedKeys()) {
54 while (rs.next()) {
55 System.out.printf("Key %d was generated%n", rs.getLong(1));
56 }
57 }
58 System.out.println();
59 // Test UPDATE and DELETE operations.
60 stat.execute("UPDATE TEST_VIEW SET NAME = 'Hallo' WHERE ID = 1");
61 stat.execute("DELETE FROM TEST_VIEW WHERE ID = 2");
62
63 // Print the contents of the table and the view, they should be the
64 // same.
65 System.out.println("TEST_TABLE:");
66 try (ResultSet rs = stat.executeQuery("TABLE TEST_TABLE")) {
67 while (rs.next()) {
68 System.out.printf("%d %s%n", rs.getLong(1), rs.getString(2));
69 }
70 }
71 System.out.println();
72 System.out.println("TEST_VIEW:");
73 try (ResultSet rs = stat.executeQuery("TABLE TEST_VIEW")) {
74 while (rs.next()) {
75 System.out.printf("%d %s%n", rs.getLong(1), rs.getString(2));
76 }
77 }
78 }
79 }
80
81 @Override
82 public void init(Connection conn, String schemaName, String triggerName, String tableName, boolean before,
83 int type) throws SQLException {
84 prepDelete = conn.prepareStatement("DELETE FROM TEST_TABLE WHERE ID = ?");
85 // INSERT and UPDATE triggers should return the FINAL values of the row.
86 // Table TEST_TABLE has a generated column, so the FINAL row can be
87 // different from the row that we try to insert here.
88 prepInsert = conn.prepareStatement("SELECT * FROM FINAL TABLE(INSERT INTO TEST_TABLE VALUES (?, ?))");
89 super.init(conn, schemaName, triggerName, tableName, before, type);
90 }
91
92 @Override
93 public void fire(Connection conn, ResultSet oldRow, ResultSet newRow) throws SQLException {
94 if (oldRow != null && oldRow.next()) {
95 prepDelete.setLong(1, oldRow.getLong(1));
96 prepDelete.execute();
97 }
98 if (newRow != null && newRow.next()) {
99 long id = newRow.getLong(1);
100 if (newRow.wasNull()) {
101 prepInsert.setNull(1, Types.BIGINT);
102 } else {
103 prepInsert.setLong(1, id);
104 }
105 prepInsert.setString(2, newRow.getString(2));
106 // Now we need to execute the INSERT statement and update the newRow
107 // with the FINAL values.
108 // It is necessary for the FINAL TABLE and getGeneratedKeys(); if we
109 // don't update the newRow, the FINAL TABLE will work like the NEW
110 // TABLE.
111 // It is only necessary when the source table has generated columns
112 // or other columns with default values, or it has a trigger that
113 // can change the inserted values; without such columns the NEW
114 // TABLE and the FINAL TABLE are the same.
115 try (ResultSet rs = prepInsert.executeQuery()) {
116 rs.next();
117 newRow.updateLong(1, rs.getLong(1));
118 newRow.updateString(2, rs.getString(2));
119 newRow.rowUpdated();
120 }
121 }
122 }
123
124 @Override
125 public void close() throws SQLException {
126 prepInsert.close();
127 prepDelete.close();
128 }
129
130 }