# Application Programming Interface Source: https://docs.wirekite.io/apicli/api Complete reference for the Wirekite REST API — every endpoint customers can call from scripts or applications. ## Getting Started ### Server The API is a single Go binary, `wirekite-api`, listening on HTTPS. * **Default port:** `9443` (override with `--port`) * **Base URL:** `https://:9443` * **Version prefix:** every path begins with `/v1/` * **TLS:** self-signed cert at `api/certs/server.crt` by default; override with `--cert` / `--key` **Start command:** ```bash theme={null} ./api/wirekite-api --port 9443 --cert ./api/certs/server.crt --key ./api/certs/server.key ``` ### Authentication All endpoints except `/v1/health` require a Bearer token: ``` Authorization: Bearer ``` Keys live in `api/config/api_keys.json`. Create one before calling protected endpoints: ```json theme={null} { "keys": { "k_a1b2c3...": { "name": "default", "created_at": "2026-04-24T00:00:00Z" } } } ``` Auth failures return `401 Unauthorized` with `error.code = "AUTH_FAILED"`. ### Response Envelope Every response uses the same JSON shape: ```json theme={null} { "success": true, "result": { }, "error": null, "logs": { "extractor": "…tail of log…", "loader": "…" }, "duration": "2m15s" } ``` * `result` — endpoint-specific payload; `null` on error. * `error` — `{ "code": "...", "message": "...", "details": {...} }` on error; `null` on success. * `logs` — optional, included for synchronous operations. * `duration` — optional, elapsed wall-clock time. ### Error Codes | `error.code` | HTTP | Meaning | | ----------------------------- | --------- | -------------------------------------------------------------- | | `AUTH_FAILED` | 401 | Missing or invalid Bearer token | | `INVALID_REQUEST` | 400 | Malformed body / bad parameters | | `MIGRATION_NOT_FOUND` | 404 | Migration does not exist | | `SOURCE_NOT_FOUND` | 404 / 400 | Source does not exist / not created | | `TARGET_NOT_FOUND` | 404 / 400 | Target does not exist / not created | | `OPERATION_CONFLICT` | 409 | Another operation already running on this migration | | `OPERATION_NOT_FOUND` | 404 | Operation id unknown | | `CONNECTION_REFUSED` | 200 / 500 | Connection test failed (details in `error.details`) | | `SCHEMA_APPLY_FAILED` | 500 | Schema apply exited non-zero | | `OBJECTS_APPLY_FAILED` | 500 | Objects apply exited non-zero | | `EXTRACTOR_FAILED` | 500 | Data/change extractor exited non-zero | | `LOADER_FAILED` | 500 | Data/change loader exited non-zero | | `ORCHESTRATOR_FAILED` | 500 | Orchestrator startup failed | | `RESET_FAILED` | 500 | Reset operation failed | | `VALIDATE_FAILED` | 500 | Data validation failed | | `DATA_FAILED` | 500 | Data migration failed | | `REPLICATION_FAILED` | 500 | Replication failed | | `FIREBOLT_SCHEMA_PUBLIC_ONLY` | 400 | Firebolt target requires `public` schema (use `schema_rename`) | ### Synchronous vs. Asynchronous | Category | Behavior | Endpoints | | ---------------- | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Synchronous** | HTTP blocks until done (≤ 15 min). Response includes `result` + `logs` + `duration`. | All CRUD, `/prereqs`, `/validate`, `/schema/extract`, `/schema/apply`, `/objects/apply`, `/reset`, `/validate` (data), `/sources/test`, `/targets/test`, `/queues/test`, pause/resume, health | | **Asynchronous** | Returns immediately with `operation_id`. Poll `/v1/migrations/:name/status` or `/v1/operations/:id`. | `/data`, `/replication`, `/replication-queue`, `/data-replication` | Async endpoints accept an optional `X-Request-Id: ` header. Repeating the same request id returns the same operation — safe for retries across flaky networks. ### Conventions in examples The examples below use these shell variables: ```bash theme={null} HOST=localhost # or your server host TOKEN= CURL='curl -sk' # -k skips self-signed cert verification ``` *** ## All Endpoints at a Glance | Method | Path | Sync? | | ------ | ----------------------------------------------- | ------------- | | GET | `/v1/health` | sync (public) | | PUT | `/v1/sources/:name` | sync | | GET | `/v1/sources/:name` | sync | | GET | `/v1/sources` | sync | | DELETE | `/v1/sources/:name` | sync | | POST | `/v1/sources/test` | sync | | PUT | `/v1/targets/:name` | sync | | GET | `/v1/targets/:name` | sync | | GET | `/v1/targets` | sync | | DELETE | `/v1/targets/:name` | sync | | POST | `/v1/targets/test` | sync | | POST | `/v1/queues/test` | sync | | PUT | `/v1/migrations/:name` | sync | | GET | `/v1/migrations/:name` | sync | | GET | `/v1/migrations` | sync | | DELETE | `/v1/migrations/:name` | sync | | POST | `/v1/prereqs` | sync | | POST | `/v1/validate` | sync | | POST | `/v1/migrations/:name/schema/extract` | sync | | POST | `/v1/migrations/:name/schema/apply` | sync | | POST | `/v1/migrations/:name/objects/apply` | sync | | POST | `/v1/migrations/:name/data` | **async** | | POST | `/v1/migrations/:name/replication` | **async** | | POST | `/v1/migrations/:name/replication/pause` | sync | | POST | `/v1/migrations/:name/replication/resume` | sync | | POST | `/v1/migrations/:name/replication-queue` | **async** | | POST | `/v1/migrations/:name/replication-queue/pause` | sync | | POST | `/v1/migrations/:name/replication-queue/resume` | sync | | POST | `/v1/migrations/:name/data-replication` | **async** | | POST | `/v1/migrations/:name/reset` | sync | | POST | `/v1/migrations/:name/validate` | sync | | GET | `/v1/migrations/:name/status` | sync | | GET | `/v1/operations` | sync | | GET | `/v1/operations/:id` | sync | | POST | `/v1/operations/:id/cancel` | sync | | POST | `/v1/operations/:id/stop` | sync | *** ## Health ### `GET /v1/health` Public, no auth. Returns `200 OK`. ```bash theme={null} $CURL https://$HOST:9443/v1/health # → {"status":"ok"} ``` *** ## Sources Supported `type`: `mysql`, `mariadb`, `postgres`, `oracle`, `sqlserver`. ### `PUT /v1/sources/:name` Create or replace a source. **Request body:** ```json theme={null} { "type": "mysql", "parameters": { "host": "10.0.0.1", "port": "3306", "username": "wirekite", "password": "secret", "database": "app" } } ``` **Response `result`:** `{ "name": "mysql-prod", "type": "mysql" }` ```bash theme={null} $CURL -X PUT https://$HOST:9443/v1/sources/mysql-prod \ -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ -d '{"type":"mysql","parameters":{"host":"10.0.0.1","port":"3306","username":"wirekite","password":"secret","database":"app"}}' ``` ### `GET /v1/sources/:name` Returns the source; sensitive params (password, etc.) are masked as `"***"`. ### `GET /v1/sources` Returns `{ "sources": [ { name, type, parameters } ... ] }` (sensitive masked). ### `DELETE /v1/sources/:name` Deletes the source. Fails with `INVALID_REQUEST` if any migration still references it. ### `POST /v1/sources/test` Test a connection without saving. Body has the same shape as `PUT`. **Response `result`:** `{ "connected": true, "message": "…" }` *** ## Targets Supported `type`: * **Database targets:** `mysql`, `mariadb`, `postgres`, `oracle`, `sqlserver`, `snowflake`, `bigquery`, `spanner`, `firebolt`, `databricks`, `singlestore`, `mongodb` * **Queue targets:** `kafka`, `redpanda`, `pubsub` ### `PUT /v1/targets/:name` Create or replace a target. **Database target body** (e.g. Spanner): ```json theme={null} { "type": "spanner", "parameters": { "project": "my-project", "instance": "my-instance", "database": "my-db", "credentials_file": "/path/to/sa.json" } } ``` **Queue target body** (Kafka/Redpanda): ```json theme={null} { "type": "kafka", "parameters": { "brokers": "broker1:9092,broker2:9092", "topic": "wirekite-changes", "batchSize": "1", "compression": "snappy" } } ``` `batchSize` optional (default `1`); `compression` optional (`none|snappy|lz4|zstd`). **Response `result`:** `{ "name": "...", "type": "..." }` ### `GET /v1/targets/:name` Get one (sensitive masked). ### `GET /v1/targets` List all. ### `DELETE /v1/targets/:name` Fails if referenced by a migration. ### `POST /v1/targets/test` Test a database target connection. Body same shape as `PUT`. Queue types are rejected — use `/v1/queues/test` instead. ### `POST /v1/queues/test` Test a Kafka/Redpanda broker + topic without saving. ```json theme={null} { "type": "kafka", "brokers": "broker1:9092,broker2:9092", "topic": "wirekite-changes" } ``` **Response `result`:** `{ "ok": true, "message": "broker reachable, topic 'wirekite-changes' found" }` *** ## Migrations A migration binds one source to one or both of `fileTarget` (DB target) and `queueTarget` (Kafka/Redpanda target). At least one must be provided. Most operations require `fileTarget`; queue-only CDC uses `/replication-queue`. ### `PUT /v1/migrations/:name` Create or replace a migration. **Body:** ```json theme={null} { "source": "mysql-prod", "fileTarget": "spanner-prod", "queueTarget": "kafka-prod", "tables": ["app.customers", "app.orders"], "threads": 4, "rows_per_file": 50000, "schema_rename": "app:public", "logDetail": "basic" } ``` Required: `source`, `tables`, and at least one of `fileTarget` / `queueTarget`. Optional: `threads`, `rows_per_file`, `schema_rename`, `logDetail` (`"basic"` default, or `"verbose"`). **Response `result`:** `{ "name": "...", "source": "...", "fileTarget": "...", "queueTarget": "...", "tables": }` ### `GET /v1/migrations/:name` Return the migration config. ### `GET /v1/migrations` List all as `{ "migrations": [ { name, source, fileTarget, queueTarget, tables: } ... ] }`. ### `DELETE /v1/migrations/:name` Delete migration + working directory. Rejects with `OPERATION_CONFLICT` if an operation is still running. *** ## Prerequisites & Validation ### `POST /v1/prereqs` Get SQL that must be run on source and target before migration works. Does **not** execute anything. **Body:** ```json theme={null} { "source": { "type": "mysql", "parameters": {"host":"...","port":"3306","username":"...","database":"app"} }, "target": { "type": "spanner", "parameters": {"project":"...","instance":"...","database":"..."} }, "tables": ["app.customers","app.orders"], "mode": "data+replication", "schema_rename": "app:public" } ``` `mode`: one of `data`, `replication`, `data+replication` (controls which grants are included). **Response `result`:** ```json theme={null} { "source_commands": "GRANT SELECT ON app.customers TO 'wirekite'@'%';\n...", "target_commands": "CREATE SCHEMA public;\nGRANT ... ;\n..." } ``` ### `POST /v1/validate` Actually connect and check every prerequisite is satisfied. Body same shape as `/prereqs`, plus valid `password` values. **Response `result`:** ```json theme={null} { "ready": false, "checks": [ { "name": "source: SELECT on app.customers", "passed": true }, { "name": "source: binlog_format=ROW", "passed": false, "error": "binlog_format is 'STATEMENT'" } ] } ``` *** ## Schema ### `POST /v1/migrations/:name/schema/extract` Extract DDL from source. Requires `fileTarget`. Produces `tables-schema.sql`, `objects-schema.sql`, `drop-tables.sql` inside the migration working directory. Times out after 15 minutes. **Response `result`:** `{ "sql_file": "/path/to/tables-schema.sql", "tables": }` ### `POST /v1/migrations/:name/schema/apply` Apply DDL to target. Idempotent. **Body (optional):** `{ "sql_file": "/custom/path.sql" }` — defaults to the extracted `tables-schema.sql`. **Response `result`:** `{ "tables_created": }` *** ## Objects ### `POST /v1/migrations/:name/objects/apply` Apply database objects (views, procedures, triggers, functions) to the target. Runs after `schema/extract`. Partial failures are reported rather than aborting. **Response `result`:** `{ "objects_succeeded": , "objects_failed": }` *** ## Data Migration (async) ### `POST /v1/migrations/:name/data` Start data load (extract → move → load). Returns immediately. **Body (optional):** ```json theme={null} { "resume": false } ``` Optional header: `X-Request-Id: ` for safe retries. **Response `result`:** ```json theme={null} { "operation_id": "op-20260424-a1b2c3", "status": "running", "started_at": "2026-04-24T10:00:00Z" } ``` Poll `/v1/migrations/:name/status` or `/v1/operations/:id` for progress. *** ## Replication (async) ### `POST /v1/migrations/:name/replication` Start CDC replication to `fileTarget`. Requires `schema/extract` to have been run. **Body (optional):** ```json theme={null} { "resume": false, "position": "mysql-bin.000123:456" } ``` `position` format is source-type-specific (MySQL: `file:offset`; Oracle: SCN; SQL Server: hex LSN). Ignored when `resume=true`. **Response `result`:** `{ "operation_id": "...", "status": "running", "started_at": "..." }` ### `POST /v1/migrations/:name/replication/pause` Pause the running replication (process stays alive). ### `POST /v1/migrations/:name/replication/resume` Resume a paused replication. **Response `result`:** `{ "migration": "...", "action": "paused" | "resumed" }` *** ## Replication to Queue (async) Use when the migration has `queueTarget` only (no `fileTarget`). Migrations that have a `fileTarget` are rejected by this endpoint. ### `POST /v1/migrations/:name/replication-queue` Start queue-only CDC. No schema extract required. **Body (optional):** `{ "resume": false, "position": "..." }` **Response `result`:** `{ "operation_id": "...", "status": "running", "started_at": "...", "mode": "change-queue" }` ### `POST /v1/migrations/:name/replication-queue/pause` and `/resume` Same shape as `/replication/pause|resume`. *** ## Data + Replication (async, chained) ### `POST /v1/migrations/:name/data-replication` Two-phase: data load → hand off position → start CDC. Requires `fileTarget`. **Body (optional):** `{ "resume": false, "position": "..." }` Smart resume: if `position.pkt` already exists the data phase is skipped and CDC resumes from there; otherwise the data phase re-runs. **Response `result`:** `{ "operation_id": "...", "status": "running", "started_at": "..." }` *** ## Reset ### `POST /v1/migrations/:name/reset` Reset the target. Requires `fileTarget`. **Body (optional):** `{ "mode": "drop" | "truncate" | "metadata" }` (default `drop`). **Response `result`:** * drop: `{ "mode": "drop", "tables_dropped": N, "drop_failed": M }` * truncate: `{ "mode": "truncate", "tables_truncated": N, "truncate_failed": M }` * metadata: `{ "mode": "metadata" }` *** ## Validate Data ### `POST /v1/migrations/:name/validate` Compare row counts / checksums between source and target. Safe to run during active replication. Requires `fileTarget`. **Body (optional):** `{ "sample_percent": 100 }` (0 or 100 = all rows; 1–99 = sample). **Response `result`:** ```json theme={null} { "tables_checked": 12, "tables_matched": 11, "tables_failed": 1, "mismatches": ["app.orders"] } ``` *** ## Status ### `GET /v1/migrations/:name/status` Get live progress of the currently running operation, or a summary of the last completed operation when idle. **Running (data phase):** ```json theme={null} { "operation_id": "op-20260424-a1b2c3", "mode": "data", "status": "running", "phase": "loading", "started_at": "2026-04-24T10:00:00Z", "tables": { "total": 12, "extracted": 8, "loaded": 5 }, "rows": { "extracted": 3200000, "loaded": 2100000 }, "current_table": "orders", "log_tail": "…" } ``` **Running (change phase):** ```json theme={null} { "operation_id": "...", "mode": "change", "status": "running", "phase": "replication", "rows": { "inserts": 45000, "updates": 12000, "deletes": 800 }, "lag": { "pending_files": 2 }, "log_tail": "…" } ``` **Idle:** ```json theme={null} { "operation_id": null, "status": "idle", "last_operation": { "id": "...", "mode": "data", "status": "completed", "finished_at": "...", "duration": "2h15m" } } ``` *** ## Operations Generic long-running-operation tracking across all async ops. ### `GET /v1/operations` List with filters + pagination. **Query params** (all optional): `migration=`, `status=`, `mode=`, `page_size=<1-200>` (default 50), `page_token=`. **Response `result`:** ```json theme={null} { "operations": [ { "id":"…", "migration":"…", "mode":"data", "status":"running", "started_at":"…", "finished_at":"…", "pid":12345, "request_id":"…", "error": null } ], "total": 42, "next_page_token": "50" } ``` ### `GET /v1/operations/:id` Full detail including `result`, `error`, and per-binary `logs` tails. ### `POST /v1/operations/:id/cancel` Graceful termination (SIGTERM). **Response `result`:** `{ "operation_id":"…", "status":"cancelled" }` ### `POST /v1/operations/:id/stop` Force kill (SIGKILL) + cleanup of orphaned child processes. **Response `result`:** `{ "operation_id":"…", "status":"stopped" }` # Command Line Interface Source: https://docs.wirekite.io/apicli/cli Complete reference for the wirekite-cli command-line tool. Every command wraps a single REST API call. The CLI binary `wirekite-cli` wraps the REST API. Every command maps to one REST call (noted as `→ METHOD path`). ## Global Flags Set on every command, or via environment variable. | Flag | Env | Default | Description | | ----------------- | ------------------ | ------------------------ | ------------------------------------------------- | | `--server ` | `WIREKITE_SERVER` | `https://localhost:9443` | API base URL | | `--api-key ` | `WIREKITE_API_KEY` | — | Bearer token | | `--insecure` | — | false | Skip TLS cert verification (dev / self-signed) | | `--json` | — | false | Print raw JSON response instead of formatted text | **Example — set once in the shell:** ```bash theme={null} export WIREKITE_SERVER=https://api.example.com:9443 export WIREKITE_API_KEY=k_a1b2c3... ./wirekite-cli source list ``` *** ## All Commands at a Glance | Command | Purpose | | ------------------------------------------------------------- | ----------------------------------- | | `wirekite health` | Health check | | `wirekite source create` / `get` / `list` / `delete` / `test` | Manage sources | | `wirekite target create` / `get` / `list` / `delete` / `test` | Manage targets (DB and queue) | | `wirekite migration create` / `get` / `list` / `delete` | Manage migrations | | `wirekite prereqs` | Print SQL prerequisites | | `wirekite validate` | Check all prerequisites | | `wirekite schema extract` / `apply` | Schema DDL | | `wirekite objects apply` | Apply views / procedures / triggers | | `wirekite data start` | Data migration (async) | | `wirekite replication start` / `pause` / `resume` | File-based CDC | | `wirekite replication-queue start` / `pause` / `resume` | Queue-only CDC | | `wirekite data-replication start` | Data + CDC chained | | `wirekite reset` | Drop / truncate / clear metadata | | `wirekite validate-data` | Row-count / checksum validation | | `wirekite status` | Current progress | | `wirekite operation list` / `get` / `cancel` / `stop` | Operation tracking | *** ## `wirekite health` No flags. → `GET /v1/health`. *** ## `wirekite source …` `--param key=value` is repeatable and provides the connection parameters (`host`, `port`, `username`, `password`, `database`, etc.). | Command | Required | Optional | Calls | | --------------- | ------------------ | ---------------------------- | -------------------------- | | `source create` | `--name`, `--type` | `--param key=value` (repeat) | `PUT /v1/sources/:name` | | `source get` | `--name` | — | `GET /v1/sources/:name` | | `source list` | — | — | `GET /v1/sources` | | `source delete` | `--name` | — | `DELETE /v1/sources/:name` | | `source test` | `--type` | `--param key=value` (repeat) | `POST /v1/sources/test` | `--type` ∈ `mysql | mariadb | postgres | oracle | sqlserver`. **Example:** ```bash theme={null} wirekite-cli source create \ --name mysql-prod --type mysql \ --param host=10.0.0.1 --param port=3306 \ --param username=wirekite --param password=secret --param database=app ``` *** ## `wirekite target …` Same flag shape as `source`. Queue targets use `--param brokers=… --param topic=…` (optional `batchSize`, `compression`). | Command | Required | Optional | Calls | | --------------- | ------------------ | ---------------------------- | -------------------------- | | `target create` | `--name`, `--type` | `--param key=value` (repeat) | `PUT /v1/targets/:name` | | `target get` | `--name` | — | `GET /v1/targets/:name` | | `target list` | — | — | `GET /v1/targets` | | `target delete` | `--name` | — | `DELETE /v1/targets/:name` | | `target test` | `--type` | `--param key=value` (repeat) | `POST /v1/targets/test` | `--type` ∈ `spanner | bigquery | snowflake | databricks | singlestore | firebolt | postgres | mysql | mariadb | oracle | sqlserver | mongodb | kafka | redpanda | pubsub`. **Example (Spanner):** ```bash theme={null} wirekite-cli target create \ --name spanner-prod --type spanner \ --param project=my-project --param instance=my-inst --param database=my-db \ --param credentials_file=/path/to/sa.json ``` **Example (Kafka):** ```bash theme={null} wirekite-cli target create \ --name kafka-prod --type kafka \ --param brokers=broker1:9092,broker2:9092 --param topic=wirekite-changes \ --param compression=snappy ``` *** ## `wirekite migration …` | Command | Required | Optional | Calls | | ------------------ | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | | `migration create` | `--name`, `--source`, `--tables` (CSV), and at least one of `--file-target` / `--queue-target` | `--file-target`, `--queue-target`, `--log-detail basic\|verbose`, `--threads `, `--rows-per-file `, `--schema-rename old:new` | `PUT /v1/migrations/:name` | | `migration get` | `--name` | — | `GET /v1/migrations/:name` | | `migration list` | — | — | `GET /v1/migrations` | | `migration delete` | `--name` | — | `DELETE /v1/migrations/:name` | **Example:** ```bash theme={null} wirekite-cli migration create \ --name my-mig --source mysql-prod \ --file-target spanner-prod \ --tables app.customers,app.orders,app.products \ --threads 4 --rows-per-file 50000 \ --schema-rename app:public ``` *** ## `wirekite prereqs` / `wirekite validate` Both take the same flags. `prereqs` just prints the SQL you need to run; `validate` connects and checks each prerequisite. **Required:** `--source-type`, `--target-type`, `--tables`, `--mode` (`data | replication | data+replication`). **Optional:** `--source-param key=value` (repeat), `--target-param key=value` (repeat), `--schema-rename old:new`. **Calls:** `POST /v1/prereqs` / `POST /v1/validate`. *** ## `wirekite schema …` and `wirekite objects apply` | Command | Required | Optional | Calls | | ---------------- | ------------- | ------------------- | ------------------------------------------ | | `schema extract` | `--migration` | — | `POST /v1/migrations/:name/schema/extract` | | `schema apply` | `--migration` | `--sql-file ` | `POST /v1/migrations/:name/schema/apply` | | `objects apply` | `--migration` | — | `POST /v1/migrations/:name/objects/apply` | *** ## Data & Replication All four *start* commands default to polling status every 10 seconds and redrawing a progress line. Use `--async` for fire-and-forget (returns operation id and exits). | Command | Required | Optional | Calls | | -------------------------- | ------------- | ----------------------------------------- | ---------------------------------------------------- | | `data start` | `--migration` | `--resume`, `--async` | `POST /v1/migrations/:name/data` | | `replication start` | `--migration` | `--resume`, `--position `, `--async` | `POST /v1/migrations/:name/replication` | | `replication pause` | `--migration` | — | `POST /v1/migrations/:name/replication/pause` | | `replication resume` | `--migration` | — | `POST /v1/migrations/:name/replication/resume` | | `replication-queue start` | `--migration` | `--resume`, `--position `, `--async` | `POST /v1/migrations/:name/replication-queue` | | `replication-queue pause` | `--migration` | — | `POST /v1/migrations/:name/replication-queue/pause` | | `replication-queue resume` | `--migration` | — | `POST /v1/migrations/:name/replication-queue/resume` | | `data-replication start` | `--migration` | `--resume`, `--async` | `POST /v1/migrations/:name/data-replication` | `--position` format by source: MySQL `file:offset`, Oracle `SCN`, SQL Server hex LSN. Ignored when `--resume` is set. *** ## `wirekite reset` / `wirekite validate-data` | Command | Required | Optional | Calls | | --------------- | ------------- | -------------------------------------------------- | ------------------------------------ | | `reset` | `--migration` | `--mode drop\|truncate\|metadata` (default `drop`) | `POST /v1/migrations/:name/reset` | | `validate-data` | `--migration` | `--sample-percent <1-100>` (default 100) | `POST /v1/migrations/:name/validate` | *** ## `wirekite status` **Required:** `--migration`. → `GET /v1/migrations/:name/status`. *** ## `wirekite operation …` | Command | Required | Optional | Calls | | ------------------ | -------- | ----------------------------------- | -------------------------------- | | `operation list` | — | `--migration`, `--status`, `--mode` | `GET /v1/operations?...` | | `operation get` | `--id` | — | `GET /v1/operations/:id` | | `operation cancel` | `--id` | — | `POST /v1/operations/:id/cancel` | | `operation stop` | `--id` | — | `POST /v1/operations/:id/stop` | `cancel` sends SIGTERM (graceful); `stop` sends SIGKILL (immediate, also sweeps orphaned children). # Cassandra Source: https://docs.wirekite.io/datatypes/cassandra This page explains how Apache Cassandra (CQL) source data types are mapped to each target database. Please visit the [CQL Data Types Documentation](https://cassandra.apache.org/doc/latest/cassandra/developing/cql/types.html) for a primer on the various Cassandra datatypes. Cassandra is supported **as a source for [Target Sync](/run/targetsync) only** — there is no CDC path. See the [Cassandra Source Guide](/sourceguides/cassandra) for configuration. ### Schema Mapping Wirekite projects a CQL keyspace onto a fundamentally relational target. The structural mapping is: | CQL concept | Target concept | | ---------------------------------- | ----------------------------------------------- | | keyspace | schema (renamable via `schemaRename`) | | table | table | | partition key + clustering columns | composite `PRIMARY KEY` (in declaration order) | | regular column | nullable column | | static column | regular column (the static-ness is not modeled) | | `frozen<…>` | transparent — the inner type is used | ### Canonical Type Mapping Wirekite first converts each CQL type to an internal Wirekite type, then each target's loader maps that to a concrete column type. The source of truth is `cassandra/db_utils.CQLToWirekite`. | CQL type | Wirekite type | Notes | | ----------------------------------------- | ------------- | ------------------------------------------------------------------------------------ | | `text`, `varchar`, `ascii` | `VARCHAR` | length **synthesized** to 4000 — see [Synthesized Bounds](#synthesized-bounds) | | `tinyint` | `INT8` | | | `smallint` | `INT16` | | | `int` | `INT32` | | | `bigint` | `INT64` | | | `counter` | `INT64` | read as its current value | | `varint` | `NUMERIC` | arbitrary-precision integer — precision **synthesized** to `(38,0)` | | `decimal` | `NUMERIC` | precision/scale **synthesized** to `(38,18)` | | `float` | `FLOAT32` | | | `double` | `FLOAT64` | | | `boolean` | `BOOL` | | | `timestamp` | `TIMESTAMP` | millisecond precision, UTC | | `date` | `DATE` | | | `time` | `TIME` | nanosecond-since-midnight rendered `HH:MM:SS.ffffff` | | `uuid`, `timeuuid` | `UUID` | rendered lowercase for stable ordering | | `inet` | `VARCHAR` | IP rendered as text | | `duration` | `VARCHAR` | ISO-8601-ish text | | `blob` | `BLOB` | | | `list<…>`, `set<…>`, `map<…>`, `tuple<…>` | `JSON` | serialized to JSON — see [how collections are encoded](#how-collections-are-encoded) | | user-defined type (UDT), any unknown | `JSON` | serialized to JSON | ### Mapping to Targets The following tables show how each CQL type lands on every supported Target Sync target. #### Integer Types | Cassandra | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ---------- | ---------- | ---------- | ---------- | ------------ | ---------- | --------- | --------- | ------- | -------- | ----------- | ---------- | | `tinyint` | `smallint` | `TINYINT` | `SMALLINT` | `NUMBER(38)` | `SMALLINT` | `INTEGER` | `tinyint` | `INT64` | `INT64` | `TINYINT` | `TINYINT` | | `smallint` | `smallint` | `SMALLINT` | `SMALLINT` | `NUMBER(38)` | `SMALLINT` | `INTEGER` | `number` | `INT64` | `INT64` | `SMALLINT` | `SMALLINT` | | `int` | `integer` | `INT` | `INT` | `NUMBER(38)` | `INTEGER` | `INTEGER` | `int` | `INT64` | `INT64` | `INT` | `INT` | | `bigint` | `bigint` | `BIGINT` | `BIGINT` | `NUMBER(38)` | `BIGINT` | `BIGINT` | `bigint` | `INT64` | `INT64` | `BIGINT` | `BIGINT` | | `counter` | `bigint` | `BIGINT` | `BIGINT` | `NUMBER(38)` | `BIGINT` | `BIGINT` | `bigint` | `INT64` | `INT64` | `BIGINT` | `BIGINT` | #### Decimal Types | Cassandra | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | --------- | ---------------- | ---------------- | ---------------- | --------------- | --------- | ---------------- | --------------- | --------- | --------- | ---------------- | ---------------- | | `varint` | `numeric(38,0)` | `NUMERIC(38,0)` | `NUMERIC(38,0)` | `NUMBER(38,0)` | `DECIMAL` | `NUMERIC(38,0)` | `number(38,0)` | `NUMERIC` | `NUMERIC` | `NUMERIC(38,0)` | `DECIMAL(38,0)` | | `decimal` | `numeric(38,18)` | `NUMERIC(38,18)` | `NUMERIC(38,18)` | `NUMBER(38,18)` | `DECIMAL` | `NUMERIC(38,18)` | `number(38,18)` | `NUMERIC` | `NUMERIC` | `NUMERIC(38,18)` | `DECIMAL(38,18)` | **Spanner and BigQuery use a fixed-scale `NUMERIC`.** Spanner `NUMERIC` is precision/scale `(38,9)` and BigQuery `NUMERIC` caps at `(38,9)`. A Cassandra `decimal` carries up to scale 18, so on these two targets the scale is clamped to 9. The validator compares decimal values **numerically** (not as strings), so padding/clamping on the other targets does not produce false diffs. #### Floating Point Types | Cassandra | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | --------- | ------------------ | -------- | ---------- | --------------- | -------- | -------- | --------- | --------- | --------- | ----------- | ---------- | | `float` | `real` | `FLOAT` | `REAL` | `BINARY_FLOAT` | `DOUBLE` | `DOUBLE` | `float` | `FLOAT32` | `FLOAT64` | `FLOAT` | `FLOAT` | | `double` | `double precision` | `DOUBLE` | `FLOAT` | `BINARY_DOUBLE` | `DOUBLE` | `DOUBLE` | `float` | `FLOAT64` | `FLOAT64` | `DOUBLE` | `DOUBLE` | #### Boolean Type | Cassandra | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | --------- | ---------- | ------------ | ---------- | --------- | --------- | --------- | --------- | ------- | -------- | ------------ | ---------- | | `boolean` | `boolean` | `TINYINT(1)` | `BIT` | `CHAR(1)` | `BOOLEAN` | `BOOLEAN` | `boolean` | `BOOL` | `BOOL` | `TINYINT(1)` | `BOOLEAN` | #### Date and Time Types | Cassandra | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ----------- | ----------------------------- | ------------- | ----------- | -------------- | ------------- | ----------- | --------------- | ----------- | ---------- | ------------- | --------------- | | `timestamp` | `timestamp without time zone` | `DATETIME(6)` | `DATETIME2` | `TIMESTAMP` | `TIMESTAMP` | `TIMESTAMP` | `timestamp_ntz` | `TIMESTAMP` | `DATETIME` | `DATETIME(6)` | `TIMESTAMP_NTZ` | | `date` | `date` | `DATE` | `DATE` | `DATE` | `DATE` | `DATE` | `date` | `DATE` | `DATE` | `DATE` | `DATE` | | `time` | `time without time zone` | `TIME(6)` | `TIME` | `VARCHAR2(64)` | `VARCHAR(64)` | `TEXT` | `time` | `STRING` | `TIME` | `TIME(6)` | `STRING` | #### Character, Network & UUID Types | Cassandra | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ---------------------------- | ------------------------- | --------------- | ------------------ | ---------------- | -------------- | -------- | --------------- | -------------- | -------- | --------------- | ---------- | | `text` / `varchar` / `ascii` | `character varying(4000)` | `VARCHAR(4000)` | `VARCHAR(4000)` | `VARCHAR2(4000)` | `VARCHAR` | `TEXT` | `varchar(4000)` | `STRING(4000)` | `STRING` | `VARCHAR(4000)` | `STRING` | | `inet` | `character varying(4000)` | `VARCHAR(4000)` | `VARCHAR(4000)` | `VARCHAR2(4000)` | `VARCHAR` | `TEXT` | `varchar(4000)` | `STRING(4000)` | `STRING` | `VARCHAR(4000)` | `STRING` | | `duration` | `character varying(4000)` | `VARCHAR(4000)` | `VARCHAR(4000)` | `VARCHAR2(4000)` | `VARCHAR` | `TEXT` | `varchar(4000)` | `STRING(4000)` | `STRING` | `VARCHAR(4000)` | `STRING` | | `uuid` / `timeuuid` | `uuid` | `VARCHAR(64)` | `UNIQUEIDENTIFIER` | `VARCHAR2(128)` | `VARCHAR(128)` | `TEXT` | `varchar(64)` | `STRING` | `STRING` | `VARCHAR(64)` | `STRING` | #### Binary Type | Cassandra | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | --------- | ---------- | ------ | ---------------- | ------ | ------ | -------- | --------- | ------- | -------- | ----------- | ---------- | | `blob` | `bytea` | `BLOB` | `VARBINARY(MAX)` | `BLOB` | `BLOB` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `BLOB` | `BINARY` | #### Collection & Complex Types | Cassandra | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | -------------------------------------- | ---------- | ------ | -------------- | ------ | ------ | -------- | --------- | ------- | -------- | ----------- | ---------- | | `list` / `set` / `map` / `tuple` / UDT | `jsonb` | `JSON` | `VARCHAR(MAX)` | `CLOB` | `CLOB` | `TEXT` | `varchar` | `JSON` | `JSON` | `JSON` | `STRING` | **MariaDB** maps identically to MySQL, and **TigerData** identically to PostgreSQL. **MongoDB** is a schemaless target — scalar types land as native BSON values and JSON columns become sub-documents, so it is not shown as a column above. ### Synthesized Bounds Cassandra has **no column lengths, precisions, or scales** — `text` is unbounded and `decimal`/`varint` are arbitrary-precision. Relational targets, however, want bounded, precise column types, and some bulk loaders reject unbounded ones outright. So the schema extractor synthesizes sensible bounds: * **`varint` → `NUMERIC(38,0)`** and **`decimal` → `NUMERIC(38,18)`.** Without an explicit precision, Databricks defaults `NUMERIC` to `DECIMAL(10,0)` and overflows on a 19-digit varint. 38 is the maximum Databricks/Oracle decimal precision; scale 0 keeps varint an exact integer, and scale 18 leaves room for a fraction. Targets that prefer arbitrary precision (PostgreSQL, Firebolt) simply pad the scale. * **`text` / `varchar` / `ascii` / `inet` / `duration` → length 4000.** A length-less `VARCHAR` becomes `VARCHAR(MAX)` on SQL Server (whose BCP loader cannot bind it) and `CLOB` on Oracle (whose OCI loader cannot bulk-load it). 4000 is Oracle's `VARCHAR2` standard maximum and within SQL Server's 8000 non-MAX cap. The fixed 4000-character bound is **lossy for genuinely large Cassandra `text`.** It is ample for typical keys, labels, and short documents; tables that need larger text should raise this bound. ### How Collections Are Encoded `list`, `set`, `map`, `tuple`, and user-defined types are serialized to a single **JSON** column on the target. Wirekite does **not** explode collections into child tables, normalize maps, or model UDT fields — the relational skeleton (primary key + scalar columns) stays queryable, and the complex values ride along as JSON. To keep the diff stable across runs, the JSON is canonicalized: * `list` and `tuple` → JSON array, **order preserved**. * `set` → JSON array, **sorted** (sets are unordered in Cassandra). * `map` → JSON object with **keys sorted** and coerced to strings. * UDT → JSON object, fields in **declared order**. Complex columns **cannot be part of a primary key**, and `frozen<…>` wrappers are transparent (the inner type is used). # Db2 Source: https://docs.wirekite.io/datatypes/db2 This page explains how data types are mapped from a source IBM Db2 (LUW) database to the target databases. See the [Db2 Data Types documentation](https://www.ibm.com/docs/en/db2/11.5?topic=elements-data-types) for a primer on the various Db2 datatypes. ### Mapping The following tables explain how Db2 source datatypes are mapped to each target database. Wirekite extracts data from Db2, converts it to an internal type representation, then maps to the appropriate target type. Wirekite reads column metadata from the `SYSCAT.COLUMNS` catalog view. Unquoted Db2 identifiers are folded to uppercase in the catalog; Wirekite lowercases table and column names on output. **CDC (Replicate) type coverage is narrower than the initial data load.** The types below marked † extract correctly during a one-time **Data** load but are **not decodable from the Db2 recovery log** during **Replicate** (CDC). A tracked table with one of these columns will lose that column — and every column after it — in the change stream. The affected types are `DECFLOAT`, `GRAPHIC`, `VARGRAPHIC`, `LONG VARGRAPHIC`, `DBCLOB`, and `LONG VARCHAR`. Avoid them on tables you replicate, or keep them last in column order. #### Numeric Types | Db2 | PostgreSQL | MySQL | SQL Server | Oracle | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ------------ | ------------------ | ---------- | ---------- | --------------- | --------- | --------- | --------- | --------- | ----------- | ---------- | | `SMALLINT` | `smallint` | `SMALLINT` | `SMALLINT` | `NUMBER(38)` | `INTEGER` | `number` | `INT64` | `INT64` | `SMALLINT` | `SMALLINT` | | `INTEGER` | `integer` | `INT` | `INT` | `NUMBER(38)` | `INTEGER` | `int` | `INT64` | `INT64` | `INT` | `INT` | | `BIGINT` | `bigint` | `BIGINT` | `BIGINT` | `NUMBER(38)` | `BIGINT` | `bigint` | `INT64` | `INT64` | `BIGINT` | `BIGINT` | | `DECIMAL` | `numeric` | `NUMERIC` | `NUMERIC` | `NUMBER` | `NUMERIC` | `number` | `NUMERIC` | `NUMERIC` | `NUMERIC` | `DECIMAL` | | `NUMERIC` | `numeric` | `NUMERIC` | `NUMERIC` | `NUMBER` | `NUMERIC` | `number` | `NUMERIC` | `NUMERIC` | `NUMERIC` | `DECIMAL` | | `REAL` | `real` | `FLOAT` | `REAL` | `BINARY_FLOAT` | `DOUBLE` | `float` | `FLOAT32` | `FLOAT64` | `FLOAT` | `FLOAT` | | `DOUBLE` | `double precision` | `DOUBLE` | `FLOAT` | `BINARY_DOUBLE` | `DOUBLE` | `float` | `FLOAT64` | `FLOAT64` | `DOUBLE` | `DOUBLE` | | `DECFLOAT` † | `double precision` | `DOUBLE` | `FLOAT` | `BINARY_DOUBLE` | `DOUBLE` | `float` | `FLOAT64` | `FLOAT64` | `DOUBLE` | `DOUBLE` | `DECIMAL`/`NUMERIC` carry their precision and scale through to the target. Db2's maximum `DECIMAL` precision is 31; a source column with higher precision is capped at 31 when Db2 is the **target**. `DECFLOAT` is decimal floating-point with no fixed scale, so it maps to a 64-bit float rather than a fixed `NUMERIC(p,s)`. #### Boolean Type | Db2 | PostgreSQL | MySQL | SQL Server | Oracle | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | --------- | ---------- | ------------ | ---------- | --------- | --------- | --------- | ------- | -------- | ------------ | ---------- | | `BOOLEAN` | `boolean` | `TINYINT(1)` | `BIT` | `CHAR(1)` | `BOOLEAN` | `boolean` | `BOOL` | `BOOL` | `TINYINT(1)` | `BOOLEAN` | #### Character Types | Db2 | PostgreSQL | MySQL | SQL Server | Oracle | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | -------------------- | ------------------- | ---------- | -------------- | ---------- | -------- | --------- | -------- | -------- | ----------- | ---------- | | `CHAR` / `CHARACTER` | `character` | `CHAR` | `CHAR` | `CHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `CHAR` | `STRING` | | `VARCHAR` | `character varying` | `VARCHAR` | `VARCHAR` | `VARCHAR2` | `TEXT` | `varchar` | `STRING` | `STRING` | `VARCHAR` | `STRING` | | `LONG VARCHAR` † | `character varying` | `VARCHAR` | `VARCHAR` | `VARCHAR2` | `TEXT` | `varchar` | `STRING` | `STRING` | `VARCHAR` | `STRING` | | `CLOB` | `text` | `LONGTEXT` | `VARCHAR(MAX)` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `LONGTEXT` | `STRING` | #### Graphic (Double-Byte) Types | Db2 | PostgreSQL | MySQL | SQL Server | Oracle | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ------------------- | ------------------- | ---------- | -------------- | ---------- | -------- | --------- | -------- | -------- | ----------- | ---------- | | `GRAPHIC` † | `character` | `CHAR` | `CHAR` | `CHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `CHAR` | `STRING` | | `VARGRAPHIC` † | `character varying` | `VARCHAR` | `VARCHAR` | `VARCHAR2` | `TEXT` | `varchar` | `STRING` | `STRING` | `VARCHAR` | `STRING` | | `LONG VARGRAPHIC` † | `character varying` | `VARCHAR` | `VARCHAR` | `VARCHAR2` | `TEXT` | `varchar` | `STRING` | `STRING` | `VARCHAR` | `STRING` | | `DBCLOB` † | `text` | `LONGTEXT` | `VARCHAR(MAX)` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `LONGTEXT` | `STRING` | Db2 graphic (DBCS) types store Unicode text and fold to the same internal representation as their character counterparts (`GRAPHIC`→`CHAR`, `VARGRAPHIC`→`VARCHAR`, `DBCLOB`→`CLOB`). On a UTF-8 database the values are preserved through the initial load. They are not supported by CDC — see the warning above. #### Binary Types | Db2 | PostgreSQL | MySQL | SQL Server | Oracle | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ----------- | ---------- | ----------- | ---------------- | ------ | -------- | --------- | ------- | -------- | ----------- | ---------- | | `BINARY` | `bytea` | `BINARY` | `BINARY` | `RAW` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `BINARY` | `BINARY` | | `VARBINARY` | `bytea` | `VARBINARY` | `VARBINARY` | `RAW` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `VARBINARY` | `BINARY` | | `BLOB` | `bytea` | `BLOB` | `VARBINARY(MAX)` | `BLOB` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `BLOB` | `BINARY` | #### Date and Time Types | Db2 | PostgreSQL | MySQL | SQL Server | Oracle | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ----------- | ----------------------------- | ------------- | ----------- | -------------- | ----------- | --------------- | ----------- | ---------- | ------------- | --------------- | | `DATE` | `date` | `DATE` | `DATE` | `DATE` | `DATE` | `date` | `DATE` | `DATE` | `DATE` | `DATE` | | `TIME` | `time without time zone` | `TIME(6)` | `TIME` | `VARCHAR2(64)` | `TEXT` | `time` | `STRING` | `TIME` | `TIME(6)` | `STRING` | | `TIMESTAMP` | `timestamp without time zone` | `DATETIME(6)` | `DATETIME2` | `TIMESTAMP` | `TIMESTAMP` | `timestamp_ntz` | `TIMESTAMP` | `DATETIME` | `DATETIME(6)` | `TIMESTAMP_NTZ` | Db2 `TIME` has no sub-second precision. `TIMESTAMP` supports fractional seconds up to 12 digits; Wirekite preserves microsecond precision (`.FF6`) on the wire. #### Other Types | Db2 | PostgreSQL | MySQL | SQL Server | Oracle | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ------------------ | ------------------- | --------- | ---------- | ---------- | -------- | --------- | -------- | -------- | ----------- | ---------- | | `XML` | `xml` | `TEXT` | `XML` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `TEXT` | `STRING` | | `(Any other type)` | `character varying` | `VARCHAR` | `VARCHAR` | `VARCHAR2` | `TEXT` | `varchar` | `STRING` | `STRING` | `VARCHAR` | `STRING` | Any Db2 type not listed above (for example `ROWID`, `TIMESTAMP WITH TIME ZONE`, or `CHAR FOR BIT DATA`) falls back to a wide character type on the initial load, with a warning logged. These fallback types are not supported by CDC. # MySQL / MariaDB / SingleStore Source: https://docs.wirekite.io/datatypes/mysql This page explains how data types are mapped from a source MySQL and MariaDB database to target databases. Please visit the [MySQL Data Types Documentation](https://dev.mysql.com/doc/refman/8.4/en/data-types.html) to get a primer on the various MySQL and MariaDB datatypes. ### Mapping The following tables explain how MySQL/MariaDB source datatypes are mapped to each target database. Wirekite extracts data from MySQL, converts it to an internal type representation, then maps to the appropriate target type. #### Numeric Types | MySQL | PostgreSQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | -------------------- | ------------------ | ------------- | --------------- | --------------- | --------- | --------- | --------- | --------- | -------------------- | ---------- | | `TINYINT` | `smallint` | `SMALLINT` | `NUMBER(38)` | `SMALLINT` | `INTEGER` | `tinyint` | `INT64` | `INT64` | `TINYINT` | `TINYINT` | | `TINYINT UNSIGNED` | `smallint` | `SMALLINT` | `NUMBER(38)` | `SMALLINT` | `INTEGER` | `number` | `INT64` | `INT64` | `TINYINT UNSIGNED` | `SMALLINT` | | `SMALLINT` | `smallint` | `SMALLINT` | `NUMBER(38)` | `SMALLINT` | `INTEGER` | `number` | `INT64` | `INT64` | `SMALLINT` | `SMALLINT` | | `SMALLINT UNSIGNED` | `integer` | `INT` | `NUMBER(38)` | `INTEGER` | `INTEGER` | `number` | `INT64` | `INT64` | `SMALLINT UNSIGNED` | `INT` | | `MEDIUMINT` | `integer` | `INT` | `NUMBER(38)` | `INTEGER` | `INTEGER` | `number` | `INT64` | `INT64` | `MEDIUMINT` | `INT` | | `MEDIUMINT UNSIGNED` | `integer` | `INT` | `NUMBER(38)` | `INTEGER` | `INTEGER` | `number` | `INT64` | `INT64` | `MEDIUMINT UNSIGNED` | `INT` | | `INT` | `integer` | `INT` | `NUMBER(38)` | `INTEGER` | `INTEGER` | `int` | `INT64` | `INT64` | `INT` | `INT` | | `INT UNSIGNED` | `bigint` | `BIGINT` | `NUMBER(38)` | `BIGINT` | `BIGINT` | `number` | `INT64` | `INT64` | `INT UNSIGNED` | `DECIMAL` | | `BIGINT` | `bigint` | `BIGINT` | `NUMBER(38)` | `BIGINT` | `BIGINT` | `bigint` | `INT64` | `INT64` | `BIGINT` | `BIGINT` | | `BIGINT UNSIGNED` | `numeric(21)` | `NUMERIC(21)` | `NUMBER(38)` | `DECIMAL(20,0)` | `NUMERIC` | `number` | `NUMERIC` | `NUMERIC` | `BIGINT UNSIGNED` | `DECIMAL` | | `DECIMAL` | `decimal` | `DECIMAL` | `NUMBER` | `DECIMAL` | `NUMERIC` | `number` | `NUMERIC` | `NUMERIC` | `DECIMAL` | `DECIMAL` | | `DECIMAL UNSIGNED` | `numeric` | `NUMERIC(38)` | `NUMBER` | `DECIMAL` | `NUMERIC` | `number` | `NUMERIC` | `NUMERIC` | `DECIMAL UNSIGNED` | `DECIMAL` | | `FLOAT` | `real` | `REAL` | `BINARY_FLOAT` | `DOUBLE` | `DOUBLE` | `float` | `FLOAT32` | `FLOAT64` | `FLOAT` | `FLOAT` | | `FLOAT UNSIGNED` | `double precision` | `REAL` | `BINARY_FLOAT` | `DOUBLE` | `DOUBLE` | `float` | `FLOAT64` | `FLOAT64` | `FLOAT UNSIGNED` | `DOUBLE` | | `DOUBLE` | `double precision` | `FLOAT` | `BINARY_DOUBLE` | `DOUBLE` | `DOUBLE` | `float` | `FLOAT64` | `FLOAT64` | `DOUBLE` | `DOUBLE` | | `DOUBLE UNSIGNED` | N/A | N/A | `BINARY_DOUBLE` | `DOUBLE` | N/A | N/A | `NUMERIC` | `NUMERIC` | `DOUBLE UNSIGNED` | `DECIMAL` | | `BIT` | `bit varying` | `VARCHAR` | `VARCHAR2` | `VARCHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `BIT` | `STRING` | | `BOOL` / `BOOLEAN` | `boolean` | `BIT` | `CHAR(1)` | `SMALLINT` | `BOOLEAN` | `boolean` | `BOOL` | `BOOL` | `TINYINT(1)` | `BOOLEAN` | | `YEAR` | `smallint` | `SMALLINT` | `NUMBER(38)` | `SMALLINT` | `INTEGER` | `int` | `INT64` | `INT64` | `YEAR` | `INT` | MySQL BIT columns larger than 64 bits are automatically mapped to VARCHAR since MySQL's BIT type has a 64-bit maximum. #### Date and Time Types | MySQL | PostgreSQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ----------- | ----------------------------- | ------------- | -------------------------------- | ------------- | ----------- | --------------- | ----------- | ---------- | ------------- | ----------- | | `DATE` | `date` | `DATE` | `DATE` | `DATE` | `DATE` | `date` | `DATE` | `DATE` | `DATE` | `DATE` | | `TIME` | `time without time zone` | `TIME` | `VARCHAR2(64)` | `VARCHAR(64)` | `TEXT` | `time` | `STRING` | `TIME` | `TIME(6)` | `STRING` | | `DATETIME` | `timestamp without time zone` | `DATETIME2` | `TIMESTAMP` | `TIMESTAMP` | `TIMESTAMP` | `timestamp_ntz` | `TIMESTAMP` | `DATETIME` | `DATETIME(6)` | `TIMESTAMP` | | `TIMESTAMP` | `varchar(64)` | `VARCHAR(32)` | `TIMESTAMP WITH LOCAL TIME ZONE` | `TIMESTAMP` | `TIMESTAMP` | `timestamp_ltz` | `STRING` | `STRING` | `DATETIME(6)` | `STRING` | #### Character Types | MySQL | PostgreSQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ------------ | ------------------- | -------------- | --------------- | -------------- | -------- | --------- | -------- | -------- | ------------ | ---------- | | `CHAR` | `character` | `CHAR` | `CHAR` | `CHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `CHAR` | `STRING` | | `VARCHAR` | `character varying` | `VARCHAR` | `VARCHAR2` | `VARCHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `VARCHAR` | `STRING` | | `TINYTEXT` | `text` | `VARCHAR(MAX)` | `VARCHAR2(255)` | `VARCHAR(255)` | `TEXT` | `varchar` | `STRING` | `STRING` | `TINYTEXT` | `STRING` | | `TEXT` | `text` | `VARCHAR(MAX)` | `CLOB` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `LONGTEXT` | `STRING` | | `MEDIUMTEXT` | `text` | `VARCHAR(MAX)` | `CLOB` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `MEDIUMTEXT` | `STRING` | | `LONGTEXT` | `text` | `VARCHAR(MAX)` | `CLOB` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `LONGTEXT` | `STRING` | | `JSON` | `jsonb` | `VARCHAR(MAX)` | `CLOB` | `CLOB` | `TEXT` | `varchar` | `JSON` | `JSON` | `JSON` | `STRING` | #### Binary Types | MySQL | PostgreSQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ------------ | ---------- | ---------------- | ------ | ----------- | -------- | --------- | ------- | -------- | ------------ | ---------- | | `BINARY` | `bytea` | `BINARY` | `RAW` | `BINARY` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `BINARY` | `BINARY` | | `VARBINARY` | `bytea` | `VARBINARY` | `RAW` | `VARBINARY` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `VARBINARY` | `BINARY` | | `TINYBLOB` | `bytea` | `VARBINARY` | `RAW` | `VARBINARY` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `TINYBLOB` | `BINARY` | | `BLOB` | `bytea` | `VARBINARY(MAX)` | `BLOB` | `BLOB` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `BLOB` | `BINARY` | | `MEDIUMBLOB` | `bytea` | `VARBINARY(MAX)` | `BLOB` | `BLOB` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `MEDIUMBLOB` | `BINARY` | | `LONGBLOB` | `bytea` | `VARBINARY(MAX)` | `BLOB` | `BLOB` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `LONGBLOB` | `BINARY` | #### Set Types | MySQL | PostgreSQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ------ | ------------- | ------------- | ---------- | --------------- | -------- | ------------- | -------- | -------- | ----------- | ---------- | | `ENUM` | `varchar(64)` | `VARCHAR(64)` | `VARCHAR2` | `VARCHAR(4000)` | `TEXT` | `varchar(64)` | `STRING` | `STRING` | `ENUM` | `STRING` | | `SET` | `varchar(64)` | `VARCHAR(64)` | `VARCHAR2` | `VARCHAR(4000)` | `TEXT` | `varchar(64)` | `STRING` | `STRING` | `SET` | `STRING` | When the target is also MySQL, MariaDB, or SingleStore, ENUM and SET types are preserved natively with their original value definitions rather than being converted to VARCHAR. #### Spatial Types | MySQL | PostgreSQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ------------ | ---------- | --------------- | ---------------- | --------------- | -------- | --------------- | -------- | -------- | --------------- | ---------- | | `POINT` | `point` | `VARCHAR(256)` | `VARCHAR2(256)` | `VARCHAR(4000)` | `TEXT` | `varchar(256)` | `STRING` | `STRING` | `VARCHAR(256)` | `STRING` | | `LINESTRING` | `text` | `VARCHAR(256)` | `VARCHAR2(256)` | `VARCHAR(4000)` | `TEXT` | `varchar(256)` | `STRING` | `STRING` | `VARCHAR(256)` | `STRING` | | `POLYGON` | `polygon` | `VARCHAR(1024)` | `VARCHAR2(1024)` | `VARCHAR(4000)` | `TEXT` | `varchar(1024)` | `STRING` | `STRING` | `VARCHAR(1024)` | `STRING` | | `GEOMETRY` | `text` | `VARCHAR(1024)` | `VARCHAR2(1024)` | `VARCHAR(4000)` | `TEXT` | `varchar` | `STRING` | `STRING` | `VARCHAR(1024)` | `STRING` | | `MULTIPOINT` | `text` | `VARCHAR(1024)` | `VARCHAR2(1024)` | `VARCHAR(4000)` | `TEXT` | `varchar` | `STRING` | `STRING` | `VARCHAR(1024)` | `STRING` | # Oracle Source: https://docs.wirekite.io/datatypes/oracle This page explains how data types are mapped from a source Oracle database to the target databases. Please visit the [Oracle Data Types Documentation](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Data-Types.html#GUID-7B72E154-677A-4342-A1EA-C74C1EA928E6) to get a primer on the various Oracle datatypes. ### Mapping The following tables explain how Oracle source datatypes are mapped to each target database. Wirekite extracts data from Oracle, converts it to an internal type representation, then maps to the appropriate target type. #### Numeric Types | Oracle | PostgreSQL | MySQL | SQL Server | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | --------------- | ------------------ | --------- | ---------- | --------- | --------- | --------- | --------- | --------- | ----------- | ---------- | | `NUMBER` | `numeric` | `NUMERIC` | `NUMERIC` | `DECIMAL` | `NUMERIC` | `number` | `NUMERIC` | `NUMERIC` | `NUMERIC` | `DECIMAL` | | `FLOAT` | `double precision` | `DOUBLE` | `FLOAT` | `DOUBLE` | `DOUBLE` | `float` | `FLOAT64` | `FLOAT64` | `DOUBLE` | `DOUBLE` | | `BINARY_FLOAT` | `real` | `FLOAT` | `REAL` | `DOUBLE` | `DOUBLE` | `float` | `FLOAT32` | `FLOAT64` | `FLOAT` | `FLOAT` | | `BINARY_DOUBLE` | `double precision` | `DOUBLE` | `FLOAT` | `DOUBLE` | `DOUBLE` | `float` | `FLOAT64` | `FLOAT64` | `DOUBLE` | `DOUBLE` | #### Date and Time Types | Oracle | PostgreSQL | MySQL | SQL Server | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | -------------------------------- | ----------------------------- | ------------- | ------------- | -------------- | ------------- | --------------- | ----------- | ----------- | ------------- | --------------- | | `DATE` | `timestamp without time zone` | `DATETIME(6)` | `DATETIME2` | `TIMESTAMP` | `TIMESTAMP` | `timestamp_ntz` | `TIMESTAMP` | `DATETIME` | `DATETIME(6)` | `TIMESTAMP` | | `TIMESTAMP` | `timestamp without time zone` | `DATETIME(6)` | `DATETIME2` | `TIMESTAMP` | `TIMESTAMP` | `timestamp_ntz` | `TIMESTAMP` | `DATETIME` | `DATETIME(6)` | `TIMESTAMP_NTZ` | | `TIMESTAMP WITH TIME ZONE` | `timestamp with time zone` | `VARCHAR(32)` | `VARCHAR(32)` | `TIMESTAMP` | `TIMESTAMPTZ` | `timestamp_tz` | `STRING` | `TIMESTAMP` | `VARCHAR(32)` | `TIMESTAMP` | | `TIMESTAMP WITH LOCAL TIME ZONE` | `varchar(64)` | `DATETIME(6)` | `VARCHAR(32)` | `TIMESTAMP` | `TIMESTAMP` | `timestamp_ltz` | `STRING` | `STRING` | `DATETIME(6)` | `STRING` | | `INTERVAL YEAR TO MONTH` | `interval` | `VARCHAR(64)` | `VARCHAR(64)` | `VARCHAR(128)` | `TEXT` | `varchar(64)` | `STRING` | `STRING` | `VARCHAR(64)` | `STRING` | | `INTERVAL DAY TO SECOND` | `interval` | `VARCHAR(64)` | `VARCHAR(64)` | `VARCHAR(128)` | `TEXT` | `varchar(64)` | `STRING` | `STRING` | `VARCHAR(64)` | `STRING` | #### Character Types | Oracle | PostgreSQL | MySQL | SQL Server | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ----------- | ------------------- | ---------- | --------------- | --------- | -------- | --------- | -------- | -------- | ----------- | ---------- | | `CHAR` | `character` | `CHAR` | `CHAR` | `CHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `CHAR` | `STRING` | | `NCHAR` | `character` | `CHAR` | `NCHAR` | `CHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `CHAR` | `STRING` | | `VARCHAR2` | `character varying` | `VARCHAR` | `VARCHAR` | `VARCHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `VARCHAR` | `STRING` | | `NVARCHAR2` | `character varying` | `VARCHAR` | `NVARCHAR` | `VARCHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `VARCHAR` | `STRING` | | `CLOB` | `text` | `LONGTEXT` | `VARCHAR(MAX)` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `LONGTEXT` | `STRING` | | `NCLOB` | `text` | `LONGTEXT` | `NVARCHAR(MAX)` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `LONGTEXT` | `STRING` | #### Binary Types | Oracle | PostgreSQL | MySQL | SQL Server | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ------ | ---------- | ----------- | ---------------- | ----------- | -------- | --------- | ------- | -------- | ----------- | ---------- | | `RAW` | `bytea` | `VARBINARY` | `VARBINARY` | `VARBINARY` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `VARBINARY` | `BINARY` | | `BLOB` | `bytea` | `BLOB` | `VARBINARY(MAX)` | `BLOB` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `BLOB` | `BINARY` | #### Other Types | Oracle | PostgreSQL | MySQL | SQL Server | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ------------------ | --------------- | --------------- | --------------- | --------------- | -------- | --------------- | -------- | -------- | --------------- | ---------- | | `XMLTYPE` | `xml` | `TEXT` | `XML` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `TEXT` | `STRING` | | `JSON` | `jsonb` | `JSON` | `VARCHAR(MAX)` | `CLOB` | `TEXT` | `varchar` | `JSON` | `JSON` | `JSON` | `STRING` | | `ROWID` | `varchar(4000)` | `VARCHAR(4000)` | `VARCHAR(4000)` | `VARCHAR(4000)` | `TEXT` | `varchar(4000)` | `STRING` | `STRING` | `VARCHAR(4000)` | `STRING` | | `UROWID` | `varchar(4000)` | `VARCHAR(4000)` | `VARCHAR(4000)` | `VARCHAR(4000)` | `TEXT` | `varchar(4000)` | `STRING` | `STRING` | `VARCHAR(4000)` | `STRING` | | `(Any other type)` | `varchar(4000)` | `VARCHAR(4000)` | `VARCHAR(4000)` | `VARCHAR(4000)` | `TEXT` | `varchar(4000)` | `STRING` | `STRING` | `VARCHAR(4000)` | `STRING` | # PostgreSQL / YugaByte / TigerData / AlloyDB Source: https://docs.wirekite.io/datatypes/postgres This page explains how data types are mapped from a source PostgreSQL database to the target databases. Please visit the [PostgreSQL Data Types Documentation](https://www.postgresql.org/docs/current/datatype.html) to get a primer on the various PostgreSQL datatypes. ### Mapping The following tables explain how PostgreSQL source datatypes are mapped to each target database. Wirekite extracts data from PostgreSQL, converts it to an internal type representation, then maps to the appropriate target type. #### Numeric Types | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ----------------------------- | --------------- | ---------- | --------------- | --------------- | --------------- | -------------- | --------- | --------- | --------------- | --------------- | | `SMALLINT` / `INT2` | `SMALLINT` | `SMALLINT` | `NUMBER(38)` | `SMALLINT` | `INTEGER` | `number` | `INT64` | `INT64` | `SMALLINT` | `SMALLINT` | | `INTEGER` / `INT4` | `INT` | `INT` | `NUMBER(38)` | `INTEGER` | `INTEGER` | `int` | `INT64` | `INT64` | `INT` | `INT` | | `BIGINT` / `INT8` | `BIGINT` | `BIGINT` | `NUMBER(38)` | `BIGINT` | `BIGINT` | `bigint` | `INT64` | `INT64` | `BIGINT` | `BIGINT` | | `NUMERIC` | `NUMERIC` | `NUMERIC` | `NUMBER` | `DECIMAL` | `NUMERIC` | `number` | `NUMERIC` | `NUMERIC` | `NUMERIC` | `DECIMAL` | | `REAL` / `FLOAT4` | `FLOAT` | `REAL` | `BINARY_FLOAT` | `DOUBLE` | `DOUBLE` | `float` | `FLOAT32` | `FLOAT64` | `FLOAT` | `FLOAT` | | `DOUBLE PRECISION` / `FLOAT8` | `DOUBLE` | `FLOAT` | `BINARY_DOUBLE` | `DOUBLE` | `DOUBLE` | `float` | `FLOAT64` | `FLOAT64` | `DOUBLE` | `DOUBLE` | | `MONEY` | `DECIMAL(21,2)` | `MONEY` | `NUMBER(21,2)` | `DECIMAL(21,2)` | `NUMERIC(21,2)` | `number(21,2)` | `NUMERIC` | `NUMERIC` | `DECIMAL(21,2)` | `DECIMAL(21,2)` | | `BOOLEAN` | `TINYINT(1)` | `BIT` | `CHAR(1)` | `BOOLEAN` | `BOOLEAN` | `boolean` | `BOOL` | `BOOL` | `TINYINT(1)` | `BOOLEAN` | | `SMALLSERIAL` | `SMALLINT` | `SMALLINT` | `NUMBER(38)` | `SMALLINT` | `INTEGER` | `number` | `INT64` | `INT64` | `SMALLINT` | `SMALLINT` | | `SERIAL` | `INT` | `INT` | `NUMBER(38)` | `INTEGER` | `INTEGER` | `int` | `INT64` | `INT64` | `INT` | `INT` | | `BIGSERIAL` | `BIGINT` | `BIGINT` | `NUMBER(38)` | `BIGINT` | `BIGINT` | `bigint` | `INT64` | `INT64` | `BIGINT` | `BIGINT` | #### Date and Time Types | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | -------------------------- | ------------- | ------------- | -------------------------- | -------------- | ------------- | --------------- | ----------- | ----------- | ------------- | --------------- | | `DATE` | `DATE` | `DATE` | `DATE` | `DATE` | `DATE` | `date` | `DATE` | `DATE` | `DATE` | `DATE` | | `TIME` | `TIME(6)` | `TIME` | `VARCHAR2(64)` | `VARCHAR(64)` | `TEXT` | `time` | `STRING` | `TIME` | `TIME(6)` | `STRING` | | `TIME WITH TIME ZONE` | `VARCHAR(32)` | `VARCHAR(64)` | `VARCHAR2(64)` | `VARCHAR(64)` | `TEXT` | `varchar(32)` | `STRING` | `STRING` | `VARCHAR(32)` | `STRING` | | `TIMESTAMP` | `DATETIME(6)` | `DATETIME2` | `TIMESTAMP` | `TIMESTAMP` | `TIMESTAMP` | `timestamp_ntz` | `TIMESTAMP` | `DATETIME` | `DATETIME(6)` | `TIMESTAMP_NTZ` | | `TIMESTAMP WITH TIME ZONE` | `VARCHAR(32)` | `VARCHAR(32)` | `TIMESTAMP WITH TIME ZONE` | `TIMESTAMP` | `TIMESTAMPTZ` | `timestamp_tz` | `STRING` | `TIMESTAMP` | `VARCHAR(32)` | `TIMESTAMP` | | `INTERVAL` | `VARCHAR(64)` | `VARCHAR(64)` | `VARCHAR2(128)` | `VARCHAR(128)` | `TEXT` | `varchar(64)` | `STRING` | `STRING` | `VARCHAR(64)` | `STRING` | #### Character Types | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ------------------------------- | ------------- | ------------------ | --------------- | -------------- | -------- | ------------- | -------- | -------- | ------------- | ---------- | | `CHARACTER` / `CHAR` | `CHAR` | `CHAR` | `CHAR` | `CHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `CHAR` | `STRING` | | `CHARACTER VARYING` / `VARCHAR` | `VARCHAR` | `VARCHAR` | `VARCHAR2` | `VARCHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `VARCHAR` | `STRING` | | `TEXT` | `LONGTEXT` | `VARCHAR(MAX)` | `CLOB` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `LONGTEXT` | `STRING` | | `UUID` | `VARCHAR(64)` | `UNIQUEIDENTIFIER` | `VARCHAR2(128)` | `VARCHAR(128)` | `TEXT` | `varchar(64)` | `STRING` | `STRING` | `VARCHAR(64)` | `STRING` | | `XML` | `TEXT` | `XML` | `CLOB` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `TEXT` | `STRING` | | `JSON` / `JSONB` | `JSON` | `VARCHAR(MAX)` | `CLOB` | `CLOB` | `TEXT` | `varchar` | `JSON` | `JSON` | `JSON` | `STRING` | #### Binary Types | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ---------- | ------ | ---------------- | ------ | ------ | -------- | --------- | ------- | -------- | ----------- | ---------- | | `BYTEA` | `BLOB` | `VARBINARY(MAX)` | `BLOB` | `BLOB` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `BLOB` | `BINARY` | #### Bit String Types | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | --------------------- | ----- | ---------- | ---------- | --------- | -------- | --------- | -------- | -------- | ----------- | ---------- | | `BIT` / `BIT VARYING` | `BIT` | `VARCHAR` | `VARCHAR2` | `VARCHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `BIT` | `STRING` | #### Network Address Types | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ---------- | ------------- | ------------- | --------------- | -------------- | -------- | ------------- | -------- | -------- | ------------- | ---------- | | `INET` | `VARCHAR(64)` | `VARCHAR(64)` | `VARCHAR2(128)` | `VARCHAR(128)` | `TEXT` | `varchar(64)` | `STRING` | `STRING` | `VARCHAR(64)` | `STRING` | | `CIDR` | `VARCHAR(64)` | `VARCHAR(64)` | `VARCHAR2(128)` | `VARCHAR(128)` | `TEXT` | `varchar(64)` | `STRING` | `STRING` | `VARCHAR(64)` | `STRING` | | `MACADDR` | `VARCHAR(64)` | `VARCHAR(64)` | `VARCHAR2(128)` | `VARCHAR(128)` | `TEXT` | `varchar(64)` | `STRING` | `STRING` | `VARCHAR(64)` | `STRING` | #### Geometric Types | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ---------- | --------------- | --------------- | ---------------- | --------------- | -------- | --------------- | -------- | -------- | --------------- | ---------- | | `POINT` | `VARCHAR(256)` | `VARCHAR(256)` | `VARCHAR2(256)` | `VARCHAR(256)` | `TEXT` | `varchar(256)` | `STRING` | `STRING` | `VARCHAR(256)` | `STRING` | | `LINE` | `VARCHAR(256)` | `VARCHAR(256)` | `VARCHAR2(256)` | `VARCHAR(256)` | `TEXT` | `varchar(256)` | `STRING` | `STRING` | `VARCHAR(256)` | `STRING` | | `LSEG` | `VARCHAR(512)` | `VARCHAR(512)` | `VARCHAR2(512)` | `VARCHAR(512)` | `TEXT` | `varchar(512)` | `STRING` | `STRING` | `VARCHAR(512)` | `STRING` | | `BOX` | `VARCHAR(512)` | `VARCHAR(512)` | `VARCHAR2(512)` | `VARCHAR(512)` | `TEXT` | `varchar(512)` | `STRING` | `STRING` | `VARCHAR(512)` | `STRING` | | `PATH` | `VARCHAR(1024)` | `VARCHAR(1024)` | `VARCHAR2(1024)` | `VARCHAR(1024)` | `TEXT` | `varchar(1024)` | `STRING` | `STRING` | `VARCHAR(1024)` | `STRING` | | `POLYGON` | `VARCHAR(1024)` | `VARCHAR(1024)` | `VARCHAR2(1024)` | `VARCHAR(1024)` | `TEXT` | `varchar(1024)` | `STRING` | `STRING` | `VARCHAR(1024)` | `STRING` | | `CIRCLE` | `VARCHAR(256)` | `VARCHAR(256)` | `VARCHAR2(256)` | `VARCHAR(256)` | `TEXT` | `varchar(256)` | `STRING` | `STRING` | `VARCHAR(256)` | `STRING` | #### Text Search Types | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ---------- | --------------- | --------------- | ---------------- | --------------- | -------- | --------------- | -------- | -------- | --------------- | ---------- | | `TSVECTOR` | `VARCHAR(1024)` | `VARCHAR(1024)` | `VARCHAR2(1024)` | `VARCHAR(1024)` | `TEXT` | `varchar(1024)` | `STRING` | `STRING` | `VARCHAR(1024)` | `STRING` | | `TSQUERY` | `VARCHAR(256)` | `VARCHAR(256)` | `VARCHAR2(256)` | `VARCHAR(256)` | `TEXT` | `varchar(256)` | `STRING` | `STRING` | `VARCHAR(256)` | `STRING` | #### Other Types | PostgreSQL | MySQL | SQL Server | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | --------------- | ------------- | ------------- | --------------- | --------------- | -------- | ------------- | -------- | -------- | ------------- | ---------- | | `TXID_SNAPSHOT` | `VARCHAR(64)` | `VARCHAR(64)` | `VARCHAR2(128)` | `VARCHAR(128)` | `TEXT` | `varchar(64)` | `STRING` | `STRING` | `VARCHAR(64)` | `STRING` | | `ENUM` | `ENUM` | `VARCHAR(64)` | `VARCHAR2` | `VARCHAR(4000)` | `TEXT` | `varchar(64)` | `STRING` | `STRING` | `ENUM` | `STRING` | | `ARRAY` | *varies* | *varies* | *varies* | `VARCHAR(4000)` | `ARRAY` | `ARRAY` | `ARRAY` | `ARRAY` | *varies* | `ARRAY` | **ENUM types**: When the target is MySQL or SingleStore, built-in ENUM types are preserved natively. For all other targets, PostgreSQL user-defined ENUM types are mapped to `varchar(4000)`. **ARRAY types**: PostgreSQL array types (e.g., `integer[]`, `text[]`) are detected automatically and converted to native ARRAY types where the target supports them (Firebolt, Snowflake, Spanner, BigQuery, Databricks). For targets without native array support, arrays are stored as VARCHAR strings. # SQL Server Source: https://docs.wirekite.io/datatypes/sqlserver This page explains how data types are mapped from a source SQL Server database to the target databases. Please visit the [SQL Server Data Types Documentation](https://learn.microsoft.com/en-us/sql/t-sql/data-types/data-types-transact-sql?view=sql-server-ver17) to get a primer on the various SQL Server datatypes. ### Mapping The following tables explain how SQL Server source datatypes are mapped to each target database. Wirekite extracts data from SQL Server, converts it to an internal type representation, then maps to the appropriate target type. #### Numeric Types | SQL Server | PostgreSQL | MySQL | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ------------ | ---------------------------- | ------------------- | --------------------------------- | --------------- | --------- | --------- | ---------------------- | --------- | ------------------- | ------------------- | | `TINYINT` | `smallint` | `TINYINT UNSIGNED` | `NUMBER(38)` | `SMALLINT` | `INTEGER` | `number` | `INT64` | `INT64` | `TINYINT UNSIGNED` | `SMALLINT` | | `SMALLINT` | `smallint` | `SMALLINT` | `NUMBER(38)` | `SMALLINT` | `INTEGER` | `number` | `INT64` | `INT64` | `SMALLINT` | `SMALLINT` | | `INT` | `integer` | `INT` | `NUMBER(38)` | `INTEGER` | `INTEGER` | `int` | `INT64` | `INT64` | `INT` | `INT` | | `BIGINT` | `bigint` | `BIGINT` | `NUMBER(38)` | `BIGINT` | `BIGINT` | `bigint` | `INT64` | `INT64` | `BIGINT` | `BIGINT` | | `DECIMAL` | `decimal` | `DECIMAL` | `NUMBER` | `DECIMAL` | `NUMERIC` | `number` | `NUMERIC` | `NUMERIC` | `DECIMAL` | `DECIMAL` | | `NUMERIC` | `numeric` | `NUMERIC` | `NUMBER` | `DECIMAL` | `NUMERIC` | `number` | `NUMERIC` | `NUMERIC` | `NUMERIC` | `DECIMAL` | | `MONEY` | `numeric` | `NUMERIC` | `NUMBER` | `DECIMAL(21,2)` | `NUMERIC` | `number` | `NUMERIC` | `NUMERIC` | `NUMERIC` | `DECIMAL` | | `SMALLMONEY` | `numeric` | `NUMERIC` | `NUMBER` | `DECIMAL(21,2)` | `NUMERIC` | `number` | `NUMERIC` | `NUMERIC` | `NUMERIC` | `DECIMAL` | | `FLOAT` | `real` or `double precision` | `FLOAT` or `DOUBLE` | `BINARY_FLOAT` or `BINARY_DOUBLE` | `DOUBLE` | `DOUBLE` | `float` | `FLOAT32` or `FLOAT64` | `FLOAT64` | `FLOAT` or `DOUBLE` | `FLOAT` or `DOUBLE` | | `REAL` | `real` | `FLOAT` | `BINARY_FLOAT` | `DOUBLE` | `DOUBLE` | `float` | `FLOAT32` | `FLOAT64` | `FLOAT` | `FLOAT` | | `BIT` | `boolean` | `TINYINT(1)` | `CHAR(1)` | `BOOLEAN` | `BOOLEAN` | `boolean` | `BOOL` | `BOOL` | `TINYINT(1)` | `BOOLEAN` | #### Date and Time Types | SQL Server | PostgreSQL | MySQL | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ---------------- | ----------------------------- | ------------- | -------------------------------- | ------------- | ----------- | --------------- | ----------- | ---------- | ------------- | ----------- | | `DATE` | `date` | `DATE` | `DATE` | `DATE` | `DATE` | `date` | `DATE` | `DATE` | `DATE` | `DATE` | | `TIME` | `time without time zone` | `TIME(6)` | `VARCHAR2(64)` | `VARCHAR(64)` | `TEXT` | `time` | `STRING` | `TIME` | `TIME(6)` | `STRING` | | `DATETIME` | `timestamp without time zone` | `DATETIME(6)` | `TIMESTAMP` | `TIMESTAMP` | `TIMESTAMP` | `timestamp_ntz` | `TIMESTAMP` | `DATETIME` | `DATETIME(6)` | `TIMESTAMP` | | `DATETIME2` | `timestamp without time zone` | `DATETIME(6)` | `TIMESTAMP` | `TIMESTAMP` | `TIMESTAMP` | `timestamp_ntz` | `TIMESTAMP` | `DATETIME` | `DATETIME(6)` | `TIMESTAMP` | | `SMALLDATETIME` | `timestamp without time zone` | `DATETIME(6)` | `TIMESTAMP` | `TIMESTAMP` | `TIMESTAMP` | `timestamp_ntz` | `TIMESTAMP` | `DATETIME` | `DATETIME(6)` | `TIMESTAMP` | | `DATETIMEOFFSET` | `varchar(64)` | `DATETIME(6)` | `TIMESTAMP WITH LOCAL TIME ZONE` | `TIMESTAMP` | `TIMESTAMP` | `timestamp_ltz` | `STRING` | `STRING` | `DATETIME(6)` | `STRING` | #### Character Types | SQL Server | PostgreSQL | MySQL | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ---------- | ------------------- | ---------- | ----------- | --------- | -------- | --------- | -------- | -------- | ----------- | ---------- | | `CHAR` | `character` | `CHAR` | `CHAR` | `CHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `CHAR` | `STRING` | | `NCHAR` | `character` | `CHAR` | `NCHAR` | `CHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `CHAR` | `STRING` | | `VARCHAR` | `character varying` | `VARCHAR` | `VARCHAR2` | `VARCHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `VARCHAR` | `STRING` | | `NVARCHAR` | `character varying` | `VARCHAR` | `NVARCHAR2` | `VARCHAR` | `TEXT` | `varchar` | `STRING` | `STRING` | `VARCHAR` | `STRING` | | `TEXT` | `text` | `LONGTEXT` | `CLOB` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `LONGTEXT` | `STRING` | | `NTEXT` | `text` | `LONGTEXT` | `NCLOB` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `LONGTEXT` | `STRING` | #### Binary Types | SQL Server | PostgreSQL | MySQL | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ----------- | ---------- | ----------- | ------ | ----------- | -------- | --------- | ------- | -------- | ----------- | ---------- | | `BINARY` | `bytea` | `BINARY` | `RAW` | `BINARY` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `BINARY` | `BINARY` | | `VARBINARY` | `bytea` | `VARBINARY` | `RAW` | `VARBINARY` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `VARBINARY` | `BINARY` | | `IMAGE` | `bytea` | `VARBINARY` | `RAW` | `BLOB` | `BYTEA` | `binary` | `BYTES` | `BYTES` | `VARBINARY` | `BINARY` | #### Other Types | SQL Server | PostgreSQL | MySQL | Oracle | DB2 | Firebolt | Snowflake | Spanner | BigQuery | SingleStore | Databricks | | ------------------ | --------------- | --------------- | ---------------- | --------------- | -------- | --------------- | -------- | -------- | --------------- | ---------- | | `UNIQUEIDENTIFIER` | `uuid` | `VARCHAR(64)` | `VARCHAR2(128)` | `VARCHAR(128)` | `TEXT` | `varchar(64)` | `STRING` | `STRING` | `VARCHAR(64)` | `STRING` | | `XML` | `xml` | `TEXT` | `CLOB` | `CLOB` | `TEXT` | `varchar` | `STRING` | `STRING` | `TEXT` | `STRING` | | `JSON` | `jsonb` | `JSON` | `CLOB` | `CLOB` | `TEXT` | `varchar` | `JSON` | `JSON` | `JSON` | `STRING` | | `GEOGRAPHY` | `varchar(4000)` | `VARCHAR(4000)` | `VARCHAR2(4000)` | `VARCHAR(4000)` | `TEXT` | `varchar(4000)` | `STRING` | `STRING` | `VARCHAR(4000)` | `STRING` | | `GEOMETRY` | `varchar(4000)` | `VARCHAR(4000)` | `VARCHAR2(4000)` | `VARCHAR(4000)` | `TEXT` | `varchar(4000)` | `STRING` | `STRING` | `VARCHAR(4000)` | `STRING` | | `HIERARCHYID` | `varchar(4000)` | `VARCHAR(4000)` | `VARCHAR2(4000)` | `VARCHAR(4000)` | `TEXT` | `varchar(4000)` | `STRING` | `STRING` | `VARCHAR(4000)` | `STRING` | | `SQL_VARIANT` | `varchar(4000)` | `VARCHAR(4000)` | `VARCHAR2(4000)` | `VARCHAR(4000)` | `TEXT` | `varchar(4000)` | `STRING` | `STRING` | `VARCHAR(4000)` | `STRING` | # Architecture Source: https://docs.wirekite.io/introduction/architecture This is the general architecture of Wirekite, the components that make up the Wirekite data movement stack, as well as limitations of those components. For a more detailed architecture please check the Implementation page. ## Flow Wirekite's components operate beteen the source and target database instances. Extractors extract "stuff" from source databases, Movers move it to intermediate storage, and Loaders load the "stuff" to the target database instances. Thus Wirekite has three classes of components as explained below. ## Entities Wirekite extracts and loads three general types of data from the source database into the target database and in the following order. Schema refers to the "structure" of the data. Schema covers the definition of tables, columns, datatypes, and other properties such as primary keys and constraints. Wirekite extracts vendor-specific schema definitions into generic "schema files" containing CREATE TABLE statements and related data definitions. This is a one time task so that we have empty tables in the target database that can receive data in the next steps. Data at this stage refers to the initial dump of data from the source. Usually this means multiple tables which can also be large in size. This is the heavyweight bits of the source database that needs to be loaded to the target database. This is also a one time process. Unless you can afford to quiesce (or take down) your customer-facing database instance, this is usually done from a replica. Wirekite data extractors use a tab-delimited proprietary format to extract data. This format is understood by Wirekite loaders. This process supports a high degrees of parallelism since data can be loaded onto the target in any order. Change refers to the constant "changes" that take place in the source database. Typically this means Inserts, Updates and Deletes. Note that this happens "forever" and Wirekite establishes a pipeline from the source to the target so that the target is kept up-to-date with the source. The change extractor is a single-threaded process since transactions that COMMIT on the source need to be extracted in the exact same order. The change loader, however, can apply changes using multiple merge threads for higher throughput. ## Components Wirekite has three components which are essentially the actions that are taken on the data listed above. Extractors are the components that extract schema, data and change from the source database. Extractors are only aware of sources and are completely agnostic to details of the downstream target. This component "reads" from the source database to "writes" to intermediate storage. This is the component that does the moving of the files from the source database to an environment where it can be accessed by the target. Movers are agnostic to the contents of files, although Wirekite has different movers for simple file transfer, Amazon Web Services S3 uploads, and a few vendor-specific "data staging" environments. Movers regard the files as byte-streams and make no attempt to parse their contents. This is the component that reads the files that are moved by the Mover and "loads" them to the target database instances. Loaders work on schema, data and change files. Schema and change loaders read the files and translate them to corresponding database language statements and execute those statements on the database, while data loaders may directly load data or may use database-native facilities like COPY or LOAD DATA INFILE to quickly load data, depending on the capabilities of the target database. # Implementation Source: https://docs.wirekite.io/introduction/implementation This page provides a more detailed view of the architecture, specifically relating to how will you implement wirekite in your infrastructure. ## Wirekite Components Wirekite has three main database entities -- schema, data and change -- and three components -- Extractor, Mover and Loader. The entities are the objects in the database that wirekite works upon, while components are the operators that work on the entities. Lets put these all together and we get a sequence in which all the components work on the entities to ultimately establish a target database which is continuously updated from the source database. The **sequence** that is to be followed in a real production infrastructure is as follows. ### Schema Extract the Schema of your source database. One Time. Move the Schema from source to target database. One Time. Load the schema on the target database. One Time. ### Data Extract the Data of your source database. One Time. Move the Data from source to target database. One Time. Load the data on the target database. One Time. ### Change Extract the Changes from your source database. Continuous. Move the Change files from source to target database. Continuous. Load the changes on the target database. Continuous. ## Sequential Steps The following architectural diagram how data will be migrated to a target database and how a replication pipeline will be established from a source to a target database instance. ## Design Points These are some of the noteworthy points regarding the above diagram. 1. Wirekite operates using a replica of the customer-facing database instance. This is so we can avoid taking down the active production database instance, while having a quiesced database instance during the initial data extraction. The details of setting up a replica is database vendor-specific. 2. Wirekite components - Extractor, Mover, and Loader - can and should run in parallel. This minimizes the amount of time required to load an initial dump, as well as minimizing storage space needed for in-flight data files as they are fetched by the Extractor and loaded by the Loader. The shorter the initial dump/move/load time the shorter the lag when we switch from initial extraction mode to change data capture mode. 3. The performance characteristics - latency and throughput - of the connectivity between source and target as well as the storage database instances and their hosts should be appropriately scaled to the size and activity of the database. 4. The performance of the change data capture must be more than the rate of overall change events in the source database. For example if you are generating a 1 GB MySQL or MariaDB binlog in 10 seconds, you need to scale your endpoints and networking so that the contents of this binlog are extracted, moved, and loaded in significantly less than 10 seconds. If this is not the case, the target database will lag the source database "forever". Specifically the following equation must hold true. **wirekite\_extraction\_time + wirekite\_ship\_time + wirekite\_load\_time \< source\_database\_change\_generation\_time** # Sources & Targets Source: https://docs.wirekite.io/introduction/matrix The full engine and capability matrix — which databases Wirekite supports as a source, as a target, and as a streaming queue, across all three movement modes: Data, Replicate, and Target Sync. ## Movement Modes Wirekite moves data three ways. Every cell in the matrices below refers to one of these modes: One-time bulk load — schema and rows into an empty target, once. Continuous change data capture (CDC), streamed source to target. One-shot diff-and-apply — reconciles an already-populated target to its source. ## As a Source Which databases Wirekite can extract from, and in which modes. | Engine | Data | Replicate | Target Sync | | -------------- | :--: | :-------: | :---------: | | Oracle | ✓ | ✓ | ✓ | | PostgreSQL | ✓ | ✓ | ✓ | | MySQL | ✓ | ✓ | ✓ | | MariaDB | ✓ | ✓ | ✓ | | SQL Server | ✓ | ✓ | ✓ | | IBM Db2 | ✓ | ✓ | — | | SingleStore | ✓ | ✓ | — | | YugabyteDB | ✓ | ✓ | — | | TigerData | ✓ | ✓ | — | | Google AlloyDB | ✓ | ✓ | — | | Google Spanner | — | ✓ | — | | Cassandra | — | — | ✓ | **Google Spanner** is a Replicate (CDC) source only. **Cassandra** is a [Target Sync](/run/targetsync) source only — it has no CDC path. YugabyteDB, TigerData, and AlloyDB are PostgreSQL-compatible; SingleStore is MySQL-compatible. ## As a Target Which databases Wirekite can load into, and in which modes. | Engine | Data | Replicate | Target Sync | | --------------- | :--: | :-------: | :---------: | | Oracle | ✓ | ✓ | ✓ | | PostgreSQL | ✓ | ✓ | ✓ | | MySQL | ✓ | ✓ | ✓ | | MariaDB | ✓ | ✓ | ✓ | | SQL Server | ✓ | ✓ | ✓ | | IBM Db2 | ✓ | ✓ | ✓ | | SingleStore | ✓ | ✓ | ✓ | | YugabyteDB | ✓ | ✓ | — | | TigerData | ✓ | ✓ | — | | Google AlloyDB | ✓ | ✓ | — | | Google Spanner | ✓ | ✓ | ✓ | | Snowflake | ✓ | ✓ | ✓ | | Firebolt | ✓ | ✓ | ✓ | | Google BigQuery | ✓ | ✓ | ✓ | | Databricks | ✓ | ✓ | ✓ | | MongoDB | ✓ | ✓ | ✓ | ## Streaming Queues Wirekite can also publish a source's change stream to a message queue instead of a database, for downstream consumers to read. Queues carry CDC change events (the Replicate mode). | Queue | Replicate | | -------------- | :-------: | | Apache Kafka | ✓ | | Redpanda | ✓ | | Google Pub/Sub | ✓ | See the [Queues](/queues/overview) guides for configuration. Don't see your engine? New sources and targets are added based on what teams need — reach out at [hello@wirekite.io](mailto:hello@wirekite.io). # Overview Source: https://docs.wirekite.io/introduction/overview Welcome to the Wirekite documentation and reference. Everything you need to understand what Wirekite is and how it helps with your data migration challenges — whether that's a one-time migration or an ongoing pipeline between two databases. ## What is Wirekite Wirekite is a highly performant, cross database, extract, load and replication platform. To break down the definition wirekite is * **Performant**- We pride ourselves in being extremely fast. Please visit our [extract and load benchmarks](https://benchmarks.wirekite.io/series/benchmarks-extract-and-load) and [replication benchmarks](https://benchmarks.wirekite.io/series/benchmarks-replication). **Wirekite is 10x-100x faster than its competitors.** * **Cross Database**- Wirekite allows you to move data from Oracle, PostgreSQL, YugaByte, TigerData, AlloyDB, MySQL, MariaDB, SingleStore, SQL Server, Google Cloud Spanner (CDC only), and Apache Cassandra (Target Sync only) to multiple cloud and on-premise databases. Supported targets include MySQL, MariaDB, SingleStore, PostgreSQL, YugaByte, TigerData, AlloyDB, Oracle, SQL Server, Snowflake, Firebolt, Google BigQuery, Google Cloud Spanner, Databricks, and MongoDB. See the [full source, target, and queue matrix](/introduction/matrix) for every supported engine and the modes it supports. * **Extract, Load**- Wirekite to allows you to extract and load data from source databases to targets. Part of any data migration - whether one time or ongoing - involves taking an initial extract of data and moving it to the target. Wirekite prides itself in moving copious amounts of data in much shorter time frames than other technologies. Wirekite can migrate tables with **billions** of rows within **minutes**. * **Replication**- In addition to moving large data, wirekite allows you to keep the data on the target fresh from the source. This helps enormously with doing an application switch over from source to target while affording relatively small downtime. * **Target Sync**- Wirekite can also reconcile an already-populated target back to its source in a single pass - diffing the two databases and applying only the differences, with no CDC required. This is ideal for repairing drift, backfilling a target, or a one-shot migration where continuous replication isn't available. See [Target Sync](/run/targetsync). ## At a glance | | | | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | Sources | 11 engines — Oracle, PostgreSQL, YugaByte, TigerData, AlloyDB, MySQL, MariaDB, SingleStore, SQL Server, Spanner (CDC), Cassandra (Target Sync) | | Targets | 15 engines — the OLTP family plus Snowflake, Firebolt, BigQuery, Spanner, Databricks, MongoDB | | Modes | Extract & load · CDC replication · Target Sync (diff-and-repair, no CDC required) | | Queues | Kafka · Google Pub/Sub | | Interfaces | Web UI · command line · REST API | | Delivery | On-prem installer · Docker · managed cloud | The [source, target, and queue matrix](/introduction/matrix) is the authoritative per-engine list. ## Explore the docs On-prem, Docker, or managed cloud — pick a path and get running. The initial extract and load — copious data, short time frames. Keep the target fresh from the source with seconds of lag. Per-engine setup for every supported source. Per-engine setup for every supported target. Drive migrations from the browser, the shell, or the REST API. ## Use Cases There can be a multitude of reasons that data needs to be moved from one databases platform to another. But the most common reasons are the following * Migration of application and or database from one platform to another. * Permanent pipelines from one database to another typically from an OLTP database to a Data Warehouse or Analytics database. Wirekite helps with both. Lets talk about both cases in a bit more detail. ### Application Migration Sooner or later you will encounter a scenario where you will have to migrate your application to a new platform. This is very common these days since many firms are migrating their whole infrastructure to the cloud. Migrating a production application to the cloud will have one very firm constraint - downtime. Wirekite makes sure that your downtime is minimal. Furthermore your technical committee might decide to write an "interim" application that migrates the data, in small chunks, in a continuous fashion to the new data store. This poses a multitude of problems since now you have to keep track of how much data has been migrated and possibilities of drift between the two data stores. Wirekite frees your from all the vulnerabilities of writing such interim infrastructure. A much better approach would be to migrate the data to the new data store, while also making sure that the new data store is continuously replicated from the source with a minimal lag. Once this design is in place all you have to do is switchover the application to work on the new data store. Wirekite thrives in creating such an infrastructure. ### Data Warehouse Pipelines A mature data infrastructure usually has two components - A production OLTP database which serves the production application, and a secondary Data Warehouse / Analytics database which can be used by the analytic applications. The two databases usually have vastly different schemas and hence there are ETL pipelines going from OLTP to DW. ETL pipelines come with a variety of disadvantages causing delays in the arrival of data in the data warehouse, thus preventing quick analysis of data to make relevant decisions. Fairly recently we are seeing the advent of ELT pipelines where the loading is done first allowing the analysis of data to occur sooner the later. Wirekite allows the "loading" component of the data to be order of magnitude faster and also allows the loaded data to be updated with the source data with a lag of few seconds. ## Next steps 1. [Install Wirekite](/run/installation) — on-prem, Docker, or cloud. 2. [Set up your source](/sourceguides/mysql) and [your target](/targetguides/snowflake). 3. [Load the data](/run/dataloading), then [turn on replication](/run/replication). 4. Watch it all from the [Web UI](/run/execution/ux). # Why Wirekite Source: https://docs.wirekite.io/introduction/whywirekite This page talks about why you should consider wirekite as your data migration solution or as your data pipeline infrastructure from your production database to data warehouse. ## TL;DR We are [faster, way faster](https://benchmarks.wirekite.io/series/benchmarks-extract-and-load). This allows you to have an [order of magnitude shorter downtime](https://benchmarks.wirekite.io/series/benchmarks-extract-and-load) when migrating your application from one infrastructure to another or to refresh your OLTP data in the Data Warehouse, so you can [analyze the data quicker](https://benchmarks.wirekite.io/series/benchmarks-extract-and-load). > Please check our [extract and load benchmarks](https://benchmarks.wirekite.io/series/benchmarks-extract-and-load) and [replication benchmarks](https://benchmarks.wirekite.io/series/benchmarks-replication) ## Background Since the advent of computers data has been a critical component of the infrastructure and technologies have evolved to store and retrieve data in a performant container while keeping costs low. We have seen the rise of RDBMS databases, NoSQL databases and now we are in the Cloud database era that promises infinite scalability and elasticity. Part of the problem is moving this data from one platform to another. Given that data volumes have exploded and applications have significantly shorter downtime SLAs, this problem has become the brunt of failures of most data migration projects. **60% to 80% of data migration projects fail.** Wirekite solves this problem, albeit better than other technologies. ## Data Migration Consider a 100 GB table and a data migration solution that moves data at 10 MBPS (the average speed of other solutions), you will take approx 22 hours to transfer the data. If the rate is amped up to 100 MBPS, it will take slightly more than 2 hours to move the same amount of data. Now imagine if the rate is 1 GBPS (wirekite), you can do the migration in 20 minutes. **The data transfer rate is not limited by the network but by the rate of data extraction, loading on source and target database.** ## Data Warehouse Pipeline Imagine the same kind of performance impact when you can move all of the data from your production OLTP database into your Data Warehouse. When you have the "recent" data faster, your analysis is far more accurate and valuable. ## Performance ### Extract and Load / Data One of the first stages of any data migration project is moving data to the target database. This involves extracting all the data and loading into the target database. Since the data does not have to be inserted in any given order in the target database, we can take advantage of large degree of parallelism. ### Replication / Change Once the data is loaded to the target database wirekite makes sure that continuous changes that are happening in the source database are replicated to the target database. Note that changes happen on the source database in a given order and must be executed in the same order on the target database, thus preventing us from using parallelism. Wirekite handles the single threaded replication very efficiently. # Kafka and Redpanda Source: https://docs.wirekite.io/queues/kafka How to configure a Kafka or Redpanda queue target — broker prerequisites, topic creation, compression, and connection testing. ## Overview Apache Kafka and Redpanda are interchangeable from Wirekite's perspective: both speak the Kafka wire protocol, and Wirekite uses the same driver and the same code path for both. The only customer-visible difference is the **type** label on the queue target (`kafka` vs `redpanda`) — pick whichever matches the system you're actually operating, since that label flows through to the UX list and metrics attribution. For cross-vendor concepts (message format, ordering, retries, charts), see [Queues Overview](/queues/overview). ## Prerequisites ### Broker cluster You need a reachable broker cluster — Wirekite does not bundle or manage one. The cluster must: * Speak Kafka protocol (Kafka, Redpanda, or any compatible implementation). * Accept plaintext connections from the Wirekite extractor host. SASL and TLS are not yet supported by the Wirekite client; terminate them in front of the broker if your environment requires them. * Allow auto-topic-creation OR have the topic pre-created (see below). ### Topic Wirekite uses **one topic per queue target** — every change record from every table in the migration lands on the same topic. Pick a name that attributes the stream to the migration, e.g. `-wirekite--to-`. ``` # Kafka kafka-topics.sh --bootstrap-server :9092 \ --create --topic \ --partitions --replication-factor # Redpanda rpk topic create \ --partitions --replicas \ --brokers :9092 ``` Partition count caps the consumer-side parallelism. For a single-table migration that fits in one partition, `--partitions 1` keeps things simple; for high-volume multi-table migrations, size partitions to the expected consumer parallelism. Wirekite's per-table ordering guarantee holds at any partition count because lines from one transaction ship in one ordered batch. If `auto.create.topics.enable=true` on the broker, Wirekite's first publish will create the topic implicitly. The connection test (see below) explicitly avoids auto-create so a missing topic surfaces as an error rather than an unintended side effect. ## Wirekite configuration ### Queue-target definition Create the queue target through the UX wizard or the API. The field set: | Field | Required | Description | | ------------- | -------- | -------------------------------------------------------------- | | `type` | yes | `kafka` or `redpanda` | | `brokers` | yes | Comma-separated `host:port` list | | `topic` | yes | Topic name (must exist or auto-create must be enabled) | | `batchSize` | no | `.ckt` lines per Kafka message; default `1` | | `compression` | no | `none`, `snappy`, `lz4`, `zstd`; default `""` (no compression) | The same fields, with the same names, are exposed through the API. ### Extractor config keys When wiring the extractor directly (e.g. for `qa/fulltest` or scripted runs), the orchestrator emits these keys into the change-extractor config: ``` queueType=kafka queueBrokers=broker1:9092,broker2:9092 queueTopic= queueBatchSize=100 queueCompression=zstd ``` `queueType=redpanda` is accepted as a synonym — the dispatch is identical. ## Compression Compression is applied at the Kafka producer (per-message wire format), not at the application layer. The codec choice is a CPU-vs-bandwidth trade-off: | Codec | CPU cost | Compression ratio | Notes | | ---------------- | -------- | ----------------- | ---------------------------------------------- | | `none` (default) | None | 1.0× | Use when broker is local and bandwidth is free | | `snappy` | Low | \~2× | Good general default | | `lz4` | Low | \~2× | Slightly faster than snappy on most CPUs | | `zstd` | Medium | \~3× | Best compression; modest CPU cost | For a CDC stream of newline-delimited row data, `zstd` typically halves broker storage at a small CPU cost on the extractor side. ## Authentication The current release supports **plaintext brokers only**. SASL\_PLAINTEXT, SASL\_SSL, and mTLS are not wired through the Wirekite client. If your brokers require auth, terminate it at a sidecar/proxy in front of the broker — for example, a local Kafka REST proxy or an identity-translation gateway — until first-class auth lands. ## Connection testing The UX wizard exposes a **Test Message** button that runs a Metadata request against the configured brokers with auto-create disabled. A successful test confirms: * The first broker in the list is reachable on the configured port. * The cluster responds to a metadata request within a 10-second timeout. * The named topic exists. Failure modes the test catches: | Test failure | Cause | | ------------------------------------- | -------------------------------------------- | | `broker unreachable` | DNS, firewall, port, or down broker | | `topic does not exist on the cluster` | Topic not pre-created and auto-create is off | | `metadata error for topic` | Cluster-side ACL or other broker rejection | The same probe runs at extractor startup; a queue target that passes the wizard test will also pass the startup gate, barring intervening broker state changes. ## Failure semantics The Wirekite Kafka publisher is fail-fast: any publish error from `kafka-go.WriteMessages` (after the SDK's `MaxAttempts=10` budget is spent) increments the `errors` counter, logs `QUEUE: flush failed`, and exits the extractor. The orchestrator flips the migration to **Replication Failed**; recovery is through **Resume from Failed**, which replays from the last commit boundary persisted to the progress DB. On the SQL Server C extractor, the `librdkafka` driver runs with `message.timeout.ms=300000` (5 minutes). Any message that cannot be durably acknowledged within that window triggers the same fail-fast path through the delivery-report callback. This means a transient broker outage shorter than the SDK's retry budget is invisible to Wirekite — the SDK retries internally. A sustained outage causes a clean failure plus replay-on-recovery. ## Operations The reference consumer for end-to-end verification is at `qa/queue_reader/queue_reader` in the Wirekite source tree: ``` queue_reader -brokers :9092 -topic \ -group -outdir ``` It subscribes to the topic, demultiplexes incoming messages by the `OP\tschema\ttable\t...` prefix into per-table `.ckt` files in ``, and prints final counters that should match the extractor's `submitted` / `delivered`. This is the same utility used by `qa/fulltest` to validate end-to-end correctness. For Pub/Sub-specific setup, see [Google Pub/Sub](/queues/pubsub). # Queues Overview Source: https://docs.wirekite.io/queues/overview How Wirekite publishes change records to message queues — supported backends, message format, ordering, batching, retries, and the operational signals you can monitor. ## Overview A Wirekite **queue target** is a first-class destination — alongside file/DB targets — that receives the change-data-capture stream produced by an extractor. A migration may have a file/DB target, a queue target, or both. When a queue is configured, every committed change is published as a message; the queue is the integration point for downstream consumers (your loader, a stream processor, a search index, etc.). Queue targets are used during the **replication** phase only. Initial schema and bulk-data loads always go through the file/DB target. A migration whose only target is a queue is therefore a replication-only migration — it cannot be run in `data` or `data-replication` modes. ## Supported backends | Backend | Type identifier | Driver | | -------------- | --------------- | ------------------------------------------------------------------------------------ | | Apache Kafka | `kafka` | `segmentio/kafka-go` (mysql/postgres/oracle), `librdkafka` (sqlserver) | | Redpanda | `redpanda` | Same Kafka driver — Redpanda speaks the Kafka wire protocol | | Google Pub/Sub | `pubsub` | `cloud.google.com/go/pubsub` (mysql/postgres/oracle), `google-cloud-cpp` (sqlserver) | All four source databases (MySQL, PostgreSQL, Oracle, SQL Server) can publish to any of the three backends. The choice is per-queue-target, not per-deployment — a single Wirekite installation can have Kafka, Redpanda, and Pub/Sub queue targets in use at the same time. Pick **Kafka or Redpanda** when you control the broker hardware, latency is dominant, or the downstream consumer is Kafka-native. Pick **Pub/Sub** when the deployment already runs in Google Cloud, or you don't want to operate a broker cluster. ## Configuration parameters The same parameter set applies whether you create a queue target through the UX wizard, the API, or by hand-writing extractor configs for `qa/fulltest`. A queue target is identified by `queueType`; the rest of the parameters split into shared, kafka-only, and pubsub-only groups. ### Shared parameters Backend selector. One of `kafka`, `redpanda`, `pubsub`. Empty value defaults to `kafka` for backward compatibility with pre-Pub/Sub configs. Topic / Pub/Sub topic id. A single topic carries every change record for the migration — there is one topic per queue target, not one per source table. Customer pre-creates the topic; Wirekite errors loudly at startup if it does not exist. Number of `.ckt` change-record lines packed into a single broker message. `1` means one line per message (highest fidelity, highest message count). Higher values reduce broker RPC volume but increase per-message size. See "Message compilation" below for the exact packing rules. ### Kafka / Redpanda parameters Comma-separated list of broker addresses (e.g. `broker1.example.com:9092,broker2.example.com:9092`). The first broker is dialed at startup as a connectivity check; subsequent metadata is discovered from the cluster. Wire-format compression codec. One of `""` (no compression), `none`, `snappy`, `lz4`, `zstd`. Unknown codecs are rejected at startup. Authentication (SASL/TLS) is **not** supported in the current release. Plaintext brokers only. If you need SASL today, terminate it in front of the broker (e.g. with a sidecar proxy) until first-class auth lands. ### Google Pub/Sub parameters GCP project id that owns the topic. Used as the project segment in `projects//topics/`. Absolute path to a service-account JSON key on the extractor host. The plaintext file is encrypted in place by the API at queue-target creation time, so the unencrypted contents do not need to remain on disk afterwards. Empty value falls back to Application Default Credentials. The `queueCompression` field is **rejected** on Pub/Sub queue targets — gRPC handles transport compression transparently. Setting it surfaces a config typo rather than silently ignoring it. ## Message compilation The change extractor produces a stream of native Wirekite `.ckt` change record lines, each line representing one row event in the form: ``` OP\tschema\ttable\t\n ``` `OP` is one of `I` (insert), `U` (update), `D` (delete). Every line is self-contained and carries the full row image as required by the downstream change loader. ### Per-line vs batched messages When `queueBatchSize=1`, every `.ckt` line becomes one queue message. When `queueBatchSize=N` (N > 1), the publisher accumulates lines in an internal buffer and emits one message holding `N` newline-terminated `.ckt` records once the buffer is full. The downstream consumer demultiplexes by splitting the message body on `\n`. Batching trade-offs: | Concern | `batchSize=1` | `batchSize=100` | | -------------------- | --------------------------- | ----------------------------------------- | | Broker RPC count | One per row | One per \~100 rows | | Per-message overhead | Dominates at high row rates | Amortized | | Failure blast radius | One row per failed publish | Up to `batchSize` rows per failed publish | | Consumer parallelism | Per-row | Per-batch | For high-volume migrations, `queueBatchSize=100` is a typical sweet spot; beyond that, broker per-message limits start to bind on wide rows. ### Ordering and partitioning Change records for a given source row must arrive at the consumer in commit order, otherwise CDC semantics break (e.g. an `UPDATE` arriving before its preceding `INSERT`). Wirekite preserves per-table order: | Backend | Ordering mechanism | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Kafka / Redpanda | Messages within a single produce call are ordered. The default `LeastBytes` balancer hashes across partitions; the consumer's per-partition order matches per-table publish order because `FlushAll` ships one transaction's worth of lines as one ordered batch. | | Google Pub/Sub | Each message carries `OrderingKey = "."`. The publisher sets `EnableMessageOrdering=true` on the topic; the subscription must be created with `--enable-message-ordering`. | When `batchSize > 1` and the backend is Pub/Sub, lines are accumulated in **per-table** batchers — a single Pub/Sub message never mixes rows from different tables, because every message has exactly one ordering key. Kafka does not have this constraint; Kafka batches may contain mixed-table rows because per-partition order is sufficient. ### Flush boundaries `FlushAll` is called at every source-side **commit boundary** — a SQL transaction in MySQL/Postgres/Oracle, a Log Sequence Number group in SQL Server. This guarantees: * A message never contains rows from two different transactions. * Counters never include a partial transaction. * Downstream consumers see committed state only. ## Retries Wirekite delegates retry policy to the underlying SDK on each backend. The Wirekite layer itself does **not** retry — it relies on the SDK's internal retry budget and treats an exhausted-retries error as terminal. | Backend | Retry layer | Retryable conditions | Budget | | ------------------------------- | ---------------------------------------- | ------------------------------------------------------ | -------------------------------------- | | Kafka / Redpanda (Go) | `kafka-go` `Writer.MaxAttempts=10` | Broker transient errors per the Kafka protocol | 10 attempts | | Kafka / Redpanda (SQL Server C) | `librdkafka` `message.timeout.ms=300000` | Same as above plus producer queue retry | 300 s wall clock | | Google Pub/Sub | `cloud.google.com/go/pubsub` + `gax` | `Unavailable`, `DeadlineExceeded`, `ResourceExhausted` | Exponential backoff until SDK gives up | Once the SDK signals a permanent failure, Wirekite's behavior is **fail-fast**: 1. Increment the `errors` counter. 2. Log a `FATAL` line naming the failure. 3. Exit with code `1`. The orchestrator detects the non-zero exit, flips the migration to **Replication Failed**, and surfaces the failure in the UX. Recovery is through **Resume from Failed**, which rewinds to the last persisted progress-DB position and re-emits from there. This produces at-least-once delivery semantics — a small window of records may be re-published after a failure. Downstream consumers must therefore tolerate duplicates, or rely on broker-side deduplication (Pub/Sub's `enable-exactly-once-delivery` subscription flag). The fail-fast policy is a deliberate design choice. CDC streams are strongly ordered; silently dropping or reordering a record corrupts the downstream replica. Loud failure plus replay from the last commit boundary is the only safe recovery shape. ### Stall watchdog (Pub/Sub only) The Google Pub/Sub publisher has an additional safety net for the case where the SDK's per-message future never resolves — neither succeeding nor failing. A watchdog ticks every 5 seconds and tracks whether the `delivered` counter is advancing. If it has been frozen for 30 seconds **while there are unresolved publishes**, the extractor logs a `FATAL: QUEUE stall detected` line and exits. The orchestrator then treats this the same way as any other publish failure (Replication Failed → Resume from Failed). Kafka does not need an equivalent watchdog — `librdkafka`'s `message.timeout.ms` already covers this failure mode. ## Charts and operational signals The Replication pane in the Wirekite UX shows a **Queue** subpane for every migration that has a queue target. It surfaces three series on one chart: | Series | Source | Meaning | | --------------- | ------------------------------------------- | ------------------------------------------------------ | | `Extracted/min` | `EXTRACTED.rows` field on the extractor log | `.ckt` lines accepted into the publisher's local queue | | `Delivered/min` | `EXTRACTED.delivered` field | `.ckt` lines durably acknowledged by the broker | | `Errors` | `EXTRACTED.queue_errors` field | Cumulative publish errors (steady state = 0) | In a healthy migration `Delivered/min` tracks `Extracted/min` closely; sustained divergence indicates broker back-pressure. `Errors > 0` is always followed by extractor exit (fail-fast), so a non-zero point on the errors series is the marker for a failure incident. The publishers run in **async** mode on the Go side (`Async: true` for Kafka, completion-worker pool for Pub/Sub), so `submitted` (Extracted) and `delivered` are tracked separately. On the SQL Server C extractor both counters are wired through `librdkafka`'s delivery-report callback (Kafka) or google-cloud-cpp's per-publish future (Pub/Sub), producing the same semantics. The chart schema is identical across all four extractors. The shutdown log line names the lifetime totals: ``` QUEUE: shutdown (submitted=N, delivered=N, errors=0) ``` `submitted` and `delivered` should match exactly when a run completes cleanly. A non-zero `errors` always co-occurs with a `FATAL` line earlier in the log. ## Error conditions | Symptom | Likely cause | Recovery | | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------- | | Extractor exits at startup with `cannot connect to broker` | Bad `queueBrokers`; firewall; broker down | Verify broker reachability, fix config, restart | | Extractor exits at startup with `topic … does not exist` | Topic not pre-created on the broker | Customer creates the topic, then resumes | | Extractor exits at startup with `queueCompression: unsupported codec` | Typo in compression value | Use one of `none`, `snappy`, `lz4`, `zstd` | | Extractor exits mid-run with `FATAL: QUEUE … failed` | SDK exhausted retries on a publish | Resume from Failed; investigate broker-side cause | | Extractor exits mid-run with `FATAL: QUEUE stall detected` (pubsub) | Pub/Sub future never resolved | Resume from Failed; check Pub/Sub quotas / IAM | | `Delivered/min` lags `Extracted/min` for sustained periods | Broker back-pressure or network latency | Investigate broker capacity; consider raising `batchSize` | | Consumer sees out-of-order rows for one table | Pub/Sub subscription created without `--enable-message-ordering` | Recreate the subscription — the flag is unflippable | | Consumer sees duplicate rows | Resume from Failed replayed; or Pub/Sub subscription without `--enable-exactly-once-delivery` | Add consumer-side dedup, or recreate the subscription | | Queue target deletion leaves topic on the broker | Expected — Wirekite removes its reference only | Delete the topic out-of-band if desired | For backend-specific setup (broker bring-up, IAM, subscription flags), continue to the next pages. # Google Pub/Sub Source: https://docs.wirekite.io/queues/pubsub How to configure a Google Pub/Sub queue target — GCP setup, IAM roles, ordering, exactly-once delivery, and cost guidance. ## Overview Google Pub/Sub is supported as a queue target alongside Kafka and Redpanda. The Wirekite extractor publishes one message per `.ckt` change record (or one per batch when `queueBatchSize > 1`) using the official `cloud.google.com/go/pubsub` SDK on the Go-side extractors and `google-cloud-cpp` on the SQL Server C++ extractor. For cross-vendor concepts (message format, ordering, retries, charts), see [Queues Overview](/queues/overview). ## When to choose Pub/Sub Pick Pub/Sub when: * The deployment already runs in Google Cloud and Pub/Sub fits the existing pipeline (Dataflow, BigQuery streaming inserts, downstream services that already subscribe to Pub/Sub topics). * You don't want to operate a Kafka/Redpanda cluster. * Per-table delivery order is required (Pub/Sub preserves it via ordering keys; see "Ordering and exactly-once" below). Pick Kafka or Redpanda when: * Latency is dominant and you control the broker hardware. * Per-message cost is unacceptable (Pub/Sub Standard is metered; Kafka is hardware-cost only — see "Cost" below). * The downstream consumer is a Kafka-native system. ## One-time GCP setup ### 1. Create the topic ``` gcloud pubsub topics create --project= ``` Pub/Sub topic names are flat (no folders). One topic per migration is the natural unit. Suggested name shape: `-wirekite--to-`. ### 2. Create the subscription The subscription is what the downstream consumer reads from. **Two flags must be set at creation time** — neither can be flipped later on an existing subscription: ``` gcloud pubsub subscriptions create \ --topic= \ --enable-message-ordering \ --enable-exactly-once-delivery \ --project= ``` | Flag | Why | | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `--enable-message-ordering` | Wirekite uses `schema.table` as the ordering key on every published message. Without this flag, the broker still accepts the ordering keys but does not enforce per-key delivery order — a downstream consumer sees rows interleaved out of commit order. | | `--enable-exactly-once-delivery` | Default Pub/Sub behavior is at-least-once: the broker may redeliver a message even after the subscriber acked it. Wirekite's reference consumer and the production change-loader pipeline both assume one-shot delivery — duplicates cause double-applied changes downstream. Exactly-once shifts the broker to deduplicating delivery within an ack window. | Both flags are unflippable once the subscription is created. If you need to change either, delete and recreate the subscription. The extractor checks both flags at startup (when running the reference consumer) and refuses to start unless they are both `true`. **Recommended subscription settings:** * `ack-deadline = 60s` (default `10s` — increase if your consumer takes longer than 10s to process a single batched message). * `message-retention-duration = 1d` (sufficient for catching up after a short consumer outage; longer retention raises storage cost). ### 3. Service-account credentials Create a service account dedicated to the Wirekite migration: ``` gcloud iam service-accounts create wirekite-pubsub --project= gcloud projects add-iam-policy-binding \ --member="serviceAccount:wirekite-pubsub@.iam.gserviceaccount.com" \ --role="roles/pubsub.publisher" gcloud projects add-iam-policy-binding \ --member="serviceAccount:wirekite-pubsub@.iam.gserviceaccount.com" \ --role="roles/pubsub.viewer" ``` Both roles are required. `pubsub.publisher` alone does **not** include `pubsub.topics.get`, which Wirekite calls at startup to confirm the topic exists before any publishes are accepted. Without `pubsub.viewer`, the extractor exits at startup with `pubsub topic … exists check: permission denied`. If you also intend to run Wirekite's reference consumer (`pubsub_reader`) or its drain helper (`pubsub_admin -seek-now`) against the same subscription, also add: ``` --role="roles/pubsub.subscriber" # for pubsub_reader pulls --role="roles/pubsub.editor" # for pubsub_admin SeekToTime ``` Download a JSON key for the service account and store it where the Wirekite extractor host can read it. The path you supply to Wirekite is encrypted in place at queue-target creation time, so the plaintext key does not have to remain on disk afterward. ## Wirekite configuration ### Queue-target definition Create the queue target through the UX wizard or the API: | Field | Required | Description | | ------------------ | -------- | ------------------------------------------------------------------------------------- | | `type` | yes | `pubsub` | | `project` | yes | GCP project id holding the topic | | `topic` | yes | Pub/Sub topic id (NOT the full `projects//topics/` form) | | `credentials_file` | yes | Absolute path to the service-account JSON; encrypted in place at target-creation time | The kafka-only fields (`brokers`, `compression`) are rejected on Pub/Sub queue targets — gRPC handles transport compression transparently, and Pub/Sub has no "broker list" concept. Setting either field surfaces the misconfiguration rather than silently ignoring it. ### Extractor config keys When wiring the extractor directly, the orchestrator emits: ``` queueType=pubsub queueTopic= queueProject= queueCredentialsFile= queueBatchSize=100 # optional ``` The same key shape applies to every source database (mysql / postgres / oracle Go extractors and the SQL Server `change_extractor_pubsub` C++ binary). ## Ordering and exactly-once **Ordering key.** Wirekite sets `OrderingKey = ".
"` on every published message. Per-table change order matches the source's commit order end-to-end **as long as** the subscription has `enableMessageOrdering=true`. **Per-table batching.** When `queueBatchSize > 1`, lines are accumulated in independent per-key buffers — one buffer per `schema.table`. A single Pub/Sub message therefore never contains rows from two different tables (each message carries exactly one ordering key). **Exactly-once delivery.** Wirekite's reference consumer relies on `enableExactlyOnceDelivery=true`. Without it, transient ack failures cause the broker to redeliver messages already processed; the change loader will reapply changes and validation runs will report spurious diffs. **Per-key throughput ceiling.** Pub/Sub bounds throughput per ordering key at roughly 1 MB/s. For a single high-write table whose change volume exceeds that, split it at the source level (separate migrations or separate topics) — a single Pub/Sub topic with one ordering key per table is not the right shape for >1 MB/s on one table. ## Failure semantics The Wirekite Pub/Sub publisher is **fail-fast**, with two distinct detection paths: 1. **Explicit error.** When the SDK's `PublishResult.Get()` returns an error (after `gax` exponential backoff is exhausted on retryable codes — `Unavailable`, `DeadlineExceeded`, `ResourceExhausted`), Wirekite increments `errors`, logs `FATAL: QUEUE delivery failed`, and exits. 2. **Stall watchdog.** A 5-second-cadence watchdog tracks whether the `delivered` counter is advancing. If it has been frozen for **30 seconds** while there are unresolved publishes (`inflight > 0`), Wirekite logs `FATAL: QUEUE stall detected — inflight=N, delivered held at M for Ks with no progress` and exits. This catches the pathological case where the SDK's per-message future never resolves — an observed-once failure mode that the SDK does not surface as an error. In both cases the orchestrator detects the non-zero exit, flips the migration to **Replication Failed**, and surfaces the failure in the UX. Recovery is **Resume from Failed**, which rewinds to the last commit boundary persisted to the progress DB and re-emits from there. The Pub/Sub publisher uses a fixed pool of 8 completion-worker goroutines reading off a buffered channel — this bounds goroutine count regardless of publish rate and provides natural back-pressure when broker acks lag. The completion workers do not retry; they trust the SDK's internal retry layer. ## Cost Pub/Sub Standard pricing (US, as of 2026-05): `$40 / TB` of message throughput, plus `$0.27/GB` egress for cross-region consumers, plus storage if subscription retention exceeds 7 days. Concrete sizing: | Throughput | Avg msg size | `$/day` | `$/month` | | -------------------------- | ------------ | ------- | ---------- | | 1k changes/s | 256 B | `<$1` | `~$10` | | 50k changes/s | 256 B | `~$15` | `~$450` | | 334k changes/s (benchmark) | 256 B | `~$450` | `~$13,500` | Notes: * "Changes/s" is per source, **not** per topic. A single topic carries every change from one migration. * Application-level batching (`queueBatchSize=100`) does NOT reduce message-throughput billing — Pub/Sub bills on byte volume, not RPC count. Batching reduces RPC count and SDK overhead, not data volume. * For benchmark-scale runs, prefer Kafka/Redpanda on customer-managed hardware. Pub/Sub Standard is cost-appropriate for production-rate workloads, not synthetic load tests. Pub/Sub Lite (capacity-based, cheaper) is **not supported**. Google announced Pub/Sub Lite deprecation in 2024 with end-of-life on 2026-06-30; Wirekite does not target a sunsetting product. ## Operations ### Drain a subscription The reference helper `qa/queue_reader/pubsub_admin -seek-now` moves the subscription's read cursor to the current time so any messages published before that point are treated as already-acked. Used by `qa/fulltest` between iterations; usable ad-hoc: ``` pubsub_admin -project -subscription \ -credentials -seek-now ``` ### Reference consumer ``` pubsub_reader -project -subscription \ -credentials -outdir ``` Subscribes to the subscription, demultiplexes incoming messages by the `OP\tschema\ttable\t...` prefix into per-table `.ckt` files in ``. Refuses to start unless the subscription has both `enableMessageOrdering=true` and `enableExactlyOnceDelivery=true`. ### Validate publish counts The extractor and `pubsub_reader` print final counters in the same shape: ``` QUEUE: shutdown (pubsub, submitted=N, delivered=N, errors=0) ``` `submitted` and `delivered` should match exactly when the run completes cleanly. Any non-zero `errors` indicates a publish-side failure that will already have been logged earlier as a `FATAL` line and triggered extractor exit. ## Troubleshooting | Symptom | Likely cause | Fix | | ------------------------------------------------------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------- | | `pubsub topic does not exist in project

` at startup | Topic id misspelled or in a different project | Verify with `gcloud pubsub topics describe --project=` | | `pubsub topic … exists check: permission denied` at startup | Service account missing `roles/pubsub.viewer` | Add the role per "Service-account credentials" above | | `pubsub_reader` receives messages out of publish order within a table | Subscription created without `--enable-message-ordering` | Recreate the subscription — the flag cannot be toggled | | `pubsub_reader` receives the same message multiple times | Subscription created without `--enable-exactly-once-delivery` | Recreate the subscription — the flag cannot be toggled | | Validator diff shows extra rows in queue dump that aren't in `.ckt` files | Same as above (duplicates) | Recreate the subscription with exactly-once enabled | | `FATAL: QUEUE stall detected` during a run | Pub/Sub publisher future never resolved | Resume from Failed; check Pub/Sub quotas, IAM, and service health | | Sustained billing spike | Benchmark/load-test workload running against Pub/Sub Standard | Move benchmark workloads to Kafka/Redpanda; reserve Pub/Sub for production-rate traffic | For Kafka/Redpanda-specific setup, see [Kafka and Redpanda](/queues/kafka). # Wiretalk SQL Command Line Source: https://docs.wirekite.io/run/commandline The Wiretalk SQL Command Line Utility - a universal database query tool. Most database vendors provide their own SQL command line tools, but they vary significantly in features and usage. To simplify working with multiple databases, Wirekite provides **Wiretalk** - a unified SQL command line tool that works consistently across all supported databases. Wiretalk uses the same DSN/URL connection files as other Wirekite tools. If you can connect to a database using Wiretalk, the same connection file will work with other Wirekite components. ## Supported Databases Wiretalk supports all Wirekite source and target databases: | Database | Type Flag | | -------------------- | -------------------------- | | PostgreSQL | `postgres` or `postgresql` | | MySQL | `mysql` | | MariaDB | `mariadb` | | SQL Server | `sqlserver` | | Oracle | `oracle` | | Snowflake | `snowflake` | | Firebolt | `firebolt` | | Google BigQuery | `bigquery` | | Google Cloud Spanner | `spanner` | | Databricks | `databricks` | | SingleStore | `singlestore` | ## Command Line Usage ```bash theme={null} wiretalk -d -c ``` Or with a direct connection string: ```bash theme={null} wiretalk -d -dsn "" ``` ### Required Flags | Flag | Description | | ------ | --------------------------------------------------------- | | `-d` | Database type (required) - see supported databases above | | `-c` | Path to file containing the connection string | | `-dsn` | Connection string provided directly (alternative to `-c`) | **Note:** Either `-c` or `-dsn` must be provided. ### Optional Flags | Flag | Description | | ------------------ | -------------------------------------------------------------------------------------------------------------------- | | `-quiet` | Suppress prompts, print only row numbers and column names | | `-silent` | Print only query results (no metadata) | | `-csv` | Output results in CSV format with headers | | `-json` | Output per-statement JSON results (for programmatic integration) | | `-credfile ` | Path to a GCP service account JSON file. Required for Spanner and BigQuery connections | | `-ignore-errors` | Continue executing remaining SQL statements even if one fails. Without this flag, execution stops on the first error | ## Interactive Mode When run interactively (connected to a terminal), Wiretalk provides a prompt-based interface with command history. ### Example Session ```bash theme={null} $ wiretalk -d firebolt -c fi_url.txt firebolt instance connect successful => create table example (a int, b int); ok => insert into example values (1,1),(2,2),(3,3); ok => select * from example; 1: a: 1 1: b: 1 2: a: 2 2: b: 2 3: a: 3 3: b: 3 => \d csv display type set to csv => select * from example; 'a','b' '1','1' '2','2' '3','3' => -D bye ``` ## Escape Commands Wiretalk provides several escape commands for controlling output and behavior: | Command | Description | | ---------------------------- | ---------------------------------------------------------- | | `\h` | Display help information | | `\i ` | Load and execute SQL statements from a file | | `\o [filename]` | Redirect output to a file; `\o` alone disables file output | | `\d csv\|list` | Change display format (default: `list`) | | `\p ` | Set number of rows per page; `0` disables paging | | `\r true\|false` | Show or hide row numbers | | `\t` | Toggle elapsed time display | | `\D` | Print current display settings | | `\c ` | Configure CSV format parameters | ### CSV Format Configuration The `\c` command configures CSV output format with four parameters: ``` \c ``` Available separator tokens: * `QUOTE` - single quote (`'`) * `DOUBLEQUOTE` - double quote (`"`) * `COMMA` - comma (`,`) * `SPACE` - space character * `TAB` - tab character * `PIPE` - pipe (`|`) * `NONE` - no character * `NEWLINE` - newline (`\n`) * `CRLF` - carriage return + newline (`\r\n`) * Any other literal character Example: ``` => \c DOUBLEQUOTE COMMA NEWLINE true ``` ## Non-Interactive Mode Wiretalk can execute SQL from files or stdin in non-interactive mode: ```bash theme={null} # From a file wiretalk -d postgres -c pg_conn.txt < schema.sql # Piped input cat queries.sql | wiretalk -d mysql -c mysql_conn.txt -quiet ``` ### JSON Output Mode For programmatic integration, use `-json` to get structured output: ```bash theme={null} echo "CREATE TABLE test (id INT); INSERT INTO test VALUES (1);" | wiretalk -d postgres -c pg_conn.txt -json ``` Output: ```json theme={null} {"index":1,"sql":"CREATE TABLE test (id INT)","status":"OK","lineNum":1} {"index":2,"sql":"INSERT INTO test VALUES (1)","status":"OK","lineNum":1} ``` Each statement produces a JSON object with: * `index` - statement number (1-based) * `sql` - the executed SQL * `status` - `OK` or `FAILED` * `error` - error message (only if status is `FAILED`) * `lineNum` - line number in input ## Database-Specific Features ### Oracle PL/SQL Blocks Oracle PL/SQL blocks (starting with `BEGIN` or `DECLARE`) are terminated by a `/` on its own line: ```sql theme={null} BEGIN DBMS_OUTPUT.PUT_LINE('Hello World'); END; / ``` ### Google Cloud Spanner Batch DDL Spanner requires DDL statements to be batched together. Wiretalk supports this with special commands: ```sql theme={null} START BATCH DDL; CREATE TABLE users (id INT64, name STRING(100)) PRIMARY KEY (id); CREATE TABLE orders (id INT64, user_id INT64) PRIMARY KEY (id); RUN BATCH; ``` ## Notes * Command history is saved to `~/.linerhistory` * Multi-line SQL statements are supported - statements are executed when a semicolon is encountered * For PostgreSQL, `sslmode=disable` is automatically added if not specified * SQL Server PRINT output from stored procedures is captured and displayed # Data Loading Source: https://docs.wirekite.io/run/dataloading How Wirekite's extractors and loaders work together to move data from source to target databases. ## The Pipeline Wirekite moves data through a pipeline of independent components. The extractor reads from the source database and writes intermediate files to disk. The mover optionally transports those files to a location accessible by the target. The loader reads the intermediate files and applies them to the target database. ``` Source DB → Extractor → Files → Mover → Files → Loader → Target DB ``` The intermediate files are the decoupling point. Extractors know nothing about the target database and loaders know nothing about the source database. This separation means any supported source can be paired with any supported target without custom integration logic. In data mode, the orchestrator starts the extractor, mover, and loader in parallel. The extractor writes files continuously, the mover picks them up and transfers them, and the loader consumes them as they arrive. This pipeline architecture minimizes the storage footprint since files are loaded and cleared while extraction is still in progress. ## Standalone Binaries Each extractor and loader is compiled as its own standalone binary. The orchestrator invokes these binaries as child processes, passing each one a configuration file. The orchestrator constructs these child configuration files by extracting the relevant section from the main configuration. For example, `source.data.dsnFile` in the orchestrator config becomes simply `dsnFile` in the data extractor's config. Because the binaries are standalone, they can also be run independently outside the orchestrator for testing or debugging purposes. Each binary takes a single argument: the path to its configuration file. ### Binary Selection The orchestrator uses an internal binary map to determine which binary to invoke for a given source, target, and mode combination. For example, a MySQL source in data mode invokes the MySQL data extractor binary, while a Snowflake target in data mode invokes the Snowflake data loader binary. The same orchestrator binary handles all source and target combinations. ## Local and Remote Database Access When Wirekite runs on the same host as the database (or shares a filesystem), it can use faster server-side file operations instead of streaming data through the client connection. The `databaseRemote` parameter controls this behavior. When `true` (the default), Wirekite streams data through the client connection. This works with any database regardless of where it is hosted, including cloud-managed databases like RDS, Cloud SQL, and Azure Database. When `false`, Wirekite uses server-side file operations where the database server reads or writes files directly on its local filesystem. This is faster but requires that Wirekite and the database share a filesystem. ### How It Works The mechanism differs between extractors and loaders: **Extractors** (source side): * **Remote** (`databaseRemote=true`): The extractor runs a query and streams the result set through the client connection, writing rows to files locally * **Local** (`databaseRemote=false`): The extractor instructs the database server to write query results directly to a file on the server's filesystem **Loaders** (target side): * **Remote** (`databaseRemote=true`): The loader reads files locally and streams the data to the database server through the client connection * **Local** (`databaseRemote=false`): The loader tells the database server to read files directly from its own filesystem ### Database-Specific Mechanisms The underlying SQL mechanism used depends on the database: | Database | Remote (default) | Local | | ------------------------ | ----------------------------------- | ---------------------------- | | **MySQL Extractor** | `SELECT` with client-side streaming | `SELECT ... INTO OUTFILE` | | **PostgreSQL Extractor** | `COPY ... TO STDOUT` | `COPY ... TO ''` | | **MySQL Loader** | `LOAD DATA LOCAL INFILE` | `LOAD DATA INFILE` | | **PostgreSQL Loader** | `COPY ... FROM STDIN` | `COPY ... FROM ''` | | **SingleStore Loader** | `LOAD DATA LOCAL INFILE` | `LOAD DATA INFILE` | ### Which Databases Support It The `databaseRemote` parameter is only relevant for databases that have both a client-side and server-side file transfer mechanism: | Component | Supports databaseRemote | | -------------------- | --------------------------------------- | | MySQL extractor | Yes | | PostgreSQL extractor | Yes | | Oracle extractor | No -- always streams through the client | | SQL Server extractor | No -- always streams through the client | | MySQL loader | Yes | | PostgreSQL loader | Yes | | SingleStore loader | Yes | | Oracle loader | No -- always streams through the client | | SQL Server loader | No -- uses native bulk loader | Cloud data warehouses (Snowflake, BigQuery, Databricks, Firebolt, Spanner) do not use `databaseRemote`. They have their own staging and upload mechanisms -- for example, Snowflake uses an internal stage with `PUT` and `COPY INTO`, and BigQuery loads through Google Cloud Storage. ### When to Use Each For most deployments, the default (`databaseRemote=true`) is the right choice. Only set `databaseRemote=false` if Wirekite is running on the same host as the database server or they share a mounted filesystem. * **Cloud-managed databases** (Amazon RDS, Google Cloud SQL, Azure Database): Use `databaseRemote=true`. Server-side file access is not available on managed instances. * **Self-hosted databases on the same host as Wirekite**: Set `databaseRemote=false` for better performance through server-side file operations. * **Self-hosted databases on a different host**: Use `databaseRemote=true`. The database server cannot access files on the Wirekite host. ## Thread Counts Data extractors and data loaders process multiple tables concurrently using configurable thread counts. The number of concurrent threads used by a data extractor or data loader. Each thread processes one table at a time. All source extractors and all target loaders support this parameter. The extractor and loader thread counts are configured independently. For example, the extractor can use 8 threads while the loader uses 4. The right values depend on the hardware, network bandwidth, and how much concurrent load the source and target databases can handle. ```shellscript theme={null} # Extractor threads source.data.maxThreads=8 # Loader threads target.data.maxThreads=4 ``` Change extractors are single-threaded because they must read the transaction log sequentially to preserve commit ordering. Change loaders use a fixed internal thread pool for parallel merge operations across tables, but this is not user-configurable. ## Handover: Transitioning to Change Replication When data and change modes are combined in a single configuration, the orchestrator automatically handles the transition from bulk data loading to continuous change replication. After the data phase completes, a handover process captures the exact position in the source database's transaction log. The change extractor then begins from that position, ensuring no data is missed or duplicated. Each source database type has its own position mechanism -- MySQL uses binlog coordinates, PostgreSQL uses WAL LSN, Oracle uses SCN, and SQL Server uses LSN. For full details on change replication, handover mechanics, and crash recovery, see [CDC Replication](/run/replication). # Command Line Source: https://docs.wirekite.io/run/execution/commandline Run Wirekite migrations from the command line via the orchestrator. ## Orchestrator Wirekite has a main binary called the orchestrator. The actual binary is called wirekite. This is a top level binary which calls all the other binaries to execute the task of data movement. Note that other binaries can be called independently also for testing purposes. ## Orchestrator Configuration File Orchestrator takes a configuration file to understand what needs to be done. The configuration file has the following rules. 1. The configuration variables can be represented using the format `variable=value`. 2. Empty lines are allowed. 3. Comments are allowed. A line starting with `#` is a full-line comment; the parser also strips inline comments — anything from whitespace + `#` to end of line is dropped (e.g., `maxThreads=8 # tune this`). 4. Multilevel variables are allowed using the format `parent.child=value`. ## Variables The configuration file has the following main variables and allowed values. home is the Wirekite installation directory. source is the database type from which we are extracting. The possible values are 1. mysql 2. oracle 3. postgres 4. sqlserver 5. spanner (CDC only) target is the database type to which we are loading. The possible values are 1. snowflake 2. firebolt 3. databricks 4. bigquery 5. spanner 6. singlestore 7. mysql 8. postgres 9. oracle 10. sqlserver 11. mongodb log is the path to the orchestrator log file. When set to `true`, the orchestrator preserves the existing `position.pkt` file and resumes from the last saved position. When `false` (or absent), the orchestrator truncates the position file before starting. The Web Interface sets this automatically when resuming a migration. ## Modes The mode of operation is declared explicitly using the `mode` variable in the configuration file. The operation mode. Must be one of the values listed below. ### Schema Modes | Mode | Description | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `schema-extract` | Extract the schema from the source database. Produces a `.skt` schema file and optionally an `.okt` objects file. | | `schema-apply-tables` | Apply CREATE TABLE statements to the target database using the generated SQL file. | | `schema-apply-objects` | Apply non-table objects (indexes, constraints, foreign keys) to the target database. Errors on individual statements are logged but do not stop execution. | Schema modes must run independently and cannot be combined with data or change modes. The schema loader generates SQL files for the target database. These SQL files are not automatically executed on the target database during extraction -- this is done in separate apply steps so you can make granular changes to the schema properties on the target database. ### Data and Change Modes | Mode | Description | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data` | One-time bulk data extraction and loading. The orchestrator runs the extractor, mover, and loader in parallel. | | `change` | Continuous CDC replication. Extracts ongoing changes (inserts, updates, deletes) from the source and applies them to the target. | | `change-queue` | Continuous CDC replication to a **queue target only** (Kafka, Redpanda, or Pub/Sub) — no file target, no loader. Used when downstream consumers read changes directly from the queue. Required mode for queue-only migrations; using `change` against a queue target is rejected. | | `data+change` | Combined data migration followed by CDC replication. The orchestrator first completes the bulk data load, captures the source position automatically, and then starts continuous change replication from that position. Do not specify a starting position for the change source -- the orchestrator captures this during the data phase. | In data and change modes, Wirekite automatically creates two metadata tables in the target database: `wirekite_progress` for tracking migration state and crash recovery, and `wirekite_action` for pause/stop/resume control. See [Operations](/run/operations) for details on monitoring and controlling running migrations. ### Reset Modes | Mode | Description | | ---------------- | ---------------------------------------------------------------------------------------------- | | `reset-drop` | Drop tables from the target database using the specified drop file. | | `reset-trunc` | Truncate tables on the target database. | | `reset-metadata` | Reset Wirekite's internal metadata (progress and action tables) without modifying target data. | ### Validation Mode | Mode | Description | | ---------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `validate` | Compare data between source and target databases to verify migration accuracy. See [Data Validation](/run/validation) for details. | ## Source and Target Child Variables Both `source` and `target` variables have child variables that include the mode as part of the hierarchy. The format is `source..=value` and `target..=value`. For example, `source.data.dsnFile` is the connection string file for the data extractor and `target.schema.schemaFile` is the input schema file for the schema loader. The specific variables available depend on the source and target database types. For example if the source is mysql then the child variables can be any of the variables listed in [mysql variables](/sourceguides/mysql). If the target is snowflake then the child variables can be any of the variables listed in [snowflake variables](/targetguides/snowflake). ## Mover Variables The mover is an optional component that transfers files between the source and target. It is configured separately using the `mover.=value` format. The mover does not have a mode prefix since the same mover handles both data and change files. ## Bringing It All Together Below are example orchestrator configuration files for each mode. ### Schema Mode Example Schema mode extracts the database schema from the source and generates SQL files for the target. Schema extraction and application are separate modes. ```shellscript theme={null} # Schema extraction configuration # main home=/opt/wirekite source=mysql target=snowflake mode=schema-extract log=/var/log/wirekite/schema-migration.log # schema source source.schema.tablesFile=/opt/wirekite/config/tables.txt source.schema.outputDirectory=/opt/wirekite/output/schema source.schema.dsnFile=/opt/wirekite/config/mysql-source.dsn source.schema.logFile=/var/log/wirekite/schema-extractor.log # schema target target.schema.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.schema.createTableFile=/opt/wirekite/output/sql/create-tables.sql target.schema.createConstraintFile=/opt/wirekite/output/sql/create-constraints.sql target.schema.createForeignKeyFile=/opt/wirekite/output/sql/create-foreign-keys.sql target.schema.dropTableFile=/opt/wirekite/output/sql/drop-tables.sql target.schema.logFile=/var/log/wirekite/schema-loader.log target.schema.createMergeTables=true ``` To apply the extracted schema tables to the target, use `mode=schema-apply-tables` with the generated SQL file. Then use `mode=schema-apply-objects` to apply indexes, constraints, and foreign keys. ### Data Mode Example Data mode performs a one-time bulk data transfer from source to target. ```shellscript theme={null} # Data migration configuration # main home=/opt/wirekite source=oracle target=snowflake mode=data log=/var/log/wirekite/data-migration.log # data source source.data.dsnFile=/opt/wirekite/config/oracle-source.dsn source.data.tablesFile=/opt/wirekite/config/tables.txt source.data.outputDirectory=/opt/wirekite/data/extract source.data.logFile=/var/log/wirekite/data-extractor.log source.data.maxThreads=8 source.data.maxRowsPerDump=50000 # data target target.data.dsnFile=/opt/wirekite/config/snowflake-target.dsn target.data.dataDirectory=/opt/wirekite/data/stage target.data.doneDirectory=/opt/wirekite/data/done target.data.logFile=/var/log/wirekite/data-loader.log target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.dataFileExtension=dkt target.data.maxThreads=4 # mover mover.awsRegion=us-east-1 mover.awsBucket=wirekite-migration-bucket mover.dataDirectory=/opt/wirekite/data/extract mover.logFile=/var/log/wirekite/data-mover.log mover.maxThreads=4 mover.gzipFiles=false mover.removeFiles=false ``` ### Change Mode Example Change mode captures ongoing changes (CDC) and applies them to the target. When running change mode independently you must specify the starting position for your source database type. ```shellscript theme={null} # Change replication configuration # main home=/opt/wirekite source=mysql target=postgres mode=change log=/var/log/wirekite/change-replication.log # change source source.change.dsnFile=/opt/wirekite/config/mysql-source.dsn source.change.tablesFile=/opt/wirekite/config/tables.txt source.change.outputDirectory=/opt/wirekite/changes/extract source.change.logFile=/var/log/wirekite/change-extractor.log source.change.binlogFile=mysql-bin.000042 source.change.binlogPosition=154 source.change.exitWhenIdle=false # change target target.change.dsnFile=/opt/wirekite/config/postgres-target.dsn target.change.dataDirectory=/opt/wirekite/changes/stage target.change.workDirectory=/opt/wirekite/changes/work target.change.logFile=/var/log/wirekite/change-loader.log target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.changeFileExtension=ckt target.change.doneDirectory=/opt/wirekite/changes/done target.change.removeFiles=true target.change.maxFilesPerBatch=30 ``` ### Data + Change Mode Example Data and change modes can be combined using `mode=data+change`. The orchestrator will first complete the bulk data load, capture the source position automatically, and then start continuous change replication. Do not specify a starting position for the change source -- the orchestrator captures this automatically during the data phase. ```shellscript theme={null} # Full migration configuration (data + change) # main home=/opt/wirekite source=sqlserver target=snowflake mode=data+change log=/var/log/wirekite/full-migration.log # data source source.data.dsnFile=/opt/wirekite/config/sqlserver-source.dsn source.data.tablesFile=/opt/wirekite/config/tables.txt source.data.outputDirectory=/opt/wirekite/data/extract source.data.logFile=/var/log/wirekite/data-extractor.log source.data.maxThreads=8 source.data.maxRowsPerDump=100000 # data target target.data.dsnFile=/opt/wirekite/config/snowflake-target.dsn target.data.dataDirectory=/opt/wirekite/data/stage target.data.doneDirectory=/opt/wirekite/data/done target.data.logFile=/var/log/wirekite/data-loader.log target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.dataFileExtension=dkt target.data.maxThreads=6 # change source source.change.dsnFile=/opt/wirekite/config/sqlserver-source.dsn source.change.tablesFile=/opt/wirekite/config/tables.txt source.change.outputDirectory=/opt/wirekite/changes/extract source.change.logFile=/var/log/wirekite/change-extractor.log source.change.exitWhenIdle=false # change target target.change.dsnFile=/opt/wirekite/config/snowflake-target.dsn target.change.dataDirectory=/opt/wirekite/changes/stage target.change.workDirectory=/opt/wirekite/changes/work target.change.logFile=/var/log/wirekite/change-loader.log target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.changeFileExtension=ckt target.change.doneDirectory=/opt/wirekite/changes/done target.change.removeFiles=true target.change.maxFilesPerBatch=30 # mover mover.awsRegion=us-west-2 mover.awsBucket=wirekite-migration-bucket mover.dataDirectory=/opt/wirekite/data/extract mover.logFile=/var/log/wirekite/mover.log mover.maxThreads=4 mover.gzipFiles=false mover.removeFiles=false ``` # UX Source: https://docs.wirekite.io/run/execution/ux Run Wirekite migrations from the full-featured web interface. ## Overview The Wirekite UX Server provides a web-based graphical interface for managing all aspects of database migrations. It allows you to configure sources and targets, run migrations, monitor progress in real-time, and validate data—all through your browser. The UX Server runs on **HTTPS port 8443** by default and requires authentication. ## Technology Stack The UX Server is built with: * **Backend:** Go with the Gin web framework * **Frontend:** HTML/CSS/JavaScript with HTMX for dynamic updates * **Charts:** Apache ECharts for real-time progress visualization * **SQL Editor:** CodeMirror with syntax highlighting ## Getting Started ### Starting the UX Server ```bash theme={null} # Start the UX server cd /opt/wirekite/ux/server ./ux-server # Or use systemd (recommended for production) sudo systemctl start wirekite-ux ``` ### Initial Setup 1. Open your browser and navigate to `https://your-server:8443` 2. On first access, you'll be redirected to the setup page 3. Create your root (admin) user account 4. Log in with your new credentials The initial root user can only be created once. Store these credentials securely. ## Main Features ### Dashboard The main dashboard displays: * All configured migrations with their current status * Source and target database connections * Quick access to tools and settings ### Migration Status Indicators | Status | Description | | ------------------- | ------------------------------------------------ | | Migration Created | Migration configured but schema not yet migrated | | Schema Created | Schema has been applied to target | | Data Loaded | Initial data load completed | | Replication Running | CDC replication is active | | Replication Paused | CDC replication is paused | ## Configuring Sources Sources are the databases you extract data from. The GUI supports: * **MySQL** - Host, port, username, password, database * **PostgreSQL** - Host, port, username, password, database * **Oracle** - Host, port, username, password, service name * **SQL Server** - Host, port, username, password, database ### Creating a Source 1. Click **Sources** in the sidebar 2. Click **Add Source** 3. Select the database type 4. Fill in the connection parameters 5. Click **Test Connection** to verify 6. Click **Save** ## Configuring Targets Targets are the databases you load data into. The GUI supports: ### On-Premise Targets * MySQL * PostgreSQL * Oracle * SQL Server * SingleStore ### Cloud Targets * Snowflake * Firebolt * Google BigQuery * Google Cloud Spanner * Databricks ### Cloud Target Configuration Cloud targets require additional configuration for staging areas: * Account identifier * Username and password * Database and warehouse * Role (optional) * Account name * Client ID and secret * Engine name * AWS S3 bucket for staging * GCP Project ID * Dataset name * GCS bucket for staging * Workspace host URL * Access token * SQL Warehouse ID * Catalog and schema * AWS S3 bucket for staging * GCP Project ID * Instance ID * Database ID ## Creating Migrations A migration links a source to a target: 1. Click **Migrations** in the sidebar 2. Click **Create Migration** 3. Enter a migration name 4. Select the source database 5. Select the target database 6. Click **Create** ## Migration Workflow ### Step 1: Schema Migration Extract and apply the schema from source to target: 1. Open your migration 2. Click **Schema** tab 3. Click **Extract Schema** to pull schema from source 4. Select which schemas/tables to include 5. Optionally rename schemas (e.g., `dbo` → `app_schema`) 6. Review the generated SQL 7. Click **Run SQL** to apply to target You can edit the generated SQL before applying it if you need to make adjustments for the target database. ### Step 2: Data Migration Load data from source to target: 1. Click **Data** tab 2. Configure migration options: Number of parallel threads for extracting data from source. Number of parallel threads for loading data to target. Maximum rows per data file. Smaller values use less memory. When running data+replication mode, the default is 50,000. 3. Click **Start Data Migration** 4. Monitor progress in real-time via the graph ### Step 3: Data Validation Verify data integrity after migration: 1. Click **Validate** tab 2. Set sample percentage (1-100%) 3. Click **Run Validation** 4. Review per-table results showing row count comparisons ### Step 4: Replication (Optional) Enable Change Data Capture (CDC) for continuous replication: 1. Click **Replication** tab 2. Configure replication threads 3. Click **Start Replication** 4. Monitor change lag in real-time Replication keeps your target synchronized with ongoing changes to the source database. #### Replication Controls * **Pause** - Temporarily stop applying changes (source still tracks changes) * **Resume** - Continue applying queued changes * **Stop** - Permanently stop replication ## Real-Time Progress Monitoring The GUI provides real-time graphs showing: * **Extracted Rows** - Data pulled from source (blue line) * **Loaded Rows** - Data written to target (green line) * **Per-Table Progress** - Breakdown by individual tables Graphs update automatically every 2 seconds during active migrations. ## Tools ### Wiretalk Query Executor Execute ad-hoc SQL queries against your sources or targets: 1. Click **Tools** → **Wiretalk** 2. Select source or target connection 3. Enter your SQL query 4. Click **Execute** 5. View results in tabular or vertical format ### Log Downloads Download migration logs for troubleshooting: 1. Open your migration 2. Click **Download Logs** 3. Receive a ZIP file containing all log files ## Scheduling Set up automated data refreshes: 1. Open your migration 2. Click **Schedule** tab 3. Select frequency: * Hourly * Every 6 hours * Every 12 hours * Daily (select time) * Weekly (select day and time) * Custom (cron expression) 4. Click **Save Schedule** ## User Management Root users can manage other users: 1. Click your username → **User Management** 2. **Add User** - Create new accounts 3. **Delete User** - Remove accounts Regular users can only see and manage their own migrations. Root users can see all migrations. ## Configuration ### Server Configuration File The UX Server reads configuration from `ux-server.cfg`: ```ini theme={null} # Server port (default 8443) PORT=8443 # SSL certificates CERT_FILE=/opt/wirekite/ux/server/certs/server.crt KEY_FILE=/opt/wirekite/ux/server/certs/server.key # Directory paths STATIC_DIR=/opt/wirekite/ux/static CONFIG_DIR=/opt/wirekite/ux/configs ORCHESTRATOR_BIN=/opt/wirekite/orchestrator/wirekite # Optional: IP whitelist (comma-separated) ALLOWED_IPS=192.168.1.100,192.168.1.101 ``` ### SSL Certificates Generate self-signed certificates for testing: ```bash theme={null} openssl req -x509 -newkey rsa:4096 \ -keyout /opt/wirekite/ux/server/certs/server.key \ -out /opt/wirekite/ux/server/certs/server.crt \ -days 365 -nodes -subj "/CN=your-hostname" ``` For production, use certificates from a trusted CA or Let's Encrypt. ## Systemd Service ### Service File Create `/etc/systemd/system/wirekite-ux.service`: ```ini theme={null} [Unit] Description=Wirekite UX Server After=network.target [Service] Type=simple User=wirekite Group=wirekite WorkingDirectory=/opt/wirekite/ux/server ExecStart=/opt/wirekite/ux/server/ux-server Restart=always RestartSec=10 StandardOutput=append:/opt/wirekite/ux/logs/ux-server.log StandardError=append:/opt/wirekite/ux/logs/ux-server-error.log Environment="GIN_MODE=release" [Install] WantedBy=multi-user.target ``` ### Service Commands ```bash theme={null} # Enable on boot sudo systemctl enable wirekite-ux # Start service sudo systemctl start wirekite-ux # Check status sudo systemctl status wirekite-ux # View logs sudo journalctl -u wirekite-ux -f # Restart after config changes sudo systemctl restart wirekite-ux ``` ## Directory Structure ``` /opt/wirekite/ ├── orchestrator/wirekite # Main orchestrator binary ├── ux/ │ ├── server/ │ │ ├── ux-server # UX server binary │ │ ├── ux-server.cfg # Configuration │ │ └── certs/ # SSL certificates │ ├── static/ # Web assets (HTML/CSS/JS) │ └── logs/ # Server logs ├── instance/ # Migration data │ ├── migrations.json # Migration registry │ ├── sources/ # Source DSN files │ ├── targets/ # Target DSN files │ └── / # Per-migration data │ ├── schema/ │ ├── data/ │ ├── change/ │ └── logs/ └── wiretalk/wiretalk # Query tool ``` ## Troubleshooting ### Cannot Connect to UX Server 1. Verify the service is running: `systemctl status wirekite-ux` 2. Check the server logs: `tail -f /opt/wirekite/ux/logs/ux-server.log` 3. Ensure port 8443 is open in your firewall 4. Verify SSL certificates exist and are readable ### Migration Stuck or Failed 1. Check the migration logs via **Download Logs** 2. Review `orchestrator.log` for high-level errors 3. Check extractor/loader logs for specific issues 4. Verify source/target connectivity with **Test Connection** ### Authentication Issues 1. Clear browser cookies and try logging in again 2. Check `sessions.json` hasn't become corrupted 3. Verify `users.json` contains your user account 4. Restart the UX server to clear all sessions # Installation Source: https://docs.wirekite.io/run/installation Pick the Wirekite installation path that fits your environment. Wirekite ships in three delivery paths. All three share the same binaries, the same UI, and the same source/target support — they differ only in **who operates the host** and **what runs as the supervisor** (systemd, Docker runtime, or our cloud). ## Choose a path Run on your own Linux host with a self-extracting installer. Wirekite is managed by systemd. Best when you want full control of the host and network. Run as a single Docker container on your host. No systemd; the container runtime is the supervisor. Best when you already run a Docker-based ops stack or want a minimal-touch deploy. We host Wirekite on a dedicated VM in our infrastructure. You get a URL, sign in, start migrating. Nothing to install. Best when you want a fully managed path. ## At-a-glance comparison | | **On-Prem** | **Docker** | **Cloud** | | --------------------- | -------------------------------- | -------------------------------------------------- | -------------------------- | | Who owns the host | You | You | Wirekite | | Artifact you receive | `wirekite-installer.run` | Image tag on Docker Hub (or `.tar` for air-gapped) | A URL | | Supervisor | `systemd` | Docker runtime | `systemd` (on our VM) | | TLS by default | Self-signed CA | Self-signed CA | Let's Encrypt wildcard | | License delivery | You install at setup | You bind-mount the pair | We install at provisioning | | Upgrade model | Re-run `.run` | `docker rm -f` + new `--image-tag` | Coordinated VM rebuild | | API server (`:9443`) | Optional (`--with-api` at build) | Disabled | Disabled | | Source/target support | Full | Full | Full | | Caps + metering | Enforced | Enforced | Enforced | The data plane is identical across all three. A migration that works on on-prem will work the same way on Docker or cloud. ## Shared invariants Regardless of which path you pick: 1. **One config file.** Every Wirekite binary reads `/etc/wirekite/wirekite.cfg` (inside the container for Docker, on the VM for cloud). No environment variables for runtime knobs. 2. **License is mandatory at startup.** Every binary validates `$WIREKITE_HOME/license/wirekite.{license,key}` and refuses to start without a valid pair. 3. **The `wirekite` system user owns runtime state.** UID/GID `999` is created at install (or pre-existing in the Docker image). 4. **Encryption key is per-host, never shared.** Each install/container/VM generates its own `instance/encryption.key` on first run and refuses to overwrite it. 5. **Web UI is on `:8443`.** Mapped to host port `:8443` by default for Docker; routed via `:443` at the edge for cloud. *** ## License management License operations are identical across all three paths once installed. ### License files A Wirekite license consists of two files: Encrypted license file containing customer name, expiration date, feature flags, and optional host binding and usage caps. The file is AES-256 encrypted and signed with HMAC-SHA256 to prevent tampering. Decryption key used to read the license file. Must be paired with the matching `.license` file. ### How license validation works Every Wirekite binary validates the license at startup, before doing anything else. If validation fails, the binary prints an error and exits with code 1. The following checks are performed: | Check | Error Message | | ---------------------------------------------- | ------------------------------------------------- | | License file exists and is readable | `License check fail: failed to read license file` | | Signature is valid (file not tampered with) | `license file has been tampered with` | | License has not expired | `License has expired` | | System clock is not set before the issued date | `License issued date is in the future` | | MAC address matches (if host-bound) | `Host ID mismatch` | In the **cloud** path, MAC and clock checks are skipped (cloned VMs cannot have stable MACs and time may be re-synced after boot). Expiry and feature caps are still enforced. ### Validating your license You can manually validate a license at any time using the license utility: ```bash theme={null} /opt/wirekite/license/license -cmd validate \ -input /opt/wirekite/license/wirekite.license \ -keyfile /opt/wirekite/license/wirekite.key ``` This outputs the license details including customer name, expiration date, days remaining, features, and any validation errors. ### Checking licensed features To list all features in your license: ```bash theme={null} /opt/wirekite/license/license -cmd features \ -input /opt/wirekite/license/wirekite.license \ -keyfile /opt/wirekite/license/wirekite.key ``` To check for a specific feature: ```bash theme={null} /opt/wirekite/license/license -cmd features \ -input /opt/wirekite/license/wirekite.license \ -keyfile /opt/wirekite/license/wirekite.key \ -check-feature prod ``` ### Usage caps Some licenses include usage caps that limit the total bytes processed for data migrations and CDC replication. When a cap is reached, the affected loader exits with code 2 and the orchestrator reports the limit in its log. Usage is tracked in `/opt/wirekite/instance/usage.log`. You can view current usage through the [Web Interface](/run/execution/ux) under the license section. A usage cap of `0` means unlimited. If your license does not include usage caps, there are no byte limits on data migration or CDC replication. ### Replacing a license To replace an expired or updated license: * **On-Prem.** Re-run the installer with the new license pair: ```bash theme={null} sudo ./wirekite-installer.run -- \ --license-file=/path/to/new-wirekite.license \ --license-key=/path/to/new-wirekite.key ``` * **Docker.** Replace both files in your `--license-pair-dir`, then `docker restart wirekite-`. The container picks up the new pair from the bind-mount on next license validation. * **Cloud.** Send the new license to your Wirekite rep; we install it on your VM. Running migrations do not need to be restarted — the new license takes effect the next time validation is performed. # Cloud Installation Source: https://docs.wirekite.io/run/installation/cloud Use Wirekite on infrastructure we host and operate. In the cloud path, Wirekite runs on a dedicated VM that we provision, operate, and patch on your behalf. There is **nothing to install** on your side — you receive a URL and a license, sign in, and start configuring migrations. The cloud deployment is functionally identical to on-prem and Docker: same UI, same source/target support, same caps and metering. The only differences are operational (we own the host) and license validation (MAC address and clock checks are skipped, since cloned VMs cannot have stable MACs). ## What you receive from Wirekite Two things, delivered out-of-band (signed URL, secure email, or portal): 1. **Your customer URL** — `https://.cloud.wirekite.io` 2. **First-login instructions** — confirmation that the URL is live and a one-line note that you'll be prompted to create a root user on first browse. That's the entire handoff. We do not send a license file in the cloud path because the license is installed on the VM at provisioning time. ## Getting started ### Step 1: Open the URL Browse to `https://.cloud.wirekite.io`. The cloud edge terminates TLS with a Let's Encrypt wildcard certificate, so your browser will **not** show a certificate warning. ### Step 2: Create the root user The first person to reach the URL is prompted to create the root user (username + password). This account is the only administrator until you create additional users from inside the app. The root user can only be created once. Store these credentials securely — there is no out-of-band password reset for the root account. ### Step 3: Configure your first migration After signing in: 1. **Add a source** — pick a database type (MySQL, PostgreSQL, Oracle, SQL Server, MariaDB), enter host/port/credentials. Wirekite tests the connection and stores credentials encrypted on the data disk. 2. **Add a target** — pick a target type (Firebolt, Snowflake, BigQuery, Spanner, etc.) and enter its credentials. 3. **Create a migration** — choose source + target, pick the schemas and tables you want. 4. **Run** — Wirekite extracts the schema, applies it to the target, streams data, and (optionally) starts continuous CDC replication. The UX shows row counts, throughput, lag, and error logs in real time. ## Network requirements For Wirekite to reach your source and target databases, the cloud VM needs outbound network connectivity to the host:port of each database you configure. | Direction | Endpoint | Why | | -------------------------------------------- | -------------- | ---------------------------------------------------------------------------------- | | Outbound from VM | Your source DB | Schema extraction + initial-load reads + CDC reads | | Outbound from VM | Your target DB | Schema apply + bulk writes (or staging bucket for Snowflake / BigQuery / Firebolt) | | Inbound to `.cloud.wirekite.io:443` | Your browsers | UI access | Most customers either: * Allow-list the cloud VM's outbound egress IP at their database firewall, or * Run a private-link / VPN tunnel between their VPC and ours. Ask your Wirekite rep which option fits your network. The egress IP is provided at hand-off. ## Operational responsibilities | What | Who owns it | | --------------------------------- | ------------------------------------------ | | VM patching, OS updates | Wirekite | | Wirekite version upgrades | Wirekite (coordinated with you) | | Source/target DB credentials | You | | Schema/migration design | You | | Source/target firewall rules | You | | Backup of `encryption.key` | Wirekite (per-customer, in operator vault) | | Backup of source/target databases | You | ## Limits compared to on-prem and Docker A few cloud-specific differences worth knowing: * **API server is disabled.** The cloud path is UX-only. If you need programmatic access, ask about on-prem or Docker with `--with-api`. * **Per-migration data/change directories are hidden** in the UI; cloud uses fixed `/mnt/data` and `/mnt/change` mounts on dedicated disks we provision. * **In-place version upgrades are not yet supported.** Major upgrades are done by re-provisioning your VM; we coordinate with you ahead of time and preserve all migration history. ## Getting help The cloud path comes with hands-on operator support. For anything that doesn't fall into your day-to-day source/target configuration — VM sizing, network plumbing, version upgrades, performance tuning — contact your Wirekite rep through your account's secure channel. # Docker Installation Source: https://docs.wirekite.io/run/installation/container Install Wirekite as a Docker container on a Linux host. The Docker path ships the same install tree baked into a single runtime image. You pull the image from Docker Hub (or load it from a tarball for air-gapped hosts), then run a small wrapper script that renders configuration, stages your license, mints a TLS cert, and starts the container. ## Requirements | Requirement | Notes | | ---------------- | ------------------------------------------------------------------------------ | | Operating system | Any Linux distro that runs current Docker | | Docker engine | 20.10 or newer (`docker --version`) | | Privileges | Root or `sudo` (the wrapper writes under `/var/lib/wirekite/`) | | Free TCP port | `8443` by default (changeable via `--port-host`) | | Outbound HTTPS | To `docker.io` for the image pull, and to your target databases for migrations | | Disk | \~700 MB for the image; migration data + change files on disks you allocate | ## What you receive from Wirekite Three things, delivered out-of-band: 1. **Docker Hub credentials** — a username + Personal Access Token (PAT) that grants read access to `wirekite/wirekite`. (Air-gapped customers receive a `wirekite-image.tar` instead.) 2. **License pair** — `wirekite.license` and `wirekite.key`. Keep both files together. 3. **A pinned image tag** — for example `wirekite/wirekite:0.1.0`. The same image supports every source and target Wirekite ships. ### Stage the license Place both license files in a single directory on the host. The path is your choice; you'll pass it to `--license-pair-dir` later. ```bash theme={null} sudo mkdir -p /opt/wirekite/license sudo cp wirekite.license wirekite.key /opt/wirekite/license/ sudo chmod 0644 /opt/wirekite/license/wirekite.{license,key} ``` Both files must be readable by the container's `wirekite` user (uid `999`); mode `0644` covers that. ## One-time setup ### Docker login ```bash theme={null} docker login -u docker.io # Password: paste the PAT you received. ``` A warning about unencrypted credential storage is normal on a server without Docker Desktop; configure a system credential helper later if your security policy requires it. ### (Optional) Provision data + change disks For production, allocate two host directories — one for each migration's **data** files (initial-load rows in transit) and one for **change** files (CDC chunks). They can sit on separate physical disks for better throughput. ```bash theme={null} # Substitute your block devices sudo mkfs.ext4 /dev/sdb sudo mkfs.ext4 /dev/sdc sudo mkdir -p /mnt/wk-data /mnt/wk-change sudo mount /dev/sdb /mnt/wk-data sudo mount /dev/sdc /mnt/wk-change echo "/dev/sdb /mnt/wk-data ext4 defaults,nofail 0 2" | sudo tee -a /etc/fstab echo "/dev/sdc /mnt/wk-change ext4 defaults,nofail 0 2" | sudo tee -a /etc/fstab # Allow the container's wirekite uid (999) to read/write sudo chown 999:999 /mnt/wk-data /mnt/wk-change ``` Sizing rule of thumb: data disk ≈ 2× the largest single-pass extract; change disk ≈ 24 hours of CDC throughput. Most customers start with 100 GB data + 50 GB change. If you skip this section, Wirekite falls back to a single directory under `/var/lib/wirekite//data/` — fine for evaluation, not recommended for production. ## Install in three steps ### Step 1: Extract the wrapper script from the image ```bash theme={null} docker run --rm --entrypoint=cat \ wirekite/wirekite: /opt/wirekite/scripts/docker_setup.sh \ > docker_setup.sh && chmod +x docker_setup.sh ``` This implicitly pulls the image (\~700 MB first time) and writes `docker_setup.sh` to your current directory. Substitute `` with the pinned tag you received. ### Step 2: Run the wrapper Pick **one** invocation depending on whether you provisioned split disks. **Single-mount (evaluation / dev):** ```bash theme={null} sudo ./docker_setup.sh customer \ --public-hostname= \ --license-pair-dir=/opt/wirekite/license \ --image-tag=wirekite/wirekite: ``` **Split-disk (production-recommended):** ```bash theme={null} sudo ./docker_setup.sh customer \ --public-hostname= \ --license-pair-dir=/opt/wirekite/license \ --image-tag=wirekite/wirekite: \ --data-disk=/mnt/wk-data \ --change-disk=/mnt/wk-change ``` Where: * `` — a short identifier you pick (lowercase alphanumeric + hyphens). Becomes the container name (`wirekite-`) and the per-customer state dir (`/var/lib/wirekite//` by default). * `` — the hostname or IP your users will type in a browser. This value is baked into the TLS certificate's SAN so the browser doesn't flag a mismatch. **TLS and Let's Encrypt**: by default Wirekite mints a self-signed CA. Browsers will show a warning until users accept the cert or you bring your own. Let's Encrypt **does not issue certificates for IPs** — it requires a real DNS name. To use a CA-issued cert see [Bring your own TLS certificate](#bring-your-own-tls-certificate) below. On success the wrapper prints: ``` == Done — container 'wirekite-' is up == Customer URL : https://:8443 ``` ### Step 3: Browse to the URL Open `https://:8443/` in a browser. Accept the self-signed cert warning (or use a CA-issued cert as below). You'll land on the **setup page**. Create the **root user** (username + password), then sign in. ## Bring your own TLS certificate If your organization requires a CA-issued certificate, pass the cert flags instead of relying on the default self-signed CA: ```bash theme={null} sudo ./docker_setup.sh customer \ --public-hostname= \ --license-pair-dir=/opt/wirekite/license \ --image-tag=wirekite/wirekite: \ --cert-mode=customer \ --cert-file=/path/to/your/server.crt \ --key-file=/path/to/your/server.key \ [--chain-file=/path/to/intermediate-chain.crt] \ [--data-disk=/mnt/wk-data --change-disk=/mnt/wk-change] ``` The cert + key files are copied into the container's state dir and bind-mounted read-only. The certificate's `CN` or SAN must include ``. Wirekite does **not** run ACME or auto-renew certs inside the container — that is your operational responsibility. ## Common operations ### Restart the container ```bash theme={null} docker restart wirekite- ``` State on the named volumes is preserved; in-flight migrations reattach automatically. ### Upgrade to a new image tag ```bash theme={null} docker rm -f wirekite- # Re-run the same docker_setup.sh customer ... command with --image-tag= ``` Persistent state (encryption key, certs, license, migration history) survives the recreate because it lives on named volumes and host bind-mounts, not on the container's writable layer. ### Stop temporarily ```bash theme={null} docker stop wirekite- docker start wirekite- ``` Auto-restart on host reboot is on by default (`--restart=unless-stopped`). ### Uninstall ```bash theme={null} docker rm -f wirekite- docker volume rm wirekite--instance wirekite--certs sudo rm -rf /var/lib/wirekite/ docker rmi wirekite/wirekite: ``` Migration data on bind-mounted disks (`/mnt/wk-data`, `/mnt/wk-change`) is preserved unless you remove those host directories yourself. ## Troubleshooting ### `docker pull` fails with "denied: requested access to the resource is denied" You're not logged in or your PAT lacks read access to `wirekite/wirekite`. Run `docker login -u docker.io` and paste your PAT. ### Wrapper says "container 'wirekite-``' already exists" A previous install left a stopped or running container. Remove it: ```bash theme={null} docker rm -f wirekite- ``` Then re-run the wrapper. ### `docker logs` shows "license file does not exist" The `--license-pair-dir` you passed doesn't contain `wirekite.license` and `wirekite.key`, or the directory permissions block the container's uid (999). ```bash theme={null} ls -la /wirekite.license /wirekite.key # Both files should be readable; mode 0644 is fine ``` ### Container restarts in a loop ```bash theme={null} docker logs --tail 50 wirekite- ``` Common causes: * License invalid or expired — contact your Wirekite rep * Bind-mounted cert/key files unreadable — check permissions (`0644`) * Port `8443` already in use on the host — stop the conflicting process or pass `--port-host=` to the wrapper ### Cannot reach a database at `127.0.0.1` from the container The container is on Docker's default bridge network — `127.0.0.1` inside the container is the container's own loopback, not the host's. Use the host's reachable IP, or ask your Wirekite rep about local-mode (host-network) installs for same-host MySQL/Postgres source extracts. # On-Prem Installation Source: https://docs.wirekite.io/run/installation/onprem Install Wirekite on your own Linux host using the self-extracting installer. The on-prem path delivers Wirekite as a single self-extracting installer (`wirekite-installer.run`) that you run on a Linux host you control. Wirekite lives at `/opt/wirekite/`, the web UI runs as a systemd service on port `8443`, and all configuration lives in `/etc/wirekite/wirekite.cfg`. ## Requirements | Requirement | Notes | | ---------------- | ------------------------------------------------------------------------------------ | | Operating system | Ubuntu 20.04+, RHEL 8+, Debian 11+, or Amazon Linux 2 | | Architecture | x86\_64 | | Privileges | Root or `sudo` | | Init system | systemd | | Free TCP ports | `8443` (UX) and `9443` (API, only if API enabled) | | Disk | \~2 GB for the install tree; migration data + change files are on disks you allocate | If you plan to use **Oracle as a source**, the installer bundles the runtime libraries it needs — no separate Oracle Instant Client install is required. ## What you receive from Wirekite Two artifacts, delivered out-of-band (signed URL, secure email, or portal): 1. **`wirekite-installer.run`** — the self-extracting installer. Same binary regardless of which source/target you'll use. 2. **License pair** — two small files: * `wirekite.license` — your customer license * `wirekite.key` — the decryption key paired with that license Keep both license files together. The installer expects them as a pair. ## Install ### Step 1: Run the installer Non-interactive (recommended for scripting): ```bash theme={null} sudo ./wirekite-installer.run -- \ --license-file=/path/to/wirekite.license \ --license-key=/path/to/wirekite.key ``` The `--` separates installer-extractor arguments from the install-script arguments that follow. The installer will: 1. Extract the install tree to `/opt/wirekite/` 2. Create the `wirekite` system user 3. Validate and install your license pair to `/opt/wirekite/license/` 4. Write `/etc/wirekite/wirekite.cfg` with `DEPLOYMENT=onprem` 5. Mint a self-signed CA and TLS server cert (`wirekite_ca` mode, default) 6. Generate the per-host `instance/encryption.key` 7. Install the dynamic linker config for bundled database drivers 8. Install the `wirekite-ux.service` systemd unit and start it If you omit `--license-file` / `--license-key`, the installer prompts for them interactively. ### Step 2: Browse to the UI Open `https://:8443/` in a browser. Because the default cert is self-signed, your browser will show a "your connection is not private" warning — accept it (or see [Bring your own TLS certificate](#bring-your-own-tls-certificate) below). You'll land on the **setup page**. Create the **root user** (username + password). After that, sign in and start configuring sources, targets, and migrations. ## Bring your own TLS certificate To avoid the browser warning, supply a CA-issued certificate at install time: ```bash theme={null} sudo ./wirekite-installer.run -- \ --license-file=/path/to/wirekite.license \ --license-key=/path/to/wirekite.key \ --cert-mode=customer \ --cert-file=/path/to/server.crt \ --key-file=/path/to/server.key ``` The certificate's `CN` or SAN must match the hostname users will type in the browser. ## Split-disk layout (recommended for production) Wirekite reads two optional keys from `/etc/wirekite/wirekite.cfg`: ```ini theme={null} DATA_BASE_DIR=/mnt/data CHANGE_BASE_DIR=/mnt/change ``` * `DATA_BASE_DIR` — where extracted-row files for initial loads are staged * `CHANGE_BASE_DIR` — where CDC change files are staged Putting these on separate physical disks improves throughput and isolates data-phase IO from CDC-phase IO. After editing the cfg, restart the UX server: ```bash theme={null} sudo systemctl restart wirekite-ux ``` Both directories must be writable by the `wirekite` user: ```bash theme={null} sudo chown wirekite:wirekite /mnt/data /mnt/change ``` If these keys are unset, Wirekite falls back to per-migration subdirectories under `$WIREKITE_HOME/instance//`. ## Service management The installer registers `wirekite-ux.service`. Manage it with the usual `systemctl` commands: ```bash theme={null} sudo systemctl status wirekite-ux sudo systemctl restart wirekite-ux sudo journalctl -u wirekite-ux -f ``` `wirekite-ux` is the only unit required. The orchestrator and per-database loaders are launched as child processes by the UX server when migrations run. ## Upgrade To upgrade to a new release: 1. Stop the UX server: ```bash theme={null} sudo systemctl stop wirekite-ux ``` 2. Run the new installer: ```bash theme={null} sudo ./wirekite-installer.run -- \ --license-file=/path/to/wirekite.license \ --license-key=/path/to/wirekite.key ``` The installer preserves your existing state: * `/opt/wirekite/instance/` — encryption key, users, migrations metadata * `/opt/wirekite/license/` — your license pair * `/opt/wirekite/certs/` — your TLS certs 3. The installer restarts the UX server on success. ## Uninstall ```bash theme={null} sudo /opt/wirekite/packager/uninstall.sh ``` Add `-y` to skip the confirmation prompt. The uninstaller stops + removes the systemd unit, deletes `/opt/wirekite/`, removes the `wirekite` user, and deletes `/etc/wirekite/`. Uninstalling removes all migration configurations and data under `/opt/wirekite/instance/`. Back it up first if you need to preserve your migrations. ## Troubleshooting ### License validation failed Run the license utility directly: ```bash theme={null} sudo -u wirekite /opt/wirekite/license/license -cmd validate \ -input /opt/wirekite/license/wirekite.license \ -keyfile /opt/wirekite/license/wirekite.key ``` Common failures: * `License has expired` — contact your Wirekite rep for a renewal. * `Host ID mismatch` — your license is bound to a specific MAC address. Either run on the bound host or request a host-independent license. * `license file has been tampered with` — the `.license` and `.key` are mismatched, or one was modified after issue. Reinstall the pair you originally received. ### UX server won't start ```bash theme={null} sudo journalctl -u wirekite-ux -n 100 sudo tail -f /opt/wirekite/ux/logs/ux-server.log ``` Most startup failures are license, port, or cert issues. Check that port `8443` is free (`sudo lsof -i :8443`) and that `/opt/wirekite/ux/server/certs/` contains a readable `server.crt` + `server.key`. # Operations Source: https://docs.wirekite.io/run/operations Monitor, pause, and control running Wirekite migrations using metadata tables. ## Overview Wirekite uses two metadata tables to track migration progress and enable operational control: * **wirekite\_progress** - Tracks every file/operation processed, storing position checkpoints for crash recovery * **wirekite\_action** - Single-row control table for pause/stop/resume operations These tables are created automatically in the target database when a migration starts. ## Metadata Tables ### wirekite\_progress This table tracks the state of every extraction and loading operation, enabling crash recovery and progress monitoring. **Schema:** ```sql theme={null} CREATE TABLE wirekite.wirekite_progress ( source VARCHAR(256), target VARCHAR(256), operation TEXT NOT NULL, transmission TEXT NOT NULL DEFAULT 'F', mark VARCHAR(64) NULL, table_name VARCHAR(256) NULL, start_time TIMESTAMP NOT NULL, finish_time TIMESTAMP NULL, restarts INT DEFAULT 0 NOT NULL, PRIMARY KEY (source, target) ); ``` The schema name varies by database: `wirekite` for PostgreSQL, MySQL, Oracle, SingleStore; `public` for Snowflake and Firebolt. **Column Reference:** Primary key component. Identifies the file or resource being processed (e.g., `0.ckt`, `schema.table.0.dkt`, binlog name). Primary key component. Identifies the destination or operation type. Operation code: * `D` - Data Load * `CE` - Change Extract * `C` - Change Load Transfer mode: * `F` - File-based processing Progress checkpoint. Meaning depends on operation type: * **Data loaders**: Row count successfully committed * **Change extractors**: LSN/binlog position/SCN (database-specific position marker) * **Change loaders**: Sequence number in .ckt file Associated table name for multi-table operations. When this operation started. `NULL` while in progress; set to completion time when done. This is the critical recovery indicator. Counter tracking how many times this operation was restarted after a crash. ### wirekite\_action This single-row table controls the running state of loaders and extractors. **Schema:** ```sql theme={null} CREATE TABLE wirekite.wirekite_action ( action VARCHAR(5), PRIMARY KEY (action) ); INSERT INTO wirekite.wirekite_action VALUES ('RUN'); ``` **Valid Values:** | Value | Behavior | | ------- | --------------------------------------------------------------- | | `RUN` | Normal operation - processes data continuously | | `PAUSE` | Pause operation - component sleeps for 5 seconds between checks | | `STOP` | Stop operation - component exits gracefully | ## Pause, Stop, and Resume Wirekite components poll the `wirekite_action` table during processing. This enables non-disruptive control without restarting processes. ### Using the Web Interface The easiest way to control migrations is through the [Web Interface](/run/execution/ux): 1. Navigate to the migration details page 2. Click **Pause** to pause replication 3. Click **Resume** to continue 4. Click **Stop** to gracefully shut down ### Using SQL Commands You can also control migrations directly via SQL on the target database: **Pause Replication:** ```sql theme={null} UPDATE wirekite.wirekite_action SET action = 'PAUSE'; ``` **Resume Replication:** ```sql theme={null} UPDATE wirekite.wirekite_action SET action = 'RUN'; ``` **Stop Replication:** ```sql theme={null} UPDATE wirekite.wirekite_action SET action = 'STOP'; ``` Always use `STOP` for graceful shutdown rather than killing the process. This ensures the current transaction completes and progress is recorded. ## Monitoring Progress ### Check Migration Status Query `wirekite_progress` to see the state of all operations: ```sql theme={null} SELECT source, operation, mark, start_time, finish_time, restarts FROM wirekite.wirekite_progress WHERE operation IN ('D', 'CE', 'C') ORDER BY start_time DESC; ``` ### Find Incomplete Operations Identify operations that are still in progress or may be stuck: ```sql theme={null} SELECT source, operation, table_name, start_time, restarts FROM wirekite.wirekite_progress WHERE finish_time IS NULL ORDER BY start_time DESC; ``` Records with `finish_time IS NULL` and an old `start_time` may indicate a hung process. ### Monitor Restart Counts High values in the `restarts` column indicate repeated failures: ```sql theme={null} SELECT source, operation, restarts, start_time FROM wirekite.wirekite_progress WHERE restarts > 0 ORDER BY restarts DESC; ``` ## Crash Recovery Wirekite automatically recovers from crashes using the `wirekite_progress` table: 1. On startup, components check for records with `finish_time IS NULL` 2. If found, processing resumes from the position stored in `mark` 3. The `restarts` counter is incremented This ensures zero data loss - partially loaded files resume from the last committed position. ## Resetting Migration State Resetting migration state can cause duplicate data if not done correctly. Always truncate both the progress table AND the target tables together. To reset a migration and start fresh: **1. Stop the migration:** ```sql theme={null} UPDATE wirekite.wirekite_action SET action = 'STOP'; ``` **2. Wait for processes to exit, then truncate progress on both source and target:** ```sql theme={null} TRUNCATE TABLE wirekite.wirekite_progress; ``` **3. Truncate target tables that will be reloaded.** **4. Reset action to RUN:** ```sql theme={null} UPDATE wirekite.wirekite_action SET action = 'RUN'; ``` **5. Restart the migration.** ## Safety Guidelines Deleting records from `wirekite_progress` can cause duplicate data in the target or missed changes during replication. High restart counts indicate repeated failures. Investigate the root cause before the issue compounds. Records with NULL `finish_time` and old `start_time` may indicate hung processes that need investigation. When resetting, always truncate `wirekite_progress` AND target tables together to prevent duplicates. # Performance Tuning Source: https://docs.wirekite.io/run/performance Optimize Wirekite migrations for throughput, memory, and resource efficiency. ## Overview Wirekite performance is controlled by three main levers: **thread counts**, **batch sizes**, and **compression**. This guide covers how each parameter affects performance and provides recommendations for common scenarios. ## Thread Configuration Threads control parallelism across all components. Each component runs its threads independently, so the total resource usage is the sum of all active components. ### Extraction Threads Number of parallel threads for extracting tables from the source database. Each thread extracts one table at a time. The change extractor is single-threaded to preserve transaction commit ordering. This parameter exists for future use but should be left at the default. ### Loading Threads Number of parallel threads for loading data files into the target database. Each thread loads one file at a time. Number of parallel threads for applying change files to the target database. For cloud targets (Snowflake, BigQuery, Firebolt, Databricks), the `maxMergeThreads` parameter (default: 2x CPU cores) controls parallelism within each merge batch. ### Mover Threads Number of parallel threads for transferring files between source and target staging areas (S3, GCS, or Snowflake internal stage). Movers default to a higher thread count since file transfers are I/O-bound rather than CPU-bound. ### Thread Recommendations | Scenario | Extraction | Loading | Mover | | --------------------------- | ---------- | ------- | ----- | | Small database (under 10GB) | 4 | 4 | 4 | | Medium database (10-100GB) | 8 | 6 | 8 | | Large database (over 100GB) | 8-12 | 8 | 10 | | Resource-constrained host | 2-4 | 2-4 | 4 | Each extraction thread opens a database connection. Ensure your source database can handle the total connection count: `maxThreads` per active component. Monitor your database connection limits before increasing threads. ## Batch Sizes Batch sizes control how much data is processed per unit of work. Larger batches improve throughput but use more memory. ### Data Extraction Maximum rows per extracted data file. Tables larger than this threshold are split into multiple files. Applies to MySQL, Oracle, and SQL Server extractors. PostgreSQL-specific alternative to `maxRowsPerDump`. Measures in 8KB database pages rather than rows. The default of 8,000 pages produces files of approximately 64MB. **Sizing guidance:** | Row width | Recommended maxRowsPerDump | Approximate file size | | ------------------------ | -------------------------- | --------------------- | | Narrow (under 200 bytes) | 200,000-500,000 | 40-100MB | | Medium (200-1000 bytes) | 100,000-200,000 | 50-200MB | | Wide (over 1000 bytes) | 50,000-100,000 | 50-100MB | ### Change Loading Number of change files to process in a single merge operation. Higher values increase throughput but create larger transactions. Default is 60 for most targets; 30 for Spanner and SingleStore. ### CDC Event Buffering Number of change events buffered in memory before flushing to disk. Applies to MySQL and Oracle change extractors only. PostgreSQL uses a fixed rotation threshold of approximately 150,000 operations. Lower values reduce memory usage but increase I/O operations. ### SQL Server CDC Number of LSN (Log Sequence Number) records to process per batch. SQL Server specific. ## Compression Compress data files with gzip before transferring to cloud staging areas. Applies to AWS S3, GCS, and Snowflake internal stage movers. **When to enable compression:** | Condition | Recommendation | | ---------------------------------------------------- | -------------- | | Network bandwidth is limited | Enable | | Cloud egress costs are a concern | Enable | | CPU is the bottleneck | Disable | | Files are already small (under 10MB) | Disable | | Large dataset with high compressibility (text-heavy) | Enable | Tabular data typically compresses 5-10x with gzip. A 200MB data file may compress to 20-40MB, significantly reducing transfer time on constrained networks. ## Database-Specific Tuning ### MySQL / MariaDB / SingleStore * The extractor uses `SQL_NO_CACHE` to bypass the query cache and avoid polluting it during bulk reads * Use `loadLocal=true` if the MySQL server lacks the FILE privilege (uses `LOAD DATA LOCAL INFILE` instead) * Binary data encoding (`hexEncoding` or `base64Encoding`) adds overhead; only enable if required by the target ### PostgreSQL / YugaByte / TigerData / AlloyDB * Uses the COPY protocol for high-speed bulk data movement * Tune `maxPages` instead of `maxRowsPerDump` for page-aligned extraction * `sortFiles=true` sorts output by primary key after extraction, which can improve target load performance for ordered storage engines ### Oracle * CDC uses System Change Numbers (SCN) for precise position tracking * `sortFiles=true` enables primary key ordering for extracted data * LOB (Large Object) columns are handled inline and can significantly increase row width ### SQL Server * The change extractor maintains a connection pool of 50 open connections and 25 idle connections * `useExternalDumper=true` uses the BCP utility for faster extraction when available * `lsnBatchSize` controls the granularity of CDC processing; reduce if memory is constrained ### Snowflake * Loading performance depends on the Snowflake warehouse size specified in the connection string * Uses atomic COPY operations with `ON_ERROR=ABORT_STATEMENT` for data integrity * Each loading thread performs a PUT followed by COPY; the warehouse compute scales with thread count ### BigQuery * Requires a GCS bucket for staging (`gcs_bucket` parameter) * Uses a two-stage load process: CSV files are uploaded to GCS, then loaded via BigQuery load jobs * Loading thread count should be conservative to avoid exceeding BigQuery quotas ### Spanner * Be conservative with `maxThreads` (start at 4-5) as higher values can trigger Spanner rate limiting * Uses mutation batching for CDC operations ## Pipeline Architecture Understanding how the orchestrator coordinates components helps with tuning: ``` Source DB → [Extractor] → Local Files → [Mover] → Cloud Stage → [Loader] → Target DB ↑ ↑ ↑ maxThreads=5 maxThreads=10 maxThreads=5 ``` All three components run in parallel. The extractor produces files, the mover transfers them, and the loader consumes them. The pipeline naturally balances itself: * If extraction is fastest, the mover and loader work through a growing backlog * If loading is slowest, files accumulate in the staging area until the loader catches up * The `removeFiles` parameter controls whether files are cleaned up after loading For combined data + change mode, the orchestrator completes the bulk data load first, captures the source position, then starts change replication from that position. Thread counts are configured independently for each phase. ## Tuning by Scenario ### Maximize Throughput (Large Migration) When migrating a large database and resources are plentiful: ```ini theme={null} # Aggressive extraction source.data.maxThreads=12 source.data.maxRowsPerDump=200000 # Fast loading target.data.maxThreads=8 # Fast file transfer mover.maxThreads=10 mover.gzipFiles=false ``` ### Minimize Resource Usage When running on a constrained host or sharing resources: ```ini theme={null} # Conservative extraction source.data.maxThreads=2 source.data.maxRowsPerDump=50000 # Conservative loading target.data.maxThreads=2 # Conservative transfer mover.maxThreads=4 mover.gzipFiles=true ``` ### Optimize for Network-Limited Environments When bandwidth between source and target is limited: ```ini theme={null} # Normal extraction source.data.maxThreads=8 source.data.maxRowsPerDump=100000 # Normal loading target.data.maxThreads=6 # Maximize transfer efficiency mover.maxThreads=10 mover.gzipFiles=true ``` ### CDC Replication Tuning For low-latency continuous replication: ```ini theme={null} # Change extraction (MySQL/Oracle) source.change.eventsPerFlush=5000 # Change loading - smaller batches for lower latency target.change.maxFilesPerBatch=10 # Fast change file transfer mover.maxThreads=8 ``` ## Monitoring During a migration, monitor these indicators to identify bottlenecks: | Indicator | What to Watch | Action if Bottleneck | | -------------------- | ------------------------------------------------- | ------------------------------------------------------------ | | Extraction rate | Files produced per minute in the output directory | Increase `source.data.maxThreads` | | File backlog | Files waiting in the staging area | Increase `mover.maxThreads` or `target.data.maxThreads` | | Load rate | Files consumed per minute by the loader | Increase `target.data.maxThreads` or reduce `maxRowsPerDump` | | Database connections | Active connections on source/target | Reduce `maxThreads` if approaching limits | | Memory usage | System memory on the Wirekite host | Reduce `maxRowsPerDump`, `maxThreads`, or `maxFilesPerBatch` | | Disk space | Local file staging directory | Enable `removeFiles=true` or increase mover threads | Use the [Web Interface](/run/execution/ux) to monitor real-time extraction and loading progress with per-table breakdown, or query the [wirekite\_progress](/run/operations) table directly. # CDC Replication Source: https://docs.wirekite.io/run/replication How Wirekite captures and applies changes for continuous database replication. ## Overview Wirekite's Change Data Capture (CDC) replication keeps a target database synchronized with ongoing changes to the source. The system extracts changes (inserts, updates, deletes) from the source database's transaction log, writes them to intermediate `.ckt` files, and applies them to the target using merge tables. CDC can run independently or combined with a bulk data load. When combined, the orchestrator automatically handles the transition from data migration to continuous replication. ## Handover: Data to CDC Transition When data and change modes are combined in a single configuration, the orchestrator performs an automatic handover after the bulk data load completes. This captures the exact source position so that change replication begins without missing or duplicating any rows. The handover is a 4-step process: Pause replication on the source to freeze the position. Record the current position in the source transaction log. Launch the change extractor and loader with the captured position. Resume replication on the source. The change extractor now captures all new events from the saved position forward. ### Position Capture by Database Each database type uses a different mechanism to identify the current position in its transaction log: | Database | Position Type | Capture Method | | ---------- | ----------------------------- | ----------------------------------------------------------------------------------- | | MySQL | Binlog file + byte offset | `SHOW MASTER STATUS` followed by `FLUSH BINARY LOGS` | | PostgreSQL | WAL Log Sequence Number (LSN) | `pg_current_wal_lsn()` plus creation of a logical replication slot | | Oracle | System Change Number (SCN) | `SELECT CURRENT_SCN FROM V$DATABASE` followed by `ALTER SYSTEM ARCHIVE LOG CURRENT` | | SQL Server | Log Sequence Number (LSN) | `sys.fn_cdc_get_max_lsn()` via CDC, or HADR/transaction log fallback | When running data + change mode together, do not specify a starting position in the change source configuration. The orchestrator captures and injects the position automatically during handover. ## Change Extraction The change extractor connects to the source database's transaction log and writes changes to `.ckt` files in the output directory. ### Continuous Replication Loop The extractor runs in a continuous loop: 1. Wait for new events from the transaction log (with timeout) 2. Process each event (write INSERT, UPDATE, or DELETE to the current `.ckt` file) 3. When the operation count reaches the rotation threshold or a time-based flush triggers, rotate to a new file at the next COMMIT boundary 4. Record the new file in the `wirekite_progress` table 5. Repeat ### File Rotation The extractor rotates to a new `.ckt` file when either condition is met: * **Operation count**: PostgreSQL rotates after approximately 150,000 data operations. MySQL rotates based on `flushIntervalSeconds` (time-based) or binlog rotation. Oracle and SQL Server rotate per archive log or LSN range. * **Time-based flush**: Buffered data is flushed every few seconds to prevent loss on crash Rotation always occurs at a transaction COMMIT boundary to ensure no partial transactions span files. The rotation process is atomic: 1. Flush buffered data to the temporary file (`N.ckt_`) 2. Close the file 3. Rename `N.ckt_` to `N.ckt` (atomic filesystem operation) 4. Record the file in `wirekite_progress` 5. Open the next file (`N+1.ckt_`) ### exitWhenIdle When true, the change extractor exits after a period of inactivity (controlled by `idleWaitSeconds`). On exit, it creates a `CHANGE.DONE` marker file in the output directory. Useful for one-time sync scenarios where continuous replication is not needed. When `exitWhenIdle` is false (the default), the extractor runs indefinitely until stopped via the [wirekite\_action](/run/operations) table or process termination. ## Transaction Consistency Wirekite maintains transaction ordering through several mechanisms: * **Single-threaded extraction**: The change extractor processes the transaction log sequentially, preserving the original commit order * **File rotation at COMMIT boundaries**: Files never split a transaction, so each `.ckt` file contains only complete transactions * **Ordered file processing**: The change loader processes files in sequential numeric order (0.ckt, 1.ckt, 2.ckt, ...) * **Multi-threaded merge**: Within each batch, the change loader can apply changes to multiple tables concurrently using merge threads (controlled by `maxMergeThreads`), while still preserving per-table ordering * **Atomic merge operations**: Each batch of changes is applied within a single transaction on the target The `processCommits` parameter controls whether BEGIN (`B`) and COMMIT (`C`) markers are written to `.ckt` files. When enabled, the change loader can use these markers to understand transaction boundaries during application. ## Crash Recovery CDC replication recovers automatically from crashes using the `wirekite_progress` table. ### Change Extractor Recovery On restart, the change extractor: 1. Queries `wirekite_progress` for the latest `CE` (Change Extract) record 2. If the record has `finish_time IS NULL`, the last file was incomplete -- resumes from the `mark` position (binlog position, LSN, or SCN) 3. If a temporary file (`.ckt_`) exists, it is either renamed or discarded based on the recovery state 4. Continues writing from the next file number ### Change Loader Recovery On restart, the change loader: 1. Scans the input directory for `.ckt` files 2. Queries `wirekite_progress` for the last processed `C` (Change Load) record 3. Skips files that have already been fully processed (`finish_time IS NOT NULL`) 4. Resumes from the next unprocessed file Each batch starts with a clean state, so partial batches from a previous crash are safely discarded and reprocessed. ## Monitoring Replication ### Progress Queries Check the latest extractor position: ```sql theme={null} SELECT source, mark, start_time, finish_time FROM wirekite.wirekite_progress WHERE operation = 'CE' ORDER BY start_time DESC LIMIT 5; ``` Check the latest loader position: ```sql theme={null} SELECT source, mark, start_time, finish_time FROM wirekite.wirekite_progress WHERE operation = 'C' ORDER BY start_time DESC LIMIT 5; ``` ### Measuring Lag Replication lag is the difference between the current time and the timestamp of the latest change file processed by the loader: ```sql theme={null} SELECT TIMESTAMPDIFF(SECOND, MAX(finish_time), NOW()) AS lag_seconds FROM wirekite.wirekite_progress WHERE operation = 'C' AND finish_time IS NOT NULL; ``` You can also monitor lag through the [Web Interface](/run/execution/ux), which displays real-time change lag on the replication tab. ### Source-Side Lag Queries Monitor the source database to understand how far behind extraction is: **MySQL:** ```sql theme={null} SHOW MASTER STATUS; -- Compare current position with extractor's last recorded position ``` **PostgreSQL:** ```sql theme={null} SELECT slot_name, pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn) AS lag_bytes FROM pg_replication_slots WHERE slot_name = 'wirekite_replication_slot'; ``` ## Configuration Reference Key parameters for CDC replication. For the complete parameter list, see the individual [Source Guides](/sourceguides/mysql) and [Target Guides](/targetguides/snowflake). ### Change Extractor Parameters | Parameter | Type | Default | Description | | ---------------------- | ------- | ------- | ---------------------------------------------------------------------------------------------------------------- | | `exitWhenIdle` | boolean | false | Exit after idle timeout instead of running continuously | | `idleWaitSeconds` | integer | varies | Seconds of inactivity before considering idle. Defaults: MySQL=2, PostgreSQL=3, SQL Server=10, Oracle=30 | | `flushIntervalSeconds` | integer | 5 | Force flush buffered data every N seconds (MySQL and Oracle only) | | `eventsPerFlush` | integer | 5000 | Flush after N events (MySQL and Oracle only). PostgreSQL uses a fixed rotation threshold of \~150,000 operations | | `processCommits` | boolean | false | Include BEGIN/COMMIT markers in .ckt files | | `binlogFile` | string | - | MySQL starting binlog filename (standalone change mode only) | | `binlogPosition` | integer | - | MySQL starting byte offset (standalone change mode only) | | `startScn` | string | - | Oracle starting SCN (standalone change mode only) | | `startLsn` | string | - | SQL Server starting LSN (standalone change mode only) | | `replicationSlot` | string | - | PostgreSQL replication slot name (required for PostgreSQL CDC) | | `lsnBatchSize` | integer | 1000000 | Number of LSNs per batch (SQL Server only) | ### Change Loader Parameters | Parameter | Type | Default | Description | | --------------------- | ------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `maxFilesPerBatch` | integer | 60 | Number of .ckt files per merge batch (30 for Spanner and SingleStore) | | `maxMergeThreads` | integer | 2 x CPU cores | Number of parallel threads for applying merge operations within each batch. Applies to Snowflake, BigQuery, Firebolt, and Databricks targets. MySQL, PostgreSQL, Oracle, and SQL Server targets use a fixed maximum of 10. | | `removeFiles` | boolean | false | Delete .ckt files after successful loading | | `changeFileExtension` | string | ckt | Extension for change files | | `workDirectory` | string | - | Working directory for merge operations | | `doneDirectory` | string | - | Directory to move completed files (alternative to removeFiles) | # Target Sync Source: https://docs.wirekite.io/run/targetsync Reconcile an already-populated target back to its source in a single pass — Wirekite diffs the two databases and applies only the differences, with no CDC. ## Overview **Target Sync makes a target table set match a source table set in one shot, without CDC.** It compares each table between a source and a target database, row by row, and applies exactly the inserts, updates, and deletes needed to bring the **target** into agreement with the **source**. Where [Data Loading](/run/dataloading) does a one-time bulk load into an empty target and [CDC Replication](/run/replication) streams ongoing changes continuously, Target Sync is the third mode: a **one-shot diff-and-apply** that reconciles a target that already holds data. Target Sync is **one-directional**: the source is the source of truth, and the target is reconciled to it. To sync the other way, swap source and target in a separate run. Internally, Target Sync reuses the [TableValidator's](/run/validation) sort-merge diff walk. Instead of only *reporting* differences, it *emits* them as change records that a change-loader applies to the target — so the change records are byte-identical to the ones CDC produces, and the same target loaders apply them. ### When to use it A target that has diverged from its source — a CDC gap, a manual edit, a load that stopped halfway — is re-converged exactly. Seed or top up a target that has no change feed, without standing up a continuous pipeline for a one-time job. Move a database pair where CDC is unavailable or not worth configuring. A single reconciling pass lands the data. ### When *not* to use it * **Continuous replication** — use [CDC Replication](/run/replication) (the streaming change extractor + change loader). * **Bidirectional sync** — Target Sync is one-directional per run. ## How It Works Target Sync runs as two cooperating stages that communicate through a shared **emit directory** on local disk. ``` ┌───────────┐ read + diff ┌──────────┐ SOURCE ─▶│ EMIT │◀────────────────│ TARGET │ (truth) │ (Table- │ read PKs └──────────┘ │ Validator)│ ▲ └─────┬─────┘ │ apply I/U/D │ writes N.ckt files │ ▼ │ emit directory ──────────────▶ ┌──────────┐ (0.ckt, 1.ckt, …, │ APPLY │ CHANGE.DONE) │ (change │ │ loader) │ └──────────┘ ``` | Stage | Binary | Role | | ------------ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | **1. Emit** | `tablevalidator` | Reads source + target, diffs each table in primary-key order, writes change records as `N.ckt` files, then drops a `CHANGE.DONE` sentinel. | | **2. Apply** | `/loader/change_loader` | Watches the emit directory, applies each `N.ckt` to the target, moves applied files aside, and exits when it sees `CHANGE.DONE`. | The two stages run **concurrently**: the loader begins applying early `N.ckt` files while the emitter is still producing later ones. They rendezvous on the `CHANGE.DONE` sentinel — when the loader logs `CHANGE.DONE - exiting`, the target matches the source. Target Sync can be driven from the Wirekite **GUI** or **API**, which manage the run directory, config files, and both processes for you. The mechanics below describe what those interfaces orchestrate, and how to run it directly. ## Supported Databases | Role | Supported types | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | **Source** | `postgres`, `mysql`, `mariadb`, `sqlserver`, `oracle`, `cassandra` | | **Target** | `postgres`, `mysql`, `mariadb`, `singlestore`, `sqlserver`, `oracle`, `firebolt`, `snowflake`, `databricks`, `bigquery`, `spanner`, `mongodb` | The source set is smaller because the source drives full INSERT/UPDATE row encoding (it needs complete column-type coverage). The target only supplies primary keys for DELETE detection, so more target types are supported. The emitter **fails loud** at startup on an unsupported source or target type. **Cassandra is a Target-Sync-only source.** Cassandra has no CDC path in Wirekite — it participates as a source exclusively through Target Sync (snapshot + drift repair). See the [Cassandra Source Guide](/sourceguides/cassandra) and the [Cassandra Datatype Matrix](/datatypes/cassandra). **MariaDB and TigerData reuse other binaries.** MariaDB reuses the MySQL change-loader and TigerData reuses PostgreSQL's. When resolving the change-loader path, map `mariadb → mysql` and `tigerdata → postgres`. The `sourceType`/`targetType` names in the configs stay as the real database type. ## Prerequisites Target Sync inserts, updates, and deletes rows; it does **not** create tables. Run [schema migration](#schema-migration) first if the target is empty. The `.skt` describes the tables (columns, types, primary keys). It is produced by the schema-migration step and consumed by **both** stages — they must be given the *same* `.skt`. UPDATE and DELETE records are keyed by primary key. The emitter refuses a table with no PK rather than emit unkeyed records. The sort-merge diff relies on a consistent key ordering. A case-insensitive source syncing to a case-sensitive target (or vice-versa) can mis-window keys. See [Limitations](#limitations--correctness-rules). ### Schema Migration Target Sync does **not** create tables or produce the `.skt` — a one-time **schema migration** does both. Run it whenever the target tables don't yet exist (or the source schema has changed). It has three logical steps, coordinated by the `wirekite` orchestrator: 1. **Extract** the source schema → `wirekite_schema.skt` via the source's `schema_extractor`. 2. **Generate** the target DDL from the `.skt` — `c.sql` (CREATE TABLE, plus the `_wkm` merge shadow tables), `i.sql` (constraints / primary keys), `f.sql` (foreign keys), `d.sql` (DROP TABLE) — via the target's `schema_loader`. 3. **Apply** the generated DDL to the target to actually create the tables. The orchestrator's `schema-extract` mode performs steps 1–2 in one invocation. Step 3 (applying the SQL) is run separately — via the orchestrator's apply modes or by executing the generated `.sql` files with your own DB client. **Create the target schema with `createMergeTables=true`.** The change-loader applies change records through per-table `_wkm` merge shadow tables; those must exist before the apply stage runs. The schema loader creates them when this flag is set. After schema migration completes, the target tables and the `.skt` are in place. Proceed to the emit and apply stages, passing the **same** `wirekite_schema.skt` and the **same** `schemaRename` you used during migration. ## Stage 1 — Emit (TableValidator) The emit stage runs the TableValidator in emit mode. It reads the source and target, diffs each table, and writes change records to the emit directory. ```bash theme={null} tablevalidator ``` ### Configuration Must be `true` to enable Target Sync emit. Otherwise the binary runs in plain [validation](/run/validation) mode. Directory where `N.ckt` files and the `CHANGE.DONE` sentinel are written. Created if absent. The apply stage reads from here. One of the supported source types (see [Supported Databases](#supported-databases)). Path to a file containing the source DSN. One of the supported target types. Path to a file containing the target DSN. Path to the `.skt` schema file. Must be the same file given to the apply stage. Path to a file listing tables to sync, one `schema.table` per line (source-side names). `sourceSchema:targetSchema` — rewrites the schema name in emitted records (e.g. `dbo:app_schema`). Required when the source and target schema names differ, and must match the value used during schema migration. Rows per diff window (e.g. `10000`). Controls memory and parallel granularity. Recommended. Maximum concurrent table-window comparisons. Bound it by the source and target connection limits. Recommended. Target size of each consolidated `N.ckt` file. Larger files amortize the loader's per-file cost (most impactful for cloud targets). Emit log path. Recommended. Enables emit resume — records each emitted window so a restarted emitter skips finished work. See [Resume & Crash Recovery](#resume--crash-recovery). When `true`, resumes from `checkpointDir` instead of clearing prior output. GCP credentials JSON. Required for Spanner and BigQuery targets (the emitter reads target DELETE primary keys from them). #### Cassandra source options When `true`, uses the bounded `(pk, hash)` diff — projecting each row to a primary key plus a row hash rather than materializing whole tables. Recommended for Cassandra sources. Applies to single-PK tables; composite PKs fall back to a whole-table sort automatically. In-memory ceiling for the `(pk, hash)` projection before it spills to a k-way merge. Trade RAM for spill I/O. In-memory ceiling for the whole-row sort (the composite-PK fallback and initial data migration). ### Output | File | Meaning | | ----------------------------- | ---------------------------------------------------------------------------------------------------- | | `0.ckt`, `1.ckt`, … | Gapless, ascending change-record files. | | `CHANGE.DONE` | Zero-byte sentinel written **after** all `N.ckt` are finalized. Its presence means emit is complete. | | `part_*.part`, `building.tmp` | Transient intermediates — ignore them. | In emit mode the per-table summary is worded **DIFF** (not FAIL) — differences are the expected product of a sync, not a validation failure. The emitter prints a final line: `target-sync emit complete: N CKT file(s) … + CHANGE.DONE`. ## Stage 2 — Apply (Change Loader) The apply stage runs the target's change loader. It drains `N.ckt` files from the emit directory and applies them to the target. ```bash theme={null} /loader/change_loader ``` Resolve the binary directory with the `mariadb → mysql` and `tigerdata → postgres` mapping. For example, a MariaDB target uses `mysql/loader/change_loader`. ### Configuration Path to a file containing the **target** DSN. The same `.skt` given to the emitter. The emitter's `emitOutputDirectory`. Where applied `N.ckt` files are moved after success. Scratch directory for the loader. Must be `false` — the emitter base64-encodes string and binary values. Maximum concurrent table applies. Recommended. Apply log path. Recommended. GCP credentials JSON. Required for Spanner and BigQuery targets. Staging bucket for the loader's `COPY`. Required for Firebolt and Databricks targets (they stage CSVs to S3). Pair with `awsRegion` and `awsCredentials` / `awsCredentialsFile`. ### Behavior * Polls `inputDirectory` for the next expected `N.ckt`, applies it to the target, and moves it to `doneDirectory`. * Relational targets apply via MERGE/upsert plus delete; cloud targets (Firebolt, Snowflake, Databricks, BigQuery) stage rows to their bucket and bulk-load. * Exits cleanly when it has applied through the last file and seen `CHANGE.DONE` (log line `CHANGE.DONE - exiting`). ## Change Record Format Each `N.ckt` file is UTF-8 text, tab-delimited, one change record per line. The format is byte-identical to the [CDC](/run/replication) change extractor's, so the change-loader applies it unchanged. ``` I

… # INSERT: all columns, in schema order U
… # UPDATE: PK, then (column-offset, value) pairs for changed columns only D
# DELETE: primary-key columns only ``` * **`I` (insert)** — a row present in the source but missing from the target; all column values in schema order. * **`U` (update)** — a row whose PK matches but whose columns differ; the PK followed by sparse `(offset, value)` pairs, where `offset` is the 0-based column position. Only changed columns appear. * **`D` (delete)** — a row present in the target but absent from the source; primary-key columns only. Values are encoded on the wire as: **base64** for strings and binary/blob, **ISO-8601** for timestamps, and the literal `\N` for `NULL`. Each record ends with a trailing tab then newline (`\t\n`). ## End-to-End Example A complete `sqlserver → mysql` run, chaining schema migration → emit → apply. It assumes the Wirekite binaries are built and the two DSN files exist. ```bash theme={null} # ---- Setup ---- WK=/home/wirekite # Wirekite home (built binaries live here) WORK=/var/wirekite/sync_run_42 EMIT=$WORK/emit DONE=$WORK/done mkdir -p "$WORK" "$EMIT" "$DONE" SRC_DSN=/etc/wirekite/dsn/source_sqlserver.dsn TGT_DSN=/etc/wirekite/dsn/target_mysql.dsn # Tables to sync — SOURCE-side schema.table, one per line cat > "$WORK/tables.txt" < "$WORK/schema.cfg" < wirekite_schema.skt, and generate the DDL files. "$WK/orchestrator/wirekite" "$WORK/schema.cfg" # 1b. Apply the generated DDL to the target: drop, create, constraints, foreign keys. # (drop and FK steps are best-effort; -ignore-errors lets them pass.) "$WK/wiretalk/wiretalk" -d mysql -c "$TGT_DSN" -ignore-errors < "$WORK/d.sql" "$WK/wiretalk/wiretalk" -d mysql -c "$TGT_DSN" < "$WORK/c.sql" "$WK/wiretalk/wiretalk" -d mysql -c "$TGT_DSN" < "$WORK/i.sql" "$WK/wiretalk/wiretalk" -d mysql -c "$TGT_DSN" -ignore-errors < "$WORK/f.sql" # The target tables (and their _wkm merge shadow tables) now exist. # ============================================================ # PHASE 2 + 3 — Emit + Apply (run concurrently; reuse the SAME .skt + schemaRename) # ============================================================ cat > "$WORK/emit.cfg" < "$WORK/apply.cfg" < **Cloud targets** (Firebolt, Snowflake, Databricks, BigQuery, Spanner) need the extra staging/credential keys in `apply.cfg`, and `gcpCredfile` for the schema phase. See the [Stage 2](#stage-2--apply-change-loader) configuration. ## Resume & Crash Recovery Target Sync is restartable at every stage. * **Emit resume.** Set `checkpointDir` (typically the emit dir) and `resume=true`. The emitter records each completed window; a restarted run skips already-emitted windows and preserves published `*.ckt` files. * **Emit-once across crashes.** Within a window, the emitter writes a per-file high-water sidecar (`N.ckt.hw`, fsync'd before `N.ckt` is published) recording how far that window's PK-ordered emit reached. On resume it continues *past* the high-water, so every difference lands in **exactly one** committed `.ckt` — even if the host crashed mid-emit, and with no reliance on loader idempotency (required for non-MERGE loaders such as Spanner). * **Apply recovery.** The change-loader checkpoints applied files; on restart it resumes at the next un-applied `N.ckt`. Files already moved to `doneDirectory` are not re-applied. * **Gapless invariant.** A fresh emit run clears stale `*.ckt` / `CHANGE.DONE` first, so the loader never sees a leftover higher-numbered file or a premature `CHANGE.DONE`. Do not hand-place files in the emit directory. The loader applies `N.ckt` files in strict ascending order and treats `CHANGE.DONE` as the completion signal; a stray file breaks the gapless invariant. ## Performance & Tuning * **`windowSize`** — larger windows reduce per-window overhead but raise memory per concurrent comparison. * **`maxThreads`** — raises concurrency across table-windows; bound it by source and target connection limits. * **`emitFileTargetMB`** — larger `N.ckt` files reduce the loader's per-file COPY/upload overhead (most impactful for cloud targets). * **SQL Server source** — the validator reads SQL Server with a 32 KB TDS packet size, so wide tables transfer several times faster than the 4 KB default. This is automatic. * **Wide-table syncs** are dominated by raw data transfer; expect throughput in the tens of MB/s per stream over typical intra-cloud networking. * **Cassandra source** — keep `cassandraPKHashValidation=true` so the footprint stays bounded, and tune `cassandraPKHashMemRows` to trade RAM for spill I/O. The diff/emit cost is bounded by the **drift** (the rows that differ), not the table size; at large base size the source ring's read throughput is the ceiling. ## Limitations & Correctness Rules * **One-directional.** Reconciles the target to the source's state. To sync the other way, swap source and target in a separate run. * **Primary key required** on every table. * **Target schema must pre-exist.** Target Sync moves data, not DDL — run [schema migration](#schema-migration) first. * **Case-sensitivity must align.** Source and target must agree on PK case sensitivity. A case-insensitive source → case-sensitive target is fine; a case-sensitive source → case-insensitive target can lose case-distinct keys (the target folds them) and is unsupported. For mixed collations, ensure PK data is single-case or that the target PK columns use a binary collation. * **Type coverage is source-driven.** Only the supported source types can encode full-row INSERT/UPDATE values. ## Related Configure Apache Cassandra as a Target-Sync source. How CQL types map onto each relational and warehouse target. The diff engine behind the emit stage, also usable for standalone validation. Continuous change capture — the streaming alternative to a one-shot sync. # Troubleshooting Source: https://docs.wirekite.io/run/troubleshooting Diagnose and resolve common Wirekite migration issues. ## Exit Codes | Code | Meaning | Action | | ---- | ------------------------------------------------------------------------------------------------- | ----------------------------------------- | | 0 | Success | None | | 1 | Operational error (connection failure, config error, I/O error, license validation failure, etc.) | Check logs for the specific error message | | 2 | Usage cap exceeded | Check usage limits or upgrade license | ## Log Files Each component writes to a log file specified by the `logFile` parameter in the orchestrator configuration. For migrations created through the [Web Interface](/run/execution/ux), logs are stored under the migration directory. **Per-migration log structure:** ``` /opt/wirekite/instance// ├── schema/logs/ ├── data/logs/ ├── change/logs/ └── validate/logs/ ``` **UX Server logs:** ``` /opt/wirekite/ux/logs/ux-server.log /opt/wirekite/ux/logs/ux-server-error.log ``` **Usage tracking:** ``` /opt/wirekite/instance/usage.log ``` You can download all logs for a migration as a ZIP file through the Web Interface by opening the migration and clicking **Download Logs**. ## License Issues ### License Check Failed (Exit Code 1) The orchestrator validates the license at startup. If validation fails, it prints an error and exits with code 1. Note that exit code 1 is also used for other operational errors (connection failures, configuration errors, file I/O errors, etc.) -- check the log message for the specific cause. | Error Message | Cause | Fix | | -------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------ | | `failed to read license file` | License file missing or unreadable | Verify files exist at `/opt/wirekite/license/` with mode 600 | | `license file has been tampered with` | HMAC signature mismatch | Reinstall license with `install-license.sh` | | `License has expired` | Current date is past the expiry date | Contact your license provider for renewal | | `License issued date is in the future` | System clock is set incorrectly | Fix system clock with `timedatectl` or NTP | | `Host ID mismatch` | License is bound to a different machine's MAC address | Contact provider for a license matching this host | **Diagnose with:** ```bash theme={null} /opt/wirekite/license/license -cmd validate \ -input /opt/wirekite/license/wirekite.license \ -keyfile /opt/wirekite/license/wirekite.key ``` ### Usage Cap Exceeded (Exit Code 2) Some licenses limit total bytes processed. When a cap is reached, the loader exits with code 2. | Error Message | Cause | | -------------------------------- | ----------------------------------- | | `data migration limit exceeded` | Data load byte cap reached | | `CDC replication limit exceeded` | Change replication byte cap reached | Check current usage through the Web Interface or contact your license provider to increase the cap. ## Connection Issues ### DSN File Errors | Error Message | Cause | Fix | | --------------------------------------------- | ---------------------------------------- | ------------------------------------- | | `failed to open DSN file` | File path is wrong or file doesn't exist | Verify the path in your config | | `DSN file is empty or contains only comments` | DSN file has no connection string | Add the connection string to the file | ### Database Connection Failures | Error Message | Cause | Fix | | -------------------------------------- | ---------------------------- | -------------------------------------------- | | `failed to open MySQL connection` | Cannot connect to MySQL | Check host, port, credentials | | `failed to open PostgreSQL connection` | Cannot connect to PostgreSQL | Check host, port, credentials | | `failed to connect to Spanner` | Spanner connection failed | Verify project ID, instance, and credentials | | `failed to execute test query` | Connected but query failed | Check user permissions | **Diagnosis steps:** 1. Test connectivity from the Wirekite host: ```bash theme={null} nc -zv ``` 2. Test DNS resolution: ```bash theme={null} nslookup ``` 3. Use the Web Interface **Test Connection** button to validate credentials 4. Run a test query with [Wiretalk](/run/commandline): ```bash theme={null} wiretalk -dsn /path/to/dsn -sql "SELECT 1" ``` ## Data Migration Issues ### Migration Stops Mid-Process **Symptoms:** No new data arriving at target, logs show no recent activity. **Diagnosis:** ```sql theme={null} -- Check for incomplete operations on target SELECT source, operation, mark, start_time, restarts FROM wirekite.wirekite_progress WHERE finish_time IS NULL ORDER BY start_time DESC; ``` ```bash theme={null} -- Check if the process is still running ps aux | grep -E "extractor|loader|orchestrator" -- Check disk space df -h ``` **Recovery:** Restart the migration. Wirekite automatically resumes from the last saved position using the [wirekite\_progress](/run/operations) table. ### Duplicate Key Errors During Load **Cause:** Table already has data from a previous partial load, and the loader is re-inserting rows. **Recovery:** 1. Check if the file was already loaded: ```sql theme={null} SELECT * FROM wirekite.wirekite_progress WHERE source = 'schema.table.0.dkt'; ``` 2. If the record shows `finish_time IS NOT NULL`, the file completed successfully and should be skipped automatically. If the recovery table is missing the record, truncate the target table and reset: ```sql theme={null} TRUNCATE TABLE target_schema.table_name; DELETE FROM wirekite.wirekite_progress WHERE target LIKE '%table_name%' AND operation = 'D'; ``` ### Schema Mismatch **Symptoms:** Data load fails with type mismatch or column not found errors. **Cause:** Source schema changed after schema extraction, or type mappings are incompatible. **Recovery:** 1. Re-run schema extraction to capture the latest source schema 2. Verify type mappings in the generated SQL 3. Regenerate and re-apply the create table SQL on the target ### Out of Disk Space **Symptoms:** File operations fail with `no space left on device`. **Recovery:** 1. Free disk space (check `/tmp`, log directories, old data files) 2. Enable `removeFiles=true` in the mover and loader to clean up processed files 3. Restart the migration - it resumes from the recovery checkpoint ## CDC/Replication Issues ### MySQL / MariaDB / SingleStore | Error | Cause | Fix | | ------------------------------- | ------------------------------------------- | -------------------------------------------------------------------- | | `failed to get binlog position` | Binary logging not enabled or binlog purged | Enable with `SET GLOBAL binlog_format='ROW'` and ensure `log_bin=ON` | | `failed to start replication` | Replication user lacks permissions | Grant `SELECT, REPLICATION SLAVE, REPLICATION CLIENT` | | `failed to flush binary logs` | Insufficient privileges | Grant `RELOAD` privilege | **Check binlog status:** ```sql theme={null} SHOW VARIABLES LIKE 'log_bin'; SHOW MASTER STATUS; ``` ### PostgreSQL / YugaByte / TigerData / AlloyDB | Error | Cause | Fix | | ----------------------------------- | --------------------------------------------------- | ----------------------------------------------------- | | `failed to create replication slot` | `max_replication_slots` reached or slot name in use | Increase `max_replication_slots` or drop unused slots | | `failed to drop replication slot` | Slot has an active consumer | Terminate the consuming connection first | | `Replication slot does not exist` | Slot was dropped or never created | Recreate the replication slot | **Check replication status:** ```sql theme={null} -- List all slots SELECT slot_name, active, restart_lsn FROM pg_replication_slots; -- Check WAL level SHOW wal_level; -- Must be 'logical' -- Check replication lag SELECT slot_name, pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) AS lag_bytes FROM pg_replication_slots; ``` **Drop a stuck slot:** ```sql theme={null} SELECT pg_drop_replication_slot('wirekite_replication_slot'); ``` ### Oracle | Error | Cause | Fix | | ------------------ | -------------------------------- | ------------------------------------------ | | LogMiner errors | Supplemental logging not enabled | `ALTER DATABASE ADD SUPPLEMENTAL LOG DATA` | | Archive log errors | Database not in ARCHIVELOG mode | Switch to ARCHIVELOG mode | ### SQL Server | Error | Cause | Fix | | ------------------------- | ------------------------------------- | ----------------------------------------- | | CDC not capturing changes | CDC not enabled on database or tables | Enable CDC on the database and each table | | Transaction log full | Log space exhausted | Increase log file size or run log backup | **Enable CDC:** ```sql theme={null} -- Enable on database EXEC sys.sp_cdc_enable_db; -- Enable on table EXEC sys.sp_cdc_enable_table @source_schema = 'dbo', @source_name = 'your_table', @role_name = NULL; ``` ## Cloud Staging Issues ### S3/GCS Upload Failures | Error | Cause | Fix | | ----------------------- | -------------------------------------- | -------------------------------------- | | `Upload error` | Credentials invalid or expired | Refresh AWS/GCS credentials | | `InitGCSBucketInfo err` | Bucket doesn't exist or not accessible | Verify bucket name and IAM permissions | **Diagnosis:** * AWS: Verify credentials with `aws sts get-caller-identity` * GCS: Verify credentials with `gcloud auth list` * Check bucket access and write permissions * Verify the bucket region matches your configuration ### Snowflake Stage Errors **Symptoms:** PUT or COPY commands fail. **Check:** 1. Verify warehouse is running and has available compute 2. Check that the connection string specifies a valid warehouse 3. Verify the user has USAGE on the warehouse and stage ## Recovery Table Issues ### `wirekite_action must have 1 row in it` **Cause:** The `wirekite_action` table was accidentally emptied or has extra rows. **Fix:** ```sql theme={null} -- Check current state SELECT * FROM wirekite.wirekite_action; -- Reset to exactly one row DELETE FROM wirekite.wirekite_action; INSERT INTO wirekite.wirekite_action VALUES ('RUN'); ``` ### High Restart Counts If the `restarts` column in `wirekite_progress` shows high values for a file, the same operation is crashing repeatedly. **Diagnosis:** ```sql theme={null} SELECT source, operation, restarts, start_time FROM wirekite.wirekite_progress WHERE restarts > 3 ORDER BY restarts DESC; ``` Investigate the component logs for the specific file to find the root cause before restarting again. ## UX Server Issues ### Cannot Connect to UX Server 1. Verify the service is running: `sudo systemctl status wirekite-ux` 2. Check logs: `tail -f /opt/wirekite/ux/logs/ux-server.log` 3. Ensure port 8443 is open: `sudo lsof -i :8443` 4. Verify SSL certificates exist at `/opt/wirekite/ux/server/certs/` ### Authentication Issues 1. Clear browser cookies and retry 2. Check `users.json` in the config directory 3. Restart the UX server to clear all sessions: `sudo systemctl restart wirekite-ux` ## Diagnostic Tools ### Wiretalk Run ad-hoc queries against any configured source or target to diagnose connectivity and data issues. See [Wiretalk](/run/commandline). ### TableValidator Validate data integrity between source and target after migration. See [TableValidator](/run/validation). ### Web Interface Diagnostics The [Web Interface](/run/execution/ux) provides: * **Test Connection** - Validate database credentials * **Download Logs** - ZIP archive of all migration logs * **Real-time Progress** - Monitor extraction and loading rates * **Validation** - Run data validation with configurable sample size ## Pre-Migration Checklist Before starting a migration, verify: Test connections to both source and target databases. Validate your license is current and has sufficient usage cap. Ensure adequate space on the Wirekite host for data files. If using CDC, enable the required replication features on the source (binlog for MySQL, logical WAL for PostgreSQL, supplemental logging for Oracle, CDC for SQL Server). Verify database users have the required privileges for extraction and loading. Extract and review the schema before starting data migration. # Data Validation Source: https://docs.wirekite.io/run/validation Validate migration accuracy by comparing source and target data row-by-row. ## Overview The TableValidator tool compares data between source and target databases after a migration to verify accuracy. It performs row-by-row comparison using primary key ordering and reports missing rows, extra rows, and value differences. TableValidator handles database-specific differences automatically, including timestamp normalization, float precision tolerance, trailing space trimming, and NULL/empty string semantics. ## Usage TableValidator takes a configuration file as its only argument: ```bash theme={null} /opt/wirekite/tablevalidator/tablevalidator /path/to/validation.cfg ``` The configuration file uses the same `key=value` format as the orchestrator. ## Required Parameters Source database type. Supported values: `mysql`, `mariadb`, `postgres`, `oracle`, `sqlserver`, `singlestore`. (`mariadb` is accepted as an alias and handled identically to `mysql`.) Path to a file containing the source database connection string. Target database type. Supported values: `mysql`, `mariadb`, `postgres`, `oracle`, `sqlserver`, `snowflake`, `firebolt`, `bigquery`, `databricks`, `spanner`, `singlestore`, `mongodb`. (`mariadb` is accepted as an alias and handled identically to `mysql`.) Path to a file containing the target database connection string. Path to the Wirekite schema file (`.skt`) generated by the Schema Extractor. Used to determine table structures, column types, and primary keys. Path to a file listing the tables to validate, one per line in `schema.table` format. ## Optional Parameters Path to the log output file. If not specified, output is written to stdout. Schema mapping for source-to-target name differences. Format: `sourceSchema:targetSchema`. Use commas for multiple mappings: `schema1:mapped1,schema2:mapped2`. Number of parallel validation threads. Defaults to 2x the number of CPU cores. Path to a GCP service account JSON credentials file. Required when validating against Spanner or BigQuery targets. Number of rows per pagination window. The validator uses keyset pagination to compare large tables in chunks of this size. When `true`, stops validation immediately when any table has differences. When `false`, continues validating all tables and reports all differences at the end. When `true`, treats empty strings and NULL values as equivalent. Useful when migrating from Oracle (which treats empty strings as NULL) to other databases. ### Partial Validation For large databases, you can validate a random sample instead of all rows: Percentage of rows to validate (1-100). When set to 0 (default), all rows are validated. Maximum number of rows to validate. When set to 0 (default), all rows are validated. If both `samplePercent` and `sampleRows` are set, the smaller sample is used. When `true`, randomly selects which windows to validate during partial validation. When `false`, validates windows sequentially from the beginning. ## Example Configuration ```shellscript theme={null} # Validation configuration # Source sourceType=postgres sourceDsnFile=/opt/wirekite/config/postgres-source.dsn # Target targetType=snowflake targetDsnFile=/opt/wirekite/config/snowflake-target.dsn # Schema and tables schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt tablesFile=/opt/wirekite/config/tables.txt # Options logFile=/var/log/wirekite/validation.log maxThreads=8 stopOnError=false emptyEqualsNull=false ``` ### Partial Validation Example ```shellscript theme={null} # Validate 25% of rows randomly sourceType=oracle sourceDsnFile=/opt/wirekite/config/oracle-source.dsn targetType=bigquery targetDsnFile=/opt/wirekite/config/bigquery-target.dsn schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt tablesFile=/opt/wirekite/config/tables.txt logFile=/var/log/wirekite/validation.log samplePercent=25 randomizeWindows=true ``` ## Output TableValidator reports results per table and provides a summary at the end. ### Per-Table Results For each table, the validator reports: * Source and target row counts * Number of rows missing in target * Number of extra rows in target * Number of rows with value differences * Sample rows for each category (up to 10 examples) ### Summary Report The summary shows totals across all tables: * Total tables validated (passed, failed, errors) * Total rows compared * Total matches, missing, extra, and differences ### Exit Codes | Code | Meaning | | ---- | --------------------------------------------- | | 0 | All tables passed validation | | 1 | One or more tables have differences or errors | ## Comparison Behavior TableValidator automatically handles common cross-database differences: | Category | Handling | | ------------- | ------------------------------------------------ | | Timestamps | Normalized to UTC for comparison | | Floats | Compared with relative tolerance (1e-5) | | Decimals | Arbitrary precision comparison for large numbers | | CHAR padding | Trailing spaces trimmed | | NULL vs empty | Configurable via `emptyEqualsNull` | | JSON | Semantic equality (ignores formatting) | | UUID | Case-insensitive comparison | | Money | Currency symbol and separator normalization | You can also run validation through the [Web Interface](/run/execution/ux) under the Validate tab of a migration. # AWS Data Mover Source: https://docs.wirekite.io/sourceguides/awsmover Transfers extracted data files to AWS S3 buckets for cloud-based targets. The AWS Data Mover transfers files extracted by Wirekite Extractors to AWS S3 buckets. It is used when your target database loads data from S3, such as Firebolt or other AWS-integrated targets. The mover watches a local directory for extracted data files, uploads them to the specified S3 bucket, and optionally compresses and removes local files after successful upload. ## When to Use Use the AWS Data Mover when: * Your target database loads data from AWS S3 * You're using Firebolt as a target * Your extracted data needs to be staged in S3 before loading ## Features * **Multi-threaded uploads** - Parallel uploads for better throughput * **Optional gzip compression** - Compress files before upload to reduce transfer time and storage costs * **Crash recovery** - Skips files that already exist in S3, allowing safe restarts * **Automatic cleanup** - Removes local files after successful upload * **Coordinated completion** - Waits for `DATA.DONE` signal before finalizing ## Configuration The AWS Data Mover uses a configuration file passed as a command-line argument: ```bash theme={null} aws_data_mover ``` ### Configuration Parameters The AWS region where your S3 bucket is located (e.g., `us-east-1`, `eu-west-1`). The name of the S3 bucket where files will be uploaded. The full path on the local machine where the Wirekite Data Extractor writes its files. The path to a file where the AWS Data Mover will write its logging output. Path to a file containing AWS credentials in the format `access_key:secret_key`. If not provided, the mover uses the default AWS credential chain (environment variables, IAM role, etc.). Maximum number of parallel threads for uploading files. Default is `10`. Whether to gzip files before uploading. Compressed files use the `.dgz` extension. Default is `false`. Whether to remove local files after successful upload. Default is `true`. ### Example Configuration ``` awsRegion = us-east-1 awsBucket = my-wirekite-staging dataDirectory = /data/wirekite/extract logFile = /var/log/wirekite/aws_mover.log awsCredentials = /etc/wirekite/aws_creds.txt maxThreads = 20 gzipFiles = true removeFiles = true ``` ### AWS Credentials File Format If using the `awsCredentials` option, the file should contain: ``` ACCESS_KEY_ID:SECRET_ACCESS_KEY ``` ## Orchestrator Integration When using the AWS Data Mover with the Wirekite Orchestrator, add the mover configuration to your orchestrator config: ``` moverType = aws moverConfig = /path/to/aws_mover.cfg ``` ## How It Works 1. The mover monitors `dataDirectory` for files with the specified extension 2. For each file found: * Checks if the file already exists in S3 (crash recovery) * Optionally compresses the file with gzip * Uploads to the S3 bucket * Removes the local file (if configured) 3. When `DATA.DONE` appears in the directory, uploads it and exits gracefully ## Notes * Ensure the AWS credentials have `s3:PutObject` and `s3:GetObject` permissions on the target bucket * The mover creates files with their original names in the bucket root * For large migrations, increase `maxThreads` to improve throughput * Enable `gzipFiles` to reduce network transfer time and S3 storage costs # Cassandra Source: https://docs.wirekite.io/sourceguides/cassandra This guide explains how to configure Apache Cassandra as a source database for Wirekite Target Sync. ## Overview Wirekite supports Apache Cassandra as a source database for: * **Schema Extraction** — Read a keyspace's table definitions into Wirekite's intermediate `.skt` format. * **Data Extraction** — Bulk extract table data for an initial load into the target. * **Target Sync** — Diff the Cassandra source against the target and emit the change records that reconcile them. Cassandra is supported **one-directionally, as a source, for [Target Sync](/run/targetsync) only.** There is **no CDC / streaming replication** path for Cassandra. Commit-log CDC is per-node, needs replica deduplication and back-pressure handling; Target Sync sidesteps all of it by walking the source and target in primary-key order and emitting only the differences. Cassandra is mostly relational-shaped, which is what makes this work: CQL tables have a fixed, declared schema; the primary key (partition key + clustering columns) becomes a relational composite primary key; and scalar columns map one-to-one. The only impedance is complex column types (collections, UDTs, tuples), which are carried as JSON. See the [Cassandra Datatype Matrix](/datatypes/cassandra) for the full mapping. ## How Cassandra Fits Target Sync A Cassandra source run follows the standard Target Sync pipeline: The schema extractor reads `system_schema` and writes `wirekite_schema.skt`. The target's schema loader turns the `.skt` into target DDL, which is applied to create the target tables (with `createMergeTables=true`). The data extractor writes a primary-key-ordered `.dkt` snapshot; the target's data loader bulk-loads it. The [TableValidator](/run/validation) diffs source against target; any drift is emitted as change records and applied, then re-validated. For the end-to-end mechanics (emit + apply stages, config files, resume), see the [Target Sync guide](/run/targetsync). This page covers the Cassandra-specific source configuration. ## Prerequisites ### Connectivity * **Driver:** Wirekite connects with the `gocql` driver over the native CQL protocol (default port `9042`). * **Contact points:** One or more reachable ring nodes. Wirekite discovers the rest of the ring from the contact points unless host lookup is disabled (see [Connection String](#connection-string)). * **Consistency:** Reads default to `LOCAL_QUORUM`. Target Sync assumes a **static source during a run** — it does not take a point-in-time snapshot; a later run re-converges any changes made during the previous one. ### Permissions The connecting role needs: * **`SELECT` on the keyspace tables** being extracted — the data extractor runs full token-range scans over them. * **Read access to `system_schema`** — the schema extractor reads `system_schema.columns` (and `system_schema.types` for UDTs). Authenticated roles can read the system keyspaces by default. ```sql theme={null} -- Grant read access to the keyspace being extracted GRANT SELECT ON KEYSPACE app_keyspace TO wirekite; ``` Wirekite **only reads** from Cassandra — it creates no tables, triggers, or tracking state on the source. Extraction progress is tracked in local files on the Wirekite host, not in the cluster. ## Connection String The Cassandra DSN is a single line in the `dsnFile`: ``` cassandra://[user:pass@]host1[,host2,...][:port]/[keyspace][?option=value&...] ``` **Examples:** ``` # Single node, default port (9042) and consistency (LOCAL_QUORUM) cassandra://10.0.0.5/app_keyspace # Authenticated, multi-node contact points, explicit port cassandra://wirekite:secret@10.0.0.5,10.0.0.6,10.0.0.7:9042/app_keyspace # Reach a docker-bridged ring from another host cassandra://10.0.0.5/app_keyspace?disable_host_lookup=true&consistency=LOCAL_QUORUM ``` | Component | Default | Notes | | ----------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `user:pass@` | none | Optional. Enables password authentication. | | `host1,host2,…` | — | One or more contact points, comma-separated. | | `:port` | `9042` | A trailing numeric port applies to all hosts. | | `/keyspace` | none | Optional. The schema extractor reads `system_schema` regardless of the session keyspace. | | `?consistency=` | `LOCAL_QUORUM` | One of `ANY`, `ONE`, `TWO`, `THREE`, `QUORUM`, `ALL`, `LOCAL_QUORUM`, `EACH_QUORUM`, `LOCAL_ONE`. | | `?disable_host_lookup=` | `false` | When `true`, use only the listed contact point(s) and skip `system.peers` discovery. Needed when the ring's advertised IPs aren't routable from the Wirekite host (e.g. a docker-bridged cluster). | ## Schema Extractor The Schema Extractor reads table definitions from Cassandra's `system_schema` and outputs them to Wirekite's intermediate schema format (`wirekite_schema.skt`). For each `keyspace.table` it maps each CQL column type to a Wirekite type, derives the primary key from the partition and clustering columns, and synthesizes sensible bounds for the precisionless CQL types (see the [Datatype Matrix](/datatypes/cassandra)). ### Required Parameters Path to a file containing the Cassandra connection string (one line). See [Connection String](#connection-string). Path to a file listing the tables to extract, one per line in `keyspace.table` format. Blank lines and lines starting with `#` are ignored. **Example tablesFile contents:** ``` app_keyspace.users app_keyspace.orders analytics.events ``` Absolute path to the directory where Wirekite writes `wirekite_schema.skt`. The directory must exist and be writable. Absolute path to the schema extractor's log file. ### Optional Parameters Map a source keyspace to a different target schema name. Format: `srcKeyspace:tgtSchema[,src2:tgt2,...]`. For example, `app_keyspace:app_schema` writes `app_schema` as the schema name in the output. Must match the `schemaRename` used in the data extractor and the emit stage. A CQL primary key (`partition_key…`, `clustering…`) is emitted as the target's composite primary key in declaration order. Primary-key columns are non-nullable; all other columns are nullable. Static columns are emitted as ordinary (denormalized) columns. ## Data Extractor The Data Extractor performs the initial bulk extraction, writing a per-table snapshot to Wirekite's intermediate data format (`.dkt` files) that the target's data loader applies. For parallelism it uses the standard Cassandra full-scan pattern: it splits the Murmur3 token ring into ranges and scans each concurrently across worker threads, spread over the ring's nodes. Each `(table, range)` writes its own `schema.table.N.dkt` file. ### Required Parameters Path to a file containing the Cassandra connection string. Path to a file listing the tables to extract, one per line in `keyspace.table` format. Absolute path to the directory where Wirekite writes data files (`schema.table.N.dkt`). Absolute path to the data extractor's log file. ### Optional Parameters Number of parallel scan workers. Token ranges are distributed across these workers, so raising it increases concurrency across the ring. Bound it by the cluster's capacity. Number of token-ring slices per table (the parallelism granularity). Defaults to `maxThreads × 8`, which provides enough jobs to keep every worker busy and even out token skew. Set it explicitly to tune for very large or very skewed tables. When `true`, binary and string data is encoded as hexadecimal instead of base64. Larger files, but may be required for certain target loaders. Map a source keyspace to a different output schema name. Format: `srcKeyspace:tgtSchema[,...]`. Must match the value used elsewhere in the run. Extraction is crash-recoverable: each `.dkt` file is tracked locally, so a re-run skips ranges that already finished and resumes where it left off. A `DATA.DONE` marker is written only once every range completes. ## Validation & Emit The diff/emit stage is the [TableValidator](/run/validation) reading a Cassandra source. Because Cassandra cannot stream rows in primary-key order — it orders by `token()`, a hash — the validator uses a **bounded-footprint `(pk, hash)` projection**: it projects each source row to a primary key plus a row hash, sorts and merges those against the target's same projection, and re-fetches the full rows only for the mismatches. This keeps memory bounded (≈30M rows validate in \~3 GB) instead of materializing whole tables. Set these keys on the emit/validate config (see [Target Sync § Stage 1](/run/targetsync#stage-1--emit-tablevalidator)): When `true`, uses the bounded `(pk, hash)` diff. Recommended. Applies to **single-PK tables**; tables with a composite primary key automatically fall back to a whole-table sort-merge. In-memory ceiling for the `(pk, hash)` projection before it spills to a k-way merge on disk. Trade RAM for spill I/O. In-memory ceiling for the whole-row sort (the composite-PK fallback path). ## Resilience A full token-range scan over a large ring takes minutes, and a stressed ring can stall mid-scan. Wirekite wraps the Cassandra reads in a transient-retry and session-recreate layer: transient errors are retried with backoff, and a wedged connection pool (`no hosts available`) is healed by recreating the `gocql` session. Re-scanned boundary rows are deduplicated by primary key during the sort. This lets a long scan survive a degraded cluster — a 10M-row run has survived 16 pool-wedge recoveries and still passed validation. ## Limitations * **Source only, Target Sync only.** No CDC, and Cassandra is not supported as a target. * **Text is bounded to 4000 characters.** Cassandra `text` has no length; Wirekite synthesizes a bound so strict target loaders accept it. Lossy for genuinely large text — see the [Datatype Matrix](/datatypes/cassandra). * **Collections and UDTs become opaque JSON.** `list`, `set`, `map`, `tuple`, and user-defined types are serialized to a single JSON column — they are not exploded into child tables or normalized, and cannot be part of a primary key. * **Static columns are not modeled as static** — they are denormalized onto every row in the partition. * **`counter` columns** are read as their current point-in-time value. * **No point-in-time snapshot.** Target Sync assumes a static source during a run; changes made mid-run are reconciled by a later run. ## Related The one-shot reconciliation feature Cassandra sources flow through. Full CQL-to-target type mapping and the synthesized bounds. # Db2 Source: https://docs.wirekite.io/sourceguides/db2 This guide explains how to configure IBM Db2 (LUW) as a source database for Wirekite data extraction and replication. ## Overview Wirekite supports IBM Db2 for Linux, UNIX and Windows (LUW) 11.5 and above as a source database for: * **Schema Extraction** - Extract table definitions to Wirekite's intermediate format * **Data Extraction** - Bulk extract table data for initial load * **Change Extraction (CDC)** - Capture ongoing inserts, updates, and deletes by reading the Db2 recovery log Db2 Change Extraction reads the Db2 recovery (transaction) log directly through the `db2ReadLog` administrative API. This requires **archive logging** (not circular logging) and **`DATA CAPTURE CHANGES`** to be enabled on each tracked table. Db2 is supported as a **Data** (one-time load) and **Replicate** (CDC) source. It is not currently a [Target Sync](/run/targetsync) source. As a Wirekite **target**, Db2 additionally supports Target Sync — see the [Db2 target guide](/targetguides/db2target). ### How it works The Db2 source uses two extraction paths: | Path | Used for | Db2 access | Where it runs | | ------------------------- | -------------------------------- | --------------------------------------------------------------- | --------------------------------------------------------------- | | **Schema + initial load** | Schema Extractor, Data Extractor | `go_ibm_db` over the relocatable **clidriver** (plain `SELECT`) | Any host that can reach the Db2 port | | **Change capture (CDC)** | Change Extractor | `db2ReadLog` via the full **Data Server Client** | On a host with a Db2 instance (typically the Db2 server itself) | **CDC type coverage is narrower than the initial load.** The initial load extracts every mapped Db2 type; change capture decodes a narrower set from the log. Columns of type `DECFLOAT`, `GRAPHIC`, `VARGRAPHIC`, `LONG VARGRAPHIC`, `DBCLOB`, or `LONG VARCHAR` are **not decodable from the log** — a replicated table containing one of these columns loses that column and every column after it in the change stream. Avoid these types on replicated tables, or place them last in column order. They load correctly during the one-time Data load. See the [Db2 datatype matrix](/datatypes/db2). ## Prerequisites Before configuring Db2 as a Wirekite source, ensure the following requirements are met: ### Database Configuration 1. **Version**: Db2 (LUW) 11.5 or above. 2. **Archive logging** (CDC only): The database must use archive logging (`LOGARCHMETH1` set to a destination, not `OFF`/circular), which requires an initial full backup. Circular logging cannot drive `db2ReadLog` change capture. 3. **`DATA CAPTURE CHANGES`** (CDC only): Must be enabled on each tracked table so that full row images (not just keys) are written to the log. ### File System Access * Ensure the user running Wirekite has write permissions to the output directory. * Verify sufficient disk space for extracted data files. ### Replication Considerations When performing the initial data extraction, quiesce writes where possible. The Data Extractor holds a `LOCK TABLE ... IN SHARE MODE` on every extracted table for the duration of the snapshot to produce a consistent image and capture a precise log position for handoff to CDC. Out-of-line values (LOB/XML) and relocated rows are resolved by primary-key lookups that converge correctly against a drained/quiescent source. *** ## Source Database Setup ### Step 1: Create the Wirekite User Db2 authenticates against operating-system users. Create an OS user for Wirekite on the Db2 server and grant it database access: ```sql theme={null} -- Connect as an instance owner / DBADM GRANT CONNECT ON DATABASE TO USER wirekite; ``` ### Step 2: Grant Read Access to Application Tables For each application table that needs to be extracted: ```sql theme={null} GRANT SELECT ON .table1 TO USER wirekite; GRANT SELECT ON .table2 TO USER wirekite; -- repeat for each table to be extracted ``` Wirekite also reads column and constraint metadata from the `SYSCAT` catalog views (`SYSCAT.COLUMNS`, `SYSCAT.TABLES`, `SYSCAT.TABCONST`, `SYSCAT.KEYCOLUSE`, `SYSCAT.REFERENCES`, `SYSCAT.CHECKS`, `SYSCAT.INDEXES`, `SYSCAT.INDEXCOLUSE`), which are readable by any connected user by default. ### Step 3 (CDC Only): Enable Archive Logging Change capture reads the recovery log, which requires archive (not circular) logging. As the instance owner: ```bash theme={null} # Point the primary log archive at a destination db2 update db cfg for using LOGARCHMETH1 DISK:/db2/archive/ # Archive logging requires an initial full backup to activate db2 backup db to /db2/backup/ ``` ### Step 4 (CDC Only): Enable DATA CAPTURE CHANGES For each table to be tracked, enable full change capture to the log: ```sql theme={null} ALTER TABLE .table1 DATA CAPTURE CHANGES; ALTER TABLE .table2 DATA CAPTURE CHANGES; -- repeat for each table to be tracked ``` **Verify:** ```sql theme={null} SELECT TABSCHEMA, TABNAME, DATACAPTURE FROM SYSCAT.TABLES WHERE TABSCHEMA = ''; -- DATACAPTURE should be 'L' (changes captured to log) for tracked tables ``` Without `DATA CAPTURE CHANGES`, the log only records primary-key (keys-only) images for a table, and Wirekite cannot reconstruct full-row changes. Pre-existing customer tables are usually **not** armed for capture by default. ### Step 5 (CDC Only): Grant Log Read Authority The `db2ReadLog` API is privileged and requires DBADM (or SYSADM): ```sql theme={null} GRANT DBADM ON DATABASE TO USER wirekite; ``` ### Step 6 (CDC Only): Set the Db2 Instance The Change Extractor must run with the `DB2INSTANCE` environment variable set to the instance that owns the database (default `db2inst1`), because `db2ReadLog` operates in the instance context. This is provided by the `db2Instance` config key or the `DB2INSTANCE` environment variable. ### Privilege Summary | Privilege | Required For | | ---------------------------------- | ------------------------------------------------------- | | `CONNECT` | Basic connectivity | | `SELECT ON .
` | Reading application table data | | Catalog (`SYSCAT.*`) read | Schema metadata (granted to connected users by default) | | `DBADM` | CDC: `db2ReadLog` recovery-log access | | `DATA CAPTURE CHANGES` (per table) | CDC: full row images in the log | Wirekite does **not** create any tracking tables, triggers, or stored procedures on the Db2 source. Change capture uses the `db2ReadLog` log-read API exclusively, and progress is tracked in a local file outside Db2. *** ## Schema Extractor The Schema Extractor reads table definitions from Db2's `SYSCAT` catalog and outputs them to Wirekite's intermediate schema format (`.skt` file). This schema file is used by target loaders to create corresponding tables in the destination database. ### Required Parameters Path to a file containing the Db2 connection string (see [Connection String](#connection-string)). The file should contain exactly one line. Path to a file listing the tables to extract, one per line in `schema.table` format. Absolute path to the directory where Wirekite will write the schema file (`wirekite_schema.skt`). The directory must exist and be writable. Absolute path to the log file where the Schema Extractor will write operational logs. ### Optional Parameters Rename source schemas in the output. Format: `sourceSchema:targetSchema,source2:target2`. Useful when the target database uses a different schema name. The Schema Extractor emits columns, primary keys, unique constraints, foreign keys, check constraints, and regular secondary indexes. Column defaults are not translated (emitted as none). Db2 folds unquoted identifiers to uppercase in the catalog; Wirekite lowercases table and column names in the schema file. *** ## Data Extractor The Data Extractor performs bulk extraction of table data, writing records to Wirekite's intermediate data format (`.dkt` files). Large tables are automatically split across multiple files based on the `maxRowsPerDump` setting. ### Required Parameters Path to a file containing the Db2 connection string. Path to a file listing the tables to extract, one per line in `schema.table` format. Absolute path to the directory where Wirekite will write data files. Files are named `schema.table.N.dkt` where N is a sequence number. Absolute path to the log file for Data Extractor operations. ### Optional Parameters Number of parallel extraction threads. Each thread consumes one database connection. Tables are chunked by primary key: single-column integer keys use fast range predicates; other keys use ordered fetch windows; tables with no primary key are extracted as a single chunk. Maximum number of rows written to each output file. Large tables are split into multiple files. When `true`, binary and string data is encoded as hexadecimal instead of base64. Hex encoding produces larger files but may be required for certain target databases. When `true`, sorts output files by table name for easier management and verification. When `true`, the Data Extractor captures the current recovery-log position at the end of the snapshot (while table locks are still held) and writes it to `position.pkt`. Used to hand off to the Change Extractor without losing any commits. The Orchestrator sets this automatically in `data+change` mode. Pause extraction when free disk space on the output volume drops below this many megabytes (backpressure). Resume extraction once free disk space rises back above this many megabytes. Rename source schemas in the output. Format: `sourceSchema:targetSchema`. *** ## Change Extractor The Change Extractor captures ongoing data changes (INSERT, UPDATE, DELETE) by reading the Db2 recovery log via the `db2ReadLog` API. It groups log records by transaction and emits committed changes to Wirekite's change format (`.ckt` files). The Change Extractor requires the full Db2 Data Server Client and runs in the context of a Db2 instance (`DB2INSTANCE`). It is typically deployed on the Db2 server host. ### Required Parameters Path to a file containing the Db2 connection string. (Alternatively, provide the string via the `connectionString` key.) Path to a file listing the tables to track for changes, one per line in `schema.table` format. Absolute path to the directory where Wirekite will write change files (`N.ckt`). ### Position Parameters The Db2 recovery-log position (a compact LRI) from which to start extracting changes. This is typically the position captured at the end of the initial snapshot. When running via the Orchestrator in `data+change` mode, this is captured and passed automatically. In change-only mode (without an initial data extraction), you must specify the correct `position` to define where change capture should begin. Incorrect values may result in missing changes or duplicate data. ### Optional Parameters Path to the log file for Change Extractor operations. Number of change rows to write to each `.ckt` file before rotating to the next. Transactions never span multiple output files. Milliseconds to sleep when the reader has caught up to the end of the log before polling again. When `true`, the extractor exits cleanly once it has caught up and stayed idle. When `false` (default), it runs continuously. Number of idle seconds to wait before `exitWhenIdle` triggers an exit. When `true`, wipes existing change files and progress and restarts reading from the beginning of the available log. Used by the "restart replication" flow. The Db2 instance (`DB2INSTANCE`) that owns the database, required for `db2ReadLog`. Rename the source schema in the output. Format: `sourceSchema:targetSchema`. *** ## Connection String The Db2 extractors connect through the `go_ibm_db` driver (schema/data) and the Db2 client (CDC), both of which use a **keyword-style connection string** (not a URL). The `dsnFile` should contain exactly one line: ``` HOSTNAME=;PORT=;PROTOCOL=TCPIP;DATABASE=;UID=;PWD= ``` **Example DSN file contents:** ``` HOSTNAME=db2-source.example.com;PORT=50000;PROTOCOL=TCPIP;DATABASE=APP_DB;UID=wirekite;PWD=secretpass ``` The default Db2 port is **50000**. For the CDC helper tools, the connection string is passed on standard input so it never lands on disk. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix source parameters with `source.schema.`, `source.data.`, or `source.change.` depending on the operation mode. **Example orchestrator configuration for Db2 source:** ``` # Main configuration source=db2 target=snowflake # Schema extraction source.schema.dsnFile=/opt/wirekite/config/db2.dsn source.schema.tablesFile=/opt/wirekite/config/tables.txt source.schema.outputDirectory=/opt/wirekite/output/schema source.schema.logFile=/var/log/wirekite/schema-extractor.log # Data extraction source.data.dsnFile=/opt/wirekite/config/db2.dsn source.data.tablesFile=/opt/wirekite/config/tables.txt source.data.outputDirectory=/opt/wirekite/output/data source.data.logFile=/var/log/wirekite/data-extractor.log source.data.maxThreads=8 source.data.maxRowsPerDump=100000 # Change extraction (CDC) source.change.dsnFile=/opt/wirekite/config/db2.dsn source.change.tablesFile=/opt/wirekite/config/tables.txt source.change.outputDirectory=/opt/wirekite/output/changes source.change.logFile=/var/log/wirekite/change-extractor.log source.change.db2Instance=db2inst1 source.change.cktRowsPerFile=50000 ``` When running in `data+change` mode, the Orchestrator captures the recovery-log position after data extraction and passes it to the Change Extractor. You do not need to manually specify `position` in this mode. *** ## Limitations * **Target Sync** is not supported with a Db2 source (Data and Replicate only). * **CDC type coverage** is narrower than the initial load: `DECFLOAT`, `GRAPHIC`, `VARGRAPHIC`, `LONG VARGRAPHIC`, `DBCLOB`, and `LONG VARCHAR` columns are not decodable from the log and truncate the change row. They load fine during the one-time Data load. * **Primary keys**: tables without a primary key can be bulk-extracted, but have no reliable row identity for change capture. Use primary keys on replicated tables. * **LOB and XML** values are stored out-of-line and resolved by a primary-key lookup at commit time; they converge correctly against a quiescent source. LOB primary-key resolution supports integer and character key columns. * **`TIME`** has no sub-second precision in Db2. * **Column defaults** are not translated into the schema output. * Unknown/unmapped Db2 types fall back to a wide character type on the initial load (with a warning) and are not supported by CDC. For details on how each Db2 type is converted, see the [Db2 datatype matrix](/datatypes/db2). # GCS Data Mover Source: https://docs.wirekite.io/sourceguides/gcsmover Transfers extracted data files to Google Cloud Storage buckets for GCP-based targets. The GCS Data Mover transfers files extracted by Wirekite Extractors to Google Cloud Storage (GCS) buckets. It is used when your target database loads data from GCS, such as BigQuery, Spanner, or other GCP-integrated targets. The mover watches a local directory for extracted data files, uploads them to the specified GCS bucket, and optionally compresses and removes local files after successful upload. ## When to Use Use the GCS Data Mover when: * Your target database loads data from Google Cloud Storage * You're using BigQuery or Spanner as a target * Your extracted data needs to be staged in GCS before loading ## Features * **Multi-threaded uploads** - Parallel uploads for better throughput * **Optional gzip compression** - Compress files before upload to reduce transfer time and storage costs * **Crash recovery** - Skips files that already exist in GCS, allowing safe restarts * **Automatic cleanup** - Removes local files after successful upload * **Coordinated completion** - Waits for `DATA.DONE` signal before finalizing ## Configuration The GCS Data Mover uses a configuration file passed as a command-line argument: ```bash theme={null} gcs_data_mover ``` ### Configuration Parameters The name of the GCS bucket where files will be uploaded. The full path on the local machine where the Wirekite Data Extractor writes its files. The path to a file where the GCS Data Mover will write its logging output. Path to a GCP service account JSON credentials file. If not provided, the mover uses Application Default Credentials (ADC). Maximum number of parallel threads for uploading files. Default is `10`. Whether to gzip files before uploading. Compressed files use the `.dgz` extension. Default is `false`. Whether to remove local files after successful upload. Default is `true`. ### Example Configuration ``` gcsBucket = my-wirekite-staging dataDirectory = /data/wirekite/extract logFile = /var/log/wirekite/gcs_mover.log gcsCredentials = /etc/wirekite/gcs-service-account.json maxThreads = 20 gzipFiles = true removeFiles = true ``` ### GCS Credentials The GCS Data Mover supports two authentication methods: 1. **Service Account JSON** - Provide the path to a service account key file via `gcsCredentials` 2. **Application Default Credentials** - If no credentials file is specified, uses ADC (useful when running on GCP infrastructure) The service account needs the following permissions on the target bucket: * `storage.objects.create` * `storage.objects.get` ## Orchestrator Integration When using the GCS Data Mover with the Wirekite Orchestrator, add the mover configuration to your orchestrator config: ``` moverType = gcs moverConfig = /path/to/gcs_mover.cfg ``` ## How It Works 1. The mover monitors `dataDirectory` for files with the specified extension 2. For each file found: * Checks if the file already exists in GCS (crash recovery) * Optionally compresses the file with gzip * Uploads to the GCS bucket * Removes the local file (if configured) 3. When `DATA.DONE` appears in the directory, uploads it and exits gracefully ## Notes * Ensure proper IAM permissions are configured for the service account * The mover creates files with their original names in the bucket root * For large migrations, increase `maxThreads` to improve throughput * Enable `gzipFiles` to reduce network transfer time and GCS storage costs * When running on GCP VMs, consider using Application Default Credentials for simpler configuration # MySQL / MariaDB / SingleStore Source: https://docs.wirekite.io/sourceguides/mysql This guide explains how to configure MySQL, MariaDB, or SingleStore as a source database for Wirekite data extraction and replication. ## Overview Wirekite supports MySQL 5.x and above (including MariaDB and SingleStore) as a source database for: * **Schema Extraction** - Extract table definitions to Wirekite's intermediate format * **Data Extraction** - Bulk extract table data for initial load * **Change Extraction (CDC)** - Capture ongoing inserts, updates, and deletes via binlog All references to MySQL in this guide also apply to MariaDB and SingleStore setups. SingleStore uses the MySQL wire protocol, so the configuration and parameters are identical. For SingleStore-specific target details (DSN and version differences), see the [SingleStore Notes](/targetguides/mysqltarget#singlestore-notes) in the target guide. ## Prerequisites Before configuring MySQL as a Wirekite source, ensure the following requirements are met: ### Database Configuration 1. **Version**: MySQL 5.7 or later (MySQL 8.0+ recommended) 2. **Storage Engine**: Tables must use InnoDB 3. **Binary Logging** (CDC only): Must be enabled with ROW format in `my.cnf`: ```ini theme={null} [mysqld] log_bin = mysql-bin binlog_format = ROW binlog_row_image = FULL server_id = 1 ``` Restart MySQL after changing these settings. 4. **Group Concat Length**: The schema extractor uses `GROUP_CONCAT()` internally. Set this variable to avoid silently truncated results: ```sql theme={null} SET GLOBAL group_concat_max_len = 50000; ``` ### File System Access For server-side extraction (recommended for performance): * Configure `secure_file_priv` to allow MySQL to write to the output directory * Ensure the MySQL process has write permissions to the output directory For cloud-managed MySQL instances (RDS, Cloud SQL, etc.) or remote databases where server-side file access isn't available, use `databaseRemote=true` (the default) to extract data via the client connection. ### Replication Considerations When performing initial data extraction, stop replication on the source database to ensure the dump is consistent to a specific binlog position. It is highly recommended to run Wirekite against a replica rather than the production primary to avoid impacting production workloads. *** ## Source Database Setup Wirekite requires a dedicated user, a `wirekite` database for internal tracking tables, and specific privileges on the application database. Follow these steps to configure your MySQL source. ### Step 1: Create the Wirekite Database Wirekite uses a dedicated `wirekite` database for its internal tracking tables (`wirekite_progress` and `wirekite_action`). These tables track extraction progress and enable crash recovery. ```sql theme={null} CREATE DATABASE IF NOT EXISTS wirekite; ``` ### Step 2: Create the Wirekite User ```sql theme={null} CREATE USER 'wirekite'@'%' IDENTIFIED BY ''; ``` If wirekite will only connect from a specific host: ```sql theme={null} CREATE USER 'wirekite'@'' IDENTIFIED BY ''; ``` ### Step 3: Grant Privileges on the Wirekite Database Wirekite needs full control of its own internal database to create and manage tracking tables: ```sql theme={null} GRANT CREATE, DROP, INDEX, INSERT, SELECT, UPDATE ON wirekite.* TO 'wirekite'@'%'; ``` ### Step 4: Grant Read Access to Application Tables For each application database that contains tables you want to extract: ```sql theme={null} GRANT SELECT ON .* TO 'wirekite'@'%'; ``` To grant access to specific tables only: ```sql theme={null} GRANT SELECT ON .table1 TO 'wirekite'@'%'; GRANT SELECT ON .table2 TO 'wirekite'@'%'; -- repeat for each table ``` ### Step 5 (Optional): Server-Side File Export If you plan to use server-side file export (the "local" mode where the database writes files directly using `SELECT ... INTO OUTFILE`), the wirekite user needs the global `FILE` privilege: ```sql theme={null} GRANT FILE ON *.* TO 'wirekite'@'%'; ``` This is NOT needed if Wirekite and the database are on different machines (the default "remote" streaming mode with `databaseRemote=true`). ### Step 6 (CDC Only): Grant Replication Privileges For change data capture (CDC), Wirekite uses MySQL's native binary log replication protocol. The wirekite user needs replication privileges: ```sql theme={null} GRANT REPLICATION SLAVE ON *.* TO 'wirekite'@'%'; GRANT REPLICATION CLIENT ON *.* TO 'wirekite'@'%'; ``` `REPLICATION SLAVE` allows Wirekite to read the binary log stream. `REPLICATION CLIENT` allows Wirekite to run `SHOW BINARY LOGS` and `SHOW MASTER STATUS`. ### Step 7 (CDC + Replica Handover Only): Additional Privileges If you are extracting from a MySQL replica and need handover operations (stop/start replication on the replica): **MySQL 8.0+:** ```sql theme={null} GRANT RELOAD ON *.* TO 'wirekite'@'%'; GRANT REPLICATION_SLAVE_ADMIN ON *.* TO 'wirekite'@'%'; ``` **MySQL 5.7:** ```sql theme={null} GRANT RELOAD ON *.* TO 'wirekite'@'%'; GRANT SUPER ON *.* TO 'wirekite'@'%'; ``` `RELOAD` is needed for `FLUSH BINARY LOGS`. `REPLICATION_SLAVE_ADMIN` (or `SUPER` on 5.7) is needed for `STOP REPLICA` / `START REPLICA`. ### Step 8: Apply Privileges ```sql theme={null} FLUSH PRIVILEGES; ``` ### Complete Setup Script #### Data Extraction Only ```sql theme={null} -- Run as root or admin user -- 1. Create wirekite database CREATE DATABASE IF NOT EXISTS wirekite; -- 2. Create user CREATE USER 'wirekite'@'%' IDENTIFIED BY ''; -- 3. Grant wirekite database privileges GRANT CREATE, DROP, INDEX, INSERT, SELECT, UPDATE ON wirekite.* TO 'wirekite'@'%'; -- 4. Grant read access to application tables GRANT SELECT ON .* TO 'wirekite'@'%'; FLUSH PRIVILEGES; ``` #### Data Extraction + CDC (Change Data Capture) ```sql theme={null} -- Run as root or admin user -- 1. Create wirekite database CREATE DATABASE IF NOT EXISTS wirekite; -- 2. Create user CREATE USER 'wirekite'@'%' IDENTIFIED BY ''; -- 3. Grant wirekite database privileges GRANT CREATE, DROP, INDEX, INSERT, SELECT, UPDATE ON wirekite.* TO 'wirekite'@'%'; -- 4. Grant read access to application tables GRANT SELECT ON .* TO 'wirekite'@'%'; -- 5. Grant replication privileges for CDC GRANT REPLICATION SLAVE ON *.* TO 'wirekite'@'%'; GRANT REPLICATION CLIENT ON *.* TO 'wirekite'@'%'; FLUSH PRIVILEGES; -- 6. Verify binary logging SHOW VARIABLES LIKE 'log_bin'; -- must be ON SHOW VARIABLES LIKE 'binlog_format'; -- must be ROW SHOW VARIABLES LIKE 'binlog_row_image'; -- should be FULL ``` ### Verify the Setup Connect as the wirekite user and verify access: ```sql theme={null} -- Should succeed SELECT 1 FROM .table1 LIMIT 1; -- Should succeed SELECT * FROM information_schema.columns WHERE table_schema = '' AND table_name = 'table1' LIMIT 1; -- Should succeed (CDC only) SHOW BINARY LOGS; ``` ### What Wirekite Creates | Object | Type | Database | Purpose | | ------------------- | ----- | ---------- | ------------------------------------------ | | `wirekite_progress` | Table | `wirekite` | Tracks extraction progress, crash recovery | | `wirekite_action` | Table | `wirekite` | Run/pause/stop control | | `wkp_finish_time` | Index | `wirekite` | Index on wirekite\_progress | | `wkp_start_time` | Index | `wirekite` | Index on wirekite\_progress | Wirekite does NOT create any triggers, functions, or stored procedures on the source database. CDC is purely binary-log-based. ### Privilege Summary | Privilege | Scope | Required For | | --------------------------------------------- | ------------------ | ---------------------------------------- | | `CREATE, DROP, INDEX, INSERT, SELECT, UPDATE` | `wirekite.*` | Internal tracking tables | | `SELECT` | `.*` | Reading application table data | | `FILE` | `*.*` (global) | Optional: server-side file export only | | `REPLICATION SLAVE` | `*.*` (global) | CDC only: binlog replication | | `REPLICATION CLIENT` | `*.*` (global) | CDC only: binlog position queries | | `RELOAD` | `*.*` (global) | CDC + replica handover only | | `REPLICATION_SLAVE_ADMIN` | `*.*` (global) | CDC + replica handover only (MySQL 8.0+) | *** ## Schema Extractor The Schema Extractor reads table definitions from MySQL and outputs them to Wirekite's intermediate schema format (`.skt` file). This schema file is used by target loaders to create corresponding tables in the destination database. The Schema Extractor can run standalone or as part of the Orchestrator workflow. The configuration parameters are the same in both cases. ### Required Parameters Path to a file containing the MySQL connection string. The file should contain exactly one line with the DSN. **Connection string format:** ``` username:password@tcp(host:port)/database?multiStatements=true&loc=Local ``` **Example DSN file contents:** ``` wirekite:secretpass@tcp(mysql-replica.example.com:3306)/myapp?multiStatements=true&loc=Local ``` Path to a file listing the tables to extract, one per line in `schema.table` format. **Example tablesFile contents:** ``` myapp.users myapp.orders myapp.products inventory.items ``` Absolute path to the directory where Wirekite will write the schema file (`wirekite_schema.skt`). The directory must exist and be writable. Absolute path to the log file where the Schema Extractor will write operational logs. *** ## Data Extractor The Data Extractor performs bulk extraction of table data, writing records to Wirekite's intermediate data format (`.dkt` files). Large tables are automatically split across multiple files based on the `maxRowsPerDump` setting. ### Required Parameters Path to a file containing the MySQL connection string. **Connection string format:** ``` username:password@tcp(host:port)/database?multiStatements=true&loc=Local ``` Path to a file listing the tables to extract, one per line in `schema.table` format. Absolute path to the directory where Wirekite will write data files. Files are named `schema.table.N.dkt` where N is a sequence number. Absolute path to the log file for Data Extractor operations. ### Optional Parameters Number of parallel extraction threads. Each thread consumes one database connection and approximately one CPU core. Set this based on available CPU cores and acceptable database load. Maximum number of rows written to each output file. Large tables are split into multiple files. Adjust based on available memory and disk space. Smaller values create more files but use less memory. When `true`, the data extractor captures the current binlog position (file + offset) at the end of the load and writes it to `position.pkt`. Used to hand off to a subsequent change extractor without losing any commits. The orchestrator sets this automatically in `data+change` mode — only set it explicitly when invoking the data extractor outside the orchestrator. When `true`, binary and string data is encoded as hexadecimal instead of base64. Hex encoding produces larger files but may be required for certain target databases. Must match the setting used by the target loader. When `true`, uses client-side data extraction instead of MySQL's `SELECT INTO OUTFILE`. **Required for cloud-managed MySQL instances** (Amazon RDS, Google Cloud SQL, Azure Database for MySQL) where server-side file operations are not available. Set to `false` for local extraction using server-side file operations. For best performance on dedicated extraction hosts, set `maxThreads` equal to the number of CPU cores available. *** ## Change Extractor The Change Extractor captures ongoing data changes (INSERT, UPDATE, DELETE) by reading MySQL binary logs. It outputs change events to Wirekite's change format (`.ckt` files) for loading into target databases. The Change Extractor requires binary logging to be enabled with `binlog_format = ROW`. It connects to MySQL as a replication client to stream binlog events. ### Required Parameters Path to a file containing the MySQL connection string. **Connection string format:** ``` username:password@tcp(host:port)/database?multiStatements=true&loc=Local ``` Path to a file listing the tables to track for changes, one per line in `schema.table` format. Absolute path to the directory where Wirekite will write change files. Files are named with sequential numbers (e.g., `0.ckt`, `1.ckt`, etc.). Absolute path to the log file for Change Extractor operations. ### Position Parameters The MySQL binary log filename to start reading from (e.g., `mysql-bin.000042`). When running via the Orchestrator in data+change mode, this is automatically captured after data extraction completes. Required for change-only mode. The position within the binlog file to start reading from. Combined with `binlogFile`, this defines the exact starting point for change capture. When running via the Orchestrator in data+change mode, this is automatically captured. In change-only mode (without data extraction), you must specify both `binlogFile` and `binlogPosition` to define where change capture should begin. Using incorrect values may result in missing changes or duplicate data. ### Optional Parameters When `true`, enables detailed logging including metadata files that can help troubleshoot issues. When `true`, processes only one binary log file and then exits. Useful for testing or manual incremental processing. When `true`, includes BEGIN and COMMIT markers in the output. Wirekite guarantees that transactions never span multiple output files regardless of this setting. Number of change events to buffer before flushing to disk. Lower values reduce memory usage but increase I/O operations. The buffer is always flushed at transaction boundaries. When `true`, the extractor exits after processing all available binlog events. When `false` (default), it runs continuously, waiting for new changes indefinitely. Number of seconds to wait for new binlog events before exiting. Only applies when `exitWhenIdle` is `true`. Minimum value is 2. Interval in seconds for periodic flushing of accumulated changes to disk. Ensures data is written even during low-activity periods. Only applies when `exitWhenIdle` is `false`. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix source parameters with `source.schema.`, `source.data.`, or `source.change.` depending on the operation mode. **Example orchestrator configuration for MySQL source:** ``` # Main configuration source=mysql target=snowflake # Schema extraction source.schema.dsnFile=/opt/wirekite/config/mysql.dsn source.schema.tablesFile=/opt/wirekite/config/tables.txt source.schema.outputDirectory=/opt/wirekite/output/schema source.schema.logFile=/var/log/wirekite/schema-extractor.log # Data extraction source.data.dsnFile=/opt/wirekite/config/mysql.dsn source.data.tablesFile=/opt/wirekite/config/tables.txt source.data.outputDirectory=/opt/wirekite/output/data source.data.logFile=/var/log/wirekite/data-extractor.log source.data.maxThreads=8 source.data.maxRowsPerDump=100000 source.data.databaseRemote=false # Change extraction (CDC) source.change.dsnFile=/opt/wirekite/config/mysql.dsn source.change.tablesFile=/opt/wirekite/config/tables.txt source.change.outputDirectory=/opt/wirekite/output/changes source.change.logFile=/var/log/wirekite/change-extractor.log source.change.eventsPerFlush=10000 source.change.exitWhenIdle=false ``` When running in data+change mode, the Orchestrator automatically captures the binlog position after data extraction and passes it to the Change Extractor. You do not need to manually specify `binlogFile` and `binlogPosition` in this mode. For complete Orchestrator documentation, see the [Execution Guide](/run/execution). # Oracle Source: https://docs.wirekite.io/sourceguides/oracle This guide explains how to configure Oracle as a source database for Wirekite data extraction and replication. ## Overview Wirekite supports Oracle 11g and above as a source database for: * **Schema Extraction** - Extract table definitions to Wirekite's intermediate format * **Data Extraction** - Bulk extract table data for initial load * **Change Extraction (CDC)** - Capture ongoing inserts, updates, and deletes via LogMiner Oracle Change Extraction uses LogMiner to read archive logs and capture changes. This requires archivelog mode to be enabled and supplemental logging configured on the tables being extracted. ## Prerequisites Before configuring Oracle as a Wirekite source, ensure the following requirements are met: ### Database Configuration 1. **Version**: Oracle 12c or later (12c+ required for the `LOGMINING` privilege) 2. **Archivelog Mode** (CDC only): Must be enabled for change capture 3. **Supplemental Logging** (CDC only): Database-level and table-level supplemental logging must be configured (see [Source Database Setup](#source-database-setup) below) ### File System Access * Ensure the user running Wirekite has write permissions to the output directory * Verify sufficient disk space for extracted data files ### Replication Considerations When performing initial data extraction, stop replication and quiesce the database. This ensures the dump is consistent to a specific Oracle SCN (System Change Number) and all transactions have either committed or rolled back. It is highly recommended to run Wirekite against a Data Guard replica rather than the production primary. *** ## Source Database Setup Wirekite requires a dedicated `WIREKITE` schema (user) for internal tracking tables and specific privileges on the application schema and system views. Follow these steps to configure your Oracle source. ### Step 1: Create the Wirekite User/Schema In Oracle, a user and a schema are the same thing. Create a dedicated `WIREKITE` user: ```sql theme={null} -- Connect as SYS or a DBA user CREATE USER wirekite IDENTIFIED BY "" DEFAULT TABLESPACE users QUOTA UNLIMITED ON users; ``` ### Step 2: Grant Basic Session Privileges ```sql theme={null} GRANT CREATE SESSION TO wirekite; ``` ### Step 3: Grant Table Creation Privileges Wirekite creates two internal tracking tables (`wirekite_progress` and `wirekite_action`) in the `WIREKITE` schema for progress tracking and crash recovery: ```sql theme={null} GRANT CREATE TABLE TO wirekite; ``` ### Step 4: Grant Read Access to Application Tables For each application table that needs to be extracted: ```sql theme={null} GRANT SELECT ON .table1 TO wirekite; GRANT SELECT ON .table2 TO wirekite; -- repeat for each table to be extracted ``` Alternatively, to grant SELECT on all current and future tables in a schema: ```sql theme={null} GRANT SELECT ANY TABLE TO wirekite; ``` `SELECT ANY TABLE` is a broad privilege. Use individual table grants for tighter security. ### Step 5: Grant Data Dictionary Access Wirekite queries Oracle data dictionary views for schema metadata (columns, constraints, indexes, etc.): ```sql theme={null} GRANT SELECT ANY DICTIONARY TO wirekite; ``` This covers all of the following views that Wirekite uses: * `DBA_TAB_COLUMNS` -- column metadata * `DBA_CONSTRAINTS` / `DBA_CONS_COLUMNS` -- primary keys, unique keys, foreign keys, check constraints * `DBA_INDEXES` / `DBA_IND_COLUMNS` -- index metadata * `DBA_SEQUENCES` -- sequences (full schema extraction) * `DBA_VIEWS` -- views (full schema extraction) * `DBA_MVIEWS` / `DBA_JOBS` / `DBA_REFRESH` -- materialized views (full schema extraction) * `DBA_SYNONYMS` / `DBA_OBJECTS` -- synonyms (full schema extraction) * `DBA_TAB_PRIVS` -- privilege extraction (full schema extraction) * `DBA_ROLES` / `DBA_USERS` / `DBA_ROLE_PRIVS` / `DBA_SYS_PRIVS` -- roles/users (full schema extraction) * `DBA_TRIGGERS` -- triggers (full schema extraction) * `DBA_SOURCE` -- procedure/function/package source (full schema extraction) If you prefer individual grants instead of `SELECT ANY DICTIONARY`, grant SELECT on each of the views listed above. ### Step 6 (CDC Only): Enable Supplemental Logging For change data capture (CDC), Wirekite uses Oracle LogMiner to read redo/archive logs. **Enable database-level supplemental logging:** ```sql theme={null} ALTER DATABASE ADD SUPPLEMENTAL LOG DATA; ``` **Enable table-level primary key supplemental logging** for each table that needs change tracking: ```sql theme={null} ALTER TABLE .table1 ADD SUPPLEMENTAL LOG DATA (PRIMARY KEY) COLUMNS; ALTER TABLE .table2 ADD SUPPLEMENTAL LOG DATA (PRIMARY KEY) COLUMNS; -- repeat for each table to be tracked ``` All tables used with CDC must have a primary key. **Verify supplemental logging:** ```sql theme={null} -- Database level SELECT SUPPLEMENTAL_LOG_DATA_MIN FROM V$DATABASE; -- Should return YES -- Table level SELECT OWNER, TABLE_NAME, LOG_GROUP_TYPE FROM DBA_LOG_GROUPS WHERE LOG_GROUP_TYPE = 'PRIMARY KEY LOGGING' AND OWNER = ''; ``` ### Step 7 (CDC Only): Grant LogMiner Privileges ```sql theme={null} -- V$ dynamic performance views for LogMiner GRANT SELECT ON SYS.V_$DATABASE TO wirekite; GRANT SELECT ON SYS.V_$ARCHIVED_LOG TO wirekite; GRANT SELECT ON SYS.V_$LOGMNR_CONTENTS TO wirekite; GRANT SELECT ON SYS.V_$TRANSACTION TO wirekite; -- LogMiner packages GRANT EXECUTE ON SYS.DBMS_LOGMNR TO wirekite; GRANT EXECUTE ON SYS.DBMS_LOGMNR_D TO wirekite; -- LogMiner privilege (Oracle 12c+) GRANT LOGMINING TO wirekite; ``` ### Step 8 (CDC Only, Optional): Grant Log Switch Privilege If you want Wirekite to automatically flush redo logs to archive logs (the `autoFlushLogs` option): ```sql theme={null} GRANT ALTER SYSTEM TO wirekite; ``` This allows Wirekite to execute `ALTER SYSTEM SWITCH LOGFILE` and `ALTER SYSTEM ARCHIVE LOG CURRENT`. If you prefer not to grant this, ensure that archive logs are generated frequently enough by your existing Oracle configuration. ### Step 9 (Standby Handover Only): SYSDBA Access If you are extracting from an Oracle Data Guard standby and need to stop/start managed recovery: ```sql theme={null} -- SYSDBA is required for: -- ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL -- ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION ``` This is only needed for Data Guard standby operations. For normal primary database extraction, SYSDBA is not required. ### Complete Setup Script #### Data Extraction Only ```sql theme={null} -- Connect as SYS or DBA -- 1. Create wirekite user CREATE USER wirekite IDENTIFIED BY "" DEFAULT TABLESPACE users QUOTA UNLIMITED ON users; -- 2. Basic session access GRANT CREATE SESSION TO wirekite; -- 3. Allow internal table creation GRANT CREATE TABLE TO wirekite; -- 4. Grant read access to application tables GRANT SELECT ON .table1 TO wirekite; GRANT SELECT ON .table2 TO wirekite; -- repeat for each table to be extracted -- 5. Data dictionary access GRANT SELECT ANY DICTIONARY TO wirekite; ``` #### Data Extraction + CDC (Change Data Capture) ```sql theme={null} -- Connect as SYS or DBA -- 1. Create wirekite user CREATE USER wirekite IDENTIFIED BY "" DEFAULT TABLESPACE users QUOTA UNLIMITED ON users; -- 2. Basic session access GRANT CREATE SESSION TO wirekite; -- 3. Allow internal table creation GRANT CREATE TABLE TO wirekite; -- 4. Grant read access to application tables GRANT SELECT ON .table1 TO wirekite; GRANT SELECT ON .table2 TO wirekite; -- repeat for each table to be extracted -- 5. Data dictionary access GRANT SELECT ANY DICTIONARY TO wirekite; -- 6. LogMiner privileges GRANT SELECT ON SYS.V_$DATABASE TO wirekite; GRANT SELECT ON SYS.V_$ARCHIVED_LOG TO wirekite; GRANT SELECT ON SYS.V_$LOGMNR_CONTENTS TO wirekite; GRANT SELECT ON SYS.V_$TRANSACTION TO wirekite; GRANT EXECUTE ON SYS.DBMS_LOGMNR TO wirekite; GRANT EXECUTE ON SYS.DBMS_LOGMNR_D TO wirekite; GRANT LOGMINING TO wirekite; -- 7. (Optional) Auto log switch GRANT ALTER SYSTEM TO wirekite; -- 8. Enable supplemental logging ALTER DATABASE ADD SUPPLEMENTAL LOG DATA; -- 9. Enable PK supplemental logging per table ALTER TABLE .table1 ADD SUPPLEMENTAL LOG DATA (PRIMARY KEY) COLUMNS; ALTER TABLE .table2 ADD SUPPLEMENTAL LOG DATA (PRIMARY KEY) COLUMNS; -- repeat for each table to be tracked ``` ### Verify the Setup Connect as the wirekite user and verify access: ```sql theme={null} -- Should succeed SELECT * FROM .table1 WHERE ROWNUM = 1; -- Should succeed SELECT column_name FROM DBA_TAB_COLUMNS WHERE owner = UPPER('') AND table_name = 'TABLE1'; -- Should succeed (CDC only) SELECT SUPPLEMENTAL_LOG_DATA_MIN FROM V$DATABASE; ``` ### What Wirekite Creates | Object | Type | Schema | Purpose | | ------------------- | ----- | ---------- | ------------------------------------------ | | `wirekite_progress` | Table | `WIREKITE` | Tracks extraction progress, crash recovery | | `wirekite_action` | Table | `WIREKITE` | Run/pause/stop control | | `wkp_finish_time` | Index | `WIREKITE` | Index on wirekite\_progress | | `wkp_start_time` | Index | `WIREKITE` | Index on wirekite\_progress | Wirekite does NOT create any triggers, stored procedures, packages, or other PL/SQL objects on the source database. CDC uses Oracle LogMiner exclusively. ### Privilege Summary | Privilege | Required For | | -------------------------------- | ---------------------------------------------- | | `CREATE SESSION` | Basic connectivity | | `CREATE TABLE` | Internal tracking tables in WIREKITE schema | | `SELECT ON .
` | Reading application table data | | `SELECT ANY DICTIONARY` | Schema metadata from data dictionary views | | `SELECT ON V_$DATABASE` | CDC: supplemental logging check, current SCN | | `SELECT ON V_$ARCHIVED_LOG` | CDC: archive log discovery for LogMiner | | `SELECT ON V_$LOGMNR_CONTENTS` | CDC: reading LogMiner output | | `SELECT ON V_$TRANSACTION` | CDC: transaction checkpoint for crash recovery | | `EXECUTE ON SYS.DBMS_LOGMNR` | CDC: LogMiner session management | | `EXECUTE ON SYS.DBMS_LOGMNR_D` | CDC: LogMiner dictionary | | `LOGMINING` | CDC: LogMiner access (Oracle 12c+) | | `ALTER SYSTEM` | CDC (optional): automatic redo log switch | *** ## Schema Extractor The Schema Extractor reads table definitions from Oracle and outputs them to Wirekite's intermediate schema format (`.skt` file). This schema file is used by target loaders to create corresponding tables in the destination database. The Schema Extractor can run standalone or as part of the Orchestrator workflow. The configuration parameters are the same in both cases. ### Required Parameters Path to a file containing the Oracle connection string. The file should contain exactly one line with the DSN. **Connection string format:** ``` username/password@host:port/service_name ``` **Example DSN file contents:** ``` wirekite/secretpass@oracle-replica.example.com:1521/ORCL ``` Path to a file listing the tables to extract, one per line in `schema.table` format. **Example tablesFile contents:** ``` HR.EMPLOYEES HR.DEPARTMENTS SALES.ORDERS INVENTORY.PRODUCTS ``` Absolute path to the directory where Wirekite will write the schema file (`wirekite_schema.skt`). The directory must exist and be writable. Absolute path to the log file where the Schema Extractor will write operational logs. ### Optional Parameters Rename the source schema in the output. Format: `sourceSchema:targetSchema`. Useful when the target database uses a different schema name. When `true`, extracts all database objects including views, indexes, and constraints in addition to table definitions. *** ## Data Extractor The Data Extractor performs bulk extraction of table data, writing records to Wirekite's intermediate data format (`.dkt` files). Large tables are automatically split across multiple files based on the `maxRowsPerDump` setting. ### Required Parameters Path to a file containing the Oracle connection string. **Connection string format:** ``` username/password@host:port/service_name ``` Path to a file listing the tables to extract, one per line in `schema.table` format. Absolute path to the directory where Wirekite will write data files. Files are named `schema.table.N.dkt` where N is a sequence number. Absolute path to the log file for Data Extractor operations. ### Optional Parameters Number of parallel extraction threads. Each thread consumes one database connection and approximately one CPU core. Set this based on available CPU cores and acceptable database load. Maximum number of rows written to each output file. Large tables are split into multiple files. Adjust based on available memory and disk space. When `true`, the data extractor captures the current SCN at the end of the load and writes it to `position.pkt`. Used to hand off to a subsequent change extractor without losing any commits. The orchestrator sets this automatically in `data+change` mode — only set it explicitly when invoking the data extractor outside the orchestrator. When `true`, binary and string data is encoded as hexadecimal instead of base64. Hex encoding produces larger files but may be required for certain target databases (e.g., Snowflake). When `true`, sorts output files by table name for easier management and verification. Rename the source schema in the output. Format: `sourceSchema:targetSchema`. For best performance on dedicated extraction hosts, set `maxThreads` equal to the number of CPU cores available. *** ## Change Extractor The Change Extractor captures ongoing data changes (INSERT, UPDATE, DELETE) by reading Oracle archive logs via LogMiner. It outputs change events to Wirekite's change format (`.ckt` files) for loading into target databases. The Change Extractor requires archivelog mode to be enabled. It uses Oracle LogMiner to read and parse archive log files. ### Required Parameters Path to a file containing the Oracle connection string. **Connection string format:** ``` username/password@host:port/service_name ``` Path to a file listing the tables to track for changes, one per line in `schema.table` format. Absolute path to the directory where Wirekite will write change files. Files are named with sequential numbers (e.g., `0.ckt`, `1.ckt`, etc.). Absolute path to the log file for Change Extractor operations. ### Position Parameters The Oracle System Change Number (SCN) from which to start extracting changes. This is typically the SCN captured when the data extraction was taken. When running via the Orchestrator in data+change mode, this is automatically captured. When not specified, defaults to `"none"` meaning no starting position is set. In change-only mode (without data extraction), you must specify the correct `startScn` to define where change capture should begin. Using incorrect values may result in missing changes or duplicate data. ### Optional Parameters When `true`, enables detailed logging including metadata files that can help troubleshoot issues. When `true`, processes only one archive log file and then exits. Useful for testing or manual incremental processing. When `true`, includes BEGIN and COMMIT markers in the output. Wirekite guarantees that transactions never span multiple output files regardless of this setting. Number of change events to buffer before flushing to disk. Lower values reduce memory usage but increase I/O operations. The buffer is always flushed at transaction boundaries. When `true`, the extractor exits after processing all available archive logs. When `false` (default), it runs continuously, waiting for new archive logs indefinitely. Number of seconds to wait between checks for new archive logs when idle. Only applies when `exitWhenIdle` is `false`. When `true`, automatically triggers archive log switches to ensure changes are captured promptly. Interval in seconds between automatic log flushes when `autoFlushLogs` is enabled. Maximum number of archive logs to process in a single LogMiner session before restarting. Parsed for backward compatibility but no longer used in the current implementation. Number of previous archive logs to include in each mining session. Parsed for backward compatibility but no longer used in the current implementation. Rename the source schema in the output. Format: `sourceSchema:targetSchema`. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix source parameters with `source.schema.`, `source.data.`, or `source.change.` depending on the operation mode. **Example orchestrator configuration for Oracle source:** ``` # Main configuration source=oracle target=snowflake # Schema extraction source.schema.dsnFile=/opt/wirekite/config/oracle.dsn source.schema.tablesFile=/opt/wirekite/config/tables.txt source.schema.outputDirectory=/opt/wirekite/output/schema source.schema.logFile=/var/log/wirekite/schema-extractor.log # Data extraction source.data.dsnFile=/opt/wirekite/config/oracle.dsn source.data.tablesFile=/opt/wirekite/config/tables.txt source.data.outputDirectory=/opt/wirekite/output/data source.data.logFile=/var/log/wirekite/data-extractor.log source.data.maxThreads=8 source.data.maxRowsPerDump=100000 source.data.hexEncoding=false # Change extraction (CDC) source.change.dsnFile=/opt/wirekite/config/oracle.dsn source.change.tablesFile=/opt/wirekite/config/tables.txt source.change.outputDirectory=/opt/wirekite/output/changes source.change.logFile=/var/log/wirekite/change-extractor.log source.change.eventsPerFlush=10000 source.change.exitWhenIdle=false source.change.autoFlushLogs=true source.change.flushLogIntervalSeconds=300 ``` When running in data+change mode, the Orchestrator automatically captures the SCN after data extraction and passes it to the Change Extractor. You do not need to manually specify `startScn` in this mode. For complete Orchestrator documentation, see the [Execution Guide](/run/execution). # PostgreSQL / YugaByte / TigerData / AlloyDB Source: https://docs.wirekite.io/sourceguides/postgres This guide explains how to configure PostgreSQL (including YugaByte, TigerData, and AlloyDB) as a source database for Wirekite data extraction and replication. ## Overview Wirekite supports PostgreSQL 10 and above (including YugaByte, TigerData, and Google AlloyDB) as a source database for: * **Schema Extraction** - Extract table definitions to Wirekite's intermediate format * **Data Extraction** - Bulk extract table data for initial load * **Change Extraction (CDC)** - Capture ongoing inserts, updates, and deletes via logical replication All references to PostgreSQL in this guide also apply to YugaByte, TigerData, and AlloyDB setups. These databases use the PostgreSQL wire protocol, so the configuration and parameters are identical. PostgreSQL Change Extraction uses the `pgoutput` logical replication plugin, which is built into PostgreSQL 10 and later. This provides efficient, low-overhead change capture without requiring additional extensions. ## Prerequisites Before configuring PostgreSQL as a Wirekite source, ensure the following requirements are met: ### Database Configuration 1. **Version**: PostgreSQL 10 or later (PostgreSQL 15+ recommended for non-superuser CDC) 2. **Logical Replication** (CDC only): WAL level must be set to `logical` in `postgresql.conf`: ``` wal_level = logical max_replication_slots = 4 # at least 1 available slot max_wal_senders = 4 # at least 1 available sender ``` Restart PostgreSQL after changing these settings. ### File System Access * For server-side extraction: Ensure the `postgres` user has write permissions to the output directory * Verify sufficient disk space for extracted data files For cloud-managed PostgreSQL instances (RDS, Cloud SQL, etc.) or remote databases where server-side file access isn't available, use `databaseRemote=true` (the default) to extract data via the client connection. ### General Recommendations When performing initial data extraction, stop replication and quiesce the database instance. This ensures the entire dump is consistent to a specific position. It is highly recommended to run Wirekite against a replica rather than production to avoid impacting workloads. *** ## Source Database Setup Wirekite requires a dedicated user with specific privileges and a `wirekite` schema for internal tracking tables. Follow these steps to configure your PostgreSQL source. ### Step 1: Create the Wirekite User Connect as a superuser (e.g., `postgres`) and run: ```sql theme={null} CREATE ROLE wirekite WITH LOGIN PASSWORD ''; ``` ### Step 2: Grant Connection Access ```sql theme={null} GRANT CONNECT ON DATABASE TO wirekite; ``` ### Step 3: Create the Wirekite Schema Wirekite uses a dedicated `wirekite` schema for its internal tracking tables (`wirekite_progress` and `wirekite_action`). These tables track extraction progress and enable crash recovery. ```sql theme={null} -- Connect to the target database first \c GRANT CREATE ON DATABASE TO wirekite; ``` Wirekite will automatically create the `wirekite` schema and its tables on first run. Alternatively, you can create the schema in advance: ```sql theme={null} CREATE SCHEMA IF NOT EXISTS wirekite AUTHORIZATION wirekite; ``` ### Step 4: Grant Read Access to Application Tables For each application schema that contains tables you want to extract: ```sql theme={null} GRANT USAGE ON SCHEMA TO wirekite; GRANT SELECT ON ALL TABLES IN SCHEMA TO wirekite; -- For tables created in the future: ALTER DEFAULT PRIVILEGES IN SCHEMA GRANT SELECT ON TABLES TO wirekite; ``` For example, if your application tables are in the `public` schema: ```sql theme={null} GRANT USAGE ON SCHEMA public TO wirekite; GRANT SELECT ON ALL TABLES IN SCHEMA public TO wirekite; ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO wirekite; ``` ### Step 5: System Catalog Access PostgreSQL grants `SELECT` on `information_schema` and `pg_catalog` views to all users by default. No additional grants are needed for: * `information_schema.tables` * `information_schema.columns` * `pg_catalog.pg_constraint` * `pg_catalog.pg_class` * `pg_catalog.pg_indexes` * `pg_catalog.pg_publication` * `pg_catalog.pg_replication_slots` ### Step 6 (Optional): Server-Side File Export If you plan to use server-side file export (the "local" mode where the database writes files directly), the wirekite user needs the `pg_write_server_files` role: ```sql theme={null} GRANT pg_write_server_files TO wirekite; ``` This is NOT needed if Wirekite and the database are on different machines (the default "remote" streaming mode with `databaseRemote=true`). ### Step 7 (CDC Only): Grant Replication Privileges For change data capture (CDC), Wirekite uses PostgreSQL's native logical replication with the built-in `pgoutput` plugin. The wirekite user needs the `REPLICATION` attribute: ```sql theme={null} ALTER ROLE wirekite WITH REPLICATION; ``` #### Publication Ownership (PostgreSQL 15+) Wirekite creates a publication for each replication slot. On PostgreSQL 15+, the wirekite user must be the owner of the tables being published, OR you can use a superuser for publication creation. If the application tables are owned by another user, you can either: **Option A**: Grant table ownership to wirekite (not recommended for production): ```sql theme={null} ALTER TABLE .
OWNER TO wirekite; ``` **Option B**: Create the publication as superuser and let wirekite use it: ```sql theme={null} -- As superuser, create the publication for the tables wirekite needs to track: CREATE PUBLICATION wirekite_pub FOR TABLE .table1, .table2, .table3; ``` **Option C (PostgreSQL 10-14)**: `CREATE PUBLICATION` requires superuser. Either run wirekite as superuser for the initial setup, or pre-create the publication as shown in Option B. #### Create the Replication Slot Wirekite can create its own replication slot, but you can also pre-create it: ```sql theme={null} SELECT pg_create_logical_replication_slot('wirekite_slot', 'pgoutput'); ``` When running via the Orchestrator in data+change mode, the replication slot is created automatically **before** data extraction begins. In change-only mode, create the replication slot manually before starting the Change Extractor. ### Complete Setup Script #### Data Extraction Only ```sql theme={null} -- Run as superuser (e.g., postgres) -- 1. Create user CREATE ROLE wirekite WITH LOGIN PASSWORD ''; -- 2. Grant connection GRANT CONNECT ON DATABASE TO wirekite; -- 3. Allow schema creation (for wirekite internal tables) GRANT CREATE ON DATABASE TO wirekite; -- 4. Grant read access to application tables GRANT USAGE ON SCHEMA TO wirekite; GRANT SELECT ON ALL TABLES IN SCHEMA TO wirekite; ALTER DEFAULT PRIVILEGES IN SCHEMA GRANT SELECT ON TABLES TO wirekite; ``` #### Data Extraction + CDC (Change Data Capture) ```sql theme={null} -- Run as superuser (e.g., postgres) -- 1. Create user with replication CREATE ROLE wirekite WITH LOGIN REPLICATION PASSWORD ''; -- 2. Grant connection GRANT CONNECT ON DATABASE TO wirekite; -- 3. Allow schema creation GRANT CREATE ON DATABASE TO wirekite; -- 4. Grant read access to application tables GRANT USAGE ON SCHEMA TO wirekite; GRANT SELECT ON ALL TABLES IN SCHEMA TO wirekite; ALTER DEFAULT PRIVILEGES IN SCHEMA GRANT SELECT ON TABLES TO wirekite; -- 5. Create publication for CDC (as superuser) -- List all tables that need change tracking: CREATE PUBLICATION wirekite_pub FOR TABLE .table1, .table2; -- add more tables as needed -- 6. Verify wal_level SHOW wal_level; -- must be 'logical' ``` ### pg\_hba.conf Ensure the wirekite user can connect from the Wirekite server. Add to `pg_hba.conf`: ``` # TYPE DATABASE USER ADDRESS METHOD host wirekite /32 scram-sha-256 ``` For CDC replication connections, also add: ``` host replication wirekite /32 scram-sha-256 ``` Reload PostgreSQL after changes: `SELECT pg_reload_conf();` ### What Wirekite Creates | Object | Type | Schema | Purpose | | ------------------- | ---------------- | ---------- | ------------------------------------------ | | `wirekite` | Schema | n/a | Holds internal tracking tables | | `wirekite_progress` | Table | `wirekite` | Tracks extraction progress, crash recovery | | `wirekite_action` | Table | `wirekite` | Run/pause/stop control | | Publication | Publication | n/a | Routes WAL changes to wirekite (CDC only) | | Replication slot | Replication Slot | n/a | Reserves WAL for wirekite (CDC only) | Wirekite does NOT create any triggers, functions, or stored procedures on the source database. ### Privilege Summary | Privilege | Required For | | --------------------------------------------- | -------------------------------------- | | `CONNECT ON DATABASE` | Basic connectivity | | `CREATE ON DATABASE` | Creating the `wirekite` schema | | `USAGE ON SCHEMA ` | Accessing application tables | | `SELECT ON ALL TABLES IN SCHEMA ` | Reading table data | | `REPLICATION` role attribute | CDC only: logical replication protocol | | `pg_write_server_files` role | Optional: server-side file export only | *** ## Schema Extractor The Schema Extractor reads table definitions from PostgreSQL and outputs them to Wirekite's intermediate schema format (`.skt` file). This schema file is used by target loaders to create corresponding tables in the destination database. The Schema Extractor can run standalone or as part of the Orchestrator workflow. The configuration parameters are the same in both cases. ### Required Parameters Path to a file containing the PostgreSQL connection string. The file should contain exactly one line with the DSN. **Connection string format:** ``` postgres://username:password@host:port/database ``` **Example DSN file contents:** ``` postgres://wirekite:secretpass@postgres-replica.example.com:5432/myapp ``` Path to a file listing the tables to extract, one per line in `schema.table` format. **Example tablesFile contents:** ``` public.users public.orders public.products inventory.items ``` Absolute path to the directory where Wirekite will write the schema file (`wirekite_schema.skt`). The directory must exist and be writable. Absolute path to the log file where the Schema Extractor will write operational logs. ### Optional Parameters Rename the source schema in the output. Format: `sourceSchema:targetSchema`. Useful when the target database uses a different schema name. *** ## Data Extractor The Data Extractor performs bulk extraction of table data, writing records to Wirekite's intermediate data format (`.dkt` files). Large tables are automatically split across multiple files based on the `maxPages` setting. ### Required Parameters Path to a file containing the PostgreSQL connection string. **Connection string format:** ``` postgres://username:password@host:port/database ``` Path to a file listing the tables to extract, one per line in `schema.table` format. Absolute path to the directory where Wirekite will write data files. Files are named `schema.table.N.dkt` where N is a sequence number. Absolute path to the log file for Data Extractor operations. ### Optional Parameters Number of parallel extraction threads. Each thread consumes one database connection and approximately one CPU core. Set this based on available CPU cores and acceptable database load. Maximum number of PostgreSQL storage pages to visit by each extraction thread. The default of 8,000 pages produces files of approximately 64MB. Since pages have varying numbers of rows, this corresponds loosely to the number of rows extracted at a time. Adjust based on available memory. When `true`, the data extractor captures the current WAL position (LSN) at the end of the load and writes it to `position.pkt`. Used to hand off to a subsequent change extractor without losing any commits. The orchestrator sets this automatically in `data+change` mode — only set it explicitly when invoking the data extractor outside the orchestrator. When `true`, binary and string data is encoded as hexadecimal instead of base64. Hex encoding produces larger files but may be required for certain target databases (e.g., Snowflake). When `true`, sorts output files by table name for easier management and verification. When `true`, uses client-side data extraction instead of server-side file writes. **Required for cloud-managed PostgreSQL instances** (Amazon RDS, Google Cloud SQL, Azure Database for PostgreSQL) or any remote database where server-side file access is not available. Set to `false` for local extraction using server-side file operations. Rename the source schema in the output. Format: `sourceSchema:targetSchema`. For best performance on dedicated extraction hosts with local database access, set `maxThreads` equal to the number of CPU cores available (e.g., 32 threads for a 32-core host). *** ## Change Extractor The Change Extractor captures ongoing data changes (INSERT, UPDATE, DELETE) by consuming PostgreSQL logical replication stream. It outputs change events to Wirekite's change format (`.ckt` files) for loading into target databases. The Change Extractor uses the `pgoutput` logical replication plugin and requires a replication slot to be created before starting extraction. ### Required Parameters Path to a file containing the PostgreSQL connection string. **Connection string format:** ``` postgres://username:password@host:port/database ``` Path to a file listing the tables to track for changes, one per line in `schema.table` format. Absolute path to the directory where Wirekite will write change files. Files are named with sequential numbers (e.g., `0.ckt`, `1.ckt`, etc.). Absolute path to the log file for Change Extractor operations. The name of the PostgreSQL replication slot to use for change capture. This slot must be created before starting the Change Extractor: ```sql theme={null} SELECT pg_create_logical_replication_slot('slot_name', 'pgoutput'); ``` The replication slot must exist before starting the Change Extractor. If the slot doesn't exist, the extractor will fail to start. ### Optional Parameters When `true`, includes BEGIN and COMMIT markers in the output. Wirekite guarantees that transactions never span multiple output files regardless of this setting. When `true`, the extractor exits after processing all pending changes. When `false` (default), it runs continuously, waiting for new changes indefinitely. Number of seconds of inactivity before the extractor considers itself idle. Only relevant when `exitWhenIdle` is `true`. Rename the source schema in the output. Format: `sourceSchema:targetSchema`. *** ## Handover Operations The Handover utility provides administrative operations for managing replication slots. It can be run independently or as part of orchestrated workflows. ### Create Replication Slot ```bash theme={null} handover -operation createslot -dsnfile /path/to/dsn -slotname wirekite_slot ``` ### Drop Replication Slot ```bash theme={null} handover -operation dropslot -dsnfile /path/to/dsn -slotname wirekite_slot ``` Dropping a replication slot will discard all unconsumed changes. Only drop slots when you are certain change capture is no longer needed or when recreating the slot from a new position. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix source parameters with `source.schema.`, `source.data.`, or `source.change.` depending on the operation mode. **Example orchestrator configuration for PostgreSQL source:** ``` # Main configuration source=postgres target=snowflake # Schema extraction source.schema.dsnFile=/opt/wirekite/config/postgres.dsn source.schema.tablesFile=/opt/wirekite/config/tables.txt source.schema.outputDirectory=/opt/wirekite/output/schema source.schema.logFile=/var/log/wirekite/schema-extractor.log # Data extraction source.data.dsnFile=/opt/wirekite/config/postgres.dsn source.data.tablesFile=/opt/wirekite/config/tables.txt source.data.outputDirectory=/opt/wirekite/output/data source.data.logFile=/var/log/wirekite/data-extractor.log source.data.maxThreads=8 source.data.databaseRemote=true # Change extraction (CDC) source.change.dsnFile=/opt/wirekite/config/postgres.dsn source.change.tablesFile=/opt/wirekite/config/tables.txt source.change.outputDirectory=/opt/wirekite/output/changes source.change.logFile=/var/log/wirekite/change-extractor.log source.change.replicationSlot=wirekite_slot source.change.exitWhenIdle=false ``` When running in data+change mode, the Orchestrator automatically creates the replication slot before data extraction and manages change capture positioning. For complete Orchestrator documentation, see the [Execution Guide](/run/execution). # Snowflake Data Mover Source: https://docs.wirekite.io/sourceguides/snowflakemover Transfers extracted data files directly to Snowflake internal stages using PUT commands. The Snowflake Data Mover transfers files extracted by Wirekite Extractors directly to Snowflake's internal stage using native PUT commands. This is the recommended mover for Snowflake targets as it leverages Snowflake's optimized file transfer mechanism. The mover watches a local directory for extracted data files, uploads them to the user's Snowflake stage (`@~`), and optionally compresses and removes local files after successful upload. ## When to Use Use the Snowflake Data Mover when: * Snowflake is your target database * You want to use Snowflake's native PUT command for optimal performance * You prefer staging data in Snowflake's internal stage rather than external cloud storage ## Features * **Native Snowflake PUT** - Uses Snowflake's optimized file transfer protocol * **Multi-threaded uploads** - Parallel uploads for better throughput * **Optional gzip compression** - Compress files before upload * **Crash recovery** - Safe restarts without re-uploading completed files * **Automatic cleanup** - Removes local files after successful upload * **Coordinated completion** - Waits for `DATA.DONE` signal before finalizing ## Configuration The Snowflake Data Mover uses a configuration file passed as a command-line argument: ```bash theme={null} snowflake_data_mover ``` ### Configuration Parameters Path to a file containing the Snowflake connection string (DSN). The file should contain a single line with the full Snowflake connection URL. The full path on the local machine where the Wirekite Data Extractor writes its files. The path to a file where the Snowflake Data Mover will write its logging output. Maximum number of parallel threads for uploading files. Default is `10`. Whether to gzip files before uploading. When enabled, files are compressed locally and uploaded with `SOURCE_COMPRESSION=GZIP`. Default is `false`. Whether to remove local files after successful upload. Default is `false`. ### Example Configuration ``` dsnFile = /etc/wirekite/snowflake_dsn.txt dataDirectory = /data/wirekite/extract logFile = /var/log/wirekite/snowflake_mover.log maxThreads = 15 gzipFiles = true removeFiles = true ``` ### Snowflake DSN File Format The DSN file should contain a single line with your Snowflake connection string: ``` user:password@account/database/schema?warehouse=COMPUTE_WH ``` Or with additional parameters: ``` user:password@account.region.cloud/database/schema?warehouse=COMPUTE_WH&role=DATA_LOADER ``` ## Orchestrator Integration When using the Snowflake Data Mover with the Wirekite Orchestrator, add the mover configuration to your orchestrator config: ``` moverType = snowflake moverConfig = /path/to/snowflake_mover.cfg ``` ## How It Works 1. The mover connects to Snowflake using the provided DSN 2. Monitors `dataDirectory` for files with the specified extension 3. For each file found: * Optionally compresses the file with gzip * Executes a PUT command to upload to `@~/filename` * Verifies the upload status is `UPLOADED` * Removes the local file (if configured) 4. When `DATA.DONE` appears in the directory, uploads it and exits gracefully ### PUT Command Details The mover uses different PUT commands based on compression settings: **Without compression:** ```sql theme={null} PUT file:///path/to/file.dkt @~/file.dkt SOURCE_COMPRESSION=NONE AUTO_COMPRESS=FALSE; ``` **With compression:** ```sql theme={null} PUT file:///path/to/file.dgz @~/file.dgz SOURCE_COMPRESSION=GZIP; ``` ## Notes * Files are uploaded to the user's default stage (`@~`) * The Snowflake user must have permissions to PUT files to their stage * For large migrations, increase `maxThreads` to improve throughput * Enable `gzipFiles` to reduce network transfer time * The Snowflake Loader should be configured to read from the same stage * This mover requires direct network connectivity to Snowflake from the extraction host # SQL Server Source: https://docs.wirekite.io/sourceguides/sqlserver This guide explains how to configure SQL Server as a source database for Wirekite data extraction and replication. ## Overview Wirekite supports SQL Server 2016 and above as a source database for: * **Schema Extraction** - Extract table definitions to Wirekite's intermediate format * **Data Extraction** - Bulk extract table data for initial load * **Change Extraction (CDC)** - Capture ongoing inserts, updates, and deletes via Change Data Capture SQL Server Change Extraction uses the built-in Change Data Capture (CDC) feature. CDC must be enabled at both the database and table level before Wirekite can capture changes. ## Prerequisites Before configuring SQL Server as a Wirekite source, ensure the following requirements are met: ### Database Configuration 1. **Version**: SQL Server 2016 or later 2. **SQL Server Agent** (CDC only): Must be running for CDC capture jobs 3. **Change Data Capture** (CDC only): Must be enabled at both database and table level (see [Source Database Setup](#source-database-setup) below) ### File System Access * Ensure the user running Wirekite has write permissions to the output directory * Verify sufficient disk space for extracted data files ### Replication Considerations When performing initial data extraction, stop replication on the source database to ensure a consistent dump. It is highly recommended to run Wirekite against a replica rather than the production primary, as Wirekite can generate significant load on the database server. *** ## Source Database Setup Wirekite requires a dedicated login/user, a `wirekite` schema for internal tracking tables, and specific privileges on the application schema and CDC infrastructure. Follow these steps to configure your SQL Server source. ### Step 1: Create the Wirekite Login Connect as `sa` or a sysadmin and run: ```sql theme={null} -- Server-level login CREATE LOGIN wirekite WITH PASSWORD = ''; ``` ### Step 2: Create a Database User Connect to the application database and create a user mapped to the login: ```sql theme={null} USE ; CREATE USER wirekite FOR LOGIN wirekite; ``` ### Step 3: Create the Wirekite Schema Wirekite uses a dedicated `wirekite` schema for its internal tracking tables (`wirekite_progress` and `wirekite_action`). These tables track extraction progress and enable crash recovery. ```sql theme={null} CREATE SCHEMA wirekite AUTHORIZATION wirekite; ``` This gives the wirekite user ownership of the schema, allowing it to create, drop, and modify tables within it. ### Step 4: Grant Read Access to Application Tables For the application schema (e.g., `dbo`): ```sql theme={null} GRANT SELECT ON SCHEMA::dbo TO wirekite; ``` Or grant on specific tables: ```sql theme={null} GRANT SELECT ON dbo.table1 TO wirekite; GRANT SELECT ON dbo.table2 TO wirekite; -- repeat for each table to be extracted ``` Alternatively, add wirekite to the `db_datareader` role for read access to all tables: ```sql theme={null} EXEC sp_addrolemember 'db_datareader', 'wirekite'; ``` ### Step 5: System Catalog Access SQL Server grants `SELECT` on `sys.*` catalog views and `INFORMATION_SCHEMA` views to all database users by default. No additional grants are needed for: * `sys.columns`, `sys.types`, `sys.tables`, `sys.schemas` * `sys.indexes`, `sys.index_columns`, `sys.key_constraints` * `sys.default_constraints` * `INFORMATION_SCHEMA.COLUMNS` ### Step 6 (CDC Only): Enable CDC on the Database CDC must be enabled at the database level by a `sysadmin` or `db_owner`: ```sql theme={null} USE ; EXEC sys.sp_cdc_enable_db; ``` ### Step 7 (CDC Only): Enable CDC on Each Table For each table that needs change tracking: ```sql theme={null} EXEC sys.sp_cdc_enable_table @source_schema = N'dbo', @source_name = N'table1', @role_name = NULL; EXEC sys.sp_cdc_enable_table @source_schema = N'dbo', @source_name = N'table2', @role_name = NULL; -- repeat for each table to be tracked ``` Setting `@role_name = NULL` means any user with SELECT access can read the CDC change tables. If you want to restrict access, specify a role name and add the wirekite user to that role. ### Step 8 (CDC Only): Grant CDC-Specific Privileges ```sql theme={null} -- Read access to CDC change tables and metadata GRANT SELECT ON SCHEMA::cdc TO wirekite; -- CDC system functions GRANT EXECUTE ON sys.fn_cdc_increment_lsn TO wirekite; GRANT EXECUTE ON sys.fn_cdc_get_max_lsn TO wirekite; -- Start/restart the CDC capture job if it stops GRANT EXECUTE ON sys.sp_cdc_start_job TO wirekite; -- Server-level: access to DMVs for monitoring CDC health USE master; GRANT VIEW SERVER STATE TO wirekite; ``` ### Step 9 (CDC Only): Grant Session Cleanup Privilege Wirekite cleans up orphaned CDC extractor sessions on startup. This requires: ```sql theme={null} -- Server-level permission for KILL command USE master; GRANT ALTER ANY CONNECTION TO wirekite; ``` If you prefer not to grant this, Wirekite will still function but may log warnings about orphaned sessions that it cannot clean up. ### Step 10 (HADR Handover Only): Additional Privileges If you are extracting from an Always On Availability Group secondary replica and need handover operations: ```sql theme={null} -- For ALTER DATABASE SET HADR SUSPEND / RESUME GRANT ALTER ON DATABASE:: TO wirekite; -- For reading HADR replica state GRANT VIEW SERVER STATE TO wirekite; -- (already granted in Step 8) ``` The `fn_dblog()` fallback for LSN retrieval requires `sysadmin` or `db_owner`. This is only used when both CDC and HADR position methods fail. ### Step 11: Verify SQL Server Agent is Running CDC requires SQL Server Agent to be running: ```sql theme={null} SELECT dss.status, dss.servicename FROM sys.dm_server_services dss WHERE dss.servicename LIKE '%Agent%'; -- status should be 4 (Running) ``` ### Complete Setup Script #### Data Extraction Only ```sql theme={null} -- Run as sysadmin (e.g., sa) -- 1. Create login CREATE LOGIN wirekite WITH PASSWORD = ''; -- 2. Create database user USE ; CREATE USER wirekite FOR LOGIN wirekite; -- 3. Create wirekite schema for internal tables CREATE SCHEMA wirekite AUTHORIZATION wirekite; -- 4. Grant read access to application schema GRANT SELECT ON SCHEMA::dbo TO wirekite; ``` #### Data Extraction + CDC (Change Data Capture) ```sql theme={null} -- Run as sysadmin (e.g., sa) -- 1. Create login CREATE LOGIN wirekite WITH PASSWORD = ''; -- 2. Create database user USE ; CREATE USER wirekite FOR LOGIN wirekite; -- 3. Create wirekite schema for internal tables CREATE SCHEMA wirekite AUTHORIZATION wirekite; -- 4. Grant read access to application schema GRANT SELECT ON SCHEMA::dbo TO wirekite; -- 5. Enable CDC on the database EXEC sys.sp_cdc_enable_db; -- 6. Enable CDC on each table EXEC sys.sp_cdc_enable_table @source_schema = N'dbo', @source_name = N'table1', @role_name = NULL; EXEC sys.sp_cdc_enable_table @source_schema = N'dbo', @source_name = N'table2', @role_name = NULL; -- repeat for each table to be tracked -- 7. Grant CDC access GRANT SELECT ON SCHEMA::cdc TO wirekite; GRANT EXECUTE ON sys.fn_cdc_increment_lsn TO wirekite; GRANT EXECUTE ON sys.fn_cdc_get_max_lsn TO wirekite; GRANT EXECUTE ON sys.sp_cdc_start_job TO wirekite; -- 8. Server-level permissions USE master; GRANT VIEW SERVER STATE TO wirekite; GRANT ALTER ANY CONNECTION TO wirekite; -- 9. Verify SQL Server Agent is running SELECT dss.status, dss.servicename FROM sys.dm_server_services dss WHERE dss.servicename LIKE '%Agent%'; ``` ### Does Wirekite Need sysadmin? **No.** Wirekite does not require `sysadmin`. However: * Enabling CDC (`sp_cdc_enable_db`, `sp_cdc_enable_table`) must be done by `sysadmin` or `db_owner` as a one-time setup step * The `fn_dblog()` fallback in handover requires `sysadmin`, but this is only used when both CDC and HADR position methods fail ### Verify the Setup Connect as the wirekite user and verify access: ```sql theme={null} USE ; -- Should succeed SELECT TOP 1 * FROM dbo.table1; -- Should succeed SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'dbo' AND table_name = 'table1'; -- Should succeed (CDC only) SELECT * FROM cdc.lsn_time_mapping WHERE 1=0; -- Should succeed (CDC only) SELECT sys.fn_cdc_get_max_lsn(); ``` ### What Wirekite Creates | Object | Type | Schema | Purpose | | ------------------- | ------ | ---------- | ------------------------------------------ | | `wirekite` | Schema | n/a | Holds internal tracking tables | | `wirekite_progress` | Table | `wirekite` | Tracks extraction progress, crash recovery | | `wirekite_action` | Table | `wirekite` | Run/pause/stop control | | `wkp_finish_time` | Index | `wirekite` | Index on wirekite\_progress | | `wkp_start_time` | Index | `wirekite` | Index on wirekite\_progress | Wirekite does NOT create any triggers, stored procedures, or CDC infrastructure. CDC must be enabled by a DBA before Wirekite can use it. Wirekite only reads from the `cdc.*_CT` change tables that SQL Server creates automatically. ### Privilege Summary | Privilege | Scope | Required For | | ------------------------------------- | -------- | --------------------------------------------- | | `SELECT ON SCHEMA::dbo` | Database | Reading application table data | | `wirekite` schema ownership | Database | Internal tracking tables (create/drop/modify) | | `SELECT ON SCHEMA::cdc` | Database | CDC: reading change tables | | `EXECUTE ON sys.fn_cdc_increment_lsn` | Database | CDC: LSN arithmetic | | `EXECUTE ON sys.fn_cdc_get_max_lsn` | Database | CDC: current LSN position | | `EXECUTE ON sys.sp_cdc_start_job` | Database | CDC: restart capture job | | `VIEW SERVER STATE` | Server | CDC: monitoring DMVs | | `ALTER ANY CONNECTION` | Server | CDC: cleaning up orphaned sessions | | `ALTER ON DATABASE` | Database | HADR handover only | *** ## Schema Extractor The Schema Extractor reads table definitions from SQL Server and outputs them to Wirekite's intermediate schema format (`.skt` file). This schema file is used by target loaders to create corresponding tables in the destination database. The Schema Extractor can run standalone or as part of the Orchestrator workflow. The configuration parameters are the same in both cases. ### Required Parameters Path to a file containing the SQL Server connection string. The file should contain exactly one line with the DSN. **Connection string format:** ``` sqlserver://username:password@host:port?database=databasename&encrypt=disable&connection+timeout=30 ``` **Example DSN file contents:** ``` sqlserver://wirekite:secretpass@sqlserver-replica.example.com:1433?database=myapp&encrypt=disable&connection+timeout=30 ``` Path to a file listing the tables to extract, one per line in `schema.table` format. **Example tablesFile contents:** ``` dbo.users dbo.orders sales.customers inventory.products ``` Absolute path to the directory where Wirekite will write the schema file (`wirekite_schema.skt`). The directory must exist and be writable. Absolute path to the log file where the Schema Extractor will write operational logs. ### Optional Parameters Rename the source schema in the output. Format: `sourceSchema:targetSchema`. Useful when the target database uses a different schema name. *** ## Data Extractor The Data Extractor performs bulk extraction of table data, writing records to Wirekite's intermediate data format (`.dkt` files). Large tables are automatically split across multiple files based on the `maxRowsPerDump` setting. ### Required Parameters Path to a file containing the SQL Server connection string. **Connection string format:** ``` sqlserver://username:password@host:port?database=databasename&encrypt=disable&connection+timeout=30 ``` Path to a file listing the tables to extract, one per line in `schema.table` format. Absolute path to the directory where Wirekite will write data files. Files are named `schema.table.N.dkt` where N is a sequence number. Absolute path to the log file for Data Extractor operations. ### Optional Parameters Number of parallel extraction threads. Each thread consumes one database connection and approximately one CPU core. Set this based on available CPU cores and acceptable database load. Maximum number of rows written to each output file. Large tables are split into multiple files. Adjust based on available memory and disk space. When `true`, the data extractor captures the current LSN at the end of the load and writes it to `position.pkt`. Used to hand off to a subsequent change extractor without losing any commits. The orchestrator sets this automatically in `data+change` mode — only set it explicitly when invoking the data extractor outside the orchestrator. When `true`, binary and string data is encoded as hexadecimal instead of base64. Hex encoding produces larger files but may be required for certain target databases (e.g., Snowflake). When `true`, sorts output files by table name for easier management and verification. When `true`, uses a native C extractor instead of the default SQL Server extractor. This can provide better performance for large extractions. Rename the source schema in the output. Format: `sourceSchema:targetSchema`. For best performance on dedicated extraction hosts, set `maxThreads` equal to the number of CPU cores available. *** ## Change Extractor The Change Extractor captures ongoing data changes (INSERT, UPDATE, DELETE) by reading SQL Server CDC change tables. It outputs change events to Wirekite's change format (`.ckt` files) for loading into target databases. The Change Extractor requires Change Data Capture (CDC) to be enabled at both the database and table level. It reads from the CDC change tables (cdc.\*\_CT) to capture modifications. ### Required Parameters Path to a file containing the SQL Server connection string. **Connection string format:** ``` sqlserver://username:password@host:port?database=databasename&encrypt=disable&connection+timeout=30 ``` Path to a file listing the tables to track for changes, one per line in `schema.table` format. Absolute path to the directory where Wirekite will write change files. Files are named with sequential numbers (e.g., `0.ckt`, `1.ckt`, etc.). Absolute path to the log file for Change Extractor operations. ### Position Parameters The Log Sequence Number (LSN) from which to start extracting changes. This is typically the LSN captured when the data extraction was taken. When running via the Orchestrator in data+change mode, this is automatically captured. In change-only mode (without data extraction), you must specify the correct `startLsn` to define where change capture should begin. Using incorrect values may result in missing changes or duplicate data. ### Optional Parameters When `true`, enables detailed logging including metadata files that can help troubleshoot issues. When `true`, the extractor exits after processing all available changes. When `false` (default), it runs continuously, waiting for new changes indefinitely. Number of seconds of inactivity before the extractor considers itself idle. Only relevant when `exitWhenIdle` is `true`. Number of LSNs to process in each batch. Databases with autocommit or many small transactions may generate many LSNs, in which case this value can be increased for better performance. Rename the source schema in the output. Format: `sourceSchema:targetSchema`. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix source parameters with `source.schema.`, `source.data.`, or `source.change.` depending on the operation mode. **Example orchestrator configuration for SQL Server source:** ``` # Main configuration source=sqlserver target=snowflake # Schema extraction source.schema.dsnFile=/opt/wirekite/config/sqlserver.dsn source.schema.tablesFile=/opt/wirekite/config/tables.txt source.schema.outputDirectory=/opt/wirekite/output/schema source.schema.logFile=/var/log/wirekite/schema-extractor.log # Data extraction source.data.dsnFile=/opt/wirekite/config/sqlserver.dsn source.data.tablesFile=/opt/wirekite/config/tables.txt source.data.outputDirectory=/opt/wirekite/output/data source.data.logFile=/var/log/wirekite/data-extractor.log source.data.maxThreads=8 source.data.maxRowsPerDump=100000 source.data.hexEncoding=false # Change extraction (CDC) source.change.dsnFile=/opt/wirekite/config/sqlserver.dsn source.change.tablesFile=/opt/wirekite/config/tables.txt source.change.outputDirectory=/opt/wirekite/output/changes source.change.logFile=/var/log/wirekite/change-extractor.log source.change.lsnBatchSize=1000000 source.change.exitWhenIdle=false ``` When running in data+change mode, the Orchestrator automatically captures the LSN after data extraction and passes it to the Change Extractor. You do not need to manually specify `startLsn` in this mode. For complete Orchestrator documentation, see the [Execution Guide](/run/execution). # Built-in functions Source: https://docs.wirekite.io/sumatra/builtins The functions available in Sumatra compute position — null handling, math, text, and date/time — with their exact semantics. Sumatra's function catalog is deliberately small: a basic programming language's daily-use kernel, not a SQL reference. The split to remember: * **Inside the opaque read** (and inside server-side statements) you are writing the engine's SQL — *every* function the engine has is available there, and heavyweight transformation (regex, format masks, text parsing) belongs there. * **In compute position** — expressions on variables and `rec` fields — the functions on this page are the supported set. They run in Sumatra's own evaluator, bit-exact to the engine's semantics. Unless noted otherwise, a NULL argument makes the result NULL. ## Null handling | Function | Behavior | | --------------------- | ------------------------------------------------ | | `COALESCE(a, b, ...)` | First non-NULL argument, evaluated left to right | | `NULLIF(a, b)` | NULL if `a = b`, otherwise `a` | | `GREATEST(a, b, ...)` | Largest argument | | `LEAST(a, b, ...)` | Smallest argument | Operands of `GREATEST`, `LEAST` (and `CASE` arms) must share a type family — mixing `TEXT` with numbers or dates is a compile error asking for an explicit `CAST`, rather than a runtime coercion that faults only on bad data. ## Math | Function | Behavior | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `ABS(x)` | Absolute value, type-preserving. `ABS` of the most negative integer faults with `OVERFLOW` | | `MOD(a, b)` | Remainder; integer and decimal operands (no float form) | | `FLOOR(x)` / `CEIL(x)` | On `NUMERIC`, keeps the scale (`FLOOR` of `1.55` at scale 2 is `1.00`); on integers and floats, returns `DOUBLE` | | `ROUND(x [, d])` | On `NUMERIC`: **half-up**, scale preserved. On floats: returns `DOUBLE`, rounds **half-even**. `d` must be a literal digit count | | `TRUNC(x [, d])` | Truncates toward zero; `d` must be a literal digit count | | `SQRT(x)` | `DOUBLE` only — cast a `NUMERIC` operand first (`x::DOUBLE`); a negative argument faults | | `PI()` | `3.141592653589793` | Division is the `/` operator; dividing by zero faults with `ZERO_DIVIDE` (see [numeric semantics](/sumatra/language#numeric-semantics) for the width, promotion, and overflow rules). ## Text | Function | Behavior | | ------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | `LENGTH(s)` | Character count (not bytes) | | `UPPER(s)` / `LOWER(s)` | Case conversion | | `TRIM(s)` / `LTRIM(s)` / `RTRIM(s)` | One argument: strips spaces. `LTRIM`/`RTRIM` with a second argument strip that set of characters instead | | `SUBSTR(s, start [, len])` | 1-based; an out-of-range window saturates rather than faulting; a negative length faults | | `POSITION(needle IN haystack)` | 1-based position of the first match, `0` if absent | | `REPLACE(s, from, to)` | Replace every occurrence | | `SPLIT_PART(s, delim, n)` | The n-th field after splitting on `delim` | | `LPAD(s, len, fill)` / `RPAD(s, len, fill)` | Pad to `len` | | `CONCAT(a, b, ...)` | Variadic concatenation; integer, decimal, and date operands are coerced to text | Two operator companions: `||` concatenates two strings (NULL propagates), and `LIKE` (with the usual `%` and `_` wildcards) is the language's pattern match. ## Date and time | Function | Behavior | | ------------------------------------ | -------------------------------------------------------------------------------------------------------------- | | `CURRENT_DATE` / `CURRENT_TIMESTAMP` | Keywords, no parentheses; UTC, from the running program's clock | | `DATE_ADD(unit, n, d)` | Add `n` units; **returns a `TIMESTAMP`** even for a `DATE` input — cast back when storing into a `DATE` column | | `DATE_DIFF(unit, a, b)` | Whole units between two dates/timestamps | | `EXTRACT(unit, ts)` | One time part as a number; fractional seconds come back as a decimal | The unit is a quoted string, first argument: `'year'`, `'month'`, `'day'`, `'hour'`, `'minute'`, `'second'` — plus `'dow'` for the day of week (`0` = Sunday). ```sql theme={null} rec.due_date := CAST(DATE_ADD('day', 30, rec.invoice_date) AS DATE); minutes_since := DATE_DIFF('minute', last_ts, rec.event_ts); rec.year_part := EXTRACT('year', rec.event_ts); ``` An out-of-range result (before year 1 or after year 9999) faults with `OVERFLOW`. Time parts cannot be extracted from a plain `DATE`. `INTERVAL` arithmetic (`ts - INTERVAL '24' HOUR`) is SQL-side — use it inside reads and write statements. ## Casts and conversions `CAST(x AS T)` and the shorthand `x::T` convert between compute types: | Conversion | Rule | | ------------------------- | --------------------------------------------------------------------------------------- | | `DOUBLE`/`REAL` → integer | Rounds **half-even** (`2.5` → `2`, `3.5` → `4`) | | `NUMERIC` → integer | Rounds **half-up** | | Integer → `NUMERIC(p,s)` | Exact; overflow past the precision faults | | `TIMESTAMP` → `DATE` | Truncates the time part | | Anything ↔ `TEXT` | **Not available in compute position** — parse and format text in the read's SQL instead | These are the same conversions assignment applies implicitly when the declared type differs from the value's type. # Exceptions and recovery Source: https://docs.wirekite.io/sumatra/errors Sumatra's fault model: typed exceptions, the EXCEPTION block, STOP versus RAISE, durable prefixes, and how re-runs recover. Sumatra's error philosophy is simple: **a wrong value is worse than a loud stop**. Overflow, division by zero, and unexpected engine errors are faults that end the run — never silently absorbed, never replaced with a NULL. What the language gives you is precise control over *how* the run ends, and a commit model that makes recovery a re-run rather than a forensic exercise. ## The fault model Faults arrive in three lanes, and the distinction matters: | Lane | Examples | Catchable? | | --------------------------------- | -------------------------------------------------------------- | ------------------ | | Typed faults from your compute | `ZERO_DIVIDE`, `OVERFLOW`, `NO_DATA_FOUND` | Yes, by name | | Engine errors from SQL statements | constraint-style errors, MERGE cardinality, SQL runtime errors | Yes, as `OTHERS` | | Infrastructure failures | network, authentication, engine unavailable | **No — by design** | Infrastructure failures are deliberately uncatchable: a `WHEN OTHERS` handler can never mask an outage as a handled condition. An infra failure always exits `1`, so your scheduler's alert lane stays honest. Running out of memory is in the same lane — no handler ever sees it. One infrastructure failure carries a distinct message: if the connection dies on the `COMMIT` statement itself, the engine may have committed before the drop, so the error says `connection lost during COMMIT: commit state unknown — verify target state before re-running`. Treat that one differently from a generic transport error: check the target before re-running, because re-running a commit that actually landed would double-apply append work. The typed faults: * `ZERO_DIVIDE` — division by zero in compute. * `OVERFLOW` — integer width overflow on `+ - *` or a cast, decimal precision overflow, a float operation that would produce NaN or Infinity, or an out-of-range date result. * `NO_DATA_FOUND` — a keyed-collection probe missed (or used a NULL key), or a `SELECT ... INTO` found no row. There are no user-defined exception names in this release, and an empty read is **not** a fault — a read that matches zero rows is a clean no-op. ## The EXCEPTION block A program may end with one handler block: ```sql theme={null} BEGIN ... EXCEPTION WHEN ZERO_DIVIDE THEN STOP; -- anticipated: stop cleanly, keep the prefix WHEN OVERFLOW THEN STOP; WHEN OTHERS THEN RAISE; -- anything else: surface it loudly END; ``` The rules: * Handler actions are exactly two: `STOP` or `RAISE`. There is no handler that patches a value and continues — a handler never resumes the loop it interrupted. * `WHEN OTHERS` must be the last handler, and no exception may be handled twice. * One `EXCEPTION` block per program, covering the whole body. ## STOP versus RAISE **`STOP`** is the graceful ending for a fault you anticipated: the in-flight batch's open transaction rolls back, every previously committed batch stays durable, and the process exits **`2`** with `Stopped — STOP handled; committed prefix retained`. A stop is not a success — exit 2 exists precisely so schedulers can tell "finished" from "stopped early with valid partial progress". **`RAISE`** rethrows: the run dies with exit **`1`**, for faults that should page a human. An unhandled fault behaves the same way. ## Raising faults yourself Business invariants can reuse the typed faults, with an optional condition: ```sql theme={null} RAISE ZERO_DIVIDE WHEN rec.denominator = 0; -- conditional raise IF rec.qty > 1000000 THEN RAISE OVERFLOW; -- unconditional END IF; ``` `ZERO_DIVIDE` and `OVERFLOW` can be raised explicitly; `NO_DATA_FOUND` and `OTHERS` cannot. ## The durable prefix The commit grain you chose in the program (see [COMMIT: placement is meaning](/sumatra/programs#commit-placement-is-meaning)) decides what a fault leaves behind: * **Per-batch commits** — a fault on batch 40 leaves batches 1–39 committed. That committed **prefix** is always valid data, because a batch only commits after its writes applied. * **At-end commit** — a fault anywhere leaves nothing committed; all-or-nothing. The standard recovery pattern makes the program *re-runnable*: filter the read on a done-flag and flip the flag as part of each row's write. ```sql theme={null} BEGIN FOR batch IN (SELECT account_id, gross, factor, weight, risk_score, scored FROM risk_inputs WHERE scored = FALSE) -- only unprocessed rows ORDER KEY (account_id) BATCH SIZE 10000 LOOP FOR rec IN batch LOOP rec.risk_score := rec.gross * rec.factor / rec.weight; rec.scored := TRUE; -- flag rides the same write UPDATE risk_inputs SET ROW = rec WHERE account_id = rec.account_id; END LOOP; COMMIT; END LOOP; EXCEPTION WHEN ZERO_DIVIDE THEN STOP; -- bad row stops the run at exit 2 END; ``` If a zero `weight` stops this run, every earlier batch is already committed and flagged. Fix the data, run the same program again, and the read picks up exactly the unprocessed remainder. Re-running is always **your** action — Sumatra has no automatic retry or resume. And note that carried variables restart from their `DECLARE` initializers on a re-run: design carried state so it is either derivable from the data (as in a per-customer reset) or irrelevant across runs. ## Guard, don't catch A handler stops the run; it cannot skip the faulting row and carry on. When bad rows are expected and should be tolerated, guard *before* the fault instead: ```sql theme={null} FOR rec IN batch LOOP CONTINUE WHEN rec.weight = 0; -- skip the rows that would fault rec.risk_score := rec.gross * rec.factor / rec.weight; ... END LOOP; ``` Use guards for row-level tolerance, and the `EXCEPTION` block for stopping the run cleanly when something genuinely unexpected happens. ## Exit codes for schedulers | Exit | Meaning | Typical scheduler action | | ---- | ------------------------------------------------------------------ | ----------------------------------- | | `0` | Completed (including a clean `RETURN;`) | Nothing | | `2` | Stopped by a handler; committed prefix retained | Re-run after investigating the data | | `1` | Unhandled fault, `RAISE`, compile error, or infrastructure failure | Alert a human | # Learning by example Source: https://docs.wirekite.io/sumatra/examples Nine complete Sumatra programs, graded from the smallest possible to carried state, runtime-routed writes, watermarks, exception handling, pipelines, and dynamic table names. Every program on this page is complete and runnable as written, and each comes from — or directly mirrors — the toolchain's live-verified example corpus. Each example lists the tables it needs — create them (with a few sample rows) in your Firebolt database, save the program to a file, and run it with `sumatra --dsn my.dsn @file.sumatra`. They build on each other in order, so if this is your first contact with Sumatra, read top to bottom. ## 1. The smallest program: set-DML When the work is already set-shaped, a program is just SQL statements and a `COMMIT` — no variables, no loops. Sumatra runs these server-side exactly as written. ```sql Tables theme={null} CREATE TABLE sumatra_sessions ( session_id BIGINT NOT NULL, state TEXT, last_seen TIMESTAMP ) PRIMARY INDEX session_id; CREATE TABLE sumatra_session_tokens ( token_id BIGINT NOT NULL, revoked BOOLEAN ) PRIMARY INDEX token_id; ``` ```sql expire.sumatra theme={null} -- Expire idle sessions and purge revoked tokens, in one transaction. BEGIN UPDATE sumatra_sessions -- plain set-DML: runs on the engine SET state = 'expired' -- exactly as written, rows never WHERE state = 'active' -- leave the server AND last_seen < CURRENT_TIMESTAMP - INTERVAL '24' HOUR; DELETE FROM sumatra_session_tokens -- second statement, same open WHERE revoked = TRUE; -- transaction COMMIT; -- one transaction for the whole program END; ``` What to notice: * A body can hold plain `UPDATE`/`DELETE`/`INSERT ... SELECT` statements directly. They run on the engine as-is — rows never move to the client. * The single top-level `COMMIT;` makes both statements one atomic transaction. * The datetime expression is the engine's own dialect — inside SQL statements you write the engine's SQL (Firebolt here), verbatim. ## 2. Branching per row: CASE and write-back The canonical Sumatra shape: read in batches, compute per row, write each row back. ```sql Tables theme={null} CREATE TABLE sumatra_grade_demo ( id BIGINT NOT NULL, band INT, grade TEXT, gpa NUMERIC(5,2) ) PRIMARY INDEX id; INSERT INTO sumatra_grade_demo VALUES (1, 3, NULL, NULL), (2, 1, NULL, NULL), (3, 2, NULL, NULL), (4, 0, NULL, NULL); ``` ```sql grades.sumatra theme={null} -- Assign a letter grade and GPA from a numeric band. BEGIN FOR batch IN (SELECT id, band, grade, gpa FROM sumatra_grade_demo) ORDER KEY (id) -- a strict order: required for a chunked read BATCH SIZE 4000 -- rows arrive 4,000 at a time LOOP FOR rec IN batch LOOP -- iterate the batch in memory CASE rec.band -- CASE *statement*: statements per branch WHEN 3 THEN rec.grade := 'A'; rec.gpa := 4.00; WHEN 2 THEN rec.grade := 'B'; rec.gpa := 3.00; WHEN 1 THEN rec.grade := 'C'; rec.gpa := 2.00; ELSE rec.grade := 'D'; rec.gpa := 1.00; END CASE; UPDATE sumatra_grade_demo SET ROW = rec WHERE id = rec.id; -- captured per row; the whole batch -- lands as ONE statement END LOOP; COMMIT; -- this batch is now durable END LOOP; END; ``` What to notice: * The `CASE ... END CASE;` **statement** puts statements in each branch. Its cousin, the CASE *expression*, selects a value instead — see [the language reference](/sumatra/language#operators). * The read selects every column of the table because `SET ROW = rec` writes the whole record back (all columns except the key it matches on). * The compiler turns the loop's captured writes into one set-based statement per batch — you get row-by-row logic at set-based cost. ## 3. Carried state: a running balance The pattern SQL struggles with most: each row's result depends on the previous row's result. Variables declared in `DECLARE` carry across rows **and across batches**, and `ORDER KEY` guarantees the order they carry in. ```sql Tables theme={null} CREATE TABLE sumatra_ledger ( entry_id BIGINT NOT NULL, customer_id INT, delta NUMERIC(12,2), running_balance NUMERIC(14,2) ) PRIMARY INDEX customer_id, entry_id; INSERT INTO sumatra_ledger VALUES (1, 100, 50.00, NULL), (2, 100, -20.00, NULL), (3, 100, -80.00, NULL), (4, 200, 10.00, NULL), (5, 200, 15.00, NULL); ``` ```sql balance.sumatra theme={null} -- A floored per-customer running balance. DECLARE running NUMERIC(14,2) := 0; -- carried across rows and batches last_customer BIGINT := NULL; BEGIN FOR batch IN (SELECT entry_id, customer_id, delta, running_balance FROM sumatra_ledger) ORDER KEY (customer_id, entry_id) -- each customer's rows arrive contiguous, in order BATCH SIZE 50000 -- memory bounded; the answer is batch-size-invariant LOOP FOR rec IN batch LOOP IF rec.customer_id <> last_customer OR last_customer IS NULL THEN running := 0; -- new customer: reset last_customer := rec.customer_id; END IF; running := GREATEST(running + rec.delta, 0); -- clamp at zero rec.running_balance := running; -- state flows row to row — -- and across batch seams UPDATE sumatra_ledger SET ROW = rec WHERE entry_id = rec.entry_id; END LOOP; COMMIT; -- per-batch checkpoint END LOOP; END; ``` Customer 100's balances land as `50.00`, `30.00`, `0.00` (the clamp caught the overdraft); customer 200's as `10.00`, `25.00`. What to notice: * `ORDER KEY (customer_id, entry_id)` makes each customer's rows contiguous and ordered — which is exactly what lets `running` and `last_customer` carry correctly, even across batch boundaries. * The per-customer reset is runtime logic (`IF` on a comparison with carried state), not a window-function trick. * `BATCH SIZE 50000` bounds memory; the answer is identical at any batch size — that invariance is a language guarantee. ## 4. Runtime-routed writes: insert, update, or delete per row A per-row branch chooses `DELETE`, `UPDATE`, or `INSERT` based on a value the data produced. Compile-time templating cannot express this; in Sumatra it is just an `IF`. ```sql Tables theme={null} CREATE TABLE sumatra_account_changes ( customer_id INT NOT NULL, new_balance NUMERIC(14,2), exists_flag BOOLEAN ) PRIMARY INDEX customer_id; CREATE TABLE sumatra_account ( customer_id INT NOT NULL, balance NUMERIC(14,2) ) PRIMARY INDEX customer_id; ``` ```sql apply_changes.sumatra theme={null} -- Apply a change feed: negative balance deletes the account, -- an existing account updates, a new one inserts. BEGIN FOR batch IN (SELECT customer_id, new_balance, exists_flag FROM sumatra_account_changes) ORDER KEY (customer_id) BATCH SIZE 20000 LOOP FOR rec IN batch LOOP IF rec.new_balance < 0 THEN -- the data picks the operation, per row DELETE FROM sumatra_account -- captured as op 'd' WHERE customer_id = rec.customer_id; ELSIF rec.exists_flag THEN UPDATE sumatra_account SET balance = rec.new_balance WHERE customer_id = rec.customer_id; -- captured as op 'u' ELSE INSERT INTO sumatra_account (customer_id, balance) VALUES (rec.customer_id, rec.new_balance); -- captured as op 'i' END IF; END LOOP; -- the whole mixed change-set lands as COMMIT; -- ONE op-tagged MERGE, then commits END LOOP; END; ``` What to notice: * All three writes target one table, keyed on `customer_id`; the compiler captures whichever branch fired for each row and applies the whole batch's mixed changes as **one** set-based statement. * Inside a row loop, `INSERT` uses `VALUES` — per-row inserts are captured and batched like the other writes. * Writing the same key twice in one batch is a program error surfaced loudly at run time — never a silent last-write-wins. ## 5. Parameters: one program, many runs `PARAM` declares program inputs; values arrive on the command line, in declaration order, and bind into the read's SQL as real query parameters. ```sql Tables theme={null} CREATE TABLE sumatra_param_src ( region TEXT, sale_date DATE, grp INT, amt NUMERIC(12,2) ); CREATE TABLE sumatra_param_tgt ( grp INT NOT NULL, total NUMERIC(14,2), n BIGINT ) PRIMARY INDEX grp; ``` ```sql region_rollup.sumatra theme={null} -- Roll one region-day of sales into per-group totals. PARAM want_region TEXT; -- values arrive on the command line, PARAM want_date DATE; -- in declaration order BEGIN FOR batch IN (SELECT grp, SUM(amt) AS amt, COUNT(*) AS n FROM sumatra_param_src -- aggregate in the engine; PARAM(...) WHERE region = PARAM('want_region') AND sale_date = CAST(PARAM('want_date') AS DATE) GROUP BY grp) -- binds out-of-band, never spliced in BATCH SIZE ALL -- whole-set: the right grain for GROUP BY LOOP UPDATE sumatra_param_tgt -- accumulate into existing groups — SET total = total + batch.amt, n = n + batch.n WHERE grp = batch.grp; -- server-side, correlated to the batch INSERT INTO sumatra_param_tgt (grp, total, n) SELECT grp, amt, n FROM batch -- insert the complement: together with WHERE grp NOT IN (SELECT grp FROM sumatra_param_tgt); -- the UPDATE, an upsert END LOOP; COMMIT; -- both statements, one transaction END; ``` ```bash theme={null} sumatra --dsn my.dsn @region_rollup.sumatra "EMEA" 2026-07-01 ``` What to notice: * A parameter is referenced only inside SQL, as `PARAM('name')`, and a non-text parameter needs a cast at the point of use. * `BATCH SIZE ALL` runs the aggregating read as one whole-set batch — the right grain for a `GROUP BY` source — and, because the body is order-independent, no `ORDER KEY` is needed. * There is no row loop here: the statements reference `batch` as a set, so the whole body runs server-side. The update-then-insert pair is the idiomatic upsert — accumulate existing keys, insert the complement. ## 6. The incremental watermark: a program that parameterizes itself Every declared variable is visible to the program's own SQL as `PARAM('name')` — so a program can compute a cursor from its target and filter its read by it. The result is an incremental job with **no command-line arguments at all**: every run rolls forward exactly the days that arrived since the last run. ```sql Tables theme={null} CREATE TABLE sumatra_wm_sales ( day DATE, amt NUMERIC(12,2) ); CREATE TABLE sumatra_wm_rollup ( day DATE NOT NULL, total NUMERIC(14,2), n BIGINT ) PRIMARY INDEX day; ``` ```sql watermark_rollup.sumatra theme={null} -- Roll up any sales days newer than what the rollup already holds. DECLARE wm DATE; BEGIN SELECT MAX(day) INTO wm FROM sumatra_wm_rollup; -- where did we stop last time? IF wm IS NULL THEN wm := DATE '1970-01-01'; -- first run: everything is new END IF; FOR batch IN (SELECT day, SUM(amt) AS total, COUNT(*) AS n FROM sumatra_wm_sales WHERE day > CAST(PARAM('wm') AS DATE) -- the variable, bound into the read GROUP BY day) BATCH SIZE ALL LOOP INSERT INTO sumatra_wm_rollup (day, total, n) SELECT day, total, n FROM batch; -- append the new days, server-side END LOOP; COMMIT; -- the rollup itself is the new watermark END; ``` What to notice: * `PARAM('wm')` inside the read refers to the **declared variable** — every declared scalar publishes into every server statement's bind list under its own name, per execution. A non-text value reads back through a cast, exactly like an argument. * The watermark is **derived from the target itself** (`MAX(day)`), so the job needs no state file, no scheduler-managed cursor, and no arguments: re-running it is always safe and always incremental. * A variable that is unset or NULL at the moment a statement runs is absent from that statement's binds — referencing it then is the engine's own loud error. The `IF wm IS NULL` guard makes the first run explicit instead. ## 7. Exceptions: fail safe, keep the checkpoint Arithmetic on real data can fault: a zero divisor, an overflow. Rather than guard every row, this program handles faults at the program level and leans on per-batch commits for recovery. ```sql Tables theme={null} CREATE TABLE sumatra_risk_inputs ( account_id INT NOT NULL, gross NUMERIC(14,2), factor NUMERIC(8,4), weight NUMERIC(8,4), risk_score NUMERIC(14,4), scored BOOLEAN ) PRIMARY INDEX account_id; ``` ```sql score.sumatra theme={null} -- Score each unscored account; stop cleanly on bad data. DECLARE score NUMERIC(14,4); BEGIN FOR batch IN (SELECT account_id, gross, factor, weight FROM sumatra_risk_inputs WHERE scored = FALSE) -- only unprocessed rows: a re-run ORDER KEY (account_id) -- resumes where the last one stopped BATCH SIZE 50000 LOOP FOR rec IN batch LOOP score := rec.gross * rec.factor / rec.weight; -- weight = 0 raises ZERO_DIVIDE UPDATE sumatra_risk_inputs SET risk_score = score, scored = TRUE -- sparse update: writes just WHERE account_id = rec.account_id; -- these two columns END LOOP; COMMIT; -- per-batch durable checkpoint END LOOP; EXCEPTION WHEN ZERO_DIVIDE THEN STOP; -- bad denominator: stop, keep committed batches WHEN OVERFLOW THEN STOP; WHEN OTHERS THEN RAISE; -- anything unexpected: surface it loudly END; ``` What to notice: * The `UPDATE` here sets **two named columns** rather than `SET ROW` — a sparse update. Only those columns are written; everything else is untouched, and the read projects just the columns it needs. * On a fault, `STOP` discards only the in-flight batch and exits with code `2`. Already-committed batches remain a valid prefix — and because processed rows are flagged `scored = TRUE`, re-running the same program picks up exactly where it stopped. * `WHEN OTHERS THEN RAISE` is the recommended tail: anticipated faults stop gracefully, everything else stays loud. ## 8. A pipeline: the whole pass, once per slice A counted loop at the top level repeats an entire read → compute → write pass — here, settling each month in its own transaction. The loop variable is visible to the read's SQL as `PARAM('m')`. ```sql Tables theme={null} CREATE TABLE sumatra_settlements ( id BIGINT NOT NULL, month_no INT, amt NUMERIC(12,2), settled BOOLEAN, pass INT ) PRIMARY INDEX id; ``` ```sql settle_year.sumatra theme={null} -- Settle every month of the year, one transaction grain per month. BEGIN FOR m IN 1 .. 12 LOOP -- twelve passes: one month per iteration FOR batch IN (SELECT id, month_no, amt, settled, pass FROM sumatra_settlements WHERE month_no = CAST(PARAM('m') AS INT) -- the loop variable, AND settled = FALSE) -- bound per iteration ORDER KEY (id) BATCH SIZE 20000 LOOP FOR rec IN batch LOOP rec.settled := TRUE; rec.pass := m; -- in compute, m is an ordinary INT UPDATE sumatra_settlements SET ROW = rec WHERE id = rec.id; END LOOP; COMMIT; -- checkpoint inside the iteration END LOOP; END LOOP; -- a month with nothing pending is a END; -- clean zero-row pass ``` What to notice: * The pipeline body holds a **whole read block** — legal precisely because the loop is at the top level; the same loop inside a row loop would be in-memory compute, where a read is a compile error. * Each iteration's read binds the current `m` (published like any variable), so twelve passes each see only their own month's rows — and a month with nothing pending is a clean zero-row no-op. * The bound is the program's own (`1 .. 12`), never a per-row server call: twelve read-compute-write passes, each checkpointing per batch. * `rec.pass := m` uses the loop variable in compute — it is an ordinary read-only `INT` there. A `WHILE` pipeline works the same way, its predicate over carried variables a lookup can refresh — "repeat until the data says done". ## 9. Dynamic table names: one program, many targets A `%TABLE` parameter makes the *table name* a program input — the same logic run against interchangeable, shape-identical tables. ```sql Tables theme={null} CREATE TABLE sumatra_region_us ( id BIGINT NOT NULL, amt NUMERIC(12,2), flagged BOOLEAN ) PRIMARY INDEX id; CREATE TABLE sumatra_region_eu ( id BIGINT NOT NULL, amt NUMERIC(12,2), flagged BOOLEAN ) PRIMARY INDEX id; ``` ```sql flag_region.sumatra theme={null} -- Flag large amounts in whichever region table the run names. PARAM tgt sumatra_region_us%TABLE; -- compile against this table's shape; -- the run supplies the actual name BEGIN FOR batch IN (SELECT id, amt, flagged FROM PARAM('tgt') -- every use substitutes the runtime name WHERE flagged = FALSE) ORDER KEY (id) BATCH SIZE 10000 LOOP FOR rec IN batch LOOP IF rec.amt >= 1000 THEN rec.flagged := TRUE; UPDATE PARAM('tgt') SET ROW = rec WHERE id = rec.id; END IF; -- the captured write targets it too END LOOP; COMMIT; END LOOP; END; ``` ```bash theme={null} sumatra --dsn my.dsn @flag_region.sumatra sumatra_region_us sumatra --dsn my.dsn @flag_region.sumatra sumatra_region_eu ``` What to notice: * The declaration names a **reference table** (`sumatra_region_us`) — the program compiles against that shape; the run supplies the actual name, and a table whose shape drifted from the reference is refused at run start. * The runtime name must be a plain identifier (at most 128 bytes) — quotes, spaces, and punctuation are unspellable, so a dynamic name can only ever be what a static name could have been. * The name parameter works in the read's `FROM` and as the captured write's target — the two places a target table is named. ## Where to go deeper * [Programs and batches](/sumatra/programs) — the rules behind read blocks, write routing, and commit grains. * [Types, expressions, and control flow](/sumatra/language) — the full language reference, including records and keyed collections. * [Exceptions and recovery](/sumatra/errors) — the fault model in detail. * [Stored procedures](/sumatra/procedures) — turn any of these programs into a named, schedulable procedure. # Types, expressions, and control flow Source: https://docs.wirekite.io/sumatra/language The Sumatra language reference: the type system, literals, operators, NULL semantics, control-flow statements, records, and keyed collections. A Sumatra program contains two dialects. Inside a read block's parentheses and inside write statements you are writing **SQL** — the connected engine's own dialect (Firebolt, in these docs' examples), relayed verbatim. Between them, in the procedural middle, you are writing **Sumatra's compute dialect** — whose value semantics are deliberately identical to the engine's, down to rounding and overflow, so moving an expression between the two never changes the answer. ## Types | Type | What it is | Notes | | -------------- | --------------------------------- | ------------------------------------------------------------------------------------------------ | | `INT` | 32-bit signed integer | Overflow is a loud fault, never a wrap | | `BIGINT` | 64-bit signed integer | | | `NUMERIC(p,s)` | Exact decimal | Precision up to 38 | | `DOUBLE` | 64-bit IEEE float | Bit-exact to the engine; no NaN or Infinity — an operation that would produce one faults instead | | `REAL` | 32-bit IEEE float | | | `TEXT` | UTF-8 string | | | `BOOLEAN` | three-valued with NULL | | | `DATE` | `0001-01-01` through `9999-12-31` | | | `TIMESTAMP` | microsecond resolution | | | `BYTEA` | binary | Carry-only — see below | | `ARRAY` | engine array | Server-side carry only | Prefer the spellings `DOUBLE` and `REAL`. Firebolt's own `FLOAT` keyword is a 64-bit alias, so writing `FLOAT` invites confusion about width; the corpus convention is `DOUBLE` for 64-bit and `REAL` for 32-bit. **Carry vs. compute.** Every type can be *carried* — read from the engine and written back — as long as the value stays on the server side (a read column passed through `INSERT ... SELECT FROM batch`). Only the scalar types above the line participate in *compute* — in-memory expressions and variables. `BYTEA` and `ARRAY` cannot enter a row loop's in-memory record, and arithmetic on a carry-only type is a compile error, not a silent coercion. ## Literals * Integer literals are typed by magnitude: a value that fits in 32 bits is `INT`, otherwise `BIGINT`. Beyond 64 bits, write it in decimal form (`9300000000000000000.0`). Scientific notation is not accepted. * A literal with a decimal point is `NUMERIC` with the written scale (`4.00` is NUMERIC scale 2). * Strings are single-quoted: `'shipped'`. * Booleans are `TRUE` and `FALSE`. * Dates and timestamps: `DATE '2026-07-01'`, `TIMESTAMP '2026-07-01 12:30:00'`. * A NULL that needs a type is written `CAST(NULL AS T)`. ## Variables and assignment Assignment is `:=`; plain `=` is SQL's comparison and `SET` operator, used only inside SQL statements. ```sql theme={null} running := GREATEST(running + rec.delta, 0); rec.status := 'priority'; ``` Reading a variable before it has ever been assigned is a compile error. Assignment converts the value to the declared type; converting a float to an integer rounds half-even (`2.5` → `2`, `3.5` → `4`). ## Operators | Category | Operators | | ----------- | --------------------------------------------------------------------------------- | | Arithmetic | `+ - * /` and unary `-` | | String | `\|\|` (concatenation) | | Comparison | `= <> != < <= > >=`, `BETWEEN`, `LIKE`, `IS NULL`, `IS [NOT] DISTINCT FROM` | | Logic | `NOT AND OR` (operands must be BOOLEAN) | | Cast | `CAST(x AS T)` and `x::T` | | Conditional | `CASE` expressions — simple and searched | Precedence is conventional (`OR` \< `AND` \< `NOT` \< comparison \< additive \< multiplicative); parenthesize anything you would parenthesize in SQL. Inequality has two spellings — `<>` and `!=` — and they are one and the same operator from the lexer on. A `!` that is not part of `!=` is not Sumatra syntax. Chained comparison (`a = b = c`) is a parse error — parenthesize what you mean. A `CASE` **expression** selects a value and works anywhere a value does: ```sql theme={null} tax := rec.subtotal * CASE WHEN rec.country = 'US' THEN 0.00 WHEN rec.country = 'DE' THEN 0.19 ELSE 0.10 END; ``` ## Numeric semantics Sumatra's arithmetic is the bound engine's arithmetic, bit for bit — Firebolt's, in these docs' examples: * **Integers** are width-checked at every `+ - *` and every cast: `INT` math stays `INT` and faults with `OVERFLOW` past 32 bits; mixing widths promotes (`INT * BIGINT` is `BIGINT`). * **Decimals** follow the engine's strict typing: the result scale of `+ - * /` is the widest operand scale, precision grows to fit and is capped at 38, and exceeding it is a loud overflow. Multiplication and division are computed in a wide intermediate and rounded half-up to that scale. * **Floats** are IEEE 754 with no fused-multiply-add surprises. Mixing `DOUBLE` with `NUMERIC` or integers promotes to `DOUBLE`. A result that would be NaN or Infinity faults instead. * **Division by zero** faults with `ZERO_DIVIDE` — never NULL, never Infinity. One deliberate strictness: operands of `CASE` arms, `GREATEST`, and `LEAST` must share a type family. Mixing `TEXT` with a numeric or temporal operand is a compile error asking for an explicit `CAST`, where the engine alone would coerce at runtime and fault only on bad data. Casts that cross into or out of `TEXT` are not available in compute position — do text parsing and formatting in the read's SQL, where the engine's full conversion machinery applies. ## NULL semantics Sumatra uses SQL's three-valued logic, unchanged: * NULL propagates through operators and functions: `NULL + 1` is NULL, `NULL || 'x'` is NULL, comparisons with NULL are NULL. * Test with `IS NULL`, or compare null-safely with `IS [NOT] DISTINCT FROM`. * A condition that evaluates to NULL is not TRUE: an `IF` takes its ELSE path, and a capture filter skips the row. NULLs are restricted in exactly three places: `ORDER KEY` columns (a NULL key is a loud runtime error), keyed-collection keys (NULL never matches; a NULL-key probe raises `NO_DATA_FOUND`), and merge-key matching (a NULL key component never matches a target row). ## Control flow ```sql theme={null} IF rec.balance < 0 THEN ... ELSIF rec.flagged THEN ... ELSE ... END IF; ``` ```sql theme={null} CASE rec.band -- simple form: subject compared to each WHEN WHEN 3 THEN rec.grade := 'A'; WHEN 2 THEN rec.grade := 'B'; ELSE rec.grade := 'C'; END CASE; CASE -- searched form: first TRUE predicate wins WHEN rec.spend >= 100000 THEN rec.tier := 'platinum'; ELSE rec.tier := 'standard'; END CASE; ``` ```sql theme={null} WHILE i > 0 LOOP -- bounded, in-memory s := s + i; i := i - 1; END LOOP; FOR i IN 1 .. rec.n LOOP -- counted, ascending; i is a read-only INT ... END LOOP; ``` * `CONTINUE WHEN pred;` (or bare `CONTINUE;`) skips to the next iteration. * `EXIT WHEN pred;` (or bare `EXIT;`) leaves the innermost loop. Both also work at the batch-loop boundary itself — see [stopping a batched read early](/sumatra/programs#stopping-a-batched-read-early). * `RETURN;` ends the whole program cleanly (exit 0) from anywhere; writes persist only up to the last `COMMIT` that was reached. Every loop closes with `END LOOP;` — batch reads, row loops, counted loops, and `WHILE` alike. What a counted or `WHILE` loop's body may contain depends on where the loop stands: * **Inside a row loop (compute position):** the body is in-memory compute — a read block or a `COMMIT` inside it is a compile error by design, so a per-row server operation stays unwriteable. * **At the top level of the program:** the loop is a **pipeline** — its body takes the full top-level alphabet: whole read blocks, writes, lookups, and its own per-iteration `COMMIT`. See [pipelines](/sumatra/programs#pipelines-repeating-a-read-compute-write). ## Records Declare a record type explicitly, or derive one from a table. A record variable can be initialized with a positional literal — `ev := (1001, 'shipped', 25.00, CURRENT_TIMESTAMP);` — matched one-to-one against its field list (exact arity, each element converted to its field's type, a bare NULL taking the field's type); the literal form exists only in a `DECLARE` initializer. ```sql theme={null} DECLARE TYPE audit_rec IS RECORD ( order_id BIGINT, event TEXT, amount NUMERIC(14,2), logged_at TIMESTAMP ); ev audit_rec; row2 order_audit%ROWTYPE; -- shape = the table's columns, from the live catalog BEGIN ev.order_id := rec.order_id; ev.event := 'shipped'; ev.amount := rec.amount; ev.logged_at := CURRENT_TIMESTAMP; INSERT INTO order_audit VALUES ev; -- record shape must match the target row ``` The rows of a read (`rec` in `FOR rec IN batch`) are records too — their fields are the SELECT's columns, and they are assignable. ## Collections Sumatra's collection is the **keyed map**: a whole table (or filtered subset) loaded into memory once and probed by key — the lookup-table pattern. ```sql theme={null} DECLARE TYPE rate_map IS TABLE OF rate_dim%ROWTYPE INDEX BY tier; rmap rate_map; BEGIN SELECT tier, mult BULK COLLECT INTO rmap FROM rate_dim WHERE mult > 0; FOR batch IN (SELECT id, amount, tier, adjusted FROM txns) ORDER KEY (id) BATCH SIZE 20000 LOOP FOR rec IN batch LOOP rec.adjusted := rec.amount * rmap(rec.tier).mult; UPDATE txns SET ROW = rec WHERE id = rec.id; END LOOP; COMMIT; END LOOP; END; ``` * `INDEX BY` names the key column(s) of the element type — composite keys are supported (`INDEX BY wh, sku`), and the probe key can be a runtime-computed value, the one correlation no JOIN can express. * A probe on a missing key (or a NULL key) raises `NO_DATA_FOUND` — handleable like any fault. * The map is a read-only lookup: there is no iteration over a collection, and no `.COUNT`-style methods. It is resident in memory, so load dimensions, not fact tables. * Key columns may be integer, decimal, text, date, or timestamp — not float. For a single-row lookup without a map, `SELECT ... INTO` fetches scalars directly; zero rows raises `NO_DATA_FOUND`, and more than one row is a loud error: ```sql theme={null} SELECT mult INTO v_mult FROM rate_dim WHERE tier = 'gold'; ``` A lookup is one server round trip, so where it may stand is governed by how often it would repeat: at the top level (and inside a top-level `IF`/`CASE` arm, where it runs zero times or once), or directly in a batch loop's body — one re-fetch per batch. Inside a row, counted, or `WHILE` loop it is rejected: that would be a per-iteration server call. See [lookups inside the batch loop](/sumatra/programs#lookups-inside-the-batch-loop). ## Identifiers and names * Identifiers are ASCII: letters, digits, underscore, not starting with a digit. Case is not significant; the convention is UPPERCASE keywords and lowercase identifiers. * Table names are single bare identifiers — there is no `schema.table` qualification. A table or column whose name needs quoting in the engine can be reached by aliasing it inside the read's SQL. * Reserved words cannot name variables, types, record fields, parameters, or procedures, and the check is case-insensitive. Three groups are reserved: **every language keyword** (including the type names, `TRUE`/`FALSE`, `CURRENT_DATE`/`CURRENT_TIMESTAMP`, `STOP`, the exception names, and the reserved-for-future words `MERGE`, `FUNCTION`, `SCAN`, `FOLD`, `MAP`, `FILTER`, `COLLAPSE`); the **C++ keyword table**, adopted wholesale and frozen (so `class`, `template`, `new`, … are rejected — the error says "reserved word" either way); and any name starting with the **`__sumatra_`** prefix. The one deliberate non-reserved keyword is `BATCH`, so the canonical `FOR batch IN (...)` idiom can name its loop variable `batch`. # Limitations Source: https://docs.wirekite.io/sumatra/limitations What Sumatra deliberately rejects, what is absent from the current release, and the operational boundaries to plan around. Sumatra's design stance is that a limitation should be a **loud compile-time rejection with a named reason**, not a silent performance cliff or a wrong value discovered in production. This page collects the boundaries: permanent ones (rejected on principle), release ones (not in 0.2.0), and operational ones (true today, worth planning around). ## Permanent, by design These are not roadmap items — they define the execution model. * **No per-row server operations.** A per-row server query or write — the cursor-style pattern from OLTP databases — is inexpressible by grammar. All server interaction is batched. * **No nested read blocks**, and no read inside a row, counted, or `WHILE` loop in compute position. Decorrelate with a JOIN in the read, load the inner table as a [keyed collection](/sumatra/language#collections) and probe it, or — when the shape is genuinely "repeat a whole read → compute → write pass" — use a top-level [pipeline loop](/sumatra/programs#pipelines-repeating-a-read-compute-write), whose body legally contains read blocks and whose bound is the program's own (a counted range or a predicate over carried state), never a per-row server call. * **Chained comparison is a parse error.** `a = b = c` is rejected — parenthesize the comparison you mean. (The engine would parse it left-associatively; Sumatra is deliberately stricter.) * **`ORDER KEY` columns must be `INT`, `BIGINT`, or `TIMESTAMP`.** Floats are excluded on principle (float equality is unsound as a cursor); `DATE` is excluded because keyset pagination over a one-value-per-day key cannot make progress within a day. * **No text-crossing casts in compute.** `TEXT` → number or number → `TEXT` conversions belong in the read's SQL, where the engine's full conversion machinery (and error surface) applies. * **A write cannot change its own merge key.** `SET` of a key column, or a `SET ROW` matched on anything other than the record's own key field, is a compile error. * **One change per key per batch.** Duplicate writes to one merge key in a flush unit are a program error, surfaced loudly (repeated DELETEs excepted). * **Bare table names only.** No `schema.table` qualification, and engine identifiers must be usable unquoted — reach exotic names by aliasing them inside the read's SQL. Identifiers are ASCII. ## Not in this release Absent from 0.2.0; some are roadmapped, none are promised here: * **User-defined functions** (`FUNCTION` / `RETURN expr` are reserved words today). * **User-defined exceptions** — the catchable set is `ZERO_DIVIDE`, `OVERFLOW`, `NO_DATA_FOUND`, `OTHERS`. * **Iterating or aggregating a collection.** Keyed maps are probe-only lookups: no `FOR x IN map`, no `.COUNT`, no in-memory `SUM` over a map. Aggregate in the read instead. * **`BYTEA` and `ARRAY` in compute.** Both types carry fine through server-side statements; neither can enter an in-memory record. * **Regex, format masks, and transcendental math** in compute position (`REGEXP_*`, `TO_CHAR`/`TO_DATE`, `POWER`/`EXP`/`LN`/trig — `SQRT` is the exception). Use them in the read's SQL. * **Loop labels** (`EXIT` always exits the innermost loop) and procedure calling procedure. * **`EXEC` literal escaping** — a text argument containing a single quote cannot be passed. * **Reloading a keyed collection inside a batch loop.** `BULK COLLECT` runs at the top level (or a top-level arm): the map loads once. A per-batch reload is rejected while the replace-versus-accumulate question is open. Per-batch `SELECT INTO` scalar lookups are the supported re-fetch. * **A pipeline iteration must drain its own at-end read.** A read block inside a pipeline whose staged write-back would only be committed by a *later* iteration's `COMMIT` is rejected — commit each iteration's work in that iteration, or after the loop. ## Classic stored-procedure features deliberately not carried over For readers arriving from a classic procedural SQL dialect: explicit cursors and cursor attributes (`%FOUND`, `%NOTFOUND`, `%ROWCOUNT`), `FORALL`, `GOTO`, packages, overloading, autonomous transactions, `SAVEPOINT`, explicit `ROLLBACK` (a fault's rollback is automatic; graceful stops are the `EXCEPTION` block's job), dynamic SQL (`EXECUTE IMMEDIATE` — though a table *name* can be a program input; see [dynamic table names](/sumatra/programs#dynamic-table-names)), `%TYPE`, `CONSTANT`, and declaration `DEFAULT`/`NOT NULL` modifiers. `VARRAY`, nested tables, and `MULTISET` are replaced by the single keyed-map collection. ## Operational boundaries * **The backends are the new-class warehouses — Firebolt and Snowflake.** The toolchain is engine-neutral by construction — the DSN scheme declares the backend, and everything engine-specific lives behind per-backend profiles. The examples and the deepest proof in these docs run on Firebolt. * **Linux x86-64 only**, and compiling hosts need `g++`, `pkg-config`, and libcurl headers. (Hosts that only run cached stored procedures need none of that.) * **Compiling requires a live connection** — the connected database is the schema. The offline `sumatra-compile` tool works only against its built-in sample schema. * **`BATCH SIZE ALL` on a compute path holds the whole result in client memory.** A result that does not fit is a loud fault, not a spill. Chunk with `BATCH SIZE N` where results are large. * **Aggregating reads re-evaluate per chunk** under `BATCH SIZE N` — use `BATCH SIZE ALL` for `GROUP BY` sources. * **The `sumatra_` prefix is reserved** in target databases: the toolchain creates and drops `sumatra_stage_*` and `sumatra_stage_lock_*` tables and owns `sumatra_source`. It also reserves one staging column name on its own staging tables. There is no collision guard — keep your own objects off the prefix. * **DSN files are plaintext** — protect them with file permissions (`chmod 600`). There is no encrypted-DSN mechanism in this release. * **Concurrent identical runs are refused.** The same procedure with the same argument values will not start twice at once (a stale lock from a crashed run clears itself after a timeout). * **A dynamic table name is validated, not open-ended.** A `%TABLE` argument's runtime value must be a plain Sumatra identifier (lowercase word characters, at most 128 bytes) naming a table shape-identical to the declared reference table — anything else is refused before the run starts. * **The shell is one statement per line** — no multi-line input, no SQL passthrough. * **Shared host cache across accounts.** Two same-named databases on different Firebolt accounts share one per-host binary-cache directory; prefer distinct database names. * **One exotic cursor edge:** a row whose `ORDER KEY` value equals the exact type minimum (`INT`/`BIGINT` minimum, or timestamp `0001-01-01 00:00:00`) is never fetched by a chunked read. Real keys never live there; synthetic sentinel keys should not. ## Reading an error you did not expect Compile-time rejections name the rule that fired and, where one exists, the supported alternative — the error text is the documentation of first resort. If a program you believe should compile is rejected, check this page's permanent list first, then [Programs and batches](/sumatra/programs) for the structural rules (commit placement, `ORDER KEY` requirements, write shapes). # What is Sumatra? Source: https://docs.wirekite.io/sumatra/overview Sumatra is a procedural language for the new class of analytical warehouses — Firebolt and Snowflake: classic stored-procedure-style programs — loops, variables, conditionals, exceptions — compiled to native binaries that run batch-shaped SQL inside the engine. Sumatra is a procedural language for the database your data lives in. You write row-by-row logic — loops, variables, conditionals, exception handlers — around plain SQL reads and writes, and the toolchain compiles the program into a native binary that runs it against your database, batching reads and routing every write to the lightest correct SQL form automatically. The language is built for the **new class of analytical warehouse** — object storage beneath elastic, shared compute — and runs against **Firebolt and Snowflake**. The engine underneath is a profile, not a premise: the backend is declared per-database by the connection string, and the program's SQL surface is whatever the connected engine speaks. Firebolt is the concrete engine behind every example in this documentation — the proof runs deepest there. Here is a complete Sumatra program. It computes a per-customer running balance — each row's result depends on the previous row's result, the kind of logic SQL alone expresses only awkwardly: ```sql balance.sumatra theme={null} DECLARE running NUMERIC(14,2) := 0; last_customer BIGINT := NULL; BEGIN FOR batch IN (SELECT entry_id, customer_id, delta, running_balance FROM ledger) ORDER KEY (customer_id, entry_id) BATCH SIZE 50000 LOOP FOR rec IN batch LOOP IF rec.customer_id <> last_customer OR last_customer IS NULL THEN running := 0; last_customer := rec.customer_id; END IF; running := GREATEST(running + rec.delta, 0); rec.running_balance := running; UPDATE ledger SET ROW = rec WHERE entry_id = rec.entry_id; END LOOP; COMMIT; END LOOP; END; ``` No connection handling, no pagination code, no staging tables, no `MERGE` statements — the compiler produces all of that. The program reads in 50,000-row batches, carries `running` across every row and every batch in order, and commits each batch as a durable checkpoint. ## The problem it solves Modern analytical engines — Firebolt among them — deliberately ship no stored procedures and no procedural SQL dialect. Set-based SQL covers enormous ground, but the moment a pipeline needs a step that **carries state across rows**, **branches on a value the data just produced**, or **loops until a computed condition is met**, that step has to leave the database: a Python script here, a Spark job there, dbt orchestrating around the gap, and data movement stitching it together. Sumatra collapses that split. The procedural mid-work is written in one small language and executes as batch-shaped SQL on the engine itself, next to the set-based steps it belongs with. | Approach | What it gives you | Where it stops | | ---------------------- | ---------------------------------------------- | -------------------------------------------------------------------------------------------- | | The engine's SQL alone | Fast, distributed set transforms | No carried state, no runtime branching, no loops | | dbt | Orchestrated set steps | Control flow is compile-time templating, not runtime data | | Python / Spark | Full procedural power | Data leaves the platform; connections, batching, staging, and retries are all yours to build | | Sumatra | Procedural logic over batched reads and writes | Runs inside the database, in one language — the claim is the combination | The full case — what staying in-database saves you operationally, and what the batch and merge machinery buys you technically — is on [Why Sumatra](/sumatra/why). ## The mental model Every Sumatra program reduces to one shape: **Read → Compute → Write** * **Read** — pull rows from the engine in batches into memory. Never a per-row server query. * **Compute** — arbitrary in-memory work: loops, branches, carried variables, record and collection types. No server round-trips. * **Write** — push results back in batches. Never a per-row server write. The loop in the middle never touches the server — the engine receives `SELECT`s and `MERGE`s, nothing else. If you have written stored procedures in a classic procedural SQL dialect, the only real shift is this: **the grain is a batch of rows, not a single row**. Cursor-style row-at-a-time server access — natural on OLTP databases — is pathological on a distributed analytical engine, so Sumatra makes it inexpressible: the language's grammar has no way to write a per-row server call. In exchange, the batch machinery (pagination, ordering, staging, write-back, commit grain) is entirely the compiler's job, driven by two declarations on the read: `ORDER KEY` and `BATCH SIZE`. Beyond that frame, the language is deliberately the familiar stored-procedure idiom: `DECLARE`/`BEGIN`/`END`, `:=` assignment, `IF`/`ELSIF`, `CASE`, `WHILE`, `FOR` loops, records, `%ROWTYPE`, keyed collections, `EXCEPTION` handlers, explicit `COMMIT`. A handful of new words cover the batch boundary: `BATCH SIZE`, `ORDER KEY`, `PARAM`, `STOP`. ## How programs run The `sumatra` shell compiles a program **against the live catalog** of the connected database — the database itself is the schema — then generates native code, builds it with `g++` on your host, and runs it. The compiled program makes its own connection from the same DSN file and speaks batch-shaped SQL to the engine. Writes are routed, not written by hand: * A write that is already set-shaped (plain `UPDATE`/`DELETE`/`INSERT ... SELECT`) runs server-side as-is — rows never leave the engine. * Per-row writes captured inside a loop are staged and applied as one set-based `MERGE` per batch. You never write `MERGE` or manage staging tables yourself. Programs run one-shot from a file (`@prog.sumatra`), or are stored in the database as [named procedures](/sumatra/procedures) and run with `EXEC` — compiled once, cached per host, and automatically recompiled when the source, the toolchain, or the table schemas change. ## Semantics you can trust Sumatra's answer for what a program *means* is deliberately boring: it means what the engine underneath means. Values, types, rounding, overflow, NULL handling — the in-memory evaluator is bit-exact to the bound engine's own semantics (Firebolt's, in these docs' examples), so moving a computation between the read SQL and the procedural middle never changes the answer, and a program never invents behavior the engine does not have. Three properties are worth calling out: * **Determinism.** A compute program's result is declared-order deterministic: `ORDER KEY` fixes a strict total order, state carries across batch boundaries, and the answer is invariant under `BATCH SIZE`. An order tie or a NULL key at runtime is a loud error, never a silent skip or duplicate. * **Loud failure.** Overflow, division by zero, and lossy surprises are errors, never silently wrong values. Committed batches always survive a fault as a durable prefix; recovery is explicit and yours. * **Honest rejection.** A program the model cannot run well — a nested read, a per-row server op, an unbounded server-dependent loop — is rejected at compile time with a named reason. The failure mode is a compile error, not a production performance cliff. ## Status at a glance | | | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Current version | 0.2.0 | | Platform | Linux x86-64 | | Backends | The new class of analytical warehouse — **Firebolt and Snowflake**. The DSN scheme declares the backend per database; the examples in these docs run on Firebolt | | Toolchain | `sumatra` (shell) and `sumatra-compile` (offline inspector), plus `g++` on your host | | Distribution | A single tarball; no dependencies beyond the C++ toolchain and libcurl | Sumatra is built by the Wirekite team and documented here, but it is a **standalone product**: it is not part of the Wirekite replication pipeline, is not invoked by Wirekite, and nothing in this section depends on Wirekite in any way. ## Reading order The section is laid out like a book — read it front to back: 1. [Why Sumatra](/sumatra/why) — the case for in-database transformation, and the batch and merge engines in depth. 2. [Quickstart](/sumatra/quickstart) — install, connect, and run your first two programs. 3. [Types, expressions, and control flow](/sumatra/language) — the language itself: variables, operators, conditionals, loops, records, and keyed collections. 4. [Programs and batches](/sumatra/programs) — Sumatra's own layer on top: the program skeleton, batched reads, write routing, commit grains and transactions, then pipelines and dynamic table names. 5. [Exceptions and recovery](/sumatra/errors) · [Stored procedures](/sumatra/procedures) — faults, restarts, and shipping programs as named, scheduled procedures. 6. [Learning by example](/sumatra/examples) — nine complete programs, graded from the smallest possible to pipelines and dynamic targets. 7. Reference: [The sumatra shell](/sumatra/shell) · [Built-in functions](/sumatra/builtins) · [Limitations](/sumatra/limitations). # Stored procedures Source: https://docs.wirekite.io/sumatra/procedures Name a program, store it in the database, and run it from anywhere with EXEC — compiled once per host, with automatic recompiles when source, toolchain, or schema change. A file submitted with `@` is compile-and-run: nothing persists. A **stored procedure** is the persistent form — the same program, named, stored **in the target database itself**, and runnable from any host with `EXEC name(...)`. Procedures are how scheduled and repeated work ships: compile once, run forever. ## Writing a procedure A procedure file is the `CREATE` statement itself: ```sql flag_big_orders.sumatra theme={null} CREATE OR REPLACE PROCEDURE flag_big_orders(cutoff INT) IS BEGIN FOR batch IN (SELECT order_id, customer_id, amount, status, order_date, region FROM sumatra_orders WHERE status = 'pending' AND amount >= CAST(PARAM('cutoff') AS INT)) ORDER KEY (order_id) BATCH SIZE 10000 LOOP FOR rec IN batch LOOP rec.status := 'priority'; UPDATE sumatra_orders SET ROW = rec WHERE order_id = rec.order_id; END LOOP; COMMIT; END LOOP; END; ``` The form differs from an anonymous block in three small ways: * The header is `CREATE OR REPLACE PROCEDURE name(arg TYPE, ...) IS`. Write the parentheses only when there is at least one argument — a zero-argument procedure has no `()` in its header. * Declarations come **bare between `IS` and `BEGIN`** — a procedure has no `DECLARE` keyword. * It closes with plain `END;` (not `END name;`). Arguments are positional, read-only inputs, exactly like `PARAM` declarations: reference them inside SQL as `PARAM('cutoff')`, casting non-text values at the point of use. There are no `OUT` arguments, no defaults, and no named-argument calls. A `PARAM` section inside a procedure is not allowed — the header replaces it. `RETURN;` anywhere in the body ends the run cleanly (exit 0); work committed before the `RETURN` stays committed. ## Storing it Submit the file like any other: ```text theme={null} sumatra> @flag_big_orders.sumatra [sumatra] procedure flag_big_orders created (procid 4f2a91be00c17d55) ``` Because the file's program is a `CREATE`, submitting it **stores** instead of running: the shell compiles it against the live catalog, builds it, saves the source in the database, and caches the binary on this host. Nothing executes, and a `CREATE` submission takes no arguments — argument values belong to `EXEC`. A compile error stores **nothing**. There is no "invalid procedure" state to discover at 3 a.m.: if it is stored, it compiled. ## Running it ```text theme={null} sumatra> EXEC flag_big_orders(500) Completed (exit 0) ``` `EXEC` rules: * Parentheses always — `EXEC nightly()` is the zero-argument call. * Arguments are positional literals: bare tokens (`42`, `3.14`, `2026-01-01`, `TRUE`) or single-quoted text (`'North America'`). A text value containing a quote cannot be passed in this release. * No trailing semicolon — `EXEC` is one shell statement. From a script or cron, use the one-shot form; the exit code is the run's outcome (`0` / `2` / `1`): ```bash theme={null} # crontab: reprioritize nightly at 02:00 0 2 * * * /usr/local/bin/sumatra --dsn /etc/sumatra/prod.dsn "EXEC flag_big_orders(500)" ``` ## Where things live | Location | What | Notes | | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | `sumatra_source` table, in the target database | One row per procedure: `name`, `source`, `procid`, `updated_at` | The database is the single source of truth; any SQL client can `SELECT` from it to list procedures | | `~/.sumatra/bin//` on each host | Cached compiled binaries, named `--`, with the generated `.cpp` beside each for inspection | Purely a cache — safe to delete; the next `EXEC` recompiles from stored source | Because the source lives in the database, a procedure stored from your laptop runs from the production cron host with nothing copied around — the first `EXEC` there compiles it locally and caches the binary. ## When recompiles happen A normal `EXEC` runs the cached binary with **zero** compilation. Recompiles happen only for four reasons, and each is announced: ```text theme={null} [sumatra] compiling flag_big_orders (first run on this host) [sumatra] compiling flag_big_orders (source changed) [sumatra] compiling flag_big_orders (sumatra upgraded to 0.2.0) [sumatra] compiling flag_big_orders (schema changed) ``` The last one deserves a note: every compiled program bakes in a fingerprint of the table shapes it was compiled against, and re-checks it at run start. If the schema drifted since compile, the binary refuses to run on stale assumptions; the shell then recompiles the stored source against the current schema and reruns — once. If the fresh compile refuses again, the schema is changing underfoot and the run stops loudly. ## Managing procedures ```text theme={null} sumatra> DROP PROCEDURE flag_big_orders [sumatra] procedure flag_big_orders dropped ``` `DROP PROCEDURE` removes the database row and this host's cache entries. Dropping a name that does not exist is an error, never a silent no-op. To change a procedure, just submit the edited `CREATE OR REPLACE` file again — replace is last-write-wins. A few operational notes: * **Procedures do not call procedures.** `EXEC` is a shell statement, not a language statement — composition is sequencing several `EXEC` lines in your script. * **Duplicate runs are refused.** Two concurrent runs of the same procedure with the same argument values are refused via an engine-side lock marker, so a cron overlap cannot double-apply. * **The cache key is the database name.** If two different Firebolt accounts have same-named databases, they share a host cache directory — use distinct database names (or hosts) to keep them apart. # Programs and batches Source: https://docs.wirekite.io/sumatra/programs The anatomy of a Sumatra program: parameters, declarations, the batched read block, write routing, commit grains, transactions, and pipelines. A Sumatra program is a single file. Two kinds exist: the **anonymous block** (run one-shot with `@file.sumatra`) and the **stored procedure** (the same body wrapped in `CREATE OR REPLACE PROCEDURE`, covered in [Stored procedures](/sumatra/procedures)). This page walks the anonymous block top to bottom. ```sql theme={null} -- comments run to the end of the line; /* block comments */ also work PARAM run_date DATE; -- program inputs (optional section) DECLARE -- variables and types (optional section) total NUMERIC(14,2) := 0; BEGIN ... -- the body: reads, writes, compute EXCEPTION -- fault handlers (optional section) WHEN ZERO_DIVIDE THEN STOP; WHEN OTHERS THEN RAISE; END; ``` Every statement ends with `;`. The corpus convention is UPPERCASE keywords and lowercase identifiers; identifier case is not significant. ## PARAM: program inputs ```sql theme={null} PARAM want_region TEXT; PARAM want_date DATE; ``` Parameters are declared before the body, one per line, and their values arrive on the command line in declaration order: ```bash theme={null} sumatra --dsn my.dsn @rollup.sumatra "North America" 2026-07-01 ``` A parameter is referenced **only inside SQL** — reads and write statements — as `PARAM('name')`, and it is bound out-of-band as a real query parameter, never substituted into the SQL text: ```sql theme={null} FOR batch IN (SELECT grp, SUM(amt) AS amt FROM sales WHERE region = PARAM('want_region') AND sale_date = CAST(PARAM('want_date') AS DATE) GROUP BY grp) BATCH SIZE ALL ``` Two rules follow from that design: * A non-`TEXT` parameter needs an explicit cast at the point of use: `CAST(PARAM('want_date') AS DATE)`. * A bare `want_date` in compute code is an undeclared-variable error — parameters are read-only inputs to your SQL, not variables. The one compute-side position where `PARAM('name')` is legal is a `DECLARE` initializer (`cutoff NUMERIC(12,2) := PARAM('cutoff');`), where it takes the declared type with no cast — the idiom for seeding a carried variable from a program input. ### Your variables are visible to your SQL `PARAM('name')` resolves against more than the declared parameters: **every declared scalar variable is published into every server statement's bind list**, under its own (lowercase) name. A read or a write statement can therefore filter on a value the program computed earlier in the run: ```sql theme={null} DECLARE wm DATE; BEGIN SELECT MAX(loaded_day) INTO wm FROM rollup_target; FOR batch IN (SELECT day, SUM(amt) AS amt FROM sales WHERE day > CAST(PARAM('wm') AS DATE) -- the variable, not an argument GROUP BY day) BATCH SIZE ALL LOOP ... END LOOP; COMMIT; END; ``` That is the **watermark pattern**: derive a cursor from the target, filter the next read by it, advance it as part of the run — an incremental job with no command-line arguments at all. The rules: * The binding is per-execution: a variable that is unset or NULL at the moment a statement runs is simply absent from that statement's binds, and referencing it then is the engine's own loud "parameter was not set" error — never a silent NULL. * `PARAM()` returns text, so a non-text variable is read back with a cast, exactly like an argument. * A variable may not share a name with a declared `PARAM` or procedure argument — that collision is a compile error. ## DECLARE: variables and carried state ```sql theme={null} DECLARE running NUMERIC(14,2) := 0; last_customer BIGINT := NULL; ``` Variables are **program-scoped**: they carry across rows, across batches, and across sequential read blocks — nothing ever resets them implicitly. That is what makes multi-pass and running-state programs natural to write. Initializers are optional, but reading a variable before it has ever been assigned is a compile error (definite-assignment analysis, the same rule as Java or Rust) — never a silent NULL. Give accumulators an explicit `:= 0`. An initializer may also be `PARAM('name')` (typed by the declaration), and a record variable takes a positional literal — see [records](/sumatra/language#records). `DECLARE` is also where record and collection types live — see [records and collections](/sumatra/language#records). ## The read block All row input comes through one construct: ```sql theme={null} FOR batch IN (SELECT ...) -- any SELECT the engine accepts, relayed verbatim ORDER KEY (col1, col2) -- strict total order (when required — see below) BATCH SIZE 50000 -- chunk size, or ALL LOOP ... -- the batch body END LOOP; ``` The parenthesized SELECT is **opaque**: Sumatra relays it to the engine byte-verbatim and learns its column names and types at compile time from the live database. Filter, join, aggregate, use window functions — anything the engine accepts is fine, and any of the engine's functions may appear inside it. Under `BATCH SIZE N` with a row loop and a per-batch `COMMIT`, each cycle of the loop is one round of this conversation: ```mermaid theme={null} sequenceDiagram participant P as Compiled program
(client memory) participant E as Engine loop until the read is exhausted P->>E: keyset SELECT — the next N rows, in ORDER KEY order E-->>P: one batch, into memory Note over P: compute the batch —
row loop, branches, carried state P->>E: stage + one MERGE (the captured writes) P->>E: COMMIT — this batch is a durable checkpoint end ``` ### BATCH SIZE `BATCH SIZE` is mandatory on every read and sets the working grain: * `BATCH SIZE N` — fetch the result in chunks of up to N rows, using keyset pagination over the `ORDER KEY` (the same `WHERE key > last ... LIMIT N` pattern you would hand-write). Each batch is processed and written as a unit, and memory stays bounded at N rows. * `BATCH SIZE ALL` — one whole-set batch, evaluated once. This is the right choice for aggregating reads (a `GROUP BY` source re-evaluates per chunk under `BATCH SIZE N`) and for order-independent bodies. On the client-compute path the whole set is held in memory. An empty read is a clean no-op: the loop body runs zero times and the program continues. ### ORDER KEY `ORDER KEY (...)` declares a strict total order over the read. It is required when: * `BATCH SIZE N` chunks the read (the key is the pagination cursor), or * the body is order-dependent — carried state that must see rows in a specific sequence — at any batch size, or * the loop is a writing client-compute loop. It may be omitted only for order-independent, whole-set (`ALL`) work. Key columns must be `INT`, `BIGINT`, or `TIMESTAMP` (composite keys are fine, e.g. `ORDER KEY (customer_id, entry_id)`). The order must actually be strict: a duplicate key value or a NULL in a key column at runtime is a loud error — never a silently skipped or double-processed row. ### Row loops and batch statements Inside the batch body you either iterate rows in memory: ```sql theme={null} FOR rec IN batch LOOP rec.total := rec.qty * rec.price; -- rec's fields = the SELECT's columns UPDATE orders SET ROW = rec WHERE order_id = rec.order_id; END LOOP; ``` or reference the batch **as a set** in SQL statements (no row loop), which keeps the work server-side: ```sql theme={null} INSERT INTO order_totals (id, total) SELECT id, qty * price FROM batch; ``` Reads do not nest: one read block inside another is a compile error (join or use a [keyed collection](/sumatra/language#collections) instead), and a read cannot appear inside a row, counted, or `WHILE` loop in compute position. Sequential read blocks are fine and share carried variables — the two-pass pattern — and a **top-level** counted or `WHILE` loop may contain whole read blocks: that is the [pipeline](#pipelines-repeating-a-read-compute-write). ### The batch body beyond the row loop The batch-loop body is not limited to one row loop plus a `COMMIT`. It also accepts assignments over carried variables, `IF`/`CASE` statements, counted and `WHILE` loops (in-memory compute), a bare `RETURN;`, and per-batch lookups — so per-batch setup, per-batch decisions, and a gated checkpoint are all expressible in place: ```sql theme={null} FOR batch IN (SELECT id, amt, ok FROM feed) ORDER KEY (id) BATCH SIZE 10000 LOOP batch_total := 0; -- per-batch reset (carried scalar) FOR rec IN batch LOOP batch_total := batch_total + rec.amt; UPDATE feed SET ok = TRUE WHERE id = rec.id; END LOOP; IF batch_total > 0 THEN COMMIT; -- gated checkpoint: a batch that fails END IF; -- its gate is discarded, not committed END LOOP; ``` Two walls hold inside the batch body: `rec` fields exist only inside the row loop (between batches there is no current row), and a counted or `WHILE` loop *here* is still in-memory compute — no writes, reads, or `COMMIT` inside it. On the server-side route (no row loop) the per-chunk `COMMIT` is the chunk's transaction bracket and must remain unconditional. ### Lookups inside the batch loop A `SELECT ... INTO` may stand directly in the batch body — a **per-batch scalar re-fetch**, one extra round trip per batch (never per row): ```sql theme={null} FOR batch IN (SELECT id, amt FROM feed) ORDER KEY (id) BATCH SIZE 50000 LOOP SELECT cutoff INTO v_cutoff FROM control WHERE k = 1; -- re-read once per batch FOR rec IN batch LOOP ... END LOOP; COMMIT; END LOOP; ``` Position is meaning: before the row loop, the fresh value feeds that batch's compute; after the `COMMIT`, it reads the batch's committed state. On the server-side route the lookup runs inside the chunk's transaction and sees the chunk's own uncommitted writes. A miss raises `NO_DATA_FOUND` as usual — the committed prefix stays. (`BULK COLLECT` does not join it: a keyed map loads once, at the top level.) ### Stopping a batched read early `EXIT` and `CONTINUE` (optionally `WHEN pred`) work at the batch-loop boundary itself on the client-compute route with `BATCH SIZE N`: `EXIT` stops pulling batches; `CONTINUE` skips to the next batch. The predicate is evaluated over carried variables between batches: ```sql theme={null} FOR batch IN (SELECT id, delta, applied FROM changes) ORDER KEY (id) BATCH SIZE 10000 LOOP FOR rec IN batch LOOP seen := seen + 1; rec.applied := TRUE; UPDATE changes SET ROW = rec WHERE id = rec.id; END LOOP; COMMIT; EXIT WHEN seen >= 100000; -- after the checkpoint: this batch is durable END LOOP; ``` Placement against the in-body `COMMIT` decides the in-flight batch's fate: an `EXIT` before it rolls that batch back (prior batches stay durable); after it, the batch is committed first. On the server-side route, and at `BATCH SIZE ALL` (one whole-set batch — nothing to stop), batch-boundary `EXIT`/`CONTINUE` are compile errors; gate the whole read with `IF ... THEN END IF;` instead. ## How writes are routed You write only natural `UPDATE`, `INSERT`, and `DELETE`. The compiler routes each write to the lightest correct SQL form — there is no routing keyword, and you never write `MERGE`, `COPY`, or staging tables: | You write | Where it runs | | ----------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | A top-level set statement (`UPDATE ... WHERE`, `DELETE ... WHERE`, `DELETE ... USING`, `INSERT ... SELECT`) | Server-side, as-is — rows never leave the engine | | A statement referencing `batch` as a set (`... FROM batch`, `WHERE k = batch.k`) | Server-side, correlated to the batch | | Per-row writes on `rec` inside a row loop | Captured in memory, staged, and applied as **one set-based MERGE per batch** | ```mermaid theme={null} flowchart TD S["You write UPDATE / INSERT / DELETE"] --> Q1{"References rec.*
fields from a row loop?"} Q1 -- yes --> ST["Captured in memory → staged →
one op-tagged MERGE per batch"] Q1 -- no --> Q2{"References batch
as a set?"} Q2 -- yes --> CO["Server-side, correlated:
MERGE-from-subquery / UPDATE…FROM"] Q2 -- no --> PL["Server-side, exactly as written:
plain set-DML"] ``` The per-row forms and their rules: ```sql theme={null} -- Full-row write-back: writes every column except the matched key UPDATE orders SET ROW = rec WHERE order_id = rec.order_id; -- Sparse update: writes only the SET columns; untouched columns are preserved, -- and the read may project just a subset of the target's columns UPDATE accounts SET balance = rec.balance + 10 WHERE id = rec.id; -- Append: INSERT inside a row loop takes VALUES (a record, or a column list) INSERT INTO audit VALUES ev; INSERT INTO installments (invoice_id, seq, amount) VALUES (rec.invoice_id, i, per); -- Delete DELETE FROM accounts WHERE customer_id = rec.customer_id; ``` A program may mix them — an `IF` that deletes one row, updates another, and inserts a third produces a single op-tagged change set applied by one MERGE. The **merge key** is whatever the write's `WHERE` equates with the record's own fields — a single column or a composite AND-chain (`WHERE wh = rec.wh AND sku = rec.sku`). Any extra non-key condition on `rec` fields acts as a **capture filter**: the change is captured only when it is TRUE (`WHERE id = rec.id AND rec.qty > 0` skips non-positive rows). Three rules the compiler holds you to: * A write may not change its own key: `SET` of a merge-key column, or a `SET ROW` matched on anything but the record's own key field, is a compile error. * One change per key per flush: writing the same key twice in one batch is a program error. Statically visible cases are compile errors; data-dependent duplicates surface as the engine's own MERGE cardinality error at runtime (catchable with `WHEN OTHERS`). Repeated DELETEs of the same key are idempotent and allowed. * An upsert is written as its two natural statements — an accumulate `UPDATE` plus a complement `INSERT ... WHERE key NOT IN (...)` — and both run server-side; together they behave as the upsert. ## COMMIT: placement is meaning `COMMIT` is always explicit — Sumatra never commits behind your back — and **where** you put it defines the transaction grain. There are three grains: ```sql theme={null} -- Per-batch grain: each batch commits as soon as it is written. FOR batch IN (...) ORDER KEY (id) BATCH SIZE 10000 LOOP FOR rec IN batch LOOP ... END LOOP; COMMIT; -- durable checkpoint per batch END LOOP; -- At-end grain: nothing is durable unless the whole program succeeds. FOR batch IN (...) ORDER KEY (id) BATCH SIZE 10000 LOOP FOR rec IN batch LOOP ... END LOOP; END LOOP; COMMIT; -- one all-or-nothing transaction -- Per-iteration grain: inside a top-level pipeline loop, each -- iteration's COMMIT closes that iteration's work (see Pipelines). FOR d IN 1 .. 31 LOOP ... -- reads and writes for one slice COMMIT; END LOOP; ``` Per-batch commits give you bounded memory and a **durable prefix**: if the program faults on batch 40, batches 1–39 stay committed, and a re-run picks up the remainder (see [Exceptions and recovery](/sumatra/errors)). The at-end grain trades that for all-or-nothing atomicity. The compiler enforces coherence: * A write with no `COMMIT` reachable downstream on *any* path is a compile error — there is no implicit commit to fall back on. (A `COMMIT` that exists but sits behind a runtime gate is legal — see below.) * `COMMIT` cannot appear inside a row loop, or inside a counted/`WHILE` loop in compute position — per-row commits are inexpressible by grammar. At the top level of a pipeline loop it is the per-iteration grain. * A server-side read at `BATCH SIZE N` must commit in the batch body, unconditionally — that `COMMIT` is each chunk's transaction bracket. Writes persist **iff control reaches a `COMMIT`**: a fault or crash rolls back the open transaction while every already-committed batch survives. On Firebolt, transactions are ACID and snapshot-isolated, so readers never see a half-written batch. ### How top-level statements share a transaction Top-level statements execute **eagerly, at their body position, in one open transaction**: the first write opens it, every later statement — including an interleaved `SELECT INTO` or `BULK COLLECT` — runs inside it and **sees the transaction's own uncommitted writes**, and your explicit `COMMIT` closes it. A fault or a `RETURN` before the `COMMIT` rolls the whole open transaction back. A `COMMIT` with nothing open is a legal no-op. The open transaction flows through structure rather than fencing it: * An `IF`/`CASE` is spanned as plain control flow — the arms inherit the transaction state, and writes and `COMMIT` are legal *inside* an arm. A gated commit (`IF ok THEN COMMIT; END IF;`) is a valid construct: on the run where the gate is false, the tail of the transaction simply rolls back at `END` — the same discard an early `RETURN` has always meant. Lookups in an arm run zero times or once, and a miss behind a false gate is not a fault. * A batch loop that starts while a transaction is open **joins it on batch 1**: the first batch's `COMMIT` commits the pending write(s) together with that batch, and later batches bracket per batch as usual. One consequence to know: if the read matches **zero rows**, the loop's `COMMIT` never fires — a pending earlier write then rolls back at `END` unless a later explicit `COMMIT` commits it. ## Pipelines: repeating a read-compute-write A counted or `WHILE` loop **at the top level of the program** is a **pipeline**: its body takes the full top-level alphabet — whole read blocks, writes, lookups, nested `IF`/`CASE`, and its own `COMMIT` — and runs once per iteration. This is the shape for "do the whole pass once per month / per region / until the backlog is drained": ```sql theme={null} -- Settle each month of the year in its own transaction. BEGIN FOR m IN 1 .. 12 LOOP -- m is the loop's own variable (a declared -- variable of the same name would collide) FOR batch IN (SELECT id, amt, settled, pass FROM settlements WHERE month_no = CAST(PARAM('m') AS INT) -- the loop variable, bound per iteration AND settled = FALSE) ORDER KEY (id) BATCH SIZE 20000 LOOP FOR rec IN batch LOOP rec.settled := TRUE; rec.pass := m; UPDATE settlements SET ROW = rec WHERE id = rec.id; END LOOP; COMMIT; -- per-batch inside the iteration END LOOP; END LOOP; END; ``` The rules that make pipelines predictable: * **The loop variable is visible to the body's SQL** as `PARAM('')` — bound per iteration like any published variable. It may not collide with a declared parameter or variable name. * **Loop bounds re-evaluate every iteration**, and a `WHILE` pipeline's predicate is over carried variables — which a per-batch or top-level lookup can update, so "repeat until the data says done" is written as a `WHILE` over a value the program re-reads each pass. * **A `COMMIT` in the pipeline body is the per-iteration grain**: it closes that iteration's transaction (and drains that iteration's staged write-backs). An at-end read whose staged write-back would only be committed by a *later* iteration is a compile error — each iteration settles its own work. * **`EXIT` / `CONTINUE` at pipeline level** bind to the pipeline loop — the innermost-loop rule, unchanged. * The grain is honest: N iterations mean N read-compute-write passes — the bound is the program's own (a range or a predicate over carried state), never a per-row server call. ## Dynamic table names A program can take a **table name** as an input — same logic, different target table per run — with a `%TABLE` parameter (or procedure argument): ```sql theme={null} PARAM tgt daily_rollup%TABLE; ``` The declaration names a **reference table** (`daily_rollup`): the program compiles against that table's shape, and at run time the argument supplies the actual name. Every `PARAM('tgt')` of a `%TABLE` parameter is a substitution of that name — the opposite treatment from a value parameter, decided by the declaration, never by position: ```sql theme={null} FOR batch IN (SELECT id, amt FROM PARAM('tgt') WHERE day = CAST(PARAM('d') AS DATE)) ORDER KEY (id) BATCH SIZE 20000 LOOP FOR rec IN batch LOOP ... UPDATE PARAM('tgt') SET amt = rec.amt WHERE id = rec.id; END LOOP; COMMIT; END LOOP; ``` The guardrails that keep this safe: * The runtime name must be a plain identifier (lowercase word characters, at most 128 bytes). Quotes, spaces, dots, and semicolons are unspellable — a dynamic name can be anything a static name could have been, and nothing more, which closes off injection by construction. * At run start the actual table's shape is checked against the reference table's compiled shape; a drifted table is refused, never run against stale assumptions. * A name parameter may appear in the opaque read's `FROM`/`JOIN` and as the target of a row loop's captured `UPDATE`/`INSERT`/`DELETE`. Everywhere else — a value position, a top-level set-statement target — it is a compile error. ## What the compiler manages in your database Two pieces of engine-side plumbing exist so you know what they are: * **Staging tables** — client-computed changes land in a per-run scratch table named `sumatra_stage_...` before the MERGE applies them. They are created, truncated, and dropped automatically; a crashed run's orphan is reclaimed by the next run of the same program. A companion `sumatra_stage_lock_...` marker refuses two concurrent runs of the same program with the same parameters. * **`sumatra_source`** — the stored-procedure catalog table (only created once you store a procedure). Treat the `sumatra_` name prefix as reserved for the toolchain in databases you point Sumatra at. ## Program lifecycle A run finishes in exactly one of three states, surfaced as the process exit code: `0` completed, `2` stopped by a handler with the committed prefix retained, `1` error. There is no automatic retry or resume — re-running a program is always your action, and the standard idiom is to make the read re-runnable (`WHERE processed = FALSE`, flipping the flag as part of each row's write) so a re-run continues where the committed prefix ends. # Quickstart Source: https://docs.wirekite.io/sumatra/quickstart Install the Sumatra toolchain, connect to a Firebolt database, and write and run your first two programs. This page takes you from an empty Linux host to two working Sumatra programs against your own Firebolt database: first the smallest possible program (pure set-DML), then the canonical read → compute → write shape that most real programs use. ## Prerequisites * A **Linux x86-64** host. This is the only packaged platform today. * A **Firebolt** database you can write to, plus a service account (client id and secret) and your account name. This quickstart — like every example in these docs — runs against Firebolt, the engine where Sumatra's proof runs deepest. * A C++ toolchain. Sumatra compiles each program into a small native binary **on your host**, so it needs `g++` (C++17), `pkg-config`, and the libcurl development headers: ```bash Debian / Ubuntu theme={null} sudo apt-get install g++ pkg-config libcurl4-openssl-dev ``` ```bash RHEL / Fedora theme={null} sudo dnf install gcc-c++ pkgconf-pkg-config libcurl-devel ``` The toolchain is only exercised when something actually compiles. A host that only runs already-compiled stored procedures from its cache never needs `g++` installed. ## Install Sumatra ships as a single tarball, `sumatra--linux-amd64.tar.gz`. Unpack it and run it in place: ```bash theme={null} tar xzf sumatra-0.2.0-linux-amd64.tar.gz cd sumatra-0.2.0-linux-amd64 ./sumatra --version # sumatra 0.2.0 ``` To put `sumatra` on your PATH, **symlink** it — do not copy the binary out of the directory: ```bash theme={null} mkdir -p ~/.local/bin ln -s "$PWD/sumatra" ~/.local/bin/sumatra ``` The `runtime/` and `exec/` directories must stay next to the real `sumatra` binary — they hold the headers and the I/O layer that every compiled program is built with. The tool resolves symlinks to find them, which is why a symlink works and a copied binary does not. ## Create a DSN file The shell connects with a **DSN file**: a plain text file containing one connection string. Create `my.dsn`: ```text my.dsn theme={null} firebolt:///?account_name=&client_id=&client_secret=&engine= ``` * `` — the Firebolt database to run against. Required: programs and stored procedures live per-database. * `account_name`, `client_id`, `client_secret` — your Firebolt account and service-account credentials. * `engine` — optional; omit it to use the system engine. The file holds a credential, so protect it: ```bash theme={null} chmod 600 my.dsn ``` ## Create a table to work on Run this in your Firebolt database (SQL workspace or any client) — the same table the programs in [Learning by example](/sumatra/examples) build on: ```sql theme={null} CREATE TABLE sumatra_sessions ( session_id BIGINT NOT NULL, state TEXT, last_seen TIMESTAMP ) PRIMARY INDEX session_id; INSERT INTO sumatra_sessions VALUES (1, 'active', CURRENT_TIMESTAMP - INTERVAL '30' HOUR), (2, 'active', CURRENT_TIMESTAMP - INTERVAL '1' HOUR), (3, 'expired', CURRENT_TIMESTAMP - INTERVAL '72' HOUR); ``` ## Your first program Sumatra source lives in files, conventionally with a `.sumatra` extension. Create `expire.sumatra`: ```sql expire.sumatra theme={null} -- Expire sessions that have been idle for more than 24 hours. BEGIN UPDATE sumatra_sessions SET state = 'expired' WHERE state = 'active' AND last_seen < CURRENT_TIMESTAMP - INTERVAL '24' HOUR; COMMIT; END; ``` Reading it line by line: * `--` starts a comment, to the end of the line. * `BEGIN ... END;` brackets the program body. There are no variables here, so no `DECLARE` section is needed. * The `UPDATE` is plain SQL in Firebolt's own dialect. A write that is already set-shaped stays set-shaped — Sumatra runs it server-side as-is and adds no machinery around it. * `COMMIT;` ends the transaction. Commits are always explicit in Sumatra — where you place `COMMIT` defines exactly what becomes durable together. * Every statement ends with `;`, including the final `END;`. ## Run it Point the shell at your DSN file and submit the file with `@`: ```text theme={null} $ sumatra --dsn my.dsn sumatra shell — @prog.sumatra [args…] · EXEC name(lits…) · DROP PROCEDURE name · help · exit sumatra> @expire.sumatra Completed (exit 0) sumatra> exit ``` Or skip the prompt entirely — the one-shot form runs a single statement and exits with its outcome, which is the form you use from scripts and cron: ```bash theme={null} sumatra --dsn my.dsn @expire.sumatra echo $? # 0 ``` Behind the scenes, the shell just did all of this: 1. Compiled `expire.sumatra` against the **live catalog** of the connected database — the database itself is the schema; there are no schema files to maintain. 2. Generated C++ for the program and built it with `g++` in a temporary directory. (The first build in a session also checks that `g++`, `pkg-config`, and libcurl headers are present, and fails loudly with an install hint if not.) 3. Ran the binary, which connected using the same DSN file and executed the transaction. 4. Discarded the binary. A file submitted with `@` is compile-and-run, never stored — [stored procedures](/sumatra/procedures) are the persistent form. Verify the result in Firebolt: session 1 flipped to `expired`, session 2 is untouched. ```sql theme={null} SELECT session_id, state FROM sumatra_sessions ORDER BY session_id; -- 1 expired -- 2 active -- 3 expired ``` ## A program with per-row logic Set-DML is the trivial case. Sumatra earns its keep when the logic is procedural — when each row needs branching, state, or arithmetic that is awkward to express in one SQL statement. Create an orders table and a few rows: ```sql theme={null} CREATE TABLE sumatra_orders ( order_id BIGINT NOT NULL, customer_id INT, amount NUMERIC(12,2), status TEXT, order_date DATE, region TEXT ) PRIMARY INDEX order_id; INSERT INTO sumatra_orders VALUES (101, 1, 120.00, 'pending', DATE '2026-07-20', 'US'), (102, 2, 850.00, 'pending', DATE '2026-07-21', 'DE'), (103, 1, 35.50, 'pending', DATE '2026-07-22', 'US'), (104, 3, 640.00, 'shipped', DATE '2026-07-19', 'FR'); ``` Now a program that classifies every pending order, `prioritize.sumatra`: ```sql prioritize.sumatra theme={null} -- Classify pending orders by size. BEGIN FOR batch IN (SELECT order_id, customer_id, amount, status, order_date, region FROM sumatra_orders WHERE status = 'pending') -- ordinary SQL, run as written ORDER KEY (order_id) -- a strict order for the chunked read BATCH SIZE 10000 -- rows arrive 10,000 at a time LOOP FOR rec IN batch LOOP -- per-row logic, in memory IF rec.amount >= 500 THEN rec.status := 'priority'; ELSE rec.status := 'standard'; END IF; UPDATE sumatra_orders SET ROW = rec WHERE order_id = rec.order_id; END LOOP; -- captured writes land as ONE COMMIT; -- statement, then a checkpoint END LOOP; END; ``` The new pieces: * `FOR batch IN (SELECT ...)` opens a **read block**. The parenthesized query is ordinary Firebolt SQL — filter, join, aggregate as you like. `batch` is a name you choose. * `ORDER KEY (order_id)` declares a strict total order for the read. It is required whenever the read is fetched in chunks, so results are deterministic and a re-run walks rows in the same order. * `BATCH SIZE 10000` fetches the result in chunks of up to 10,000 rows. Each batch is processed, written, and committed as a unit. * `FOR rec IN batch LOOP` iterates the current batch row by row, in memory. `rec`'s fields are the columns of your SELECT, and they are assignable. * `:=` is Sumatra assignment (plain `=` is SQL's comparison/SET, used only inside SQL statements). * `UPDATE ... SET ROW = rec WHERE order_id = rec.order_id;` writes the whole record back — every column except the key it matches on. You never write `MERGE` or staging tables yourself; the compiler batches the captured row writes and emits one set-based statement per batch. * `COMMIT;` inside the batch loop makes each batch a durable checkpoint as soon as it is written. Run it and check: ```bash theme={null} sumatra --dsn my.dsn @prioritize.sumatra ``` ```sql theme={null} SELECT order_id, amount, status FROM sumatra_orders ORDER BY order_id; -- 101 120.00 standard -- 102 850.00 priority -- 103 35.50 standard -- 104 640.00 shipped <- untouched: filtered out by the read ``` ## Exit codes Every program run finishes in exactly one of three ways: | Exit code | Meaning | | --------- | -------------------------------------------------------------------------------------------------------------------------------- | | `0` | Completed — the program ran to the end (or a clean `RETURN;`). | | `2` | Stopped — a fault was caught by an exception handler whose action was `STOP`. Batches committed before the fault remain durable. | | `1` | Error — an unhandled fault, a `RAISE`, a compile error, or an infrastructure failure. | The distinction between `2` and `1` is deliberate: `2` means the program anticipated the fault and shut down gracefully with a valid committed prefix; `1` means something needs a human. Scripts and schedulers can branch on it directly. ## Where next * [Types, expressions, and control flow](/sumatra/language) — the language itself: variables, operators, conditionals, loops, records, and keyed collections. * [Programs and batches](/sumatra/programs) — the full anatomy of a program: read blocks, write routing, commit grains, and pipelines. * [Learning by example](/sumatra/examples) — nine complete programs, from a running balance to pipelines and dynamic targets. * [The sumatra shell](/sumatra/shell) — the complete command-line reference. # The sumatra shell Source: https://docs.wirekite.io/sumatra/shell Complete reference for the sumatra command-line shell and the offline sumatra-compile inspector — flags, statements, DSN files, exit codes, and diagnostics. The toolchain ships two binaries. `sumatra` is the shell — the one command you use day to day: it compiles programs against your live database, builds them, runs them, and manages stored procedures. `sumatra-compile` is an offline inspector for looking at what a program compiles into, and is never required to run anything. ## The sumatra binary ```text theme={null} usage: sumatra --dsn [statement…] ``` There are exactly two flags: | Flag | Meaning | | ----------------- | -------------------------------------------------- | | `--dsn ` | Path to the DSN file (required for any statement). | | `--version` | Print the sumatra version and exit. | There are no subcommands and no environment-variable configuration — statements do everything. ### Interactive mode Run `sumatra --dsn my.dsn` with no statement and you get a prompt: ```text theme={null} sumatra shell — @prog.sumatra [args…] · EXEC name(lits…) · DROP PROCEDURE name · help · exit sumatra> ``` One statement per line. There is no multi-line input, no paste mode, and no statement terminator at the prompt — source code always lives in files, never typed into the shell. There is also no SQL passthrough: the shell speaks Sumatra statements only, and you keep using your normal SQL client alongside it for queries. Leave with `exit`, `quit`, or Ctrl-D. ### One-shot mode Anything after the flags is joined with spaces and parsed as **one** prompt line; the process runs it and exits with the statement's outcome: ```bash theme={null} sumatra --dsn my.dsn @nightly_rollup.sumatra sumatra --dsn my.dsn "EXEC score_accounts(500, 'july')" ``` This is the form for scripts and cron — the exit code is the program's outcome (see below), so schedulers can branch on it without parsing output. Quote values that contain spaces exactly as you would at the prompt: `"EXEC p('North America')"`. ## The statement set The `help` statement prints the whole surface: ```text theme={null} @prog.sumatra [args…] compile + build + run the file's program (one-shot; never stored) args… = the program's PARAM values, declaration order quote a value containing spaces: @p.sumatra "North America" a CREATE OR REPLACE PROCEDURE file stores + compiles instead (the file IS the CREATE statement; a CREATE takes no args) EXEC name(lits…) run a stored procedure; literals only — 42 · 3.14 · 'text' · TRUE (compiles only when needed, always announced; EXEC p() = zero args) DROP PROCEDURE name delete a stored procedure (+ this host's cache entries) help this text exit leave (also: quit, Ctrl-D) ``` ### `@prog.sumatra [args…]` Submits a file. For an ordinary program: compile against the live catalog → build with `g++` in a temporary directory → run → discard the binary. Nothing is stored; `@` is the run-once form. Arguments after the file name are the program's `PARAM` values, in declaration order. Double quotes group a value containing spaces (`@p.sumatra "North America"`); `""` is a legal empty value. If the file's program is a `CREATE OR REPLACE PROCEDURE`, submitting it **stores** the procedure instead of running anything — the file is the CREATE statement. A CREATE submission takes no arguments; argument values belong to `EXEC`. ### `EXEC name(lits…)` Runs a stored procedure. Parentheses are always required — `EXEC p()` means zero arguments. Arguments are positional literals only: * bare tokens: `42`, `3.14`, `2026-01-01`, `TRUE` * single-quoted text: `'july'`, `'North America'` There is no escape mechanism for quotes in the current release: a text value containing `'` cannot be passed and is rejected loudly. `EXEC` is one statement with no trailing semicolon. Keywords are case-insensitive and procedure names fold to lowercase. ### `DROP PROCEDURE name` Deletes the stored procedure's database record and this host's cached binaries for it. Dropping a name that does not exist is a loud error, never a silent no-op. ## Exit codes | Code | Printed at the prompt | Meaning | | ---- | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------- | | `0` | `Completed (exit 0)` | Ran to the end, or a clean `RETURN;`. | | `2` | `Stopped — STOP handled; committed prefix retained (exit 2)` | A handler caught a fault and chose `STOP`. Every batch committed before the fault is durable. | | `1` | — | Unhandled fault, `RAISE`, compile error, bad arguments, or infrastructure failure. | Shell-side failures (bad flags, unreadable files) also exit `1`. There is one internal code you may observe indirectly: a compiled program exits `3` when the database schema changed since it was compiled — a refuse, not a failure. The shell reacts by announcing `[sumatra] compiling (schema changed)`, recompiling the stored source, and rerunning once — see [stored procedures](/sumatra/procedures#when-recompiles-happen). You do not need to handle this case yourself; your scripts only ever see `0`/`2`/`1`. ## DSN files A DSN file is one line of text naming the target database: ```text theme={null} firebolt:///?account_name=&client_id=&client_secret=&engine= ``` * The URL scheme selects the backend, per database. `firebolt:` is the scheme these docs' examples use throughout; an unknown scheme is an immediate, loud error. * The database path is required — programs compile against that database's catalog, and stored procedures live in it. * `engine` is optional; without it the system engine is used. * The file holds a credential: `chmod 600 my.dsn`. In the current release the DSN is a plain file — there is no encrypted-DSN or stdin-secret mechanism yet. The shell connects with this DSN to compile and to manage procedures; each compiled program binary makes its **own** connection from the same file when it runs. ## Toolchain preflight Before the first build in a session, the shell verifies the host can compile: `g++` on PATH, `pkg-config`, libcurl development headers, and the `runtime/` + `exec/` directories sitting next to the real `sumatra` binary. Each missing piece fails with a specific install hint, e.g.: ```text theme={null} g++ not found on PATH — install the g++ package (sumatra compiles the generated C++ on this host) ``` The check is lazy: a host that only runs already-cached stored procedures never compiles, so it never needs the toolchain. ## sumatra-compile: the offline inspector ```text theme={null} usage: sumatra-compile [-emit sql|cpp] (use - for stdin) sumatra-compile -emit profile (the backend Profile header; no source file) ``` `sumatra-compile` runs entirely offline — no DSN, no connection. It compiles against a **built-in sample schema** — a fixed set of tables and read shapes from the example corpus (`sumatra_orders`, `sumatra_customers`, `sumatra_ledger`, and friends) — so it is a way to inspect what programs lower to, not a way to compile against your own tables — the `sumatra` shell does that against the live catalog. A program whose read is not in the sample set fails with a `no describe registered` message; that is the fixed schema, not a syntax error. | Invocation | Prints | | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `sumatra-compile prog.sumatra` | The server-side SQL the program lowers to (Firebolt dialect). Default, same as `-emit sql`. | | `sumatra-compile -emit cpp prog.sumatra` | The generated C++ for the client-compute route — the code the shell builds and runs. | | `sumatra-compile -emit profile` | The backend profile header: the semantic constants (rounding, overflow, type widths) the toolchain guarantees. | | `sumatra-compile -version` | Version, then exit. | `-` as the file name reads source from stdin. Compile errors exit `1`; an unknown `-emit` value exits `2`. Two program shapes have no static SQL plan, so `-emit sql` refuses them with a pointed message while `-emit cpp` still works: a program taking a [dynamic table name](/sumatra/programs#dynamic-table-names), and a [pipeline](/sumatra/programs#pipelines-repeating-a-read-compute-write) (its iteration is driven client-side). ## Diagnostics Errors are positioned and specific. The shapes you will see: ```text theme={null} sumatra-compile: parse error 10:5: COMMIT is unwriteable inside a compute loop (spec §2 #1) lex error 3:14: sema: catalog: unknown target table "nosuchtable" (not registered) ``` Positions are `line:column`, 1-based. In the shell the same errors are prefixed with the file name: `sumatra: prog.sumatra: `. Semantic errors favor prose that names the rule and the fix — for example, a variable read before it is ever assigned, or an `ORDER KEY` missing from a chunked read. ## Debugging a running program Setting the environment variable `SUMATRA_TRACE` (to any value) makes a compiled program dump each request to stderr: the head of the SQL, the HTTP status, and up to 2000 bytes of the response body. The shell's child processes inherit it: ```bash theme={null} SUMATRA_TRACE=1 sumatra --dsn my.dsn @prog.sumatra 2>trace.log ``` The trace includes SQL text and raw engine responses — treat the output as sensitive, and use it as a diagnostic aid only. # Why Sumatra Source: https://docs.wirekite.io/sumatra/why The case for transforming data inside the database — and the two engines that make it practical: the batch execution model and the merge write path. Every data platform eventually needs a transformation step that set-based SQL cannot express: a per-account state machine, a running balance, a change feed where each row's fate depends on a value the data just produced. Today that step usually leaves the database. Sumatra's premise is that it shouldn't — and its two core mechanisms, the **batch engine** and the **merge engine**, are what make staying in-database practical rather than merely possible. ## Transformation without leaving the database The conventional answer to procedural transformation is a round trip: export the data to an external compute layer (a Spark cluster, a fleet of Python jobs), transform it there, and load the results back. Every part of that round trip is a cost you keep paying: * **Data movement, twice.** The working set crosses the wire out, and the results cross back in — often the slowest and most expensive part of the pipeline. * **A second platform to operate.** The external layer has its own sizing, patching, monitoring, credentials, and failure modes. For many teams the cluster exists *only* to host the procedural steps the database couldn't run. * **Two failure domains.** A half-finished external job leaves state split across systems, and recovery logic has to reason about both. * **A wider security surface.** Data now rests, at least transiently, outside the database — a second system to bring inside audit and compliance boundaries. * **Schema drift.** The external job carries its own copy of schema knowledge, which silently rots as tables evolve. A Sumatra program removes the second platform rather than managing it: * The program **compiles against the live catalog** of the connected database — the database itself is the schema, so there is no copy to drift. If the schema changes after compile, the program refuses to run on stale assumptions and recompiles. * Reads and writes are the **engine's own SQL**. Set-shaped work never leaves the engine at all; procedural work streams through the program in bounded batches and lands back as set-based writes. Rows are never parked in a second system of record. * The runtime is **one native binary on a host you already have** — a process, not a platform. There is no cluster, no job framework, no scheduler service; cron and an exit code are enough. * Failure semantics live in one place: committed batches are durable in the database, everything else rolled back — one system to reason about when something goes wrong. The result: the pipeline's set steps and its procedural mid-work run in the same place, against the same catalog, under the same transactional rules. ## The batch engine Sumatra's execution grain is the **batch** — and one declaration sets it: ```sql theme={null} FOR batch IN (SELECT entry_id, customer_id, delta, running_balance FROM ledger) ORDER KEY (customer_id, entry_id) BATCH SIZE 50000 LOOP ... COMMIT; END LOOP; ``` That `BATCH SIZE` is one knob controlling four things at once — the read chunk, the write flush, the commit checkpoint, and the memory bound. Behind it, the compiler generates the machinery you would otherwise hand-build: **Keyset pagination, generated.** Chunked reads page by key, not by offset — the shape of the generated fetch is: ```sql theme={null} -- the shape of the generated fetch (illustrative) SELECT ... FROM ledger WHERE (customer_id, entry_id) > (last_seen_customer, last_seen_entry) ORDER BY customer_id, entry_id LIMIT 50000 ``` This is exactly how pagination is hand-written by people who have been burned by `OFFSET`: no quadratic re-scans, no scratch tables, no manufactured row numbers. You declare the key; the cursor logic, the boundary tracking, and the end-of-set detection are generated. **An order you can trust.** `ORDER KEY` declares a strict total order, and the toolchain treats it as a contract: a duplicate key or a NULL in a key column at runtime is a loud error — never a silently skipped or double-processed row. Carried state flows across batch seams in declared order, which is what makes a 50,000-row-batched running balance produce the identical answer to a single-pass run. That invariance — **the same result at any batch size** — is a language guarantee on the compute path, not a hope. **Checkpoints for free.** A `COMMIT` inside the batch loop makes every batch a durable checkpoint. A ten-hour backfill that faults at hour nine keeps nine hours of committed work as a valid prefix, and the standard done-flag idiom makes the re-run resume exactly where it stopped — restartability falls out of the commit grain instead of being engineered separately. **Bounded memory.** `BATCH SIZE N` caps the client working set at N rows regardless of table size; `BATCH SIZE ALL` is the explicit whole-set choice for aggregating reads, where one distributed evaluation of the query is the efficient shape. **And the row-at-a-time trap is fenced off.** On a distributed columnar engine, per-row server calls — the natural idiom on OLTP databases — are catastrophically slow. Sumatra does not merely discourage them; the grammar has no way to write a per-row server query or a per-row commit. The language's promise is **per-row logic at set-based cost**, and the promise is structural. ## The merge engine The write side is where hand-rolled pipelines hide their sharpest edges. Applying a mixed stream of inserts, updates, and deletes correctly means writing a staged `MERGE`: create a scratch table, bulk it full, get the match conditions and the operation arms exactly right, clean it all up — and get it right again in every job that writes. In Sumatra you write only natural per-row statements: ```sql theme={null} IF rec.new_balance < 0 THEN DELETE FROM accounts WHERE customer_id = rec.customer_id; ELSIF rec.exists_flag THEN UPDATE accounts SET balance = rec.new_balance WHERE customer_id = rec.customer_id; ELSE INSERT INTO accounts (customer_id, balance) VALUES (rec.customer_id, rec.new_balance); END IF; ``` and the compiler turns each batch's captured changes into **one set-based, op-tagged MERGE**: ```sql theme={null} -- the shape of the generated write-back (illustrative) MERGE INTO accounts t USING sumatra_stage_... m ON t.customer_id = m.customer_id WHEN MATCHED AND m.op = 'd' THEN DELETE WHEN MATCHED AND m.op = 'u' THEN UPDATE SET balance = m.balance WHEN NOT MATCHED AND m.op = 'i' THEN INSERT (customer_id, balance) VALUES (m.customer_id, m.balance); ``` What that buys you: * **One statement per batch, whatever the mix.** Ten thousand rows' worth of per-row branching — some deleted, some updated, some inserted — lands as a single set-based apply, at set-based cost. * **The staging lifecycle is invisible.** The scratch table is created, filled in bulk over the same SQL connection (no CSV export, no object-store hop, no COPY pipeline to build), applied, and dropped automatically. A crashed run's orphan staging table is reclaimed by the next run of the same program. * **Only what changed is written.** A single-column `UPDATE` stages just the key and that column — a sparse update that leaves every other column untouched and lets the read project only what it needs. `SET ROW` writes the whole record when that is what you mean. * **The lightest form wins.** Captured-and-staged MERGE is the *heaviest* route, used only when per-row compute demands it. A write that is already set-shaped runs as plain DML exactly as you wrote it, and a write that correlates to the batch as a set runs as one correlated statement — the compiler always routes each write to the cheapest form that is correct, with no keyword and no hints. And it holds you to the invariants that make merges trustworthy: * **One change per key per flush.** Two captured changes to the same merge key in one batch is a program error surfaced loudly — never a silent last-write-wins that quietly picks a survivor. * **Keys are immutable in a write.** A statement that would change its own merge key is rejected at compile time, because a staged merge cannot express it correctly. * **NULL keys never match**, exactly as SQL joins treat them — no accidental cross-matching through NULLs. The net effect: the trickiest statement in analytical SQL is one you never write, generated from per-row logic that says what you actually mean — and the classic merge bugs are unrepresentable. ## Built to run unattended The same machinery composes into an operational shape schedulers can rely on. Every run ends in exactly one of three states — `0` completed, `2` stopped cleanly with the committed prefix retained, `1` needs a human — so cron can branch without parsing logs. A program can parameterize itself from its own data — compute a watermark, then filter the next read by it — so incremental jobs run with no arguments at all. Stored procedures compile once and run from cache on any host, recompiling only when source, toolchain, or schema actually changed — and each recompile is announced. Concurrent duplicate runs of the same procedure with the same arguments are refused engine-side, so an overlapping cron slot cannot double-apply a batch. ## Engine-neutral by construction Sumatra deliberately defines program meaning as **the connected engine's meaning**: values, rounding, overflow, and NULL behavior are the bound backend's semantics, verified bit-exact, and everything engine-specific in the toolchain — type names, SQL dialect, semantic constants — lives behind per-backend profiles rather than in the language. Your read SQL is your engine's own dialect, relayed verbatim. The backend is declared by the DSN's URL scheme, per database — today, **Firebolt or Snowflake**, the two engines of the class. Firebolt is the engine used throughout these docs, where the proof runs deepest; the language surface you learn — batches, routing, merge discipline, exceptions — is identical across engines, and built to carry to further ones as they are bound. ## See it in practice * [Quickstart](/sumatra/quickstart) — run the round trip yourself in ten minutes. * [Learning by example](/sumatra/examples) — the running balance, change-feed apply, and fail-safe scoring programs. * [Programs and batches](/sumatra/programs) — the precise rules behind the batch and merge machinery described here. # Google BigQuery Source: https://docs.wirekite.io/targetguides/bigquery This guide explains how to configure Google BigQuery as a target database for Wirekite data loading and replication. ## Overview Wirekite supports Google BigQuery as a target data warehouse for: * **Schema Loading** - Create target tables from Wirekite's intermediate schema format * **Data Loading** - Bulk load extracted data via Google Cloud Storage staging * **Change Loading (CDC)** - Apply ongoing changes using MERGE operations BigQuery loaders stage data through Google Cloud Storage (GCS) buckets before loading to BigQuery using COPY INTO commands. ## Prerequisites Before configuring BigQuery as a Wirekite target, ensure the following requirements are met: ### Google Cloud Configuration 1. **Project Setup**: Have a Google Cloud project with BigQuery API enabled 2. **Dataset**: Create a BigQuery dataset in the desired location 3. **GCS Bucket**: Create a Google Cloud Storage bucket for staging data 4. **Authentication**: Configure Application Default Credentials or service account 5. **IAM Permissions**: Ensure the service account has: * `bigquery.tables.create`, `bigquery.tables.updateData` * `storage.objects.create`, `storage.objects.delete` on the GCS bucket 6. **Metadata Tables**: Wirekite automatically creates `wirekite_progress` and `wirekite_action` tables in the target dataset for tracking migration state and operational control. See [Operations](/run/operations) for details. ### Storage Requirements The GCS bucket must be accessible from both the loader host and BigQuery. Ensure the bucket is in the same region as your BigQuery dataset for best performance. Use Application Default Credentials for simplest authentication: run `gcloud auth application-default login` on the loader host. *** ## Schema Loader The Schema Loader reads Wirekite's intermediate schema format (`.skt` file) and generates BigQuery-appropriate DDL statements for creating target tables. ### Required Parameters Path to the Wirekite schema file (`.skt`) generated by the Schema Extractor. Must be an absolute path. Output file for CREATE TABLE statements. Includes both base tables and merge tables for CDC operations. Output file for constraint definitions (BigQuery has limited constraint support). Output file for FOREIGN KEY constraints (informational only in BigQuery). Absolute path to the log file for Schema Loader operations. ### Optional Parameters Output file for DROP TABLE IF EXISTS statements. Set to "none" to skip generation. Output file for recovery table creation SQL. Set to "none" to skip. When `true`, generates merge tables (`_wkm` suffix) for CDC operations. Set to `false` if only doing data loads. *** ## Data Mover (GCS) The Data Mover uploads extracted data files to Google Cloud Storage for subsequent loading into BigQuery. ### Required Parameters GCS bucket name (without `gs://` prefix) for staging data files. Local directory containing data files (`.dkt`) from the Data Extractor. Absolute path to the log file for Data Mover operations. ### Optional Parameters Path to GCS service account credentials JSON file. Uses Application Default Credentials if not specified. Maximum number of parallel upload threads. When `true`, compresses files with gzip before uploading. Changes extension to `.dgz`. When `true`, deletes local files after successful upload to GCS. *** ## Data Loader The Data Loader reads data files from GCS and loads them into BigQuery tables using COPY INTO operations. ### Required Parameters Path to a file containing the BigQuery connection string. **Connection string format:** ``` bigquery://PROJECT_ID/DATASET?gcs_bucket=BUCKET_NAME ``` **Example:** ``` bigquery://my-project/my_dataset?gcs_bucket=my-staging-bucket ``` Path to the Wirekite schema file used by Schema Loader. Required for table structure information. Absolute path to the log file for Data Loader operations. ### Optional Parameters Path to GCS service account credentials JSON file. Uses Application Default Credentials if not specified. Maximum number of parallel threads for loading tables. Set to `true` if data was extracted using hex encoding instead of base64. BigQuery dataset location (e.g., "US", "EU"). Only needed if non-default. The Data Loader creates temporary staging tables with auto-expiration for intermediate processing. *** ## Change Loader The Change Loader applies ongoing data changes (INSERT, UPDATE, DELETE) to BigQuery tables using MERGE operations with shadow tables. ### Required Parameters Path to a file containing the BigQuery connection string. **Connection string format:** ``` bigquery://PROJECT_ID/DATASET?gcs_bucket=BUCKET_NAME ``` Directory containing change files (`.ckt`) from the Change Extractor. Working directory for temporary CSV files during merge operations. Must be writable. Path to the Wirekite schema file for table structure information. Absolute path to the log file for Change Loader operations. ### Optional Parameters Path to GCS service account credentials JSON file. Uses Application Default Credentials if not specified. Maximum number of change files to process in a single batch. Number of parallel threads for applying merge operations within each batch. Defaults to 2x the number of CPU cores on the host. Set to `true` if change data was extracted using hex encoding. BigQuery dataset location (e.g., "US", "EU"). Only needed if non-default. The Change Loader should not start until the Data Loader has successfully completed the initial full load. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix parameters with `mover.`, `target.schema.`, `target.data.`, or `target.change.`. **Example orchestrator configuration for BigQuery target:** ``` # Main configuration source=postgres target=bigquery # Data mover (GCS) mover.gcsBucket=my-staging-bucket mover.dataDirectory=/opt/wirekite/output/data mover.logFile=/var/log/wirekite/data-mover.log mover.maxThreads=10 mover.removeFiles=true # Schema loading target.schema.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.schema.createTableFile=/opt/wirekite/output/schema/create_tables.sql target.schema.createConstraintFile=/opt/wirekite/output/schema/constraints.sql target.schema.createForeignKeyFile=/opt/wirekite/output/schema/foreign_keys.sql target.schema.logFile=/var/log/wirekite/schema-loader.log # Data loading target.data.dsnFile=/opt/wirekite/config/bigquery.dsn target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.logFile=/var/log/wirekite/data-loader.log target.data.maxThreads=8 # Change loading (CDC) target.change.dsnFile=/opt/wirekite/config/bigquery.dsn target.change.inputDirectory=/opt/wirekite/output/changes target.change.workDirectory=/opt/wirekite/work target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.logFile=/var/log/wirekite/change-loader.log target.change.maxFilesPerBatch=30 ``` For complete Orchestrator documentation, see the [Execution Guide](/run/execution). # Databricks Source: https://docs.wirekite.io/targetguides/databricks This guide explains how to configure Databricks as a target database for Wirekite data loading and replication. ## Overview Wirekite supports Databricks (using Delta Lake) as a target data lakehouse for: * **Schema Loading** - Create target tables from Wirekite's intermediate schema format * **Data Loading** - Bulk load extracted data via cloud storage staging * **Change Loading (CDC)** - Apply ongoing changes using MERGE operations Databricks loaders stage data through AWS S3 or Google Cloud Storage buckets before loading to Databricks using COPY INTO commands. Tables are created using Delta Lake format. ## Prerequisites Before configuring Databricks as a Wirekite target, ensure the following requirements are met: ### Databricks Configuration 1. **Workspace**: Have a Databricks workspace with SQL warehouse or cluster 2. **Catalog & Schema**: Create the target catalog and schema 3. **Cloud Storage**: Configure an S3 bucket or GCS bucket for staging 4. **Authentication**: Configure service principal or personal access token 5. **Metadata Tables**: Wirekite automatically creates `wirekite_progress` and `wirekite_action` tables in the target schema for tracking migration state and operational control. See [Operations](/run/operations) for details. ### Cloud Storage Requirements Either an AWS S3 bucket or GCS bucket is required for staging data. The bucket must be accessible from both the loader host and Databricks workspace. For AWS, ensure IAM credentials have read/write access to the S3 bucket. For GCS, use a service account with Storage Object Admin role. *** ## Schema Loader The Schema Loader reads Wirekite's intermediate schema format (`.skt` file) and generates Databricks-appropriate DDL statements for creating Delta Lake tables. Tables are created with `USING DELTA` format. The Schema Loader also generates merge tables with `_wkm` suffix for CDC operations. ### Required Parameters Path to the Wirekite schema file (`.skt`) generated by the Schema Extractor. Must be an absolute path. Output file for CREATE TABLE statements using Delta Lake format. Output file for CHECK constraints (Databricks has limited constraint support). Output file for FOREIGN KEY constraints (informational, commented out in output). Absolute path to the log file for Schema Loader operations. ### Optional Parameters Output file for DROP TABLE IF EXISTS statements. Set to "none" to skip generation. Output file for recovery table creation SQL. Set to "none" to skip. When `true`, generates merge tables (`_wkm` suffix) for CDC operations. Set to `false` if only doing data loads. *** ## Data Loader The Data Loader reads data files from cloud storage and loads them into Databricks tables using COPY INTO operations. ### Required Parameters Path to a file containing the Databricks connection string. **Connection string format:** ``` databricks://token:TOKEN@HOSTNAME:443/default?catalog=CATALOG&schema=SCHEMA ``` Path to the Wirekite schema file used by Schema Loader. Required for table structure information. Absolute path to the log file for Data Loader operations. ### Cloud Storage Parameters (one required) AWS S3 bucket name for staging data. Required if using AWS. GCS bucket name for staging data. Required if using Google Cloud. ### Optional AWS Parameters AWS region where the S3 bucket resides. AWS credentials in format: `aws_access_key_id=KEY,aws_secret_access_key=SECRET`. Not required if using IAM roles. ### Optional GCS Parameters Path to GCS service account credentials JSON file. Uses Application Default Credentials if not specified. ### General Optional Parameters Maximum number of parallel threads for loading tables. Set to `true` if data was extracted using hex encoding instead of base64. Uses `unhex()` for decoding. The Data Loader creates temporary staging tables that are automatically cleaned up after successful loads. *** ## Change Loader The Change Loader applies ongoing data changes (INSERT, UPDATE, DELETE) to Databricks tables using MERGE operations with shadow tables. ### Required Parameters Path to a file containing the Databricks connection string. Directory containing change files (`.ckt`) from the Change Extractor. Working directory for temporary CSV files during merge operations. Must be writable. Path to the Wirekite schema file for table structure information. Absolute path to the log file for Change Loader operations. ### Cloud Storage Parameters (one required) AWS S3 bucket name for staging change data. Required if using AWS. GCS bucket name for staging change data. Required if using Google Cloud. ### Optional AWS Parameters AWS region where the S3 bucket resides. AWS credentials in format: `aws_access_key_id=KEY,aws_secret_access_key=SECRET`. ### Optional GCS Parameters Path to GCS service account credentials JSON file. ### General Optional Parameters Maximum number of change files to process in a single batch. Number of parallel threads for applying merge operations within each batch. Defaults to 2x the number of CPU cores on the host. Set to `true` if change data was extracted using hex encoding. The Change Loader should not start until the Data Loader has successfully completed the initial full load. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix parameters with `mover.`, `target.schema.`, `target.data.`, or `target.change.`. **Example orchestrator configuration for Databricks target (using AWS S3):** ``` # Main configuration source=postgres target=databricks # Data mover (S3) mover.awsBucket=my-staging-bucket mover.awsRegion=us-east-1 mover.dataDirectory=/opt/wirekite/output/data mover.logFile=/var/log/wirekite/data-mover.log mover.maxThreads=10 mover.removeFiles=true mover.awsCredentials=aws_access_key_id=KEY,aws_secret_access_key=SECRET # Schema loading target.schema.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.schema.createTableFile=/opt/wirekite/output/schema/create_tables.sql target.schema.createConstraintFile=/opt/wirekite/output/schema/constraints.sql target.schema.createForeignKeyFile=/opt/wirekite/output/schema/foreign_keys.sql target.schema.logFile=/var/log/wirekite/schema-loader.log # Data loading target.data.dsnFile=/opt/wirekite/config/databricks.dsn target.data.awsBucket=my-staging-bucket target.data.awsRegion=us-east-1 target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.logFile=/var/log/wirekite/data-loader.log target.data.maxThreads=8 target.data.awsCredentials=aws_access_key_id=KEY,aws_secret_access_key=SECRET # Change loading (CDC) target.change.dsnFile=/opt/wirekite/config/databricks.dsn target.change.awsBucket=my-staging-bucket target.change.awsRegion=us-east-1 target.change.inputDirectory=/opt/wirekite/output/changes target.change.workDirectory=/opt/wirekite/work target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.logFile=/var/log/wirekite/change-loader.log target.change.maxFilesPerBatch=30 target.change.awsCredentials=aws_access_key_id=KEY,aws_secret_access_key=SECRET ``` For complete Orchestrator documentation, see the [Execution Guide](/run/execution). # Db2 Source: https://docs.wirekite.io/targetguides/db2target This guide explains how to configure IBM Db2 (LUW) as a target database for Wirekite data loading and replication. ## Overview Wirekite supports IBM Db2 for Linux, UNIX and Windows (LUW) 11.5 and above as a target database for: * **Schema Loading** - Create target tables from Wirekite's intermediate schema format * **Data Loading** - Bulk load extracted data into Db2 tables * **Change Loading (CDC)** - Apply ongoing changes using Db2's native `MERGE` statement The Db2 loaders use the `go_ibm_db` driver (IBM CLI / clidriver). The Change Loader applies changes through per-table staging tables (`_wkm` suffix) and a single `MERGE` per batch, giving idempotent, exactly-once change application. ## Prerequisites Before configuring Db2 as a Wirekite target, ensure the following requirements are met: ### Database Configuration 1. **Version**: Db2 (LUW) 11.5 or above. Db2 11.5 is required for native `BOOLEAN`, `BINARY`/`VARBINARY`, and `DROP TABLE IF EXISTS`. 2. **Primary keys**: Every table loaded into Db2 **must have a primary key**. The Schema Loader errors on any table without one, because change application and validation identify rows by primary key. 3. **32K tablespace for LOBs**: Tables containing `CLOB`/`BLOB` columns are placed in a 32K-page tablespace named `ts32k`. Create this tablespace (with a matching 32K bufferpool and temp tablespace) before loading a schema that contains LOB columns. For example: ```sql theme={null} CREATE BUFFERPOOL bp32k IMMEDIATE SIZE 4000 PAGESIZE 32K; CREATE TABLESPACE ts32k PAGESIZE 32K BUFFERPOOL bp32k; CREATE USER TEMPORARY TABLESPACE tmp32k PAGESIZE 32K BUFFERPOOL bp32k; ``` 4. **User Permissions**: A dedicated Wirekite user with table creation and DML privileges on the target schema (see [Privileges](#privileges) below). ### File System Access * Ensure the user running Wirekite has write permissions to the input and work directories. * Verify sufficient disk space for intermediate data and change files. Unlike the Oracle and PostgreSQL targets, Wirekite does **not** create metadata tables (`wirekite_progress`, `wirekite_action`) on the Db2 server. Progress and crash-recovery state are kept in a local SQLite database in the loader's input directory (see [Progress Tracking](#progress-tracking)). Use the Wirekite cmdline tool or the Db2 CLP (`db2`) to verify connectivity before running the loaders. *** ## Schema Loader The Schema Loader reads Wirekite's intermediate schema format (`.skt` file) and generates Db2-appropriate DDL statements. It makes no database connection — it only writes SQL files, which are applied later (for example by the Wirekite cmdline tool). The Schema Loader generates both base tables and staging/merge tables (with `_wkm` suffix) for CDC operations. Db2 forbids `$` in unquoted identifiers, so Wirekite uses `_wkm` (staging table), `_wkpk` (primary-key copy columns), and `wk_merge_op` (operation marker) rather than the `$wkm` convention used by some other targets. ### Required Parameters Path to the Wirekite schema file (`.skt`) generated by the Schema Extractor. Must be an absolute path. Output file for CREATE TABLE statements. Includes both base tables and staging/merge tables for CDC operations. Absolute path to the log file for Schema Loader operations. ### Optional Parameters Output file for `DROP TABLE IF EXISTS` statements (base and `_wkm` tables). Set to `none` to skip generation. In Db2, dropping a table cascade-drops its indexes, constraints, and foreign keys. Output file for secondary index definitions (`CREATE INDEX` / `CREATE UNIQUE INDEX`). Output file for UNIQUE and CHECK constraint definitions. Output file for FOREIGN KEY constraints. Db2 foreign keys are emitted as `NOT ENFORCED DISABLE QUERY OPTIMIZATION` — see the note below. Output file for dropping non-table objects. On Db2 this is emitted as a comment-only no-op (Db2 targets replicate tables and their indexes/constraints only). When `true`, generates staging/merge tables (`_wkm` suffix) required for CDC operations. Set to `false` for data-only loads without change capture. When `true`, only creates staging/merge tables, skipping base table creation. Useful for bounce-back scenarios. **Foreign keys are not enforced on the Db2 target.** They are emitted as `... NOT ENFORCED DISABLE QUERY OPTIMIZATION` so that the parallel, out-of-order data load and concurrent change apply cannot raise referential-integrity violations. The source database remains the integrity authority. This matches the behavior of Wirekite's Spanner target. **Db2-specific schema behavior:** * **Identifiers** are emitted unquoted, so Db2 folds schema, table, and column names to **UPPERCASE**. * **DECIMAL** precision is capped at Db2's maximum of **31**. A non-primary-key numeric with higher (or unbounded) precision is stored as text (`VARCHAR`) to preserve the exact value; a primary-key numeric is capped to `DECIMAL(31,s)`. * **LOB columns** (`CLOB`/`BLOB`) are emitted with `INLINE LENGTH 4000` and their tables are placed `IN ts32k`. A `CLOB`/`BLOB` cannot be a primary key, so such a PK column is coerced to `VARCHAR(4000)`. * **String lengths** use `CODEUNITS32` (character counts). Oversized character columns become `CLOB`; oversized binary columns become `BLOB`. * **Non-table objects** (views, procedures, triggers, sequences, synonyms) are not created on Db2. *** ## Data Loader The Data Loader reads Wirekite's intermediate data format (`.dkt` files) and loads records into Db2 target tables using batched multi-row `INSERT` statements over the `go_ibm_db` connection. Db2's `LOAD`/`IMPORT` utilities read server-side files and cannot see a remote loader's data, so Wirekite loads via bind-parameter `INSERT` batches. Each batch commits independently (implicit autocommit) to keep the Db2 active log bounded. ### Required Parameters Path to a file containing the Db2 connection string (see [Connection String](#connection-string)). Directory containing data files (`.dkt`) to load. Files are processed in parallel based on `maxThreads`. Path to the Wirekite schema file used by the Schema Loader. Required for table structure information. Absolute path to the log file for Data Loader operations. ### Optional Parameters Maximum number of parallel threads for loading tables. Each thread loads one data file at a time over its own database connection. Desired number of rows per `INSERT` batch. The effective batch size is capped so the statement stays under Db2's parameter-marker limit (roughly `30000 / number_of_columns`). Set to `true` if data was extracted using hex encoding instead of base64. After loading each table, the Data Loader runs `RUNSTATS` (`CALL SYSPROC.ADMIN_CMD('RUNSTATS ON TABLE ... WITH DISTRIBUTION AND INDEXES ALL')`) so that the Change Loader's first `MERGE` compiles an efficient primary-key index plan. This requires DBADM or SQLADM authority (satisfied by the dev-mode grants below). For best performance, set `maxThreads` close to the number of CPU cores available on the loader host. *** ## Change Loader The Change Loader applies ongoing data changes (INSERT, UPDATE, DELETE) to Db2 target tables. For each batch it collapses the change files down to one final operation per primary key, populates a per-table staging table (`_wkm`), and applies a single native Db2 `MERGE`. The Change Loader requires the staging/merge tables to be created by the Schema Loader (`createMergeTables=true`). The `MERGE` is idempotent, so re-processing a partially applied batch after a crash is a no-op for already-applied rows. ### Required Parameters Path to a file containing the Db2 connection string. Directory containing change files (`.ckt`) from the Change Extractor. Working directory for progress/crash-recovery state. Must be writable. Path to the Wirekite schema file for table structure information. Absolute path to the log file for Change Loader operations. ### Optional Parameters Maximum number of change files aggregated into a single collapsed batch before executing `MERGE` operations. Number of parallel workers that populate a table's staging table over disjoint primary-key ranges. Parallel populate engages only above \~4000 rows for a table. Set to `true` if changes were extracted using hex encoding instead of base64. Set to `verbose` to emit per-table insert/update/delete breakdowns to the load-statistics charts. Accepts `basic` or `verbose`. When `true`, purges the Change Loader's progress state and reprocesses change files from the start. Used by the "restart replication" flow. The Orchestrator sets this automatically — set it manually only when running the Change Loader standalone. The Change Loader should not start until the Data Loader has successfully completed the initial full load. The `MERGE` applies four operation types: `i` (insert), `u` (update), `d` (delete), and `r` (resync/upsert — matches both the update and insert branches). Unchanged columns in a sparse update are preserved on the target rather than overwritten. Changes within a batch are applied in primary-key-ordered chunks and retried automatically on transient Db2 lock-timeout/deadlock errors (SQLSTATE 40001). *** ## Connection String The Db2 loaders connect through the `go_ibm_db` driver, which uses a **keyword-style connection string** (not a URL). The `dsnFile` should contain exactly one line: ``` HOSTNAME=;PORT=;PROTOCOL=TCPIP;DATABASE=;UID=;PWD= ``` **Example DSN file contents:** ``` HOSTNAME=db2-target.example.com;PORT=50000;PROTOCOL=TCPIP;DATABASE=APP_DB;UID=wirekite;PWD=secretpass ``` The default Db2 port is **50000**. When Wirekite generates the DSN through the Web GUI or API, it also injects `ConnectTimeout=15` (seconds) so a failed connection does not hang indefinitely. The target schema is taken from the schema file, not the connection string. *** ## Progress Tracking Wirekite does not create metadata tables on the Db2 server. Instead, each loader keeps its progress state in a local SQLite database in its `inputDirectory`: | File | Loader | Purpose | | ------------------------- | ------------- | ----------------------------------------------------------- | | `wirekite_progress_dl.db` | Data Loader | Per-file load progress, resume, "already-complete" skipping | | `wirekite_progress_cl.db` | Change Loader | Per-batch change-apply progress and crash recovery | Each file contains a `wirekite_progress` table (one row per processed file) and a `wirekite_action` control row (`RUN`/`PAUSE`/`STOP`) that the Change Loader polls for lifecycle control. Exactly-once behavior comes from the combination of these marks and the idempotent `MERGE`. *** ## Privileges Create a dedicated Wirekite user (for example `WIREKITE`) and grant it the privileges below. ### Development / Self-Provisioned For a dedicated, self-managed Db2 instance, the broad grant set is simplest: ```sql theme={null} GRANT CONNECT ON DATABASE TO USER wirekite; GRANT DBADM, DATAACCESS, ACCESSCTRL ON DATABASE TO USER wirekite; ``` `DBADM` also covers the `RUNSTATS` call the Data Loader issues after each table load. ### Production Least-Privilege For a shared or production Db2, grant only what the loaders use. Run these as a DBADM/SECADM operator: ```sql theme={null} -- Connectivity GRANT CONNECT ON DATABASE TO USER wirekite; -- Create the base and _wkm tables GRANT CREATETAB ON DATABASE TO USER wirekite; -- DML + DDL within the target schema GRANT CREATEIN, ALTERIN, DROPIN, SELECTIN, INSERTIN, UPDATEIN, DELETEIN ON SCHEMA TO USER wirekite; ``` Under a fully `RESTRICTIVE` Db2 (where `PUBLIC` does not hold tablespace `USE`), also grant `USE OF TABLESPACE` on the data tablespace (for example `USERSPACE1`) and on `ts32k` for LOB tables. The `RUNSTATS` step run by the Data Loader requires DBADM or SQLADM; if you cannot grant that, disable it or run it manually. ### Privilege Summary | Privilege | Required For | | ----------------------------------------------------------- | ------------------------------------------------------------------------------- | | `CONNECT` | Basic connectivity | | `CREATETAB` | Creating base and `_wkm` tables | | `CREATEIN` / `DROPIN` on schema | `CREATE TABLE` / `DROP TABLE IF EXISTS` in the target schema | | `ALTERIN` on schema | `ALTER TABLE ... VOLATILE`, `ADD CONSTRAINT` | | `SELECTIN` / `INSERTIN` / `UPDATEIN` / `DELETEIN` on schema | Data load `INSERT`; change-apply `MERGE` (insert/update/delete + staging reads) | | `USE OF TABLESPACE` | Only under `RESTRICTIVE` Db2 (data tablespace + `ts32k`) | | `DBADM` or `SQLADM` | `RUNSTATS` after data load | *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix target parameters with `target.schema.`, `target.data.`, or `target.change.` depending on the operation. **Example orchestrator configuration for Db2 target:** ``` # Main configuration source=postgres target=db2 # Schema loading target.schema.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.schema.createTableFile=/opt/wirekite/output/schema/create_tables.sql target.schema.createIndexFile=/opt/wirekite/output/schema/indexes.sql target.schema.createConstraintFile=/opt/wirekite/output/schema/constraints.sql target.schema.createForeignKeyFile=/opt/wirekite/output/schema/foreign_keys.sql target.schema.logFile=/var/log/wirekite/schema-loader.log # Data loading target.data.dsnFile=/opt/wirekite/config/db2.dsn target.data.inputDirectory=/opt/wirekite/output/data target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.logFile=/var/log/wirekite/data-loader.log target.data.maxThreads=8 target.data.db2BatchRows=2000 # Change loading (CDC) target.change.dsnFile=/opt/wirekite/config/db2.dsn target.change.inputDirectory=/opt/wirekite/output/changes target.change.workDirectory=/opt/wirekite/work target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.logFile=/var/log/wirekite/change-loader.log target.change.maxFilesPerBatch=60 target.change.populateWorkers=8 ``` For complete Orchestrator documentation, see the [Execution Guide](/run/execution/commandline). *** ## Limitations * **Primary key required** on every table — a table with no primary key is a hard error. * **Foreign keys are not enforced** (`NOT ENFORCED`); the source is the integrity authority. * **Non-table objects** (views, materialized views, procedures, functions, triggers, packages, sequences, synonyms) are not created on Db2. * **DECIMAL** precision is capped at 31; wider non-PK numerics are preserved as text. * **TIME** values are stored as `VARCHAR(64)` because Db2 `TIME` has no sub-second precision; **timestamp-with-time-zone** values are normalized to UTC `TIMESTAMP`. * **UNIQUE constraints** require `NOT NULL` columns in Db2; model a nullable uniqueness rule as a unique index instead. * See the [Db2 datatype matrix](/datatypes/db2) for how each source type is mapped into Db2. # Firebolt Source: https://docs.wirekite.io/targetguides/firebolt This guide explains how to configure Firebolt as a target data warehouse for Wirekite data loading and replication. ## Overview Wirekite supports Firebolt as a target data warehouse for: * **Schema Loading** - Create target tables from Wirekite's intermediate schema format * **Data Loading** - Bulk load extracted data via AWS S3 staging * **Change Loading (CDC)** - Apply ongoing changes using MERGE operations Firebolt loaders stage data through AWS S3 buckets before loading using Firebolt's [COPY SQL](https://docs.firebolt.io/reference-sql/commands/data-management/copy-from) command. ## Prerequisites Before configuring Firebolt as a Wirekite target, ensure the following requirements are met: ### Firebolt Configuration 1. **User Setup**: Create a properly configured Firebolt user 2. **Engine**: Ensure a Firebolt engine is available for loading operations 3. **Database**: Create the target database ### AWS S3 Requirements An AWS S3 bucket is required for staging data. The bucket must be: * In the same AWS Region as your Firebolt database * Accessible for read/write from the loader host * Accessible for read from Firebolt Install the AWS CLI tool (`aws`) for managing the bucket. Run `aws configure` to set up shell-level authentication. [AWS CLI install instructions](https://docs.aws.amazon.com/cli/v1/userguide/install-linux.html) ### Internal Tables Ensure the Wirekite target metadata tables (`wirekite_progress` and `wirekite_action`) exist in your Firebolt database. Use the Wirekite cmdline tool to verify connectivity. *** ## Schema Loader The Schema Loader reads Wirekite's intermediate schema format (`.skt` file) and generates Firebolt-appropriate DDL statements for creating target tables. Firebolt does not support FOREIGN KEYs or external CHECK constraints. The Schema Loader will generate empty files for these. Column-level constraints (NOT NULL) are included in CREATE TABLE. ### Required Parameters Path to the Wirekite schema file (`.skt`) generated by the Schema Extractor. Must be an absolute path. Output file for CREATE TABLE statements. Includes both base tables and merge tables for CDC operations. Output file for constraints (always empty for Firebolt). Required but the file will be empty. Output file for FOREIGN KEY constraints (always empty for Firebolt). Required but the file will be empty. Absolute path to the log file for Schema Loader operations. ### Optional Parameters Output file for DROP TABLE IF EXISTS statements. Set to "none" to skip generation. Output file for recovery table creation SQL. Set to "none" to skip. When `true`, generates merge tables for CDC operations. Set to `false` if only doing data loads without change capture. *** ## Data Mover (AWS) The Data Mover uploads extracted data files to an AWS S3 bucket for subsequent loading into Firebolt. ### Required Parameters AWS S3 bucket name (without `s3://` prefix) for staging data files. AWS Region where the S3 bucket resides (must match Firebolt region). Local directory containing data files (`.dkt`) from the Data Extractor. Absolute path to the log file for Data Mover operations. ### Optional Parameters AWS credentials in format: `aws_access_key_id=KEY,aws_secret_access_key=SECRET`. Only required if AWS access isn't configured via IAM roles or environment. Maximum number of parallel upload threads. When `true`, compresses files with gzip before uploading. Changes extension to `.dgz`. When `true`, deletes local files after successful upload to S3. Should be `true` in production to save disk space. *** ## Data Loader The Data Loader reads data files from AWS S3 and loads them into Firebolt tables using COPY commands. ### Required Parameters Path to a file containing the Firebolt connection string. **Connection string format:** ``` firebolt://?account_name=&account_id=&client_secret=&engine= ``` **Example:** ``` firebolt://mydb?account_name=myaccount&account_id=12345&client_secret=mysecret&engine=myengine ``` AWS S3 bucket name (without `s3://` prefix) where data files were staged. Path to the Wirekite schema file used by Schema Loader. Required for table structure information. Absolute path to the log file for Data Loader operations. ### Optional Parameters AWS Region where the S3 bucket resides. AWS credentials in format: `aws_access_key_id=KEY,aws_secret_access_key=SECRET`. Only required if AWS access isn't set up in Firebolt. Maximum number of parallel threads for loading data. We recommend setting this to the number of CPUs on the host. Set to `true` if data was extracted using hex format instead of base64. When `true`, counts rows in temporary tables before inserting (for progress tracking). When `true`, removes files from S3 after successful loading to Firebolt. *** ## Change Loader The Change Loader applies ongoing data changes (INSERT, UPDATE, DELETE) to Firebolt tables using MERGE operations with shadow tables. The Change Loader uploads intermediate change data to S3 before executing MERGE. The same S3 bucket used for data loading can be used. ### Required Parameters Path to a file containing the Firebolt connection string. **Connection string format:** ``` firebolt://?account_name=&account_id=&client_secret=&engine= ``` AWS S3 bucket name (without `s3://` prefix) for staging change data. AWS Region where the S3 bucket resides. Directory containing change files (`.ckt`) from the Change Extractor. Working directory for intermediate CSV files before uploading to S3. Path to the Wirekite schema file for table structure information. Absolute path to the log file for Change Loader operations. ### Optional Parameters AWS credentials in format: `aws_access_key_id=KEY,aws_secret_access_key=SECRET`. Only required if AWS access isn't set up in Firebolt. Maximum number of change files to process in a single batch before executing MERGE. Number of parallel threads for applying merge operations within each batch. Defaults to 2x the number of CPU cores on the host. When `true`, removes change files from `inputDirectory` after fully processing. The Change Loader should not start until the Data Loader has successfully completed the initial full load. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix parameters with `mover.`, `target.schema.`, `target.data.`, or `target.change.`. **Example orchestrator configuration for Firebolt target:** ``` # Main configuration source=postgres target=firebolt # Data mover (AWS) mover.awsBucket=my-firebolt-staging mover.awsRegion=us-east-1 mover.dataDirectory=/opt/wirekite/output/data mover.logFile=/var/log/wirekite/data-mover.log mover.maxThreads=10 mover.removeFiles=true mover.awsCredentials=aws_access_key_id=KEY,aws_secret_access_key=SECRET # Schema loading target.schema.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.schema.createTableFile=/opt/wirekite/output/schema/create_tables.sql target.schema.createConstraintFile=/opt/wirekite/output/schema/constraints.sql target.schema.createForeignKeyFile=/opt/wirekite/output/schema/foreign_keys.sql target.schema.logFile=/var/log/wirekite/schema-loader.log # Data loading target.data.dsnFile=/opt/wirekite/config/firebolt.dsn target.data.awsBucket=my-firebolt-staging target.data.awsRegion=us-east-1 target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.logFile=/var/log/wirekite/data-loader.log target.data.maxThreads=8 target.data.awsCredentials=aws_access_key_id=KEY,aws_secret_access_key=SECRET # Change loading (CDC) target.change.dsnFile=/opt/wirekite/config/firebolt.dsn target.change.awsBucket=my-firebolt-staging target.change.awsRegion=us-east-1 target.change.inputDirectory=/opt/wirekite/output/changes target.change.workDirectory=/opt/wirekite/work target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.logFile=/var/log/wirekite/change-loader.log target.change.maxFilesPerBatch=30 target.change.awsCredentials=aws_access_key_id=KEY,aws_secret_access_key=SECRET ``` For complete Orchestrator documentation, see the [Execution Guide](/run/execution). # MongoDB Source: https://docs.wirekite.io/targetguides/mongodbtarget This guide explains how to configure MongoDB as a target database for Wirekite data loading and replication. ## Overview Wirekite supports MongoDB as a target database for: * **Schema Loading** - Create collections with optional JSON Schema validators * **Data Loading** - Bulk load extracted data using InsertMany operations * **Change Loading (CDC)** - Apply ongoing changes using BulkWrite operations MongoDB loaders convert relational table data to BSON documents. Primary keys are mapped to MongoDB's `_id` field. Composite primary keys are stored as nested BSON documents (e.g., `{_id: {col1: val1, col2: val2}}`). ## Prerequisites Before configuring MongoDB as a Wirekite target, ensure the following requirements are met: ### Database Configuration 1. **Version**: MongoDB 4.x or above 2. **User Permissions**: The connection user must have: * `readWrite` role on the target database ### Limitations MongoDB does not support FOREIGN KEY or CHECK constraints. These are skipped during schema loading with a warning in the log. *** ## Schema Loader The Schema Loader reads Wirekite's intermediate schema format (`.skt` file) and **emits two mongo-shell script files** — one with `db..drop()` statements and one with `db.createCollection("")` statements. The orchestrator runs these scripts against the target during the schema-apply phase; the schema loader itself does not connect to MongoDB. Collection names follow `schema.tablename` format (e.g., `public.users`). When the orchestrator applies the create script, `createCollection` is a no-op if the collection already exists. ### Required Parameters Path to the Wirekite schema file (`.skt`) generated by the Schema Extractor. Absolute path to the log file for Schema Loader operations. Output file for `db..drop()` statements (one line per table). The orchestrator runs this script against the target before re-creating collections, only when re-applying schema. Output file for `db.createCollection("")` statements (one line per table). The orchestrator runs this script against the target during schema apply. *** ## Data Loader The Data Loader reads Wirekite's intermediate data format (`.dkt` files) and loads documents into MongoDB collections using InsertMany with unordered batches for maximum throughput. The Data Loader uses a 3-stage pipeline architecture (Scanner, Parsers, Writers) for high-performance parallel loading. ### Required Parameters Path to a file containing the MongoDB connection string. Directory containing data files (`.dkt`) to load. Path to the Wirekite schema file for table structure information. Absolute path to the log file for Data Loader operations. ### Optional Parameters Maximum number of parallel threads for loading files. Each thread loads one file at a time. Set to `true` if data was extracted using hex encoding instead of base64. *** ## Change Loader The Change Loader applies ongoing data changes (INSERT, UPDATE, DELETE) to MongoDB collections using BulkWrite operations. Updates use sparse `$set` operations, only modifying changed fields. Inserts and replaces use full document upserts. ### Required Parameters Path to a file containing the MongoDB connection string. Directory containing change files (`.ckt`) from the Change Extractor. Path to the Wirekite schema file for table structure information. Absolute path to the log file for Change Loader operations. ### Optional Parameters Set to `true` if change data was extracted using hex encoding. The Change Loader should not start until the Data Loader has successfully completed the initial full load. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix target parameters with `target.schema.`, `target.data.`, or `target.change.` depending on the operation. **Example orchestrator configuration for MongoDB target:** ``` # Main configuration source=postgres target=mongodb # Schema loading target.schema.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.schema.dropTableFile=/opt/wirekite/output/schema/drop-collections.js target.schema.createTableFile=/opt/wirekite/output/schema/create-collections.js target.schema.logFile=/var/log/wirekite/schema-loader.log # Data loading target.data.dsnFile=/opt/wirekite/config/mongodb.dsn target.data.inputDirectory=/opt/wirekite/output/data target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.logFile=/var/log/wirekite/data-loader.log target.data.maxThreads=8 # Change loading (CDC) target.change.dsnFile=/opt/wirekite/config/mongodb.dsn target.change.inputDirectory=/opt/wirekite/output/changes target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.logFile=/var/log/wirekite/change-loader.log ``` For complete Orchestrator documentation, see the [Execution Guide](/run/execution). # MySQL / MariaDB / SingleStore Source: https://docs.wirekite.io/targetguides/mysqltarget This guide explains how to configure MySQL, MariaDB, or SingleStore as a target database for Wirekite data loading and replication. ## Overview Wirekite supports MySQL 5.x and above (including MariaDB and SingleStore) as a target database for: * **Schema Loading** - Create target tables from Wirekite's intermediate schema format * **Data Loading** - Bulk load extracted data using LOAD DATA INFILE * **Change Loading (CDC)** - Apply ongoing changes using merge table approach All references to MySQL in this guide also apply to MariaDB and SingleStore setups. SingleStore uses the MySQL wire protocol, so the configuration and parameters are identical. See the [SingleStore Notes](#singlestore-notes) section below for DSN and version differences. ## Prerequisites Before configuring MySQL as a Wirekite target, ensure the following requirements are met: ### Database Configuration 1. **Version**: MySQL 5.x or above (or MariaDB equivalent) 2. **User Permissions**: Create a Wirekite user with: * CREATE TABLE privilege * FILE privilege for LOAD DATA operations * INSERT, UPDATE, DELETE on target tables * Read/write access to Wirekite internal tables (`wirekite_progress` and `wirekite_action`) ### CLI Tools Use the `mysql` command line tool or Wirekite cmdline tool to interact with the database. For cloud-managed MySQL (RDS, Cloud SQL), you'll need to use `databaseRemote=true` (the default) to use `LOAD DATA LOCAL INFILE`. *** ## Schema Loader The Schema Loader reads Wirekite's intermediate schema format (`.skt` file) and generates MySQL-appropriate DDL statements for creating target tables. If you need to add storage directives or other schema elements, use the CREATE TABLE output as a basis. Don't change column names, column order, or datatypes to incompatible ones. ### Required Parameters Path to the Wirekite schema file (`.skt`) generated by the Schema Extractor. Must be an absolute path. Output file for CREATE TABLE statements. Includes both base tables and merge tables for CDC operations. Output file for non-columnar constraints including indexes. Column-level constraints (NOT NULL) are in CREATE TABLE. Output file for FOREIGN KEY definitions. Consider applying these after initial data load for better performance. Absolute path to the log file for Schema Loader operations. ### Optional Parameters Output file for DROP TABLE IF EXISTS statements. Set to "none" to skip generation. Output file for recovery table creation SQL. Set to "none" to skip. When `true`, generates merge tables (`$wkm` suffix) for CDC operations. Set to `false` if only doing data loads. When `true`, only creates merge tables, skipping base table creation. *** ## Data Loader The Data Loader reads Wirekite's intermediate data format (`.dkt` files) and loads records into MySQL tables using LOAD DATA INFILE. ### Required Parameters Path to a file containing the MySQL connection string. **Connection string format:** ``` username:password@tcp(host:port)/database?multiStatements=true&loc=Local ``` **Example:** ``` wirekite:secretpass@tcp(mysql-target.example.com:3306)/myapp?multiStatements=true&loc=Local ``` Directory containing data files (`.dkt`) to load. Path to the Wirekite schema file used by Schema Loader. Required for table structure information. Absolute path to the log file for Data Loader operations. ### Optional Parameters Maximum number of parallel threads for loading tables. We recommend setting this to the number of CPUs on the host. Set to `true` if data was extracted using hex encoding instead of base64. When `true`, uses `LOAD DATA LOCAL INFILE`. When `false`, uses `LOAD DATA INFILE` (requires file access from server). When `true`, removes data files from `inputDirectory` after loading. *** ## Change Loader The Change Loader applies ongoing data changes (INSERT, UPDATE, DELETE) to MySQL tables using a merge approach with shadow tables. The Change Loader uses merge tables to stage changes, then applies INSERT-SELECT, UPDATE, and DELETE operations to transfer changes to base tables. ### Required Parameters Path to a file containing the MySQL connection string. **Connection string format:** ``` username:password@tcp(host:port)/database?multiStatements=true&loc=Local ``` Directory containing change files (`.ckt`) from the Change Extractor. Working directory for intermediate CSV files during merge operations. Path to the Wirekite schema file for table structure information. Absolute path to the log file for Change Loader operations. ### Optional Parameters When `true`, uses `LOAD DATA LOCAL INFILE` for loading changes to merge tables. Maximum number of change files to process in a single batch before executing merge operations. When `true`, removes change files from `inputDirectory` after fully processing. The Change Loader should not start until the Data Loader has successfully completed the initial full load. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix target parameters with `target.schema.`, `target.data.`, or `target.change.`. **Example orchestrator configuration for MySQL target:** ``` # Main configuration source=oracle target=mysql # Schema loading target.schema.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.schema.createTableFile=/opt/wirekite/output/schema/create_tables.sql target.schema.createConstraintFile=/opt/wirekite/output/schema/constraints.sql target.schema.createForeignKeyFile=/opt/wirekite/output/schema/foreign_keys.sql target.schema.logFile=/var/log/wirekite/schema-loader.log # Data loading target.data.dsnFile=/opt/wirekite/config/mysql.dsn target.data.inputDirectory=/opt/wirekite/output/data target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.logFile=/var/log/wirekite/data-loader.log target.data.maxThreads=8 target.data.databaseRemote=true # Change loading (CDC) target.change.dsnFile=/opt/wirekite/config/mysql.dsn target.change.inputDirectory=/opt/wirekite/output/changes target.change.workDirectory=/opt/wirekite/work target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.logFile=/var/log/wirekite/change-loader.log target.change.maxFilesPerBatch=30 target.change.databaseRemote=true ``` For complete Orchestrator documentation, see the [Execution Guide](/run/execution). *** ## SingleStore Notes SingleStore (formerly MemSQL) uses the MySQL wire protocol and is fully compatible with the MySQL loaders described above. The following differences apply when targeting SingleStore. ### Version SingleStore 7.x or above is required. ### Connection String The SingleStore DSN must include `allowAllFiles=true` in addition to `multiStatements=true`. The `loc=Local` parameter used by MySQL is not needed. **Connection string format:** ``` username:password@tcp(host:port)/database?allowAllFiles=true&multiStatements=true ``` **Example:** ``` wirekite:secretpass@tcp(singlestore.example.com:3306)/myapp?allowAllFiles=true&multiStatements=true ``` The `allowAllFiles=true` parameter is required for LOAD DATA operations to work correctly with SingleStore. It is automatically added if missing. ### Orchestrator Configuration When targeting SingleStore, use `target=singlestore` in the orchestrator configuration: ``` # Main configuration source=mysql target=singlestore # Schema loading target.schema.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.schema.createTableFile=/opt/wirekite/output/schema/create_tables.sql target.schema.createConstraintFile=/opt/wirekite/output/schema/constraints.sql target.schema.createForeignKeyFile=/opt/wirekite/output/schema/foreign_keys.sql target.schema.logFile=/var/log/wirekite/schema-loader.log # Data loading target.data.dsnFile=/opt/wirekite/config/singlestore.dsn target.data.inputDirectory=/opt/wirekite/output/data target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.logFile=/var/log/wirekite/data-loader.log target.data.maxThreads=8 target.data.databaseRemote=true # Change loading (CDC) target.change.dsnFile=/opt/wirekite/config/singlestore.dsn target.change.inputDirectory=/opt/wirekite/output/changes target.change.workDirectory=/opt/wirekite/work target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.logFile=/var/log/wirekite/change-loader.log target.change.maxFilesPerBatch=30 target.change.databaseRemote=true ``` # Oracle Source: https://docs.wirekite.io/targetguides/oracletarget This guide explains how to configure Oracle as a target database for Wirekite data loading and replication. ## Overview Wirekite supports Oracle 11g and above as a target database for: * **Schema Loading** - Create target tables from Wirekite's intermediate schema format * **Data Loading** - Bulk load extracted data into Oracle tables * **Change Loading (CDC)** - Apply ongoing changes using MERGE operations Oracle loaders use OCI (Oracle Call Interface) for high-performance bulk loading. The Change Loader uses shadow/merge tables for atomic change application. ## Prerequisites Before configuring Oracle as a Wirekite target, ensure the following requirements are met: ### Database Configuration 1. **Version**: Oracle 11g or above 2. **User Permissions**: Create a dedicated Wirekite user with: * CREATE TABLE privilege * INSERT, UPDATE, DELETE on target tables * Read/write access to Wirekite internal tables (`wirekite_progress` and `wirekite_action`) ### File System Access * Ensure the user running Wirekite has write permissions to the work directory * Verify sufficient disk space for intermediate files during change loading Use the Wirekite cmdline tool or Oracle SQL\*Plus to interact with the database and verify connectivity before running loaders. *** ## Schema Loader The Schema Loader reads Wirekite's intermediate schema format (`.skt` file) and generates Oracle-appropriate DDL statements for creating target tables. The Schema Loader generates both base tables and merge tables (with `$wkm` suffix) for CDC operations. ### Required Parameters Path to the Wirekite schema file (`.skt`) generated by the Schema Extractor. Must be an absolute path. Output file for CREATE TABLE statements. Includes both base tables and merge tables for CDC operations. Output file for constraint definitions (indexes, unique constraints, check constraints). Output file for FOREIGN KEY constraints. Can be applied after initial data load for better performance. Absolute path to the log file for Schema Loader operations. ### Optional Parameters Output file for DROP TABLE IF EXISTS statements. Set to "none" to skip generation. Output file for recovery table creation SQL. Set to "none" to skip. When `true`, generates merge tables (`$wkm` suffix) for CDC operations. Set to `false` if only doing data loads without change capture. When `true`, only creates merge tables, skipping base table creation. Useful for bounce-back scenarios. *** ## Data Loader The Data Loader reads Wirekite's intermediate data format (`.dkt` files) and loads records into Oracle target tables using high-performance OCI bulk operations. ### Required Parameters Path to a file containing the Oracle connection string. **Connection string format:** ``` username/password@host:port/service_name ``` **Example:** ``` wirekite/secretpass@oracle-target.example.com:1521/ORCL ``` Directory containing data files (`.dkt`) to load. Files are processed in parallel based on `maxThreads`. Path to the Wirekite schema file used by Schema Loader. Required for table structure information. Absolute path to the log file for Data Loader operations. ### Optional Parameters Maximum number of parallel threads for loading tables. Each thread loads one table at a time. Set to `true` if data was extracted using hex encoding instead of base64. When `true`, uses the C OCI bulk loader for approximately 100x faster performance. When `false`, uses Go row-by-row insertion. File extension for data files to process. For best performance, set `maxThreads` equal to the number of CPU cores available and keep `useOCILoader` enabled. *** ## Change Loader The Change Loader applies ongoing data changes (INSERT, UPDATE, DELETE) to Oracle target tables using a merge approach with shadow tables. The Change Loader requires merge tables to be created by the Schema Loader. It uses Oracle's MERGE statement for atomic change application. ### Required Parameters Path to a file containing the Oracle connection string. **Connection string format:** ``` username/password@host:port/service_name ``` Directory containing change files (`.ckt`) from the Change Extractor. Working directory for temporary CSV files during merge operations. Must be writable. Path to the Wirekite schema file for table structure information. Absolute path to the log file for Change Loader operations. ### Optional Parameters When `true`, loads changes locally. When `false`, uses remote loading methods. Maximum number of change files to process in a single batch before executing MERGE operations. The Change Loader should not start until the Data Loader has successfully completed the initial full load. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix target parameters with `target.schema.`, `target.data.`, or `target.change.` depending on the operation. **Example orchestrator configuration for Oracle target:** ``` # Main configuration source=postgres target=oracle # Schema loading target.schema.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.schema.createTableFile=/opt/wirekite/output/schema/create_tables.sql target.schema.createConstraintFile=/opt/wirekite/output/schema/constraints.sql target.schema.createForeignKeyFile=/opt/wirekite/output/schema/foreign_keys.sql target.schema.logFile=/var/log/wirekite/schema-loader.log # Data loading target.data.dsnFile=/opt/wirekite/config/oracle.dsn target.data.inputDirectory=/opt/wirekite/output/data target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.logFile=/var/log/wirekite/data-loader.log target.data.maxThreads=8 target.data.useOCILoader=true # Change loading (CDC) target.change.dsnFile=/opt/wirekite/config/oracle.dsn target.change.inputDirectory=/opt/wirekite/output/changes target.change.workDirectory=/opt/wirekite/work target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.logFile=/var/log/wirekite/change-loader.log target.change.maxFilesPerBatch=30 ``` For complete Orchestrator documentation, see the [Execution Guide](/run/execution). # PostgreSQL / YugaByte / TigerData / AlloyDB Source: https://docs.wirekite.io/targetguides/postgrestarget This guide explains how to configure PostgreSQL (including YugaByte, TigerData, and AlloyDB) as a target database for Wirekite data loading and replication. ## Overview Wirekite supports PostgreSQL 10 and above (including YugaByte, TigerData, Google AlloyDB, and AWS Aurora PostgreSQL) as a target database for: * **Schema Loading** - Create target tables from Wirekite's intermediate schema format * **Data Loading** - Bulk load extracted data using COPY command * **Change Loading (CDC)** - Apply ongoing changes using merge table approach PostgreSQL loaders use the high-performance COPY command for bulk loading. The Change Loader uses shadow tables with `$wkm` suffix for atomic change application. ## Prerequisites Before configuring PostgreSQL as a Wirekite target, ensure the following requirements are met: ### Database Configuration 1. **Version**: PostgreSQL 10 or above 2. **User Permissions**: Create a Wirekite user with: * CREATE TABLE privilege * FILE access for COPY operations * INSERT, UPDATE, DELETE on target tables * Read/write access to Wirekite internal tables (`wirekite_progress` and `wirekite_action`) ### CLI Tools Use the `psql` command line tool or Wirekite cmdline tool to interact with PostgreSQL. For cloud-managed PostgreSQL (AlloyDB, Aurora, Cloud SQL), you'll need to use `databaseRemote=true` (the default) since server-side file access isn't available. *** ## Schema Loader The Schema Loader reads Wirekite's intermediate schema format (`.skt` file) and generates PostgreSQL-appropriate DDL statements for creating target tables. If you need to add storage directives or other schema elements, use the CREATE TABLE output as a basis. Don't change column names, column order, or datatypes to incompatible ones. ### Required Parameters Path to the Wirekite schema file (`.skt`) generated by the Schema Extractor. Must be an absolute path. Output file for CREATE TABLE statements. Includes both base tables and merge tables for CDC operations. Output file for non-columnar constraints including indexes. Column-level constraints (NOT NULL) are in CREATE TABLE. Output file for FOREIGN KEY definitions. Consider applying these after initial data load for better performance. Absolute path to the log file for Schema Loader operations. ### Optional Parameters Output file for DROP TABLE IF EXISTS statements. Set to "none" to skip generation. Output file for recovery table creation SQL. Set to "none" to skip. When `true`, generates merge tables (`$wkm` suffix) for CDC operations. Set to `false` if only doing data loads. ### Extended Schema Options When migrating from Oracle, PostgreSQL can generate additional DDL for non-table objects. Set each parameter to a file path to enable, or leave as `"none"` to skip. Path to the source XKT file containing extended schema objects (views, procedures, etc.). Output file for CREATE INDEX statements. Output file for CREATE SEQUENCE statements. Output file for CREATE VIEW statements. Output file for CREATE MATERIALIZED VIEW statements. Output file for CREATE SYNONYM statements. Output file for GRANT statements. Output file for role and user creation statements. Output file for CREATE SCHEMA statements. Output file for CREATE TRIGGER statements. Output file for CREATE PROCEDURE statements. Output file for CREATE FUNCTION statements. Output file for CREATE PACKAGE statements. *** ## Data Loader The Data Loader reads Wirekite's intermediate data format (`.dkt` files) and loads records into PostgreSQL tables using COPY commands. ### Required Parameters Path to a file containing the PostgreSQL connection string. **Connection string format:** ``` postgres://username:password@host:port/database ``` **Example:** ``` postgres://wirekite:secretpass@postgres-target.example.com:5432/myapp ``` Directory containing data files (`.dkt`) to load. Path to the Wirekite schema file used by Schema Loader. Required for table structure information. Absolute path to the log file for Data Loader operations. ### Optional Parameters Maximum number of parallel threads for loading tables. We recommend setting this to the number of CPUs on the host. Set to `true` if data was extracted using hex encoding instead of base64. When `true`, uses `COPY FROM STDIN`. When `false`, uses local file I/O methods. When `true`, removes data files from `inputDirectory` after loading. Should typically be `true` to save disk space. *** ## Change Loader The Change Loader applies ongoing data changes (INSERT, UPDATE, DELETE) to PostgreSQL tables using a merge approach with shadow tables. The Change Loader uses merge tables to stage changes before applying them atomically to base tables. ### Required Parameters Path to a file containing the PostgreSQL connection string. **Connection string format:** ``` postgres://username:password@host:port/database ``` Directory containing change files (`.ckt`) from the Change Extractor. Working directory for intermediate files during merge operations. Path to the Wirekite schema file for table structure information. Absolute path to the log file for Change Loader operations. ### Optional Parameters When `true`, indicates remote database connection mode. Maximum number of change files to process in a single batch. When `true`, removes change files from `inputDirectory` after fully processing. Should typically be `true` to save disk space. The Change Loader should not start until the Data Loader has successfully completed the initial full load. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix target parameters with `target.schema.`, `target.data.`, or `target.change.`. **Example orchestrator configuration for PostgreSQL target:** ``` # Main configuration source=oracle target=postgres # Schema loading target.schema.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.schema.createTableFile=/opt/wirekite/output/schema/create_tables.sql target.schema.createConstraintFile=/opt/wirekite/output/schema/constraints.sql target.schema.createForeignKeyFile=/opt/wirekite/output/schema/foreign_keys.sql target.schema.logFile=/var/log/wirekite/schema-loader.log # Data loading target.data.dsnFile=/opt/wirekite/config/postgres.dsn target.data.inputDirectory=/opt/wirekite/output/data target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.logFile=/var/log/wirekite/data-loader.log target.data.maxThreads=8 target.data.databaseRemote=true # Change loading (CDC) target.change.dsnFile=/opt/wirekite/config/postgres.dsn target.change.inputDirectory=/opt/wirekite/output/changes target.change.workDirectory=/opt/wirekite/work target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.logFile=/var/log/wirekite/change-loader.log target.change.maxFilesPerBatch=30 target.change.databaseRemote=true ``` For complete Orchestrator documentation, see the [Execution Guide](/run/execution). # Snowflake Source: https://docs.wirekite.io/targetguides/snowflake This guide explains how to configure Snowflake as a target data warehouse for Wirekite data loading and replication. ## Overview Wirekite supports Snowflake as a target data warehouse for: * **Schema Loading** - Create target tables from Wirekite's intermediate schema format * **Data Loading** - Bulk load extracted data via Snowflake internal stage * **Change Loading (CDC)** - Apply ongoing changes using MERGE operations Snowflake loaders stage data through Snowflake's internal stage using PUT commands, then use COPY INTO for high-performance bulk loading. ## Prerequisites Before configuring Snowflake as a Wirekite target, ensure the following requirements are met: ### Snowflake Configuration 1. **User Setup**: Create a properly configured Snowflake user with appropriate privileges 2. **Warehouse**: Ensure a virtual warehouse is available for loading operations 3. **Database & Schema**: Create the target database and schema 4. **CLI Tools**: Either install the [SnowSQL command line tool](https://docs.snowflake.com/en/user-guide/snowsql-install-config) or use the Wirekite cmdline tool ### Internal Tables Ensure the Wirekite target metadata tables (`wirekite_progress` and `wirekite_action`) exist in your Snowflake database and are read-write accessible. Use the Wirekite cmdline tool to verify connectivity. For connection string format details, see the [Snowflake connection documentation](https://docs.snowflake.com/en/user-guide/gen-conn-config). *** ## Schema Loader The Schema Loader reads Wirekite's intermediate schema format (`.skt` file) and generates Snowflake-appropriate DDL statements for creating target tables. The Schema Loader generates both base tables and merge tables (with `$wkm` suffix) for CDC operations. ### Required Parameters Path to the Wirekite schema file (`.skt`) generated by the Schema Extractor. Must be an absolute path. Output file for CREATE TABLE statements. Includes both base tables and merge tables for CDC operations. Output file for CHECK constraints. Snowflake doesn't enforce many constraints, so you may choose not to load this file. Output file for FOREIGN KEY constraints. You may elect not to load foreign keys if you don't need them. Absolute path to the log file for Schema Loader operations. ### Optional Parameters Output file for DROP TABLE IF EXISTS statements. Set to "none" to skip generation. Output file for recovery table creation SQL. Set to "none" to skip. When `true`, generates merge tables (`$wkm` suffix) for CDC operations. Set to `false` if only doing data loads without change capture. *** ## Data Mover The Data Mover uploads extracted data files to Snowflake's internal stage using PUT commands for subsequent loading. ### Required Parameters Path to a file containing the Snowflake connection string. **Connection string format (Golang connector):** ``` :@-//?warehouse= ``` **Example:** ``` wirekite:secretpass@myorg-myaccount/MYDB/PUBLIC?warehouse=COMPUTE_WH ``` Directory where the Data Extractor wrote its files. These will be copied to the Snowflake staging area. Absolute path to the log file for Data Mover operations. ### Optional Parameters Maximum number of parallel threads for uploading to Snowflake stage. When `true`, compresses files before uploading. Changes extension to `.dgz`. When `true`, deletes local files after successful PUT to stage. Should typically be `true` in production to save disk space. *** ## Data Loader The Data Loader reads data files from Snowflake's internal stage and loads them into target tables using COPY INTO commands. ### Required Parameters Path to a file containing the Snowflake connection string. **Connection string format (Golang connector):** ``` :@-//?warehouse= ``` Path to the Wirekite schema file used by Schema Loader. Required for table structure information. Absolute path to the log file for Data Loader operations. ### Optional Parameters Maximum number of parallel COPY threads. We recommend setting this to the number of CPUs on the host. Set to `true` if data was extracted using hex encoding instead of base64. File extension for data files to process (e.g., "dkt", "dgz"). For best performance, set `maxThreads` equal to the number of CPU cores available on the loader host. *** ## Change Loader The Change Loader applies ongoing data changes (INSERT, UPDATE, DELETE) to Snowflake tables using MERGE operations with shadow tables. The Change Loader uses a merging approach that stages intermediate data to Snowflake's internal stage before executing MERGE statements. ### Required Parameters Path to a file containing the Snowflake connection string. **Connection string format (Golang connector):** ``` :@-//?warehouse= ``` Directory where the Change Extractor wrote its files. These will be sourced for changes. Working directory for intermediate files that are uploaded to Snowflake stage during merge operations. Path to the Wirekite schema file for table structure information. Absolute path to the log file for Change Loader operations. ### Optional Parameters Maximum number of change files to process in a single batch before executing MERGE operations. Number of parallel threads for applying merge operations within each batch. Defaults to 2x the number of CPU cores on the host. Set to `true` if change data was extracted using hex encoding. When `true`, removes change files from `inputDirectory` after fully processing. Should typically be `true` in production to save disk space. The Change Loader should not start until the Data Loader has successfully completed the initial full load. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix parameters with `mover.`, `target.schema.`, `target.data.`, or `target.change.`. **Example orchestrator configuration for Snowflake target:** ``` # Main configuration source=postgres target=snowflake # Data mover mover.dsnFile=/opt/wirekite/config/snowflake.dsn mover.dataDirectory=/opt/wirekite/output/data mover.logFile=/var/log/wirekite/data-mover.log mover.maxThreads=10 mover.removeFiles=true # Schema loading target.schema.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.schema.createTableFile=/opt/wirekite/output/schema/create_tables.sql target.schema.createConstraintFile=/opt/wirekite/output/schema/constraints.sql target.schema.createForeignKeyFile=/opt/wirekite/output/schema/foreign_keys.sql target.schema.logFile=/var/log/wirekite/schema-loader.log # Data loading target.data.dsnFile=/opt/wirekite/config/snowflake.dsn target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.logFile=/var/log/wirekite/data-loader.log target.data.maxThreads=8 # Change loading (CDC) target.change.dsnFile=/opt/wirekite/config/snowflake.dsn target.change.inputDirectory=/opt/wirekite/output/changes target.change.workDirectory=/opt/wirekite/work target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.logFile=/var/log/wirekite/change-loader.log target.change.maxFilesPerBatch=30 ``` For complete Orchestrator documentation, see the [Execution Guide](/run/execution). # Google Cloud Spanner Source: https://docs.wirekite.io/targetguides/spanner This guide explains how to configure Google Cloud Spanner as a target database for Wirekite data loading and replication. ## Overview Wirekite supports Google Cloud Spanner as a target database for: * **Schema Loading** - Create target tables from Wirekite's intermediate schema format * **Data Loading** - Bulk load extracted data using Spanner mutations * **Change Loading (CDC)** - Apply ongoing changes using shadow table merge approach Spanner loaders respect Spanner's mutation limits (80,000 mutations per commit). The Change Loader uses shadow tables with `_wkm` suffix for atomic change application. ## Prerequisites Before configuring Spanner as a Wirekite target, ensure the following requirements are met: ### Google Cloud Configuration 1. **Project Setup**: Have a Google Cloud project with Spanner API enabled 2. **Instance & Database**: Create a Spanner instance and database 3. **Authentication**: Configure Application Default Credentials or service account 4. **IAM Permissions**: Ensure the service account has: * `spanner.databases.read` * `spanner.databases.write` * `spanner.sessions.create` 5. **Metadata Tables**: Wirekite automatically creates `wirekite_progress` and `wirekite_action` tables in the target database for tracking migration state and operational control. See [Operations](/run/operations) for details. ### Spanner Limitations Spanner has specific limitations to be aware of: * Maximum STRING/BYTES length: 2,621,440 bytes (2.5MB) * Maximum mutations per commit: 80,000 (counting columns) * Change streams have maximum 7-day retention Use Application Default Credentials for simplest authentication: run `gcloud auth application-default login` on the loader host. *** ## Schema Loader The Schema Loader reads Wirekite's intermediate schema format (`.skt` file) and generates Spanner-appropriate DDL statements for creating target tables. The Schema Loader can also generate Change Stream DDL for Spanner-to-Spanner replication scenarios. ### Required Parameters Path to the Wirekite schema file (`.skt`) generated by the Schema Extractor. Must be an absolute path. Output file for CREATE TABLE statements. Includes both base tables and merge tables for CDC operations. Output file for constraint definitions (indexes, unique constraints). Output file for FOREIGN KEY constraints (interleaved tables in Spanner). Absolute path to the log file for Schema Loader operations. ### Optional Parameters Output file for DROP TABLE statements. Set to "none" to skip generation. Output file for recovery table creation DDL. Set to "none" to skip. Output file for CREATE CHANGE STREAM statement. Used when Spanner is also a source. Output file for DROP CHANGE STREAM statement. Set to "none" to skip. Change stream retention period. Maximum is "7d" (7 days) for Spanner. When `true`, generates merge tables (`_wkm` suffix) for CDC operations. Set to `false` if only doing data loads. *** ## Data Loader The Data Loader reads Wirekite's intermediate data format (`.dkt` files) and loads records into Spanner tables using batched mutations. ### Required Parameters Path to a file containing the Spanner connection string. **Connection string format:** ``` projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID ``` **Example:** ``` projects/my-project/instances/my-instance/databases/my-database ``` Directory containing data files (`.dkt`) to load. Path to the Wirekite schema file used by Schema Loader. Required for table structure information. Absolute path to the log file for Data Loader operations. Absolute path to a GCP service-account JSON credentials file. Used to authenticate the Spanner client. If the loader host already has Application Default Credentials configured (e.g. via `gcloud auth application-default login` or a workload-identity-bound VM), point this at the ADC file path — the loader will not start without an explicit value. ### Optional Parameters Maximum number of parallel threads for loading tables. Set to `true` if data was extracted using hex encoding instead of base64. The Data Loader automatically batches mutations to stay within Spanner's 80,000 mutation limit per commit. *** ## Change Loader The Change Loader applies ongoing data changes (INSERT, UPDATE, DELETE) to Spanner tables using a merge approach with shadow tables. ### Required Parameters Path to a file containing the Spanner connection string. **Connection string format:** ``` projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID ``` Directory containing change files (`.ckt`) from the Change Extractor. Working directory for temporary files during merge operations. Must be writable. Path to the Wirekite schema file for table structure information. Absolute path to the log file for Change Loader operations. ### Optional Parameters When `true`, loads changes locally. Maximum number of change files to process in a single batch. When `true`, uses shadow table merge approach. When `false`, uses direct mutations. The Change Loader should not start until the Data Loader has successfully completed the initial full load. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix target parameters with `target.schema.`, `target.data.`, or `target.change.`. **Example orchestrator configuration for Spanner target:** ``` # Main configuration source=postgres target=spanner # Schema loading target.schema.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.schema.createTableFile=/opt/wirekite/output/schema/create_tables.sql target.schema.createConstraintFile=/opt/wirekite/output/schema/constraints.sql target.schema.createForeignKeyFile=/opt/wirekite/output/schema/foreign_keys.sql target.schema.logFile=/var/log/wirekite/schema-loader.log # Data loading target.data.dsnFile=/opt/wirekite/config/spanner.dsn target.data.inputDirectory=/opt/wirekite/output/data target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.logFile=/var/log/wirekite/data-loader.log target.data.gcpCredfile=/opt/wirekite/config/gcp-sa.json target.data.maxThreads=8 # Change loading (CDC) target.change.dsnFile=/opt/wirekite/config/spanner.dsn target.change.inputDirectory=/opt/wirekite/output/changes target.change.workDirectory=/opt/wirekite/work target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.logFile=/var/log/wirekite/change-loader.log target.change.maxFilesPerBatch=30 ``` For complete Orchestrator documentation, see the [Execution Guide](/run/execution). # SQL Server Source: https://docs.wirekite.io/targetguides/sqlservertarget This guide explains how to configure SQL Server as a target database for Wirekite data loading and replication. ## Overview Wirekite supports SQL Server 2016 and above as a target database for: * **Schema Loading** - Create target tables from Wirekite's intermediate schema format * **Data Loading** - Bulk load extracted data using ODBC bulk copy * **Change Loading (CDC)** - Apply ongoing changes using MERGE operations SQL Server loaders use ODBC bulk copy for high-performance data loading. The Change Loader uses shadow/merge tables with `_wkm` suffix for atomic change application. ## Prerequisites Before configuring SQL Server as a Wirekite target, ensure the following requirements are met: ### Database Configuration 1. **Version**: SQL Server 2016 or above 2. **ODBC Driver**: Install ODBC Driver 18 for SQL Server on the loader host 3. **User Permissions**: Create a dedicated Wirekite user with: * CREATE TABLE privilege * INSERT, UPDATE, DELETE on target tables * Read/write access to Wirekite internal tables (`wirekite_progress` and `wirekite_action`) ### File System Access * Ensure the user running Wirekite has write permissions to the work directory * Verify sufficient disk space for intermediate files during change loading Use the Wirekite cmdline tool or sqlcmd to verify database connectivity before running loaders. *** ## Schema Loader The Schema Loader reads Wirekite's intermediate schema format (`.skt` file) and generates SQL Server-appropriate DDL statements for creating target tables. The Schema Loader generates both base tables and merge tables (with `_wkm` suffix) for CDC operations. ### Required Parameters Path to the Wirekite schema file (`.skt`) generated by the Schema Extractor. Must be an absolute path. Output file for CREATE TABLE statements. Includes both base tables and merge tables for CDC operations. Output file for constraint definitions (indexes, unique constraints, check constraints). Output file for FOREIGN KEY constraints. Can be applied after initial data load for better performance. Absolute path to the log file for Schema Loader operations. ### Optional Parameters Output file for DROP TABLE IF EXISTS statements. Set to "none" to skip generation. Output file for recovery table creation SQL. Set to "none" to skip. When `true`, generates merge tables (`_wkm` suffix) for CDC operations. Set to `false` if only doing data loads without change capture. When `true`, only creates merge tables, skipping base table creation. *** ## Data Loader The Data Loader reads Wirekite's intermediate data format (`.dkt` files) and loads records into SQL Server target tables using ODBC bulk copy for high performance. ### Required Parameters Path to a file containing the SQL Server connection string. **Connection string format:** ``` sqlserver://username:password@host:port?database=databasename&encrypt=disable&connection+timeout=30 ``` **Example:** ``` sqlserver://wirekite:secretpass@sqlserver-target.example.com:1433?database=myapp&encrypt=disable&connection+timeout=30 ``` Directory containing data files (`.dkt`) to load. Files are processed in parallel based on `maxThreads`. Path to the Wirekite schema file used by Schema Loader. Required for table structure information. Absolute path to the log file for Data Loader operations. ### Optional Parameters Maximum number of parallel threads for loading tables. Each thread loads one table at a time. Set to `true` if data was extracted using hex encoding instead of base64. When `true`, indicates the database is remote. Affects how bulk copy operations are performed. For best performance, set `maxThreads` equal to the number of CPU cores available on the loader host. *** ## Change Loader The Change Loader applies ongoing data changes (INSERT, UPDATE, DELETE) to SQL Server target tables using MERGE operations with shadow tables. The Change Loader requires merge tables to be created by the Schema Loader. It processes up to 8 concurrent MERGE operations. ### Required Parameters Path to a file containing the SQL Server connection string. **Connection string format:** ``` sqlserver://username:password@host:port?database=databasename&encrypt=disable&connection+timeout=30 ``` Directory containing change files (`.ckt`) from the Change Extractor. Working directory for temporary CSV files during merge operations. Must be writable. Path to the Wirekite schema file for table structure information. Absolute path to the log file for Change Loader operations. ### Optional Parameters When `true`, loads changes locally. When `false`, uses remote loading methods. Maximum number of change files to process in a single batch before executing MERGE operations. The Change Loader should not start until the Data Loader has successfully completed the initial full load. *** ## Orchestrator Configuration When using the Wirekite Orchestrator, prefix target parameters with `target.schema.`, `target.data.`, or `target.change.` depending on the operation. **Example orchestrator configuration for SQL Server target:** ``` # Main configuration source=oracle target=sqlserver # Schema loading target.schema.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.schema.createTableFile=/opt/wirekite/output/schema/create_tables.sql target.schema.createConstraintFile=/opt/wirekite/output/schema/constraints.sql target.schema.createForeignKeyFile=/opt/wirekite/output/schema/foreign_keys.sql target.schema.logFile=/var/log/wirekite/schema-loader.log # Data loading target.data.dsnFile=/opt/wirekite/config/sqlserver.dsn target.data.inputDirectory=/opt/wirekite/output/data target.data.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.data.logFile=/var/log/wirekite/data-loader.log target.data.maxThreads=8 # Change loading (CDC) target.change.dsnFile=/opt/wirekite/config/sqlserver.dsn target.change.inputDirectory=/opt/wirekite/output/changes target.change.workDirectory=/opt/wirekite/work target.change.schemaFile=/opt/wirekite/output/schema/wirekite_schema.skt target.change.logFile=/var/log/wirekite/change-loader.log target.change.maxFilesPerBatch=30 ``` For complete Orchestrator documentation, see the [Execution Guide](/run/execution).