Skip to main content

D1Database

Creates and manages Cloudflare D1 Databases - serverless SQL databases built on SQLite.

Props

name
string
Name of the database.
primaryLocationHint
string
Optional primary location hint for the database.Options: wnam, enam, weur, eeur, apac, oc
readReplication
object
Read replication configuration (only mutable property during updates).
delete
boolean
default:"true"
Whether to delete the database when the resource is removed from Alchemy.
adopt
boolean
default:"false"
Whether to adopt an existing database with the same name if it exists.
clone
D1Database | { id: string } | { name: string }
Clone data from an existing database to this new database (only applicable during creation phase).
const clonedDb = await D1Database("cloned-db", {
  clone: otherDb
});
importFiles
string[]
The names of SQL files to import. After migrations are applied, these files will be run.
migrationsTable
string
default:"d1_migrations"
Name of the table used to track migrations. Only used if migrationsDir is specified.
migrationsDir
string
Directory containing migration SQL files. If not set, no migrations will be applied.
const db = await D1Database("mydb", {
  migrationsDir: "./migrations"
});
jurisdiction
default | eu | fedramp
Optional jurisdiction for the database.

Output

id
string
The unique ID of the database (UUID).
name
string
The name of the database.
jurisdiction
D1DatabaseJurisdiction
The jurisdiction of the database.
type
d1
Type identifier for the binding.

Examples

Basic D1 Database

const db = await D1Database("my-app-db", {
  name: "my-app-db"
});

const worker = await Worker("api", {
  entrypoint: "./src/api.ts",
  bindings: {
    DB: db
  }
});

Database with Location Hint

const westUsDb = await D1Database("west-us-db", {
  name: "west-us-db",
  primaryLocationHint: "wnam"
});

Adopt Existing Database

const existingDb = await D1Database("existing-db", {
  name: "existing-db",
  adopt: true,
  readReplication: {
    mode: "auto"
  }
});

Database with Migrations

const db = await D1Database("mydb", {
  name: "mydb",
  migrationsDir: "./migrations"
});

Database with Custom Migration Table (Drizzle Compatible)

const db = await D1Database("mydb", {
  name: "mydb",
  migrationsDir: "./migrations",
  migrationsTable: "drizzle_migrations"
});

Clone Existing Database

const sourceDb = await D1Database("source-db");

const clonedDb = await D1Database("cloned-db", {
  name: "cloned-db",
  clone: sourceDb
});

Build docs developers (and LLMs) love