To interact with your D1 database from your Worker, you need to access it through the environment bindings provided to the Worker (env).
async fetch(request, env) {
// D1 database is 'env.DB', where "DB" is the binding name from the Wrangler configuration file.
}from workers import WorkerEntrypoint
class Default(WorkerEntrypoint):
async def fetch(self, request):
# D1 database is 'self.env.DB', where "DB" is the binding name from the Wrangler configuration file.
passA D1 binding has the type D1Database, and supports a number of methods, as listed below.
Creates a prepared statement without executing it. D1 rejects SQL transaction control statements when you execute the statement, not when you call prepare().
const someVariable = `Bs Beverages`;
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);some_variable = "Bs Beverages"
stmt = self.env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(some_variable)query:StringRequired- The SQL query you wish to execute on the database.
D1PreparedStatement:Object- An object which only contains methods. Refer to Prepared statement methods.
You can use the bind method to dynamically bind a value into the query statement, as shown below.
-
Example of a static statement without using
bind:const stmt = db .prepare("SELECT * FROM Customers WHERE CompanyName = 'Alfreds Futterkiste' AND CustomerId = 1")stmt = db.prepare("SELECT * FROM Customers WHERE CompanyName = 'Alfreds Futterkiste' AND CustomerId = 1") -
Example of an ordered statement using
bind:const stmt = db .prepare("SELECT * FROM Customers WHERE CompanyName = ? AND CustomerId = ?") .bind("Alfreds Futterkiste", 1);stmt = db.prepare("SELECT * FROM Customers WHERE CompanyName = ? AND CustomerId = ?").bind("Alfreds Futterkiste", 1)
Refer to the bind method documentation for more information.
Sends multiple SQL statements in one call to D1, reducing network round trips. D1 runs the statements in order in one SQLite transaction ↗︎ and commits them together. If a statement fails or D1 cannot commit the transaction, none of the changes in the batch take effect.
D1 manages the transaction for you. Do not include SQL transaction control statements in a batch.
To send batch statements, provide D1Database::batch a list of prepared statements and get the results in the same order.
const companyName1 = `Bs Beverages`;
const companyName2 = `Around the Horn`;
const stmt = env.DB.prepare(`SELECT * FROM Customers WHERE CompanyName = ?`);
const batchResult = await env.DB.batch([
stmt.bind(companyName1),
stmt.bind(companyName2)
]);company_name1 = "Bs Beverages"
company_name2 = "Around the Horn"
stmt = self.env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?")
batch_result = await self.env.DB.batch([
stmt.bind(company_name1),
stmt.bind(company_name2),
])statements:Array- An array of
D1PreparedStatements.
- An array of
results:Array- An array of
D1Resultobjects containing the results of theD1Database::preparestatements. Each object is in the array position corresponding to the array position of the initialD1Database::preparestatement within thestatements. - Refer to
D1Resultfor more information about this object.
- An array of
Example of return values
const companyName1 = `Bs Beverages`;
const companyName2 = `Around the Horn`;
const stmt = await env.DB.batch([
env.DB.prepare(`SELECT * FROM Customers WHERE CompanyName = ?`).bind(companyName1),
env.DB.prepare(`SELECT * FROM Customers WHERE CompanyName = ?`).bind(companyName2)
]);
return Response.json(stmt)from workers import Response
company_name1 = "Bs Beverages"
company_name2 = "Around the Horn"
stmt = await self.env.DB.batch([
self.env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(company_name1),
self.env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(company_name2),
])
return Response.json(stmt)[
{
"success": true,
"meta": {
"served_by": "miniflare.db",
"duration": 0,
"changes": 0,
"last_row_id": 0,
"changed_db": false,
"size_after": 8192,
"rows_read": 4,
"rows_written": 0
},
"results": [
{
"CustomerId": 11,
"CompanyName": "Bs Beverages",
"ContactName": "Victoria Ashworth"
},
{
"CustomerId": 13,
"CompanyName": "Bs Beverages",
"ContactName": "Random Name"
}
]
},
{
"success": true,
"meta": {
"served_by": "miniflare.db",
"duration": 0,
"changes": 0,
"last_row_id": 0,
"changed_db": false,
"size_after": 8192,
"rows_read": 4,
"rows_written": 0
},
"results": [
{
"CustomerId": 4,
"CompanyName": "Around the Horn",
"ContactName": "Thomas Hardy"
}
]
}
]console.log(stmt[1].results);print(stmt[1].results.to_py())[
{
"CustomerId": 4,
"CompanyName": "Around the Horn",
"ContactName": "Thomas Hardy"
}
]-
You can construct batches reusing the same prepared statement:
const companyName1 = `Bs Beverages`; const companyName2 = `Around the Horn`; const stmt = env.DB.prepare(`SELECT * FROM Customers WHERE CompanyName = ?`); const batchResult = await env.DB.batch([ stmt.bind(companyName1), stmt.bind(companyName2) ]); return Response.json(batchResult);from workers import Response company_name1 = "Bs Beverages" company_name2 = "Around the Horn" stmt = self.env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?") batch_result = await self.env.DB.batch([ stmt.bind(company_name1), stmt.bind(company_name2), ]) return Response.json(batch_result)
Use env.DB.batch([...]) when multiple dependent writes must commit or roll back together.
This example inserts an order, writes a ledger entry, and debits an account in one batch() call. It uses whole credits and assumes orders.account_id references accounts(id) and accounts.balance uses INTEGER NOT NULL CHECK (balance >= 0). If the account does not exist or the debit would make its balance negative, a constraint fails and D1 rolls back the batch.
async function placeOrder(env, orderId, accountId, amount) {
if (!Number.isSafeInteger(amount) || amount <= 0) {
return Response.json(
{ error: "Amount must be a positive safe integer" },
{ status: 400 },
);
}
const results = await env.DB.batch([
env.DB.prepare(
"INSERT INTO orders (id, account_id, amount) VALUES (?, ?, ?)",
).bind(orderId, accountId, amount),
env.DB.prepare(
"INSERT INTO ledger (order_id, account_id, delta) VALUES (?, ?, ?)",
).bind(orderId, accountId, -amount),
env.DB.prepare(
"UPDATE accounts SET balance = balance - ? WHERE id = ?",
).bind(amount, accountId),
]);
return Response.json({ ok: true, results });
}export interface Env {
DB: D1Database;
}
async function placeOrder(
env: Env,
orderId: string,
accountId: string,
amount: number,
): Promise<Response> {
if (!Number.isSafeInteger(amount) || amount <= 0) {
return Response.json(
{ error: "Amount must be a positive safe integer" },
{ status: 400 },
);
}
const results = await env.DB.batch([
env.DB.prepare(
"INSERT INTO orders (id, account_id, amount) VALUES (?, ?, ?)",
).bind(orderId, accountId, amount),
env.DB.prepare(
"INSERT INTO ledger (order_id, account_id, delta) VALUES (?, ?, ?)",
).bind(orderId, accountId, -amount),
env.DB.prepare(
"UPDATE accounts SET balance = balance - ? WHERE id = ?",
).bind(amount, accountId),
]);
return Response.json({ ok: true, results });
}An UPDATE whose WHERE clause matches no rows still succeeds. It does not cause D1 to roll back the batch. To check a condition and update a row in one statement, refer to Conditional atomic updates.
Executes one or more queries directly without prepared statements or parameter bindings.
const returnValue = await env.DB.exec(`SELECT * FROM Customers WHERE CompanyName = "Bs Beverages"`);return_value = await self.env.DB.exec('SELECT * FROM Customers WHERE CompanyName = "Bs Beverages"')query:StringRequired- The SQL query statement without parameter binding.
D1ExecResult:Object- The
countproperty contains the number of executed queries. - The
durationproperty contains the duration of operation in milliseconds.- Refer to
D1ExecResultfor more information.
- Refer to
- The
Example of return values
const returnValue = await env.DB.exec(`SELECT * FROM Customers WHERE CompanyName = "Bs Beverages"`);
return Response.json(returnValue);from workers import Response
return_value = await self.env.DB.exec('SELECT * FROM Customers WHERE CompanyName = "Bs Beverages"')
return Response.json(return_value){
"count": 1,
"duration": 1
}- If an error occurs, an exception is thrown with the query and error messages, execution stops and further statements are not executed. Refer to Errors to learn more.
- This method can have poorer performance (prepared statements can be reused in some cases) and, more importantly, is less safe.
- Only use this method for maintenance and one-shot tasks (for example, migration jobs).
- The input can be one or multiple queries separated by
\n. - Do not include SQL transaction control statements. D1 rejects them when you call
exec().
Dumps the entire D1 database to an SQLite compatible file inside an ArrayBuffer.
const dump = await db.dump();
return new Response(dump, {
status: 200,
headers: {
"Content-Type": "application/octet-stream",
},
});from workers import Response
dump = await db.dump()
return Response(dump, status=200, headers={"Content-Type": "application/octet-stream"})- None.
- None.
Starts a D1 session which maintains sequential consistency among queries executed on the returned D1DatabaseSession object.
const session = env.DB.withSession("<parameter>");session = self.env.DB.withSession("<parameter>")-
first-primary:StringOptional- Directs the first query in the Session (whether read or write) to the primary database instance. Use this option if you need to start the Session with the most up-to-date data from the primary database instance.
- Subsequent queries in the Session may use read replicas.
- Subsequent queries in the Session have sequential consistency.
-
first-unconstrained:StringOptional- Directs the first query in the Session (whether read or write) to any database instance. Use this option if you do not need to start the Session with the most up-to-date data, and wish to prioritize minimizing query latency from the very start of the Session.
- Subsequent queries in the Session have sequential consistency.
- This is the default behavior when no parameter is provided.
-
bookmark:StringOptional- A
bookmarkfrom a previous D1 Session. This allows you to start a new Session from at least the providedbookmark. - Subsequent queries in the Session have sequential consistency.
- A
D1DatabaseSession:Object- An object which contains the methods
prepare()andbatch()similar toD1Database, along with the additionalgetBookmarkmethod.
- An object which contains the methods
- To use read replication, you have to use the D1 Sessions API, otherwise all queries will continue to be executed only by the primary database.
- You can return the last encountered
bookmarkfor a given Session usingsession.getBookmark().
Retrieves the latest bookmark from the D1 Session.
const session = env.DB.withSession("first-primary");
const result = await session
.prepare(`SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'`)
.run()
const { bookmark } = session.getBookmark();
return bookmark;session = self.env.DB.withSession("first-primary")
result = await session.prepare(
"SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'"
).run()
bookmark = session.getBookmark()- None
bookmark:String | null- A
bookmarkwhich identifies the latest version of the database seen by the last query executed within the Session. - Returns
nullif no query is executed within a Session.
- A
This method is equivalent to D1Database::prepare.
This method is equivalent to D1Database::batch.