PostgreSQL Sink (JDBC) Connector for Confluent Cloud

The fully-managed PostgreSQL Sink connector for Confluent Cloud moves data from an Apache Kafka® topic to a PostgreSQL database. It writes data from a topic in Kafka to a table in the specified PostgreSQL database. Table auto-creation and limited auto-evolution are supported.

Note

Features

The PostgreSQL Sink connector provides the following features:

  • Idempotent writes: The default insert.mode is INSERT. If it is configured as UPSERT, the connector will use upsert semantics rather than plain insert statements. Upsert semantics refer to atomically adding a new row or updating the existing row if there is a primary key constraint violation, which provides idempotence.
  • SSL support: Supports one-way SSL.
  • Schemas: The connector supports Avro, JSON Schema, and Protobuf input value formats. The connector supports Avro, JSON Schema, Protobuf, and String input key formats. Schema Registry must be enabled to use a Schema Registry-based format.
  • Primary key support: Supported PK modes are kafka, none, record_key, and record_value. Used in conjunction with the PK Fields property.
  • Table and column auto-creation: auto.create and auto-evolve are supported. If tables or columns are missing, they can be created automatically. Table names are created based on Kafka topic names. For more information, see Table names and Kafka topic names.
  • At least once delivery: This connector guarantees that records from the Kafka topic are delivered at least once.
  • Supports multiple tasks: The connector supports running one or more tasks. More tasks may improve performance.
  • PostgreSQL JSON and JSONB: The connector supports sinking to PostgreSQL tables containing data stored as JSON or JSONB (JSON binary format). JSON or JSONB should be stored as STRING type in Kafka and matching columns should be defined as JSON or JSONB in PostgreSQL.

For more information and examples to use with the Confluent Cloud API for Connect, see the Confluent Cloud API for Connect Usage Examples section.

Limitations

Be sure to review the following information.

Table names and Kafka topic names

You can configure the connector to combine the value for table.name.format and the Kafka topic name. If the resulting combined value (table name) exceeds the maximum-permitted identifier length for the database version in use, the connector truncates the value to the permitted identifier length.

For example, PostgreSQL 14 uses 63 bytes as its default identifier length setting. If the value used for table.name.format and the Kafka topic name exceeds 63 characters, only the first 63 characters from the combined name are used.

For this reason, you should not run the connector with very long Kafka topic names and table names. If the table name is truncated, and the connector receives records from different upstream topics, the records map to the same table name after truncation takes place. This results in a duplicate table name collision.

Note

You can expect this connector behavior for any interactions with the database, both DDL (table creation and evolution) and DML (insert, upsert, and delete).

Quick Start

Use this quick start to get up and running with the Confluent Cloud PostgreSQL sink connector. The quick start provides the basics of selecting the connector and configuring it to stream events to a PostgreSQL database.

Prerequisites
  • Kafka cluster credentials. The following lists the different ways you can provide credentials.
    • Enter an existing service account resource ID.
    • Create a Confluent Cloud service account for the connector. Make sure to review the ACL entries required in the service account documentation. Some connectors have specific ACL requirements.
    • Create a Confluent Cloud API key and secret. To create a key and secret, you can use confluent api-key create or you can autogenerate the API key and secret directly in the Cloud Console when setting up the connector.

Using the Confluent Cloud Console

Step 1: Launch your Confluent Cloud cluster

See the Quick Start for Confluent Cloud for installation instructions.

Step 2: Add a connector

In the left navigation menu, click Connectors. If you already have connectors in your cluster, click + Add connector.

Step 3: Select your connector

Click the PostgreSQL Sink connector card.

PostgreSQL Sink Connector Card

Step 4: Enter the connector details

Note

  • Ensure you have all your prerequisites completed.
  • An asterisk ( * ) designates a required entry.

At the Add PostgreSQL Sink Connector screen, complete the following:

If you’ve already populated your Kafka topics, select the topics you want to connect from the Topics list.

To create a new topic, click +Add new topic.

Step 5: Check the results in PostgreSQL

Verify that new records are being added to the PostgreSQL database.

For more information and examples to use with the Confluent Cloud API for Connect, see the Confluent Cloud API for Connect Usage Examples section.

Tip

When you launch a connector, a Dead Letter Queue topic is automatically created. See View Connector Dead Letter Queue Errors in Confluent Cloud for details.

Using the Confluent CLI

Complete the following steps to set up and run the connector using the Confluent CLI.

Note

Make sure you have all your prerequisites completed.

Step 1: List the available connectors

Enter the following command to list available connectors:

confluent connect plugin list

