Class PostgresConnection
java.lang.Object
io.debezium.jdbc.JdbcConnection
io.debezium.connector.postgresql.connection.PostgresConnection
- All Implemented Interfaces:
AutoCloseable
JdbcConnection connection extension used for connecting to Postgres instances.- Author:
- Horia Chiorean
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceNested classes/interfaces inherited from class io.debezium.jdbc.JdbcConnection
JdbcConnection.BlockingMultiResultSetConsumer, JdbcConnection.BlockingResultSetConsumer, JdbcConnection.CallPreparer, JdbcConnection.ConnectionFactory, JdbcConnection.MultiResultSetConsumer, JdbcConnection.Operations, JdbcConnection.ParameterResultSetConsumer, JdbcConnection.ResultSetConsumer, JdbcConnection.ResultSetExtractor<T extends Object>, JdbcConnection.ResultSetMapper<T extends Object>, JdbcConnection.StatementFactory, JdbcConnection.StatementPreparer -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringprivate final PostgresDefaultValueConverterprivate static final Patternprotected static final JdbcConnection.ConnectionFactoryprivate static final Patternprivate static org.slf4j.Loggerprivate static final intObtaining a replication slot may fail if there's a pending transaction.private static final Durationprivate final TypeRegistryprivate static final String -
Constructor Summary
ConstructorsConstructorDescriptionPostgresConnection(PostgresConnectorConfig config, TypeRegistry typeRegistry, String connectionUsage) Create a Postgres connection using the supplied configuration andTypeRegistryPostgresConnection(JdbcConfiguration config, PostgresConnection.PostgresValueConverterBuilder valueConverterBuilder, String connectionUsage) Creates a Postgres connection using the supplied configuration.PostgresConnection(JdbcConfiguration config, String connectionUsage) Creates a Postgres connection using the supplied configuration. -
Method Summary
Modifier and TypeMethodDescription(package private) static JdbcConfigurationaddDefaultSettings(JdbcConfiguration configuration, String connectionUsage) voidclose()Returns a JDBC connection string for the current configuration.Returns the PG id of the current active transactionlongReturns the current position in the server tx log.private Optional<ColumnEditor>doReadTableColumn(ResultSet columnMetadata, TableId tableId, Tables.ColumnNameFilter columnFilter) booleandropPublication(String publicationName) Drops the debezium publication that was created.booleandropReplicationSlot(String slotName) Drops a replication slot that was created on the DBprivate ServerInfo.ReplicationSlotfetchReplicationSlotInfo(String slotName, String pluginName) Fetches the state of a replication stage given a slot name and plugin namegetAllTableIds(String catalogName) Retrieves allTableIds in a given database catalog, including partitioned tables.getColumnValue(ResultSet rs, int columnIndex, Column column, Table table) getReplicationSlotState(String slotName, String pluginName) Returns the current state of the replication slotorg.postgresql.jdbc.TimestampUtilsprivate booleanprotected booleanisTableType(String tableType) protected booleanisTableUniqueIndexIncluded(String indexName, String columnName) private LsnparseConfirmedFlushLsn(String slotName, String pluginName, String database, ResultSet rs) Obtains the LSN to resume streaming from.private LsnparseRestartLsn(String slotName, String pluginName, String database, ResultSet rs) protected ServerInfo.ReplicationSlotqueryForSlot(String slotName, String database, String pluginName, JdbcConnection.ResultSetMapper<ServerInfo.ReplicationSlot> map) quotedColumnIdString(String columnName) readColumnForDecoder(ResultSet columnMetadata, TableId tableId, Tables.ColumnNameFilter columnNameFilter) readIndexOfReplicaIdentity(TableId tableId) This query retrieves information about the INDEX as long as replica identity is configure USING INDEXreadReplicaIdentityInfo(TableId tableId) Prints out information about the REPLICA IDENTITY status of a table.(package private) ServerInfo.ReplicationSlotreadReplicationSlotInfo(String slotName, String pluginName) Fetches a replication slot, repeating the query until either the slot is created or until the max number of attempts has been reached To fetch the slot without the retries, use thefetchReplicationSlotInfo(java.lang.String, java.lang.String)callprotected Optional<ColumnEditor>readTableColumn(ResultSet columnMetadata, TableId tableId, Tables.ColumnNameFilter columnFilter) protected intresolveJdbcType(int metadataJdbcType, int nativeType) protected intresolveNativeType(String typeName) Returns information about the PG server to which this instance is connected.voidsetQueryColumnValue(PreparedStatement statement, Column column, int pos, Object value) voidsetReplicaIdentityForTable(TableId tableId, ReplicaIdentityInfo replicaIdentityValue) Update REPLICA IDENTITY status of a table.protected String[]private LsntryFallbackToRestartLsn(String slotName, String pluginName, String database, ResultSet rs) private Lsnprivate static voidvalidateServerVersion(Statement statement) Methods inherited from class io.debezium.jdbc.JdbcConnection
buildSelectWithRowLimits, call, commit, config, connect, connection, connection, connectionString, database, escapeEscapeSequence, execute, execute, executeWithoutCommitting, getAttributeDetails, getColumnsDetails, getCurrentTimestamp, isConnected, isNullable, isValid, loadKeyStore, overrideColumn, parseSqlStatementString, patternBasedFactory, patternBasedFactory, prepareQuery, prepareQuery, prepareQuery, prepareQuery, prepareQuery, prepareQueryAndMap, prepareQueryWithBlockingConsumer, prepareUpdate, print, print, query, query, queryAndMap, queryAndMap, querySingleValue, queryWithBlockingConsumer, quotedTableIdString, readAllCatalogNames, readAllSchemaNames, readAllTableNames, readPrimaryKeyNames, readPrimaryKeyOrUniqueIndexNames, readSchema, readTableNames, readTablePreparedStatement, readTableStatement, readTableUniqueIndices, resolveCatalogName, rollback, rowToArray, setAutoCommit, singleResultMapper, tableTypes, username
-
Field Details
-
CONNECTION_STREAMING
- See Also:
-
CONNECTION_SLOT_INFO
- See Also:
-
CONNECTION_DROP_SLOT
- See Also:
-
CONNECTION_VALIDATE_CONNECTION
- See Also:
-
CONNECTION_HEARTBEAT
- See Also:
-
CONNECTION_GENERAL
- See Also:
-
FUNCTION_DEFAULT_PATTERN
-
EXPRESSION_DEFAULT_PATTERN
-
LOGGER
private static org.slf4j.Logger LOGGER -
URL_PATTERN
-
FACTORY
-
MAX_ATTEMPTS_FOR_OBTAINING_REPLICATION_SLOT
private static final int MAX_ATTEMPTS_FOR_OBTAINING_REPLICATION_SLOTObtaining a replication slot may fail if there's a pending transaction. We're retrying to get a slot for 30 min.- See Also:
-
PAUSE_BETWEEN_REPLICATION_SLOT_RETRIEVAL_ATTEMPTS
-
typeRegistry
-
defaultValueConverter
-
-
Constructor Details
-
PostgresConnection
public PostgresConnection(JdbcConfiguration config, PostgresConnection.PostgresValueConverterBuilder valueConverterBuilder, String connectionUsage) Creates a Postgres connection using the supplied configuration. If necessary this connection is able to resolve data type mappings. Such a connection requires aPostgresValueConverter, and will provide its ownTypeRegistry. Usually only one such connection per connector is needed.- Parameters:
config-Configurationinstance, may not be null.valueConverterBuilder- supplies a configuredPostgresValueConverterfor a givenTypeRegistryconnectionUsage- a symbolic name of the connection to be tracked in monitoring tools
-
PostgresConnection
public PostgresConnection(PostgresConnectorConfig config, TypeRegistry typeRegistry, String connectionUsage) Create a Postgres connection using the supplied configuration andTypeRegistry- Parameters:
config-Configurationinstance, may not be null.typeRegistry- an existing/already-primedTypeRegistryinstanceconnectionUsage- a symbolic name of the connection to be tracked in monitoring tools
-
PostgresConnection
Creates a Postgres connection using the supplied configuration. The connector is the regular one without datatype resolution capabilities.- Parameters:
config-Configurationinstance, may not be null.connectionUsage- a symbolic name of the connection to be tracked in monitoring tools
-
-
Method Details
-
addDefaultSettings
static JdbcConfiguration addDefaultSettings(JdbcConfiguration configuration, String connectionUsage) -
connectionString
Returns a JDBC connection string for the current configuration.- Returns:
- a
Stringwhere the variables inurlPatternare replaced with values from the configuration
-
readReplicaIdentityInfo
@VisibleForTesting public ReplicaIdentityInfo readReplicaIdentityInfo(TableId tableId) throws SQLException Prints out information about the REPLICA IDENTITY status of a table. This in turn determines how much information is available for UPDATE and DELETE operations for logical replication.- Parameters:
tableId- the identifier of the table- Returns:
- the replica identity information; never null
- Throws:
SQLException- if there is a problem obtaining the replica identity information for the given table
-
readIndexOfReplicaIdentity
This query retrieves information about the INDEX as long as replica identity is configure USING INDEX- Parameters:
tableId- the identifier of the table- Returns:
- Index name linked to replica identity; never null
- Throws:
SQLException- if there is a problem obtaining the replica identity and index information for the given table
-
setReplicaIdentityForTable
Update REPLICA IDENTITY status of a table. This in turn determines how much information is available for UPDATE and DELETE operations for logical replication.- Parameters:
tableId- the identifier of the tablereplicaIdentityValue- Replica Identity value
-
getReplicationSlotState
Returns the current state of the replication slot- Parameters:
slotName- the name of the slotpluginName- the name of the plugin used for the desired slot- Returns:
- the
SlotStateor null, if no slot state is found - Throws:
SQLException
-
fetchReplicationSlotInfo
private ServerInfo.ReplicationSlot fetchReplicationSlotInfo(String slotName, String pluginName) throws SQLException Fetches the state of a replication stage given a slot name and plugin name- Parameters:
slotName- the name of the slotpluginName- the name of the plugin used for the desired slot- Returns:
- the
ServerInfo.ReplicationSlotobject or aServerInfo.ReplicationSlot.INVALIDif the slot is not valid - Throws:
SQLException- is thrown by the underlying JDBC
-
readReplicationSlotInfo
@VisibleForTesting ServerInfo.ReplicationSlot readReplicationSlotInfo(String slotName, String pluginName) throws SQLException, InterruptedException Fetches a replication slot, repeating the query until either the slot is created or until the max number of attempts has been reached To fetch the slot without the retries, use thefetchReplicationSlotInfo(java.lang.String, java.lang.String)call- Parameters:
slotName- the slot namepluginName- the name of the plugin- Returns:
- the
ServerInfo.ReplicationSlotobject or aServerInfo.ReplicationSlot.INVALIDif the slot is not valid - Throws:
SQLException- is thrown by the underyling jdbc driverInterruptedException- is thrown if we don't return an answer within the set number of retries
-
queryForSlot
protected ServerInfo.ReplicationSlot queryForSlot(String slotName, String database, String pluginName, JdbcConnection.ResultSetMapper<ServerInfo.ReplicationSlot> map) throws SQLException - Throws:
SQLException
-
parseConfirmedFlushLsn
private Lsn parseConfirmedFlushLsn(String slotName, String pluginName, String database, ResultSet rs) Obtains the LSN to resume streaming from. On PG 9.5 there is no confirmed_flushed_lsn yet, so restart_lsn will be read instead. This may result in more records to be re-read after a restart. -
hasIdleTransactions
- Throws:
SQLException
-
tryFallbackToRestartLsn
-
parseRestartLsn
-
tryParseLsn
private Lsn tryParseLsn(String slotName, String pluginName, String database, ResultSet rs, String column) throws org.apache.kafka.connect.errors.ConnectException, SQLException - Throws:
org.apache.kafka.connect.errors.ConnectExceptionSQLException
-
dropReplicationSlot
Drops a replication slot that was created on the DB- Parameters:
slotName- the name of the replication slot, may not be null- Returns:
trueif the slot was dropped,falseotherwise
-
dropPublication
Drops the debezium publication that was created.- Parameters:
publicationName- the publication name, may not be null- Returns:
trueif the publication was dropped,falseotherwise
-
close
public void close()- Specified by:
closein interfaceAutoCloseable- Overrides:
closein classJdbcConnection
-
currentTransactionId
Returns the PG id of the current active transaction- Returns:
- a PG transaction identifier, or null if no tx is active
- Throws:
SQLException- if anything fails.
-
currentXLogLocation
Returns the current position in the server tx log.- Returns:
- a long value, never negative
- Throws:
SQLException- if anything unexpected fails.
-
serverInfo
Returns information about the PG server to which this instance is connected.- Returns:
- a
ServerInfoinstance, nevernull - Throws:
SQLException- if anything fails
-
getDatabaseCharset
-
getTimestampUtils
public org.postgresql.jdbc.TimestampUtils getTimestampUtils() -
validateServerVersion
- Throws:
SQLException
-
quotedColumnIdString
- Overrides:
quotedColumnIdStringin classJdbcConnection
-
resolveNativeType
- Overrides:
resolveNativeTypein classJdbcConnection
-
resolveJdbcType
protected int resolveJdbcType(int metadataJdbcType, int nativeType) - Overrides:
resolveJdbcTypein classJdbcConnection
-
readTableColumn
protected Optional<ColumnEditor> readTableColumn(ResultSet columnMetadata, TableId tableId, Tables.ColumnNameFilter columnFilter) throws SQLException - Overrides:
readTableColumnin classJdbcConnection- Throws:
SQLException
-
readColumnForDecoder
public Optional<Column> readColumnForDecoder(ResultSet columnMetadata, TableId tableId, Tables.ColumnNameFilter columnNameFilter) throws SQLException - Throws:
SQLException
-
doReadTableColumn
private Optional<ColumnEditor> doReadTableColumn(ResultSet columnMetadata, TableId tableId, Tables.ColumnNameFilter columnFilter) throws SQLException - Throws:
SQLException
-
getDefaultValueConverter
-
getTypeRegistry
-
getColumnValue
public Object getColumnValue(ResultSet rs, int columnIndex, Column column, Table table) throws SQLException - Overrides:
getColumnValuein classJdbcConnection- Throws:
SQLException
-
supportedTableTypes
- Overrides:
supportedTableTypesin classJdbcConnection
-
isTableType
- Overrides:
isTableTypein classJdbcConnection
-
isTableUniqueIndexIncluded
- Overrides:
isTableUniqueIndexIncludedin classJdbcConnection
-
getAllTableIds
Retrieves allTableIds in a given database catalog, including partitioned tables.- Parameters:
catalogName- the catalog/database name- Returns:
- set of all table ids for existing table objects
- Throws:
SQLException- if a database exception occurred
-
setQueryColumnValue
public void setQueryColumnValue(PreparedStatement statement, Column column, int pos, Object value) throws SQLException - Overrides:
setQueryColumnValuein classJdbcConnection- Throws:
SQLException
-