Skip to content
littlebit labs
Product

Minimal Core

Auto API Custom API MCP Databases

By database

Postgres MySQL and MariaDB ClickHouse

Compare

vs Supabase vs Data API builder vs PostgREST vs Hasura vs DreamFactory

Built on Minimal Core

Chat Studio API Bay All products
Pricing Docs Company
Self-host Start Free, Always

Minimal Core

Auto API Custom API MCP Databases

More

All products Pricing Docs Company Self-host Start Free, Always
HACKING DBDRVOL. I An acorn woodpecker perched on a branch Inside dbdr
1A Tutorial Introduction
Getting started The first dump Adding the data A faster way Between engines What we have seen Exercises
2The Shape of the Program
The source tree Building and testing The life of a run Who opens the file Output naming The configuration Exercises
3The Dumper Interface
The interface The registry Two ways to hold a connection Contracts the signatures don't show The stub Exercises
4Entities and Dependency Order
What an entity is Introspection in ClickHouse Introspection in Postgres Ordering Which entities carry rows Exercises
5Moving Rows
Why not one query The SQL path: a cursor on the key The native path: ranges fixed in advance The Postgres native path: splicing COPY streams The portable path Exercises
6The Portable Format
The schema Mapping types Defaults and keys Origin markers The row format Canonical values Adding a Kind Exercises
7Restore
Choosing a path Replaying SQL Loading native data Loading portable data Finalize Sequences after a restore Safety defaults Exercises
8Testing and Debugging
What the tests cover What the tests don't cover Testing the retry path Reading a dump Debugging against a real server Exercises
9Adding a Backend
The plan What not to change Before you send it Exercises
AReference Manual
A.1 Commands A.2 The password A.2a Encryption A.3 Dump flags A.4 Restore flags A.5 list-databases flags A.6 Artifacts and their names A.7 What each format includes A.8 SQL dump layout (ClickHouse) A.9 The .dbschema format A.10 The .dbdata format A.11 Type mapping A.12 Portable defaults A.13 Exit status
BPackage Reference
B.1 internal/config B.2 internal/dumper B.3 internal/schema B.4 internal/portable B.5 internal/compress B.6 cmd/dbdr B.7 Backend internals worth knowing
Docs/Hacking dbdr/Vol. I

Inside dbdr

How dbdr works inside: a first dump and restore, the shape of the program, the dumper interface, dependency order, moving rows, the portable format, restore, testing, and adding a backend.

11 CHAPTERS · 11,729 WORDS · 8 DIAGRAMS

Vol. IVol. II

1A Tutorial Introduction

The only way to learn a new program is to run it. So before we look at any code, we will dump a database, restore it somewhere else, and then do the same thing between two different engines. The rest of the book explains what happened.

Getting started

You need Go, a ClickHouse server, and a Postgres server. A container for each is the easiest way to get them:

bash
docker run -d --name ch -p 9000:9000 -p 8123:8123 clickhouse/clickhouse-server
docker run -d --name pg -p 5432:5432 -e POSTGRES_PASSWORD=pg postgres

Build the program from the root of the repository:

bash
make build

This leaves a binary in dist/. For the rest of this chapter we will call it dbdr and assume it is on your PATH. Check that it runs:

$ dbdr --version
dbdr dev (commit none, built unknown)

A plain go build prints exactly that. A binary built by scripts/build.sh stamps in the tag, commit and build time instead.

Now load the example database. shop-database.sql, next to this chapter, holds the same small bakery twice: once for ClickHouse and once for Postgres. Load the first half into ClickHouse and the second half into Postgres.

bash
clickhouse client --multiquery < shop-clickhouse.sql
psql -U postgres -f shop-postgres.sql

The ClickHouse half has four products, 250,000 orders, a table called daily_units that a materialized view keeps up to date, and a plain view called big_orders. Keep those in mind, because each of them will cause dbdr a different kind of trouble.

dbdr never takes a password on the command line. It reads one from the environment, or prompts for it:

bash
export DBDR_PASSWORD=...

It also encrypts every connection by default, and verifies the server's certificate. The two containers above have no TLS, so every command in this chapter adds --tls=disable, and dbdr warns each time that it's sending everything in plain text. That's fine for containers on your own machine. Across any network you don't control, leave TLS on. The README's "Encryption in transit" section explains --tls-ca for servers with their own CA. With --tls=disable, ClickHouse's default ports are the plain ones the containers publish, 9000 and 8123. With TLS they would be 9440 and 8443.

The first dump

The first thing to find out is what's on the server:

$ dbdr list-databases -un=default --tls=disable
warning: --tls=disable: the password and all data cross the network in plain text
connecting to clickhouse at localhost:9000 as "default"...
shop

Progress goes to the standard error and the answer goes to the standard output, so dbdr list-databases | wc -l counts databases and nothing else. system, information_schema and default are left out on purpose.

Now dump the structure of shop, with no data:

$ dbdr -db=shop -un=default --only=schema -o=shop_schema.sql --tls=disable
warning: --tls=disable: the password and all data cross the network in plain text
connecting to clickhouse at localhost:9000 as "default"...
dumping database "shop" -> shop_schema.sql... done in 5ms

and look at what it wrote:

sql
-- dbdr: ClickHouse dump of database "shop"
-- generated: 2026-11-27T08:45:41+05:30
-- entities: 5
-- mode: schema-only
-- mode: no DROP statements (see --add-drop-statement in the README).
-- CREATE will fail loudly on any object that already exists at the
-- destination, rather than silently replacing it.

CREATE DATABASE IF NOT EXISTS `shop`;

-- ----------------------------
-- Table: shop.daily_units (SummingMergeTree)
-- ----------------------------
CREATE TABLE shop.daily_units (`day` Date, `units` UInt64) ENGINE = SummingMergeTree ORDER BY day ...

-- ----------------------------
-- Table: shop.orders (MergeTree)
-- ----------------------------
CREATE TABLE shop.orders (`id` UInt64, ...) ENGINE = MergeTree ORDER BY (product_id, order_date, id) ...

-- ----------------------------
-- View: shop.big_orders (View)
-- ----------------------------
CREATE VIEW shop.big_orders (...) AS SELECT * FROM shop.orders WHERE qty >= 10;

-- ----------------------------
-- Materialized View: shop.daily_units_mv (MaterializedView)
-- ----------------------------
CREATE MATERIALIZED VIEW shop.daily_units_mv TO shop.daily_units (...) AS SELECT ...

-- ----------------------------
-- Table: shop.products (MergeTree)
-- ----------------------------
CREATE TABLE shop.products (...) ENGINE = MergeTree ORDER BY id ...

The order matters. big_orders reads from orders, so orders must exist first. daily_units_mv reads from orders and writes to daily_units, so both of those must come before it. products depends on nothing and nothing depends on it, so it falls to the end in alphabetical order. Working out this order is the first thing dbdr does, and Chapter 4 shows how.

Adding the data

Drop --only=schema and you get data as well:

$ dbdr -db=shop -un=default --split-insert-size=10000 -o=shop.sql --tls=disable
warning: --tls=disable: the password and all data cross the network in plain text
connecting to clickhouse at localhost:9000 as "default"...
dumping database "shop" -> shop.sql... done in 266ms
$ grep -c '^INSERT' shop.sql
26

Twenty-five statements of up to 10,000 rows each cover orders, and one covers products. Nothing was written for daily_units. That is deliberate, and it's the most important idea in this chapter. When the file is replayed, every CREATE runs before any INSERT, so the materialized view already exists by the time the orders arrive, and it rebuilds daily_units exactly as it built it the first time. Replay the file into a copy of the database and count:

orders    250000
units     1749985

which matches the source exactly. Had dbdr dumped daily_units as well, every unit would have been counted twice.

--split-insert-size matters more than it looks. Without it every row becomes its own INSERT, and ClickHouse turns each INSERT into a new part on disk. The same 250,000 rows as single-row statements replay more than a thousand times slower. Always batch.

A faster way

Text is a slow way to move numbers. --format=native asks the server for its own binary format and copies the bytes straight into a zip, without decoding them:

$ dbdr -db=shop -un=default --only=data -fmt=native -o=data.zip --tls=disable
warning: --tls=disable: the password and all data cross the network in plain text
connecting to clickhouse at localhost:9000 as "default"...
dumping database "shop" (native) -> data.zip...
  shop.orders: computing 1 range boundaries on product_id... done in 3ms
  shop.orders: range 1/2... done in 18ms
  shop.orders: range 2/2... done in 16ms
 2 table(s) in 43ms
done in 43ms (2 table(s) total)
$ unzip -l data.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
  5310677  11-27-2026 08:49   shop/orders.native
      142  11-27-2026 08:49   shop/products.native

A native file holds data only, which is why --only=data is required. You pair it with the schema dump from before. To restore both into a second server:

$ dbdr restore -un=default -hn=target -s=shop_schema.sql -d=data.zip --tls=disable
warning: --tls=disable: the password and all data cross the network in plain text
connecting to clickhouse at target:9000 as "default"...
applying schema from shop_schema.sql (6 statement(s))...
schema applied in 9ms
loading 2 table(s) from data.zip...
loading shop.orders... done in 92ms
loading shop.products... done in 55ms
done in 147ms

Count on the target and you get the same 250,000 orders and the same 1,749,985 units. The materialized view rebuilt its table during the load, just as it did when the SQL was replayed.

Between engines

The native format belongs to one engine. To move data between engines, dbdr has a third format of its own, portable. The schema goes to one small JSON file and the rows go to a compact binary file:

$ dbdr -db=shop -un=default --only=schema -fmt=portable -o=shop.dbschema --tls=disable
$ dbdr -db=shop -un=default --only=data -fmt=portable -o=shop.dbdata --tls=disable
warning: --tls=disable: the password and all data cross the network in plain text
connecting to clickhouse at localhost:9000 as "default"...
dumping database "shop" (portable) -> shop.dbdata...
  shop.daily_units: 250 row(s)
  shop.orders: 250000 row(s) -> shop_orders.dbdata
  shop.products: 4 row(s)
  2 file(s) in 172ms

Neither file mentions Postgres. The destination is chosen when you restore, not when you dump:

$ DBDR_PASSWORD=pg dbdr restore -e=postgres -un=postgres -s=shop.dbschema -d=shop.dbdata --tls=disable
warning: --tls=disable: the password and all data cross the network in plain text
connecting to postgres at localhost:5432 as "postgres"...
applying portable schema from shop.dbschema (database "shop", 3 table(s)) -> postgres...
schema applied in 9ms
loading portable data (2 file(s)) for database "shop"...
  shop.dbdata...
  daily_units: 250 row(s)
  products: 4 row(s)
  shop_orders.dbdata...
  orders: 250000 row(s)
done in 579ms

As with every command, the default port follows the engine, so a Postgres destination means 5432 unless you pass -pn.

