-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathschema_constraints.go
More file actions
339 lines (293 loc) · 9.56 KB
/
Copy pathschema_constraints.go
File metadata and controls
339 lines (293 loc) · 9.56 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
// Copyright 2025 DoorDash, Inc.
//
// 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.
package codegen
import (
"fmt"
"slices"
"sort"
"github.com/pb33f/libopenapi/datamodel/high/base"
)
type ConstraintsContext struct {
hasNilType bool
required bool
specLocation SpecLocation
}
type Constraints struct {
Required *bool
Nullable *bool
ReadOnly *bool
WriteOnly *bool
MinLength *int64
MaxLength *int64
Pattern *string
Min *float64
Max *float64
MinItems *int64
MaxItems *int64
MinProperties *int64
MaxProperties *int64
ValidationTags []string
}
func (c Constraints) IsEqual(other Constraints) bool {
return ptrEqual(c.Required, other.Required) &&
ptrEqual(c.Nullable, other.Nullable) &&
ptrEqual(c.ReadOnly, other.ReadOnly) &&
ptrEqual(c.WriteOnly, other.WriteOnly) &&
ptrEqual(c.MinLength, other.MinLength) &&
ptrEqual(c.MaxLength, other.MaxLength) &&
ptrEqual(c.Pattern, other.Pattern) &&
ptrEqual(c.Min, other.Min) &&
ptrEqual(c.Max, other.Max) &&
ptrEqual(c.MinItems, other.MinItems) &&
ptrEqual(c.MaxItems, other.MaxItems) &&
ptrEqual(c.MinProperties, other.MinProperties) &&
ptrEqual(c.MaxProperties, other.MaxProperties) &&
slices.Equal(c.ValidationTags, other.ValidationTags)
}
// Count returns the number of validation constraints.
// This is useful for determining which schema is "stricter" when deduplicating union elements.
func (c Constraints) Count() int {
count := 0
// String constraints
if c.MinLength != nil {
count++
}
if c.MaxLength != nil {
count++
}
if c.Pattern != nil {
count++
}
// Numeric constraints
if c.Min != nil {
count++
}
if c.Max != nil {
count++
}
// Array constraints
if c.MinItems != nil {
count++
}
if c.MaxItems != nil {
count++
}
// Object constraints
if c.MinProperties != nil {
count++
}
if c.MaxProperties != nil {
count++
}
// ValidationTags includes additional constraints like enum, format, etc.
// Each tag represents a constraint
count += len(c.ValidationTags)
return count
}
// hasPattern reports whether these constraints carry a non-empty regex pattern.
func (c Constraints) hasPattern() bool {
return c.Pattern != nil && *c.Pattern != ""
}
func newConstraints(schema *base.Schema, opts ConstraintsContext) Constraints {
if schema == nil {
return Constraints{}
}
isInt := slices.Contains(schema.Type, "integer")
isFloat := slices.Contains(schema.Type, "number")
isBoolean := slices.Contains(schema.Type, "boolean")
isString := slices.Contains(schema.Type, "string")
// Check if the string format converts to a non-string Go type.
// These formats do not support minLength/maxLength validation tags because
// the Go type is not a string (e.g., time.Time, uuid.UUID).
hasNonStringFormat := isString && (schema.Format == "date-time" || schema.Format == "date" || schema.Format == "uuid")
isArray := slices.Contains(schema.Type, "array")
isObject := schema.Type == nil || slices.Contains(schema.Type, "object")
var validationTags []string
hasNilType := opts.hasNilType
// Use the required value from opts - it's already set correctly by the caller
// based on the parent schema's required list.
// We should NOT check schema.Required here because for $ref properties,
// schema is the resolved target schema, not the property schema.
// Checking schema.Required would incorrectly mark a property as required
// if the resolved schema happens to have a required property with the same name.
required := opts.required
// ReadOnly fields should not have struct-level required validation.
// They are only present in responses, not in requests, so requiring them
// at the struct level would fail when validating request bodies.
// Component schemas are shared between requests and responses, so we can't
// rely on specLocation to determine the context.
if required && schema.ReadOnly != nil && *schema.ReadOnly {
required = false
}
// WriteOnly fields should not have struct-level required validation.
// They are only present in requests, not in responses, so requiring them
// at the struct level would fail when validating response bodies.
// Component schemas are shared between requests and responses, so we can't
// rely on specLocation to determine the context.
if required && schema.WriteOnly != nil && *schema.WriteOnly {
required = false
}
nullable := !required || hasNilType || deref(schema.Nullable)
if required && (isBoolean || isInt || isFloat) {
// otherwise validation will always fail with zero value.
// The validator library treats zero as "not set" for required numeric/boolean fields.
required = false
nullable = hasNilType
}
// Don't require strings with maxLength=0 - the only valid value is ""
// which is nonsensical as a required field (likely a broken spec generator default)
if required && isString && schema.MaxLength != nil && *schema.MaxLength == 0 {
required = false
}
// Don't add "required" validation tag for object types (structs)
// Objects should be validated by calling their .Validate() method, not by validator.Var()
if required && isObject {
required = false
// Still mark as nullable if it's not required, so we get omitempty
if hasNilType {
nullable = true
}
}
if required && nullable {
nullable = true
}
if required {
validationTags = append(validationTags, "required")
} else if nullable {
validationTags = append(validationTags, "omitempty")
}
var readOnly *bool
if schema.ReadOnly != nil {
readOnly = schema.ReadOnly
}
var writeOnly *bool
if schema.WriteOnly != nil {
writeOnly = schema.WriteOnly
}
var minValue *float64
// Only store minimum for numeric types (integer/number)
// For strings, minimum is invalid per OpenAPI spec - ignore it completely
if schema.Minimum != nil && (isInt || isFloat) {
minTag := "gte"
val := *schema.Minimum
if schema.ExclusiveMinimum != nil && ((schema.ExclusiveMinimum.IsA() && schema.ExclusiveMinimum.A) || schema.ExclusiveMinimum.IsB()) {
minTag = "gt"
if schema.ExclusiveMinimum.IsB() {
val = schema.ExclusiveMinimum.B
}
}
minValue = &val
tag := fmt.Sprintf("%s=%g", minTag, val)
if isInt {
tag = fmt.Sprintf("%s=%d", minTag, int64(val))
}
validationTags = append(validationTags, tag)
}
var maxValue *float64
// Only store maximum for numeric types (integer/number)
// For strings, maximum is invalid per OpenAPI spec - ignore it completely
if schema.Maximum != nil && (isInt || isFloat) {
maxTag := "lte"
val := *schema.Maximum
if schema.ExclusiveMaximum != nil && ((schema.ExclusiveMaximum.IsA() && schema.ExclusiveMaximum.A) || schema.ExclusiveMaximum.IsB()) {
maxTag = "lt"
if schema.ExclusiveMaximum.IsB() {
val = schema.ExclusiveMaximum.B
}
}
maxValue = &val
tag := fmt.Sprintf("%s=%g", maxTag, val)
if isInt {
tag = fmt.Sprintf("%s=%d", maxTag, int64(val))
}
validationTags = append(validationTags, tag)
}
var minLength *int64
// Only store minLength for strings and arrays
// For integers/numbers/booleans, minLength is invalid per OpenAPI spec - ignore it completely
if schema.MinLength != nil && (isString || isArray) && !hasNonStringFormat {
minLength = schema.MinLength
validationTags = append(validationTags, fmt.Sprintf("min=%d", *minLength))
}
var maxLength *int64
// Only store maxLength for strings and arrays
// For integers/numbers/booleans, maxLength is invalid per OpenAPI spec - ignore it completely
if schema.MaxLength != nil && (isString || isArray) && !hasNonStringFormat {
maxLength = schema.MaxLength
validationTags = append(validationTags, fmt.Sprintf("max=%d", *maxLength))
}
var pattern *string
if schema.Pattern != "" {
pattern = &schema.Pattern
}
var minItems *int64
if schema.MinItems != nil {
minItems = schema.MinItems
}
var maxItems *int64
if schema.MaxItems != nil {
maxItems = schema.MaxItems
}
var minProperties *int64
if schema.MinProperties != nil {
minProperties = schema.MinProperties
}
var maxProperties *int64
if schema.MaxProperties != nil {
maxProperties = schema.MaxProperties
}
if len(validationTags) == 1 && validationTags[0] == "omitempty" {
validationTags = nil
}
// place required, omitempty first in the list, then sort the rest
sort.Slice(validationTags, func(i, j int) bool {
a, b := validationTags[i], validationTags[j]
// Define priority order
priority := func(tag string) int {
switch tag {
case "required":
return 0
case "omitempty":
return 1
default:
return 2
}
}
pa, pb := priority(a), priority(b)
if pa != pb {
return pa < pb
}
return a < b
})
var requiredPtr *bool
if required {
requiredPtr = ptr(true)
}
var nullablePtr *bool
if nullable {
nullablePtr = ptr(true)
}
return Constraints{
Nullable: nullablePtr,
Required: requiredPtr,
ReadOnly: readOnly,
WriteOnly: writeOnly,
Min: minValue,
Max: maxValue,
MinLength: minLength,
MaxLength: maxLength,
Pattern: pattern,
MinItems: minItems,
MaxItems: maxItems,
MinProperties: minProperties,
MaxProperties: maxProperties,
ValidationTags: validationTags,
}
}