DBTrail

Types

How each PostgreSQL type is captured, recovered and read in SQL on the copy, the names the copy reads as its own words, and extensions.

DBTrail keeps every value exactly as PostgreSQL writes it, so an undo puts back exactly what was there. On the copy, a few types read a little differently. This page says which.

Copy and paste

This lists the types your captured tables use. Look each one up in how each type reads in SQL on the copy:

psql <<'SQL'
SELECT format_type(a.atttypid, a.atttypmod) AS type, count(*) AS columns
FROM pg_publication_tables p
JOIN pg_namespace n ON n.nspname = p.schemaname
JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = p.tablename
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
WHERE p.pubname = 'bintrail_pub'
GROUP BY 1 ORDER BY 2 DESC, 1;
SQL

What most often matters:

  • A column named like a word of the copy's SQL (at, by, show, pivot and a few more) needs double quotes: "at".
  • json, jsonb, varchar(n), char(n) and enums come back as text (Connect a client).
  • A division or an avg() on the copy has 16 decimals. round(a / b, k) gives PostgreSQL's exact text (why).
  • money depends on the server's locale: undo into a database with the same lc_monetary.

In detail

DBTrail captures every value as the text PostgreSQL writes for it, so recovery puts back exactly what was there. This page lists the types tested end to end, how each one reads in SQL on the copy, the column and table names the copy reads as its own words, and what holds for extension types.

In SQL on the copy, in short

Numbers, dates, booleans, uuid, arrays, time and interval read as their types, not as text. Statements run by PostgreSQL's rules where they change the answer: NULL sorts last ascending, two integers divide to an integer, and text compares with case. What still differs, and how each type reads: how each type reads in SQL on the copy.

infinity and -infinity in date and timestamp columns read as those words, as on the source.

A table or column named like a word of the copy's own SQL is refused with a syntax error when written without quotes, though PostgreSQL takes it: columns at, by, pivot, qualify, show, describe, glob, lambda and a few more, tables pivot, qualify, show and a few more. Write the name in double quotes ("at"), the table with its schema (public.pivot), or the column with its table (t.at), and the answer is PostgreSQL's. On the PostgreSQL port, qualify, asof, anti, semi and positional send the statement to your PostgreSQL when the server has a forwarding user. Every name: names the copy reads as its own words.

Type support

bintrail-pg captures every value as its PostgreSQL text representation (the pgoutput text format) and, on recovery, regenerates it as a standard-conforming quoted literal that the target column's input function coerces back. Because the value is stored verbatim as text: never reparsed through a numeric type in the index, the numeric-via-float64 precision class cannot occur here. (A snapshot file may store some columns as their type, read back as the same text.)

The following types are round-trip tested two ways: insert → capture → index → recover → re-execute the reversal against live PostgreSQL, asserting the column's canonical ::text is byte-for-byte identical (TestOne_PGTypeRoundTripMatrix), and through the baseline+delta reconstruct fold under deliberately skewed session GUCs (TestOne_PGTypeMatrixThroughReconstructFold), in internal/pgstreamrun, run across the PG 15/16/17/18 CI matrix:

CategoryTypesNotes
Integersmallint, integer, bigintexact
Arbitrary precisionnumeric (decimal is its alias)full precision and scale preserved: values > 2^53 and trailing zeros (1.50) survive
Floating pointreal, double precisionrendered under pinned extra_float_digits=3 (shortest-precise) on both capture and baseline sessions
Charactertext, varchar(n), char(n)single quotes and backslashes escaped correctly (standard_conforming_strings); char(n) round-trips (trailing blanks are insignificant in bpchar: PostgreSQL trims them on cast to text)
Booleanboolean
UUIDuuid
Binarybyteahex (\x…) form: guaranteed by the pinned bytea_output=hex, no longer default-dependent
JSONjson, jsonbjsonb tested with an embedded quote
Date / timedate, time, timestamp, timestamptz, intervalrendered under pinned TimeZone=UTC / DateStyle=ISO / IntervalStyle=postgres on both capture and baseline sessions: no longer dependent on server defaults
Networkinet, cidr, macaddr
Bit stringbit(n), varbit
Rangeint4rangethe other built-in range types share the same text mechanism
Arrayinteger[], text[]element quoting/escaping (e.g. a comma inside an element) preserved
Geometricpoint
Enumuser ENUM typesrecovered by label: the target must declare the same enum type
Compositeuser-defined composite typesfield quoting preserved (embedded comma, doubled quote); the target must declare the same composite type
Moneymoneyround-trips, but its text form is locale-dependent ($-prefixed); recover into a target with the same lc_monetary

