Skip to main content

PostgreSQL

ENTERPRISE FEATURE

The features or components discussed in this document are available in TDengine TSDB-Enterprise only. TDengine TSDB-OSS does not include these features or components.

TDengine can continuously publish the results of a subscription query to a single PostgreSQL table. taosX creates a TMQ query topic from the SQL, writes batches to the target table by primary key, and commits the consumer position only after each write succeeds.

Prepare the Environment​

  • Verify that taosd and taosAdapter are running and that taosX is installed with data publishing support.
  • Use PostgreSQL 12 and later. The target database and schema must already exist. taosX does not create either.
  • Set WAL_RETENTION_PERIOD on the source database to a value greater than zero. The source user needs permission to create topics and subscribe. The target user needs permission to write to the table and, if automatic table creation is enabled, to create it.
  • Execution through an agent or via is not supported.

Prepare Data​

Run the following SQL in the taos CLI or taosExplorer to create an example supertable and insert a row. You do not need to create a topic manually.

CREATE DATABASE IF NOT EXISTS dataout_demo VGROUPS 1 WAL_RETENTION_PERIOD 3600;

CREATE STABLE IF NOT EXISTS dataout_demo.meters (
ts TIMESTAMP,
current FLOAT,
voltage INT
) TAGS (site INT);

INSERT INTO dataout_demo.meter01 USING dataout_demo.meters TAGS (1)
VALUES (NOW, 10.5, 220);

Create a PostgreSQL Data Out Task​

In taosExplorer, open Data Out, click Create New Task, enter a task name, and select PostgreSQL as the data target type.

TDengine Subscription​

TDengine subscription settings

  • TDengine Endpoint: for example tmq+ws://root:taosdata@localhost:6041/db. The database in the path is the default database of the subscription SQL.
  • Subscription SQL: a single SELECT query. It follows TDengine query topic rules: query one table, child table or supertable, and project columns, tags, tbname and scalar functions with an optional WHERE. Aggregates, windows, JOIN, subqueries, UNION, DISTINCT, GROUP BY, ORDER BY, LIMIT and virtual tables are not supported.
  • Start Position: earliest includes historical data, latest subscribes only new data. It takes effect only on the first consumption of the consumer group.
  • Consumer Group ID: defaults to the task topic name. Changing it uses a new consumer group and rereads the data.
  • TSDB Data: when enabled, persisted TSDB data is subscribed as well, not only WAL data. Together with the start position it determines what is read on the first start.
Start PositionTSDB DataData read on the first start
earliestonAll persisted historical data from TSDB, then WAL for new data
earliestoffOnly from the earliest position still retained in WAL
latestanyOnly data written after the task starts

For this example, use SELECT ts, tbname, current, voltage FROM dataout_demo.meters. For more about query topics and consumer positions, see Data Subscription.

Connection and Authentication​

Under Connection, enter the host, port (default 5432), and the name of an existing database such as rdb_out. Under Authentication, enter the database user and password.

PostgreSQL connection options

  • Application Name: Optional name for identifying the connection in PostgreSQL.
  • SSL Mode: Choose DISABLE, ALLOW, PREFER, or REQUIRE to match the PostgreSQL server’s TLS configuration.

Target Table​

PostgreSQL target table with a composite primary key

  • Schema: The schema of the target table. Defaults to public.
  • Table: Enter the target table name, such as meters_out.
  • Create Table: If enabled, taosX creates the table when it does not exist. For an existing table, taosX checks compatibility without changing the table definition.
  • Primary Key: Fetch the result columns and select up to 16 columns. The form initially selects the first eligible column. Select ts and tbname as the composite key in this example. If you select only ts, rows from different child tables at the same timestamp can overwrite one another.
  • Timestamp Storage: With Auto, millisecond and microsecond timestamps use a date-time type and nanosecond timestamps use BIGINT. With BIGINT, all timestamps are stored as raw integers.

