Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(GraphQL): Custom logic now supports DQL queries #6115

Merged
merged 4 commits into from
Jul 30, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions graphql/e2e/custom_logic/custom_logic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import (
)

const (
alphaGrpc = "localhost:9180"
alphaURL = "http://localhost:8180/graphql"
alphaAdminURL = "http://localhost:8180/admin"
subscriptionEndpoint = "ws://localhost:8180/graphql"
Expand Down Expand Up @@ -2414,3 +2415,154 @@ func TestRestCustomLogicInDeepNestedField(t *testing.T) {
]
}`, string(result.Data))
}

func TestCustomDQL(t *testing.T) {
dg, err := testutil.DgraphClient(alphaGrpc)
require.NoError(t, err)
testutil.DropAll(t, dg)

schema := `
type Tweets {
id: ID!
text: String! @search(by: [fulltext])
user: User
timestamp: DateTime! @search
}
type User {
screen_name: String! @id
followers: Int @search
tweets: [Tweets] @hasInverse(field: user)
}
type UserTweetCount @remote {
screen_name: String
tweetCount: Int
}

type Query {
dqlTweetsByAuthorFollowers: [Tweets] @custom(dql: """
query {
var(func: type(Tweets)) @filter(anyoftext(Tweets.text, "DQL")) {
Tweets.user {
followers as User.followers
}
userFollowerCount as sum(val(followers))
}
dqlTweetsByAuthorFollowers(func: uid(userFollowerCount), orderdesc: val(userFollowerCount)) {
id: uid
text: Tweets.text
timestamp: Tweets.timestamp
}
}
""")

filteredTweetsByAuthorFollowers(search: String!): [Tweets] @custom(dql: """
query t($search: string) {
var(func: type(Tweets)) @filter(anyoftext(Tweets.text, $search)) {
Tweets.user {
followers as User.followers
}
userFollowerCount as sum(val(followers))
}
filteredTweetsByAuthorFollowers(func: uid(userFollowerCount), orderdesc: val(userFollowerCount)) {
id: uid
text: Tweets.text
timestamp: Tweets.timestamp
}
}
""")

queryUserTweetCounts: [UserTweetCount] @custom(dql: """
query {
queryUserTweetCounts(func: type(User)) {
screen_name: User.screen_name
tweetCount: count(User.tweets)
}
}
""")
}
`
updateSchemaRequireNoGQLErrors(t, schema)
time.Sleep(2 * time.Second)

params := &common.GraphQLParams{
Query: `
mutation {
addTweets(input: [
{
text: "Hello DQL!"
user: {
screen_name: "abhimanyu"
followers: 5
}
timestamp: "2020-07-29"
}
{
text: "Woah DQL works!"
user: {
screen_name: "pawan"
followers: 10
}
timestamp: "2020-07-29"
}
{
text: "hmm, It worked."
user: {
screen_name: "abhimanyu"
followers: 5
}
timestamp: "2020-07-30"
}
]) {
numUids
}
}`,
}

result := params.ExecuteAsPost(t, alphaURL)
common.RequireNoGQLErrors(t, result)

params = &common.GraphQLParams{
Query: `
query {
dqlTweetsByAuthorFollowers {
text
}
filteredTweetsByAuthorFollowers(search: "hello") {
text
}
queryUserTweetCounts {
screen_name
tweetCount
}
}`,
}

result = params.ExecuteAsPost(t, alphaURL)
common.RequireNoGQLErrors(t, result)

require.JSONEq(t, `{
"dqlTweetsByAuthorFollowers": [
{
"text": "Woah DQL works!"
},
{
"text": "Hello DQL!"
}
],
"filteredTweetsByAuthorFollowers": [
{
"text": "Hello DQL!"
}
],
"queryUserTweetCounts": [
{
"screen_name": "abhimanyu",
"tweetCount": 2
},
{
"screen_name": "pawan",
"tweetCount": 1
}
]
}`, string(result.Data))
}
29 changes: 23 additions & 6 deletions graphql/resolve/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,33 @@ func (qr *queryResolver) rewriteAndExecute(ctx context.Context, query schema.Que
}
}

dgQuery, err := qr.queryRewriter.Rewrite(ctx, query)
if err != nil {
return emptyResult(schema.GQLWrapf(err, "couldn't rewrite query %s",
query.ResponseName()))
var qry string
vars := make(map[string]string)

// DQL queries don't have any rewriter, as they are already in DQL form
if query.QueryType() == schema.DQLQuery {
qry = query.DQLQuery()
args := query.Arguments()
for k, v := range args {
vStr, err := x.ScalarToString(v)
if err != nil {
return emptyResult(schema.GQLWrapf(err, "couldn't convert argument %s to string",
k))
}
vars["$"+k] = vStr
}
} else {
dgQuery, err := qr.queryRewriter.Rewrite(ctx, query)
if err != nil {
return emptyResult(schema.GQLWrapf(err, "couldn't rewrite query %s",
query.ResponseName()))
}
qry = dgraph.AsString(dgQuery)
}

queryTimer := newtimer(ctx, &dgraphQueryDuration.OffsetDuration)
queryTimer.Start()
resp, err := qr.executor.Execute(ctx, &dgoapi.Request{Query: dgraph.AsString(dgQuery),
ReadOnly: true})
resp, err := qr.executor.Execute(ctx, &dgoapi.Request{Query: qry, Vars: vars, ReadOnly: true})
queryTimer.Stop()

if err != nil {
Expand Down
6 changes: 6 additions & 0 deletions graphql/resolve/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,12 @@ func (rf *resolverFactory) WithConventionResolvers(
})
}

for _, q := range s.Queries(schema.DQLQuery) {
rf.WithQueryResolver(q, func(q schema.Query) QueryResolver {
return NewQueryResolver(nil, fns.Ex, StdQueryCompletion())
})
}

for _, m := range s.Mutations(schema.AddMutation) {
rf.WithMutationResolver(m, func(m schema.Mutation) MutationResolver {
return NewDgraphResolver(fns.Arw(), fns.Ex, StdMutationCompletion(m.Name()))
Expand Down
3 changes: 2 additions & 1 deletion graphql/schema/gqlschema.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ const (
SubscriptionDirective = "withSubscription"

// custom directive args and fields
dqlArg = "dql"
mode = "mode"
BATCH = "BATCH"
SINGLE = "SINGLE"
Expand Down Expand Up @@ -121,7 +122,7 @@ directive @auth(
add: AuthRule,
update: AuthRule,
delete:AuthRule) on OBJECT
directive @custom(http: CustomHTTP) on FIELD_DEFINITION
directive @custom(http: CustomHTTP, dql: String) on FIELD_DEFINITION
directive @remote on OBJECT | INTERFACE
directive @cascade on FIELD

Expand Down
Loading