diff --git a/jdbc-postgresql/src/main/java/module-info.java b/jdbc-postgresql/src/main/java/module-info.java index 13bf83e..01de615 100644 --- a/jdbc-postgresql/src/main/java/module-info.java +++ b/jdbc-postgresql/src/main/java/module-info.java @@ -4,6 +4,7 @@ import org.xbib.jdbc.postgresql.Postgresql; module org.xbib.jdbc.postgresql { requires org.xbib.jdbc.query; requires java.sql; + requires org.postgresql.jdbc; uses Flavor; exports org.xbib.jdbc.postgresql; provides Flavor with Postgresql; diff --git a/jdbc-postgresql/src/main/java/org/xbib/jdbc/postgresql/Listener.java b/jdbc-postgresql/src/main/java/org/xbib/jdbc/postgresql/Listener.java new file mode 100644 index 0000000..3c1c372 --- /dev/null +++ b/jdbc-postgresql/src/main/java/org/xbib/jdbc/postgresql/Listener.java @@ -0,0 +1,53 @@ +package org.xbib.jdbc.postgresql; + +import org.postgresql.PGNotification; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.function.Consumer; + +public class Listener implements Runnable { + + private final Connection connection; + + private final org.postgresql.PGConnection pgConnection; + + private final Consumer notificationConsumer; + + private final Consumer errorConsumer; + + public Listener(Connection connection, + Consumer notificationConsumer, + Consumer errorConsumer) throws SQLException { + this.connection = connection; + this.pgConnection = (org.postgresql.PGConnection) connection; + this.errorConsumer = errorConsumer; + this.notificationConsumer = notificationConsumer; + try (Statement stmt = connection.createStatement()) { + stmt.execute("LISTEN event"); + } + } + + @Override + public void run() { + while (true) { + try (Statement stmt = connection.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT 1")) { + } catch (SQLException e) { + errorConsumer.accept(e); + } + try { + PGNotification[] notifications = pgConnection.getNotifications(); + if (notifications != null) { + for (PGNotification notification : notifications) { + notificationConsumer.accept(notification); + } + } + } catch (SQLException e) { + errorConsumer.accept(e); + } + } + } +}