Now look at the table Postgres was given:

$ psql -d shop -c '\d orders'
 id         | numeric(20,0) | not null
 order_date | date          | not null
 product_id | bigint        | not null
 qty        | integer       | not null
 customer   | text          |

ClickHouse's UInt64 has no Postgres equivalent, because bigint is signed and too small, so it became numeric(20,0). That loses nothing in Postgres, but it would make the next dump wrong. A later dump of this table back to ClickHouse would see a decimal and produce Decimal(20,0). dbdr prevents this by leaving itself a note in the column's comment:

$ psql -d shop -Atc "select col_description('orders'::regclass, 1)"
dbdr:origin={"Kind":"uint","Width":64}

Dump this Postgres table back out and id comes back as uint64. Chapter 6 explains how.

Notice one difference from the earlier dumps. The portable dump wrote daily_units and left out the two views. It has to work that way, because a Postgres destination has no materialized view to rebuild those rows. The portable format moves tables and their rows. It doesn't move views. In each format, which entities get their rows written is a policy decision, and Chapter 4 looks at those decisions closely.

What we have seen

In a few commands we have used every major part of the program:

graph LR
    A["dbdr (dump)"] --> B[config.Parse]
    B --> C{"--format"}
    C -->|sql| D["Dumper.Dump"]
    C -->|native| E["Dumper.DumpNative"]
    C -->|portable| F["Dumper.DumpPortable*"]
    G["dbdr restore"] --> H{"file extension"}
    H -->|".sql + .zip"| I["Exec + RestoreNative"]
    H -->|".dbschema + .dbdata"| J["ApplyPortableSchema + LoadPortableData"]

Every path through the program goes through one interface, Dumper, which each engine implements once.

The rest of the book takes these paths one at a time.

Exercises

Exercise 1-1. Dump shop with --dump-mv-data and compare the data section with the default dump. Which tables gained INSERTs? In what order do CREATE and INSERT now appear, and why does that order matter only in this mode?

Exercise 1-2. Dump with --split-insert-size=2 --data-compact=false and read the output. Then find the code that decides between the two layouts. (Hint: look for compact in internal/dumper/clickhouse/data.go.)

Exercise 1-3. Restore the Postgres half of shop into ClickHouse using the portable format. Two columns lose their defaults on the way. Which ones, and why didn't dbdr translate them?

Exercise 1-4. Run dbdr with no arguments at all, then run dbdr restore --help. The two help screens are produced by different functions. Find both.

2The Shape of the Program

Before reading any function closely, it helps to know where things are and which way the dependencies point. This chapter is a map. After that it follows one run from os.Args to the first byte written, and ends with the configuration every other part of the program reads.

The source tree

cmd/dbdr/                 the command: dispatch, output files, restore
  main.go                 dump entry point; chooses a format path
  restore.go              dbdr restore
  list_databases.go       dbdr list-databases
  output.go               thin wrappers over internal/compress
  version.go              version, commit, date (set by -ldflags)

internal/config/          flags, validation, defaults
  config.go               Config and Parse
  password.go             DBDR_PASSWORD, terminal prompt, stdin

internal/dumper/          the engine-neutral contract
  dumper.go               the Dumper interface and its registry
  clickhouse/             the ClickHouse backend
  postgres/               the Postgres backend
  mysql/                  a stub that refuses every call

internal/schema/          the engine-neutral schema (portable format)
internal/portable/        the engine-neutral row format
internal/compress/        gzip, zip and plain output; file naming

scripts/build.sh          cross-compiles release binaries
Makefile                  build, test, vet, run

The packages are layered, and the layers only point one way:

graph TD
    CMD["cmd/dbdr"] --> DUMPER["internal/dumper"]
    CMD --> CONFIG["internal/config"]
    CMD --> COMPRESS["internal/compress"]
    DUMPER --> CONFIG
    CH["dumper/clickhouse"] --> DUMPER
    PG["dumper/postgres"] --> DUMPER
    CH --> SCHEMA["internal/schema"]
    CH --> PORTABLE["internal/portable"]
    PG --> SCHEMA
    PG --> PORTABLE
    PORTABLE --> SCHEMA
    CMD -. "blank import (init only)" .-> CH
    CMD -. "blank import (init only)" .-> PG

The command knows the interface, not the engines. The engines know the neutral formats, but the neutral formats know nothing about any engine.

The dotted edges are the only place cmd/dbdr names a backend:

go
_ "github.com/harishiyer89/dbdump/internal/dumper/clickhouse"
_ "github.com/harishiyer89/dbdump/internal/dumper/postgres"

A blank import runs the package's init function and does nothing else, and each backend's init registers it with internal/dumper. Delete one of these lines and that engine disappears from the program. Nothing else breaks.

The two backends lay out their files the same way, so once you know one you can find your way around the other:

File Holds
<engine>.go Connect, Close, Exec, ListDatabases, the SQL Dump
entity.go the in-memory model of one introspected object
introspect.go the catalog queries that build the entities
order.go the topological sort
schema.go, ddl.go writing CREATE and DROP text
native.go --format=native, both directions
xportable.go --format=portable, both directions
format.go turning values into SQL literals

Building and testing

bash
make test        # go test ./...
make vet         # go vet ./...
make build       # a binary for this machine, in dist/
make build-all   # every platform listed in scripts/build.sh
make run ARGS="list-databases -un=default"

Everything builds with CGO_ENABLED=0, so there's no C toolchain to install. scripts/build.sh passes -ldflags -X to set main.version, main.commit and main.date. That is the whole mechanism behind dbdr --version.

The life of a run

Take the dump from the last chapter:

bash
dbdr -db=shop -un=default --split-insert-size=10000 -o=shop.sql

main calls run(os.Args[1:]), which looks at the first argument before anything is parsed:

go
if len(args) > 0 && args[0] == "restore" {
    return runRestore(args[1:])
}
if len(args) > 0 && args[0] == "list-databases" {
    return runListDatabases(args[1:])
}
cfg, err := config.Parse(args)

Each subcommand has its own flag.FlagSet, so a flag that only makes sense for dumping never shows up in restore --help. Anything that isn't a subcommand is a dump and goes to config.Parse.

With a Config in hand, run asks the registry for a backend, connects, and if -db=all was given, replaces "all" with the real list of databases. This can only happen after connecting, because only the server knows the list. Then it picks a path by format:

graph TD
    R["run"] --> P{"cfg.Format"}
    P -->|portable| DP["dumpPortable"]
    P -->|native| DN["dumpNative"]
    P -->|sql| N{"how many databases?"}
    N -->|one| DC["dumpCombined"]
    N -->|several| DS["dumpSplit"]
    DP --> M1["DumpPortableSchema or DumpPortableData"]
    DN --> M2["DumpNative, one .zip per database"]
    DC --> M3["Dump into one file"]
    DS --> M3b["Dump into one file per database"]

Four ways out of run, and each one is a loop over cfg.Databases that calls one Dumper method per database.

Every one of these loops does the same thing at the top:

go
for _, dbName := range cfg.Databases {
    cfg.Database = dbName
    ...
}

Config.Databases is the list the user asked for. Config.Database is the one being dumped right now. Backends only ever read the singular field. This is how a backend can be written as if there were only one database in the world.

Who opens the file

The answer depends on the format, and it explains the shape of the interface:

  • SQL and portable schema. The command opens the file through compress.Open, wraps it in a bufio.Writer, and passes the backend an io.Writer. The backend never touches the filesystem.
  • Native and portable data. The backend gets a path and creates its own files. A native dump writes one zip entry per table. A portable data dump decides table by table whether to put the rows in the main file or give the table a file of its own.

The command's loops are careful about errors. They always flush and close, and then, if any of the three steps failed, delete the file:

go
dumpErr := d.Dump(ctx, bw, cfg)
flushErr := bw.Flush()
closeErr := wc.Close()
discardOnFailure(actualPath, dumpErr, flushErr, closeErr)
if dumpErr != nil {
    return fmt.Errorf("database %q: %w", dbName, dumpErr)
}

An error from Close is never thrown away. A gzip writer that fails on close has lost its trailer, and the file is useless. And a dump that fails never leaves its file behind. That's the important part. A truncated SQL file whose last statement happens to be complete, or a gzip stream closed cleanly after the failure, looks finished, and replaying it would restore part of a database with no warning at all. The progress lines on standard error still show how far the dump got, and that is all you need to diagnose it. Backends that write their own files follow the same rule. DumpNative and DumpPortableData record every path they create in a compress.Created and remove them all on failure. When several databases are dumped and one fails, the files of the databases that finished before it are kept, because they are complete.

Output naming

When no -o is given, applyDefaultsAndValidate makes up a name with a timestamp:

Case Default name
SQL, one database <database>_<yyyymmdd_hhmmss>.sql
SQL, several databases dbdr_<ts>.sql, then _<database> inserted per file
native dbdr_native_<ts>.zip
portable schema dbdr_portable_<ts>.dbschema
portable data dbdr_portable_<ts>.dbdata

Two small functions in internal/compress do the rest. EnsureExt appends an extension if it is missing, so -o=x --compress=gzip becomes x.gz. InsertSuffix puts _<name> before the extension, so shop.dbdata and table orders give shop_orders.dbdata. The same function names per-database and per-table files, so the restore side can find them again with the same rule.

The configuration

internal/config/config.go turns flags into a Config and refuses combinations that make no sense. Three habits run through it. Follow them when you add a flag.

Every long flag has a short alias, held in a separate variable. The two are merged with firstNonEmpty(short, long), so the short form wins if both are given:

go
fs.StringVar(&database, "database", "", "...")
fs.StringVar(&database2, "db", "", "Alias for --database")
...
cfg.Database = firstNonEmpty(database2, database)

"Unset" and "zero" are different things when zero means something. Most numeric flags treat 0 as "use the default". --fetch-retries=0 means "don't retry", so the code asks the flag set whether the flag was actually given:

go
cfg.FetchRetries = 5
fs.Visit(func(f *flag.Flag) {
    if f.Name == "fetch-retries" {
        cfg.FetchRetries = fetchRetries
    }
})

Cross-flag rules live here, not in the backends. For example, native needs --only=data, portable needs --only=schema or --only=data, native output can't be gzipped (it's already a zip), and -db=all can't be mixed with names. By the time a backend sees a Config, it is consistent, and the backend doesn't check it again.

The password is the one value that never comes from a flag. ResolvePassword tries the DBDR_PASSWORD environment variable, then a prompt with echo turned off if standard input is a terminal, then one line read from standard input. Anything on a command line is visible to every user of the machine through ps, and it ends up in shell history.

