C API を包むクラス
数行の C++ で、C API をクラスにできます。コンストラクターが開き、デストラクターが閉じ、ステータスコードは例外になります。
database.h は sqlite3.h をインクルードし、sqlite3 * を private にしているので、JavaScript からポインターは見えません。await new Database() でデータベースを開き、run で文を実行し、delete() でデストラクターを実行してデータベースを閉じます。
これは、ジェネレーターがそのままではバインドしないものや、JavaScript 向けの形にしたい API に使うパターンです。詳しくは合わないものをラップするを参照してください。
試してみる
try の中で、タイプミスのある文を実行し、クラスが投げるエラーを出力してみましょう。[■]database.h1#pragma once
#include <sqlite3.h>
#include <stdexcept>
#include <string>
// SQLite's C API behind a class: an error is an exception.
class Database {
public:
Database() { sqlite3_open(":memory:", &db); }
~Database() { sqlite3_close(db); }
int run(const std::string &sql) {
const int code = sqlite3_exec(db, sql.c_str(), 0, 0, 0);
if (code) throw std::runtime_error(sqlite3_errmsg(db));
return sqlite3_changes(db);
}
private:
sqlite3 *db = nullptr;
};
[■]main.js2import { initNative, Database } from './native/database.h';
await initNative();
const db = await new Database();
await db.run('create table t (x)');
const added = await db.run('insert into t values (1), (2)');
console.log('rows added:', added);
await db.delete();