Advanced​

  • Batch Size: maximum rows written per batch, default 1000.
  • Batch Timeout (ms): maximum wait before a batch is written, default 1000.
  • Write Timeout and Max Retry Time: configurable through DSN parameters, default to 60 and 180 seconds.

Connectivity Check and Preview​

  1. Click Check Connection to check that the query returns a compatible result schema and that the target is reachable. This check does not create a topic. For query-topic restrictions, use the full preview or start the task.
  2. Set Row Count and Wait Time (s) and click Preview Data. The preview returns when it reaches either limit. Review the sample rows, the table creation statement (if a table needs to be created), and the write statement template. Preview does not write to the target database or alter the task’s consumer position.
  3. Click Submit and check the task status in the Data Out task list.

PostgreSQL Data Out preview

DSN Example​

FROM 'tmq+ws://root:password@localhost:6041/dataout_demo?query=SELECT%20ts,%20tbname,%20current,%20voltage%20FROM%20dataout_demo.meters&auto.offset.reset=earliest'
TO 'postgres://writer:password@localhost:5432/rdb_out?schema=public&table=meters_out&primary_key=ts,tbname'

Data publishing parameters for the target DSN:

ParameterDescriptionDefault
tableTarget table name, required—
primary_keyPrimary key columns separated by commas, required—
schemaSchema of the target tablepublic
create_tableWhether to create the table when it does not existtrue
timestamp_typeauto or bigintauto
batch_sizeMaximum rows per batch1000
batch_timeoutMaximum wait before a batch is written, e.g. 1000, 500ms, 2s1s
write_timeoutTimeout of one batch write60s
max_retry_timeTotal retry time for a recoverable error, at most 240 seconds180s

Type Mapping​

When taosX creates the table, it maps result columns as follows:

TDengine typePostgreSQL type
TIMESTAMP (ms, us)TIMESTAMPTZ(3) / TIMESTAMPTZ(6)
TIMESTAMP (ns)BIGINT
BOOLBOOLEAN
TINYINTSMALLINT
SMALLINT / INT / BIGINTsame name
TINYINT UNSIGNEDSMALLINT
SMALLINT UNSIGNEDINTEGER
INT UNSIGNEDBIGINT
BIGINT UNSIGNEDNUMERIC(20,0)
FLOAT / DOUBLEREAL / DOUBLE PRECISION
VARCHAR / NCHARVARCHAR(n)
VARBINARY / GEOMETRYBYTEA
BLOBBYTEA
JSON (tags only)JSONB
DECIMAL / DECIMAL64not supported

Write Semantics​

  • Idempotent writes: rows are written with an UPSERT on the primary key, updating existing rows and inserting new ones. Task restarts, network interruptions and repeated delivery never create duplicate rows or stop the task with a primary key conflict.
  • All columns are written: every result column of a row is written, including columns whose value is NULL. When a column is NULL in TDengine, the target column is written as NULL too.
  • Repeated keys within one batch: only the last value is kept.
  • Deletes are not propagated: data deleted in TDengine is kept in the target table.
  • Tag values: tag values are read as they are in TDengine at consumption time.

Limitations​

  • One subscription SQL and one target table per task. Changing the SQL, the table, the primary key, or the timestamp storage requires a new task.
  • A target table can be written by only one task and should have no other writers.
  • The target table must have a primary key or unique constraint on exactly the configured primary key.
  • DECIMAL output is not supported. Convert it in the subscription SQL, for example with CAST(col AS VARCHAR(64)), which keeps the exact decimal text.
  • Data subject to a task stop or backlog longer than the WAL retention period of the source is skipped. taosX reports a warning in the task activity when it detects this; changing the consumer group ID and restarting resynchronizes all data.
  • Topic columns are fixed at creation, so columns added to the source table later are not synchronized.

Performance and Observability​

Task metrics include messages read, rows written, batches written, retries, write errors, elapsed time of the last write, WAL data gaps, and the consumer progress per vgroup.

Write throughput mainly depends on the target database and the row width, and can be improved by tuning the batch size and batch timeout.