{"id":25150610,"url":"https://github.com/hypermodeinc/dgo","last_synced_at":"2025-05-15T18:02:13.375Z","repository":{"id":41329940,"uuid":"124306268","full_name":"hypermodeinc/dgo","owner":"hypermodeinc","description":"Official Dgraph Go client","archived":false,"fork":false,"pushed_at":"2025-03-29T16:26:20.000Z","size":836,"stargazers_count":375,"open_issues_count":1,"forks_count":85,"subscribers_count":29,"default_branch":"main","last_synced_at":"2025-03-31T22:17:19.618Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hypermodeinc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-03-07T23:18:34.000Z","updated_at":"2025-03-29T16:26:23.000Z","dependencies_parsed_at":"2022-09-26T17:50:38.756Z","dependency_job_id":"56fb9e8b-af83-4d7c-ac24-301d23c92bde","html_url":"https://github.com/hypermodeinc/dgo","commit_stats":{"total_commits":165,"total_committers":41,"mean_commits":4.024390243902439,"dds":0.7333333333333334,"last_synced_commit":"6e59191b1335c04be8184cdbfc310c66a9ff07bf"},"previous_names":["hypermodeinc/dgo","dgraph-io/dgo"],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hypermodeinc%2Fdgo","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hypermodeinc%2Fdgo/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hypermodeinc%2Fdgo/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hypermodeinc%2Fdgo/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hypermodeinc","download_url":"https://codeload.github.com/hypermodeinc/dgo/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247744333,"owners_count":20988783,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-02-08T23:00:18.634Z","updated_at":"2025-05-15T18:02:13.368Z","avatar_url":"https://github.com/hypermodeinc.png","language":"Go","readme":"# dgo [![GoDoc](https://pkg.go.dev/badge/github.com/dgraph-io/dgo)](https://pkg.go.dev/github.com/dgraph-io/dgo/v250)\n\nOfficial Dgraph Go client which communicates with the server using [gRPC](https://grpc.io/).\n\nBefore using this client, we highly recommend that you go through [dgraph.io/tour] and\n[dgraph.io/docs] to understand how to run and work with Dgraph.\n\n[dgraph.io/docs]: https://dgraph.io/docs\n[dgraph.io/tour]: https://dgraph.io/tour\n\n**Use [Github Issues](https://github.com/hypermodeinc/dgo/issues) for reporting issues about this\nrepository.**\n\n## Table of contents\n\n- [Supported Versions](#supported-versions)\n- [v25 APIs](#v25-apis)\n  - [Connection Strings](#connection-strings)\n  - [Advanced Client Creation](#advanced-client-creation)\n  - [Connecting To Dgraph Cloud](#connecting-to-dgraph-cloud)\n  - [Dropping All Data](#dropping-all-data)\n  - [Set Schema](#set-schema)\n  - [Running a Mutation](#running-a-mutation)\n  - [Running a Query](#running-a-query)\n  - [Running a Query With Variables](#running-a-query-with-variables)\n  - [Running a Best Effort Query](#running-a-best-effort-query)\n  - [Running a ReadOnly Query](#running-a-readonly-query)\n  - [Running a Query with RDF Response](#running-a-query-with-rdf-response)\n  - [Running an Upsert](#running-an-upsert)\n  - [Running a Conditional Upsert](#running-a-conditional-upsert)\n  - [Creating a New Namespace](#creating-a-new-namespace)\n  - [Dropping a Namespace](#dropping-a-namespace)\n  - [Rename a Namespace](#rename-a-namespace)\n  - [List All Namespaces](#list-all-namespaces)\n- [v1 APIs](#v1-apis)\n  - [Creating a Client](#creating-a-client)\n  - [Login into a namespace](#login-into-a-namespace)\n  - [Altering the database](#altering-the-database)\n  - [Creating a transaction](#creating-a-transaction)\n  - [Running a mutation](#running-a-mutation-1)\n  - [Running a query](#running-a-query-1)\n  - [Query with RDF response](#query-with-rdf-response)\n  - [Running an Upsert: Query + Mutation](#running-an-upsert-query--mutation)\n  - [Running Conditional Upsert](#running-conditional-upsert)\n  - [Committing a transaction](#committing-a-transaction)\n  - [Setting Metadata Headers](#setting-metadata-headers)\n- [Development](#development)\n  - [Running tests](#running-tests)\n\n## Supported Versions\n\nDepending on the version of Dgraph that you are connecting to, you will have to use a different\nversion of this client and their corresponding import paths.\n\n| Dgraph version | dgo version | dgo import path                 |\n| -------------- | ----------- | ------------------------------- |\n| dgraph 23.X.Y  | dgo 230.X.Y | \"github.com/dgraph-io/dgo/v230\" |\n| dgraph 24.X.Y  | dgo 240.X.Y | \"github.com/dgraph-io/dgo/v240\" |\n| dgraph 25.X.Y  | dgo 240.X.Y | \"github.com/dgraph-io/dgo/v240\" |\n| dgraph 25.X.Y  | dgo 250.X.Y | \"github.com/dgraph-io/dgo/v250\" |\n\n## v25 APIs\n\nThese are _experimental_ APIs that we are still making changes to. If you have any feedback, please\nlet us know either on Discord or GitHub.\n\n### Connection Strings\n\nThe dgo package supports connecting to a Dgraph cluster using connection strings. Dgraph connections\nstrings take the form `dgraph://{username:password@}host:port?args`.\n\n`username` and `password` are optional. If username is provided, a password must also be present. If\nsupplied, these credentials are used to log into a Dgraph cluster through the ACL mechanism.\n\nValid connection string args:\n\n| Arg         | Value                           | Description                                                                                                                                                   |\n| ----------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| apikey      | \\\u003ckey\\\u003e                         | a Dgraph Cloud API Key                                                                                                                                        |\n| bearertoken | \\\u003ctoken\\\u003e                       | an access token                                                                                                                                               |\n| sslmode     | disable \\| require \\| verify-ca | TLS option, the default is `disable`. If `verify-ca` is set, the TLS certificate configured in the Dgraph cluster must be from a valid certificate authority. |\n\nSome example connection strings:\n\n| Value                                                                                                        | Explanation                                                                         |\n| ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| dgraph://localhost:9080                                                                                      | Connect to localhost, no ACL, no TLS                                                |\n| dgraph://sally:supersecret@dg.example.com:443?sslmode=verify-ca                                              | Connect to remote server, use ACL and require TLS and a valid certificate from a CA |\n| dgraph://foo-bar.grpc.us-west-2.aws.cloud.dgraph.io:443?sslmode=verify-ca\u0026apikey=\\\u003cyour-api-connection-key\\\u003e | Connect to a Dgraph Cloud cluster                                                   |\n| dgraph://foo-bar.grpc.hypermode.com?sslmode=verify-ca\u0026bearertoken=\\\u003csome access token\\\u003e                      | Connect to a Dgraph cluster protected by a secure gateway                           |\n\nUsing the `Open` function with a connection string:\n\n```go\n// open a connection to an ACL-enabled, non-TLS cluster and login as groot\nclient, err := dgo.Open(\"dgraph://groot:password@localhost:8090\")\n// Check error\ndefer client.Close()\n// Use the clients\n```\n\n### Advanced Client Creation\n\nFor more control, you can create a client using the `NewClient` function.\n\n```go\nclient, err := dgo.NewClient(\"localhost:9181\",\n  // add Dgraph ACL credentials\n  dgo.WithACLCreds(\"groot\", \"password\"),\n  // add insecure transport credentials\n  dgo.WithGrpcOption(grpc.WithTransportCredentials(insecure.NewCredentials())),\n)\n// Check error\ndefer client.Close()\n// Use the client\n```\n\nYou can connect to multiple alphas using `NewRoundRobinClient`.\n\n```go\nclient, err := dgo.NewRoundRobinClient([]string{\"localhost:9181\", \"localhost:9182\", \"localhost:9183\"},\n  // add Dgraph ACL credentials\n  dgo.WithACLCreds(\"groot\", \"password\"),\n  // add insecure transport credentials\n  dgo.WithGrpcOption(grpc.WithTransportCredentials(insecure.NewCredentials())),\n)\n// Check error\ndefer client.Close()\n// Use the client\n```\n\n### Connecting To Dgraph Cloud\n\nYou can use either `Open` or `NewClient` to connect to Dgraph Cloud. Note `DialCloud` is marked\ndeprecated and will be removed in later versions.\n\nUsing `Open` with a connection string:\n\n```go\nclient, err := dgo.Open(\"dgraph://foo-bar.grpc.cloud.dgraph.io:443?sslmode=verify-ca\u0026apikey=AValidKeYFromDgrAPHCloud=\")\n// Check error\ndefer client.Close()\n```\n\nUsing `NewClient`:\n\n```go\nclient, err := dgo.NewClient(\"foo-bar.grpc.cloud.dgraph.io:443\",\n  dgo.WithDgraphAPIKey(\"AValidKeYFromDgrAPHCloud=\"),\n  dgo.WithSystemCertPool(),\n)\n// Check error\ndefer client.Close()\n```\n\n### Dropping All Data\n\nIn order to drop all data in the Dgraph Cluster and start fresh, use the `DropAllNamespaces`\nfunction.\n\n```go\nerr := client.DropAllNamespaces(context.TODO())\n// Handle error\n```\n\n### Set Schema\n\nTo set the schema, use the `SetSchema` function.\n\n```go\nsch := `\n  name: string @index(exact) .\n  email: string @index(exact) @unique .\n  age: int .\n`\nerr := client.SetSchema(context.TODO(), dgo.RootNamespace, sch)\n// Handle error\n```\n\n### Running a Mutation\n\nTo run a mutation, use the `RunDQL` function.\n\n```go\nmutationDQL := `{\n  set {\n    _:alice \u003cname\u003e \"Alice\" .\n    _:alice \u003cemail\u003e \"alice@example.com\" .\n    _:alice \u003cage\u003e \"29\" .\n  }\n}`\nresp, err := client.RunDQL(context.TODO(), dgo.RootNamespace, mutationDQL)\n// Handle error\n// Print map of blank UIDs\nfmt.Printf(\"%+v\\n\", resp.BlankUids)\n```\n\n### Running a Query\n\nTo run a query, use the same `RunDQL` function.\n\n```go\nqueryDQL := `{\n  alice(func: eq(name, \"Alice\")) {\n    name\n    email\n    age\n  }\n}`\nresp, err := client.RunDQL(context.TODO(), dgo.RootNamespace, queryDQL)\n// Handle error\nfmt.Printf(\"%s\\n\", resp.QueryResult)\n```\n\n### Running a Query With Variables\n\nTo run a query with variables, using `RunDQLWithVars`.\n\n```go\nqueryDQL = `query Alice($name: string) {\n  alice(func: eq(name, $name)) {\n    name\n    email\n    age\n  }\n}`\nvars := map[string]string{\"$name\": \"Alice\"}\nresp, err := client.RunDQLWithVars(context.TODO(), dgo.RootNamespace, queryDQL, vars)\n// Handle error\nfmt.Printf(\"%s\\n\", resp.QueryResult)\n```\n\n### Running a Best Effort Query\n\nTo run a `BestEffort` query, use the same `RunDQL` function with `TxnOption`.\n\n```go\nqueryDQL := `{\n  alice(func: eq(name, \"Alice\")) {\n    name\n    email\n    age\n  }\n}`\nresp, err := client.RunDQL(context.TODO(), dgo.RootNamespace, queryDQL, dgo.WithBestEffort())\n// Handle error\nfmt.Printf(\"%s\\n\", resp.QueryResult)\n```\n\n### Running a ReadOnly Query\n\nTo run a `ReadOnly` query, use the same `RunDQL` function with `TxnOption`.\n\n```go\nqueryDQL := `{\n  alice(func: eq(name, \"Alice\")) {\n    name\n    email\n    age\n  }\n}`\nresp, err := client.RunDQL(context.TODO(), dgo.RootNamespace, queryDQL, dgo.WithReadOnly())\n// Handle error\nfmt.Printf(\"%s\\n\", resp.QueryResult)\n```\n\n### Running a Query with RDF Response\n\nTo get the query response in RDF format instead of JSON format, use the following `TxnOption`.\n\n```go\nqueryDQL := `{\n  alice(func: eq(name, \"Alice\")) {\n    name\n    email\n    age\n  }\n}`\nresp, err = client.RunDQL(context.TODO(), dgo.RootNamespace, queryDQL, dgo.WithResponseFormat(api_v25.RespFormat_RDF))\n// Handle error\nfmt.Printf(\"%s\\n\", resp.QueryResult)\n```\n\n### Running an Upsert\n\nThe `RunDQL` function also allows you to run upserts as well.\n\n```go\nupsertQuery := `upsert {\n  query {\n    user as var(func: eq(email, \"alice@example.com\"))\n  }\n  mutation {\n    set {\n      uid(user) \u003cage\u003e \"30\" .\n      uid(user) \u003cname\u003e \"Alice Sayum\" .\n    }\n  }\n}`\nresp, err := client.RunDQL(context.TODO(), dgo.RootNamespace, upsertQuery)\n// Handle error\nfmt.Printf(\"%s\\n\", resp.QueryResult)\nfmt.Printf(\"%+v\\n\", resp.BlankUids)\n```\n\n### Running a Conditional Upsert\n\n```go\nupsertQuery := `upsert {\n  query {\n    user as var(func: eq(email, \"alice@example.com\"))\n  }\n  mutation @if(eq(len(user), 1)) {\n    set {\n      uid(user) \u003cage\u003e \"30\" .\n      uid(user) \u003cname\u003e \"Alice Sayum\" .\n    }\n  }\n}`\nresp, err := client.RunDQL(context.TODO(), dgo.RootNamespace, upsertQuery)\n// Handle error\nfmt.Printf(\"%s\\n\", resp.QueryResult)\n```\n\n### Creating a New Namespace\n\nDgraph v25 supports namespaces that have names. You can create one using the dgo client.\n\n```go\nerr := client.CreateNamespace(context.TODO(), \"finance-graph\")\n// Handle error\n```\n\nYou can now pass this name to `SetSchema`, `RunDQL` or similar functions.\n\n### Dropping a Namespace\n\nTo drop a namespace:\n\n```go\nerr := client.DropNamespace(context.TODO(), \"finance-graph\")\n// Handle error\n```\n\n### Rename a Namespace\n\nA namespace can be renamed as follows.\n\n```go\nerr := client.RenameNamespace(context.TODO(), \"finance-graph\", \"new-finance-graph\")\n// Handle error\n```\n\n### List All Namespaces\n\n```go\nnamespaces, err := client.ListNamespaces(context.TODO())\n// Handle error\nfmt.Printf(\"%+v\\n\", namespaces)\n```\n\n## v1 APIs\n\n### Creating a Client\n\n`dgraphClient` object can be initialized by passing it a list of `api.DgraphClient` clients as\nvariadic arguments. Connecting to multiple Dgraph servers in the same cluster allows for better\ndistribution of workload.\n\nThe following code snippet shows just one connection.\n\n```go\nconn, err := grpc.Dial(\"localhost:9080\", grpc.WithInsecure())\n// Check error\ndefer conn.Close()\ndgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))\n```\n\n### Login into a namespace\n\nIf your server has Access Control Lists enabled (Dgraph v1.1 or above), the client must be logged in\nfor accessing data. If you do not use the `WithACLCreds` option with `NewClient` or a connection\nstring with username:password, use the `Login` endpoint.\n\nCalling login will obtain and remember the access and refresh JWT tokens. All subsequent operations\nvia the logged in client will send along the stored access token.\n\n```go\nerr := dgraphClient.Login(ctx, \"user\", \"passwd\")\n// Check error\n```\n\nIf your server additionally has namespaces (Dgraph v21.03 or above), use the `LoginIntoNamespace`\nAPI.\n\n```go\nerr := dgraphClient.LoginIntoNamespace(ctx, \"user\", \"passwd\", 0x10)\n// Check error\n```\n\n### Altering the database\n\nTo set the schema, create an instance of `api.Operation` and use the `Alter` endpoint.\n\n```go\nop := \u0026api.Operation{\n  Schema: `name: string @index(exact) .`,\n}\nerr := dgraphClient.Alter(ctx, op)\n// Check error\n```\n\n`Operation` contains other fields as well, including `DropAttr` and `DropAll`. `DropAll` is useful\nif you wish to discard all the data, and start from a clean slate, without bringing the instance\ndown. `DropAttr` is used to drop all the data related to a predicate.\n\nStarting Dgraph version 20.03.0, indexes can be computed in the background. You can set\n`RunInBackground` field of the `api.Operation` to `true` before passing it to the `Alter` function.\nYou can find more details\n[here](https://docs.dgraph.io/master/query-language/#indexes-in-background).\n\n```go\nop := \u0026api.Operation{\n  Schema:          `name: string @index(exact) .`,\n  RunInBackground: true\n}\nerr := dgraphClient.Alter(ctx, op)\n```\n\n### Creating a transaction\n\nTo create a transaction, call `dgraphClient.NewTxn()`, which returns a `*dgo.Txn` object. This\noperation incurs no network overhead.\n\nIt is a good practice to call `txn.Discard(ctx)` using a `defer` statement after it is initialized.\nCalling `txn.Discard(ctx)` after `txn.Commit(ctx)` is a no-op. Furthermore, `txn.Discard(ctx)` can\nbe called multiple times with no additional side-effects.\n\n```go\ntxn := dgraphClient.NewTxn()\ndefer txn.Discard(ctx)\n```\n\nRead-only transactions can be created by calling `c.NewReadOnlyTxn()`. Read-only transactions are\nuseful to increase read speed because they can circumvent the usual consensus protocol. Read-only\ntransactions cannot contain mutations and trying to call `txn.Commit()` will result in an error.\nCalling `txn.Discard()` will be a no-op.\n\n### Running a mutation\n\n`txn.Mutate(ctx, mu)` runs a mutation. It takes in a `context.Context` and a `*api.Mutation` object.\nYou can set the data using JSON or RDF N-Quad format.\n\nTo use JSON, use the fields `SetJson` and `DeleteJson`, which accept a string representing the nodes\nto be added or removed respectively (either as a JSON map or a list). To use RDF, use the fields\n`SetNquads` and `DelNquads`, which accept a string representing the valid RDF triples (one per line)\nto added or removed respectively. This protobuf object also contains the `Set` and `Del` fields\nwhich accept a list of RDF triples that have already been parsed into our internal format. As such,\nthese fields are mainly used internally and users should use the `SetNquads` and `DelNquads` instead\nif they are planning on using RDF.\n\nWe define a Person struct to represent a Person and marshal an instance of it to use with `Mutation`\nobject.\n\n```go\ntype Person struct {\n  Uid   string   `json:\"uid,omitempty\"`\n  Name  string   `json:\"name,omitempty\"`\n  DType []string `json:\"dgraph.type,omitempty\"`\n}\n\np := Person{\n  Uid:   \"_:alice\",\n  Name:  \"Alice\",\n  DType: []string{\"Person\"},\n}\n\npb, err := json.Marshal(p)\n// Check error\n\nmu := \u0026api.Mutation{\n  SetJson: pb,\n}\nres, err := txn.Mutate(ctx, mu)\n// Check error\n```\n\nFor a more complete example, see\n[Example](https://pkg.go.dev/github.com/dgraph-io/dgo#example-package-SetObject).\n\nSometimes, you only want to commit a mutation, without querying anything further. In such cases, you\ncan use `mu.CommitNow = true` to indicate that the mutation must be immediately committed.\n\nMutation can be run using `txn.Do` as well.\n\n```go\nmu := \u0026api.Mutation{\n  SetJson: pb,\n}\nreq := \u0026api.Request{CommitNow:true, Mutations: []*api.Mutation{mu}}\nres, err := txn.Do(ctx, req)\n// Check error\n```\n\n### Running a query\n\nYou can run a query by calling `txn.Query(ctx, q)`. You will need to pass in a DQL query string. If\nyou want to pass an additional map of any variables that you might want to set in the query, call\n`txn.QueryWithVars(ctx, q, vars)` with the variables map as third argument.\n\nLet's run the following query with a variable $a:\n\n```go\nq := `query all($a: string) {\n    all(func: eq(name, $a)) {\n      name\n    }\n  }`\n\nres, err := txn.QueryWithVars(ctx, q, map[string]string{\"$a\": \"Alice\"})\nfmt.Printf(\"%s\\n\", res.Json)\n```\n\nYou can also use `txn.Do` function to run a query.\n\n```go\nreq := \u0026api.Request{\n  Query: q,\n  Vars: map[string]string{\"$a\": \"Alice\"},\n}\nres, err := txn.Do(ctx, req)\n// Check error\nfmt.Printf(\"%s\\n\", res.Json)\n```\n\nWhen running a schema query for predicate `name`, the schema response is found in the `Json` field\nof `api.Response` as shown below:\n\n```go\nq := `schema(pred: [name]) {\n  type\n  index\n  reverse\n  tokenizer\n  list\n  count\n  upsert\n  lang\n}`\n\nres, err := txn.Query(ctx, q)\n// Check error\nfmt.Printf(\"%s\\n\", res.Json)\n```\n\n### Query with RDF response\n\nYou can get query result as a RDF response by calling `txn.QueryRDF`. The response would contain a\n`Rdf` field, which has the RDF encoded result.\n\n**Note:** If you are querying only for `uid` values, use a JSON format response.\n\n```go\n// Query the balance for Alice and Bob.\nconst q = `\n{\n  all(func: anyofterms(name, \"Alice Bob\")) {\n    name\n    balance\n  }\n}\n`\nres, err := txn.QueryRDF(context.Background(), q)\n// check error\n\n// \u003c0x17\u003e \u003cname\u003e \"Alice\" .\n// \u003c0x17\u003e \u003cbalance\u003e 100 .\nfmt.Println(res.Rdf)\n```\n\n`txn.QueryRDFWithVars` is also available when you need to pass values for variables used in the\nquery.\n\n### Running an Upsert: Query + Mutation\n\nThe `txn.Do` function allows you to run upserts consisting of one query and one mutation. Variables\ncan be defined in the query and used in the mutation. You could also use `txn.Do` to perform a query\nfollowed by a mutation.\n\nTo know more about upsert, we highly recommend going through the docs at\n[Upsert Block](https://dgraph.io/docs/dql/dql-syntax/dql-mutation/#upsert-block).\n\n```go\nquery = `\n  query {\n      user as var(func: eq(email, \"wrong_email@dgraph.io\"))\n  }`\nmu := \u0026api.Mutation{\n  SetNquads: []byte(`uid(user) \u003cemail\u003e \"correct_email@dgraph.io\" .`),\n}\nreq := \u0026api.Request{\n  Query: query,\n  Mutations: []*api.Mutation{mu},\n  CommitNow:true,\n}\n\n// Update email only if matching uid found.\n_, err := dg.NewTxn().Do(ctx, req)\n// Check error\n```\n\n### Running Conditional Upsert\n\nThe upsert block also allows specifying a conditional mutation block using an `@if` directive. The\nmutation is executed only when the specified condition is true. If the condition is false, the\nmutation is silently ignored.\n\nSee more about Conditional Upsert\n[Here](https://dgraph.io/docs/dql/dql-syntax/dql-mutation/#conditional-upsert).\n\n```go\nquery = `\n  query {\n      user as var(func: eq(email, \"wrong_email@dgraph.io\"))\n  }`\nmu := \u0026api.Mutation{\n  Cond: `@if(eq(len(user), 1))`, // Only mutate if \"wrong_email@dgraph.io\" belongs to single user.\n  SetNquads: []byte(`uid(user) \u003cemail\u003e \"correct_email@dgraph.io\" .`),\n}\nreq := \u0026api.Request{\n  Query: query,\n  Mutations: []*api.Mutation{mu},\n  CommitNow:true,\n}\n\n// Update email only if exactly one matching uid is found.\n_, err := dg.NewTxn().Do(ctx, req)\n// Check error\n```\n\n### Committing a transaction\n\nA transaction can be committed using the `txn.Commit(ctx)` method. If your transaction consisted\nsolely of calls to `txn.Query` or `txn.QueryWithVars`, and no calls to `txn.Mutate`, then calling\n`txn.Commit` is not necessary.\n\nAn error will be returned if other transactions running concurrently modify the same data that was\nmodified in this transaction. It is up to the user to retry transactions when they fail.\n\n```go\ntxn := dgraphClient.NewTxn()\n// Perform some queries and mutations.\n\nerr := txn.Commit(ctx)\nif err == y.ErrAborted {\n  // Retry or handle error\n}\n```\n\n### Setting Metadata Headers\n\nMetadata headers such as authentication tokens can be set through the context of gRPC methods. Below\nis an example of how to set a header named \"auth-token\".\n\n```go\n// The following piece of code shows how one can set metadata with\n// auth-token, to allow Alter operation, if the server requires it.\nmd := metadata.New(nil)\nmd.Append(\"auth-token\", \"the-auth-token-value\")\nctx := metadata.NewOutgoingContext(context.Background(), md)\ndg.Alter(ctx, \u0026op)\n```\n\n## Development\n\n### Running tests\n\nMake sure you have `dgraph` installed in your GOPATH before you run the tests. The dgo test suite\nrequires that a Dgraph cluster with ACL enabled be running locally. To start such a cluster, you may\nuse the docker compose file located in the testing directory `t`.\n\n```sh\ndocker compose -f t/docker-compose.yml up -d\n# wait for cluster to be healthy\ngo test -v ./...\ndocker compose -f t/docker-compose.yml down\n```\n","funding_links":[],"categories":["Go"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhypermodeinc%2Fdgo","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhypermodeinc%2Fdgo","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhypermodeinc%2Fdgo/lists"}