forked from ent/contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gql_node.go
288 lines (263 loc) · 7.48 KB
/
gql_node.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// Copyright 2019-present Facebook
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"sync"
"sync/atomic"
"entgo.io/contrib/entgql"
"entgo.io/contrib/entgql/internal/todofed/ent/category"
"entgo.io/contrib/entgql/internal/todofed/ent/todo"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/schema"
"github.com/99designs/gqlgen/graphql"
"github.com/hashicorp/go-multierror"
"golang.org/x/sync/semaphore"
)
// Noder wraps the basic Node method.
type Noder interface {
IsNode()
}
var categoryImplementors = []string{"Category", "Node"}
// IsNode implements the Node interface check for GQLGen.
func (*Category) IsNode() {}
var todoImplementors = []string{"Todo", "Node"}
// IsNode implements the Node interface check for GQLGen.
func (*Todo) IsNode() {}
var errNodeInvalidID = &NotFoundError{"node"}
// NodeOption allows configuring the Noder execution using functional options.
type NodeOption func(*nodeOptions)
// WithNodeType sets the node Type resolver function (i.e. the table to query).
// If was not provided, the table will be derived from the universal-id
// configuration as described in: https://entgo.io/docs/migrate/#universal-ids.
func WithNodeType(f func(context.Context, int) (string, error)) NodeOption {
return func(o *nodeOptions) {
o.nodeType = f
}
}
// WithFixedNodeType sets the Type of the node to a fixed value.
func WithFixedNodeType(t string) NodeOption {
return WithNodeType(func(context.Context, int) (string, error) {
return t, nil
})
}
type nodeOptions struct {
nodeType func(context.Context, int) (string, error)
}
func (c *Client) newNodeOpts(opts []NodeOption) *nodeOptions {
nopts := &nodeOptions{}
for _, opt := range opts {
opt(nopts)
}
if nopts.nodeType == nil {
nopts.nodeType = func(ctx context.Context, id int) (string, error) {
return c.tables.nodeType(ctx, c.driver, id)
}
}
return nopts
}
// Noder returns a Node by its id. If the NodeType was not provided, it will
// be derived from the id value according to the universal-id configuration.
//
// c.Noder(ctx, id)
// c.Noder(ctx, id, ent.WithNodeType(typeResolver))
func (c *Client) Noder(ctx context.Context, id int, opts ...NodeOption) (_ Noder, err error) {
defer func() {
if IsNotFound(err) {
err = multierror.Append(err, entgql.ErrNodeNotFound(id))
}
}()
table, err := c.newNodeOpts(opts).nodeType(ctx, id)
if err != nil {
return nil, err
}
return c.noder(ctx, table, id)
}
func (c *Client) noder(ctx context.Context, table string, id int) (Noder, error) {
switch table {
case category.Table:
query := c.Category.Query().
Where(category.ID(id))
if fc := graphql.GetFieldContext(ctx); fc != nil {
if err := query.collectField(ctx, true, graphql.GetOperationContext(ctx), fc.Field, nil, categoryImplementors...); err != nil {
return nil, err
}
}
return query.Only(ctx)
case todo.Table:
query := c.Todo.Query().
Where(todo.ID(id))
if fc := graphql.GetFieldContext(ctx); fc != nil {
if err := query.collectField(ctx, true, graphql.GetOperationContext(ctx), fc.Field, nil, todoImplementors...); err != nil {
return nil, err
}
}
return query.Only(ctx)
default:
return nil, fmt.Errorf("cannot resolve noder from table %q: %w", table, errNodeInvalidID)
}
}
func (c *Client) Noders(ctx context.Context, ids []int, opts ...NodeOption) ([]Noder, error) {
switch len(ids) {
case 1:
noder, err := c.Noder(ctx, ids[0], opts...)
if err != nil {
return nil, err
}
return []Noder{noder}, nil
case 0:
return []Noder{}, nil
}
noders := make([]Noder, len(ids))
errors := make([]error, len(ids))
tables := make(map[string][]int)
id2idx := make(map[int][]int, len(ids))
nopts := c.newNodeOpts(opts)
for i, id := range ids {
table, err := nopts.nodeType(ctx, id)
if err != nil {
errors[i] = err
continue
}
tables[table] = append(tables[table], id)
id2idx[id] = append(id2idx[id], i)
}
for table, ids := range tables {
nodes, err := c.noders(ctx, table, ids)
if err != nil {
for _, id := range ids {
for _, idx := range id2idx[id] {
errors[idx] = err
}
}
} else {
for i, id := range ids {
for _, idx := range id2idx[id] {
noders[idx] = nodes[i]
}
}
}
}
for i, id := range ids {
if errors[i] == nil {
if noders[i] != nil {
continue
}
errors[i] = entgql.ErrNodeNotFound(id)
} else if IsNotFound(errors[i]) {
errors[i] = multierror.Append(errors[i], entgql.ErrNodeNotFound(id))
}
ctx := graphql.WithPathContext(ctx,
graphql.NewPathWithIndex(i),
)
graphql.AddError(ctx, errors[i])
}
return noders, nil
}
func (c *Client) noders(ctx context.Context, table string, ids []int) ([]Noder, error) {
noders := make([]Noder, len(ids))
idmap := make(map[int][]*Noder, len(ids))
for i, id := range ids {
idmap[id] = append(idmap[id], &noders[i])
}
switch table {
case category.Table:
query := c.Category.Query().
Where(category.IDIn(ids...))
query, err := query.CollectFields(ctx, categoryImplementors...)
if err != nil {
return nil, err
}
nodes, err := query.All(ctx)
if err != nil {
return nil, err
}
for _, node := range nodes {
for _, noder := range idmap[node.ID] {
*noder = node
}
}
case todo.Table:
query := c.Todo.Query().
Where(todo.IDIn(ids...))
query, err := query.CollectFields(ctx, todoImplementors...)
if err != nil {
return nil, err
}
nodes, err := query.All(ctx)
if err != nil {
return nil, err
}
for _, node := range nodes {
for _, noder := range idmap[node.ID] {
*noder = node
}
}
default:
return nil, fmt.Errorf("cannot resolve noders from table %q: %w", table, errNodeInvalidID)
}
return noders, nil
}
type tables struct {
once sync.Once
sem *semaphore.Weighted
value atomic.Value
}
func (t *tables) nodeType(ctx context.Context, drv dialect.Driver, id int) (string, error) {
tables, err := t.Load(ctx, drv)
if err != nil {
return "", err
}
idx := int(id / (1<<32 - 1))
if idx < 0 || idx >= len(tables) {
return "", fmt.Errorf("cannot resolve table from id %v: %w", id, errNodeInvalidID)
}
return tables[idx], nil
}
func (t *tables) Load(ctx context.Context, drv dialect.Driver) ([]string, error) {
if tables := t.value.Load(); tables != nil {
return tables.([]string), nil
}
t.once.Do(func() { t.sem = semaphore.NewWeighted(1) })
if err := t.sem.Acquire(ctx, 1); err != nil {
return nil, err
}
defer t.sem.Release(1)
if tables := t.value.Load(); tables != nil {
return tables.([]string), nil
}
tables, err := t.load(ctx, drv)
if err == nil {
t.value.Store(tables)
}
return tables, err
}
func (*tables) load(ctx context.Context, drv dialect.Driver) ([]string, error) {
rows := &sql.Rows{}
query, args := sql.Dialect(drv.Dialect()).
Select("type").
From(sql.Table(schema.TypeTable)).
OrderBy(sql.Asc("id")).
Query()
if err := drv.Query(ctx, query, args, rows); err != nil {
return nil, err
}
defer rows.Close()
var tables []string
return tables, sql.ScanSlice(rows, &tables)
}