-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathAttribute.php
More file actions
571 lines (513 loc) · 20.1 KB
/
Attribute.php
File metadata and controls
571 lines (513 loc) · 20.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
<?php
namespace Utopia\Database\Validator;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception as DatabaseException;
use Utopia\Database\Exception\Duplicate as DuplicateException;
use Utopia\Database\Exception\Limit as LimitException;
use Utopia\Validator;
class Attribute extends Validator
{
protected string $message = 'Invalid attribute';
/**
* @var array<Document> $attributes
*/
protected array $attributes = [];
/**
* @var array<Document> $schemaAttributes
*/
protected array $schemaAttributes = [];
/**
* @param array<Document> $attributes
* @param array<Document> $schemaAttributes
* @param int $maxAttributes
* @param int $maxWidth
* @param int $maxStringLength
* @param int $maxVarcharLength
* @param int $maxIntLength
* @param int $maxBigIntLength
* @param bool $supportForSchemaAttributes
* @param bool $supportForVectors
* @param bool $supportForSpatialAttributes
* @param bool $supportForObject
* @param callable|null $attributeCountCallback
* @param callable|null $attributeWidthCallback
* @param callable|null $filterCallback
* @param bool $isMigrating
* @param bool $sharedTables
*/
public function __construct(
array $attributes,
array $schemaAttributes = [],
protected int $maxAttributes = 0,
protected int $maxWidth = 0,
protected int $maxStringLength = 0,
protected int $maxVarcharLength = 0,
protected int $maxIntLength = 0,
protected int $maxBigIntLength = 0,
protected bool $supportForSchemaAttributes = false,
protected bool $supportForVectors = false,
protected bool $supportForSpatialAttributes = false,
protected bool $supportForObject = false,
protected mixed $attributeCountCallback = null,
protected mixed $attributeWidthCallback = null,
protected mixed $filterCallback = null,
protected bool $isMigrating = false,
protected bool $sharedTables = false,
) {
// Keep backwards compatibility for existing validator construction sites.
if ($this->maxBigIntLength === 0) {
$this->maxBigIntLength = $this->maxIntLength;
}
foreach ($attributes as $attribute) {
$key = \strtolower($attribute->getAttribute('key', $attribute->getAttribute('$id')));
$this->attributes[$key] = $attribute;
}
foreach ($schemaAttributes as $attribute) {
$key = \strtolower($attribute->getAttribute('key', $attribute->getAttribute('$id')));
$this->schemaAttributes[$key] = $attribute;
}
}
/**
* Get Type
*
* Returns validator type.
*
* @return string
*/
public function getType(): string
{
return self::TYPE_OBJECT;
}
/**
* Returns validator description
* @return string
*/
public function getDescription(): string
{
return $this->message;
}
/**
* Is array
*
* Function will return true if object is array.
*
* @return bool
*/
public function isArray(): bool
{
return false;
}
/**
* Is valid.
*
* Returns true if attribute is valid.
* @param Document $value
* @return bool
* @throws DatabaseException
* @throws DuplicateException
* @throws LimitException
*/
public function isValid($value): bool
{
if (!$this->checkDuplicateId($value)) {
return false;
}
if (!$this->checkDuplicateInSchema($value)) {
return false;
}
if (!$this->checkRequiredFilters($value)) {
return false;
}
if (!$this->checkFormat($value)) {
return false;
}
if (!$this->checkAttributeLimits($value)) {
return false;
}
if (!$this->checkType($value)) {
return false;
}
if (!$this->checkDefaultValue($value)) {
return false;
}
return true;
}
/**
* Check for duplicate attribute ID in collection metadata
*
* @param Document $attribute
* @return bool
* @throws DuplicateException
*/
public function checkDuplicateId(Document $attribute): bool
{
$id = $attribute->getAttribute('key', $attribute->getAttribute('$id'));
foreach ($this->attributes as $existingAttribute) {
if (\strtolower($existingAttribute->getId()) === \strtolower($id)) {
$this->message = 'Attribute already exists in metadata';
throw new DuplicateException($this->message);
}
}
return true;
}
/**
* Check for duplicate attribute ID in schema
*
* @param Document $attribute
* @return bool
* @throws DuplicateException
*/
public function checkDuplicateInSchema(Document $attribute): bool
{
if (!$this->supportForSchemaAttributes) {
return true;
}
if ($this->sharedTables && $this->isMigrating) {
return true;
}
$id = $attribute->getAttribute('key', $attribute->getAttribute('$id'));
foreach ($this->schemaAttributes as $schemaAttribute) {
$schemaId = $this->filterCallback ? ($this->filterCallback)($schemaAttribute->getId()) : $schemaAttribute->getId();
if (\strtolower($schemaId) === \strtolower($id)) {
$this->message = 'Attribute already exists in schema';
throw new DuplicateException($this->message);
}
}
return true;
}
/**
* Check if required filters are present for the attribute type
*
* @param Document $attribute
* @return bool
* @throws DatabaseException
*/
public function checkRequiredFilters(Document $attribute): bool
{
$type = $attribute->getAttribute('type');
$filters = $attribute->getAttribute('filters', []);
$requiredFilters = $this->getRequiredFilters($type);
if (!empty(\array_diff($requiredFilters, $filters))) {
$this->message = "Attribute of type: $type requires the following filters: " . implode(",", $requiredFilters);
throw new DatabaseException($this->message);
}
return true;
}
/**
* Get the list of required filters for each data type
*
* @param string|null $type Type of the attribute
*
* @return array<string>
*/
protected function getRequiredFilters(?string $type): array
{
return match ($type) {
Database::VAR_DATETIME => ['datetime'],
default => [],
};
}
/**
* Check if format is valid for the attribute type
*
* @param Document $attribute
* @return bool
* @throws DatabaseException
*/
public function checkFormat(Document $attribute): bool
{
$format = $attribute->getAttribute('format');
$type = $attribute->getAttribute('type');
if ($format && !Structure::hasFormat($format, $type)) {
$this->message = 'Format ("' . $format . '") not available for this attribute type ("' . $type . '")';
throw new DatabaseException($this->message);
}
return true;
}
/**
* Check attribute limits (count and width)
*
* @param Document $attribute
* @return bool
* @throws LimitException
*/
public function checkAttributeLimits(Document $attribute): bool
{
if ($this->attributeCountCallback === null || $this->attributeWidthCallback === null) {
return true;
}
$attributeCount = ($this->attributeCountCallback)($attribute);
$attributeWidth = ($this->attributeWidthCallback)($attribute);
if ($this->maxAttributes > 0 && $attributeCount > $this->maxAttributes) {
$this->message = 'Column limit reached. Cannot create new attribute. Current attribute count is ' . $attributeCount . ' but the maximum is ' . $this->maxAttributes . '. Remove some attributes to free up space.';
throw new LimitException($this->message);
}
if ($this->maxWidth > 0 && $attributeWidth >= $this->maxWidth) {
$this->message = 'Row width limit reached. Cannot create new attribute. Current row width is ' . $attributeWidth . ' bytes but the maximum is ' . $this->maxWidth . ' bytes. Reduce the size of existing attributes or remove some attributes to free up space.';
throw new LimitException($this->message);
}
return true;
}
/**
* Check attribute type and type-specific constraints
*
* @param Document $attribute
* @return bool
* @throws DatabaseException
*/
public function checkType(Document $attribute): bool
{
$type = $attribute->getAttribute('type');
$size = $attribute->getAttribute('size', 0);
$signed = $attribute->getAttribute('signed', true);
$array = $attribute->getAttribute('array', false);
$default = $attribute->getAttribute('default');
switch ($type) {
case Database::VAR_ID:
break;
case Database::VAR_STRING:
if ($size > $this->maxStringLength) {
$this->message = 'Max size allowed for string is: ' . number_format($this->maxStringLength);
throw new DatabaseException($this->message);
}
break;
case Database::VAR_VARCHAR:
if ($size > $this->maxVarcharLength) {
$this->message = 'Max size allowed for varchar is: ' . number_format($this->maxVarcharLength);
throw new DatabaseException($this->message);
}
break;
case Database::VAR_TEXT:
if ($size > 65535) {
$this->message = 'Max size allowed for text is: 65535';
throw new DatabaseException($this->message);
}
break;
case Database::VAR_MEDIUMTEXT:
if ($size > 16777215) {
$this->message = 'Max size allowed for mediumtext is: 16777215';
throw new DatabaseException($this->message);
}
break;
case Database::VAR_LONGTEXT:
if ($size > 4294967295) {
$this->message = 'Max size allowed for longtext is: 4294967295';
throw new DatabaseException($this->message);
}
break;
case Database::VAR_INTEGER:
$limit = ($signed) ? $this->maxIntLength / 2 : $this->maxIntLength;
if ($size > $limit) {
$this->message = 'Max size allowed for int is: ' . number_format($limit);
throw new DatabaseException($this->message);
}
break;
case Database::VAR_BIGINT:
break;
case Database::VAR_FLOAT:
case Database::VAR_BOOLEAN:
case Database::VAR_DATETIME:
case Database::VAR_RELATIONSHIP:
break;
case Database::VAR_OBJECT:
if (!$this->supportForObject) {
$this->message = 'Object attributes are not supported';
throw new DatabaseException($this->message);
}
if (!empty($size)) {
$this->message = 'Size must be empty for object attributes';
throw new DatabaseException($this->message);
}
if (!empty($array)) {
$this->message = 'Object attributes cannot be arrays';
throw new DatabaseException($this->message);
}
break;
case Database::VAR_POINT:
case Database::VAR_LINESTRING:
case Database::VAR_POLYGON:
if (!$this->supportForSpatialAttributes) {
$this->message = 'Spatial attributes are not supported';
throw new DatabaseException($this->message);
}
if (!empty($size)) {
$this->message = 'Size must be empty for spatial attributes';
throw new DatabaseException($this->message);
}
if (!empty($array)) {
$this->message = 'Spatial attributes cannot be arrays';
throw new DatabaseException($this->message);
}
break;
case Database::VAR_VECTOR:
if (!$this->supportForVectors) {
$this->message = 'Vector types are not supported by the current database';
throw new DatabaseException($this->message);
}
if ($array) {
$this->message = 'Vector type cannot be an array';
throw new DatabaseException($this->message);
}
if ($size <= 0) {
$this->message = 'Vector dimensions must be a positive integer';
throw new DatabaseException($this->message);
}
if ($size > Database::MAX_VECTOR_DIMENSIONS) {
$this->message = 'Vector dimensions cannot exceed ' . Database::MAX_VECTOR_DIMENSIONS;
throw new DatabaseException($this->message);
}
// Validate default value if provided
if ($default !== null) {
if (!is_array($default)) {
$this->message = 'Vector default value must be an array';
throw new DatabaseException($this->message);
}
if (count($default) !== $size) {
$this->message = 'Vector default value must have exactly ' . $size . ' elements';
throw new DatabaseException($this->message);
}
foreach ($default as $component) {
if (!is_numeric($component)) {
$this->message = 'Vector default value must contain only numeric elements';
throw new DatabaseException($this->message);
}
}
}
break;
default:
$supportedTypes = [
Database::VAR_STRING,
Database::VAR_VARCHAR,
Database::VAR_TEXT,
Database::VAR_MEDIUMTEXT,
Database::VAR_LONGTEXT,
Database::VAR_INTEGER,
Database::VAR_FLOAT,
Database::VAR_BOOLEAN,
Database::VAR_DATETIME,
Database::VAR_RELATIONSHIP
];
if ($this->supportForVectors) {
$supportedTypes[] = Database::VAR_VECTOR;
}
if ($this->supportForSpatialAttributes) {
\array_push($supportedTypes, ...Database::SPATIAL_TYPES);
}
if ($this->supportForObject) {
$supportedTypes[] = Database::VAR_OBJECT;
}
$this->message = 'Unknown attribute type: ' . $type . '. Must be one of ' . implode(', ', $supportedTypes);
throw new DatabaseException($this->message);
}
return true;
}
/**
* Check default value constraints and type matching
*
* @param Document $attribute
* @return bool
* @throws DatabaseException
*/
public function checkDefaultValue(Document $attribute): bool
{
$default = $attribute->getAttribute('default');
$required = $attribute->getAttribute('required', false);
$type = $attribute->getAttribute('type');
$array = $attribute->getAttribute('array', false);
if (\is_null($default)) {
return true;
}
if ($required === true) {
$this->message = 'Cannot set a default value for a required attribute';
throw new DatabaseException($this->message);
}
// Reject array defaults for non-array attributes (except vectors, spatial types, and objects which use arrays internally)
if (\is_array($default) && !$array && !\in_array($type, [Database::VAR_VECTOR, Database::VAR_OBJECT, ...Database::SPATIAL_TYPES], true)) {
$this->message = 'Cannot set an array default value for a non-array attribute';
throw new DatabaseException($this->message);
}
$this->validateDefaultTypes($type, $default);
return true;
}
/**
* Function to validate if the default value of an attribute matches its attribute type
*
* @param string $type Type of the attribute
* @param mixed $default Default value of the attribute
*
* @return void
* @throws DatabaseException
*/
protected function validateDefaultTypes(string $type, mixed $default): void
{
$defaultType = \gettype($default);
if ($defaultType === 'NULL') {
// Disable null. No validation required
return;
}
if ($defaultType === 'array') {
// Spatial types require the array itself
if (!in_array($type, Database::SPATIAL_TYPES) && $type != Database::VAR_OBJECT) {
foreach ($default as $value) {
$this->validateDefaultTypes($type, $value);
}
}
return;
}
switch ($type) {
case Database::VAR_STRING:
case Database::VAR_VARCHAR:
case Database::VAR_TEXT:
case Database::VAR_MEDIUMTEXT:
case Database::VAR_LONGTEXT:
if ($defaultType !== 'string') {
$this->message = 'Default value ' . $default . ' does not match given type ' . $type;
throw new DatabaseException($this->message);
}
break;
case Database::VAR_INTEGER:
case Database::VAR_FLOAT:
case Database::VAR_BOOLEAN:
if ($type !== $defaultType) {
$this->message = 'Default value ' . $default . ' does not match given type ' . $type;
throw new DatabaseException($this->message);
}
break;
case Database::VAR_DATETIME:
if ($defaultType !== Database::VAR_STRING) {
$this->message = 'Default value ' . $default . ' does not match given type ' . $type;
throw new DatabaseException($this->message);
}
break;
case Database::VAR_VECTOR:
// When validating individual vector components (from recursion), they should be numeric
if ($defaultType !== 'double' && $defaultType !== 'integer') {
$this->message = 'Vector components must be numeric values (float or integer)';
throw new DatabaseException($this->message);
}
break;
default:
$supportedTypes = [
Database::VAR_STRING,
Database::VAR_VARCHAR,
Database::VAR_TEXT,
Database::VAR_MEDIUMTEXT,
Database::VAR_LONGTEXT,
Database::VAR_INTEGER,
Database::VAR_FLOAT,
Database::VAR_BOOLEAN,
Database::VAR_DATETIME,
Database::VAR_RELATIONSHIP
];
if ($this->supportForVectors) {
$supportedTypes[] = Database::VAR_VECTOR;
}
if ($this->supportForSpatialAttributes) {
\array_push($supportedTypes, ...Database::SPATIAL_TYPES);
}
$this->message = 'Unknown attribute type: ' . $type . '. Must be one of ' . implode(', ', $supportedTypes);
throw new DatabaseException($this->message);
}
}
}