The generated reversal SQL is PostgreSQL dialect (double-quoted identifiers, standard-conforming string escaping, a SET LOCAL standard_conforming_strings = on guard): the dialect is selected automatically from the source recorded in the index, so bintrail-pg recover, the web interface, and the MCP server all emit valid PostgreSQL for a PostgreSQL source.

Extension types (PostGIS geometry/geography and pgvector vector) are round-trip tested the same insert → capture → recover → re-execute way, in dedicated CI cells running extension-bearing images (TestOne_PGExtensionTypeRoundTripMatrix); see Extensions and custom types below.

Untested / best-effort: hstore and other extension-provided types are covered under Extensions and custom types below. Range types beyond int4range, multirange, geometric types beyond point, arrays beyond the tested integer[]/text[] (multi-dimensional, NULL-containing) are not yet in the round-trip suite: they are captured as text and are expected to coerce, but verify your own round-trip.

How each type reads in SQL on the copy

A snapshot of a PostgreSQL source holds each value as the text PostgreSQL wrote, which is what keeps recovery exact, or, for some columns, as the value itself (see "Columns a snapshot stores as their type" below); either way it reads back as the same text. SQL on the copy (the web interface's SQL page, bintrail views, the views file inside each snapshot) reads each column as the type the table declares, in the table's own column order, from the shape the snapshot records beside the data. Nothing is rewritten: a snapshot that records the shape reads this way whichever version took it. One taken before the shape was recorded reads as text, in alphabetical column order, until the next full snapshot; the log names such tables once.

PostgreSQL typeReads as
smallint, integer, bigintwhole numbers of the same width
numeric(p,s) up to 38 digitsexact decimal with that precision and scale
numeric with no precisionexact decimal with 20 digits before the point and 18 after
real, double precisionfloating point, NaN and Infinity included
booleanboolean
date, timestamp, timestamptzdate and timestamps; infinity included
time, timetztime of day, with its offset for timetz
intervalinterval, with its months, days and time kept apart as PostgreSQL keeps them
uuiduuid
byteabytes
text, varchar(n), char(n)text compared byte by byte, so 'Lima' is not 'lima'
an array of any type above but bytea, numeric with no precision, time, timetz and interval (text[], integer[], date[], ...)a list of that type: labels[1] is the first element, 'red' = ANY(labels) works
everything elsethe text PostgreSQL wrote

"Everything else" is json and jsonb, enums, domains, ranges, a numeric wider than 38 digits, with a negative scale or with a scale above its precision, every extension type, and an array of any of these, of bytea, of numeric with no precision, of time, timetz or interval. ->> reads a json column as it is; an array left as text is the text {a,b}, so labels[1] is its first character, not its first element. A column left as text still compares byte by byte. Each view names the columns it left as text.

Two kinds of table are read as text throughout: one with two columns whose names differ only in case ("Id" and "id"), which the copy cannot tell apart, and any table in a views file that follows later snapshots (bintrail views without --pin-snapshot), because a type written into such a file would outlive a change of the column's type at the source.

A value its type here cannot hold fails the statement that reads it, with an error that says so. It is never rounded and never read as NULL:

  • NaN or Infinity in a numeric column.
  • A numeric with no precision holding more than 18 decimals or more than 20 digits before the point.
  • A date, timestamp or timestamptz before the common era, or beyond the years the copy's types reach.
  • A bytea not written as \x and hex digits.
  • The time 24:00:00, which the copy would show as midnight. A timetz of 24:00:00 reads as it is.
  • An interval of infinity (PostgreSQL 17).
  • An array of more than one dimension ('{{1,2},{3,4}}'), or one whose first element is not numbered 1 ('[0:1]={1,2}').

The elements of a text array compare as the session compares text. On the SQL card of a PostgreSQL server that is byte by byte. In a DuckDB of your own with default_collation = 'nocase', labels[1] = 'RED' matches red, where a text column of the same views does not.

A statement that does not read that column is not affected, and neither is recovery, which works from the text.

In the console's SQL card and the sql tool, a statement on a PostgreSQL server runs by PostgreSQL's rules where the two engines differ in silence: NULL is the largest value (last in ORDER BY x, first in ORDER BY x DESC), / between two integers gives an integer cut toward zero (9 / 2 is 4, -9 / 2 is -4), and text compares byte by byte ('a' = 'A' is false). A views file you run in a DuckDB of your own runs under that DuckDB's settings; these three lines give it the same rules:

SET default_null_order = 'nulls_last_on_asc_first_on_desc';
SET integer_division = true;
SET default_collation = '';

Three things still answer differently from PostgreSQL, with no error:

  • A division by zero is NULL, where PostgreSQL fails the statement.
  • Text sorts by bytes. PostgreSQL sorts by the collation the database was created with, which for anything but C orders letters differently.
  • char(n) compares with its padding, where PostgreSQL ignores trailing blanks. On the PostgreSQL port such a statement is not answered by the copy: it goes to the source, or is refused where nothing is sent there (which side answers). In the SQL card, the sql tool and a views file it is still the copy's answer.

A numeric with no precision prints with all 18 decimals (12345.678 as 12345.678000000000000000); it compares, sorts and sums as the same number.

A CASE, COALESCE, GREATEST or LEAST whose values are numbers of different scales can print more zeros on the copy than on PostgreSQL, for the same value: PostgreSQL writes each value with its own decimals, the copy gives them all one type and writes every one with that type's. Over a numeric(12,2) column, coalesce(sum(amount), 0) of no rows is 0 on PostgreSQL and 0.00 on the copy, and CASE WHEN ... THEN amount ELSE 0 END writes 0.00 for the rows that take the 0. The number is the same; a client that reads it as a number sees no difference. Writing the other value with the column's decimals (coalesce(sum(amount), 0.00)) makes both sides print the same. (Around a round() the port does check this, value by value, and sends a statement whose decimals would differ to the source.)

Columns a snapshot stores as their type

Reading text costs most of what a report on the copy spends: every read turns each value back into its type. So a snapshot stores these columns as the value itself instead of as text:

  • smallint, integer, bigint and oid
  • date, infinity and -infinity included
  • uuid
  • numeric(p,s) up to 38 digits, with a scale below its precision

The views read such a column with the same type and the same values as from text, so nothing changes in what a statement answers. The files are smaller and the reads faster. Every reader that needs PostgreSQL's text (recovery, reconstruct, refreshes, a views file that follows later snapshots) gets exactly the text the value was written from.

From 0.155.0 the primary key's smallint, integer and bigint columns are stored as numbers too. A filter or a join on such a key can then skip the parts of the file that cannot hold the values it looks for: on a 24-million-row table, a filter on one key value went from 582 ms to 12 ms. A key of text and a number, such as (k text, id bigint), stores id as a number and keeps k as text.

Some columns stay text all the same:

  • the columns of the primary key of any other type (uuid, numeric, date, text...);
  • every column of a table with no primary key;
  • every column of a table that holds a value that would not read back as the same text, such as a date before the common era or NaN in a numeric. The table is then written as text, as before, and the log says which column held such a value;
  • numeric(p,p) (no digit before the point) and every type not listed above.

A snapshot can hold tables of both kinds, and old snapshots, written as text, read as before. A table that a refresh writes again in full is written with the same columns typed as a new snapshot of it, or as text when writing it typed fails, which the log and the refresh's outcome say. Setting BINTRAIL_PG_TYPED_COPY=0 (or false, no, off) stores every column as text.

Only this version and later read such a file as before. After upgrading, write again any views file that follows current or the newest snapshot (bintrail views without --pin-snapshot): one written by an older version reads the stored columns as their type. A DBTrail older than this one must not read the snapshots this one writes; until every reader is upgraded, set BINTRAIL_PG_TYPED_COPY=0 where snapshots are taken.

Going back to 0.154.1 or earlier. Those versions refuse a file that stores its key as a number, and say to update DBTrail or take a new snapshot. So every table whose primary key has a smallint, integer or bigint column cannot be read there until that version takes a new snapshot. To avoid it, take a full read with BINTRAIL_PG_TYPED_COPY=0 before going back; an update with the switch off is not enough, as it keeps the table's file as it is.


Names the copy reads as its own words

The copy's SQL has words PostgreSQL does not, and a table or column with one of them as its name is refused by the copy with a syntax error when the name is written without quotes. PostgreSQL takes the same statement. Measured against a real PostgreSQL with the comparison harness (internal/pgcompare), 169 statements: 73 refused, none answered differently.

  • Tables named pivot, unpivot, qualify, asof, anti, show, describe or summarize: SELECT id, v FROM pivot is refused, and so is FROM pivot AS t.
  • Columns named at, by, anti, semi, asof, positional, qualify, pivot, pivot_longer, pivot_wider, unpivot, unpack, glob, lambda, show, describe or summarize: SELECT id, at FROM t, WHERE describe IS NOT NULL and sum(by) are refused.

Written another way, each of them answers as PostgreSQL does: the name in double quotes ("at", FROM "pivot"), the table with its schema (FROM public.pivot), or the column with its table (t.at). SELECT * is not affected.

On the PostgreSQL port each of these names, written without quotes where a name stands (a select item, a table after FROM or JOIN, an operand), is quoted before the copy reads it, with or without a forwarding user, so the statement answers as PostgreSQL does. Where PostgreSQL reads the word as its own syntax (GROUP BY, ORDER BY, PARTITION BY, AT TIME ZONE, SHOW at the start) it is left alone, and so is the copy's own syntax that PostgreSQL refuses (QUALIFY as a clause, ASOF JOIN): through a forwarding user that goes to your PostgreSQL, which refuses it. A name the port does not quote (an alias written right after a table, FROM t at) still gets the copy's syntax error (SQLSTATE 42601), or goes to your PostgreSQL through a forwarding user.

Extensions and custom types

  • bintrail installs nothing in your database. Capture is via the built-in pgoutput plugin only: no output plugin, no CREATE EXTENSION, no event trigger. This is a deliberate red line, and it is what lets bintrail-pg work against managed PostgreSQL (which forbids custom extensions).
  • PostGIS is round-trip tested. geometry and geography columns stream as hex-EWKB, which embeds the SRID and round-trips losslessly back into PostgreSQL: proven empirically by TestOne_PGExtensionTypeRoundTripMatrix against the postgis/postgis image in CI. The target just needs PostGIS installed. (REPLICA IDENTITY FULL is required, as for any table: see Prepare, step 3.)
  • pgvector is round-trip tested. vector columns stream as their bracketed text form ([0.5,-1.25,3.75]) and round-trip byte-for-byte: same test, against the pgvector/pgvector image in CI. The target needs the extension installed.
  • Other extension/custom types (hstore, …) are captured as their text representation. Recovery into a target that has the same extension installed is expected to work; treat exotic types as best-effort and test your round-trip. (Enums, ranges and user-defined composite types are round-trip tested: see the Type support matrix.)
  • TimescaleDB hypertables are out of scope. Logical decoding emits the underlying chunk tables (_timescaledb_internal._hyper_*), not the hypertable, so a hypertable is not captured coherently in this release. bintrail-pg detects a chunk relation in the stream and warns once (so you are never silently indexing raw chunks under their physical names), but it does not synthesize the logical hypertable.

On this page