Step 2: List the connector configuration properties

Enter the following command to show the connector configuration properties:

confluent connect plugin describe <connector-plugin-name>

The command output shows the required and optional configuration properties.

Step 3: Create the connector configuration file

Create a JSON file that contains the connector configuration properties. The following example shows required and optional connector properties:

{
  "connector.class": "PostgresSink",
  "name": "PostgresSinkConnector_0",
  "input.data.format": "AVRO",
  "kafka.auth.mode": "KAFKA_API_KEY",
  "kafka.api.key": "****************",
  "kafka.api.secret": "****************************************************************",
  "connection.host": "database-4.<host-id>.us-east-2.rds.amazonaws.com",
  "connection.port": "5432",
  "connection.user": "postgres",
  "connection.password": "**************",
  "db.name": "postgres",
  "topics": "postgresql_ratings",
  "insert.mode": "UPSERT",
  "db.timezone": "UTC",
  "auto.create": "true",
  "auto.evolve": "true",
  "pk.mode": "record_value",
  "pk.fields": "user_id",
  "tasks.max": "1"
}

Note the following property definitions. See the PostgreSQL Sink configuration properties for additional property values and definitions.

  • "connector.class": Identifies the connector plugin name.
  • "name": Sets a name for your new connector.
  • "kafka.auth.mode": Identifies the connector authentication mode you want to use. There are two options: SERVICE_ACCOUNT or KAFKA_API_KEY (the default). To use an API key and secret, specify the configuration properties kafka.api.key and kafka.api.secret, as shown in the example configuration (above). To use a service account, specify the Resource ID in the property kafka.service.account.id=<service-account-resource-ID>. To list the available service account resource IDs, use the following command:

    confluent iam service-account list
    

    For example:

    confluent iam service-account list
    
       Id     | Resource ID |       Name        |    Description
    +---------+-------------+-------------------+-------------------
       123456 | sa-l1r23m   | sa-1              | Service account 1
       789101 | sa-l4d56p   | sa-2              | Service account 2
    
  • "input.data.format": Sets the input Kafka record value format (data coming from the Kafka topic). Valid entries are AVRO, JSON_SR (JSON Schema), or PROTOBUF. You must have Confluent Cloud Schema Registry configured if using a schema-based message format.

  • "input.key.format": Sets the input record key format (data coming from the Kafka topic). Valid entries are AVRO, JSON_SR (JSON Schema), PROTOBUF, or STRING. You must have Confluent Cloud Schema Registry configured if using a schema-based message format.

  • "delete.on.null": Whether to treat null record values as deletes. Defaults to false. Requires pk.mode to be record_key. Defaults to false.

  • "topics": Identifies the topic name or a comma-separated list of topic names.

  • "insert.mode": Enter one of the following modes:

    • INSERT: Use the standard INSERT row function. An error occurs if the row already exists in the table.
    • UPSERT: This mode is similar to INSERT. However, if the row already exists, the UPSERT function overwrites column values with the new values provided.
  • db.timezone: Name of the time zone the connector uses when inserting time-based values. Defaults to UTC.

  • "auto.create" (tables) and "auto-evolve" (columns): (Optional) Sets whether to automatically create tables or columns if they are missing relative to the input record schema. If not entered in the configuration, both default to false. When``auto.create`` is set to true, the connector creates a table name using ${topic} (that is, the Kafka topic name). For more information, see Table names and Kafka topic names and the PostgreSQL Sink configuration properties.

  • "pk.mode": Supported modes are listed below:

    • kafka: Kafka coordinates are used as the primary key. Must be used with the PK Fields.
    • none: No primary keys used.
    • record_key: Fields from the record key are used. May be a primitive or a struct.
    • record_value: Fields from the Kafka record value are used. Must be a struct type.
  • "pk.fields": A list of comma-separated primary key field names. The runtime interpretation of this property depends on the pk.mode selected. Options are listed below:

    • kafka: Must be three values representing the Kafka coordinates. If left empty, the coordinates default to __connect_topic,__connect_partition,__connect_offset.
    • none: PK Fields not used.
    • record_key: If left empty, all fields from the key struct are used. Otherwise, this is used to extract the fields in the property. A single field name must be configured for a primitive key.
    • record_value: Used to extract fields from the record value. If left empty, all fields from the value struct are used.
  • "tasks.max": Maximum number of tasks the connector can run. See Confluent Cloud connector limitations for additional task information.

Single Message Transforms: See the Single Message Transforms (SMT) documentation for details about adding SMTs using the CLI.

See Configuration Properties for all property values and definitions.