Encryption is configured in the same place, and shared the same way. RegisterTLSFlags (tls.go) adds --tls, --tls-ca and --tls-server-name to whichever flag set it's given, so dump, restore and list-databases all accept them, and it returns a function that validates them after parsing. TLS.ClientConfig turns the result into a *tls.Config, the one object both backends pass to their drivers. The default port depends on it too: DefaultPort(engine, tlsEnabled) gives 9440 for ClickHouse with TLS and 9000 without. Keep it that way when you add an engine. A connection setting that only one command understands is a bug waiting to happen, as restore's old port default showed.

Exercises

Exercise 2-1. Add a --quiet flag that suppresses the progress lines on standard error. Where is the cleanest place to apply it, without passing a new argument through every function that prints?

Exercise 2-2. -db=all is rejected when combined with another name. Write the table-driven test cases for that rule in config_test.go, including -db=ALL and -db=" all ".

Exercise 2-3. Delete the Postgres blank import from main.go and run dbdr -e=postgres .... Read the error, then find the line that produces it.

Exercise 2-4. dumpCombined and dumpSplit are nearly the same function. Combine them into one without changing a single byte of output or a single file name. Run the tests to show you haven't.

3The Dumper Interface

internal/dumper/dumper.go is the most important file in the repository, and one of the shortest. It declares one interface and a map. Everything engine-specific lives behind the interface. Everything else is written against it.

The interface

These are the methods, grouped by what calls them:

go
type Dumper interface {
    // lifecycle
    Connect(ctx context.Context, cfg *config.Config) error
    Close() error

    // discovery
    ListDatabases(ctx context.Context) ([]string, error)

    // --format=sql
    Dump(ctx context.Context, w io.Writer, cfg *config.Config) error

    // --format=native
    DumpNative(ctx context.Context, zipPath string, cfg *config.Config) ([]string, error)
    RestoreNative(ctx context.Context, cfg *config.Config, database, table string,
        open func() (io.ReadCloser, error)) error

    // --format=portable
    DumpPortableSchema(ctx context.Context, w io.Writer, cfg *config.Config) error
    DumpPortableData(ctx context.Context, outputBase string, cfg *config.Config) ([]string, error)
    ApplyPortableSchema(ctx context.Context, cfg *config.Config, db *schema.Database) error
    LoadPortableData(ctx context.Context, cfg *config.Config, r io.Reader) error

    // restore plumbing
    Exec(ctx context.Context, statement string) error
    Finalize(ctx context.Context, cfg *config.Config) error
}

Read the portable group twice, because it holds the central idea of the design. Its methods come in two halves:

  • DumpPortableSchema and DumpPortableData are about the source. They know how to read their own engine and turn what they find into the neutral form. They never ask where the data is going.
  • ApplyPortableSchema and LoadPortableData are about the destination. They know how to turn the neutral form into their own DDL and bulk-load calls. They never ask where the data came from.
graph LR
    CH1["ClickHouse<br/>DumpPortable*"] --> N["neutral form<br/>.dbschema + .dbdata"]
    PG1["Postgres<br/>DumpPortable*"] --> N
    MY1["MySQL<br/>DumpPortable*"] -.-> N
    N --> CH2["ClickHouse<br/>Apply/Load"]
    N --> PG2["Postgres<br/>Apply/Load"]
    N -.-> MY2["MySQL<br/>Apply/Load"]

N engines need 2N methods, not N² converters. A new engine that implements both halves can exchange data with every existing engine, in both directions, and none of them has to change.

The registry

go
type Factory func() Dumper

var registry = map[config.DatabaseType]Factory{}

func Register(dbType config.DatabaseType, factory Factory) {
    registry[dbType] = factory
}

func New(dbType config.DatabaseType) (Dumper, error) {
    factory, ok := registry[dbType]
    if !ok {
        return nil, fmt.Errorf("database type %q is not implemented yet", dbType)
    }
    return factory(), nil
}

Each backend registers itself in init:

go
func init() {
    dumper.Register(config.Postgres, New)
}

The map is written only during initialization, before main runs, so it needs no lock.

Two ways to hold a connection

The interface hides a real difference between the engines, and the way it does so is worth copying.

A ClickHouse connection can reach every database on the server. Tables are named database.table. So the ClickHouse Dumper holds a single driver.Conn and reads cfg.Database on each call.

A Postgres connection belongs to one database for its whole life, and there is no cross-database query. So the Postgres Dumper keeps a small cache:

go
type Dumper struct {
    hostname string
    port     int
    username string
    password string

    conns map[string]*pgx.Conn // database name -> live connection

    currentDatabase string
}

ensureDB(ctx, name) returns the cached connection for name, opening it the first time. Every exported method goes through ensureDB, so the command never needs to know that Postgres works differently.

Exec has to go one step further. It is called with nothing but a statement, for each line of a schema.sql. So it watches for CREATE DATABASE:

go
if name, ok := parseCreateDatabase(statement); ok {
    maint, err := d.ensureDB(ctx, maintenanceDatabase)
    ...
    maint.Exec(ctx, fmt.Sprintf("CREATE DATABASE %s", quoteIdent(name)))
    d.currentDatabase = name
    ...
}

It creates the database from the postgres maintenance connection (Postgres won't let you create the database you're connected to). If the database already exists, that's fine. Then it routes every later statement to the new database, much as \c does in psql. Because of this, dbdr restore can replay a Postgres schema file without CREATE DATABASE IF NOT EXISTS, which Postgres doesn't have.

When your engine differs from the others, hide the difference the same way. The interface should look the same from outside.

Contracts the signatures don't show

A few rules aren't visible in the method signatures, and the command relies on them:

  1. Dump writes to w and nothing else. No files and no standard output. Progress goes to standard error.
  2. DumpNative and DumpPortableData return every path or entry they wrote, and on failure they remove everything they created. The command counts the paths in its summary line. A failed dump must leave nothing behind that a later restore could mistake for a complete artifact.
  3. RestoreNative takes an opener, not a reader. open is called again for every retry, so each attempt starts from the first byte. A zip entry can't be rewound, but it can be reopened.
  4. Finalize runs once, at the end, and only if data was loaded in this run. Chapter 7 explains why "only if" is there.
  5. Every method uses cfg.Database, never the first element of cfg.Databases. The command sets it before each call.

The stub

internal/dumper/mysql/mysql.go registers a Dumper whose every method returns the same error:

go
func (d *Dumper) Connect(ctx context.Context, cfg *config.Config) error {
    return fmt.Errorf("database type %q is not implemented yet", config.MySQL)
}

It exists so that -e=mysql gets a clear answer instead of "unknown engine", and so that adding MySQL means filling in methods rather than wiring anything up. Chapter 9 does exactly that.

Exercises

Exercise 3-1. Write a dumper.Dumper that records every call made to it in a slice and returns canned results. Use it to test dumpSplit without a database. What does the test show about the order in which cfg.Database changes?

Exercise 3-2. RestoreNative takes func() (io.ReadCloser, error). Rewrite it in your head to take an io.Reader instead, and list everything in restore.go that would have to change to keep retries correct.

Exercise 3-3. The interface has twelve methods, and a backend that only wants to support --format=sql must still write all of them. Sketch how it could be split into smaller interfaces (SchemaDumper, NativeDumper, ...), with the command checking support through a type assertion. What would the error messages look like?

4Entities and Dependency Order

A dump is a list of things to create, in an order that works. This chapter is about how each backend finds the things, how it orders them, and how it decides which of them have rows worth writing.

What an entity is

Each backend has its own entity type in entity.go, holding exactly what that backend needs. The ClickHouse one looks like this, slightly trimmed:

go
type entity struct {
    Database    string
    Name        string
    Engine      string // "MergeTree", "View", "MaterializedView", ...
    EngineFull  string
    CreateQuery string // verbatim from system.tables
    SortingKey  string // "product_id, order_date, id"
    MVTarget    string // a materialized view's TO table, if any
    dependsOn   map[string]struct{}
}

The ClickHouse backend doesn't build CREATE statements itself. The server already has the exact text in system.tables.create_table_query, so the backend copies it. Postgres has no such column, so its entity holds columns, constraints, indexes, view definitions and sequence state, and ddl.go builds the statements from those.

Introspection in ClickHouse

All of it starts with one query:

sql
SELECT name, engine, engine_full, create_table_query, sorting_key,
       dependencies_database, dependencies_table
FROM system.tables
WHERE database = $1
ORDER BY name

The two dependency columns have a catch, and the code points it out: they list the objects that depend on the current row, not the objects it depends on. introspect collects every row first, then turns each edge around once all the entities are known.

ClickHouse records only one kind of edge there: a materialized view reading from a table. The other edges dbdr needs have to be dug out of DDL text, and extraDependencies does that:

Engine Edge found by
MaterializedView the TO <target> clause (mvToClauseRe, searched only in the text before AS SELECT) and the FROM/JOIN tables in its query
View the FROM/JOIN tables in its query (selectSourceRefs)
Distributed the local table named in engine_full
Dictionary the SOURCE(CLICKHOUSE(TABLE '...')) table

These are regular expressions, not a SQL parser. They are good enough for the DDL ClickHouse itself produces, and they ignore references to other databases, which are out of scope for a dump of this one. If a view ever comes out before something it reads from, start here, and add the offending CREATE text to introspect_test.go as a new case.

One more rule applies during introspection. Tables named .inner. or .inner_id. are skipped. They hold the storage of materialized views that have no TO clause, and ClickHouse creates them afresh, with a new UUID, whenever the view's CREATE runs. Dumping them separately would leave an orphan table after every restore.

Introspection in Postgres

Postgres keeps much more in its catalog, so introspect runs a series of narrow queries, each one adding to the same slice of entities:

go
entities, oidByKey, err := introspectRelations(ctx, conn)
introspectColumns(ctx, conn, entities)
introspectConstraintsAndIndexes(ctx, conn, entities)
introspectPrimaryKeys(ctx, conn, entities)
introspectViewDefs(ctx, conn, entities)
seqEntities, err := introspectOwnedSequences(ctx, conn, entities)
entities = append(entities, seqEntities...)
introspectDependencies(ctx, conn, entities, oidByKey)
introspectForeignKeyDependencies(ctx, conn, entities)

To capture something new, such as triggers or COMMENT ON TABLE, add one more function to this list. Don't widen an existing query. Small passes are easier to test and easier to reason about when one of them breaks.

Postgres has namespaces, so entities are keyed by schema.name (entity.key()), not by bare name. System schemas and the per-session pg_temp_* schemas are excluded.

Ordering

Both backends sort with the same algorithm, in order.go: Kahn's topological sort with ties broken alphabetically.

go
for len(ready) > 0 {
    sort.Strings(ready)
    name := ready[0]
    ready = ready[1:]
    ordered = append(ordered, byName[name])
    for _, dep := range dependents[name] {
        inDegree[dep]--
        if inDegree[dep] == 0 {
            ready = append(ready, dep)
        }
    }
}

