dqlx is a fully featured DGraph Schema and Query Builder for Go.

dqlx

dqlx is a fully featured DGraph Schema and Query Builder for Go. It aims to simplify the interaction with the awesome Dgraph database allowing you to fluently compose any queries and mutations of any complexity. It also comes with a rich Schema builder to easily develop and maintain your Dgraph schema.

CircleCI Coverage Status Go Report Card

Status

The project is getting close to its first official release

Why?

The DGraph query language is awesome! it is really powerful, and you can achieve a lot with it. However, as you start trying to add dynamicity (like any other declarative query language) you soon starts fiddling with a lot strings concatenations and can quickly get messy.

dqlx tries to simplify the interaction with DGraph by helping to construct Queries and mutations with a fluent API.

Features

  • Schema Builder (Types, Predicates, Indexes)
  • Filtering - Connecting Filters (AND / OR)
  • Nested Selection / Filters
  • Functions
  • Pagination
  • Aggregation
  • Sorting
  • GroupBy
  • Multiple Query Block
  • Query Variables
  • Values Variables
  • Facets
  • Mutations

Documentation

You can find the documentation here: https://fenos.github.io/dqlx


Installation

go get github.com/fenos/dqlx

Quick Overview

func main() {
    // Connect to Dgraph cluster
    db, err := dqlx.Connect("localhost:9080")

    if err != nil {
        log.Fatal()
    }

    ctx := context.Background()

    var animals []map[string]interface{}

    // Query for animals
    _, err = db.
        QueryType("Animal").
        Select(`
            uid
            name
            species
            age
        `).
        Filter(
            dqlx.Eq{"species": "Cat"},
            dqlx.Lt{"age": 5},
        ).
        UnmarshalInto(&animals).
        Execute(ctx)

    if err != nil { panic(err) }

    println(fmt.Sprintf("The animals are: %v", animals))
}

Licence

MIT