Step 4: Load the configuration file and create the connector

Enter the following command to load the configuration and start the connector:

confluent connect cluster create --config-file <file-name>.json

For example:

confluent connect cluster create --config-file postgresql-sink-config.json

Example output:

Created connector PostgresSinkConnector_0 lcc-ix4dl

Step 5: Check the connector status

Enter the following command to check the connector status:

confluent connect cluster list

Example output:

ID          |       Name               | Status  | Type
+-----------+--------------------------+---------+------+
lcc-ix4dl   | PostgresSinkConnector_0  | RUNNING | sink

Step 6: Check the results in PostgreSQL.

Verify that new records are being added to the PostgreSQL database.

For more information and examples to use with the Confluent Cloud API for Connect, see the Confluent Cloud API for Connect Usage Examples section.

Tip

When you launch a connector, a Dead Letter Queue topic is automatically created. See View Connector Dead Letter Queue Errors in Confluent Cloud for details.

Configuration Properties

Use the following configuration properties with the fully-managed connector. For self-managed connector property definitions and other details, see the connector docs in Self-managed connectors for Confluent Platform.

Which topics do you want to get data from?

topics

Identifies the topic name or a comma-separated list of topic names.

  • Type: list
  • Importance: high

Schema Config

schema.context.name

Add a schema context name. A schema context represents an independent scope in Schema Registry. It is a separate sub-schema tied to topics in different Kafka clusters that share the same Schema Registry instance. If not used, the connector uses the default schema configured for Schema Registry in your Confluent Cloud environment.

  • Type: string
  • Default: default
  • Importance: medium

Input messages

input.data.format

Sets the input Kafka record value format. Valid entries are AVRO, JSON_SR, or PROTOBUF. Note that you need to have Confluent Cloud Schema Registry configured if using a schema-based message format like AVRO, JSON_SR, and PROTOBUF.

  • Type: string
  • Importance: high
input.key.format

Sets the input Kafka record key format. This need to be set to a proper format if using pk.mode=record_key. Valid entries are AVRO, JSON_SR, PROTOBUF, STRING. Note that you need to have Confluent Cloud Schema Registry configured if using a schema-based message format like AVRO, JSON_SR, and PROTOBUF.

  • Type: string
  • Importance: high
delete.enabled

Whether to treat null record values as deletes. Requires pk.mode to be record_key.

  • Type: boolean
  • Default: false
  • Importance: low

How should we connect to your data?

name

Sets a name for your connector.

  • Type: string
  • Valid Values: A string at most 64 characters long
  • Importance: high

Kafka Cluster credentials

kafka.auth.mode

Kafka Authentication mode. It can be one of KAFKA_API_KEY or SERVICE_ACCOUNT. It defaults to KAFKA_API_KEY mode.

  • Type: string
  • Default: KAFKA_API_KEY
  • Valid Values: KAFKA_API_KEY, SERVICE_ACCOUNT
  • Importance: high
kafka.api.key

Kafka API Key. Required when kafka.auth.mode==KAFKA_API_KEY.

  • Type: password
  • Importance: high
kafka.service.account.id

The Service Account that will be used to generate the API keys to communicate with Kafka Cluster.

  • Type: string
  • Importance: high
kafka.api.secret

Secret associated with Kafka API key. Required when kafka.auth.mode==KAFKA_API_KEY.

  • Type: password
  • Importance: high

How should we connect to your database?

connection.host

Depending on the service environment, certain network access limitations may exist. Make sure the connector can reach your service. Do not include jdbc:xxxx:// in the connection hostname property (e.g. database-1.abc234ec2.us-west.rds.amazonaws.com).

  • Type: string
  • Importance: high
connection.port

JDBC connection port.

  • Type: int
  • Valid Values: [0,…,65535]
  • Importance: high
connection.user

JDBC connection user.

  • Type: string
  • Importance: high
connection.password

JDBC connection password.

  • Type: password
  • Importance: high
db.name

JDBC database name.

  • Type: string
  • Importance: high
ssl.mode

What SSL mode should we use to connect to your database. prefer and require allows for the connection to be encrypted but does not do certificate validation on the server. verify-ca and verify-full require a file containing SSL CA certificate to be provided. The server’s certificate will be verified to be signed by one of these authorities.`verify-ca` will verify that the server certificate is issued by a trusted CA. verify-full will verify that the server certificate is issued by a trusted CA and that the server hostname matches that in the certificate. Client authentication is not performed.

  • Type: string
  • Default: prefer
  • Importance: high
ssl.rootcertfile

