-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathfield_relation.go
More file actions
355 lines (292 loc) · 10.1 KB
/
field_relation.go
File metadata and controls
355 lines (292 loc) · 10.1 KB
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package core
import (
"context"
"database/sql/driver"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
Fields[FieldTypeRelation] = func() Field {
return &RelationField{}
}
}
const FieldTypeRelation = "relation"
var (
_ Field = (*RelationField)(nil)
_ MultiValuer = (*RelationField)(nil)
_ DriverValuer = (*RelationField)(nil)
_ SetterFinder = (*RelationField)(nil)
)
// RelationField defines "relation" type field for storing single or
// multiple collection record references.
//
// Requires the CollectionId option to be set.
//
// If MaxSelect is not set or <= 1, then the field value is expected to be a single record id.
//
// If MaxSelect is > 1, then the field value is expected to be a slice of record ids.
//
// The respective zero record field value is either empty string (single) or empty string slice (multiple).
//
// ---
//
// The following additional setter keys are available:
//
// - "fieldName+" - append one or more values to the existing record one. For example:
//
// record.Set("categories+", []string{"new1", "new2"}) // []string{"old1", "old2", "new1", "new2"}
//
// - "+fieldName" - prepend one or more values to the existing record one. For example:
//
// record.Set("+categories", []string{"new1", "new2"}) // []string{"new1", "new2", "old1", "old2"}
//
// - "fieldName-" - subtract one or more values from the existing record one. For example:
//
// record.Set("categories-", "old1") // []string{"old2"}
type RelationField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// ---
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// Help is an extra text explaining what the field is about.
// It is usually shown in Dashboard UI under the field input.
Help string `form:"help" json:"help"`
// CollectionId is the id of the related collection.
CollectionId string `form:"collectionId" json:"collectionId"`
// CascadeDelete indicates whether the root model should be deleted
// in case of delete of all linked relations.
CascadeDelete bool `form:"cascadeDelete" json:"cascadeDelete"`
// MinSelect indicates the min number of allowed relation records
// that could be linked to the main model.
//
// No min limit is applied if it is zero or negative value.
MinSelect int `form:"minSelect" json:"minSelect"`
// MaxSelect indicates the max number of allowed relation records
// that could be linked to the main model.
//
// For multiple select the value must be > 1, otherwise fallbacks to single (default).
//
// If MinSelect is set, MaxSelect must be at least >= MinSelect.
MaxSelect int `form:"maxSelect" json:"maxSelect"`
// Required will require the field value to be non-empty.
Required bool `form:"required" json:"required"`
}
// Type implements [Field.Type] interface method.
func (f *RelationField) Type() string {
return FieldTypeRelation
}
// GetId implements [Field.GetId] interface method.
func (f *RelationField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *RelationField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *RelationField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *RelationField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *RelationField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *RelationField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *RelationField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *RelationField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// IsMultiple implements [MultiValuer] interface and checks whether the
// current field options support multiple values.
func (f *RelationField) IsMultiple() bool {
return f.MaxSelect > 1
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *RelationField) ColumnType(app App) string {
if f.IsMultiple() {
return "JSON DEFAULT '[]' NOT NULL"
}
return "TEXT DEFAULT '' NOT NULL"
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *RelationField) PrepareValue(record *Record, raw any) (any, error) {
return f.normalizeValue(raw), nil
}
func (f *RelationField) normalizeValue(raw any) any {
val := list.ToUniqueStringSlice(raw)
if !f.IsMultiple() {
if len(val) > 0 {
return val[len(val)-1] // the last selected
}
return ""
}
return val
}
// DriverValue implements the [DriverValuer] interface.
func (f *RelationField) DriverValue(record *Record) (driver.Value, error) {
val := list.ToUniqueStringSlice(record.GetRaw(f.Name))
if !f.IsMultiple() {
if len(val) > 0 {
return val[len(val)-1], nil // the last selected
}
return "", nil
}
// serialize as json string array
return append(types.JSONArray[string]{}, val...), nil
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *RelationField) ValidateValue(ctx context.Context, app App, record *Record) error {
ids := list.ToUniqueStringSlice(record.GetRaw(f.Name))
if len(ids) == 0 {
if f.Required {
return validation.ErrRequired
}
return nil // nothing to check
}
if f.MinSelect > 0 && len(ids) < f.MinSelect {
return validation.NewError("validation_not_enough_values", "Select at least {{.minSelect}}").
SetParams(map[string]any{"minSelect": f.MinSelect})
}
maxSelect := max(f.MaxSelect, 1)
if len(ids) > maxSelect {
return validation.NewError("validation_too_many_values", "Select no more than {{.maxSelect}}").
SetParams(map[string]any{"maxSelect": maxSelect})
}
// check if the related records exist
// ---
relCollection, err := app.FindCachedCollectionByNameOrId(f.CollectionId)
if err != nil {
return validation.NewError("validation_missing_rel_collection", "Relation connection is missing or cannot be accessed")
}
var total int
_ = app.ConcurrentDB().
Select("count(*)").
From(relCollection.Name).
AndWhere(dbx.In("id", list.ToInterfaceSlice(ids)...)).
Row(&total)
if total != len(ids) {
return validation.NewError("validation_missing_rel_records", "Failed to find all relation records with the provided ids")
}
// ---
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *RelationField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
validation.Field(&f.Help, validation.By(DefaultFieldHelpValidationRule)),
validation.Field(&f.CollectionId, validation.Required, validation.By(f.checkCollectionId(app, collection))),
validation.Field(&f.MinSelect, validation.Min(0)),
validation.Field(&f.MaxSelect, validation.When(f.MinSelect > 0, validation.Required), validation.Min(f.MinSelect)),
)
}
func (f *RelationField) checkCollectionId(app App, collection *Collection) validation.RuleFunc {
return func(value any) error {
v, _ := value.(string)
if v == "" {
return nil // nothing to check
}
var oldCollection *Collection
if !collection.IsNew() {
var err error
oldCollection, err = app.FindCachedCollectionByNameOrId(collection.Id)
if err != nil {
return err
}
}
// prevent collectionId change
if oldCollection != nil {
oldField, _ := oldCollection.Fields.GetById(f.Id).(*RelationField)
if oldField != nil && oldField.CollectionId != v {
return validation.NewError(
"validation_field_relation_change",
"The relation collection cannot be changed.",
)
}
}
relCollection, _ := app.FindCachedCollectionByNameOrId(v)
// validate collectionId
if relCollection == nil || relCollection.Id != v {
return validation.NewError(
"validation_field_relation_missing_collection",
"The relation collection doesn't exist.",
)
}
// allow only views to have relations to other views
// (see https://github.com/pocketbase/pocketbase/issues/3000)
if !collection.IsView() && relCollection.IsView() {
return validation.NewError(
"validation_relation_field_non_view_base_collection",
"Only view collections are allowed to have relations to other views.",
)
}
return nil
}
}
// ---
// FindSetter implements [SetterFinder] interface method.
func (f *RelationField) FindSetter(key string) SetterFunc {
switch key {
case f.Name:
return f.setValue
case "+" + f.Name:
return f.prependValue
case f.Name + "+":
return f.appendValue
case f.Name + "-":
return f.subtractValue
default:
return nil
}
}
func (f *RelationField) setValue(record *Record, raw any) {
record.SetRaw(f.Name, f.normalizeValue(raw))
}
func (f *RelationField) appendValue(record *Record, modifierValue any) {
val := record.GetRaw(f.Name)
val = append(
list.ToUniqueStringSlice(val),
list.ToUniqueStringSlice(modifierValue)...,
)
f.setValue(record, val)
}
func (f *RelationField) prependValue(record *Record, modifierValue any) {
val := record.GetRaw(f.Name)
val = append(
list.ToUniqueStringSlice(modifierValue),
list.ToUniqueStringSlice(val)...,
)
f.setValue(record, val)
}
func (f *RelationField) subtractValue(record *Record, modifierValue any) {
val := record.GetRaw(f.Name)
val = list.SubtractSlice(
list.ToUniqueStringSlice(val),
list.ToUniqueStringSlice(modifierValue),
)
f.setValue(record, val)
}