dgraph 1.1.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 57

Build Status

dgraph #

Dgraph Dart client which communicates with the server using gRPC.

Before using this client, we highly recommend that you go through tour.dgraph.io and docs.dgraph.io to understand how to run and work with Dgraph.

Table of contents #

Supported Versions #

Depending on the version of Dgraph that you are connecting to, you will have to use a different version of this client.

|:--------------:|:---------------------:| | dgraph 1.0.X | dgraph client 0.5.0 | | dgraph 1.1.X | dgraph client 1.1.X |

Note: One of the most important API breakages from dgraph client v0.5.0 to v1.1.X is in the function Txn.Mutate. This function returns an api.Assigned value until v0.5.0 but an api.Response in v1.1.X.

Using a client #

Create a client #

dgraphClient object can be initialised by passing it a list of api.DgraphApi clients as variadic arguments. Connecting to multiple Dgraph servers in the same cluster allows for better distribution of workload.

The following code snippet shows just one connection.

DgraphRpcClient rpcClient =
    DgraphRpcClient("localhost", 9080, const ChannelCredentials.insecure());
Dgraph dgraphClient = dgraph.NewDgraphClient(api.DgraphApi(rpcClient));

Altering the database #

To set the schema, create an instance of api.Operation and use the Alter endpoint.

api.Operation operation = api.Operation();
operation.schema = """
name: string @index(exact) .
""";
await dgraphClient.Alter(clientContext, operation);

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.

Creating a transaction #

To create a transaction, call dgraphClient.NewTxn(), which returns a Txn object. This operation incurs no network overhead.

It is a good practice to call txn.Discard() on a finally block after it is initialized. Calling txn.Discard() after txn.Commit() is a no-op and you can call txn.Discard() multiple times with no additional side-effects.

Txn txn;
ClientContext clientContext = ClientContext();
try {
  txn = dgraphClient.NewTxn();
  // Perform some queries and mutations.
  // Commit the transaction.
} finally {
  txn.Discard(clientContext);
}

Read-only transactions can be created by calling dgraphClient.NewReadOnlyTxn(). Read-only transactions are useful to increase read speed because they can circumvent the usual consensus protocol. Read-only transactions cannot contain mutations and trying to call txn.Commit() will result in an error. Calling txn.Discard() will be a no-op.

Running a mutation #

txn.Mutate(clientContext, mutation) runs a mutation. It takes in a ClientContext and a api.Mutation object. You can set the data using JSON or RDF N-Quad format.

To use JSON, use the fields setJson and deleteJson, which accept an encoded string representing the nodes to be added or removed respectively (either as a JSON map or a list). To use RDF, use the fields setNquads and delNquads, which accept a string representing the valid RDF triples (one per line) to added or removed respectively. This protobuf object also contains the set and del fields which accept a list of RDF triples that have already been parsed into our internal format. As such, these fields are mainly used internally and users should use the setNquads and delNquads instead if they are planning on using RDF.

We define a Map to represent a Person and convert an instance of it to use with Mutation object.

Map<String, dynamic> p = {
  "uid": "_:alice",
  "name": "Alice",
};
List<int> pb = utf8.encode(json.encode(p));
api.Mutation mutation = api.Mutation();
mutation.setJson = pb;
api.Request request = api.Request();
request.mutations.add(mutation);
api.Response response = await txn.Mutate(clientContext, request);
print("Response: ${response.uids}");
// {alice: 0x5}

Sometimes, you only want to commit a mutation, without querying anything further. In such cases, you can use mutation.commitNow = true to indicate that the mutation must be immediately committed.

Running a query #

You can run a query by calling txn.Query(clientContext, query). 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.QueryWithVars(clientContext, query, vars) with the variables map as third argument.

Let's run the following query with a variable $a:

String query = """
query all(\$a: string) {
  all(func: eq(name, \$a)) {
    name
  }
}
""";
api.Response response =
    await txn.QueryWithVars(clientContext, query, {"\$a": "Alice"});
print("Response: ${utf8.decode(response.json)}");
// {"all":[{"name":"Alice"}]}

