[ PROMPT_NODE_24076 ]
Do Storage API 参考
[ SKILL_DOCUMENTATION ]
# DO 存储 API 参考
## SQL API
typescript
const cursor = this.sql.exec('SELECT * FROM users WHERE email = ?', email);
for (let row of cursor) {} // 对象: { id, name, email }
cursor.toArray(); cursor.one(); // 单行 (若非 1 行则抛出异常)
for (let row of cursor.raw()) {} // 数组: [1, "Alice", "..."]
// 手动迭代
const iter = cursor[Symbol.iterator]();
const first = iter.next(); // { value: {...}, done: false }
cursor.columnNames; // ["id", "name", "email"]
cursor.rowsRead; cursor.rowsWritten; // 计费相关
type User = { id: number; name: string; email: string };
const user = this.sql.exec('...', userId).one();
## 同步 KV API (仅限 SQLite)
typescript
this.ctx.storage.kv.get("counter"); // 若不存在则返回 undefined
this.ctx.storage.kv.put("counter", 42);
this.ctx.storage.kv.put("user", { name: "Alice", age: 30 });
this.ctx.storage.kv.delete("counter"); // 若存在则返回 true
for (let [key, value] of this.ctx.storage.kv.list()) {}
// 列表选项: start, prefix, reverse, limit
this.ctx.storage.kv.list({ start: "user:", prefix: "user:", reverse: true, limit: 100 });
## 异步 KV API (支持两种后端)
typescript
await this.ctx.storage.get("key"); // 单个
await this.ctx.storage.get(["key1", "key2"]); // 多个 (最多 128)
await this.ctx.storage.put("key", value); // 单个
await this.ctx.storage.put({ "key1": "v1", "key2": { nested: true } }); // 多个 (最多 128)
await this.ctx.storage.delete("key");
await this.ctx.storage.delete(["key1", "key2"]);
await this.ctx.storage.list({ prefix: "user:", limit: 100 });
// 选项: allowConcurrency, noCache, allowUnconfirmed
await this.ctx.storage.get("key", { allowConcurrency: true, noCache: true });
await this.ctx.storage.put("key", value, { allowUnconfirmed: true, noCache: true });
### 存储选项
| 选项 | 方法 | 效果 | 使用场景 |
|--------|---------|--------|----------|
| `allowConcurrency` | get, list | 跳过输入门控;允许读取期间并发请求 | 不需要严格一致性的读取密集型指标 |
| `noCache` | get, put, list | 跳过内存缓存;始终从磁盘读取 | 极少访问的数据或直接测试存储 |
| `allowUnconfirmed` | put, delete | 在写入确认前返回(仍受输出门控保护) | 延迟比确认更重要的非关键写入 |
## 事务
typescript
// 同步 (仅限 SQL/同步 KV)
this.ctx.storage.transactionSync(() => {
this.sql.exec('UPDATE accounts SET balance = balance - ?