The server root cert file used for certificate validation. Only required if using verify-ca or verify-full ssl mode.

  • Type: password
  • Default: [hidden]
  • Importance: low

Database details

insert.mode

The insertion mode to use. INSERT uses the standard INSERT row function. An error occurs if the row already exists in the table; UPSERT mode is similar to INSERT. However, if the row already exists, the UPSERT function overwrites column values with the new values provided.

  • Type: string
  • Default: INSERT
  • Importance: high
table.name.format

A format string for the destination table name, which may contain ${topic} as a placeholder for the originating topic name.

For example, kafka_${topic} for the topic ‘orders’ will map to the table name ‘kafka_orders’.

  • Type: string
  • Default: ${topic}
  • Importance: medium
table.types

The comma-separated types of database tables to which the sink connector can write. By default this is TABLE, but any combination of TABLE, PARTITIONED TABLE and VIEW is allowed. Not all databases support writing to views, and when they do the sink connector will fail if the view definition does not match the records’ schemas (regardless of auto.evolve).

  • Type: list
  • Default: TABLE
  • Importance: low
fields.whitelist

List of comma-separated record value field names. If empty, all fields from the record value are utilized, otherwise used to filter to the desired fields.

  • Type: list
  • Importance: medium
db.timezone

Name of the JDBC timezone used in the connector when querying with time-based criteria. Defaults to UTC.

  • Type: string
  • Default: UTC
  • Importance: medium
date.timezone

Name of the JDBC timezone that should be used in the connector when inserting DATE type values. Defaults to DB_TIMEZONE that uses the timezone set for db.timzeone configuration (to maintain backward compatibility). It is recommended to set this to UTC to avoid conversion for DATE type values.

  • Type: string
  • Default: DB_TIMEZONE
  • Valid Values: DB_TIMEZONE, UTC
  • Importance: medium

Primary Key

pk.mode

The primary key mode, also refer to pk.fields documentation for interplay. Supported modes are:

none: No keys utilized.

kafka: Apache Kafka® coordinates are used as the PK.

record_value: Field(s) from the record value are used, which must be a struct.

record_key: Field(s) from the record key are used, which must be a struct.

  • Type: string
  • Valid Values: kafka, none, record_key, record_value
  • Importance: high
pk.fields

List of comma-separated primary key field names. The runtime interpretation of this config depends on the pk.mode:

none: Ignored as no fields are used as primary key in this mode.

kafka: Must be a trio representing the Kafka coordinates, defaults to __connect_topic,__connect_partition,__connect_offset if empty.

record_value: If empty, all fields from the value struct will be used, otherwise used to extract the desired fields.

  • Type: list
  • Importance: high

SQL/DDL Support

auto.create

Whether to automatically create the destination table if it is missing.

  • Type: boolean
  • Default: false
  • Importance: medium
auto.evolve

Whether to automatically add columns in the table if they are missing.

  • Type: boolean
  • Default: false
  • Importance: medium
quote.sql.identifiers

When to quote table names, column names, and other identifiers in SQL statements. For backward compatibility, the default is ‘always’.

  • Type: string
  • Default: ALWAYS
  • Valid Values: ALWAYS, NEVER
  • Importance: medium

Connection details

batch.sizes

Maximum number of rows to include in a single batch when polling for new data. This setting can be used to limit the amount of data buffered internally in the connector.

  • Type: int
  • Default: 3000
  • Valid Values: [1,…,5000]
  • Importance: low

Consumer configuration

max.poll.interval.ms

The maximum delay between subsequent consume requests to Kafka. This configuration property may be used to improve the performance of the connector, if the connector cannot send records to the sink system. Defaults to 300000 milliseconds (5 minutes).

  • Type: long
  • Default: 300000 (5 minutes)
  • Valid Values: [60000,…,1800000] for non-dedicated clusters and [60000,…] for dedicated clusters
  • Importance: low
max.poll.records

The maximum number of records to consume from Kafka in a single request. This configuration property may be used to improve the performance of the connector, if the connector cannot send records to the sink system. Defaults to 500 records.

  • Type: long
  • Default: 500
  • Valid Values: [1,…,500] for non-dedicated clusters and [1,…] for dedicated clusters
  • Importance: low

Number of tasks for this connector

tasks.max

Maximum number of tasks for the connector.

  • Type: int
  • Valid Values: [1,…]
  • Importance: high

Next Steps

For an example that shows fully-managed Confluent Cloud connectors in action with Confluent Cloud ksqlDB, see the Cloud ETL Demo. This example also shows how to use Confluent CLI to manage your resources in Confluent Cloud.

../_images/topology.png