Driverek

C++

Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.

Telepítés
Forrásból.
Forrás
drivers/cpp

Header-only C++17 over the C driver: nucleus::Connection (RAII; throws nucleus::Error with code() and hint()), query(sql, {params…}) returning a Result of nucleus::Values (std::variant of NULL, bool, int64, double, text, Numeric, Date, Timestamp, TimestampTz, Interval, Array, Uuid — 16 bytes, Uuid::parse — and Ext, another registered type’s name and binary form; protocol version 3’s SmallInt, Integer, Real, Bytes, Time, Inet and Cidr — Inet::parse, Cidr::parse — and Vector, a std::vector<float>, SparseVector — dimensions, 0-based positions and values — and Json, its text), transaction([](Connection&) { … }). Protocol version 4 (through the C driver): the password is proved by SCRAM-SHA-256, never sent. TLS with a C driver built with OpenSSL: Config::tls, tls_ca, tls_no_verify, tls_cert, tls_key; Config::token for an identity token. Large results stream (protocol version 6, through the C driver): for (const auto& row : db.cursor(sql, {params…}, fetch)) reads them as they arrive, a batch at a time; a Cursor destroyed or close()d early stops the statement. Columnar results: auto b = db.batches(sql); while (b.next()) b.values<int32_t>(0)… (pointers into the batch; text(col, row), is_null(col, row)). Bulk load: db.copy("COPY t FROM STDIN", data) with a string or an std::istream. Many statements in one round trip: db.pipeline({{sql, params}, …}) (each one’s Result or Error, in a std::variant); one statement for many rows, all or none: db.execute_many(sql, rows).

cc -std=c99 -c ../c/nucleus.c -o nucleus.o
c++ -std=c++17 -I../c -I. your.cpp nucleus.o

Example: examples/cpp/quickstart.cpp.

Encrypted columns

A column’s values encrypted here and decrypted here: the server stores bytea ciphertext and never holds the key; a blind index beside it finds equal values (nucleus PLAN.md §M14.30 K5, DOCS.md §11 — what it leaves visible is said there). master is 32 bytes the application keeps.

nucleus::ColumnKey key(master, "users.email");
db.query("INSERT INTO users VALUES ($1, $2, $3)",
         {int64_t(1), key.encrypt(std::string("[email protected]")), key.blind_index(std::string("[email protected]"))});
auto r = db.query("SELECT email FROM users WHERE email_index = $1", {key.blind_index(std::string("[email protected]"))});
std::get<std::string>(key.decrypt(r.rows[0][0].as<nucleus::Bytes>()));   // "[email protected]"

A sealed table’s rows whose key their user holds: db.present_subject_key(subject, secret).

Documents

A collection’s documents by MongoDB’s requests (CREATE COLLECTION; nucleus DOCS.md §8.41, §10 Documents), in the connection’s transaction:

auto people = db.collection("people");
people.insert_one(R"({"name": "ann", "age": 34})");
nucleus::FindOptions o;
o.sort = R"({"age": -1})";
for (auto& doc : people.find(R"({"age": {"$gte": 30}})", o)) std::cout << doc.text << "\n";
people.update_one(R"({"name": "ann"})", R"({"$inc": {"age": 1}})", true);

Streams

A stream’s entries (CREATE STREAM; nucleus DOCS.md §8.43): appended in a transaction, numbered by its commit; a consumer group’s next batch handled exactly once — the work’s writes and the group’s position committed together, a conflict with another consumer run again; a wait for the next entry that holds no transaction on the server:

auto jobs = db.stream_of("jobs");
jobs.append({"name", "image"}, {"resize", 42});
jobs.process("workers", 100, 30000, [&](const nucleus::Result& entries) {  // seq first
    for (auto& e : entries.rows) db.query("INSERT INTO done VALUES ($1)", {e[0]});
});                                                                         // entries processed
jobs.wait(0, 1000);                                                         // the newest seq

Task queues

A task queue’s tasks (CREATE QUEUE; nucleus DOCS.md §8.45): added (a row), taken under a lease, each done exactly once — the work’s writes and the task’s FINISH committed together; a task whose work fails is failed into a retry after the backoff or, past its attempts, a dead letter; one whose lease ran out while it worked is left to the worker that took it again:

auto jobs = db.queue_of("jobs");
jobs.add({"kind"}, {Value("resize")});           // its id
jobs.process(10, -1, [&](const nucleus::Task& task) {   // id, attempt, values
    db.query("INSERT INTO thumbnails VALUES ($1)", {Value(task.id)});
});                                              // tasks finished
auto task = jobs.take(1, 60000).at(0);           // or by hand: take, then
jobs.fail(task, std::string("timeout"));         // finish(task) / fail(...): "retry" | "dead"

Live queries

A query’s result kept as the commits change it (nucleus DOCS.md §8.47):

auto s = db.subscribe("SELECT id, title FROM tasks WHERE done = $1", {nucleus::Value(false)});
for (const auto& c : s.changes(30000)) { /* c.diff: +1 came, -1 went; c.row */ }
// s.rows(): the result, kept on this side
s.close();

A cluster

Several servers named, the one wanted found among them by the role each says it has (protocol version 12), and found again after a failover:

nucleus::Config cfg;
cfg.host = "db1";
cfg.hosts = "db2:20035,db3:20035";      // tried after host, in turn
cfg.target = "primary";                 // or "any", "replica", "prefer-replica"
nucleus::Connection db(cfg);
uint64_t token = db.last_commit();      // the newest commit seen
cfg.target = "prefer-replica";
nucleus::Connection reader(cfg);
reader.wait_commit(token, 5000);        // true: the replica has it

role(), server_host(), server_port(), reconnect(); load_balance shuffles the servers first. Outside a transaction block, a statement a former primary refused (25006) or one not sent because the connection had closed runs again on the primary found anew (looked for up to the failover timeout, 30 s); one whose connection died while it ran fails with 08006 (its outcome unknown) and the next statement connects anew. Inside a transaction block the transaction went with the connection: the next statement is refused with 08007 — a ROLLBACK passes — and the one after runs on the new primary. What the session set (SET, prepared statements) does not come along; the commit token does (nucleus DOCS.md §9 “Clients of a cluster”).

Licence

MIT — see LICENSE. The database itself is AGPL-3.0-only; a program that reaches a nucleus server through this driver is not bound by it (the repository’s COPYRIGHT).