org.postgresql.jdbc.PgConnection Java Examples

The following examples show how to use org.postgresql.jdbc.PgConnection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PostgreSqlClient.java    From presto with Apache License 2.0 6 votes vote down vote up
private static JdbcTypeHandle getArrayElementTypeHandle(Connection connection, JdbcTypeHandle arrayTypeHandle)
{
    String jdbcTypeName = arrayTypeHandle.getJdbcTypeName()
            .orElseThrow(() -> new PrestoException(JDBC_ERROR, "Type name is missing: " + arrayTypeHandle));
    try {
        TypeInfo typeInfo = connection.unwrap(PgConnection.class).getTypeInfo();
        int pgElementOid = typeInfo.getPGArrayElement(typeInfo.getPGType(jdbcTypeName));
        return new JdbcTypeHandle(
                typeInfo.getSQLType(pgElementOid),
                Optional.of(typeInfo.getPGType(pgElementOid)),
                arrayTypeHandle.getColumnSize(),
                arrayTypeHandle.getDecimalDigits(),
                arrayTypeHandle.getArrayDimensions());
    }
    catch (SQLException e) {
        throw new PrestoException(JDBC_ERROR, e);
    }
}
 
Example #2
Source File: PostgreSQLWalDumper.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@Override
public void dump(final Channel channel) {
    try {
        PGConnection pgConnection = logicalReplication.createPgConnection((JDBCDataSourceConfiguration) rdbmsConfiguration.getDataSourceConfiguration());
        decodingPlugin = new TestDecodingPlugin(((Connection) pgConnection).unwrap(PgConnection.class).getTimestampUtils());
        PGReplicationStream stream = logicalReplication.createReplicationStream(pgConnection,
                PostgreSQLLogPositionManager.SLOT_NAME, walPosition.getLogSequenceNumber());
        while (isRunning()) {
            ByteBuffer msg = stream.readPending();
            if (msg == null) {
                try {
                    Thread.sleep(10L);
                    continue;
                } catch (InterruptedException ignored) {
                
                }
            }
            AbstractWalEvent event = decodingPlugin.decode(msg, stream.getLastReceiveLSN());
            pushRecord(channel, walEventConverter.convert(event));
        }
    } catch (SQLException ex) {
        throw new SyncTaskExecuteException(ex);
    }
}
 
Example #3
Source File: DBLoader.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
Monitor(Connection con) {
	connection = con;
	LoggingInputStream lis = null;
	try {
		PgConnection a2 = (PgConnection)connection;
		QueryExecutor qe = a2.getQueryExecutor();
		// get the PGStream!
		java.lang.reflect.Field f_pgstream = QueryExecutorBase.class.getDeclaredField("pgStream");
		f_pgstream.setAccessible(true);
		PGStream pgstream = (PGStream)f_pgstream.get(qe);
		// now the InputStream
		java.lang.reflect.Field f_i = PGStream.class.getDeclaredField("pgInput");
		f_i.setAccessible(true);
		VisibleBufferedInputStream stream = (VisibleBufferedInputStream)f_i.get(pgstream);
		lis = new LoggingInputStream(stream);
		VisibleBufferedInputStream vlis = new VisibleBufferedInputStream(lis, stream.getBuffer().length);
		f_i.set(pgstream, vlis); // TADA! Many thanks to the PGSQL JDBC mailing list for this last tip on not just monitoring the PGStream as I was doing, but on replacing the inputstream altogether with a logging copy! ("CountingInputStream", they called it).

	} catch (Exception e) {
		IJError.print(e);
	}
	this.lis = lis;
	makeWindow();
}
 
Example #4
Source File: PostgresqlManager.java    From ReplicaDB with Apache License 2.0 5 votes vote down vote up
@Override
public int insertDataToTable(ResultSet resultSet, int taskId) throws SQLException, IOException {

    CopyIn copyIn = null;

    try {

        ResultSetMetaData rsmd = resultSet.getMetaData();
        String tableName;

        // Get table name and columns
        if (options.getMode().equals(ReplicationMode.COMPLETE.getModeText())) {
            tableName = getSinkTableName();
        } else {
            tableName = getQualifiedStagingTableName();
        }

        String allColumns = getAllSinkColumns(rsmd);

        // Get Postgres COPY meta-command manager
        PgConnection copyOperationConnection = this.connection.unwrap(PgConnection.class);
        CopyManager copyManager = new CopyManager(copyOperationConnection);
        String copyCmd = getCopyCommand(tableName, allColumns);
        copyIn = copyManager.copyIn(copyCmd);

        char unitSeparator = 0x1F;
        int columnsNumber = rsmd.getColumnCount();

        StringBuilder row = new StringBuilder();
        StringBuilder cols = new StringBuilder();

        byte[] bytes;
        String colValue;

        if (resultSet.next()) {
            // Create Bandwidth Throttling
            bandwidthThrottlingCreate(resultSet, rsmd);

            do {
                bandwidthThrottlingAcquiere();

                // Get Columns values
                for (int i = 1; i <= columnsNumber; i++) {
                    if (i > 1) cols.append(unitSeparator);

                    switch (rsmd.getColumnType(i)) {

                        case Types.CLOB:
                            colValue = clobToString(resultSet.getClob(i));
                            break;
                        case Types.BINARY:
                        case Types.BLOB:
                            colValue = blobToPostgresHex(resultSet.getBlob(i));
                            break;
                        default:
                            colValue = resultSet.getString(i);
                            break;
                    }

                    if (!resultSet.wasNull() || colValue != null) cols.append(colValue);
                }

                // Escape special chars
                if (this.options.isSinkDisableEscape())
                    row.append(cols.toString());
                else
                    row.append(cols.toString().replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "\\r").replace("\u0000", ""));

                // Row ends with \n
                row.append("\n");

                // Copy data to postgres
                bytes = row.toString().getBytes(StandardCharsets.UTF_8);
                copyIn.writeToCopy(bytes, 0, bytes.length);

                // Clear StringBuilders
                row.setLength(0); // set length of buffer to 0
                row.trimToSize();
                cols.setLength(0); // set length of buffer to 0
                cols.trimToSize();
            } while (resultSet.next());
        }

        copyIn.endCopy();

    } catch (Exception e) {
        if (copyIn != null && copyIn.isActive()) {
            copyIn.cancelCopy();
        }
        this.connection.rollback();
        throw e;
    } finally {
        if (copyIn != null && copyIn.isActive()) {
            copyIn.cancelCopy();
        }
    }

    this.getConnection().commit();

    return 0;
}