You can also use txn.Do function to run a query.

request = api.Request();
request.query = query;
request.vars.addAll({"\$a": "Alice"});
response = await txn.Do(clientContext, request);
print("Response: ${utf8.decode(response.json)}");
// {"all":[{"name":"Alice"}]}

When running a schema query for predicate name, the schema response is found in the json field of api.Response as shown below:

String query = """
schema(pred: [name]) {
  type
  index
  reverse
  tokenizer
  list
  count
  upsert
  lang
}
""";
api.Response response = await txn.Query(clientContext, query);
print("Response: ${utf8.decode(response.json)}");
// {"schema":[{"predicate":"name","type":"string","index":true,"tokenizer":["exact"]}]}

Committing a transaction #

A transaction can be committed using the txn.Commit(clientContext) method. If your transaction consisted solely of calls to txn.Query or txn.QueryWithVars, 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.

Txn txn;
ClientContext clientContext = ClientContext();
try {
  txn = dgraphClient.NewTxn();
  // Perform some queries and mutations.
  txn.Commit(clientContext);
} catch (e) {
  // Retry or handle error
}

Development #

Running tests #

Make sure you have dgraph installed before you run the tests. This script will run the unit tests.

pub run test --concurrency=1

Updating protobuf #

To update protobuf execute the following command from the project root:

bash lib/protos/api/regenerate-proto.sh

1.1.1 #

  • Fixed Dgraph 1.0.x compatible client version on README

1.1.0 #

  • Dgraph 1.1.x support
  • Added tests

0.5.0 #

  • Changed Commit and Discard methods to async
  • Added dropAttr to example

0.4.0 #

  • Improved README
  • Ran darfmt on dart file

0.3.0 #

  • Fixed 'Name types using UpperCamelCase' suggestion on package analysis
  • Changed grpc package version to 0.6.6 to make dartdoc works

0.2.0 #

  • Improved README
  • Added dropAll call to example
  • Ran darfmt on dart files

0.1.0 #

  • Initial release

example/example.dart

import 'package:dgraph/api.dart';
import 'package:dgraph/dgraph.dart';
import 'package:dgraph/protos/api/api.pb.dart' as api;
import 'package:dgraph/txn.dart';
import 'package:grpc/grpc.dart';
import 'package:protobuf/protobuf.dart';
import 'dart:convert';

