Dgraph auto increment id with DQL

Use below DQL for set auto increment code for database

upsert {
  query {
    var(func: has(User.code), orderdesc: User.code, first:1) {
      lastId as User.code
    }
    me() {
      VD as sum(val(lastId))
      Increment as math(VD + 1)
    }
  }
  mutation {
    set {
      _:user <dgraph.type> "User" .
      _:user <User.code> val(Increment) .
      _:user <User.name> "John" .
    }
  }
}

Which is working fine but when there is no record on User (first time) shown error as while running ToJson: Only aggregated variables allowed within empty block.

Check out the @if directive. Very common use case that it solves.

Here @if condition allow on mutation.
Error because of Increment as math(VD + 1) line where can’t use if condition. also condition can’t use in set value.
On single mutation need to add 1 for code if Increment not found.

upsert {
  query {
    var(func: has(User.code), orderdesc: User.code, first:1) {
      lastId as User.code
      VD as math(lastId + 1)
    }
    me() {
      Increment as sum(val(VD))
    }
  }
  mutation {
    set {
      _:user <dgraph.type> "User" .
      _:user <User.name> "John" .
    }
  }
  mutation @if(gt(len(VD), 0)) {
    set { 
      _:user <User.code> val(Increment) . 
    }
  }
  mutation @if(eq(len(VD), 0)) {
    set {
      _:user <Repair.code> "1" .
    }
  }
}