Sorting ready on every iteration costs a little time and buys something worth much more. The same database always produces the same file, byte for byte, apart from the timestamp, so two dumps can be compared with diff. For shop the sort gives:

graph LR
    DU[daily_units] --> MV[daily_units_mv]
    O[orders] --> MV
    O --> BO[big_orders]
    P[products]

Arrows point from a dependency to the object that needs it. The output order is daily_units, orders, big_orders, daily_units_mv, products. At each step it takes the alphabetically first object whose dependencies are all done.

A dependency on something outside the dump, such as a system table or another database, is ignored. If the sort can't finish because of a cycle, the leftover entities are appended alphabetically, and Dump writes a -- warning: dependency cycle detected among: ... line in the header instead of failing. A dump with a warning in it is still more use than no dump.

Postgres adds one extra edge that the catalog doesn't record. A SERIAL column's sequence must exist before the table, because the column's default calls nextval. But ALTER SEQUENCE ... OWNED BY needs the table to exist already. So the sequence is created early, and every OWNED BY goes in a block at the end of the schema. You can see both in the Postgres schema dump of shop.

Which entities carry rows

Ordering decides when an entity is created. A separate decision is whether its rows get written at all. In ClickHouse this comes down to two small functions, and most surprising behaviour traces back to one of them.

hasData asks whether the engine stores rows of its own:

go
func (e *entity) hasData() bool {
    switch e.Engine {
    case "View", "Distributed", "Dictionary", "Merge", "Buffer",
        "LiveView", "WindowView", "GenerateRandom", "Null":
        return false
    }
    if e.Engine == "MaterializedView" && e.MVTarget != "" {
        return false
    }
    // Kafka, RabbitMQ, NATS, S3Queue: data comes from outside
    ...
    return true
}

shouldDumpData adds the policy:

go
func shouldDumpData(e *entity, dumpMVData bool, mvTargets map[string]bool) bool {
    if !e.hasData() {
        return false
    }
    if e.Engine == "MaterializedView" {
        return dumpMVData
    }
    if mvTargets[e.Name] && !dumpMVData {
        return false
    }
    return true
}

With the default settings, neither a materialized view nor the table it writes to gets its rows dumped. They will be rebuilt by the view's trigger when the source rows are loaded again. That is why daily_units was missing from the SQL dump in Chapter 1, and why replaying it still gave the right totals.

That only works if every CREATE runs before any INSERT, so Dump has three layouts, chosen by flags:

Flags Layout
--only=schema or --only=data a single pass of whichever was asked for
--dump-mv-data each entity's CREATE followed at once by its own rows: an exact snapshot, with no trigger involved
(default) every CREATE, then a -- Data banner, then every INSERT

If you change either predicate, think through all three layouts, and run entity_shoulddumpdata_test.go.

The portable format has a different policy, and with good reason. It can't count on the destination having a trigger to rebuild anything, so it keeps every table that stores rows, including a materialized view's target table, and leaves out views and materialized views altogether. It prints a warning for each one it leaves out:

warning: shop.big_orders (View) has no portable equivalent, not included -- ...

Postgres needs none of this machinery. A Postgres materialized view has no trigger, and Postgres refuses COPY into one. So it is always created WITH NO DATA and refreshed after loading, as described in Chapter 7.

Exercises

Exercise 4-1. Add a ClickHouse view that reads from another view, and a third view that joins the first two. Confirm the sort puts them in order. Then write the same case as a test in order_test.go, using hand-built entities and no server.

Exercise 4-2. mvToClauseRe is applied only to the text before AS SELECT. Construct a materialized view whose query would fool the expression if it were applied to the whole statement. (Hint: a column or function name.)

Exercise 4-3. Postgres records view dependencies in pg_depend through pg_rewrite, but a function used in a column default can depend on a table too. Design the extra pass that would capture such an edge. What query would you write?

Exercise 4-4. Make topoSort report which edge closes a cycle, not just which entities are involved, and print it in the dump header.

5Moving Rows

Schema is small. Rows are what take time and what go wrong. This chapter covers the three ways dbdr reads rows out of a server, and the one problem they all solve differently: a big table can't be read with one query.

Why not one query

The first version of the SQL path did the obvious thing, SELECT * FROM t, and wrote rows as they arrived. On a table of 198 million rows, that query died partway through with i/o timeout. The server was busy merging and stopped sending for longer than the driver's read timeout, and the whole dump was lost with no way to resume it.

The fix, used in some form on every path, is to read a large table in bounded pieces, so that any single failure costs one piece and not the table. The three paths differ in how they cut the pieces.

The SQL path: a cursor on the key

writeData in internal/dumper/clickhouse/data.go chooses between two functions:

go
keyExprs := splitTopLevelExpressions(e.SortingKey)
if len(keyExprs) == 0 {
    return writeDataUnchunked(ctx, d.conn, w, e, cfg)
}
return writeDataChunked(ctx, d, w, e, cfg, keyExprs)

splitTopLevelExpressions splits the sorting key on commas that are not inside brackets, so toStartOfMonth(ts), id gives two expressions, not three. A table with no key at all (a Log engine, or ORDER BY tuple()) is read in one query, because there is nothing to page by.

For shop.orders, each piece is a query like this:

sql
SELECT *, (product_id) AS __dbdump_key0,
          (order_date) AS __dbdump_key1,
          (id)         AS __dbdump_key2
FROM `shop`.`orders`
WHERE (product_id, order_date, id) > ($1, $2, $3)
ORDER BY product_id, order_date, id
LIMIT 100000

The key expressions are selected again as extra columns. This lets the cursor work even when the key is an expression over a column, not a plain column. The WHERE compares tuples, which ClickHouse evaluates in dictionary order, the same order ORDER BY produces. The values for $1..$3 are the extra columns from the last row of the previous piece. buildChunkQuery builds this text, and data_test.go tests it without a server.

The loop around it holds three decisions, each made because something once went wrong:

go
for {
    for attempt := 1; attempt <= maxAttempts; attempt++ {
        buf.Reset()
        rowsInChunk, newLastKeyValues, chunkErr = fetchChunk(...)
        if chunkErr == nil {
            break
        }
        if attempt == maxAttempts || !isRetryableErr(chunkErr) {
            break
        }
        time.Sleep(backoff)              // 1s, 2s, 4s, ... at most 30s
        d.reconnect(ctx, cfg)
    }
    ...
    w.Write(buf.Bytes())
    lastKeyValues = newLastKeyValues
    if rowsInChunk == 0 {
        break
    }
}
  1. A piece is buffered in full before any of it is written. A retry therefore can't write half a piece twice. The cursor moves only after a successful write.
  2. Only network errors are retried. isRetryableErr accepts a net.Error, an EOF, the driver's closed-connection errors, and, as a last resort, messages containing i/o timeout, connection reset, broken pipe or connection refused. A bad query fails the same way every time, so retrying it only wastes time.
  3. Only an empty piece ends the loop. A short piece doesn't. A dropped connection can cut a result stream short without the driver reporting any error, and a short piece then looks exactly like the last page of the table. Stopping there once lost rows silently. The cost of the fix is one extra, empty query per table. Don't "optimise" it away.

Formatting a value as a SQL literal is the job of formatValue in format.go. Its table-driven tests are the place to add a case for any new type.

The native path: ranges fixed in advance

--format=native asks ClickHouse for FORMAT Native over HTTP and copies the bytes into the zip without decoding them. This is fast because nothing is parsed. But since nothing is parsed, there is no "last row" to page from, and the cursor method can't be used.

So the native path cuts the table before reading any of it:

graph TD
    C["SELECT count()"] --> N["ranges = count / --fetch-batch-size<br/>(at least 1, at most 256)"]
    N --> Q["one quantiles() query on the<br/>leading key column"]
    Q --> B["boundaries b1 < b2 < ... "]
    B --> R1["key <= b1"]
    B --> R2["b1 < key <= b2"]
    B --> R3["key > bn"]
    R1 --> Z["appended, in order, to<br/>shop/orders.native"]
    R2 --> Z
    R3 --> Z

The boundaries come from one aggregate query before any data is read. Each range is then an independent query.

In Chapter 1, orders had 250,000 rows and the batch size was 100,000, so dbdr asked for two ranges, which needs one boundary:

  shop.orders: computing 1 range boundaries on product_id... done in 3ms
  shop.orders: range 1/2... done in 18ms
  shop.orders: range 2/2... done in 16ms

Ranges have useful properties that cursor pieces don't. No range depends on the result of another. Each response is buffered in full before it is appended (fetchRangeNative), so a failed range can be retried with exactly the same query and leaves no partial bytes behind, and the ranges could even be fetched in parallel. (They aren't yet. See the exercises.) Native blocks can be concatenated, so the ranges can simply be appended to one zip entry.

Two details matter if you change this code. quantiles() doesn't accept every type. For a String key it fails with ILLEGAL_TYPE_OF_ARGUMENT, and isUnsupportedQuantileType recognises that error and falls back to a single unchunked fetch. That is always correct, just not chunked. And the boundaries come back as Go values that have to be written into the predicate text, so formatRangeBoundary formats them according to the key's ClickHouse type, which it reads from the result's column type. The driver hands back a Date as a time.Time, and written with a time part it would no longer compare with a Date column, so dates are written as dates.

Data goes over HTTPS on --http-port (8443 by default, or HTTP on 8123 with --tls=disable). The same TLS settings apply as for the native connection, so the Basic-auth credentials sent with every range request travel inside TLS (newHTTPClient, httpBaseURL). Introspection still uses the native TCP port, so a native dump needs both ports open.

The Postgres native path: splicing COPY streams

The Postgres version of --format=native uses COPY (SELECT ...) TO STDOUT (FORMAT binary). The ranges are found the same way in spirit, but more cheaply. computeRangeBoundaries first reads pg_stats.histogram_bounds, which ANALYZE already maintains, so this is a catalog read and not a scan. Only if there is no histogram does it fall back to one percentile_disc query.

There is a complication. Each binary COPY stream begins with a 19-byte header (PGCOPY\n\377\r\n\0 plus flags and an extension length) and ends with a two-byte trailer, 0xFFFF. Postgres rejects a stream with a header or trailer in the middle, so the ranges can't simply be appended. Instead dbdr:

  1. writes pgCopyHeader once, at the start of the entry,
  2. strips the header and trailer from each range's stream as it copies it, and
  3. writes pgCopyTrailer once, at the end.

The result is one valid stream per table, which pgx's CopyFrom loads in a single call at restore time.

The portable path

--format=portable decodes every row, because it must turn each value into its neutral form. For tables larger than --fetch-batch-size it uses the same quantile ranges as the native path, buffering each range before writing it so that a retry stays clean. Each such table also gets a file of its own:

  shop.orders: 250000 row(s) -> shop_orders.dbdata

Two reasons are given in the source. A very large table shouldn't force one enormous file that has to be moved whole. And a failure partway through costs that table's progress, not the whole database's. Small tables are grouped together in the base file.