void main(List<String> arguments) async {
  // Create a client
  DgraphRpcClient rpcClient =
      DgraphRpcClient("localhost", 9080, const ChannelCredentials.insecure());
  Dgraph dgraphClient = dgraph.NewDgraphClient(api.DgraphApi(rpcClient));

  Txn txn;
  ClientContext clientContext = ClientContext();
  try {
    // Alter the database
    api.Operation operation = api.Operation();
    operation.schema = """
    name: string @index(exact) .
    """;
    await dgraphClient.Alter(clientContext, operation);

    txn = dgraphClient.NewTxn();
    String query = """
    schema(pred: [name]) {
      type
      index
      reverse
      tokenizer
      list
      count
      upsert
      lang
    }
    """;
    api.Response response = await txn.Query(clientContext, query);
    print("Response: ${utf8.decode(response.json)}");
    txn.Discard(clientContext);

    // Create a transaction
    txn = dgraphClient.NewTxn();

    // Run a mutation
    Map<String, dynamic> p = {
      "uid": "_:alice",
      "name": "Alice",
      "age": 18,
    };
    List<int> pb = utf8.encode(json.encode(p));
    api.Mutation mutation = api.Mutation();
    mutation.setJson = pb;
    api.Request request = api.Request();
    request.mutations.add(mutation);
    response = await txn.Mutate(clientContext, request);
    print("Response: ${response.uids}");

    // Run a query
    query = """
    query all(\$a: string) {
      all(func: eq(name, \$a)) {
        name
        age
      }
    }
    """;
    response = await txn.QueryWithVars(clientContext, query, {"\$a": "Alice"});
    print("Response: ${utf8.decode(response.json)}");

    // Commit a transaction
    await txn.Commit(clientContext);

    // Alter the database
    operation = api.Operation();
    operation.dropAttr = "age";
    await dgraphClient.Alter(clientContext, operation);

    // Create another transaction
    txn = dgraphClient.NewReadOnlyTxn();

    // Run the same query again
    response = await txn.QueryWithVars(clientContext, query, {"\$a": "Alice"});
    print("Response: ${utf8.decode(response.json)}");

    // Run the same query again, but now using txn.Do
    request = api.Request();
    request.query = query;
    request.vars.addAll({"\$a": "Alice"});
    response = await txn.Do(clientContext, request);
    print("Response: ${utf8.decode(response.json)}");

    // Finish transaction without commit
    await txn.Discard(clientContext);

    // Alter the database
    operation = api.Operation();
    operation.dropAll = true;
    await dgraphClient.Alter(clientContext, operation);
  } catch (e) {
    print("Error: $e");
  } finally {
    if (txn != null) {
      await txn.Discard(clientContext);
    }
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  dgraph: ^1.1.1

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:dgraph/dgraph.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
21
Health:
Code health derived from static analysis. [more]
95
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
57
Learn more about scoring.

We analyzed this package on Jul 9, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.14

Analysis suggestions

Package not compatible with runtime flutter-web on web

Because:

  • package:dgraph/dgraph.dart that imports:
  • package:dgraph/txn.dart that imports:
  • package:grpc/grpc.dart that imports:
  • package:grpc/src/shared/streams.dart that imports:
  • package:http2/transport.dart that imports:
  • package:http2/src/hpack/hpack.dart that imports:
  • package:http2/src/hpack/huffman_table.dart that imports:
  • package:http2/src/hpack/huffman.dart that imports:
  • dart:io

Package not compatible with runtime js

Because:

  • package:dgraph/dgraph.dart that imports:
  • package:dgraph/txn.dart that imports:
  • package:grpc/grpc.dart that imports:
  • package:grpc/src/shared/streams.dart that imports:
  • package:http2/transport.dart that imports:
  • package:http2/src/hpack/hpack.dart that imports:
  • package:http2/src/hpack/huffman_table.dart that imports:
  • package:http2/src/hpack/huffman.dart that imports:
  • dart:io

Health suggestions

Fix lib/dgraph.dart. (-2.96 points)

Analysis of lib/dgraph.dart reported 6 hints, including:

line 38 col 7: Future results in async function bodies must be awaited or marked unawaited using package:pedantic.

line 48 col 7: Use rethrow to rethrow a caught exception.

line 69 col 7: Future results in async function bodies must be awaited or marked unawaited using package:pedantic.

line 71 col 11: Use isEmpty instead of length

line 82 col 7: Use rethrow to rethrow a caught exception.

Fix lib/txn.dart. (-2.48 points)

Analysis of lib/txn.dart reported 5 hints:

line 129 col 9: Use isNotEmpty instead of length

line 152 col 11: Future results in async function bodies must be awaited or marked unawaited using package:pedantic.

line 154 col 11: Use rethrow to rethrow a caught exception.

line 165 col 11: Use isNotEmpty instead of length

line 167 col 9: Future results in async function bodies must be awaited or marked unawaited using package:pedantic.

Maintenance issues and suggestions

Support latest dependencies. (-10 points)

The version constraint in pubspec.yaml does not support the latest published versions for 1 dependency (grpc).

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
grpc 0.6.6 0.6.6 2.2.0
mutex ^1.0.3 1.1.0
protobuf >=1.0.1 <2.0.0 1.0.1
Transitive dependencies
async 2.4.2
charcode 1.1.3
collection 1.14.13 1.15.0-nnbd
convert 2.1.1
crypto 2.1.5
fixnum 0.10.11
googleapis_auth 0.2.12
http 0.12.1
http2 0.1.9 1.0.0
http_parser 3.1.4
meta 1.2.1
path 1.7.0
pedantic 1.9.1
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.2.0 1.3.0-nnbd
Dev dependencies
test ^1.5.1