{{/* 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 "client" }} {{ $pkg := base $.Config.Package }} {{ template "header" $ }} import ( "log" "{{ $.Config.Package }}/migrate" {{ range $_, $n := $.Nodes }} "{{ $n.Config.Package }}/{{ $n.Package }}" {{- end }} "github.com/facebookincubator/ent/dialect" {{ range $_, $import := $.Storage.Imports -}} "{{ $import }}" {{ end -}} ) // Client is the client that holds all ent builders. type Client struct { config {{- if $.SupportMigrate }} // Schema is the client for creating, migrating and dropping schema. Schema *migrate.Schema {{- end }} {{- range $n := $.Nodes }} // {{ $n.Name }} is the client for interacting with the {{ $n.Name }} builders. {{ $n.Name }} *{{ $n.Name }}Client {{- end }} {{ template "client/fields/additional" $ }} } // NewClient creates a new client configured with the given options. func NewClient(opts ...Option) *Client { cfg := config{log: log.Println, hooks: &hooks{}} cfg.options(opts...) client := &Client{config: cfg} client.init() return client } func (c *Client) init() { {{- if $.SupportMigrate }} c.Schema = migrate.NewSchema(c.driver) {{- end }} {{- range $n := $.Nodes }} c.{{ $n.Name }} = New{{ $n.Name }}Client(c.config) {{- end }} } // Open opens a connection to the database specified by the driver name and a // driver-specific data source name, and returns a new client attached to it. // Optional parameters can be added for configuring the client. func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { switch driverName { case {{ join $.Storage.Dialects ", " }}: {{- $tmpl := printf "dialect/%s/client/open" $.Storage -}} {{- xtemplate $tmpl . -}} default: return nil, fmt.Errorf("unsupported driver: %q", driverName) } } // Tx returns a new transactional client. func (c *Client) Tx(ctx context.Context) (*Tx, error) { if _, ok := c.driver.(*txDriver); ok { return nil, fmt.Errorf("{{ $pkg }}: cannot start a transaction within a transaction") } tx, err := newTx(ctx, c.driver) if err != nil { return nil, fmt.Errorf("{{ $pkg }}: starting a transaction: %v", err) } cfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks} return &Tx{ config: cfg, {{ range $_, $n := $.Nodes -}} {{ $n.Name }}: New{{ $n.Name }}Client(cfg), {{ end -}} }, nil } {{- /* If the storage driver supports TxOptions (like SQL) */}} {{- $tmpl = printf "dialect/%s/txoptions" $.Storage }} {{- if hasTemplate $tmpl }} {{- xtemplate $tmpl . }} {{- end }} // Debug returns a new debug-client. It's used to get verbose logging on specific operations. // // client.Debug(). // {{ (index $.Nodes 0).Name }}. // Query(). // Count(ctx) // func (c *Client) Debug() *Client { if c.debug { return c } cfg := config{driver: dialect.Debug(c.driver, c.log), log: c.log, debug: true, hooks: c.hooks} client := &Client{config: cfg} client.init() return client } // Close closes the database connection and prevents new queries from starting. func (c *Client) Close() error { return c.driver.Close() } // Use adds the mutation hooks to all the entity clients. // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { {{- range $_, $n := $.Nodes }} c.{{ $n.Name }}.Use(hooks...) {{- end }} } {{ range $_, $n := $.Nodes }} {{ $client := print $n.Name "Client" }} // {{ $client }} is a client for the {{ $n.Name }} schema. type {{ $client }} struct { config } {{ $rec := $n.Receiver }}{{ if eq $rec "c" }}{{ $rec = printf "%.2s" $n.Name | lower }}{{ end }} // New{{ $client }} returns a client for the {{ $n.Name }} from the given config. func New{{ $client }}(c config) *{{ $client }} { return &{{ $client }}{config: c} } // Use adds a list of mutation hooks to the hooks stack. // A call to `Use(f, g, h)` equals to `{{ $n.Package }}.Hooks(f(g(h())))`. func (c *{{ $client }}) Use(hooks ...Hook) { c.hooks.{{ $n.Name }} = append(c.hooks.{{ $n.Name }}, hooks...) } // Create returns a create builder for {{ $n.Name }}. func (c *{{ $client }}) Create() *{{ $n.Name }}Create { mutation := new{{ $n.MutationName }}(c.config, OpCreate) return &{{ $n.Name }}Create{config: c.config, hooks: c.Hooks(), mutation: mutation} } // Update returns an update builder for {{ $n.Name }}. func (c *{{ $client }}) Update() *{{ $n.Name }}Update { mutation := new{{ $n.MutationName }}(c.config, OpUpdate) return &{{ $n.Name }}Update{config: c.config, hooks: c.Hooks(), mutation: mutation} } // UpdateOne returns an update builder for the given entity. func (c *{{ $client }}) UpdateOne({{ $rec }} *{{ $n.Name }}) *{{ $n.Name }}UpdateOne { return c.UpdateOneID({{ $rec }}.ID) } // UpdateOneID returns an update builder for the given id. func (c *{{ $client }}) UpdateOneID(id {{ $n.ID.Type }}) *{{ $n.Name }}UpdateOne { mutation := new{{ $n.MutationName }}(c.config, OpUpdateOne) mutation.id = &id return &{{ $n.Name }}UpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } // Delete returns a delete builder for {{ $n.Name }}. func (c *{{ $client }}) Delete() *{{ $n.Name }}Delete { mutation := new{{ $n.MutationName }}(c.config, OpDelete) return &{{ $n.Name }}Delete{config: c.config, hooks: c.Hooks(), mutation: mutation} } // DeleteOne returns a delete builder for the given entity. func (c *{{ $client }}) DeleteOne({{ $rec }} *{{ $n.Name }}) *{{ $n.Name }}DeleteOne { return c.DeleteOneID({{ $rec }}.ID) } // DeleteOneID returns a delete builder for the given id. func (c *{{ $client }}) DeleteOneID(id {{ $n.ID.Type }}) *{{ $n.Name }}DeleteOne { builder := c.Delete().Where({{ $n.Package }}.ID(id)) builder.mutation.id = &id builder.mutation.op = OpDeleteOne return &{{ $n.Name }}DeleteOne{builder} } // Create returns a query builder for {{ $n.Name }}. func (c *{{ $client }}) Query() *{{ $n.Name }}Query { return &{{ $n.Name }}Query{config: c.config} } // Get returns a {{ $n.Name }} entity by its id. func (c *{{ $client }}) Get(ctx context.Context, id {{ $n.ID.Type }}) (*{{ $n.Name }}, error) { return c.Query().Where({{ $n.Package }}.ID(id)).Only(ctx) } // GetX is like Get, but panics if an error occurs. func (c *{{ $client }}) GetX(ctx context.Context, id {{ $n.ID.Type }}) *{{ $n.Name }} { {{ $rec }}, err := c.Get(ctx, id) if err != nil { panic(err) } return {{ $rec }} } {{ range $_, $e := $n.Edges }} {{ $builder := $e.Type.QueryName }} // Query{{ pascal $e.Name }} queries the {{ $e.Name }} edge of a {{ $n.Name }}. func (c *{{ $client }}) Query{{ pascal $e.Name }}({{ $rec }} *{{ $n.Name }}) *{{ $builder }} { query := &{{ $builder }}{config: c.config} query.path = func(ctx context.Context) (fromV {{ $.Storage.Builder }}, _ error) { {{- with extend $n "Receiver" $rec "Edge" $e "Ident" "fromV" }} {{ $tmpl := printf "dialect/%s/query/from" $.Storage }} {{- xtemplate $tmpl . -}} {{- end -}} return fromV, nil } return query } {{ end }} // Hooks returns the client hooks. func (c *{{ $client }}) Hooks() []Hook { {{- if or $n.NumHooks $n.HasPolicy }} hooks := c.hooks.{{ $n.Name }} return append(hooks[:len(hooks):len(hooks)], {{ $n.Package }}.Hooks[:]...) {{- else }} return c.hooks.{{ $n.Name }} {{- end }} } {{ end }} {{ end }} {{/* A template that can be overrided in order to add additional fields to the client.*/}} {{ define "client/fields/additional" }}{{ end }}