SQLite3 bindings for latest MoonBit toolchian
moon add daqing/sqliteimport {
"daqing/sqlite",
}
options(
link: { "native": { "cc-link-flags": "-lsqlite3" } },
)let db = match @sqlite.Database::open(":memory:") {
Some(d) => d
None => {
println("Failed to open database")
return
}
}
// Create table
db.exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")
// Insert data with bind_all()
match db.prepare("INSERT INTO users (name, age) VALUES (?, ?)") {
Some(stmt) => {
stmt.bind_all([Text(string_to_bytes("Alice")), Int(30)]) |> ignore
stmt.execute() |> ignore
stmt.finalize()
}
None => println("Failed to prepare statement")
}
// Query with iterator
match db.query("SELECT id, name, age FROM users") {
Some(stmt) => {
for row in stmt.iter() {
let id = row.column_int(0)
let age = row.column_int(2)
println("id=\{id}, age=\{age}")
}
stmt.finalize()
}
None => println("Failed to prepare statement")
}
db.close()# Native target
moon build --target native
moon test --target native
# JavaScript target
moon build --target js
moon test --target js
# Wasm target
moon build --target wasm
moon test --target wasmpub enum SqlValue {
Null
Int(Int)
Int64(Int64)
Double(Double)
Text(Bytes)
Blob(Bytes)
}| API | Native | JS | Wasm | Notes |
|---|---|---|---|---|
| Database::open | ✅ | ✅ | ✅ | |
| Database::close | ✅ | ✅ | ✅ | |
| Database::exec | ✅ | ✅ | ✅ | |
| Database::prepare | ✅ | ✅ | ✅ | |
| Database::query | ✅ | ✅ | ✅ | |
| Database::begin | ✅ | ✅ | ✅ | |
| Database::commit | ✅ | ✅ | ✅ | |
| Database::rollback | ✅ | ✅ | ✅ | |
| Database::savepoint | ✅ | ✅ | ✅ | |
| Database::changes | ✅ | ✅ | ✅ | JS/Wasm fall back to SQL when needed |
| Database::last_insert_rowid | ✅ | ✅ | ✅ | JS/Wasm use SELECT last_insert_rowid() |
| Database::total_changes | ✅ | ✅ | ✅ | JS/Wasm use SELECT total_changes() |
| Database::errcode | ✅ | ⚠️ | ✅ | JS always returns 0 |
| Database::errmsg | ✅ | ⚠️ | ✅ | JS always returns empty |
| Database::extended_errcode | ✅ | ⚠️ | ✅ | JS always returns 0 |
| Database::busy_timeout | ✅ | ⚠️ | ⚠️ | JS/Wasm always return false |
| Database::get_autocommit | ✅ | ⚠️ | ⚠️ | JS/Wasm always return true |
| Statement::bind | ✅ | ✅ | ✅ | |
| Statement::bind_all | ✅ | ✅ | ✅ | |
| Statement::execute | ✅ | ✅ | ✅ | |
| Statement::step | ✅ | ✅ | ✅ | |
| Statement::column | ✅ | ✅ | ✅ | Integer type differs (see below) |
| Statement::column_int | ✅ | ✅ | ✅ | |
| Statement::column_text | ✅ | ✅ | ✅ | |
| Statement::column_count | ✅ | ✅ | ✅ | |
| Statement::iter | ✅ | ✅ | ✅ | |
| Statement::reset | ✅ | ✅ | ✅ | |
| Statement::finalize | ✅ | ✅ | ✅ |
pub struct Database {
// private fields
}pub(all) enum SqlValue {
Null
Int(Int)
Int64(Int64)
Double(Double)
Text(Bytes)
Blob(Bytes)
}pub struct Statement {
// private fields
}