Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .github/workflows/validate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -177,13 +177,17 @@ jobs:
strategy:
fail-fast: false
matrix:
family: [ui, postgres, mysql, mongodb, mssql, small, customer, storage]
family: [ui, postgres, mysql, mongodb, mssql, small, customer, storage, cloud]
env:
CI: "true"
E2E_FAMILIES: ${{ matrix.family }}
E2E_NO_BUILD: "1"
# The runner is thrown away anyway, and the logs of DBackup are wanted after a failure.
E2E_KEEP: "1"
# The Cloudflare account of the D1 tests, an account just for them. Only the job of the family
# cloud gets the token, and a pull request from a fork none, so its D1 test skips.
E2E_D1_ACCOUNT_ID: ${{ matrix.family == 'cloud' && vars.E2E_D1_ACCOUNT_ID || '' }}
E2E_D1_TOKEN: ${{ matrix.family == 'cloud' && secrets.E2E_D1_TOKEN || '' }}
steps:
# The image, its build and the images of the family take more than the free space of a
# runner leaves, SQL Server alone pulls 4 GB. Deleting takes a while, so it runs in the
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ Nothing locks you in. Every database backup is a standard dump and every file ba
| SQLite | 3.x | Local, SSH | Yes |
| Microsoft SQL Server | 2017, 2019, 2022, Azure SQL Edge | Direct, SSH | Yes |
| Azure SQL Database (beta) | Single database, elastic pool | Direct | Yes, drops the target first |
| Cloudflare D1 (beta) | Every D1 database of an account | API token | Yes, replaces the tables |
| Firebird (beta) | 3.x, 4.x, 5.x | Direct, SSH | Yes, through configured aliases |

**Destinations**: local filesystem, Amazon S3 and S3-compatible storage like Cloudflare R2, Hetzner, MinIO or Wasabi, Google Drive, Dropbox, OneDrive, SFTP, FTP/FTPS, WebDAV, SMB and rsync over SSH. Each of them can also be a source for file backups, and so can Docker volumes.
Expand Down
7 changes: 7 additions & 0 deletions changelog/unreleased/Skyfay-cloudflare-d1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### ✨ Features

