feat(database-lab): add local database test environments

This commit is contained in:
二丫讲梵
2026-07-18 22:11:35 +08:00
committed by GitHub
parent 2a65b278e8
commit dda65c0ef0
53 changed files with 1705 additions and 2 deletions
@@ -0,0 +1,50 @@
name: Database Environments
on:
push:
branches: [main]
paths:
- 'deploy/database/**'
- 'scripts/database-env.mjs'
- 'scripts/database-env.test.mjs'
- 'Makefile'
- 'package.json'
- 'pnpm-lock.yaml'
- 'docs/content/docs/database-lab.mdx'
- 'docs/content/docs/database-lab.cn.mdx'
- '.github/workflows/database-environments.yml'
pull_request:
branches: [main]
paths:
- 'deploy/database/**'
- 'scripts/database-env.mjs'
- 'scripts/database-env.test.mjs'
- 'Makefile'
- 'package.json'
- 'pnpm-lock.yaml'
- 'docs/content/docs/database-lab.mdx'
- 'docs/content/docs/database-lab.cn.mdx'
- '.github/workflows/database-environments.yml'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
database-environments:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v5
- name: Setup pnpm
uses: pnpm/action-setup@v6
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: 22.13.0
- name: Validate database environment tooling
run: |
pnpm test:db-env
make db-check
+39 -1
View File
@@ -3,7 +3,15 @@
PNPM ?= pnpm
TAURI_DEV_PORT ?= 1420
.PHONY: help install docs-install check-tauri-dev-port dev dev-fast dev-web dev-backend build package docs docs-build check test cargo-check-fast cargo-test-fast
.PHONY: help install docs-install check-tauri-dev-port dev dev-fast dev-web dev-backend build package docs docs-build check test cargo-check-fast cargo-test-fast db db-list db-verify db-down db-reset db-check db-completion
export DB
export DB_VERSION
export DB_BIND_ADDRESS
export DB_PORT
export DB_PASSWORD
export FOLLOW
export CONFIRM
node_modules/.modules.yaml: package.json pnpm-lock.yaml
$(PNPM) install --frozen-lockfile
@@ -34,6 +42,15 @@ help:
@printf ' %-23s %s\n' 'make cargo-check-fast' 'Run Rust check without default features'
@printf ' %-23s %s\n' 'make cargo-test-fast' 'Run Rust tests without default features'
@printf '%s\n' ''
@printf '%s\n' 'Database test environments:'
@printf ' %-23s %s\n' 'make db-list' 'List available database versions'
@printf ' %-23s %s\n' 'make db DB=mysql@8.4' 'Start and print DBX connection fields'
@printf ' %-23s %s\n' 'make db-verify DB=mysql@8.4' 'Start and run smoke checks'
@printf ' %-23s %s\n' 'make db-down DB=mysql@8.4' 'Stop an environment'
@printf ' %-23s %s\n' 'make db-reset DB=mysql@8.4 CONFIRM=1' 'Delete containers and data'
@printf ' %-23s %s\n' 'make db-check' 'Validate every recipe and Compose file'
@printf ' %-23s %s\n' 'make db-completion' 'Show Bash/Zsh completion setup'
@printf '%s\n' ''
@printf '%s\n' 'Setup:'
@printf ' %-23s %s\n' 'make install' 'Install root project dependencies'
@@ -88,3 +105,24 @@ cargo-check-fast:
cargo-test-fast:
cargo test --no-default-features
db-list:
@$(PNPM) db:env -- list
db:
@$(PNPM) db:env -- start
db-verify:
@$(PNPM) db:env -- verify
db-down:
@$(PNPM) db:env -- down
db-reset:
@$(PNPM) db:env -- reset
db-check:
@$(PNPM) db:env -- check
db-completion:
@$(PNPM) db:env -- completion
+8
View File
@@ -340,6 +340,13 @@ make docs
The official DBX documentation site lives in `docs/`. If you want to improve the website content or documentation pages, edit the files under `docs/` and run `make docs` to preview the site locally.
For clean, reproducible local database instances, use the versioned Docker Compose recipes under [`deploy/database/`](deploy/database/README.md):
```bash
make db-list
make db-verify DB=mysql@8.4
```
JDBC agent driver development projects live in `agents/`:
```bash
@@ -370,6 +377,7 @@ The installer will be in `src-tauri/target/release/bundle/`.
## Documentation
- [Official docs](https://dbxio.com/en/docs/what-is-dbx) — feature guides and tutorials
- [Database Test Lab](https://dbxio.com/en/docs/database-lab) — local database recipes for development and verification
- [Contributing](CONTRIBUTING.md) — how to pick up issues and open PRs
- [Web API reference](docs/content/docs/web-api.mdx) — HTTP API for Docker/Web deployments
- [Examples](examples/) — CLI, MCP, Docker, and API samples
+8
View File
@@ -338,6 +338,13 @@ make docs
DBX 官网文档位于 `docs/` 目录。如果你想贡献官网内容或文档页面,请修改 `docs/` 下的文件,并运行 `make docs` 在本地预览文档站。
需要干净、可重复创建的本地数据库实例时,可使用 [`deploy/database/`](deploy/database/README.zh-CN.md) 下的带版本 Docker Compose 配方:
```bash
make db-list
make db-verify DB=mysql@8.4
```
JDBC Agent 驱动开发工程位于 `agents/` 目录:
```bash
@@ -368,6 +375,7 @@ make package
## 文档
- [官方文档](https://dbxio.com/cn/docs/what-is-dbx) — 功能说明与使用教程
- [数据库测试实验室](https://dbxio.com/cn/docs/database-lab) — 用于开发和验证的本地数据库配方
- [贡献指南](CONTRIBUTING.zh-CN.md) — 如何认领 Issue 并提交 PR
- [Web API 参考](docs/content/docs/web-api.cn.mdx) — Docker/Web 部署的 HTTP API
- [示例代码](examples/) — CLI、MCP、Docker 与 API 示例
+31
View File
@@ -0,0 +1,31 @@
# DBX Database Test Environments
This directory contains reproducible Docker Compose environments for manual database verification. Each versioned recipe uses a pinned image, a named volume, a loopback-only port binding, a health check, and initialization data or smoke data created during verification.
Run commands from the repository root:
```bash
make db-list
make db DB=mysql@8.4
make db-verify DB=postgresql@17.4
make db-down DB=postgresql@17.4
```
Every network recipe uses the standard database port plus one on the host. The default password is `123456`, and the default database is `dbx`; Redis uses DB 0 and the `dbx:` key prefix. Container names follow `dbx-<product>-<version>`. Versions of the same database share the default host port, so use `DB_PORT` when running them concurrently. `DB_PORT` and `DB_PASSWORD` override the default host port and password. Ports bind to `127.0.0.1` by default. To allow remote access explicitly, set `DB_BIND_ADDRESS=0.0.0.0`, choose a strong `DB_PASSWORD`, and protect the host with firewall rules. `make db-reset` deletes the named volume and therefore requires `CONFIRM=1`:
```bash
make db-reset DB=redis@7.4 CONFIRM=1
```
The primary Make targets are `db-list`, `db`, `db-verify`, `db-down`, `db-reset`, and `db-check`. Run `make db` to print one copyable start command for every recipe. `make db-completion` prints Bash, Zsh, and PowerShell completion setup; the scripts in `completion/` dynamically complete recipe selectors. The targets avoid POSIX-shell conditionals and work with GNU Make in PowerShell, Git Bash, or WSL. For diagnosis, use the lower-level `pnpm db:env -- info|status|logs|shell <product> <version>` commands.
## Recipe layout
```text
<product>/<version>/
├── recipe.json # connection fields and smoke commands
├── compose.yaml # Docker Compose environment
└── init/ # data initialized with the environment
```
Redis does not support the image initialization-directory convention; its `init/README.md` documents the smoke key that `verify` creates and reads. Run `make db-check` after adding or editing a recipe. It verifies the recipe structure and standardized container name, then asks Docker Compose to validate each Compose file.
+31
View File
@@ -0,0 +1,31 @@
# DBX 数据库测试环境
此目录提供可重复创建的 Docker Compose 数据库环境,用于人工验证数据库功能。每个带版本的配方都固定镜像版本、使用命名卷、仅绑定本机回环地址、定义健康检查,并提供初始化数据或在验证阶段创建的冒烟数据。
在仓库根目录执行:
```bash
make db-list
make db DB=mysql@8.4
make db-verify DB=postgresql@17.4
make db-down DB=postgresql@17.4
```
所有网络数据库默认使用标准端口 `+1` 的宿主端口,默认密码统一为 `123456`,默认数据库名为 `dbx`;Redis 使用 DB 0 和 `dbx:` 键前缀。容器名统一为 `dbx-<product>-<version>`。同一种数据库的不同版本共用默认宿主端口,并行启动时请使用 `DB_PORT` 覆盖其中一个端口。`DB_PORT` 和 `DB_PASSWORD` 可以覆盖默认主机端口和密码。端口默认仅绑定 `127.0.0.1`;如需远程访问,必须显式设置 `DB_BIND_ADDRESS=0.0.0.0`,同时使用强密码和防火墙限制访问。`make db-reset` 会删除命名卷及其数据,因此必须显式传入 `CONFIRM=1`:
```bash
make db-reset DB=redis@7.4 CONFIRM=1
```
主要 Make 目标为 `db-list`、`db`、`db-verify`、`db-down`、`db-reset` 和 `db-check`。执行 `make db` 会为每个配方输出一条可直接复制的启动命令。`make db-completion` 会输出 Bash、Zsh 和 PowerShell 补全加载命令,`completion/` 中的脚本会动态补全配方选择器。目标不再依赖 POSIX Shell 条件语法,可在 PowerShell、Git Bash 或 WSL 中通过 GNU Make 使用。诊断时可使用底层命令 `pnpm db:env -- info|status|logs|shell <product> <version>`。
## 配方结构
```text
<product>/<version>/
├── recipe.json # 连接字段和冒烟命令
├── compose.yaml # Docker Compose 环境
└── init/ # 环境初始化数据
```
Redis 不支持镜像初始化目录约定;其 `init/README.md` 说明了 `verify` 会创建并读取的冒烟键。添加或修改配方后运行 `make db-check`。它会检查配方结构、标准容器名,并要求 Docker Compose 校验每个 Compose 文件。
+14
View File
@@ -0,0 +1,14 @@
# Database Recipe Template
Create `deploy/database/<product>/<version>/` with `recipe.json`, `compose.yaml`, and an `init/` directory. Set `defaultPort` in `recipe.json` to the native service port; the connection port and Compose `DB_PORT` fallback must both be `defaultPort + 1`.
Every recipe must use a pinned image, default its host binding to `${DB_BIND_ADDRESS:-127.0.0.1}`, use the standard port plus one by default, set `container_name` to `dbx-<product>-<version>`, use password `123456`, and initialize database `dbx`. Redis-like services without named databases use DB 0 and the `dbx:` key prefix.
Add both a non-interactive `smoke.steps` command and an interactive `shell` command to `recipe.json`, then run:
```bash
pnpm test:db-env
make db-check
make db-verify DB=<product>@<version>
make db-reset DB=<product>@<version> CONFIRM=1
```
@@ -0,0 +1,21 @@
services:
database:
image: docker.cnb.cool/znb/images/clickhouse-server:24.8.14.39
container_name: dbx-clickhouse-24.8
ports:
- "${DB_BIND_ADDRESS:-127.0.0.1}:${DB_PORT:-8124}:8123"
environment:
CLICKHOUSE_DB: dbx
CLICKHOUSE_USER: default
CLICKHOUSE_PASSWORD: "${DB_PASSWORD:-123456}"
volumes:
- data:/var/lib/clickhouse
- ./init:/docker-entrypoint-initdb.d:ro
healthcheck:
test: ["CMD-SHELL", "clickhouse-client --user default --password \"$$CLICKHOUSE_PASSWORD\" --query 'SELECT 1' | grep 1"]
interval: 5s
timeout: 5s
retries: 30
start_period: 15s
volumes:
data:
@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS dbx_smoke (
id UInt64,
note String,
nullable_value Nullable(String),
created_at DateTime DEFAULT now()
) ENGINE = MergeTree
ORDER BY id;
INSERT INTO dbx_smoke (id, note, nullable_value) VALUES (1, 'DBX smoke 中文 🚀', NULL);
@@ -0,0 +1,13 @@
{
"database": "clickhouse",
"name": "ClickHouse",
"version": "24.8.14.39",
"displayVersion": "24.8",
"image": "docker.cnb.cool/znb/images/clickhouse-server:24.8.14.39",
"platforms": ["linux/amd64", "linux/arm64"],
"service": "database",
"defaultPort": 8123,
"connection": { "host": "127.0.0.1", "port": 8124, "username": "default", "password": "123456", "database": "dbx" },
"shell": ["clickhouse-client", "--user", "default", "--password", "${DB_PASSWORD}", "--database", "dbx"],
"smoke": { "steps": [{ "name": "query initialized row", "command": ["clickhouse-client", "--user", "default", "--password", "${DB_PASSWORD}", "--database", "dbx", "--query", "SELECT note FROM dbx_smoke WHERE id = 1"], "expect": "DBX smoke" }] }
}
+69
View File
@@ -0,0 +1,69 @@
# Dot-source this file to complete DBX database Make targets and DB=<product>@<version> values.
$script:DbxMakeRepositoryRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..\..')).Path
function Get-DbxMakeDatabaseSelector {
& node (Join-Path $script:DbxMakeRepositoryRoot 'scripts\database-env.mjs') selectors 2>$null
}
function Get-DbxMakeTarget {
& node (Join-Path $script:DbxMakeRepositoryRoot 'scripts\database-env.mjs') make-targets 2>$null
}
function New-DbxMakeCompletionResult {
param([string]$Value, [string]$ToolTip = $Value)
[System.Management.Automation.CompletionResult]::new(
$Value,
$Value,
[System.Management.Automation.CompletionResultType]::ParameterValue,
$ToolTip
)
}
$script:DbxMakeDatabaseTargets = @('db', 'db-verify', 'db-down', 'db-reset')
$script:DbxMakeNativeCompleter = {
param($wordToComplete, $commandAst, $cursorPosition)
$elements = @($commandAst.CommandElements | ForEach-Object { $_.Extent.Text })
$target = if ($elements.Count -gt 1) { $elements[1] } else { '' }
$currentPath = (Resolve-Path -LiteralPath (Get-Location)).Path
if (-not [StringComparer]::OrdinalIgnoreCase.Equals($currentPath, $script:DbxMakeRepositoryRoot)) { return }
if ($elements.Count -le 2) {
Get-DbxMakeTarget |
Where-Object { $_ -like "$wordToComplete*" } |
ForEach-Object { New-DbxMakeCompletionResult $_ 'Make target' }
return
}
if ($target -notin $script:DbxMakeDatabaseTargets) { return }
if ($wordToComplete -like 'DB=*') {
$prefix = 'DB='
Get-DbxMakeDatabaseSelector |
Where-Object { "$prefix$_" -like "$wordToComplete*" } |
ForEach-Object { New-DbxMakeCompletionResult "$prefix$_" 'Database recipe' }
return
}
if ($wordToComplete -like 'CONFIRM=*') {
New-DbxMakeCompletionResult 'CONFIRM=1' 'Required by db-reset'
return
}
$parameters = @('DB=', 'DB_BIND_ADDRESS=', 'DB_PORT=', 'DB_PASSWORD=')
if ($target -eq 'db-reset') { $parameters += 'CONFIRM=1' }
$parameters |
Where-Object { $_ -like "$wordToComplete*" } |
ForEach-Object { New-DbxMakeCompletionResult $_ 'DBX database parameter' }
}
$register = Get-Command Register-ArgumentCompleter
if ($register.Parameters.ContainsKey('Native')) {
Register-ArgumentCompleter -Native -CommandName make -ScriptBlock $script:DbxMakeNativeCompleter
} else {
Register-ArgumentCompleter -CommandName make -ScriptBlock {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
& $script:DbxMakeNativeCompleter $wordToComplete $commandAst $null
}
}
+50
View File
@@ -0,0 +1,50 @@
#compdef make
# Source this file after running `autoload -Uz compinit && compinit`.
typeset -g _dbx_make_repository_root="${${(%):-%x}:A:h:h:h:h}"
if (( ! ${+_dbx_make_previous_completion} )); then
typeset -g _dbx_make_previous_completion="${_comps[make]:-_make}"
fi
_dbx_make_database_selectors() {
node "$_dbx_make_repository_root/scripts/database-env.mjs" selectors 2>/dev/null
}
_dbx_make_fallback() {
local completer="${_dbx_make_previous_completion:-_make}"
[[ "$completer" == _dbx_make ]] && completer=_make
"$completer" "$@"
}
_dbx_make() {
local current="${words[CURRENT]}"
local target="${words[2]}"
local -a selectors parameters
if [[ "${PWD:A}" != "$_dbx_make_repository_root" ]] || (( CURRENT == 2 )); then
_dbx_make_fallback "$@"
return
fi
case "$target" in
db|db-verify|db-down|db-reset)
if [[ "$current" == DB=* ]]; then
selectors=("${(@f)$(_dbx_make_database_selectors)}")
compset -P 'DB='
_describe 'database recipe' selectors
elif [[ "$target" == db-reset && "$current" == CONFIRM=* ]]; then
compset -P 'CONFIRM='
compadd '1'
else
parameters=(DB DB_BIND_ADDRESS DB_PORT DB_PASSWORD)
[[ "$target" == db-reset ]] && parameters+=(CONFIRM)
compadd -S '=' -- $parameters
fi
;;
*)
_dbx_make_fallback "$@"
;;
esac
}
compdef _dbx_make make
+76
View File
@@ -0,0 +1,76 @@
# Source this file to complete DBX database Make targets and DB=<product>@<version> values.
_dbx_make_repository_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../../.." && pwd)"
if [[ -z ${_dbx_make_previous_completion+x} ]]; then
_dbx_make_previous_completion=''
_dbx_make_completion_spec="$(complete -p make 2>/dev/null || true)"
if [[ "$_dbx_make_completion_spec" =~ -F[[:space:]]+([^[:space:]]+) ]]; then
_dbx_make_previous_completion="${BASH_REMATCH[1]}"
fi
unset _dbx_make_completion_spec
fi
_dbx_make_database_selectors() {
node "$_dbx_make_repository_root/scripts/database-env.mjs" selectors 2>/dev/null
}
_dbx_make_targets() {
node "$_dbx_make_repository_root/scripts/database-env.mjs" make-targets 2>/dev/null
}
_dbx_make_fallback() {
local current="${COMP_WORDS[COMP_CWORD]}"
if [[ -n "$_dbx_make_previous_completion" ]] && declare -F "$_dbx_make_previous_completion" >/dev/null; then
"$_dbx_make_previous_completion"
return
fi
COMPREPLY=()
[[ "$1" == targets ]] || return
local targets
targets="$(_dbx_make_targets)"
COMPREPLY=( $(compgen -W "$targets" -- "$current") )
}
_dbx_make() {
local current="${COMP_WORDS[COMP_CWORD]}"
local target="${COMP_WORDS[1]}"
local selectors
if [[ "$(pwd -P)" != "$_dbx_make_repository_root" ]]; then
_dbx_make_fallback
return
fi
if (( COMP_CWORD == 1 )); then
_dbx_make_fallback targets
return
fi
case "$target" in
db|db-verify|db-down|db-reset)
compopt +o bashdefault +o default 2>/dev/null || true
case "$current" in
DB=*)
selectors="$(_dbx_make_database_selectors)"
COMPREPLY=( $(compgen -W "$(printf 'DB=%s ' $selectors)" -- "$current") )
;;
CONFIRM=*)
COMPREPLY=( $(compgen -W 'CONFIRM=1' -- "$current") )
;;
*)
if [[ "$target" == 'db-reset' ]]; then
COMPREPLY=( $(compgen -W 'DB= DB_BIND_ADDRESS= DB_PORT= DB_PASSWORD= CONFIRM=1' -- "$current") )
else
COMPREPLY=( $(compgen -W 'DB= DB_BIND_ADDRESS= DB_PORT= DB_PASSWORD=' -- "$current") )
fi
;;
esac
;;
*)
_dbx_make_fallback
;;
esac
}
complete -o bashdefault -o default -F _dbx_make make
@@ -0,0 +1,20 @@
services:
database:
image: docker.cnb.cool/znb/images/mariadb:10.11.11
container_name: dbx-mariadb-10.11
ports:
- "${DB_BIND_ADDRESS:-127.0.0.1}:${DB_PORT:-3307}:3306"
environment:
MARIADB_ROOT_PASSWORD: "${DB_PASSWORD:-123456}"
MARIADB_DATABASE: dbx
volumes:
- data:/var/lib/mysql
- ./init:/docker-entrypoint-initdb.d:ro
healthcheck:
test: ["CMD-SHELL", "mariadb-admin ping -h 127.0.0.1 -uroot -p\"$$MARIADB_ROOT_PASSWORD\" --silent"]
interval: 5s
timeout: 5s
retries: 30
start_period: 20s
volumes:
data:
@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS dbx_smoke (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
note VARCHAR(255) NOT NULL,
nullable_value VARCHAR(64) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_dbx_smoke_note (note)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO dbx_smoke (note, nullable_value) VALUES ('DBX smoke 中文 🚀', NULL);
+13
View File
@@ -0,0 +1,13 @@
{
"database": "mariadb",
"name": "MariaDB",
"version": "10.11.11",
"displayVersion": "10.11",
"image": "docker.cnb.cool/znb/images/mariadb:10.11.11",
"platforms": ["linux/amd64", "linux/arm64"],
"service": "database",
"defaultPort": 3306,
"connection": { "host": "127.0.0.1", "port": 3307, "username": "root", "password": "123456", "database": "dbx" },
"shell": ["mariadb", "-uroot", "-p${DB_PASSWORD}", "-Ddbx"],
"smoke": { "steps": [{ "name": "query initialized row", "command": ["mariadb", "-uroot", "-p${DB_PASSWORD}", "-Ddbx", "-Nse", "SELECT note FROM dbx_smoke WHERE id=1"], "expect": "DBX smoke" }] }
}
+21
View File
@@ -0,0 +1,21 @@
services:
database:
image: docker.cnb.cool/znb/images/mongo:5.0.5
container_name: dbx-mongodb-5.0
ports:
- "${DB_BIND_ADDRESS:-127.0.0.1}:${DB_PORT:-27018}:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: "${DB_PASSWORD:-123456}"
MONGO_INITDB_DATABASE: dbx
volumes:
- data:/data/db
- ./init:/docker-entrypoint-initdb.d:ro
healthcheck:
test: ["CMD-SHELL", "mongosh --quiet --username root --password \"$$MONGO_INITDB_ROOT_PASSWORD\" --authenticationDatabase admin --eval 'db.adminCommand({ ping: 1 }).ok' | grep 1"]
interval: 5s
timeout: 5s
retries: 30
start_period: 15s
volumes:
data:
@@ -0,0 +1,3 @@
db = db.getSiblingDB('dbx');
db.dbx_smoke.createIndex({ note: 1 });
db.dbx_smoke.insertOne({ _id: 1, note: 'DBX smoke 中文 🚀', nullableValue: null, createdAt: new Date() });
+13
View File
@@ -0,0 +1,13 @@
{
"database": "mongodb",
"name": "MongoDB",
"version": "5.0.5",
"displayVersion": "5.0",
"image": "docker.cnb.cool/znb/images/mongo:5.0.5",
"platforms": ["linux/amd64", "linux/arm64"],
"service": "database",
"defaultPort": 27017,
"connection": { "host": "127.0.0.1", "port": 27018, "username": "root", "password": "123456", "database": "dbx", "authSource": "admin" },
"shell": ["mongosh", "--quiet", "--host", "127.0.0.1", "--port", "27017", "--username", "root", "--password", "${DB_PASSWORD}", "--authenticationDatabase", "admin", "dbx"],
"smoke": { "steps": [{ "name": "query initialized document over TCP", "command": ["mongosh", "--quiet", "--host", "127.0.0.1", "--port", "27017", "--username", "root", "--password", "${DB_PASSWORD}", "--authenticationDatabase", "admin", "dbx", "--eval", "db.dbx_smoke.findOne({_id: 1}).note"], "expect": "DBX smoke" }] }
}
+21
View File
@@ -0,0 +1,21 @@
services:
database:
image: docker.cnb.cool/znb/images/mongo:8.2.3-noble
container_name: dbx-mongodb-8.2
ports:
- "${DB_BIND_ADDRESS:-127.0.0.1}:${DB_PORT:-27018}:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: "${DB_PASSWORD:-123456}"
MONGO_INITDB_DATABASE: dbx
volumes:
- data:/data/db
- ./init:/docker-entrypoint-initdb.d:ro
healthcheck:
test: ["CMD-SHELL", "mongosh --quiet --username root --password \"$$MONGO_INITDB_ROOT_PASSWORD\" --authenticationDatabase admin --eval 'db.adminCommand({ ping: 1 }).ok' | grep 1"]
interval: 5s
timeout: 5s
retries: 30
start_period: 15s
volumes:
data:
@@ -0,0 +1,3 @@
db = db.getSiblingDB('dbx');
db.dbx_smoke.createIndex({ note: 1 });
db.dbx_smoke.insertOne({ _id: 1, note: 'DBX smoke 中文 🚀', nullableValue: null, createdAt: new Date() });
+13
View File
@@ -0,0 +1,13 @@
{
"database": "mongodb",
"name": "MongoDB",
"version": "8.2.3",
"displayVersion": "8.2",
"image": "docker.cnb.cool/znb/images/mongo:8.2.3-noble",
"platforms": ["linux/amd64", "linux/arm64"],
"service": "database",
"defaultPort": 27017,
"connection": { "host": "127.0.0.1", "port": 27018, "username": "root", "password": "123456", "database": "dbx", "authSource": "admin" },
"shell": ["mongosh", "--quiet", "--host", "127.0.0.1", "--port", "27017", "--username", "root", "--password", "${DB_PASSWORD}", "--authenticationDatabase", "admin", "dbx"],
"smoke": { "steps": [{ "name": "query initialized document over TCP", "command": ["mongosh", "--quiet", "--host", "127.0.0.1", "--port", "27017", "--username", "root", "--password", "${DB_PASSWORD}", "--authenticationDatabase", "admin", "dbx", "--eval", "db.dbx_smoke.findOne({_id: 1}).note"], "expect": "DBX smoke" }] }
}
+20
View File
@@ -0,0 +1,20 @@
services:
database:
image: docker.cnb.cool/znb/images/mysql:5.7.44
container_name: dbx-mysql-5.7
ports:
- "${DB_BIND_ADDRESS:-127.0.0.1}:${DB_PORT:-3307}:3306"
environment:
MYSQL_ROOT_PASSWORD: "${DB_PASSWORD:-123456}"
MYSQL_DATABASE: dbx
volumes:
- data:/var/lib/mysql
- ./init:/docker-entrypoint-initdb.d:ro
healthcheck:
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p\"$$MYSQL_ROOT_PASSWORD\" --silent"]
interval: 5s
timeout: 5s
retries: 30
start_period: 20s
volumes:
data:
@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS dbx_smoke (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
note VARCHAR(255) NOT NULL,
nullable_value VARCHAR(64) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_dbx_smoke_note (note)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO dbx_smoke (note, nullable_value) VALUES ('DBX smoke 中文 🚀', NULL);
+13
View File
@@ -0,0 +1,13 @@
{
"database": "mysql",
"name": "MySQL",
"version": "5.7.44",
"displayVersion": "5.7",
"image": "docker.cnb.cool/znb/images/mysql:5.7.44",
"platforms": ["linux/amd64", "linux/arm64"],
"service": "database",
"defaultPort": 3306,
"connection": { "host": "127.0.0.1", "port": 3307, "username": "root", "password": "123456", "database": "dbx" },
"shell": ["mysql", "-uroot", "-p${DB_PASSWORD}", "-Ddbx"],
"smoke": { "steps": [{ "name": "query initialized row", "command": ["mysql", "-uroot", "-p${DB_PASSWORD}", "-Ddbx", "-Nse", "SELECT note FROM dbx_smoke WHERE id=1"], "expect": "DBX smoke" }] }
}
+20
View File
@@ -0,0 +1,20 @@
services:
database:
image: docker.cnb.cool/znb/images/mysql:8.4.6
container_name: dbx-mysql-8.4
ports:
- "${DB_BIND_ADDRESS:-127.0.0.1}:${DB_PORT:-3307}:3306"
environment:
MYSQL_ROOT_PASSWORD: "${DB_PASSWORD:-123456}"
MYSQL_DATABASE: dbx
volumes:
- data:/var/lib/mysql
- ./init:/docker-entrypoint-initdb.d:ro
healthcheck:
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p\"$$MYSQL_ROOT_PASSWORD\" --silent"]
interval: 5s
timeout: 5s
retries: 30
start_period: 20s
volumes:
data:
@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS dbx_smoke (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
note VARCHAR(255) NOT NULL,
nullable_value VARCHAR(64) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_dbx_smoke_note (note)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO dbx_smoke (note, nullable_value) VALUES ('DBX smoke 中文 🚀', NULL);
+13
View File
@@ -0,0 +1,13 @@
{
"database": "mysql",
"name": "MySQL",
"version": "8.4.6",
"displayVersion": "8.4",
"image": "docker.cnb.cool/znb/images/mysql:8.4.6",
"platforms": ["linux/amd64", "linux/arm64"],
"service": "database",
"defaultPort": 3306,
"connection": { "host": "127.0.0.1", "port": 3307, "username": "root", "password": "123456", "database": "dbx" },
"shell": ["mysql", "-uroot", "-p${DB_PASSWORD}", "-Ddbx"],
"smoke": { "steps": [{ "name": "query initialized row", "command": ["mysql", "-uroot", "-p${DB_PASSWORD}", "-Ddbx", "-Nse", "SELECT note FROM dbx_smoke WHERE id=1"], "expect": "DBX smoke" }] }
}
@@ -0,0 +1,19 @@
services:
database:
image: docker.cnb.cool/znb/images/postgres:14.23
container_name: dbx-postgresql-14.23
ports:
- "${DB_BIND_ADDRESS:-127.0.0.1}:${DB_PORT:-5433}:5432"
environment:
POSTGRES_PASSWORD: "${DB_PASSWORD:-123456}"
POSTGRES_DB: dbx
volumes:
- data:/var/lib/postgresql/data
- ./init:/docker-entrypoint-initdb.d:ro
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d dbx"]
interval: 5s
timeout: 5s
retries: 30
volumes:
data:
@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS dbx_smoke (
id BIGSERIAL PRIMARY KEY,
note TEXT NOT NULL,
nullable_value TEXT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_dbx_smoke_note ON dbx_smoke (note);
INSERT INTO dbx_smoke (note, nullable_value) VALUES ('DBX smoke 中文 🚀', NULL);
@@ -0,0 +1,13 @@
{
"database": "postgresql",
"name": "PostgreSQL",
"version": "14.23",
"displayVersion": "14.23",
"image": "docker.cnb.cool/znb/images/postgres:14.23",
"platforms": ["linux/amd64", "linux/arm64"],
"service": "database",
"defaultPort": 5432,
"connection": { "host": "127.0.0.1", "port": 5433, "username": "postgres", "password": "123456", "database": "dbx" },
"shell": ["env", "PGPASSWORD=${DB_PASSWORD}", "psql", "-h", "127.0.0.1", "-p", "5432", "-U", "postgres", "-d", "dbx"],
"smoke": { "steps": [{ "name": "query initialized row over TCP", "command": ["env", "PGPASSWORD=${DB_PASSWORD}", "psql", "-h", "127.0.0.1", "-p", "5432", "-U", "postgres", "-d", "dbx", "-Atc", "SELECT note FROM dbx_smoke WHERE id=1"], "expect": "DBX smoke" }] }
}
@@ -0,0 +1,19 @@
services:
database:
image: docker.cnb.cool/znb/images/postgres:17.4
container_name: dbx-postgresql-17.4
ports:
- "${DB_BIND_ADDRESS:-127.0.0.1}:${DB_PORT:-5433}:5432"
environment:
POSTGRES_PASSWORD: "${DB_PASSWORD:-123456}"
POSTGRES_DB: dbx
volumes:
- data:/var/lib/postgresql/data
- ./init:/docker-entrypoint-initdb.d:ro
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d dbx"]
interval: 5s
timeout: 5s
retries: 30
volumes:
data:
@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS dbx_smoke (
id BIGSERIAL PRIMARY KEY,
note TEXT NOT NULL,
nullable_value TEXT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_dbx_smoke_note ON dbx_smoke (note);
INSERT INTO dbx_smoke (note, nullable_value) VALUES ('DBX smoke 中文 🚀', NULL);
@@ -0,0 +1,13 @@
{
"database": "postgresql",
"name": "PostgreSQL",
"version": "17.4",
"displayVersion": "17.4",
"image": "docker.cnb.cool/znb/images/postgres:17.4",
"platforms": ["linux/amd64", "linux/arm64"],
"service": "database",
"defaultPort": 5432,
"connection": { "host": "127.0.0.1", "port": 5433, "username": "postgres", "password": "123456", "database": "dbx" },
"shell": ["env", "PGPASSWORD=${DB_PASSWORD}", "psql", "-h", "127.0.0.1", "-p", "5432", "-U", "postgres", "-d", "dbx"],
"smoke": { "steps": [{ "name": "query initialized row over TCP", "command": ["env", "PGPASSWORD=${DB_PASSWORD}", "psql", "-h", "127.0.0.1", "-p", "5432", "-U", "postgres", "-d", "dbx", "-Atc", "SELECT note FROM dbx_smoke WHERE id=1"], "expect": "DBX smoke" }] }
}
+20
View File
@@ -0,0 +1,20 @@
services:
database:
image: docker.cnb.cool/znb/images/redis:3.0.7-alpine
platform: linux/amd64
container_name: dbx-redis-3.0.7
command: ["redis-server", "--appendonly", "yes", "--requirepass", "${DB_PASSWORD:-123456}"]
environment:
# Keep the password in container env so CMD-SHELL can quote it safely.
REDIS_PASSWORD: "${DB_PASSWORD:-123456}"
ports:
- "${DB_BIND_ADDRESS:-127.0.0.1}:${DB_PORT:-6380}:6379"
volumes:
- data:/data
healthcheck:
test: ["CMD-SHELL", "redis-cli -a \"$$REDIS_PASSWORD\" ping | grep PONG"]
interval: 5s
timeout: 5s
retries: 30
volumes:
data:
@@ -0,0 +1 @@
Redis has no automatic init directory convention. `make db-verify DB=redis@3.0.7` creates and reads the `dbx:smoke` key.
+13
View File
@@ -0,0 +1,13 @@
{
"database": "redis",
"name": "Redis",
"version": "3.0.7",
"displayVersion": "3.0.7",
"image": "docker.cnb.cool/znb/images/redis:3.0.7-alpine",
"platforms": ["linux/amd64"],
"service": "database",
"defaultPort": 6379,
"connection": { "host": "127.0.0.1", "port": 6380, "password": "123456", "database": 0 },
"shell": ["redis-cli", "-a", "${DB_PASSWORD}"],
"smoke": { "steps": [{ "name": "seed smoke key", "command": ["redis-cli", "-a", "${DB_PASSWORD}", "SET", "dbx:smoke", "DBX smoke"], "expect": "OK" }, { "name": "read smoke key", "command": ["redis-cli", "-a", "${DB_PASSWORD}", "GET", "dbx:smoke"], "expect": "DBX smoke" }] }
}
+19
View File
@@ -0,0 +1,19 @@
services:
database:
image: docker.cnb.cool/znb/images/redis:7.4.9-alpine
container_name: dbx-redis-7.4
command: ["redis-server", "--appendonly", "yes", "--requirepass", "${DB_PASSWORD:-123456}"]
environment:
# Keep the password in container env so CMD-SHELL can quote it safely.
REDIS_PASSWORD: "${DB_PASSWORD:-123456}"
ports:
- "${DB_BIND_ADDRESS:-127.0.0.1}:${DB_PORT:-6380}:6379"
volumes:
- data:/data
healthcheck:
test: ["CMD-SHELL", "redis-cli -a \"$$REDIS_PASSWORD\" ping | grep PONG"]
interval: 5s
timeout: 5s
retries: 30
volumes:
data:
+1
View File
@@ -0,0 +1 @@
Redis has no automatic init directory convention. `make db-verify DB=redis@7.4` creates and reads the `dbx:smoke` key.
+13
View File
@@ -0,0 +1,13 @@
{
"database": "redis",
"name": "Redis",
"version": "7.4.9",
"displayVersion": "7.4",
"image": "docker.cnb.cool/znb/images/redis:7.4.9-alpine",
"platforms": ["linux/amd64", "linux/arm64"],
"service": "database",
"defaultPort": 6379,
"connection": { "host": "127.0.0.1", "port": 6380, "username": "default", "password": "123456", "database": 0 },
"shell": ["redis-cli", "-a", "${DB_PASSWORD}"],
"smoke": { "steps": [{ "name": "seed smoke key", "command": ["redis-cli", "-a", "${DB_PASSWORD}", "SET", "dbx:smoke", "DBX smoke"], "expect": "OK" }, { "name": "read smoke key", "command": ["redis-cli", "-a", "${DB_PASSWORD}", "GET", "dbx:smoke"], "expect": "DBX smoke" }] }
}
+1 -1
View File
@@ -22,7 +22,7 @@ export default async function Layout({ params, children }: { params: Promise<{ l
themeSwitch={{ enabled: false }}
sidebar={{
defaultOpenLevel: 1,
footer: <DocsSidebarFooter />,
footer: <DocsSidebarFooter key="docs-sidebar-footer" />,
}}
>
{children}
+13
View File
@@ -182,6 +182,19 @@ pnpm tauri dev -- --no-default-features
如果端口 `1420` 已被占用,先关闭旧的 DBX/Vite 开发进程再重新启动。
## 本地数据库测试环境
涉及数据库驱动、连接流程、元数据查询或数据库专用 UI 的改动,应尽可能通过真实实例验证。仓库为此提供了固定版本的本地 Docker Compose 配方:
```bash
make db-list
make db DB=mysql@8.4
make db-verify DB=mysql@8.4
make db-down DB=mysql@8.4
```
服务端口默认监听 `127.0.0.1`;在共享网络中暴露主机前,请设置 `DB_BIND_ADDRESS=0.0.0.0`、使用强 `DB_PASSWORD` 并配置防火墙。所有支持的配方、覆盖变量和重置安全要求请参阅[数据库测试实验室](/cn/docs/database-lab)。
## 5. 认识项目结构
| 路径 | 适合修改的内容 |
+13
View File
@@ -182,6 +182,19 @@ A successful run opens the DBX desktop window without a compiler error in the te
If port `1420` is already in use, stop the previous DBX/Vite development process and restart.
## Local database test environments
Changes to a database driver, connection flow, metadata query, or database-specific UI should be checked against a real instance when possible. The repository provides pinned local Docker Compose recipes for this purpose:
```bash
make db-list
make db DB=mysql@8.4
make db-verify DB=mysql@8.4
make db-down DB=mysql@8.4
```
The service ports listen on `127.0.0.1` by default. Set `DB_BIND_ADDRESS=0.0.0.0`, choose a strong `DB_PASSWORD`, and use firewall controls before exposing a host to a shared network. See the [Database Test Lab](/en/docs/database-lab) for all supported recipes, overrides, and reset safety requirements.
## 5. Understand the Repository Layout
| Path | What to change there |
+109
View File
@@ -0,0 +1,109 @@
---
title: 数据库测试实验室
description: 为 DBX 开发与验证启动可重复创建的本地数据库实例。
---
数据库测试实验室提供轻量、固定版本的 Docker Compose 环境,方便使用真实数据库版本验证 DBX。每个配方都使用命名数据卷、健康检查、初始化数据或验证阶段创建的冒烟数据,并且默认监听 `127.0.0.1`。
<Callout type="warning">默认密码为 `123456`,但端口默认只能从本机访问。如需远程访问,请显式设置 `DB_BIND_ADDRESS=0.0.0.0`、修改 `DB_PASSWORD`,并配置常规防火墙规则。这些环境用于开发,不是生产部署模板。</Callout>
## 可用配方
| 数据库 | 版本目录 | Docker Hub 官方镜像 | Compose 使用的 CNB 镜像 | 默认宿主端口 | 容器名 |
| --- | --- | --- | --- | ---: | --- |
| ClickHouse | `clickhouse/24.8` | `clickhouse/clickhouse-server:24.8.14.39` | `docker.cnb.cool/znb/images/clickhouse-server:24.8.14.39` | `8124` | `dbx-clickhouse-24.8` |
| MariaDB | `mariadb/10.11` | `mariadb:10.11.11` | `docker.cnb.cool/znb/images/mariadb:10.11.11` | `3307` | `dbx-mariadb-10.11` |
| MongoDB | `mongodb/5.0` | `mongo:5.0.5` | `docker.cnb.cool/znb/images/mongo:5.0.5` | `27018` | `dbx-mongodb-5.0` |
| MongoDB | `mongodb/8.2` | `mongo:8.2.3-noble` | `docker.cnb.cool/znb/images/mongo:8.2.3-noble` | `27018` | `dbx-mongodb-8.2` |
| MySQL | `mysql/5.7` | `mysql:5.7.44` | `docker.cnb.cool/znb/images/mysql:5.7.44` | `3307` | `dbx-mysql-5.7` |
| MySQL | `mysql/8.4` | `mysql:8.4.6` | `docker.cnb.cool/znb/images/mysql:8.4.6` | `3307` | `dbx-mysql-8.4` |
| PostgreSQL | `postgresql/14.23` | `postgres:14.23` | `docker.cnb.cool/znb/images/postgres:14.23` | `5433` | `dbx-postgresql-14.23` |
| PostgreSQL | `postgresql/17.4` | `postgres:17.4` | `docker.cnb.cool/znb/images/postgres:17.4` | `5433` | `dbx-postgresql-17.4` |
| Redis | `redis/3.0.7` | `redis:3.0.7-alpine` | `docker.cnb.cool/znb/images/redis:3.0.7-alpine` | `6380` | `dbx-redis-3.0.7` |
| Redis | `redis/7.4` | `redis:7.4.9-alpine` | `docker.cnb.cool/znb/images/redis:7.4.9-alpine` | `6380` | `dbx-redis-7.4` |
所有网络数据库的默认宿主端口都比标准端口大 `1`,并且该约定由配方校验器强制检查。默认密码统一为 `123456`,默认数据库名为 `dbx`。Redis 不支持命名数据库,因此使用 DB 0,并以 `dbx:` 作为冒烟键前缀。Compose 默认使用 CNB 镜像列;Docker Hub 列保留官方上游地址,便于核对来源或直接拉取。Redis 3.0.7 仅支持 amd64;在 arm64 主机上启动时会单独提醒,Docker 将使用模拟运行。其余配方均支持 amd64 和 arm64。
Redis 3.0.7 和 Redis 7.4.9 用于覆盖兼容性的两个端点。Redis 3 早于 ACL、RESP3、Streams 及许多现代命令,Redis 7 则覆盖当前协议与命令集。对这个实验室而言,同时保留 6.2 和 7.4 所提供的兼容性覆盖更小。
同一数据库的不同版本默认会共用宿主机端口。通常一次启动一个版本;需要并行对比时,为其中一个版本指定其他端口:
```bash
DB_PORT=13307 make db DB=mysql@5.7
make db DB=mysql@8.4
```
## 启动并验证环境
在仓库根目录执行。先列出可用配方,再选择数据库和版本:
```bash
make db
make db-list
make db DB=postgresql@17.4
make db-verify DB=postgresql@17.4
```
不带参数执行 `make db` 会输出当前全部支持的、可直接复制启动的命令,以及可选参数。传入 `DB=product@version` 后,`db` 会等待 Compose 健康检查通过并输出 DBX 连接字段。`db-verify` 还会在数据库容器中执行配方中的冒烟命令,并校验预期输出;提交数据库相关修复前推荐执行此命令。
## 命令和变量
| Make 目标 | 用途 |
| --- | --- |
| `make db-list` | 列出数据库版本、镜像和支持的平台 |
| `make db DB=product@version` | 创建、等待环境就绪并输出连接字段 |
| `make db-verify DB=product@version` | 启动并运行冒烟检查 |
| `make db-down DB=product@version` | 停止环境但保留数据卷 |
| `make db-reset DB=product@version CONFIRM=1` | 删除环境及数据卷 |
| `make db-check` | 校验全部配方和 Compose 文件 |
`DB_BIND_ADDRESS` 修改主机侧绑定地址,`DB_PORT` 修改主机侧端口,`DB_PASSWORD` 修改默认密码。例如:
```bash
DB_PORT=13306 DB_PASSWORD=local-secret make db-verify DB=mysql@8.4
```
远程访问必须显式启用:
```bash
DB_BIND_ADDRESS=0.0.0.0 DB_PASSWORD=local-secret make db DB=mysql@8.4
```
`db-reset` 受安全保护:只有设置 `CONFIRM=1` 才会删除命名卷。Redis 不支持镜像初始化目录约定;其 `init/README.md` 说明了 `verify` 会创建并读取的冒烟键。需要诊断时,可直接运行 `pnpm db:env -- info|status|logs|shell <product> <version>`。
## Tab 补全
仓库提供 Make 目标和 `DB=product@version` 值的动态补全。它会读取当前配方目录,因此新增版本后无需修改补全脚本。
```bash
# Bash
source deploy/database/completion/dbx-make.bash
# Zsh
autoload -Uz compinit && compinit
source deploy/database/completion/_dbx-make.zsh
# PowerShell
. .\deploy\database\completion\Dbx.Make.ps1
```
运行 `make db-completion` 可打印上述命令。加载对应脚本后,在 `make db DB=` 后按 Tab 即可选择配方。Make 目标本身已避免依赖 POSIX Shell 条件语法,因此在 PowerShell、Git Bash 或 WSL 中使用 GNU Make 均可运行;仍需安装 Docker Desktop 和 Node.js/pnpm。
## 添加配方
在 `deploy/database/<product>/<version>/` 下添加目录,并提供:
```text
recipe.json
compose.yaml
init/
```
`recipe.json` 提供 DBX 连接字段和冒烟命令数组。不要使用 shell 字符串,命令必须作为参数数组执行。Compose 文件必须固定镜像版本、使用命名卷和健康检查、将端口默认绑定至 `${DB_BIND_ADDRESS:-127.0.0.1}`,并把 `container_name` 设置为 `dbx-<product>-<version>`。
完成后运行:
```bash
pnpm test:db-env
make db-check
```
+109
View File
@@ -0,0 +1,109 @@
---
title: Database Test Lab
description: Start reproducible, local database instances for DBX development and verification.
---
The Database Test Lab provides small, pinned Docker Compose environments for testing DBX against real database versions. Every recipe uses a named data volume, a health check, initialization data or smoke data created during verification, and listens on `127.0.0.1` by default.
<Callout type="warning">The default password is `123456`, but ports are accessible only from the local host by default. To allow remote access, explicitly set `DB_BIND_ADDRESS=0.0.0.0`, change `DB_PASSWORD`, and apply your normal firewall controls. These environments are for development, not production deployment.</Callout>
## Available recipes
| Database | Version directory | Official Docker Hub image | CNB image used by Compose | Default host port | Container name |
| --- | --- | --- | --- | ---: | --- |
| ClickHouse | `clickhouse/24.8` | `clickhouse/clickhouse-server:24.8.14.39` | `docker.cnb.cool/znb/images/clickhouse-server:24.8.14.39` | `8124` | `dbx-clickhouse-24.8` |
| MariaDB | `mariadb/10.11` | `mariadb:10.11.11` | `docker.cnb.cool/znb/images/mariadb:10.11.11` | `3307` | `dbx-mariadb-10.11` |
| MongoDB | `mongodb/5.0` | `mongo:5.0.5` | `docker.cnb.cool/znb/images/mongo:5.0.5` | `27018` | `dbx-mongodb-5.0` |
| MongoDB | `mongodb/8.2` | `mongo:8.2.3-noble` | `docker.cnb.cool/znb/images/mongo:8.2.3-noble` | `27018` | `dbx-mongodb-8.2` |
| MySQL | `mysql/5.7` | `mysql:5.7.44` | `docker.cnb.cool/znb/images/mysql:5.7.44` | `3307` | `dbx-mysql-5.7` |
| MySQL | `mysql/8.4` | `mysql:8.4.6` | `docker.cnb.cool/znb/images/mysql:8.4.6` | `3307` | `dbx-mysql-8.4` |
| PostgreSQL | `postgresql/14.23` | `postgres:14.23` | `docker.cnb.cool/znb/images/postgres:14.23` | `5433` | `dbx-postgresql-14.23` |
| PostgreSQL | `postgresql/17.4` | `postgres:17.4` | `docker.cnb.cool/znb/images/postgres:17.4` | `5433` | `dbx-postgresql-17.4` |
| Redis | `redis/3.0.7` | `redis:3.0.7-alpine` | `docker.cnb.cool/znb/images/redis:3.0.7-alpine` | `6380` | `dbx-redis-3.0.7` |
| Redis | `redis/7.4` | `redis:7.4.9-alpine` | `docker.cnb.cool/znb/images/redis:7.4.9-alpine` | `6380` | `dbx-redis-7.4` |
Every network recipe uses a host port one greater than the database standard port, and the recipe validator enforces that contract. The default password is `123456`, and the default database is `dbx`. Redis has no named databases, so it uses DB 0 with a `dbx:` smoke-key prefix. Compose uses the CNB image column; the Docker Hub column preserves the official upstream reference for provenance and direct pulls. Redis 3.0.7 is amd64-only; on arm64 hosts the command prints an architecture warning and Docker uses emulation. Every other recipe supports both amd64 and arm64.
Redis 3.0.7 and Redis 7.4.9 intentionally cover the compatibility endpoints. Redis 3 predates ACLs, RESP3, Streams, and many modern commands, while Redis 7 covers the current protocol and command set. Keeping 6.2 and 7.4 together would provide less compatibility coverage for this lab.
Versions of the same product intentionally share that default host port. Start them one at a time, or give one version another port when comparing versions concurrently:
```bash
DB_PORT=13307 make db DB=mysql@5.7
make db DB=mysql@8.4
```
## Start and verify an environment
Run commands from the repository root. List the available recipes, then choose a database and version:
```bash
make db
make db-list
make db DB=postgresql@17.4
make db-verify DB=postgresql@17.4
```
`make db` without parameters prints every currently supported copy-and-paste start command, plus optional parameters. With `DB=product@version`, it waits for the Compose health check and prints the DBX connection fields. `db-verify` also runs the recipe's smoke command inside the database container and checks its expected output. It is the preferred command before reporting a database-specific fix.
## Commands and variables
| Make target | Purpose |
| --- | --- |
| `make db-list` | List database versions, images, and supported platforms |
| `make db DB=product@version` | Create, wait for, and print the connection fields |
| `make db-verify DB=product@version` | Start and run smoke checks |
| `make db-down DB=product@version` | Stop the environment while keeping its data volume |
| `make db-reset DB=product@version CONFIRM=1` | Delete the environment and its data volume |
| `make db-check` | Validate every recipe and Compose file |
`DB_BIND_ADDRESS` changes the host-side bind address, `DB_PORT` changes the host-side port, and `DB_PASSWORD` changes the default password. For example:
```bash
DB_PORT=13306 DB_PASSWORD=local-secret make db-verify DB=mysql@8.4
```
Remote access must be enabled explicitly:
```bash
DB_BIND_ADDRESS=0.0.0.0 DB_PASSWORD=local-secret make db DB=mysql@8.4
```
`db-reset` is intentionally guarded: it will not remove a named volume unless `CONFIRM=1` is set. Redis has no image initialization-directory convention; its `init/README.md` documents the smoke key created and read by `verify`. The lower-level `info`, `status`, `logs`, and `shell` commands remain available as `pnpm db:env -- <command> <product> <version>` when needed for diagnosis.
## Tab completion
The repository includes dynamic completion for Make targets and `DB=product@version` values. It reads the current recipe directories, so newly added versions appear without editing the completion scripts.
```bash
# Bash
source deploy/database/completion/dbx-make.bash
# Zsh
autoload -Uz compinit && compinit
source deploy/database/completion/_dbx-make.zsh
# PowerShell
. .\deploy\database\completion\Dbx.Make.ps1
```
Run `make db-completion` to print these commands. After sourcing the appropriate file, press Tab after `make db DB=` to select a recipe. The Make targets themselves avoid POSIX-shell conditionals, so they work with GNU Make in PowerShell, Git Bash, or WSL; Docker Desktop and Node.js/pnpm must be available.
## Add a recipe
Add a directory under `deploy/database/<product>/<version>/` containing:
```text
recipe.json
compose.yaml
init/
```
`recipe.json` supplies the DBX connection fields and smoke command array. Do not use a shell string for smoke checks: commands execute as argument arrays. Compose files must pin an image, use a named volume and health check, default port bindings to `${DB_BIND_ADDRESS:-127.0.0.1}`, and set `container_name` to `dbx-<product>-<version>`.
Finish by running:
```bash
pnpm test:db-env
make db-check
```
+4
View File
@@ -86,6 +86,10 @@ description: 了解 DBX 可以连接哪些数据库,以及每类高级功能
<Callout type="info">SQLite、DuckDB、Access 和 JDBC 在不需要网络端口时,会在连接模型中保存为端口 `0`。</Callout>
## 本地数据库测试环境
DBX 为 ClickHouse、MariaDB、MongoDB、MySQL、PostgreSQL 和 Redis 维护了固定版本、可重复创建的 Docker Compose 配方。需要干净的本地实例验证连接、驱动行为或 Bug 修复时可以直接使用。命令、安全默认值和支持版本请参阅[数据库测试实验室](/cn/docs/database-lab)。
## 功能矩阵
DBX 只会在具备足够元数据和 SQL 生成能力的数据库上启用高级功能。
+4
View File
@@ -86,6 +86,10 @@ The connection dialog exposes ready-to-use profiles with default ports and drive
<Callout type="info">SQLite, DuckDB, Access, and JDBC profiles use port `0` in the saved connection model when a network port is not part of the connection.</Callout>
## Local database test environments
DBX maintains pinned, reproducible Docker Compose recipes for ClickHouse, MariaDB, MongoDB, MySQL, PostgreSQL, and Redis. Use them when you need a clean local instance to test a connection, driver behavior, or a bug fix. See the [Database Test Lab](/en/docs/database-lab) for commands, safe defaults, and the supported versions.
## Feature Matrix
DBX intentionally enables advanced workflows only where the app has enough metadata and SQL-generation support.
+1
View File
@@ -7,6 +7,7 @@
"getting-started",
"1panel",
"databases",
"database-lab",
"---核心功能---",
"query-editor",
"data-grid",
+1
View File
@@ -7,6 +7,7 @@
"getting-started",
"1panel",
"databases",
"database-lab",
"---Core Features---",
"query-editor",
"data-grid",
+1
View File
@@ -10,6 +10,7 @@ const pageIcons: Record<string, keyof typeof icons> = {
"getting-started": "Rocket",
"1panel": "PanelsTopLeft",
databases: "Database",
"database-lab": "FlaskConical",
"query-editor": "SquareTerminal",
"data-grid": "Table2",
"schema-browser": "Network",
+2
View File
@@ -24,6 +24,8 @@
"build": "vite build --config apps/desktop/vite.config.ts",
"build:checked": "pnpm typecheck && pnpm build",
"check": "node scripts/run-check.mjs",
"db:env": "node scripts/database-env.mjs",
"test:db-env": "node --test scripts/database-env.test.mjs",
"bench:redis-key-search": "node scripts/bench/redis-key-search.mjs",
"bench:mongodb-count": "node scripts/bench/mongodb-count.mjs",
"lint": "oxlint --vue-plugin apps/desktop/src",
+391
View File
@@ -0,0 +1,391 @@
#!/usr/bin/env node
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { basename, dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { spawnSync } from 'node:child_process';
const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
export const DEFAULT_RECIPES_ROOT = join(REPO_ROOT, 'deploy', 'database');
const DEFAULT_MAKEFILE_PATH = join(REPO_ROOT, 'Makefile');
const DEFAULT_PASSWORD = '123456';
const DEFAULT_DATABASE = 'dbx';
export function discoverRecipes(root = DEFAULT_RECIPES_ROOT) {
if (!existsSync(root)) return [];
const recipes = [];
for (const database of readdirSync(root, { withFileTypes: true })) {
if (!database.isDirectory()) continue;
const databaseDir = join(root, database.name);
for (const version of readdirSync(databaseDir, { withFileTypes: true })) {
if (!version.isDirectory()) continue;
const recipePath = join(databaseDir, version.name, 'recipe.json');
if (!existsSync(recipePath)) continue;
const recipe = JSON.parse(readFileSync(recipePath, 'utf8'));
recipes.push({ ...recipe, directory: dirname(recipePath), recipePath });
}
}
return recipes.sort((a, b) => `${a.database}/${a.displayVersion}`.localeCompare(`${b.database}/${b.displayVersion}`, 'en'));
}
export function recipeSelector(recipe) {
return `${recipe.database}@${recipe.displayVersion}`;
}
export function discoverMakeTargets(makefilePath = DEFAULT_MAKEFILE_PATH) {
if (!existsSync(makefilePath)) return [];
const source = readFileSync(makefilePath, 'utf8').replace(/\\\r?\n/g, ' ');
const targets = [];
for (const line of source.split(/\r?\n/)) {
const match = line.match(/^\.PHONY:\s*(.+)$/);
if (match) targets.push(...match[1].trim().split(/\s+/));
}
return [...new Set(targets)];
}
export function platformForArchitecture(architecture = process.arch) {
if (architecture === 'x64') return 'linux/amd64';
if (architecture === 'arm64') return 'linux/arm64';
return null;
}
export function architectureWarning(recipe, architecture = process.arch) {
const platform = platformForArchitecture(architecture);
if (!platform || recipe.platforms?.includes(platform)) return null;
return `${recipe.image} does not support ${platform}. Docker must use ${recipe.platforms.join(', ')} emulation and startup may be slower.`;
}
function printQuickStart(recipes) {
console.log('Database test environments');
console.log('Copy one command to start an environment:');
console.log('');
for (const recipe of recipes) console.log(` make db DB=${recipeSelector(recipe)}`);
console.log('');
console.log('Optional parameters:');
console.log(' DB_BIND_ADDRESS=<ip> Override the default bind address (127.0.0.1).');
console.log(' DB_PORT=<port> Override the default host port.');
console.log(' DB_PASSWORD=<password> Override the default password (123456).');
console.log('');
console.log('Next steps: make db-verify DB=<product>@<version>, make db-down DB=<product>@<version>');
console.log('Tab completion: make db-completion');
}
function printCompletionSetup() {
console.log('Bash: source deploy/database/completion/dbx-make.bash');
console.log('Zsh: autoload -Uz compinit && compinit && source deploy/database/completion/_dbx-make.zsh');
console.log('PowerShell: . .\\deploy\\database\\completion\\Dbx.Make.ps1');
}
export function resolveRecipe(recipes, database, version) {
if (!database) throw new Error('DB is required. Run `make db-list` to see available environments.');
const matches = recipes.filter((item) => item.database === database && (!version || item.displayVersion === version || item.version === version));
if (matches.length === 0) throw new Error(`No database environment found for ${database}${version ? ` ${version}` : ''}.`);
if (matches.length > 1) throw new Error(`${database} has multiple versions (${matches.map((item) => item.displayVersion).join(', ')}). Use DB=${database}@<version> (or DB_VERSION).`);
return matches[0];
}
export function parseDatabaseSelection(selection, explicitVersion) {
if (!selection) return { database: selection, version: explicitVersion };
const selectorIndex = selection.lastIndexOf('@');
if (selectorIndex === -1) return { database: selection, version: explicitVersion };
const database = selection.slice(0, selectorIndex);
const selectorVersion = selection.slice(selectorIndex + 1);
if (!database || !selectorVersion) throw new Error('DB must use the format <product>@<version>, for example DB=mysql@8.4.');
if (explicitVersion && explicitVersion !== selectorVersion) {
throw new Error(`DB version ${selectorVersion} conflicts with DB_VERSION=${explicitVersion}.`);
}
return { database, version: explicitVersion || selectorVersion };
}
export function assertResetConfirmed(value) {
if (value !== '1') throw new Error('Reset deletes the environment volume. Re-run with CONFIRM=1.');
}
export function expectedContainerName(recipe) {
return `dbx-${recipe.database}-${recipe.displayVersion}`.toLowerCase().replace(/[^a-z0-9_.-]+/g, '-');
}
export function validateRecipe(recipe) {
const errors = [];
for (const field of ['database', 'version', 'displayVersion', 'service', 'connection', 'smoke', 'shell', 'defaultPort']) {
if (recipe[field] === undefined) errors.push(`missing ${field}`);
}
if (!recipe.image || !/^[^\s]+:[^\s]+$/.test(recipe.image)) errors.push('image must be a pinned image reference');
if (recipe.connection?.host !== '127.0.0.1') errors.push('connection.host must be 127.0.0.1');
if (!Number.isInteger(recipe.defaultPort) || recipe.defaultPort < 1 || recipe.defaultPort > 65534) {
errors.push('defaultPort must be an integer between 1 and 65534');
} else if (recipe.connection?.port !== recipe.defaultPort + 1) {
errors.push('connection.port must be defaultPort + 1');
}
if (recipe.connection?.password !== DEFAULT_PASSWORD) errors.push(`connection.password must be ${DEFAULT_PASSWORD}`);
if (recipe.database === 'redis' ? recipe.connection?.database !== 0 : recipe.connection?.database !== DEFAULT_DATABASE) {
errors.push(`connection.database must be ${recipe.database === 'redis' ? '0 for Redis' : DEFAULT_DATABASE}`);
}
if (!Array.isArray(recipe.platforms) || recipe.platforms.length === 0) errors.push('platforms must not be empty');
else if (recipe.platforms.some((platform) => !['linux/amd64', 'linux/arm64'].includes(platform))) {
errors.push('platforms contains an unsupported platform');
}
if (basename(recipe.directory) !== recipe.displayVersion || basename(dirname(recipe.directory)) !== recipe.database) {
errors.push('recipe directory must match database/displayVersion');
}
const composePath = join(recipe.directory, 'compose.yaml');
if (!existsSync(composePath)) errors.push('missing compose.yaml');
else {
const compose = readFileSync(composePath, 'utf8');
if (!compose.includes(`container_name: ${expectedContainerName(recipe)}`)) {
errors.push(`compose.yaml container_name must be ${expectedContainerName(recipe)}`);
}
if (/image:\s*[^\n]*:latest(?:\s|$)/.test(compose)) errors.push('compose.yaml must not use latest');
if (!/healthcheck\s*:/.test(compose)) errors.push('compose.yaml must define a healthcheck');
if (!/^volumes\s*:/m.test(compose)) errors.push('compose.yaml must define a named volume');
if (!compose.includes(`image: ${recipe.image}`)) errors.push('compose.yaml image must match recipe.image');
if (recipe.platforms?.length === 1 && !compose.includes(`platform: ${recipe.platforms[0]}`)) {
errors.push(`single-platform image must set compose platform to ${recipe.platforms[0]}`);
}
if (!allPortMappingsDefaultToLoopback(compose)) {
errors.push('compose.yaml ports must default every mapping to 127.0.0.1 via DB_BIND_ADDRESS');
}
if (!serviceHasNamedVolume(compose, recipe.service)) errors.push('target service must mount a named volume');
if (!compose.includes(`\${DB_PORT:-${recipe.connection?.port}}:${recipe.defaultPort}`)) {
errors.push('compose.yaml must default DB_PORT to connection.port and target defaultPort');
}
}
const initDirectory = join(recipe.directory, 'init');
if (!existsSync(initDirectory) || readdirSync(initDirectory).length === 0) errors.push('init directory must contain a file');
if (!Array.isArray(recipe.smoke?.steps) || recipe.smoke.steps.length === 0) errors.push('smoke.steps must not be empty');
for (const step of recipe.smoke?.steps ?? []) {
if (!step.name || !Array.isArray(step.command) || step.command.length === 0) errors.push('every smoke step needs a name and command');
if (typeof step.expect !== 'string' || step.expect.length === 0) errors.push('every smoke step needs an expected output');
}
if (!Array.isArray(recipe.shell) || recipe.shell.length === 0) errors.push('shell must be a non-empty command array');
return errors;
}
function indentation(line) {
return line.length - line.trimStart().length;
}
function serviceBlock(compose, service) {
const lines = compose.split(/\r?\n/);
const start = lines.findIndex((line) => new RegExp(`^\\s{2}${service.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}:\\s*$`).test(line));
if (start === -1) return [];
const block = [];
for (let index = start + 1; index < lines.length; index += 1) {
const line = lines[index];
if (line.trim() && indentation(line) <= 2) break;
block.push(line);
}
return block;
}
export function allPortMappingsDefaultToLoopback(compose) {
const lines = compose.split(/\r?\n/);
let portsIndent = null;
let foundMapping = false;
for (const line of lines) {
const trimmed = line.trim();
const lineIndent = indentation(line);
if (/^ports\s*:/.test(trimmed)) {
portsIndent = lineIndent;
const inlineMappings = trimmed.match(/['\"]([^'\"]+)['\"]/g) ?? [];
if (inlineMappings.length > 0) {
foundMapping = true;
if (inlineMappings.some((mapping) => !mapping.slice(1, -1).startsWith('${DB_BIND_ADDRESS:-127.0.0.1}:'))) return false;
}
continue;
}
if (portsIndent === null) continue;
if (trimmed && lineIndent <= portsIndent) {
portsIndent = null;
continue;
}
if (!trimmed.startsWith('-')) continue;
foundMapping = true;
const mapping = trimmed.slice(1).trim().replace(/^['\"]|['\"]$/g, '');
if (!mapping.startsWith('${DB_BIND_ADDRESS:-127.0.0.1}:')) return false;
}
return foundMapping;
}
export function serviceHasNamedVolume(compose, service) {
const block = serviceBlock(compose, service);
let volumesIndent = null;
for (const line of block) {
const trimmed = line.trim();
const lineIndent = indentation(line);
if (/^volumes\s*:/.test(trimmed)) {
volumesIndent = lineIndent;
continue;
}
if (volumesIndent === null) continue;
if (trimmed && lineIndent <= volumesIndent) {
volumesIndent = null;
continue;
}
if (!trimmed.startsWith('-')) continue;
const mount = trimmed.slice(1).trim().replace(/^['\"]|['\"]$/g, '');
if (/^[A-Za-z0-9][A-Za-z0-9_.-]*:/.test(mount) && !mount.startsWith('./') && !mount.startsWith('../')) return true;
}
return false;
}
function composeArgs(recipe, ...args) {
const project = (process.env.DB_PROJECT || `dbx-${basename(REPO_ROOT)}-${recipe.database}-${recipe.displayVersion}`).toLowerCase().replace(/[^a-z0-9_-]+/g, '-');
return ['compose', '--project-name', project, '--file', join(recipe.directory, 'compose.yaml'), ...args];
}
function run(command, args, options = {}) {
const result = spawnSync(command, args, { cwd: options.cwd ?? REPO_ROOT, env: process.env, encoding: 'utf8', stdio: options.capture ? 'pipe' : 'inherit' });
if (result.error) throw result.error;
if (result.status !== 0) {
const detail = options.capture ? `\n${result.stderr || result.stdout}` : '';
throw new Error(`${command} ${args.join(' ')} failed with exit code ${result.status}.${detail}`);
}
return options.capture ? `${result.stdout ?? ''}${result.stderr ?? ''}` : '';
}
function runCompose(recipe, args, options) {
return run('docker', composeArgs(recipe, ...args), options);
}
export function expandSmokeCommand(command, recipe, environment = process.env) {
const values = {
DB_PASSWORD: environment.DB_PASSWORD || recipe.connection.password,
DB_PORT: environment.DB_PORT || String(recipe.connection.port),
};
return command.map((value) => value.replace(/\$\{(DB_PASSWORD|DB_PORT)\}/g, (_, name) => values[name]));
}
function printConnection(recipe) {
const connection = { ...recipe.connection };
if (process.env.DB_PORT) connection.port = Number(process.env.DB_PORT);
if (process.env.DB_PASSWORD) connection.password = process.env.DB_PASSWORD;
console.log(`${recipe.name} (${recipe.version})`);
for (const [key, value] of Object.entries(connection)) console.log(`${key}: ${value}`);
if (recipe.notes) console.log(`notes: ${recipe.notes}`);
const warning = architectureWarning(recipe);
if (warning) console.warn(`warning: ${warning}`);
}
function checkRecipes(recipes) {
let failed = false;
for (const recipe of recipes) {
const errors = validateRecipe(recipe);
if (errors.length) {
failed = true;
console.error(`FAIL ${recipe.database}/${recipe.displayVersion}: ${errors.join('; ')}`);
continue;
}
const result = spawnSync('docker', composeArgs(recipe, 'config', '--format', 'json'), {
encoding: 'utf8',
env: { ...process.env, DB_BIND_ADDRESS: '' },
});
if (result.error?.code === 'ENOENT') {
console.log(`OK ${recipe.database}/${recipe.displayVersion} (static checks; Docker unavailable)`);
} else if (result.status !== 0) {
failed = true;
console.error(`FAIL ${recipe.database}/${recipe.displayVersion}: docker compose config failed\n${result.stderr}`);
} else {
try {
validateRenderedCompose(recipe, JSON.parse(result.stdout));
console.log(`OK ${recipe.database}/${recipe.displayVersion}`);
} catch (error) {
failed = true;
console.error(`FAIL ${recipe.database}/${recipe.displayVersion}: ${error.message}`);
}
}
}
if (failed) throw new Error('Database environment checks failed.');
}
export function validateRenderedCompose(recipe, rendered) {
const service = rendered.services?.[recipe.service];
if (!service) throw new Error('rendered Compose config is missing the target service');
if (service.container_name !== expectedContainerName(recipe)) {
throw new Error(`rendered target service container_name must be ${expectedContainerName(recipe)}`);
}
if (!service.healthcheck?.test) throw new Error('rendered target service is missing a healthcheck');
const ports = service.ports ?? [];
if (ports.length === 0 || ports.some((port) => typeof port !== 'object' || port.host_ip !== '127.0.0.1')) {
throw new Error('rendered target service has a port mapping that does not default to 127.0.0.1');
}
const volumes = service.volumes ?? [];
if (!volumes.some((volume) => typeof volume === 'object' && volume.type === 'volume')) {
throw new Error('rendered target service does not mount a named volume');
}
}
export function main(argv = process.argv.slice(2)) {
const [command = 'list', positionalDatabase, positionalVersion] = argv.filter((argument) => argument && argument !== '--');
const recipes = discoverRecipes();
if (command === 'list') {
console.log('DATABASE\tVERSION\tIMAGE\tPLATFORMS');
for (const recipe of recipes) console.log(`${recipe.database}\t${recipe.displayVersion}\t${recipe.image}\t${recipe.platforms.join(',')}`);
return;
}
if (command === 'quick-start') return printQuickStart(recipes);
if (command === 'completion') return printCompletionSetup();
if (command === 'selectors') {
for (const recipe of recipes) console.log(recipeSelector(recipe));
return;
}
if (command === 'make-targets') {
for (const target of discoverMakeTargets()) console.log(target);
return;
}
if (command === 'check') return checkRecipes(recipes);
const { database, version } = parseDatabaseSelection(process.env.DB || positionalDatabase, process.env.DB_VERSION || positionalVersion);
if (command === 'start' && !database) return printQuickStart(recipes);
const recipe = resolveRecipe(recipes, database, version);
switch (command) {
case 'info':
printConnection(recipe);
break;
case 'start':
case 'up':
runCompose(recipe, ['up', '-d', '--wait']);
printConnection(recipe);
break;
case 'status':
runCompose(recipe, ['ps']);
break;
case 'logs':
runCompose(recipe, process.env.FOLLOW === '1' ? ['logs', '--follow'] : ['logs']);
break;
case 'shell':
runCompose(recipe, ['exec', recipe.service, ...expandSmokeCommand(recipe.shell, recipe)]);
break;
case 'verify':
runCompose(recipe, ['up', '-d', '--wait']);
for (const step of recipe.smoke.steps) {
const command = expandSmokeCommand(step.command, recipe);
const output = runCompose(recipe, ['exec', '-T', recipe.service, ...command], { capture: true });
if (step.expect && !output.includes(step.expect)) throw new Error(`Smoke check did not contain expected text: ${step.expect}\n${output}`);
console.log(`OK ${step.name}`);
}
break;
case 'down':
runCompose(recipe, ['down', '--remove-orphans']);
break;
case 'reset':
assertResetConfirmed(process.env.CONFIRM);
runCompose(recipe, ['down', '--volumes', '--remove-orphans']);
break;
default:
throw new Error(`Unknown command: ${command}`);
}
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
try {
main();
} catch (error) {
console.error(`Error: ${error.message}`);
process.exitCode = 1;
}
}
+294
View File
@@ -0,0 +1,294 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { spawnSync } from 'node:child_process';
import { DEFAULT_RECIPES_ROOT, allPortMappingsDefaultToLoopback, architectureWarning, assertResetConfirmed, discoverMakeTargets, discoverRecipes, expandSmokeCommand, expectedContainerName, parseDatabaseSelection, platformForArchitecture, recipeSelector, resolveRecipe, serviceHasNamedVolume, validateRecipe, validateRenderedCompose } from './database-env.mjs';
const bashAvailable = spawnSync('bash', ['--version'], { stdio: 'ignore' }).status === 0;
const zshAvailable = spawnSync('zsh', ['--version'], { stdio: 'ignore' }).status === 0;
const dockerComposeAvailable = spawnSync('docker', ['compose', 'version'], { stdio: 'ignore' }).status === 0;
function fixture(database, version) {
const root = mkdtempSync(join(tmpdir(), 'dbx-db-env-'));
const directory = join(root, database, version);
mkdirSync(join(directory, 'init'), { recursive: true });
writeFileSync(join(directory, 'init', '001-smoke.txt'), 'fixture initialization');
writeFileSync(join(directory, 'recipe.json'), JSON.stringify({ database, version, displayVersion: version, name: database, image: 'test:1', platforms: ['linux/amd64'], service: 'database', defaultPort: 1234, connection: { host: '127.0.0.1', port: 1235, password: '123456', database: database === 'redis' ? 0 : 'dbx' }, smoke: { steps: [{ name: 'smoke', command: ['true'], expect: 'true' }] }, shell: ['true'] }));
writeFileSync(join(directory, 'compose.yaml'), `services:\n database:\n image: test:1\n platform: linux/amd64\n container_name: dbx-${database}-${version}\n ports:\n - "\${DB_BIND_ADDRESS:-127.0.0.1}:\${DB_PORT:-1235}:1234"\n volumes:\n - data:/var/lib/database\n healthcheck:\n test: ["CMD", "true"]\nvolumes:\n data:\n`);
return root;
}
test('discovers versioned recipes', () => {
const recipes = discoverRecipes(fixture('mysql', '5.7'));
assert.equal(recipes.length, 1);
assert.equal(recipes[0].database, 'mysql');
});
test('requires DB and rejects ambiguous versions', () => {
assert.throws(() => resolveRecipe([], ''), /DB is required/);
const recipes = [{ database: 'mysql', displayVersion: '5.7' }, { database: 'mysql', displayVersion: '8.4' }];
assert.throws(() => resolveRecipe(recipes, 'mysql'), /multiple versions/);
assert.equal(resolveRecipe(recipes, 'mysql', '8.4').displayVersion, '8.4');
});
test('accepts the compact product@version database selector', () => {
assert.deepEqual(parseDatabaseSelection('mysql@8.4'), { database: 'mysql', version: '8.4' });
assert.deepEqual(parseDatabaseSelection('mysql@8.4', '8.4'), { database: 'mysql', version: '8.4' });
assert.throws(() => parseDatabaseSelection('mysql@8.4', '5.7'), /conflicts/);
assert.throws(() => parseDatabaseSelection('mysql@'), /format/);
});
test('formats a recipe as a copyable compact selector', () => {
assert.equal(recipeSelector({ database: 'mysql', displayVersion: '8.4' }), 'mysql@8.4');
});
test('discovers all public Make targets for shell completion', () => {
const targets = discoverMakeTargets();
for (const target of ['help', 'build', 'test', 'docs', 'db', 'db-verify', 'db-completion']) {
assert.ok(targets.includes(target), `missing Make target: ${target}`);
}
assert.equal(new Set(targets).size, targets.length);
});
test('Bash completion preserves all Make targets and completes database selectors', { skip: !bashAvailable }, () => {
const repoRoot = join(DEFAULT_RECIPES_ROOT, '..', '..');
const completionScript = join(DEFAULT_RECIPES_ROOT, 'completion', 'dbx-make.bash');
const result = spawnSync(
'bash',
[
'--noprofile',
'--norc',
'-c',
'source "$COMPLETION_SCRIPT"; COMP_WORDS=(make ""); COMP_CWORD=1; _dbx_make; printf "TARGET:%s\\n" "${COMPREPLY[@]}"; COMP_WORDS=(make db DB=); COMP_CWORD=2; _dbx_make; printf "SELECTOR:%s\\n" "${COMPREPLY[@]}"',
],
{ cwd: repoRoot, env: { ...process.env, COMPLETION_SCRIPT: completionScript }, encoding: 'utf8' },
);
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /^TARGET:build$/m);
assert.match(result.stdout, /^TARGET:test$/m);
assert.match(result.stdout, /^TARGET:db$/m);
assert.match(result.stdout, /^SELECTOR:DB=mysql@8\.4$/m);
});
test('Bash completion delegates to the previous completer outside the repository', { skip: !bashAvailable }, () => {
const completionScript = join(DEFAULT_RECIPES_ROOT, 'completion', 'dbx-make.bash');
const result = spawnSync(
'bash',
[
'--noprofile',
'--norc',
'-c',
'_original_make_completion() { COMPREPLY=(ORIGINAL); }; complete -F _original_make_completion make; source "$COMPLETION_SCRIPT"; cd "$TMPDIR"; COMP_WORDS=(make db DB=); COMP_CWORD=2; _dbx_make; printf "%s\\n" "${COMPREPLY[@]}"',
],
{ env: { ...process.env, COMPLETION_SCRIPT: completionScript, TMPDIR: tmpdir() }, encoding: 'utf8' },
);
assert.equal(result.status, 0, result.stderr);
assert.equal(result.stdout.trim(), 'ORIGINAL');
});
test('Zsh completion delegates ordinary Make completion and handles DB selectors', { skip: !zshAvailable }, () => {
const repoRoot = join(DEFAULT_RECIPES_ROOT, '..', '..');
const completionScript = join(DEFAULT_RECIPES_ROOT, 'completion', '_dbx-make.zsh');
const result = spawnSync(
'zsh',
[
'-f',
'-c',
'autoload -Uz compinit && compinit -D; _original_make_completion() { print ORIGINAL; }; compdef _original_make_completion make; source "$COMPLETION_SCRIPT"; words=(make ""); CURRENT=2; _dbx_make; _describe() { local values_name="$2"; print -l -- "${(@P)values_name}"; }; compset() { return 0; }; words=(make db DB=); CURRENT=3; _dbx_make',
],
{ cwd: repoRoot, env: { ...process.env, COMPLETION_SCRIPT: completionScript }, encoding: 'utf8' },
);
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /^ORIGINAL$/m);
assert.match(result.stdout, /^mysql@8\.4$/m);
});
test('records the MySQL 5.7 CNB mirror as a multi-architecture image', () => {
const recipe = discoverRecipes().find((item) => recipeSelector(item) === 'mysql@5.7');
assert.ok(recipe);
assert.deepEqual(recipe.platforms, ['linux/amd64', 'linux/arm64']);
assert.equal(recipe.notes, undefined);
});
test('warns only when the current architecture is unsupported', () => {
const recipe = { image: 'mirror/redis:3', platforms: ['linux/amd64'] };
assert.equal(platformForArchitecture('arm64'), 'linux/arm64');
assert.equal(architectureWarning(recipe, 'x64'), null);
assert.match(architectureWarning(recipe, 'arm64'), /does not support linux\/arm64/);
});
test('uses the approved CNB mirror images and matching recipe versions', () => {
const recipes = Object.fromEntries(
discoverRecipes().map((recipe) => [recipeSelector(recipe), { version: recipe.version, image: recipe.image, platforms: recipe.platforms }]),
);
assert.deepEqual(recipes, {
'clickhouse@24.8': { version: '24.8.14.39', image: 'docker.cnb.cool/znb/images/clickhouse-server:24.8.14.39', platforms: ['linux/amd64', 'linux/arm64'] },
'mariadb@10.11': { version: '10.11.11', image: 'docker.cnb.cool/znb/images/mariadb:10.11.11', platforms: ['linux/amd64', 'linux/arm64'] },
'mongodb@5.0': { version: '5.0.5', image: 'docker.cnb.cool/znb/images/mongo:5.0.5', platforms: ['linux/amd64', 'linux/arm64'] },
'mongodb@8.2': { version: '8.2.3', image: 'docker.cnb.cool/znb/images/mongo:8.2.3-noble', platforms: ['linux/amd64', 'linux/arm64'] },
'mysql@5.7': { version: '5.7.44', image: 'docker.cnb.cool/znb/images/mysql:5.7.44', platforms: ['linux/amd64', 'linux/arm64'] },
'mysql@8.4': { version: '8.4.6', image: 'docker.cnb.cool/znb/images/mysql:8.4.6', platforms: ['linux/amd64', 'linux/arm64'] },
'postgresql@14.23': { version: '14.23', image: 'docker.cnb.cool/znb/images/postgres:14.23', platforms: ['linux/amd64', 'linux/arm64'] },
'postgresql@17.4': { version: '17.4', image: 'docker.cnb.cool/znb/images/postgres:17.4', platforms: ['linux/amd64', 'linux/arm64'] },
'redis@3.0.7': { version: '3.0.7', image: 'docker.cnb.cool/znb/images/redis:3.0.7-alpine', platforms: ['linux/amd64'] },
'redis@7.4': { version: '7.4.9', image: 'docker.cnb.cool/znb/images/redis:7.4.9-alpine', platforms: ['linux/amd64', 'linux/arm64'] },
});
assert.equal(discoverRecipes().find((recipe) => recipeSelector(recipe) === 'redis@3.0.7').connection.username, undefined);
});
test('start without DB prints every copyable database command', () => {
const repoRoot = join(DEFAULT_RECIPES_ROOT, '..', '..');
const result = spawnSync(process.execPath, ['scripts/database-env.mjs', 'start'], {
cwd: repoRoot,
env: { ...process.env, DB: '', DB_VERSION: '' },
encoding: 'utf8',
});
assert.equal(result.status, 0, result.stderr);
for (const recipe of discoverRecipes()) {
assert.ok(result.stdout.includes(`make db DB=${recipeSelector(recipe)}`));
}
});
test('reset requires explicit confirmation', () => {
assert.throws(() => assertResetConfirmed(''), /CONFIRM=1/);
assert.doesNotThrow(() => assertResetConfirmed('1'));
});
test('static validation accepts a minimal safe recipe', () => {
const [recipe] = discoverRecipes(fixture('redis', '7.4'));
assert.deepEqual(validateRecipe(recipe), []);
});
test('smoke commands use password and port overrides without invoking a shell', () => {
const recipe = { connection: { password: 'default-password', port: 3306 } };
assert.deepEqual(
expandSmokeCommand(['client', '--password=${DB_PASSWORD}', '--port=${DB_PORT}'], recipe, { DB_PASSWORD: 'override', DB_PORT: '13306' }),
['client', '--password=override', '--port=13306'],
);
});
test('MongoDB commands pass reserved-character passwords as a distinct argument', () => {
const password = 'p@ss/word#with?reserved&characters';
for (const recipe of discoverRecipes().filter((item) => item.database === 'mongodb')) {
for (const command of [recipe.shell, ...recipe.smoke.steps.map((step) => step.command)]) {
const expanded = expandSmokeCommand(command, recipe, { DB_PASSWORD: password });
const passwordIndex = expanded.indexOf('--password');
assert.notEqual(passwordIndex, -1);
assert.equal(expanded[passwordIndex + 1], password);
assert.equal(expanded.some((argument) => argument.includes('mongodb://')), false);
}
}
});
test('requires every port mapping to default to loopback with an explicit override', () => {
assert.equal(allPortMappingsDefaultToLoopback('services:\n database:\n ports:\n - "127.0.0.1:3306:3306"'), false);
assert.equal(allPortMappingsDefaultToLoopback('services:\n database:\n ports:\n - "${DB_BIND_ADDRESS:-127.0.0.1}:3306:3306"'), true);
assert.equal(allPortMappingsDefaultToLoopback('services:\n database:\n ports:\n - "${DB_BIND_ADDRESS:-0.0.0.0}:3306:3306"'), false);
});
test('rendered Compose recipes bind to loopback by default', { skip: !dockerComposeAvailable }, () => {
const recipes = discoverRecipes();
for (const recipe of recipes) {
const result = spawnSync('docker', ['compose', '--file', join(recipe.directory, 'compose.yaml'), 'config', '--format', 'json'], {
encoding: 'utf8',
env: { ...process.env, DB_BIND_ADDRESS: '' },
});
assert.equal(result.status, 0, result.stderr);
assert.doesNotThrow(() => validateRenderedCompose(recipe, JSON.parse(result.stdout)));
}
const remoteResult = spawnSync('docker', ['compose', '--file', join(recipes[0].directory, 'compose.yaml'), 'config', '--format', 'json'], {
encoding: 'utf8',
env: { ...process.env, DB_BIND_ADDRESS: '0.0.0.0' },
});
assert.equal(remoteResult.status, 0, remoteResult.stderr);
const remoteService = JSON.parse(remoteResult.stdout).services[recipes[0].service];
assert.ok(remoteService.ports.every((port) => port.host_ip === '0.0.0.0'));
});
test('healthchecks safely reference configurable passwords', { skip: !dockerComposeAvailable }, () => {
const password = "space ' password";
const recipes = discoverRecipes().filter((recipe) => ['mariadb', 'mongodb', 'mysql', 'redis'].includes(recipe.database));
for (const recipe of recipes) {
const result = spawnSync('docker', ['compose', '--file', join(recipe.directory, 'compose.yaml'), 'config', '--format', 'json'], {
encoding: 'utf8',
env: { ...process.env, DB_PASSWORD: password },
});
assert.equal(result.status, 0, result.stderr);
const service = JSON.parse(result.stdout).services[recipe.service];
const command = service.healthcheck.test[1];
assert.equal(command.includes(password), false, `${recipeSelector(recipe)} interpolates the password into CMD-SHELL`);
if (recipe.database === 'mongodb') assert.match(command, /--password "\$\$MONGO_INITDB_ROOT_PASSWORD"/);
if (recipe.database === 'mysql') assert.match(command, /-p"\$\$MYSQL_ROOT_PASSWORD"/);
if (recipe.database === 'mariadb') assert.match(command, /-p"\$\$MARIADB_ROOT_PASSWORD"/);
if (recipe.database === 'redis') {
assert.equal(service.environment.REDIS_PASSWORD, password);
assert.match(command, /-a "\$\$REDIS_PASSWORD"/);
}
}
});
test('requires the target service to mount a named volume', () => {
const bindOnly = 'services:\n database:\n volumes:\n - ./init:/docker-entrypoint-initdb.d:ro\nvolumes:\n data:\n';
const namedVolume = 'services:\n database:\n volumes:\n - data:/var/lib/database\nvolumes:\n data:\n';
assert.equal(serviceHasNamedVolume(bindOnly, 'database'), false);
assert.equal(serviceHasNamedVolume(namedVolume, 'database'), true);
});
test('derives the required dbx-prefixed container name', () => {
assert.equal(expectedContainerName({ database: 'mysql', displayVersion: '5.7' }), 'dbx-mysql-5.7');
assert.equal(expectedContainerName({ database: 'PostgreSQL', displayVersion: '17.4' }), 'dbx-postgresql-17.4');
});
test('rejects a recipe whose Compose container name is not standardized', () => {
const [recipe] = discoverRecipes(fixture('mysql', '8.4'));
const composePath = join(recipe.directory, 'compose.yaml');
writeFileSync(composePath, readFileSync(composePath, 'utf8').replace('container_name: dbx-mysql-8.4', 'container_name: custom-mysql'));
assert.match(validateRecipe(recipe).join('; '), /container_name must be dbx-mysql-8.4/);
});
test('requires the shared default password and database name', () => {
const [recipe] = discoverRecipes(fixture('postgresql', '17.4'));
recipe.connection.password = 'different';
recipe.connection.database = 'other';
assert.match(validateRecipe(recipe).join('; '), /connection.password must be 123456/);
assert.match(validateRecipe(recipe).join('; '), /connection.database must be dbx/);
});
test('requires every recipe port to be one greater than its database default port', () => {
const [recipe] = discoverRecipes(fixture('postgresql', '17.4'));
recipe.connection.port = 5432;
assert.match(validateRecipe(recipe).join('; '), /connection.port must be defaultPort \+ 1/);
});
test('reports missing smoke structures without throwing a TypeError', () => {
const [recipe] = discoverRecipes(fixture('postgresql', '17.4'));
delete recipe.smoke;
let errors;
assert.doesNotThrow(() => {
errors = validateRecipe(recipe);
});
assert.match(errors.join('; '), /missing smoke/);
assert.match(errors.join('; '), /smoke\.steps must not be empty/);
recipe.smoke = {};
assert.doesNotThrow(() => validateRecipe(recipe));
assert.match(validateRecipe(recipe).join('; '), /smoke\.steps must not be empty/);
});
test('documents every checked-in recipe on both website pages', () => {
const pages = [
join(DEFAULT_RECIPES_ROOT, '..', '..', 'docs', 'content', 'docs', 'database-lab.mdx'),
join(DEFAULT_RECIPES_ROOT, '..', '..', 'docs', 'content', 'docs', 'database-lab.cn.mdx'),
].map((path) => readFileSync(path, 'utf8'));
for (const recipe of discoverRecipes()) {
const entry = `\`${recipe.database}/${recipe.displayVersion}\``;
for (const page of pages) assert.ok(page.includes(entry), `missing ${entry} from database lab documentation`);
}
});