C ではじめる
PetraDBは、SQLiteスタイルのC APIを持つネイティブ共有ライブラリ(Linuxではlibpetradb-engine.so、macOSでは.dylib)を提供します。このライブラリは自己完結型で、JVM、Scala、その他のランタイムは不要です。
ライブラリの取得
Section titled “ライブラリの取得”共有ライブラリとヘッダーの2つのファイルが必要です。
オプション1:GitHubリリースからダウンロード
Section titled “オプション1:GitHubリリースからダウンロード”最新リリースからlibpetradb-engine.soとpetradb.hをダウンロードします。任意のディレクトリ(例:/usr/local/libと/usr/local/include、またはプロジェクトローカルのディレクトリ)に配置してください。
オプション2:ソースからビルド
Section titled “オプション2:ソースからビルド”sbtとCツールチェーン(gcc/clang)が必要です。
git clone https://github.com/edadma/petradb.gitcd petradbsbt engineNative/nativeLinkこれにより以下が生成されます。
- ライブラリ:
engine/native/target/scala-3.8.2/libpetradb-engine.so - ヘッダー:
engine/native/petradb.h
最初のプログラム
Section titled “最初のプログラム”myapp.cを作成します。
#include <stdio.h>#include "petradb.h"
int main(void) { int db = petradb_open(); int conn = petradb_connect(db);
petradb_exec(conn, "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT)"); petradb_exec(conn, "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')"); petradb_exec(conn, "INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com')");
int cur = petradb_prepare(conn, "SELECT id, name, email FROM users ORDER BY id"); while (petradb_step(cur) == PETRADB_ROW) { int id = petradb_column_int(cur, 0); const char *name = petradb_column_text(cur, 1); const char *email = petradb_column_text(cur, 2); printf("%d: %s <%s>\n", id, name, email); } petradb_finalize(cur); petradb_close(db); return 0;}コンパイルと実行
Section titled “コンパイルと実行”ライブラリとヘッダーが/usr/local/libと/usr/local/includeにある場合:
gcc -o myapp myapp.c -lpetradb-engine./myappファイルがプロジェクトローカルのディレクトリ(例:./libと./include)にある場合:
gcc -o myapp myapp.c \ -I./include \ -L./lib \ -lpetradb-engine \ -Wl,-rpath,./lib
./myappフラグの説明:
-Iはコンパイラにpetradb.hの場所を指定します-Lはリンカーにlibpetradb-engine.soの場所を指定します-lはライブラリ名を指定します(リンカーがlibプレフィックスと.soサフィックスを追加します)-Wl,-rpathは実行ファイルにライブラリパスを埋め込み、実行時に.soを見つけられるようにします
出力:
1: Alice <alice@example.com>2: Bob <bob@example.com>永続ストレージ
Section titled “永続ストレージ”再起動後もデータを保持するには、petradb_open_persistentを使用します。
int db = petradb_open_persistent("mydata.db");データベースファイルは初回使用時に作成され、以降の実行で再度開かれます。すべてのテーブル、データ、インデックス、トリガー、ストアドプロシージャが自動的に保持されます。
ユーザー定義関数
Section titled “ユーザー定義関数”SQLから呼び出し可能なネイティブC関数を登録します。トリガーやストアドプロシージャからも使用できます。
void my_double(int ctx, int argc, const int* argv) { if (petradb_value_is_null(argv[0])) { petradb_result_null(ctx); return; } petradb_result_int(ctx, petradb_value_int(argv[0]) * 2);}
petradb_create_function(db, "my_double", 1, NULL, my_double);// 使用例: SELECT my_double(age) FROM users;同じ共有ライブラリはC FFIをサポートする任意の言語で動作します。
- Rust:
unsafe extern "C"宣言 +-lpetradb-engineでリンク - Python:
ctypes.cdll.LoadLibrary("libpetradb-engine.so") - Go:
cgoで// #cgo LDFLAGS: -lpetradb-engine - Ruby:
ffigemのFFI::Library
次のステップ
Section titled “次のステップ”カーソル、カラムアクセサ、ユーザー定義関数、エラー処理を含む完全な関数一覧については、C APIリファレンスをご覧ください。