D1 兼容大多数 SQLite SQL 约定,因为它利用了 SQLite 的查询引擎。您可以使用 SQL 命令查询 D1。
有多种方式可以与 D1 数据库交互:
- 在代码中使用 D1 Workers Binding API。
- 使用 D1 REST API。
- 使用 D1 Wrangler 命令。
D1 理解 SQLite 语义,允许您通过 Workers Binding API 或 REST API(包括 Wrangler 命令)使用 SQL 语句查询数据库。请参阅 D1 SQL API 了解支持的 SQL 语句。
在 D1 中使用 SQL 时,您可能希望在数据库的表之间定义并强制执行外键约束。外键约束允许您强制执行表之间的关系,或防止您删除被其他表中的行引用的行。下面展示了一个外键关系的示例。
CREATE TABLE users (
user_id INTEGER PRIMARY KEY,
email_address TEXT,
name TEXT,
metadata TEXT
)
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
status INTEGER,
item_desc TEXT,
shipped_date INTEGER,
user_who_ordered INTEGER,
FOREIGN KEY(user_who_ordered) REFERENCES users(user_id)
)有关更多信息,请参阅定义外键。
D1 允许您查询和解析存储在数据库中的 JSON 数据。例如,您可以提取 JSON 对象中的值。
给定名为 sensor_reading 的列中的以下 JSON 对象(type:blob),您可以直接从中提取值。
{
"measurement": {
"temp_f": "77.4",
"aqi": [21, 42, 58],
"o3": [18, 500],
"wind_mph": "13",
"location": "US-NY"
}
}-- Extract the temperature value
SELECT json_extract(sensor_reading, '$.measurement.temp_f')-- returns "77.4" as TEXT有关查询 JSON 对象的更多信息,请参阅查询 JSON。
Workers Binding API 主要与数据平面交互,允许您从 Worker 查询 D1 数据库。
这需要您:
- 将 D1 数据库绑定到 Worker。
- 准备语句。
- 运行语句。
export default {
async fetch(request, env) {
const {pathname} = new URL(request.url);
const companyName1 = `Bs Beverages`;
const companyName2 = `Around the Horn`;
const stmt = env.DB.prepare(`SELECT * FROM Customers WHERE CompanyName = ?`);
if (pathname === `/RUN`) {
const returnValue = await stmt.bind(companyName1).run();
return Response.json(returnValue);
}
return new Response(
`Welcome to the D1 API Playground!
\nChange the URL to test the various methods inside your index.js file.`,
);
},
};有关更多信息,请参阅 Workers Binding API。
REST API 主要与控制平面交互,允许您创建/管理 D1 数据库。
有关 D1 REST API 文档,请参阅 D1 REST API。
您可以使用 Wrangler 命令查询 D1 数据库。请注意,Wrangler 命令使用 REST API 执行其操作。
npx wrangler d1 execute prod-d1-tutorial --command="SELECT * FROM Customers"🌀 Mapping SQL input into an array of statements
🌀 Executing on local database production-db-backend (<DATABASE_ID>) from .wrangler/state/v3/d1:
┌────────────┬─────────────────────┬───────────────────┐
│ CustomerId │ CompanyName │ ContactName │
├────────────┼─────────────────────┼───────────────────┤
│ 1 │ Alfreds Futterkiste │ Maria Anders │
├────────────┼─────────────────────┼───────────────────┤
│ 4 │ Around the Horn │ Thomas Hardy │
├────────────┼─────────────────────┼───────────────────┤
│ 11 │ Bs Beverages │ Victoria Ashworth │
├────────────┼─────────────────────┼───────────────────┤
│ 13 │ Bs Beverages │ Random Name │
└────────────┴─────────────────────┴───────────────────┘