One performance note from the code is worth repeating: portable.Writer makes many small writes per row, one per field, and on an unbuffered file each of them is a system call. A 1 MiB bufio.Writer made that path about 65 times faster. Whenever you hand a writer to code that writes byte by byte, buffer it.

Exercises

Exercise 5-1. Fetch native ranges concurrently. Add a --parallel=N flag, limit the number of goroutines, and keep each table's zip entry in key order. (Either buffer the finished ranges or write each one to its own entry.) Measure the speed-up on the 250,000 row orders table, then on something a hundred times larger.

Exercise 5-2. Build a small TCP proxy that closes the connection after N bytes. Put it between dbdr and ClickHouse, and show that a SQL dump with retries enabled produces exactly the same rows as one without the proxy.

Exercise 5-3. Make shop.orders sort by (order_date, id), with a Date column first, and dump it with --format=native. Find in formatRangeBoundary why a Date boundary is written as '2026-05-05' and not with a time part, then remove that case and see the error ClickHouse gives. Now try a Date32 key: why does that one fall back to a single unchunked read instead?

Exercise 5-4. The Postgres SQL data path isn't written yet: Dump refuses to run without --only=schema. Write it, following the shape of writeDataChunked, with a (pk) > ($1) cursor on the primary key. What should happen for a table with no primary key?

6The Portable Format

A native dump only makes sense to the engine that wrote it. To go from ClickHouse to Postgres or back, dbdr needs a description of tables and rows that neither engine owns. That description has two parts. The schema is in internal/schema, and the rows are in internal/portable.

The schema

go
type Database struct {
    Name   string
    Tables []Table
}

type Table struct {
    Schema   string   // Postgres schema; empty for ClickHouse
    Name     string
    Columns  []Column
    OrderKey []string
}

type Column struct {
    Name     string
    Type     Type
    Nullable bool
    Default  *Expr
    Comment  string
}

type Type struct {
    Kind      Kind
    Width     int   // bits, for int, uint and float
    Precision int   // decimal
    Scale     int   // decimal
    Elem      *Type // array element
}

Kind is a closed set of thirteen values: int, uint, float, decimal, string, bytes, bool, date, datetime, uuid, inet, json and array. Every engine maps its types into this set on the way out and back from it on the way in. The set is deliberately small. Every Kind added is one more case that every engine has to handle in both directions.

A .dbschema file is just this structure as JSON. Here is the orders table from Chapter 1, reduced with jq to one line per table:

$ jq -c '.Tables[] | {Name, OrderKey, cols: [...]}' shop.dbschema
{"Name":"daily_units","OrderKey":["day"],"cols":["day:date","units:uint64"]}
{"Name":"orders","OrderKey":["product_id","order_date","id"],"cols":["id:uint64","order_date:date","product_id:uint32","qty:uint16","customer:string?"]}
{"Name":"products","OrderKey":["id"],"cols":["id:uint32","name:string","price:decimal"]}

(? marks a nullable column.) Being readable is a feature. You can check what the program inferred, and if you must, you can edit it before restoring.

Mapping types

Each engine has one function for each direction:

ClickHouse Postgres
native type → Type ParseCHType ParsePGType
Type → native type Type.RenderCH Type.RenderPG

They are plain functions of strings, and that's why the IR is easy to test. schema_test.go is a list of strings in and results out. A few mappings reveal the judgment calls behind them:

Source Becomes Why
CH Nullable(T), LowCardinality(T) T, with Nullable set or ignored wrappers, not types
CH Enum8(...) string labels survive, codes don't; no portable enum
CH UInt128, Int256 64-bit no engine here has wider integers
PG numeric with no precision float 64 there's no exact neutral form for unlimited precision
uint 8 → PG smallint 0..255 fits
uint 16 → PG integer 0..65535 doesn't fit smallint
uint 32 → PG bigint doesn't fit integer
uint 64 → PG numeric(20,0) doesn't fit anything else
json, inet → CH String the value survives, the type doesn't

A type that neither parser recognizes becomes string with a warning on standard error. The dump goes on. Losing a type is better than losing a column.

Defaults and keys

Two fields carry SQL text rather than data, and both are handled conservatively.

Default is an Expr: the source dialect plus the text exactly as introspected. On the way in, RenderDefault translates only a short list of expressions known to mean the same thing everywhere (now(), current_timestamp, true, false, 0, 1). Anything else is dropped with a warning:

warning: shop_from_pg.orders: column "id"'s DEFAULT "nextval('orders_id_seq'::regclass)" has no portable equivalent, dropped

A default that looks plausible but means something different on the destination would be much worse than no default. Adding an expression to the list is a one-line change, but it is a decision. Make it only when you are sure the expression means the same thing on every engine.

OrderKey is never rendered as a primary key. A ClickHouse ORDER BY sets the physical sort order. It isn't a uniqueness constraint, and MergeTree tables routinely hold duplicate keys. So a Postgres destination gets a plain CREATE INDEX on those columns, and a ClickHouse destination uses them as its ORDER BY, in the same order. A ClickHouse source takes that order from the table's own sorting key (orderKeyColumns), because system.columns can only say whether a column is in the key, not where. A table without one falls back to its first column, because MergeTree requires something.

Origin markers

Some types can't survive a round trip on their own. A ClickHouse UInt64 becomes numeric(20,0) in Postgres. Dump that column again and nothing in Postgres says it was ever unsigned, so it would come back as Decimal(20,0). That's numerically right and still the wrong type.

The fix is in internal/schema/origin.go. When a destination creates a column, it writes the column's original Type into the column comment:

dbdr:origin={"Kind":"uint","Width":64}

When the next dump reads the column, DecodeComment looks for the marker. If it finds one, the marker wins over whatever type the engine reports:

go
func DecodeComment(raw string) (userComment string, origin *Type, ok bool) {
    idx := strings.LastIndex(raw, originCommentPrefix)
    if idx == -1 {
        return raw, nil, false
    }
    var t Type
    if err := json.Unmarshal([]byte(raw[idx+len(originCommentPrefix):]), &t); err != nil {
        return raw, nil, false
    }
    return strings.TrimSuffix(raw[:idx], "\n"), &t, true
}

Three properties make this safe. A user's own comment is kept, because the marker is always appended after it on a new line. A marker that fails to parse (someone edited it) is treated as ordinary comment text, so nothing breaks. And it is always the last marker that counts, so repeated round trips don't build up a stack of them.

In Chapter 1, shop.orders went from ClickHouse to Postgres and was dumped again. id came back as uint64.

The row format

internal/portable is a stream of bytes with single-byte markers and no other framing:

stream := table* 0x00
table  := 0x01 name ncols column* row* 0x00
column := name kind width prec scale hasElem [column] nullable
row    := 0x01 value*                    one value per column
value  := 0x00                           NULL
        | 0x01 payload
name, kind := length bytes               length is a uvarint
width, prec, scale, ncols := uvarint
hasElem, nullable := one byte, 0 or 1

The payload depends on the column's kind:

Kind Payload
int, uint 8 bytes, big-endian
float 8 bytes, the IEEE 754 bits
bool 1 byte
datetime 8 bytes, nanoseconds since the Unix epoch (an instant)
date 8 bytes, the same encoding, always at midnight UTC of the calendar date as the source saw it (toDateUnixNano)
string, bytes, uuid, inet, json, decimal uvarint length, then bytes
array uvarint count, then each element's payload, with no NULL flag (array elements can't be NULL)

Two choices are worth noting. Every table header carries its own column types, so a .dbdata file can be decoded without its .dbschema. And a uint64 larger than math.MaxInt64 is stored through an int64 cast. It goes negative in between, but the cast is reversed exactly on read. portable_test.go checks that with math.MaxUint64.

A date is a calendar date, not an instant, and is stored that way. Drivers hand dates back in different timezones: clickhouse-go uses the server's, pgx uses UTC. So the encoder first takes the date as the source saw it, then stores midnight UTC of that date. Versions before v0.5.1 stored the instant instead, and every date from a server east of UTC came back a day early (issue #5). The test for it is in date_test.go.

Decimals are stored as text, which is the only representation both shopspring/decimal and pgtype.Numeric read back without loss.

Canonical values

Each driver scans values into its own Go types: uint32, int16, pgtype.Numeric, *string, and so on. If the row format had to understand all of them, it would grow with every driver. Instead, the dump side converts every value into one of a few canonical types before encoding it. The helpers are in convert.go.

Kind Canonical Go type
any integer int64
any float float64
date, datetime time.Time
text-like and decimal string
bool bool
array []any

The load side does the reverse, for the destination's column type as rendered, not as dumped. pgGoValue turns an int64 into an int16 for a column that RenderPG made smallint. chGoValue does the same for batch.Append. Values go straight into the destination's bulk API, CopyFrom or a native batch, without any SQL text. That is why the portable format is nearly as fast as the native one.

Adding a Kind

  1. Add the constant to schema.go.
  2. Map it in ParseCHType, ParsePGType, RenderCH and RenderPG.
  3. Add its encode and decode cases to portable.go, and its canonical conversion to convert.go.
  4. Handle it in chGoValue and pgGoValue.
  5. Test each step: parse and render cases in schema_test.go, a value round trip in portable_test.go, and a load conversion in each backend's xportable_test.go.

Never change an existing kind's payload. Every .dbdata file already written depends on it. The stream has no version number yet, which is the first exercise.

Exercises

Exercise 6-1. Add a format version byte to the start of .dbdata streams, and a "Version" field to .dbschema. Readers should give a clear error for a version they don't know. How will a new reader deal with files written before the version existed?

Exercise 6-2. OrderKey follows the key's own order, product_id, order_date, id, and not the table's column order. Read orderKeyColumns in the ClickHouse xportable.go and find what it does for a key like toStartOfMonth(created_at), id. Then construct a key for which it falls back to the is_in_primary_key flags, and decide whether that fallback is right.

Exercise 6-3. Add KindTime for a time of day with no date. Postgres has time, and ClickHouse has none. What should RenderCH produce, and does the column need an origin marker?

Exercise 6-4. Write a small dbdata-dump program that prints a .dbdata file as JSON lines, one per row, using only internal/portable. It is the most useful debugging tool this format doesn't have yet.

7Restore

Everything so far has been about writing artifacts. cmd/dbdr/restore.go reads them back, and it is the only code in the program that does. It doesn't depend on any engine: it works out what kind of file it has been given and calls the matching Dumper method.

Choosing a path

dbdr restore -e=<engine> [-s <schema>] [-d <data>] [-db <name>]

The file extensions decide everything:

