본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Export and save D1 database (D1 데이터베이스 내보내고 저장하기)

원문 보기 위키 갱신

이 문서는 Workflows를 사용해 D1 데이터베이스를 R2 스토리지로 내보내고 저장하는 예시를 설명해요.

출처: 문서

본문

이 예시에서는 Workflow 바인딩의 schedules 필드를 사용해 정해진 일정으로 실행되는 Workflow를 구현해요. 그 Workflow는 REST API를 사용해 D1 데이터베이스에 대한 백업을 시작하고, SQL 덤프를 R2 버킷에 저장해요.

Workflow가 트리거되면 REST API를 호출해 특정 데이터베이스에 대한 내보내기 작업(export job)을 시작해요. 그런 다음 같은 엔드포인트를 다시 호출해 백업 작업이 준비됐고 SQL 덤프를 다운로드할 수 있는지 확인해요.

이 예시에서 볼 수 있듯이 Workflows는 응답과 실패를 모두 처리하므로 개발자의 부담을 덜어줘요. Workflows는 다음 단계를 재시도해요:

  • 성공적인 응답을 받을 때까지 API 호출
  • 제공된 URL에서 백업 가져오기
  • 파일을 R2에 저장하기

Workflow는 백업 파일이 준비될 때까지 실행되며, 완료될 때까지 가능한 모든 상황을 처리해요.

이 예시는 D1 데이터베이스를 백업하기 위한 단순화된 단계를 제공해서 Workflows의 가능성을 이해하도록 도와줘요. 각 단계에서 기본 절전(sleeping) 및 재시도(retrying) 구성을 사용해요. 실제 시나리오에서는 더 많은 단계와 추가 로직이 필요할 가능성이 높아요.

import {
	WorkflowEntrypoint,
	WorkflowStep,
	WorkflowEvent,
} from "cloudflare:workers";

// We are using R2 to store the D1 backup
type Env = {
	BACKUP_WORKFLOW: Workflow;
	D1_REST_API_TOKEN: string;
	BACKUP_BUCKET: R2Bucket;
	ACCOUNT_ID: string;
	DATABASE_ID: string;
};

// Workflow logic
export class backupWorkflow extends WorkflowEntrypoint<Env> {
	async run(_event: WorkflowEvent<unknown>, step: WorkflowStep) {
		const accountId = this.env.ACCOUNT_ID;
		const databaseId = this.env.DATABASE_ID;

		const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/d1/database/${databaseId}/export`;
		const method = "POST";
		const headers = new Headers();
		headers.append("Content-Type", "application/json");
		headers.append("Authorization", `Bearer ${this.env.D1_REST_API_TOKEN}`);

		const bookmark = await step.do(
			`Starting backup for ${databaseId}`,
			async () => {
				const payload = { output_format: "polling" };

				const res = await fetch(url, {
					method,
					headers,
					body: JSON.stringify(payload),
				});
				const { result } = (await res.json()) as any;

				// If we don't get `at_bookmark` we throw to retry the step
				if (!result?.at_bookmark) throw new Error("Missing `at_bookmark`");

				return result.at_bookmark;
			},
		);

		await step.do("Check backup status and store it on R2", async () => {
			const payload = { current_bookmark: bookmark };

			const res = await fetch(url, {
				method,
				headers,
				body: JSON.stringify(payload),
			});
			const { result } = (await res.json()) as any;

			// The endpoint sends `signed_url` when the backup is ready to download.
			// If we don't get `signed_url` we throw to retry the step.
			if (!result?.signed_url) throw new Error("Missing `signed_url`");

			const dumpResponse = await fetch(result.signed_url);
			if (!dumpResponse.ok) throw new Error("Failed to fetch dump file");

			// Finally, stream the file directly to R2
			await this.env.BACKUP_BUCKET.put(result.filename, dumpResponse.body);
		});
	}
}

export default {
	async fetch(req: Request, env: Env): Promise<Response> {
		return new Response("Not found", { status: 404 });
	},
};

여기 최소한의 package.json이에요:

{
	"devDependencies": {
		"wrangler": "^3.99.0"
	}
}

대상 D1 데이터베이스를 내보낼 권한이 있는 D1_REST_API_TOKEN을 시크릿(secret)으로 만드세요.

여기 Wrangler 설정 파일이 있어요:

{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "backup-d1",
	"main": "src/index.ts",
	// Set this to today's date
	"compatibility_date": "2026-10-07",
	"compatibility_flags": [
		"nodejs_compat"
	],
	"vars": {
		"ACCOUNT_ID": "account-id",
		"DATABASE_ID": "database-id"
	},
	"workflows": [
		{
			"name": "backup-workflow",
			"binding": "BACKUP_WORKFLOW",
			"class_name": "backupWorkflow",
			"schedules": ["0 0 * * *"]
		}
	],
	"r2_buckets": [
		{
			"binding": "BACKUP_BUCKET",
			"bucket_name": "d1-backups"
		}
	]
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "backup-d1"
main = "src/index.ts"
# Set this to today's date
compatibility_date = "2026-10-07"
compatibility_flags = [ "nodejs_compat" ]

[vars]
ACCOUNT_ID = "account-id"
DATABASE_ID = "database-id"

[[workflows]]
name = "backup-workflow"
binding = "BACKUP_WORKFLOW"
class_name = "backupWorkflow"
schedules = [ "0 0 * * *" ]

[[r2_buckets]]
binding = "BACKUP_BUCKET"
bucket_name = "d1-backups"

각 예약 실행은 자동으로 새 Workflow 인스턴스를 만들어요.

예약된 인스턴스는 일치하는 cron 식(cron expression)과 예약된 트리거 시간을 event.schedule에 포함해요.

Workflow 일정을 구성할 때는 최신 Wrangler 릴리스를 사용하세요. 로컬 Wrangler 스키마가 아직 schedules를 인식하지 못한다면 배포 전에 Wrangler를 업데이트하세요.