AI LOAD INSTRUCTION:
dbThe library is Yaklang's database core module, providing SQLite/MySQL connections, SQL queries, key-value storage, Payload dictionary management, and other capabilities. This page provides directly runnable examples and several real API shape conventions (see section 4 "Pitfalls"). Both examples canyak <file>pass self-tests. When writing database-related Yaklang, refer here first.
0. Related routes
- Main entry:yak
- Basic syntax (error handling
~、map、for):yaklang-syntax
1. Temporary SQLite: create table / CRUD / aggregation
Suitable for temporarily persisting structured data in scripts (scan results, assets, intermediate tables), using SQL for query statistics.
tempDB = db.OpenTempSqliteDatabase()~ // 返回 (gormDB, err), 用 ~ 处理
// Write operation: tempDB.Exec(sql, args...).Error is a field (not a function, cannot use ~) err = tempDB.Exec("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price INTEGER)").Error assert err == nil, "create failed" tempDB.Exec("INSERT INTO products (name, price) VALUES (?, ?)", "laptop", 8000) // ? parameterization prevents injection
// Read operation: db.ScanResult returns []map, each row is a map rows = db.ScanResult(tempDB, "SELECT * FROM products WHERE price > ? ORDER BY price DESC", 100)~ for row in rows { log.info("%v -> %v", row["name"], row["price"]) }
完整示例:[examples/sqlite-crud.yak](examples/sqlite-crud.yak)
## 2. 键值存储 (KV):跨脚本共享状态
写入的是 Yakit profile 数据库(持久化),适合插件/脚本之间共享配置与中间状态。
```yak
db.SetKey("my-key", "my-value") // 写 (重复调用即覆盖)
v = db.GetKey("my-key") // 读, 不存在返回 ""
db.SetKeyWithTTL("tmp", "v", 60) // 带过期 (秒)
db.DelKey("my-key") // 删
// 项目级配置 (随项目切换), 与全局 KV 区分
db.SetProjectKey("conf", json.dumps({"a":1}))
cfg = db.GetProjectKey("conf")
3. Payload dictionary management: hand brute-force dictionaries to Yakit for unified management
db.SavePayload("my-users", ["admin", "root", "guest"])~ // 存入字典组
for content in db.YieldPayload("my-users") { // 迭代器, 逐条产出内容字符串
log.info("payload: %s", content)
}
groups = db.GetAllPayloadGroupsName() // 列出所有字典组名
db.DeletePayloadByGroup("my-users") // 删除整组
Complete example (KV + Payload, with cleanup):examples/kv-and-payload.yak
4. Real API shape conventions (must-read before writing)
| Convention | Incorrect usage | Correct usage |
|---|---|---|
.Exec(...).Error is a field not a function |
tempDB.Exec(sql).Error~ |
err = tempDB.Exec(sql).Error; assert err == nil |
db.OpenTempSqliteDatabase() returns (db, err) |
tempDB = db.OpenTempSqliteDatabase() |
tempDB = db.OpenTempSqliteDatabase()~ |
db.YieldPayload produces a content string, not an object |
for p in db.YieldPayload(g) { p.Content } |
for content in db.YieldPayload(g) { ... } |
db.GetKey returns an empty string rather than nil when it does not exist |
if db.GetKey(k) == nil |
if db.GetKey(k) == "" |
| KV / Payload are persistent writes | Use fixed dirty data for self-tests | Use a unique prefix for key/group and clean up at the end |
When unsure about a method, use
desc(db)ordesc(tempDB)to view available methods in the script. Take pride in careful consultation, be ashamed of guessing interfaces.
5. Common API quick reference
| Purpose | API |
|---|---|
| Open temporary SQLite | db.OpenTempSqliteDatabase()~ |
| Execute SQL (write) | tempDB.Exec(sql, args...).Error |
| Query returns []map | db.ScanResult(tempDB, sql, args...)~ |
| Key-value read, write, delete | db.SetKey / db.GetKey / db.DelKey / db.SetKeyWithTTL |
| Project-level configuration | db.SetProjectKey / db.GetProjectKey |
| Payload dictionary | db.SavePayload / db.YieldPayload / db.GetAllPayloadGroupsName / db.DeletePayloadByGroup |
6. Verification
cd /Users/v1ll4n/Projects/yaklang
go run common/yak/cmd/yak.go skills/yaklang-database/examples/sqlite-crud.yak
go run common/yak/cmd/yak.go skills/yaklang-database/examples/kv-and-payload.yak
Each example should: all asserts pass, logs all in English, appear ... self test passed。
Reference sources
- yaklang-ai-training-materials library-usage/db/db-practice.yak
- yaklang-ai-training-materials library-usage/yakit-db/yakit-db-practice.yak
- Library exports:
common/yak/script_engine.go