Dgraph Rust client which communicates with the server using gRPC.
Before using this client, it is highly recommended to go through tour.dgraph.io and docs.dgraph.io to understand how to run and work with Dgraph.
dgraph
supports only Dgraph versions 1.1 or higher.
Since this crate uses grpcio
, which is a wrapper around C++ library, there are
certain prerequisites needed before it can be installed. You can find them in
grpcio
documentation.
dgraph
is available on crates.io. Add the following dependency to your
Cargo.toml
.
[dependencies]
dgraph = "0.4.0"
There are also a couple of passthrough grpcio
features available:
openssl
openssl-vendored
Those are described in grpcio
documentation.
Dgraph
object can be initialised by passing it a list of dgraph::DgraphClient
clients as a vector. Connecting to multiple Dgraph servers in the same
cluster allows for better distribution of workload. The library provides
a macro to do so.
The following code snippet shows just one connection.
let dgraph = make_dgraph!(dgraph::new_dgraph_client("localhost:9080"));
Alternatively, secure client can be used:
fn open_cert_file(path: &str) -> Vec<u8> {
...
}
let root_ca = open_cert_file("./tls/ca.crt");
let cert = open_cert_file("./tls/client.user.crt");
let private_key = open_cert_file("./tls/client.user.key");
let dgraph = make_dgraph!(dgraph::new_secure_dgraph_client(
"localhost:9080",
root_ca,
cert,
private_key
));
To set the schema, create an instance of dgraph::Operation
and use the
Alter
endpoint.
let op = dgraph::Operation{
schema: "name: string @index(exact) .".to_string(), ..Default::default()
};
let result = dgraph.alter(&op);
// Check error
Operation
contains other fields as well, including DropAttr
and DropAll
.
DropAll
is useful if you wish to discard all the data, and start from a clean
slate, without bringing the instance down. DropAttr
is used to drop all the data
related to a predicate.
To create a transaction, call dgraph.new_txn()
, which returns a dgraph::Txn
object. This
operation incurs no network overhead.
Once dgraph::Txn
goes out of scope, txn.discard()
is automatically called via the Drop
trait.
Calling txn.discard()
after txn.commit()
is a no-op and calling this multiple
times has no additional side-effects.
let txn = dgraph.new_txn();
txn.mutate(mu)
runs a mutation. It takes in a dgraph::Mutation
object. You can set the data using JSON or RDF N-Quad format.
We define a Person struct to represent a Person and marshal an instance of it to use with Mutation
object.
#[derive(Serialize, Deserialize, Default, Debug)]
struct Person {
uid: String,
name: String,
}
let p = Person {
uid: "_:alice".to_string(),
Name: "Alice".to_string(),
}
let pb = serde_json::to_vec(&p).expect("Invalid json");
let mut mu = dgraph::Mutation {
json: pb, ..Default::default()
};
let assigned = txn.mutate(mu).expect("failed to create data");
For a more complete example, see the simple example simple (or the same example with secure client).
Sometimes, you only want to commit a mutation, without querying anything further.
In such cases, you can use mu.commit_now = true
to indicate that the
mutation must be immediately committed.
You can run a query by calling txn.query(q)
. You will need to pass in a GraphQL+- query string. If
you want to pass an additional map of any variables that you might want to set in the query, call
txn.query_with_vars(q, vars)
with the variables map as third argument.
Let's run the following query with a variable $a:
let q = r#"query all($a: string) {
all(func: eq(name, $a)) {
name
}
}"#;
let mut vars = HashMap::new();
vars.insert("$a".to_string(), "Alice".to_string());
let resp = dgraph.new_readonly_txn().query_with_vars(&q, vars).expect("query");
let root: Root = serde_json::from_slice(&resp.json).expect("parsing");
println!("Root: {:#?}", root);
When running a schema query, the schema response is found in the Schema
field of dgraph::Response
.
let q = r#"schema(pred: [name]) {
type
index
reverse
tokenizer
list
count
upsert
lang
}"#;
let resp = txn.query(&q)?;
println!("{:#?}", resp.schema);
A transaction can be committed using the txn.commit()
method. If your transaction
consisted solely of calls to txn.query
or txn.query_with_vars
, and no calls to
txn.mutate
, then calling txn.commit
is not necessary.
An error will be returned if other transactions running concurrently modify the same data that was modified in this transaction. It is up to the user to retry transactions when they fail.
let txn = dgraph.new_txn();
// Perform some queries and mutations.
let res = txn.commit();
if res.is_err() {
// Retry or handle error
}
Tests require Dgraph running on localhost:19080
. For the convenience there
are a couple of docker-compose-*.yaml
files - depending on Dgraph you are
testing against - prepared in the root directory:
docker-compose -f docker-compose-*.yaml up -d
Since we are working with database, tests also need to be run in a single thread to prevent aborts. Eg.:
cargo test -- --test-threads=1
Contributions are welcome. Feel free to raise an issue, for feature requests, bug fixes and improvements.
If you have made changes to one of src/protos/api.proto
files, you need to
regenerate the source files generated by Protocol Buffer tools. To do that,
install the Protocol Buffer Compiler
and then run the following command:
cargo run --features="compile-protobufs" --bin protoc
These have to be done with every version we support:
- Run tests
- Try examples
Update the version and publish crate:
- Update tag in Cargo.toml
- Update tag in README.md
git tag v0.X.X
git push origin v0.X.X
- Write release log on GitHub
cargo publish