- **Cloudflare D1**: New source that backs up and restores the D1 databases of a Cloudflare account through its API, with an API token and nothing to install. A restore keeps the database and its ID and logs a Time Travel bookmark to go back to. ([#202](https://github.com/Skyfay/DBackup/issues/202))

### 📝 Documentation

- **Cloudflare D1**: New source guide with the token setup, the lock during an export and import, and the values the export of Cloudflare cannot carry.
1 change: 1 addition & 0 deletions docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ export default defineConfig({
{ text: 'SQLite', link: '/user-guide/sources/sqlite' },
{ text: 'Microsoft SQL Server', link: '/user-guide/sources/mssql' },
{ text: 'Azure SQL Database', link: '/user-guide/sources/azure-sql' },
{ text: 'Cloudflare D1', link: '/user-guide/sources/cloudflare-d1' },
{ text: 'Firebird', link: '/user-guide/sources/firebird' }
]
},
Expand Down
4 changes: 3 additions & 1 deletion docs/developer-guide/adapters/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Database adapters handle the dump and restore operations for different database
| SQLite | `sqlite` | None (file copy) | ✅ | `sqlite` |
| MSSQL | `mssql` | None (TDS protocol) | ✅ (TDS tunnelled) | `bak` |
| Azure SQL Database | `azure-sql` | `sqlpackage` | ❌ (public PaaS endpoint) | `bacpac` |
| Cloudflare D1 | `cloudflare-d1` | None (REST API of Cloudflare) | ❌ (public API) | `sql` |
| Redis | `redis` | `redis-cli` | ✅ | `rdb` |
| Firebird | `firebird` | `gbak`, `isql` | ✅ | `fbk` |

Expand All @@ -24,7 +25,7 @@ Each adapter declares the format of its dump in `DB_FORMAT_BY_ADAPTER` in `src/l

| Format | Extension | Adapters | Stored as-is |
|--------|-----------|----------|--------------|
| `sql` | `.sql` | MySQL, MariaDB | |
| `sql` | `.sql` | MySQL, MariaDB, Cloudflare D1 | |
| `custom` | `.dump` | PostgreSQL | ✅ unless compression is `NONE` |
| `archive` | `.archive` | MongoDB | ✅ (`--gzip`) |
| `bak` | `.bak` | MSSQL | |
Expand Down Expand Up @@ -125,6 +126,7 @@ Each database adapter can optionally return size and table count information. Th
| **MongoDB** | Native `sizeOnDisk` from `listDatabases` command | `listCollections().length` per database |
| **MSSQL** | `sys.master_files` (`SUM(size) * 8 * 1024`) | `COUNT(*)` from `INFORMATION_SCHEMA.TABLES` |
| **Azure SQL Database** | `sys.database_files` (`SUM(size) * 8 * 1024`, data files only), one connection per database | `COUNT(*)` from `sys.tables`, same connection |
| **Cloudflare D1** | `file_size` of the database list, one API call for all | `num_tables` of the same list |
| **SQLite** | Not supported | Not supported |
| **Redis** | Not supported | Not supported |

Expand Down
7 changes: 7 additions & 0 deletions docs/developer-guide/reference/dev-lab.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ The lab reads the first config it finds: the file in `DBACKUP_LAB_CONFIG`, then
| `profile` | `core` for the oldest and newest version of each engine, `full` for every version | `core` |
| `docker` | The Docker host of the whole lab: its [docker context](https://docs.docker.com/engine/manage-resources/contexts/), the address DBackup reaches its ports under, and an `ssh` login for SQL Server, see [A Remote Docker Host](#a-remote-docker-host) | this machine |
| `native` | Servers without Docker by name: their address, an `ssh` login that may run the setup as root, and the `login` of their sources, see [A Native Server](#a-native-server) | none |
| `cloudflareD1` | The `accountId` and `token` of a Cloudflare account just for tests, see [Cloudflare D1](#cloudflare-d1). A token of `env:NAME` is read from that environment variable | none |

Every field is checked, and one the lab does not know is refused, so a typo does not go unnoticed.

Expand Down Expand Up @@ -134,6 +135,12 @@ The seed then adds every database of the server as a source in SSH mode. The end

MongoDB 5 and later need a CPU with AVX. A virtual machine with a generic CPU model has none, so give it the CPU type of its host, or MongoDB 8.0 does not start there, in a container or from the packages.

## Cloudflare D1

D1 runs at Cloudflare and nowhere else, so no container stands in for it. With `cloudflareD1` in the config, the seed makes sure the account holds the database `dbackup-lab-shop` with the SQLite dataset, adds the source **Lab Cloudflare D1** with a Token profile and the job **Lab Cloudflare D1 to Local**, which backs up that database only. Without it the lab has no D1 source, and `lab:status` says so.

Use a Cloudflare account of its own for this, with an API token that has **Account > D1 > Edit**. Cloudflare cannot limit a D1 token to single databases, so a token of an account with real databases could change every one of them. The free plan is enough.

## Adding an Engine or Version

Everything the lab knows about an engine is in its file under `lab/src/engines/`: the versions with their services and ports, the login, the clients in the container, the dataset with how to check for it and load it, the config of a source, and how its tools read a database and drop one again. The catalog, the dataset loader, the seed, `lab:status` and the tests all read it from there.
Expand Down
112 changes: 112 additions & 0 deletions docs/user-guide/sources/cloudflare-d1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# Cloudflare D1

Backs up the D1 databases of a Cloudflare account through the API of Cloudflare, with an API token and nothing to install.

## Supported Versions

| Database | Supported | Note |
| :--- | :--- | :--- |
| D1 databases of the current storage backend (`version: production`) | ✅ | Every database since D1 left its alpha |
| D1 databases of the alpha backend | ❌ | Cloudflare offers no export for them |
| Databases with a virtual table (FTS5, R*Tree) | ❌ | Cloudflare refuses to export them, see [Troubleshooting](#cannot-export-databases-with-virtual-tables) |

The connection is a whole Cloudflare account. A job picks one, several or all of its D1 databases, like the databases of a server.

## Prerequisites

An API token of the account with the permission **D1 Edit**:

1. In the Cloudflare dashboard, open the account and go to **Manage Account > Account API Tokens**.
2. **Create Token**, then **Custom Token**.
3. Under **Permissions**, add **Account > D1 > Edit**. Nothing else is needed.
4. Optionally limit the token to the IP address DBackup connects from and give it an expiry date.

::: warning D1 Read is not enough
Cloudflare allows the export of a database only with **D1 Edit**, even though a backup never writes. A token with **D1 Read** passes Test connection and fails at the first backup. Cloudflare also has no way to limit a D1 token to single databases: the token can change every D1 database of the account.
:::

## Configuration

::: info Credential Profiles
A `TOKEN` [credential profile](/user-guide/security/credential-profiles) holds the API token. Create one in **Vault > Credentials** before saving the source.
:::

| Field | Description | Default | Required |
| :--- | :--- | :--- | :--- |
| **Account ID** | The 32 hex characters on the overview of the account in the Cloudflare dashboard | - | ✅ |
| **Login** | `TOKEN` credential profile with the API token | - | ✅ |
| **Check the values before each backup** | Warns in the run log about values Cloudflare's export or import cannot carry, see [below](#values-cloudflare-cannot-carry) | On | ❌ |
| **Location of new databases** | Where a restore under a new name creates the database: **Automatic**, a jurisdiction (EU, FedRAMP) or a location hint | Automatic | ❌ |

## Setup Guide

1. Create the API token as described under [Prerequisites](#prerequisites).
2. In **Vault > Credentials**, add a profile of the type **Token** with the token.
3. In **Connections**, add a source of the type **Cloudflare D1**, enter the account ID and pick the profile.
4. **Test connection** lists the databases of the account.
5. Create a job and pick the databases to back up.

## How It Works

Each database is exported by Cloudflare as a SQL dump, the same file `wrangler d1 export` writes. DBackup starts the export, polls it until Cloudflare is done, downloads the dump from R2 and stores it as one `.sql` entry of the backup's archive, unchanged.

::: warning The database is locked during the export
Cloudflare answers queries on a database with errors while its export runs. A small database takes a second or two, one of about 120 MB around 10 seconds. Schedule the backup for a quiet time. Cancelling a run does not stop an export that has started, so the database stays locked until Cloudflare finishes it.
:::

Databases are picked by name and looked up on every run, so a database that was deleted and created again under the same name is backed up under its new ID.

::: info Rows read count against the account
Cloudflare bills rows read to the account. Besides the export, the check of the values reads every table once per backup, and the [Database Explorer](/user-guide/features/database-explorer) counts the rows of every table it lists and reads the rows of each page it shows. On the free plan these count against the daily limit.
:::

### Values Cloudflare cannot carry

Two kinds of values do not survive Cloudflare's export and import. DBackup takes the export as it is and cannot work around either:

- **Integers beyond 2^53** (9,007,199,254,740,991). SQLite stores integers with 64 bits, but the export writes them through JavaScript numbers. A larger one lands in the dump rounded, and one near 2^63 comes back from a restore as a floating point number. It mostly concerns IDs like those of Discord or Twitter stored as `INTEGER`. Store them as `TEXT` to keep them exact.
- **Values too long for one statement.** The export writes each row as one `INSERT`, and the import of D1 takes no statement over 100 KB. A row with a text over about 100 KB or a BLOB over about 50 KB is in the backup, but a restore into D1 fails on it, and the target stays as it was.

With **Check the values before each backup** on, DBackup reads every table once before the export and names each column that holds such a value in the run log. The backup runs either way. The check counts against the rows read of the account, so a connection with large databases can turn it off.

A text with a NUL character is restored correctly. The export writes it raw into the dump, where Cloudflare's import would stop reading without an error, so DBackup writes it as `char(0)` on the way to the import.

## Restore

Restoring onto an existing database **replaces its tables, views and triggers** with those of the backup, like every other source. The database itself stays, with its ID, so the Workers bound to it keep working. The drops and the dump run as one import, which Cloudflare runs in one transaction: if the import fails, the database is left exactly as it was.

Before it replaces anything, the restore writes the current [Time Travel](https://developers.cloudflare.com/d1/reference/time-travel/) bookmark of the database into its log, with the command that goes back to it:

```bash
wrangler d1 time-travel restore <name> --bookmark=<bookmark>
```

Restoring under a new name creates a new database. With **Location of new databases** on **Automatic**, it gets the jurisdiction of the database the backup came from while that one still exists, otherwise Cloudflare picks the location. The log names the ID of the new database, which a Worker needs as its `database_id`.

Like the export, an import locks the database while it runs. A database of about 120 MB took around 25 seconds to restore under a new name and around 35 seconds to restore over itself.

After the import DBackup checks that Cloudflare ran all of it, since Cloudflare can report an import complete that stopped early. A restore that did not run to the end fails with a message, and one into a database it created deletes that database again.

## Troubleshooting

### Cloudflare refused the export. The API token needs the permission D1 Edit

The token has **D1 Read** only. Edit the token in the Cloudflare dashboard and change the permission to **D1 Edit**.

### Cannot export databases with virtual tables

```
D1 Export error: cannot export databases with virtual tables (like FTS5)
```

**Solution:** Cloudflare cannot export a database that holds a virtual table, like an FTS5 search index. Drop the virtual tables before the backup and create them again afterwards, for example in the Worker that uses them, or leave this database out of the job.

### Cloudflare refused the API token

The token is wrong, expired, limited to other IP addresses, or belongs to another account than the account ID. Check it under **Account API Tokens**, and that the account ID is the one of the same account.

## Next Steps

- [Restore Guide](/user-guide/features/restore) - General restore documentation
- [Encryption](/user-guide/security/encryption) - Encrypting your backups
- [Database Explorer](/user-guide/features/database-explorer) - Browsing the tables of a D1 database
1 change: 1 addition & 0 deletions docs/user-guide/sources/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ DBackup supports a wide variety of database engines.
| [SQLite](/user-guide/sources/sqlite) | 3.x | `sqlite3 .backup`, stores the database file | ✅ |
| [MSSQL](/user-guide/sources/mssql) | 2017, 2019, 2022, Azure SQL Edge | `BACKUP DATABASE` | ✅ |
| [Azure SQL Database](/user-guide/sources/azure-sql) (beta) | Single database, elastic pool | `SqlPackage` BACPAC export | ✅ (drops the target first) |
| [Cloudflare D1](/user-guide/sources/cloudflare-d1) (beta) | Every D1 database of an account | D1 export API, SQL dump | ✅ (replaces the tables, keeps the database) |
| [Firebird](/user-guide/sources/firebird) (beta) | 3.x, 4.x, 5.x | `gbak` | ✅ (pre-configured aliases) |

## Directory Sources
Expand Down
1 change: 1 addition & 0 deletions e2e/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ pnpm test:e2e:ui # Playwright UI mode
| `small` | `engines.spec.ts`, `folders.spec.ts` | Redis, Valkey, Firebird, SQLite over SSH, a folder |
| `customer` | `engines.spec.ts` | The databases of the customer server over its OpenSSH |
| `storage` | `storage.spec.ts`, `notifications.spec.ts` | Every destination and every channel, with SQLite inside DBackup as the source |
| `cloud` | `cloud.spec.ts` | Cloudflare D1 in a test account at Cloudflare, through `support/cloudflare.ts`. Skips without `E2E_D1_ACCOUNT_ID` and `E2E_D1_TOKEN` (CI reads them from the variable and the secret of the same names) or `cloudflareD1` in the lab config |

- The sign-in specs under `tests/ui/` (`auth*.spec.ts`) make a person of their own per test through `support/auth.ts`, never a second factor or a passkey on the shared admin, which the setup signs in with on every run. The code of an authenticator app comes from the key the setup shows (`totp`), a passkey from the virtual authenticator of Chromium over CDP (`addVirtualAuthenticator`). better-auth limits `/sign-in/*` and `/two-factor/*` on its own, three requests from one address each within ten seconds of the last, which Settings does not lift, so every such request goes through `paced` and the specs end with `quietLimits`.
- `auth-sso.spec.ts` and `tenants-sso.spec.ts` sign in through Dex, the service `dex` of `lab/compose/e2e.yml` with `DEX` of `lab/src/catalog.ts`. DBackup reaches it at `http://dex:5556` in the network of the lab, and the browser of the `ui` project at the same name through `DEX_HOST_RULE` (`--host-resolver-rules`), so both see one issuer. Dex knows a fixed client and fixed people, so each attempt of a retry takes the provider ID and the people of its number (`dexProviderId`, `dexPerson`). Its client redirects to port 3300 only, so another `E2E_PORT` skips the specs. The tenant spec claims a domain of its own (`DEX_TENANT_DOMAIN`, `dexTenantPerson`), since the provider of the platform adds nobody of a domain a tenant claims. A new person or redirect URI goes into the inline config of Dex in `e2e.yml`, which `tests/unit/lab/lab-parts.test.ts` checks against the catalog.
Expand Down
Loading
Loading