{{/*
Copyright 2019-present Facebook Inc. All rights reserved.
This source code is licensed under the Apache 2.0 license found
in the LICENSE file in the root directory of this source tree.
*/}}

{{ define "example" }}

{{ $pkg := base $.Config.Package }}
{{ template "header" $ }}

import (
	"log"
	"testing"
	"os"
	"net/url"

	"github.com/facebookincubator/ent/dialect/sql"
	{{ range $_, $n := $.Nodes }}
		"{{ $n.Config.Package }}/{{ $n.Package }}"
	{{- end }}
)

{{ $env := upper $pkg | printf "%s_INTEGRATION_ENDPOINT" }}

// dsn for the database. In order to run the tests locally, run the following command:
//
//	 {{ $env }}="root:pass@tcp(localhost:3306)/test?parseTime=True" go test -v
//
var dsn string

{{ range $_, $n := $.Nodes -}}
func Example{{ pascal $n.Name }}() {
	if dsn == "" {
		return
	}
	ctx := context.Background()
	drv, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("failed creating database client: %v", err)
	}
	defer drv.Close()
	client := NewClient(Driver(drv))
	// creating vertices for the {{ lower $n.Name }}'s edges.
	{{ range $i, $e := $n.Edges }}
		{{- if not $e.IsInverse }}
			{{- $v := printf "%s%d" $e.Type.Receiver $i }}
			{{- $v }} := client.{{ $e.Type.Name }}.
					Create().
				{{ range $_, $f := $e.Type.Fields }}
					{{- pascal $f.Name | printf "Set%s" }}({{ $f.ExampleCode }}).
				{{ end }}
					SaveX(ctx)
			log.Println("{{ lower $e.Type.Name }} created:", {{ $v }})
		{{ end }}
	{{- end }}
	// create {{ lower $n.Name }} vertex with its edges.
	{{ $n.Receiver }} := client.{{ $n.Name }}.
		Create().
	{{ range $_, $f := $n.Fields }}
		{{- pascal $f.Name | printf "Set%s" }}({{ $f.ExampleCode }}).
	{{ end }}
	{{ range $i, $e := $n.Edges }}
		{{- if not $e.IsInverse }}
			{{- $op := "add" }}{{ if $e.Unique }}{{ $op = "set" }}{{ end }}
			{{- $func := print (pascal $op) (pascal $e.Name) }}
			{{- $func }}({{ printf "%s%d" $e.Type.Receiver $i }}).
		{{ end }}
	{{ end }}
		SaveX(ctx)
	log.Println("{{ lower $n.Name }} created:", {{ $n.Receiver }})

	// query edges.
	{{ range $i, $e := $n.Edges }}
		{{- if not $e.IsInverse }}
			{{- $v := printf "%s%d" $e.Type.Receiver $i }}
			{{- $v }}, err = {{ $n.Receiver }}.{{ pascal $e.Name | printf "Query%s" }}().First(ctx)
			if err != nil {
				log.Fatalf("failed querying {{ $e.Name }}: %v", err)
			}
			log.Println("{{ $e.Name }} found:", {{ $v }})
		{{ end }}
	{{ end }}
	// Output:
}
{{ end }}

{{ end }}
