D1
Cloudflare D1 is a distributed SQL database built on SQLite for Workers. Cloesce allows any number of D1 databases to be defined in the schema, and allows Models to represent tables in those databases.
Tip
D1 is limited to 10GB of storage, so it is best suited for the primary database of a small application, or for a queryable cache layer in front of a larger database.
For more complex applications, consider using Durable Objects, which can provide virtually unlimited storage across shards with SQLite.
Defining a D1 Binding
To define a D1 environment binding, use the d1 block within the env block:
d1 {
MyDb
}
Unlike Workers KV and R2, no binding templates can be defined on a D1 binding (though, in the future, compiler verified SQL query templates will be supported!).
To interact with the D1 database, define Models backed by the binding:
model User for MyDb {
primary {
id: int
}
column {
name: string
}
}
See more on D1 Backed Models in the Models chapter.
Wrangler Configuration
A Wrangler configuration will be generated for each D1 binding defined in the schema:
[[d1_databases]]
binding = "MyDb"
database_id = "replace_with_mydb_id"
database_name = "replace_with_mydb_name"
migrations_dir = "migrations/MyDb"
Migrations
To generate SQL migration files for a specific binding, run the following command:
cloesce migrate --binding <binding> <migration-name>
Apply the generated migrations for a D1 database using the Wrangler CLI:
npx wrangler d1 migrations apply <binding-name>