Search in sources :

Example 1 with PGConnection

use of org.postgresql.PGConnection in project sqlg by pietermartin.

the class PostgresDialect method streamSql.

@Override
public Writer streamSql(SqlgGraph sqlgGraph, String sql) {
    Connection conn = sqlgGraph.tx().getConnection();
    PGConnection pgConnection;
    try {
        pgConnection = conn.unwrap(PGConnection.class);
        OutputStream out = new PGCopyOutputStream(pgConnection, sql);
        return new OutputStreamWriter(out, "UTF-8");
    } catch (SQLException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
Also used : PGConnection(org.postgresql.PGConnection) PGCopyOutputStream(org.postgresql.copy.PGCopyOutputStream) PGCopyOutputStream(org.postgresql.copy.PGCopyOutputStream) PGConnection(org.postgresql.PGConnection)

Example 2 with PGConnection

use of org.postgresql.PGConnection in project activemq-artemis by apache.

the class PostgresSequentialSequentialFileDriver method createFile.

@Override
public void createFile(JDBCSequentialFile file) throws SQLException {
    synchronized (connection) {
        try {
            connection.setAutoCommit(false);
            LargeObjectManager lobjManager = ((PGConnection) connection).getLargeObjectAPI();
            long oid = lobjManager.createLO();
            createFile.setString(1, file.getFileName());
            createFile.setString(2, file.getExtension());
            createFile.setLong(3, oid);
            createFile.executeUpdate();
            try (ResultSet keys = createFile.getGeneratedKeys()) {
                keys.next();
                file.setId(keys.getLong(1));
            }
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            throw e;
        }
    }
}
Also used : PGConnection(org.postgresql.PGConnection) LargeObjectManager(org.postgresql.largeobject.LargeObjectManager) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet)

Example 3 with PGConnection

use of org.postgresql.PGConnection in project hale by halestudio.

the class DatabaseIT method testConnection.

/**
 * @throws SQLException if the connection cannot be obtained
 */
@Test
public void testConnection() throws SQLException {
    Connection connection = waitForConnection();
    try {
        assertTrue(connection instanceof PGConnection);
        assertTrue(connection.createStatement().execute("SELECT 1"));
    } finally {
        connection.close();
    }
}
Also used : PGConnection(org.postgresql.PGConnection) Connection(java.sql.Connection) PGConnection(org.postgresql.PGConnection) AbstractDBTest(eu.esdihumboldt.hale.io.jdbc.test.AbstractDBTest) Test(org.junit.Test)

Example 4 with PGConnection

use of org.postgresql.PGConnection in project hale by halestudio.

the class PostGISGeometries method configureGeometryColumnType.

@Override
public Class<? extends Geometry> configureGeometryColumnType(PGConnection connection, BaseColumn<?> column, DefaultTypeDefinition type) {
    Connection con = (Connection) connection;
    String columnValueName = column.getParent().getName();
    String geometryType = null;
    try {
        Statement stmt = con.createStatement();
        // Get the srid, dimension and geometry type
        ResultSet rs = stmt.executeQuery("SELECT srid,type,coord_dimension FROM geometry_columns WHERE f_table_name = " + "'" + columnValueName + "'");
        if (rs.next()) {
            geometryType = rs.getString("type");
            String dimension = rs.getString("coord_dimension");
            // Get the epsg code for the srid
            String srid = rs.getString("srid");
            ResultSet r = stmt.executeQuery("SELECT auth_srid, auth_name, srtext FROM spatial_ref_sys WHERE srid = " + srid);
            if (r.next()) {
                // Create Constraint to save the informations
                GeometryMetadata columnTypeConstraint = new GeometryMetadata(r.getString("auth_srid"), Integer.parseInt(dimension), r.getString("srtext"), r.getString("auth_name"));
                type.setConstraint(columnTypeConstraint);
            }
        } else {
        // XXX what if no SRID information is present? is that a case
        // that may still be valid?
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    // In this case we have no geometry column information
    if (geometryType == null) {
        // use geometry even if no geometry column is present describing it
        return Geometry.class;
    }
    // return the geometryType
    if (geometryType.equalsIgnoreCase("MultiPolygon")) {
        return MultiPolygon.class;
    } else if (geometryType.equalsIgnoreCase("MultiPoint")) {
        return MultiPoint.class;
    } else if (geometryType.equalsIgnoreCase("MultiLineString")) {
        return MultiLineString.class;
    } else // TODO: shouldn't this be LineString instead?
    if (geometryType.equalsIgnoreCase("LinearRing")) {
        return LinearRing.class;
    } else if (geometryType.equalsIgnoreCase("Point")) {
        return Point.class;
    } else if (geometryType.equalsIgnoreCase("Polygon")) {
        return Polygon.class;
    } else {
        return Geometry.class;
    }
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) MultiLineString(com.vividsolutions.jts.geom.MultiLineString) GeometryMetadata(eu.esdihumboldt.hale.common.schema.model.constraint.type.GeometryMetadata) SQLException(java.sql.SQLException) MultiPolygon(com.vividsolutions.jts.geom.MultiPolygon) Statement(java.sql.Statement) Connection(java.sql.Connection) PGConnection(org.postgresql.PGConnection) ResultSet(java.sql.ResultSet) MultiLineString(com.vividsolutions.jts.geom.MultiLineString) Point(com.vividsolutions.jts.geom.Point) MultiPoint(com.vividsolutions.jts.geom.MultiPoint)

Example 5 with PGConnection

use of org.postgresql.PGConnection in project eventuate-local by eventuate-local.

the class PostgresWalClient method connectAndRun.

private void connectAndRun(Optional<BinlogFileOffset> binlogFileOffset, Consumer<EVENT> eventConsumer) throws SQLException, InterruptedException, IOException {
    countDownLatchForStop = new CountDownLatch(1);
    Properties props = new Properties();
    PGProperty.USER.set(props, user);
    PGProperty.PASSWORD.set(props, password);
    PGProperty.ASSUME_MIN_SERVER_VERSION.set(props, "9.4");
    PGProperty.REPLICATION.set(props, "database");
    PGProperty.PREFER_QUERY_MODE.set(props, "simple");
    connection = DriverManager.getConnection(url, props);
    PGConnection replConnection = connection.unwrap(PGConnection.class);
    LogSequenceNumber lsn = binlogFileOffset.flatMap(offset -> Optional.ofNullable(offset.getOffset()).map(LogSequenceNumber::valueOf)).orElse(LogSequenceNumber.valueOf("0/0"));
    stream = replConnection.getReplicationAPI().replicationStream().logical().withSlotName(replicationSlotName).withSlotOption("include-xids", false).withStatusInterval(replicationStatusIntervalInMilliseconds, TimeUnit.MILLISECONDS).withStartPosition(lsn).start();
    logger.info("connection to postgres wal succeed");
    while (running) {
        ByteBuffer messageBuffer = stream.readPending();
        if (messageBuffer == null) {
            logger.info("Got empty message, sleeping");
            TimeUnit.MILLISECONDS.sleep(walIntervalInMilliseconds);
            continue;
        }
        String messageString = extractStringFromBuffer(messageBuffer);
        logger.info("Got message: " + messageString);
        postgresWalMessageParser.parse(JSonMapper.fromJson(messageString, PostgresWalMessage.class), stream.getLastReceiveLSN().asLong(), replicationSlotName).forEach(eventConsumer);
        stream.setAppliedLSN(stream.getLastReceiveLSN());
        stream.setFlushedLSN(stream.getLastReceiveLSN());
    }
    try {
        stream.close();
        connection.close();
    } catch (SQLException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
    countDownLatchForStop.countDown();
}
Also used : LogSequenceNumber(org.postgresql.replication.LogSequenceNumber) BinLogEvent(io.eventuate.local.common.BinLogEvent) Logger(org.slf4j.Logger) Connection(java.sql.Connection) Properties(java.util.Properties) BinlogFileOffset(io.eventuate.local.common.BinlogFileOffset) DbLogClient(io.eventuate.local.db.log.common.DbLogClient) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) JSonMapper(io.eventuate.javaclient.commonimpl.JSonMapper) PGProperty(org.postgresql.PGProperty) PGConnection(org.postgresql.PGConnection) ByteBuffer(java.nio.ByteBuffer) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) SQLException(java.sql.SQLException) PGReplicationStream(org.postgresql.replication.PGReplicationStream) Optional(java.util.Optional) DriverManager(java.sql.DriverManager) PGConnection(org.postgresql.PGConnection) SQLException(java.sql.SQLException) LogSequenceNumber(org.postgresql.replication.LogSequenceNumber) CountDownLatch(java.util.concurrent.CountDownLatch) Properties(java.util.Properties) ByteBuffer(java.nio.ByteBuffer)

Aggregations

PGConnection (org.postgresql.PGConnection)16 SQLException (java.sql.SQLException)11 Connection (java.sql.Connection)7 LargeObjectManager (org.postgresql.largeobject.LargeObjectManager)5 IOException (java.io.IOException)4 LargeObject (org.postgresql.largeobject.LargeObject)4 ResultSet (java.sql.ResultSet)3 Statement (java.sql.Statement)3 GeometryMetadata (eu.esdihumboldt.hale.common.schema.model.constraint.type.GeometryMetadata)2 DelegatingConnection (org.apache.commons.dbcp2.DelegatingConnection)2 PGCopyOutputStream (org.postgresql.copy.PGCopyOutputStream)2 Resource (com.revolsys.spring.resource.Resource)1 Geometry (com.vividsolutions.jts.geom.Geometry)1 MultiLineString (com.vividsolutions.jts.geom.MultiLineString)1 MultiPoint (com.vividsolutions.jts.geom.MultiPoint)1 MultiPolygon (com.vividsolutions.jts.geom.MultiPolygon)1 Point (com.vividsolutions.jts.geom.Point)1 AbstractDBTest (eu.esdihumboldt.hale.io.jdbc.test.AbstractDBTest)1 JSonMapper (io.eventuate.javaclient.commonimpl.JSonMapper)1 BinLogEvent (io.eventuate.local.common.BinLogEvent)1