Skip to content

Commit

Permalink
refactor(engine): simplify internal engine (#333)
Browse files Browse the repository at this point in the history
- provide payload in engine.Do instead of just a query
- rename client to engine
- use same consistent engine interface everywhere
  • Loading branch information
steebchen authored Dec 2, 2020
1 parent fa6ff91 commit a46052e
Show file tree
Hide file tree
Showing 14 changed files with 43 additions and 47 deletions.
2 changes: 1 addition & 1 deletion engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func New(schema string, hasBinaryTargets bool) *QueryEngine {
type Engine interface {
Connect() error
Disconnect() error
Do(ctx context.Context, query string, into interface{}) error
Do(ctx context.Context, payload interface{}, into interface{}) error
Name() string
}

Expand Down
7 changes: 5 additions & 2 deletions engine/mock/do.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,20 @@ import (
"context"
"encoding/json"
"fmt"

"github.com/prisma/prisma-client-go/engine"
)

func (e *Engine) Do(ctx context.Context, query string, v interface{}) error {
func (e *Engine) Do(ctx context.Context, payload interface{}, v interface{}) error {
e.expMu.Lock()
defer e.expMu.Unlock()

expectations := *e.expectations

var n = -1
for i, e := range expectations {
if e.Query.Build() == query {
req := payload.(engine.GQLRequest)
if e.Query.Build() == req.Query {
n = i
break
}
Expand Down
5 changes: 2 additions & 3 deletions engine/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@ type Data struct {

// GQLRequest is the payload for GraphQL queries
type GQLRequest struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
OperationName *string `json:"operationName"`
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
}

// GQLError is a GraphQL Error
Expand Down
9 changes: 2 additions & 7 deletions engine/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,10 @@ var internalDeleteNotFoundMessage = "Error occurred during query execution:\nInt
" \\'0\\'\", Some(QueryGraphBuilderError(RecordNotFound(\"Record to delete does not exist.\"))))"

// Do sends the http Request to the query engine and unmarshals the response
func (e *QueryEngine) Do(ctx context.Context, query string, v interface{}) error {
func (e *QueryEngine) Do(ctx context.Context, payload interface{}, v interface{}) error {
startReq := time.Now()

payload := GQLRequest{
Query: query,
Variables: map[string]interface{}{},
}

body, err := e.Request(ctx, "POST", "/", &payload)
body, err := e.Request(ctx, "POST", "/", payload)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
Expand Down
26 changes: 13 additions & 13 deletions generator/builder/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"strings"
"time"

"github.com/prisma/prisma-client-go/engine"
"github.com/prisma/prisma-client-go/logger"
)

Expand Down Expand Up @@ -42,20 +43,15 @@ type Field struct {
Fields []Field
}

type Client interface {
Do(ctx context.Context, query string, into interface{}) error
Name() string
}

func NewQuery() Query {
return Query{
Start: time.Now(),
}
}

type Query struct {
// Client is the generic Photon Client
Client Client
// Engine holds the implementation of how queries are processed
Engine engine.Engine

// Operation describes the PQL operation: query, mutation or subscription
Operation string
Expand Down Expand Up @@ -208,23 +204,27 @@ func (q Query) buildFields(list bool, wrapList bool, fields []Field) string {
}

func (q Query) Exec(ctx context.Context, v interface{}) error {
if q.Client == nil {
if q.Engine == nil {
panic("client.Connect() needs to be called before sending queries")
}

s := q.Build()
query := q.Build()

// TODO use specific log level
if logger.Enabled {
logger.Debug.Printf("prisma query: `%s`", s)
logger.Debug.Printf("prisma query: `%q`", query)
}

logger.Debug.Printf("[timing] building %s", time.Since(q.Start))
logger.Debug.Printf("[timing] building %q", time.Since(q.Start))

err := q.Client.Do(ctx, s, v)
payload := engine.GQLRequest{
Query: query,
Variables: map[string]interface{}{},
}
err := q.Engine.Do(ctx, payload, v)
now := time.Now()
totalDuration := now.Sub(q.Start)
logger.Debug.Printf("[timing] TOTAL %s", totalDuration)
logger.Debug.Printf("[timing] TOTAL %q", totalDuration)
return err
}

Expand Down
2 changes: 1 addition & 1 deletion generator/raw/execute_raw.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

func (r Actions) ExecuteRaw(query string, params ...interface{}) ExecuteExec {
return ExecuteExec{
query: raw(r.Client, "executeRaw", query, params...),
query: raw(r.Engine, "executeRaw", query, params...),
}
}

Expand Down
2 changes: 1 addition & 1 deletion generator/raw/query_raw.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

func (r Actions) QueryRaw(query string, params ...interface{}) QueryExec {
return QueryExec{
query: raw(r.Client, "queryRaw", query, params...),
query: raw(r.Engine, "queryRaw", query, params...),
}
}

Expand Down
7 changes: 4 additions & 3 deletions generator/raw/raw.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package raw

import (
"github.com/prisma/prisma-client-go/engine"
"github.com/prisma/prisma-client-go/generator/builder"
)

type Actions struct {
Client builder.Client
Engine engine.Engine
}

func raw(client builder.Client, action string, query string, params ...interface{}) builder.Query {
func raw(engine engine.Engine, action string, query string, params ...interface{}) builder.Query {
q := builder.NewQuery()
q.Client = client
q.Engine = engine
q.Operation = "mutation"
q.Method = action

Expand Down
2 changes: 1 addition & 1 deletion generator/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ func Run(input *Root) error {

if input.Generator.Config.DisableGitignore != "true" {
// generate a gitignore into the folder
var gitignore = "# gitignore generated by Prisma Client Go. DO NOT EDIT.\n*_gen.go\n"
var gitignore = "# gitignore generated by Prisma Engine Go. DO NOT EDIT.\n*_gen.go\n"
if err := ioutil.WriteFile(path.Join(input.Generator.Output, ".gitignore"), []byte(gitignore), 0644); err != nil {
return fmt.Errorf("could not write .gitignore: %w", err)
}
Expand Down
2 changes: 1 addition & 1 deletion generator/templates/actions/create.gotpl
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
) {{ $result }} {
var v {{ $result }}
v.query = builder.NewQuery()
v.query.Client = r.client
v.query.Engine = r.client

v.query.Operation = "mutation"
v.query.Method = "createOne"
Expand Down
2 changes: 1 addition & 1 deletion generator/templates/actions/find.gotpl
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
) {{ $result }} {
var v {{ $result }}
v.query = builder.NewQuery()
v.query.Client = r.client
v.query.Engine = r.client

v.query.Operation = "query"
v.query.Method = "find{{ $v.Name.GoCase }}"
Expand Down
4 changes: 2 additions & 2 deletions generator/templates/client.gotpl
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func NewClient() *PrismaClient {
c.{{ $model.Name.GoCase }} = {{ $model.Name.GoLowerCase }}Actions{client: c}
{{- end }}

c.Actions = &raw.Actions{Client: c}
c.Actions = &raw.Actions{Engine: c}

return c
}
Expand All @@ -50,7 +50,7 @@ func newMockClient(expectations *[]mock.Expectation) *PrismaClient {
c.{{ $model.Name.GoCase }} = {{ $model.Name.GoLowerCase }}Actions{client: c}
{{- end }}

c.Actions = &raw.Actions{Client: c}
c.Actions = &raw.Actions{Engine: c}

return c
}
Expand Down
4 changes: 2 additions & 2 deletions jsonrpc/methods.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package jsonrpc

// Manifest describes information for the Prisma Client Go generator for the Prisma CLI.
// Manifest describes information for the Prisma Engine Go generator for the Prisma CLI.
type Manifest struct {
PrettyName string `json:"prettyName"`
DefaultOutput string `json:"defaultOutput"`
Expand All @@ -9,7 +9,7 @@ type Manifest struct {
RequiresEngines []string `json:"requiresEngines"`
}

// ManifestResponse sets the response Prisma Client Go returns when Prisma asks for the Manifest.
// ManifestResponse sets the response Prisma Engine Go returns when Prisma asks for the Manifest.
type ManifestResponse struct {
Manifest Manifest `json:"manifest"`
}
16 changes: 7 additions & 9 deletions test/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,6 @@ type Database interface {
TeardownDatabase(t *testing.T, mockDBName string)
}

type Engine interface {
Connect() error
Disconnect() error
Do(context.Context, string, interface{}) error
}

var MySQL = mysql.MySQL
var PostgreSQL = postgresql.PostgreSQL
var SQLite = sqlite.SQLite
Expand Down Expand Up @@ -73,9 +67,13 @@ func Start(t *testing.T, db Database, e engine.Engine, queries []string) string
return ""
}

for _, b := range queries {
for _, q := range queries {
var response engine.GQLResponse
if err := e.Do(context.Background(), b, &response); err != nil {
payload := engine.GQLRequest{
Query: q,
Variables: map[string]interface{}{},
}
if err := e.Do(context.Background(), payload, &response); err != nil {
End(t, db, e, mockDB)
t.Fatalf("could not send mock query %s", err)
}
Expand All @@ -92,7 +90,7 @@ func Start(t *testing.T, db Database, e engine.Engine, queries []string) string
return mockDB
}

func End(t *testing.T, db Database, e Engine, mockDBName string) {
func End(t *testing.T, db Database, e engine.Engine, mockDBName string) {
defer teardown(t, db, mockDBName)

if err := e.Disconnect(); err != nil {
Expand Down

0 comments on commit a46052e

Please sign in to comment.