Comments
  • Looking for maintainers

    Looking for maintainers

    Unfortunately due to lack of time and passion for Dgraph i'm unable to maintain the project as i'd like to. If any of you would like to be a maintainer of dqlx please comment below

  • Append the individual elements of select args, not the slice

    Append the individual elements of select args, not the slice

    When appending the computed arguments from a select, the slice of arguments was being appended, not the individual elements.

    Note that this also resolves the TestExampleTestSuite/TestFundamentals/Applying_filters that has been failing.

  • ERROR: result must be a pointer

    ERROR: result must be a pointer

    Can someone help me understand this?

    The following code generates the error result must be a pointer.

    
    var data []map[string]interface{}
    
    client.Query(dqlx.HasFn("name")).
    		Filter(
                       dqlx.UID("0x12345"),
    		).Select(`
    		    name
    		`).UnmarshalInto(data).Execute(ctx)
    

    @fenos

  • Cascade directive

    Cascade directive

    Hi, I've not found any information about the @cascade directive in the library's documentation (I assume it's just not supported yet).

    I was thinking about the "ugly" workaround:

    • Add @filter(@cascade) at the root level - run ToDQL func - replace string @filter(@cascade) with just @cascade - turn back to QueryBuilder (generally I wanted to update only query string, but I didn't find any solution for turning query, args, and error back into QueryBuilder)

    Can you give me a solution on how to add @cascade for my query? It's crucial for one of my functions.

    Also, it would be nice to be able to modify the query string more directly with function, which would allow adding custom parts to the query at the root level (next to filters etc.). For example, when Dgraph would release another part of the query, needed to be placed at the root level then it would be easy to implement that part without a specific function from the DQLX package (considering that there isn't a function meant to add that part)

  • fix: broken query variables on edges and invalid serialization when used for variables

    fix: broken query variables on edges and invalid serialization when used for variables

    Example taken from the official docs:

    package main
    
    import (
    	"fmt"
    
    	"github.com/fenos/dqlx"
    )
    
    func main() {
    	variable := dqlx.Variable(dqlx.EqFn("name", "test")).
    		As("A").
    		EdgeAs("B", "film").
    		EdgeAs("C", "film->performance", dqlx.Select(`
    			D as genre
    		`))
    	s, _, _ := variable.ToDQL()
    	fmt.Println(s)
    }
    

    Current result:

    query Rootquery($0:string) { C asvar(func: eq(<name>,$0)) { <film> { <performance> { D AS <genre> } } } }
    

    Fixed with this PR:

    query Rootquery($0:string) { A as var(func: eq(<name>,$0)) { B as  { C as  { D as <genre> } } } }
    
  • Unexpected Response.Unmarshal behaviour

    Unexpected Response.Unmarshal behaviour

    I've encountered an issue where I have an object that satisfies the json.Unmarshaler interface which is not being respected by Response.Unmarshal.

    It would likely be a good idea to remove the dependency on a map[string]interface{} and then mapstructure here and instead make use of json.RawMessage. This also solves issues with decoding time.Time values as Time already implements the json.Unmarshaler interface for RFC 3339 formatted strings.

  • support cascade directive

    support cascade directive

    Support cascade directive

    	query, variables, err := dql.
    		QueryEdge("bladerunner", dql.EqFn("item", "value")).
    		Fields(`
    			uid
    			name
    			initial_release_date
    			netflix_id
    		`).
    		Cascade().
    		Edge("films", dql.Fields(`
    			id
    			date
    		`), dql.Cascade("date", "id")).
    		ToDQL()
    

    Closes #3

  • Incorrect Example shown for Upserts

    Incorrect Example shown for Upserts

    data := []map[string]interface{}{
        {
            "uid": "uid(v)",
            "email": "[email protected]",
            "name": "first name"
        },
    }
    
    userByEmailQuery := dqlx.Query(dqlx.EqFn("email", "[email protected]")).
        .Select(`
            v as uid
            name
        `)
    
    resp, err := db.Mutation().
        Query(userByEmailQuery).
        Set(data).
        Execute(ctx)
    

    The above example does not work, as userByEmailQuery is of type dqlx.QueryBuilder and Query() needs dqlx.DQLizer

  • Mutation Response returns wrong data

    Mutation Response returns wrong data

    Currently, the response of any mutation returns a map of uids and an empty JSON. This is 100% wrong for the following reasons:

    • The uids will be returned for some reason when dgraph won't generate the object because of an error that is never returned.
    • The Dgraph database returns also the objects that are being generated (based on the schema), but those objects are not included in the response.
  • Issue with edgeAS

    Issue with edgeAS

    Hey everyone,

    First thank you for this amazing repo. My issue is about EdgeAS;

    	var output []map[string]interface{}
    	_, err := r.Conn.QueryType("User").
    		Filter(
    			dqlx.UID(uid),
    		).
    		EdgeAs("total", "friendship", dqlx.Facets(dqlx.And{
    			dqlx.GtFn("requested_at", util.BeginningOfDay().Unix()),
    			dqlx.LtFn("requested_at", util.EndOfDay().Unix()),
    		}), dqlx.Select("uid")).
    		EdgeAs("to", "friendship", dqlx.UID(otherUSER), dqlx.Facets(dqlx.And{
    			dqlx.GtFn("requested_at", util.BeginningOfWeek().Unix()),
    			dqlx.LtFn("requested_at", util.EndOfWeek().Unix()),
    		}), dqlx.Select("uid")).
    		UnmarshalInto(&output).
    		Execute(ctx)
    
    	log.Print(output)
    

    when I run it, I'm getting an error as

    "rpc error: code = Unknown desc = line 1 column 35: Expected Left round brackets. Got: lex.Item [9] \"func\" at 1:35",
    

    And the generated DQL is

    query Rootquery($0:string, $1:int, $2:int, $3:int, $4:int, $5:string) { to as(func: type(<User>)) @filter(uid($0)) { <hey> @facets((gt(<requested_at>,$1) AND lt(<requested_at>,$2))) { <uid> } <hey> @facets((gt(<requested_at>,$3) AND lt(<requested_at>,$4))) @filter(uid($5)) { <uid> } } }
    map[$0:0x57 $1:1662760800 $2:1662847199 $3:1662242400 $4:1662847199 $5:0x56]
    

    anyone can help me ?

  • Upsert is not working

    Upsert is not working

    Hi, thank you for your library,

    I was trying to make an upsert block https://dgraph.io/docs/mutations/upsert-block/#example-of-uid-function and I see in your documentation: https://fenos.github.io/dqlx/docs/mutations/set#logical-upsert the way to do it. But there is a type error.

    In your example you add a Query in the mutation like this:

    resp, err := db.Mutation().
        Query(userByEmailQuery).
        Set(data).
        Execute(ctx)
    

    but the query method has a dependency on an interface DQLizer which has the method signature: ToDQL() (query string, args []interface{}, err error)

    Using the query builder in your example:

    userByEmailQuery := dqlx.Query(dqlx.EqFn("email", "[email protected]")).
        .Select(`
            v as uid
            name
        `)
    

    given us an instance of QueryBuilder which has the method ToDQL() (query string, args map[string]string, err error) that is not match to the DQLizer method:

An idiomatic Go query builder for ElasticSearch

esquery A non-obtrusive, idiomatic and easy-to-use query and aggregation builder for the official Go client for ElasticSearch. Table of Contents Descr

Jan 5, 2023
A full-featured license tool to check and fix license headers and resolve dependencies' licenses.
A full-featured license tool to check and fix license headers and resolve dependencies' licenses.

SkyWalking Eyes A full-featured license tool to check and fix license headers and resolve dependencies' licenses. Usage You can use License-Eye in Git

Dec 26, 2022
A Runtime Struct Builder for Go

A Runtime Struct Builder for Go

Jul 8, 2022
A fully Go userland with Linux bootloaders! u-root can create a one-binary root file system (initramfs) containing a busybox-like set of tools written in Go.

u-root Description u-root embodies four different projects. Go versions of many standard Linux tools, such as ls, cp, or shutdown. See cmds/core for m

Dec 29, 2022
Steampipe plugin to query your Scalingo apps, addons and more

Scalingo plugin for Steampipe Use SQL to query infrastructure including applications and addons from Scalingo. Get started → Documentation: Table defi

Nov 4, 2022
hdq - HTML DOM Query Language for Go+

hdq - HTML DOM Query Language for Go+ Summary about hdq hdq is a Go+ package for processing HTML documents. Tutorials Collect links of a html page How

Dec 13, 2022
Quickly query a Terraform provider's data type.

Terraform Query Quickly query a Terraform provider's data type. Such as a GitHub repository: ➜ ~ tfq github_repository full_name hashicorp/terraform |

Oct 12, 2021
A Go (golang) library for parsing and verifying versions and version constraints.

go-version is a library for parsing versions and version constraints, and verifying versions against a set of constraints. go-version can sort a collection of versions properly, handles prerelease/beta versions, can increment versions, etc.

Jan 9, 2023
🤖🤝A tool to test and analyze storage and retrieval deal capability on the Filecoin network.

Dealbot A tool to test and analyze storage and retrieval deal capability on the Filecoin network. Getting Started Clone the repo and build: git clone

Sep 10, 2022
Continuous profiling for analysis of CPU, memory usage over time, and down to the line number. Saving infrastructure cost, improving performance, and increasing reliability.
Continuous profiling for analysis of CPU, memory usage over time, and down to the line number. Saving infrastructure cost, improving performance, and increasing reliability.

Continuous profiling for analysis of CPU, memory usage over time, and down to the line number. Saving infrastructure cost, improving performance, and increasing reliability.

Jan 2, 2023
CUE utilities and helpers for working with tree based objects in any combination of CUE, Yaml, and JSON.

Cuetils CUE utilities and helpers for working with tree based objects in any combination of CUE, Yaml, and JSON. Using As a command line binary The cu

Dec 24, 2022
Hex dump and read values of files quickly and swiftly with Go-Hex a program designed to dump any file in a hexadecimal format

Go-Hex Hex dump and read values of files quickly and swiftly with Go-Hex a program designed to dump any file in a hexadecimal format Dump Hashes ----

Oct 10, 2021
A process that receives probe information and stores it in a database for reporting and analysis

probed is a process that receives probe information and stores it in a database for reporting and analysis.

Nov 2, 2022
Golang: unify nil and empty slices and maps

unifynil, unify nil and empty slices and maps in Golang Empty slices and maps can be nil or not nil in Go. It may become a nightmare in tests and JSON

Jan 16, 2022
🍕 Enjoy a slice! A utility library for dealing with slices and maps that focuses on type safety and performance.

?? github.com/elliotchance/pie Enjoy a slice! pie is a library of utility functions for common operations on slices and maps. Quick Start FAQ What are

Dec 30, 2022
Code Generation for Functional Programming, Concurrency and Generics in Golang

goderive goderive derives mundane golang functions that you do not want to maintain and keeps them up to date. It does this by parsing your go code fo

Dec 25, 2022
Implementation of do255e and do255s in Go

Go Implementation of do255e and do255s This is a plain Go implementation of do255e and do255s. It is considered secure; all relevant functions should

Aug 15, 2022
MemBi is all the members of bugbounty and infosec project.
MemBi is all the members of bugbounty and infosec project.

Member of Bugbounty and Infosec ?? What is MemBi? MemBi is all the members of bugbounty and infosec project. If you don't know who to follow, see! ??

Sep 23, 2022
sigurls is a reconnaissance tool, it fetches URLs from AlienVault's OTX, Common Crawl, URLScan, Github and the Wayback Machine.

sigurls is a reconnaissance tool, it fetches URLs from AlienVault's OTX, Common Crawl, URLScan, Github and the Wayback Machine. DiSCLAIMER: fe

May 22, 2021