go
portableSchema := strings.HasSuffix(rargs.SchemaPath, ".dbschema")
portableData := strings.HasSuffix(rargs.DataPath, ".dbdata")
if rargs.SchemaPath != "" && rargs.DataPath != "" && portableSchema != portableData {
    return fmt.Errorf("--schema and --data must both be portable (.dbschema/.dbdata) or both same-engine (schema.sql/.zip), not a mix")
}
graph TD
    S{"--schema"} -->|"*.sql"| E["readSQLStatements, then Exec each"]
    S -->|"*.dbschema"| A["ApplyPortableSchema"]
    D{"--data"} -->|"*.zip"| N["RestoreNative for each entry"]
    D -->|"*.dbdata"| L["LoadPortableData for each file"]
    E --> F["Finalize (only if --data was given)"]
    A --> F
    N --> F
    L --> F

Schema first, then data, then Finalize. Either half can be left out, but not both, and the two kinds can't be mixed.

Both flags are optional, which allows the common two-step workflow: load the structure now and the data later, or load the data again into a structure that is already there.

Replaying SQL

readSQLStatements is deliberately simple:

go
for _, line := range strings.Split(string(raw), "\n") {
    if strings.HasPrefix(strings.TrimSpace(line), "--") {
        continue
    }
    kept = append(kept, line)
}
for _, part := range strings.Split(content, ";\n") {
    ...
}

It drops comment lines and splits on a semicolon at the end of a line. That is exactly what dbdr writes, so it works for files dbdr wrote. It is not a SQL lexer. A string literal or a view body containing ; followed by a newline would be cut in two. Before you let this function read SQL that people wrote by hand, make it understand quotes.

Each statement goes to Exec. For Postgres, Exec also follows the CREATE DATABASE lines, as described in Chapter 3.

Loading native data

nativeEntriesFromZip turns every <database>/<table>.native entry into a target. For Postgres the table part is schema.table. Then each one is loaded with an opener:

go
for _, e := range entries {
    if err := d.RestoreNative(ctx, cfg, e.Database, e.Table, e.file.Open); err != nil {
        return fmt.Errorf("load %s.%s: %w", e.Database, e.Table, err)
    }
}

e.file is a *zip.File, and its Open method is already an opener of the right type.

ClickHouse posts the stream to INSERT INTO ... FORMAT Native over HTTP. Postgres passes it to CopyFrom. If an attempt fails, the backend calls open again and starts over from byte zero. This is why the interface takes a function and not a reader.

Loading portable data

A portable data dump may be several files: the base .dbdata, plus one <base>_<table>.dbdata for every table that was too big to group. discoverPortableDataFiles finds them:

  1. If the base file exists, it comes first.
  2. If a .dbschema was given, it looks for <base>_<table>.dbdata for each table the schema names. This is exact.
  3. Otherwise it globs <base>_*.dbdata. This is a best guess, and the reason a paired schema is the better choice.

Each file goes to LoadPortableData, which reads table headers and rows from the stream and streams them into the destination's bulk loader.

-db names the destination database. It is required when a .dbdata file is restored on its own, because nothing else names the database. When a .dbschema is given, the schema's Name is used unless -db overrides it. That override is applied in both backends by portableSchemaDatabaseName, a function that exists because the override was once ignored. The target may not exist yet, so restore connects without it. ClickHouse then uses default and Postgres uses postgres, and ApplyPortableSchema creates the target before anything is written to it.

Finalize

go
if rargs.DataPath != "" {
    if err := d.Finalize(ctx, connCfg); err != nil {
        return fmt.Errorf("finalize: %w", err)
    }
}

ClickHouse has nothing to do here. Postgres refreshes every materialized view that pg_matviews still reports as unpopulated. Here is the end of a Postgres native restore of shop:

loading shop.public.customers... done in 3ms
loading shop.public.products... done in 0s
loading shop.public.orders... done in 2.152s
done in 2.155s
refreshing materialized view shop."public"."daily_units"... done

The if matters. Run Finalize after a schema-only restore, and each materialized view is refreshed against empty tables. It is then marked as populated, so a later data-only restore skips it, and the view stays empty for good. This was found by testing the two-step workflow, not the one-step one. When you change restore.go, test both.

Sequences after a restore

COPY doesn't advance sequences. If nothing were done, the first ordinary INSERT after a restore would try id = 1 and collide with a restored row. The schema dump deals with this ahead of time by storing each sequence's value at dump time:

sql
SELECT setval('"public"."orders_id_seq"', 250000, true);
...
SELECT setval('"public"."customers_id_seq"', 500, true);

The first form handles SERIAL sequences, which are entities of their own. The second handles the sequences behind GENERATED AS IDENTITY columns, which Postgres creates implicitly with the table. After the restore above:

shop=# insert into orders (customer_id, product_id, qty) values (1,1,2) returning id;
 250001
shop=# insert into customers (email) values ('new@example.com') returning id;
 501

Safety defaults

Several defaults exist to protect the destination. Keep them unless you have a very good reason:

  • No DROP unless asked. Without --add-drop-statement, a CREATE that conflicts with an existing object fails loudly. A dump replayed against the wrong server stops at its first statement instead of replacing that server's tables.
  • CREATE DATABASE IF NOT EXISTS (ClickHouse), or its Exec equivalent (Postgres), so a schema file contains everything it needs.
  • No password in argv, on restore as much as on dump.

Exercises

Exercise 7-1. Make readSQLStatements aware of quotes: single quotes with '' escapes, double-quoted identifiers, backticks, and Postgres dollar quoting ($$ ... $$). Write the tests first.

Exercise 7-2. Add --dry-run to restore. It should print what would be executed and loaded (statements, entries, files and row counts) without connecting to a server for anything but the connection check.

Exercise 7-3. runRestore connects with the Database field cleared, then passes the real target to every later call. Find the line, and list what would break, on each engine, if Connect were given the target database instead. (Hint: the target may not exist yet.)

Exercise 7-4. A data-only restore of a .dbdata file with no paired schema falls back to globbing. Construct two dumps in the same directory whose files the glob would mix up, then design a fix.

8Testing and Debugging

make test takes less than a second and needs no database. That is a real virtue, and it shapes how code in this project is written: logic that can be pulled out of a function that talks to a server is pulled out, into a pure function that can be tested on its own. This chapter shows what that covers, what it doesn't cover, and how to find out what went wrong when a dump misbehaves.

What the tests cover

$ go test ./...
ok   github.com/harishiyer89/dbdump/cmd/dbdr                  0.426s
?    github.com/harishiyer89/dbdump/internal/compress          [no test files]
ok   github.com/harishiyer89/dbdump/internal/config            0.377s
?    github.com/harishiyer89/dbdump/internal/dumper            [no test files]
ok   github.com/harishiyer89/dbdump/internal/dumper/clickhouse 0.351s
?    github.com/harishiyer89/dbdump/internal/dumper/mysql      [no test files]
ok   github.com/harishiyer89/dbdump/internal/dumper/postgres   0.345s
ok   github.com/harishiyer89/dbdump/internal/portable          0.380s
ok   github.com/harishiyer89/dbdump/internal/schema            0.379s
Package What's tested
internal/config flag parsing, aliases, cross-flag rules, the order of password sources
internal/schema type parsing and rendering for both engines; origin markers
internal/portable encode/decode round trips, including values above MaxInt64; canonical conversion
clickhouse the sort, dependency extraction, shouldDumpData, splitting key expressions, building chunk queries, value formatting, portable conversions
postgres portable conversions
cmd/dbdr output naming, finding restore files

The tests are written in one style: a table of cases next to the code, one row per input. When you fix a bug, the input that caused it becomes a new row. This keeps the history of what went wrong inside the test file, where the next person will see it.

What the tests don't cover

Everything that needs a live server is tested only by hand. That includes the introspection queries, the HTTP Native stream, splicing binary COPY streams, retrying and reconnecting, Finalize, and every complete round trip. The Postgres backend in particular is tested only at its portable conversions.

The round trips in Chapter 1 are the kind of test that is missing, and shop-database.sql was written to be their fixture. A harness could look like this:

  1. Put the tests behind a build tag (//go:build integration) so that make test stays fast.
  2. Start throwaway servers. Use testcontainers-go, or read DBDR_IT_CLICKHOUSE and DBDR_IT_POSTGRES connection strings from the environment for CI machines that already have servers.
  3. Load shop, dump it every way, restore each dump into a fresh database, and compare counts and a checksum on both sides. On ClickHouse, sum(cityHash64(*)) works. On Postgres, use an aggregate md5 over ordered rows.
  4. Do all four directions for portable: CH→CH, CH→PG, PG→PG and PG→CH.
  5. Add a make it target and a CI job.

The totals to expect for shop are 250,000 orders, 1,749,985 units, 250 days, 4 products and 500 customers. They are the same in both engines, by construction.

A first version of that harness now exists as a shell script, scripts/integration.sh (make it), and CI runs it on every push. It uses Docker in place of testcontainers-go. It checks the totals above on both sources, then runs seven round trips: ch-sql, ch-native, ch-portable-ch, ch-portable-pg, pg-native, pg-portable-pg and pg-portable-ch. Every case prints its totals as name=value lines, so a failure names the total that differs:

FAIL ch-sql: totals differ (< source, > destination):
< daily_units.units=1749985
> daily_units.units=3499970

That one comes from breaking shouldDumpData so that it also dumps the target of a materialized view, the mistake Chapter 1 warns about. Moving the harness into Go tests behind a build tag is still open.

Testing the retry path

The retry loop is the hardest code to test, because the failures it handles are timing accidents. Don't wait for an accident. Make one. Write a TCP proxy that forwards bytes and drops the connection after the Nth byte. Point dbdr at it, set --fetch-batch-size small so there are many pieces, and check that the output is identical to a dump taken without the proxy. Vary N, and the test covers every place a connection can fail.

Reading a dump

When something is wrong, start with the evidence the program already leaves behind.

The header. Every SQL dump starts by saying what it is:

sql
-- dbdr: ClickHouse dump of database "shop"
-- generated: 2026-11-27T08:45:41+05:30
-- entities: 5
-- mode: materialized view data is repopulated live via triggers, not
-- explicitly dumped ...

Before anything else, check the entity count, the modes, and any -- warning: lines about cycles.

The order. --only=schema gives the order without the data in the way. grep -nE '^-- (Table|View|Materialized View|Sequence): ' file.sql lists one line per entity, in order.

The types. A .dbschema file is JSON. To see what dbdr inferred, and where it gave up and used string, run:

bash
jq '.Tables[].Columns[] | {Name, Type}' shop.dbschema

The warnings. Everything dbdr decides to leave out, such as an unrecognized type, an untranslatable default, or a view with no portable equivalent, is reported with a warning: line on standard error. Keep standard error separate from the output and read it:

bash
dbdr ... 2>dump.log
grep warning dump.log

The files. A native zip should have one entry per table that stores data, and none of them should be empty:

bash
unzip -l data.zip

A failed dump exits with status 1 and removes every file it created, so an artifact that exists came from a dump that finished. One case still deserves care. ClickHouse hides tables a user can't read from system.tables, so a dump run as a user with too few privileges succeeds, and leaves those tables out without a word. Check the -- entities: count in a SQL dump, or the zip listing, against what you expect, and dump as a user that can see everything.

Debugging against a real server

The quickest loop is a local server and the example database. If you can't use containers, the clickhouse binary can run a server from a directory with a short XML config, and a Postgres initdb directory works the same way. Use ports that don't clash with any server already running. Every transcript in this book was made that way.

To see exactly what dbdr sends, turn on the server's query log (system.query_log in ClickHouse, log_statement = 'all' in Postgres) and read it after a run. The chunk queries in Chapter 5 were written out from the code. The query log will show you the real thing.

Exercises

Exercise 8-1. Build the integration harness described above, for ClickHouse to ClickHouse only, with the shop fixture. Make it fail by breaking shouldDumpData on purpose, and check that the failure message says which total is wrong.

Exercise 8-2. Add the proxy test for the SQL path's retries. What is the smallest N that still lets the connection handshake succeed?

Exercise 8-3. internal/compress has no tests. Write them, including a gzip file closed after a failed write, and a zip opened with -o already ending in .zip.

Exercise 8-4. A failed dump removes every file it created (see discardOnFailure and compress.Created). Write an integration test that proves it on a real server: give a user SHOW TABLES on a whole database but SELECT on only one table, dump that database in every format, and check for exit status 1 and an empty output directory.

9Adding a Backend

The best way to understand a program is to extend it. This chapter plans a MySQL backend from the stub that's already registered. It isn't a finished implementation. It's the order of work, with each step leaving something that works and can be shipped, and the places where MySQL will make you think.

The plan

graph TD
    S1["1. Connect, Close, ListDatabases"] --> S2["2. Introspect and sort"]
    S2 --> S3["3. Dump with --only=schema"]
    S3 --> S4["4. Exec: replay schema.sql"]
    S4 --> S5["5. Portable schema, both halves"]
    S5 --> S6["6. Portable data, both halves"]
    S6 --> S7["7. Native, or a clear refusal"]
    S7 --> S8["8. Finalize, if needed"]

Each step adds a command that works. After step 5, MySQL schemas can move to and from both existing engines. After step 6, so can their data.

Step 1: connect and list. Replace the stub's Connect, Close and ListDatabases. MySQL, like ClickHouse, can reach every database from one connection, so a single *sql.DB is enough, with no cache like the one Postgres needs. Filter out mysql, information_schema, performance_schema and sys, just as the other backends filter their own system databases. After this step, dbdr list-databases -e=mysql works.

Step 2: introspect and sort. Postgres is the closer model, since MySQL has real foreign keys and an information_schema. Copy its shape: a introspectRelations pass over information_schema.tables, then small passes for columns, keys and view definitions. For view dependencies, information_schema.view_table_usage exists only in MySQL 8.0.13 and later. On older servers you need a fallback, and the ClickHouse FROM/JOIN regular expression is one. Copy order.go exactly, and test it with hand-built entities.

Step 3: schema dump. MySQL will give you each object's DDL with SHOW CREATE TABLE and SHOW CREATE VIEW, which is the same shortcut ClickHouse's create_table_query gives. Use it. A view's DEFINER clause names a user who may not exist at the destination, so decide whether to strip it, and document the decision.

Step 4: replay. Exec runs one statement. CREATE DATABASE IF NOT EXISTS exists in MySQL, so there's nothing like the Postgres CREATE DATABASE handling, but a USE after it is needed, or the schema writer must qualify every name. Qualifying names is the better choice, because then statements don't depend on session state.

Step 5: portable schema. Add ParseMySQLType and Type.RenderMySQL to internal/schema, next to the other two pairs. This is where MySQL needs the most thought:

MySQL Kind Note
tinyint(1) bool by convention only; a real tinyint(1) holding 2 would be wrong
int unsigned, bigint unsigned uint 32, 64 MySQL has the unsigned types Postgres lacks
decimal(p,s) decimal
datetime, timestamp datetime timestamp is stored in UTC, datetime isn't
json json
enum(...), set(...) string the same compromise as ClickHouse Enum
binary(16) bytes often a UUID, which there is no way to tell

Write the table as test cases before writing the functions.

Step 6: portable data. On the dump side, scan into the canonical Go types of Chapter 6. On the load side, use the fastest bulk path the driver offers. LOAD DATA LOCAL INFILE from an io.Reader is fastest. Multi-row INSERTs of a few thousand rows are the portable fallback. Reuse the chunking idea from Chapter 5 for large tables. MySQL has no quantiles(), but a cursor on the primary key works just as it does in the SQL path.

Step 7: native. MySQL has no binary bulk format that is both documented and stable enough to copy as bytes. Return a clear error from DumpNative and RestoreNative that points to --format=portable, as the Postgres SQL Dump points to native.

Step 8: finalize. Probably nothing, unless you decide to turn off foreign key checks during the load (SET FOREIGN_KEY_CHECKS = 0), in which case Finalize is where you turn them back on.

What not to change

A new backend should need changes in exactly three places: its own package, internal/schema (for one more Parse/Render pair), and the blank import in main.go. If you find yourself editing restore.go, dumper.go, or another backend, stop and ask whether the interface is missing something. If it is, change the interface on purpose, in its own commit. Don't add a special case for one engine.

Before you send it

  • Add the engine to the README's flag table and its "Known limitations" list. Say exactly which formats work.
  • Add a MySQL half to shop-database.sql that holds the same data, so that the totals in Chapter 8 hold for three engines.
  • Run every portable direction that involves the new engine, and compare the totals.

Exercises

Exercise 9-1. Do steps 1 to 4. Confirm that dbdr restore -e=mysql -s=schema.sql reproduces the shop schema on a fresh MySQL server.

Exercise 9-2. Write ParseMySQLType and RenderMySQL, with the table above as tests. Then dump shop from ClickHouse as portable, restore it into MySQL, and check that orders.id is bigint unsigned, not a decimal. Why does MySQL need no origin marker for that column, when Postgres does?

Exercise 9-3. Finish steps 5 and 6, and add the MySQL rows to the integration harness from Exercise 8-1.

AReference Manual

This appendix brings together, in one place, everything the chapters introduce one piece at a time: the commands and their flags, the artifacts and their formats, and the type mappings. Where it and the code disagree, the code is right, and this appendix needs fixing.

A.1 Commands

dbdr [dump flags]                       dump one or more databases
dbdr restore [restore flags]            load artifacts into a server
dbdr list-databases [connection flags]  print database names, one per line
dbdr --version | -version | -v          print version, commit, build date

Running dbdr, dbdr restore or dbdr list-databases with no arguments prints that command's full help.

A.2 The password

There is no password flag. In order, dbdr uses:

  1. the DBDR_PASSWORD environment variable, if it is set and not empty;
  2. a prompt with echo turned off, if standard input is a terminal;
  3. one line read from standard input, without its trailing newline.

A.2a Encryption

Every command encrypts its connections by default.

--tls Encrypts Verifies the certificate Notes
verify-full (default) yes chain and host name (or --tls-server-name), against --tls-ca or the system store
require yes no defeats eavesdropping, not an attacker in the middle
disable no no prints warning: --tls=disable: ... to standard error

There is no fallback. A TLS client never retries in plain text, and a server that doesn't offer TLS is an error. TLS 1.2 is the minimum. Every output file is created with mode 0600.

A.3 Dump flags

Flag Alias Default Meaning
--database -db (required) Database to dump. Several are comma-separated. all means every database list-databases would show, and can't be combined with names.
--username -un (required)
--hostname -hn localhost
--port-number -pn by engine and TLS: ClickHouse 9440 (9000 with --tls=disable), Postgres 5432, MySQL 3306
--engine -e clickhouse clickhouse, postgres or mysql (a stub)
--http-port 8443 (8123 with --tls=disable) ClickHouse HTTP(S) port, used only for native data
--tls verify-full verify-full, require or disable (A.2a)
--tls-ca system trust store PEM file of CAs to trust
--tls-server-name --hostname name to verify the certificate against
--only both schema or data
--format -fmt sql sql, native or portable
--output -o see A.6
--compress none none, gzip (also gz), or zip
--split-insert-size single-row rows per INSERT
--data-compact true false puts one row per line, indented
--dump-mv-data false dump materialized view data as a snapshot (A.8)
--add-drop-statement false put DROP ... IF EXISTS before each CREATE
--fetch-batch-size 100000 rows per piece or range for large tables
--fetch-retries 5 retries per piece on a network error; 0 means none

Rules that config.Parse enforces:

  • --format=native requires --only=data and refuses --compress=gzip.
  • --format=portable requires --only=schema or --only=data.
  • --split-insert-size and --fetch-batch-size must be positive when given. --fetch-retries must not be negative.
  • For Postgres, --format=sql requires --only=schema. The SQL data path isn't implemented yet.

A.4 Restore flags

Flag Alias Default Meaning
--username -un (required)
--hostname -hn localhost
--port-number -pn by engine and TLS, as for a dump the destination engine's port
--http-port 8443 (8123 with --tls=disable) ClickHouse HTTP(S) port, for native data
--tls, --tls-ca, --tls-server-name verify-full as for a dump (A.2a)
--engine -e clickhouse the destination engine
--schema -s a .sql or a .dbschema file
--data -d a .zip or a .dbdata file
--database -db the schema's name destination database, created by a portable schema restore if it doesn't exist; required for a .dbdata given without a schema
--fetch-retries 5

At least one of --schema and --data is required. If both are given, both must be portable or both same-engine.

A.5 list-databases flags

--username/-un (required), --hostname/-hn, --port-number/-pn (default chosen by engine and TLS), --engine/-e, and the three TLS flags (A.2a). It leaves out system, information_schema and default on ClickHouse, and template0 and template1 on Postgres.

A.6 Artifacts and their names

Artifact Contents Default name
.sql CREATE and/or INSERT text <db>_<ts>.sql (one database), dbdr_<ts>_<db>.sql (several)
.sql.gz, .sql.zip the same, compressed as written the extension is added to whatever name is used
.zip (native) one <db>/<table>.native entry per table with data; for Postgres the table part is <schema>.<table> dbdr_native_<ts>.zip
.dbschema the schema IR as JSON (A.9) dbdr_portable_<ts>.dbschema
.dbdata portable rows (A.10); small tables grouped dbdr_portable_<ts>.dbdata
<base>_<table>.dbdata one large table's rows next to the base file

<ts> is yyyymmdd_hhmmss in local time. When several databases are dumped, _<db> is inserted before the extension of every per-database file.

A.7 What each format includes

sql (CH) sql (PG) native portable
Tables yes yes data only yes
Views yes yes no data omitted
Materialized views yes WITH NO DATA no data omitted
MV target tables' rows only with --dump-mv-data n/a yes yes
Sequences n/a CREATE + setval n/a omitted
Constraints, indexes in DDL yes n/a OrderKey only, as a plain index
Column comments in DDL not written n/a yes, plus origin marker
Restorable into same engine same engine same engine any engine

A.8 SQL dump layout (ClickHouse)

Mode Order of statements
--only=schema CREATE DATABASE, then every CREATE in dependency order
--only=data every INSERT in dependency order; no DDL
--dump-mv-data for each entity in order: its CREATE, then its INSERTs
default CREATE DATABASE, every CREATE, a -- Data banner, every INSERT; MVs and their targets have no rows

With --add-drop-statement, a full dump also begins with a block that drops the views first, and each CREATE is preceded by its DROP.

A.9 The .dbschema format

JSON for schema.Database:

json
{
  "Name": "shop",
  "Tables": [
    {
      "Schema": "public",
      "Name": "orders",
      "Columns": [
        { "Name": "id",
          "Type": { "Kind": "int", "Width": 64 },
          "Nullable": false,
          "Default": { "SourceDialect": "postgres",
                       "Text": "nextval('orders_id_seq'::regclass)" } }
      ],
      "OrderKey": ["id"]
    }
  ]
}

Schema, Width, Precision, Scale, Elem, Default, Comment and OrderKey are left out when they are empty.

A.10 The .dbdata format

stream := table* 0x00
table  := 0x01 str:name uvarint:ncols column{ncols} row* 0x00
column := str:name str:kind uvarint:width uvarint:prec uvarint:scale
          byte:hasElem [column:elem] byte:nullable
row    := 0x01 value{ncols}
value  := 0x00 | 0x01 payload
str    := uvarint:len byte{len}
Kind Payload
int, uint 8 bytes, big-endian
float 8 bytes, big-endian IEEE 754
bool 1 byte
datetime 8 bytes, big-endian Unix nanoseconds
date 8 bytes, big-endian Unix nanoseconds of midnight UTC of the calendar date
string, bytes, uuid, inet, json, decimal str
array uvarint:count, then count payloads of the element kind (no NULL flags)

The format has no version number (see Exercise 6-1).

A.11 Type mapping

Kind from ClickHouse to ClickHouse from Postgres to Postgres
int 8/16/32/64 Int8…Int64, Int128/Int256 → 64 Int<w> smallint, integer, bigint smallint, integer, bigint
uint 8/16/32/64 UInt8…UInt64, UInt128/UInt256 → 64 UInt<w> (only via origin marker) smallint, integer, bigint, numeric(20,0)
float 32/64 Float32, Float64 Float<w> real, double precision, bare numeric real, double precision
decimal Decimal(p,s) Decimal(p,s) numeric(p,s) numeric(p,s)
string String, Enum8/16 String text, character varying, character text
bytes FixedString(n) String bytea bytea
bool Bool Bool boolean boolean
date Date, Date32 Date date date
datetime DateTime, DateTime64(..) DateTime timestamp… (with or without zone) timestamp
uuid UUID UUID uuid uuid
inet IPv4, IPv6 String inet, cidr inet
json none String json, jsonb jsonb
array Array(T) Array(T) T[] T[]

Nullable(T) and LowCardinality(T) are unwrapped. Anything not listed becomes string, with a warning.

A.12 Portable defaults

Recognized, ignoring case and surrounding spaces: now(), current_timestamp (rendered as now()), true, false, 1, 0. Every other default is dropped with a warning. On Postgres, a column whose default was dropped also becomes nullable.

A.13 Exit status

0 on success, or when help was printed. 1 on any error, with the message dbdr: <error> on standard error. A dump that exits with 1 has removed every file it created. Files that belong to databases which finished earlier in a multi-database run are kept.

BPackage Reference

This appendix lists the functions and types each internal package exports, and the unexported helpers a contributor is most likely to reach for. It's a map for finding things. The source has the details.

B.1 internal/config

go
type DatabaseType string // ClickHouse, Postgres, MySQL
type Compression string  // CompressionNone, CompressionGzip, CompressionZip
type Format string       // FormatSQL, FormatNative, FormatPortable

type Config struct {
    Database     string   // the database being dumped right now
    Databases    []string // everything asked for
    AllDatabases bool     // -db=all, resolved after Connect

    Username, Password, Hostname string
    Port, HTTPPort               int
    TLS                          TLS
    DatabaseType                 DatabaseType

    SchemaOnly, DataOnly          bool
    SplitInsert                   bool
    SplitInsertSize               int
    DataCompact, DumpMVData       bool
    AddDropStatement              bool
    FetchBatchSize, FetchRetries  int

    Output      string
    Compression Compression
    Format      Format
}

func Parse(args []string) (*Config, error)  // flag.ErrHelp for -h or no args
func ResolvePassword() (string, error)       // env, then TTY, then stdin
func DefaultPort(t DatabaseType, tlsEnabled bool) int // ClickHouse 9440 or 9000; 5432; 3306; 0 if unknown
func DefaultHTTPPort(tlsEnabled bool) int    // 8443 or 8123

type TLSMode string // TLSVerifyFull (default), TLSRequire, TLSDisable
type TLS struct { Mode TLSMode; CAFile, ServerName string }
func ParseTLSMode(s string) (TLSMode, error)
func (t TLS) Enabled() bool
func (t TLS) ClientConfig(host string) (*tls.Config, error) // nil when disabled
func RegisterTLSFlags(fs *flag.FlagSet) func() (TLS, error)

B.2 internal/dumper

go
type Dumper interface { ... }         // see Chapter 3
type Factory func() Dumper

func Register(dbType config.DatabaseType, factory Factory)
func New(dbType config.DatabaseType) (Dumper, error)

B.3 internal/schema

go
type Kind string  // KindInt ... KindArray (13 values)
type Type struct { Kind; Width, Precision, Scale int; Elem *Type }
type Expr struct { SourceDialect, Text string }
type Column struct { Name string; Type Type; Nullable bool; Default *Expr; Comment string }
type Table struct { Schema, Name string; Columns []Column; OrderKey []string }
type Database struct { Name string; Tables []Table }

func ParseCHType(chType string) (t Type, nullable bool, ok bool)
func ParsePGType(pgType string) (t Type, ok bool)
func (t Type) RenderCH() string
func (t Type) RenderPG() string

func RenderDefault(e *Expr) (text string, ok bool)

func EncodeComment(t Type, userComment string) string
func DecodeComment(raw string) (userComment string, origin *Type, ok bool)

B.4 internal/portable

go
type Writer struct { ... }
func NewWriter(w io.Writer) *Writer             // buffer w yourself
func (w *Writer) WriteTable(name string, columns []schema.Column) error
func (w *Writer) WriteRow(columns []schema.Column, values []any) error
func (w *Writer) EndTable() error
func (w *Writer) Close() error

type Reader struct { ... }
func NewReader(r io.Reader) *Reader             // buffers internally (1 MiB)
func (r *Reader) NextTable() (name string, columns []schema.Column, ok bool, err error)
func (r *Reader) NextRow(columns []schema.Column) (values []any, ok bool, err error)

A complete write:

go
pw := portable.NewWriter(bufio.NewWriterSize(f, 1<<20))
pw.WriteTable("products", cols)
pw.WriteRow(cols, []any{int64(1), "Sourdough loaf", "6.50"})
pw.EndTable()
pw.Close()

and a complete read:

go
pr := portable.NewReader(f)
for {
    name, cols, ok, err := pr.NextTable()
    if err != nil || !ok {
        break
    }
    for {
        row, ok, err := pr.NextRow(cols)
        if err != nil || !ok {
            break
        }
        fmt.Println(name, row)
    }
}

B.5 internal/compress

go
func Open(path string, c config.Compression) (io.WriteCloser, string, error)
    // gzip appends .gz, zip appends .zip and writes a single streamed
    // entry; the returned string is the path actually created
func CreatePrivate(path string) (*os.File, error) // mode 0600 whatever the umask
func EnsureExt(path, ext string) string
func InsertSuffix(base, suffix string) string   // "a.sql","x" -> "a_x.sql"

type Created struct { ... }   // files a dump created; removed if it fails
func (c *Created) Add(path string)
func (c *Created) Paths() []string
func (c *Created) RemoveAll() error   // missing files are not an error

B.6 cmd/dbdr

Function File Purpose
run main.go dispatch subcommands; choose a dump path
dumpCombined, dumpSplit main.go SQL dumps, one file or one file per database
dumpNative, dumpPortable main.go native and portable dumps
runRestore, parseRestoreArgs restore.go restore entry point and flags
readSQLStatements restore.go split a .sql file into statements
nativeEntriesFromZip restore.go <db>/<table>.native entries
discoverPortableDataFiles restore.go find base and per-table .dbdata files
runListDatabases list_databases.go list-databases
discardOnFailure main.go remove an output file if writing it failed
versionString version.go the --version line

B.7 Backend internals worth knowing

Function Package Purpose
introspect both build []*entity from the catalog
extraDependencies clickhouse edges found in DDL text
topoSort both Kahn's sort, alphabetical ties, cycles reported
hasData, shouldDumpData clickhouse which entities' rows are written
splitTopLevelExpressions clickhouse split a sorting key on top-level commas
buildChunkQuery, writeDataChunked clickhouse SQL path cursor pagination
isRetryableErr clickhouse network error or not
computeRangeBoundaries, buildRangePredicates both native and portable ranges
quantileElemType, formatRangeBoundary clickhouse write a boundary as a literal of the key's type
orderKeyColumns clickhouse sort-key columns in key order, for OrderKey
isUnsupportedQuantileType clickhouse fall back when quantiles() refuses a type
ensureDB, parseCreateDatabase postgres per-database connections; Exec routing
pgCopyHeader, pgCopyTrailer postgres splicing binary COPY streams
toSchemaTables, renderCreateTable both IR out and DDL in
chGoValue, pgGoValue each canonical value to a driver value
portableSchemaDatabaseName both honour the restore -db override
clientOptions, newHTTPClient, httpBaseURL clickhouse native TCP and HTTP(S) connections with the --tls settings
connConfig postgres connection settings with TLS set directly, and no plain-text fallback
The book← Both volumesNext volumeVol. II: dbdr in Production →
littlebit labs

Governance for databases that interface with humans, agents and machines.

Products

Minimal Core Chat Studio API Bay Agent Studio App Studio Ask Studio

Platform

Pricing Security Transparency FAQ Docs Changelog Status

Company

About Contact Book a session Terms of Service Privacy Policy Consent notice Cookie settings

Connect

GitHub X LinkedIn Discord YouTube RSS

© 2026 Littlebit Labs. All rights reserved.

Built for humans, agents and machines.

We keep only what is needed to run the site and understand traffic. Nothing is sold.