Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,28 @@
## 1.35.2

- `DBSQLMemoryAdapter`: single-field unique constraints
(`@EntityField.unique()`) are now enforced as by the SQL databases:
- On an `EntityReference` field: the entity's value (the `EntityReference`
object) was compared with the stored value (the referenced ID), so it
never conflicted. `EntityFieldInvalid.value` of such a violation is the
referenced ID.
- On a camelCase field (e.g. `externalCode`, stored as `external_code`):
the stored entry was read by the field name only, so it never
conflicted. **In-memory tests storing duplicates of such a field now
fail, as they would on PostgreSQL/MySQL/SQLite.**
- An `enum` field is compared by its stored name.

The single-field and composite (`@EntityIndex(unique: true)`) constraints
are now checked together: the entity's values normalized once, in their
stored form, and a `null` value never conflicting. Values of the same
type are now the same only by `==` (no longer also by `toString()`).
- `SetEntityRepository`: a unique `EntityReference` field compares the
referenced ID, and a null reference never conflicts (two rows with a null
reference were a violation; a reference by entity and one by ID could
differ).
- Test: the unsendable-`Zone` isolate test accepts Dart 3.14's message
(`Class: Zone`, was `_CustomZone`).

## 1.35.1

- Private fields that only memoize a public getter or method of the same
Expand Down
2 changes: 1 addition & 1 deletion lib/src/bones_api_base.dart
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ typedef APILogger = void Function(
/// Bones API Library class.
class BonesAPI {
// ignore: constant_identifier_names
static const String VERSION = '1.35.1';
static const String VERSION = '1.35.2';

static bool _boot = false;

Expand Down
21 changes: 18 additions & 3 deletions lib/src/bones_api_entity.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8818,7 +8818,9 @@ abstract class IterableEntityRepository<O extends Object>

for (var e in uniques) {
var field = e.key;
var value = getField(o, field);
var value = _uniqueComparableValue(getField(o, field));
// As the SQL databases: a `null` value (or a null reference) never
// conflicts.
if (value == null) continue;

if (_containsOtherEntryWithFieldValue(o, field, value)) {
Expand All @@ -8833,16 +8835,29 @@ abstract class IterableEntityRepository<O extends Object>
}
}

/// The [value] of a unique field as compared by [checkEntityFields] and
/// [_containsOtherEntryWithFieldValue]: an `EntityReference` by its
/// referenced ID (or its entity, if not stored yet), and `null` for a null
/// reference (that, as `null`, never conflicts). `EntityReference.==` would
/// make two null references equal, and a reference set by entity differ
/// from one set by ID.
static Object? _uniqueComparableValue(Object? value) => switch (value) {
EntityReference() => value.isNull ? null : (value.id ?? value.entity),
EntityReferenceList() => value.isNull ? null : value,
_ => value,
};

/// Whether an entry other than [o] (not the same instance, nor with the
/// same ID: a re-stored entity) has the [field] [value].
/// same ID: a re-stored entity) has the [field] [value] (already as
/// [_uniqueComparableValue]).
bool _containsOtherEntryWithFieldValue(O o, String field, Object value) {
var id = entityHandler.getID(o);

return iterable().any((elem) {
if (identical(elem, o)) return false;
if (id != null && entityHandler.getID(elem) == id) return false;

var elemValue = getField(elem, field);
var elemValue = _uniqueComparableValue(getField(elem, field));
return elemValue == value;
});
}
Expand Down
111 changes: 53 additions & 58 deletions lib/src/bones_api_entity_db_memory.dart
Original file line number Diff line number Diff line change
Expand Up @@ -401,60 +401,47 @@ class DBSQLMemoryAdapter extends DBSQLAdapter<DBSQLMemoryAdapterContext>
o,
);

var uniques =
fieldsEntityAnnotations?.entries
.where((e) => e.value.hasUnique)
.toList() ??
[];
// The unique constraints, by their fields: the single-field ones
// (`@EntityField.unique()`) and the composite ones
// (`@EntityIndex(unique: true)`), checked the same way.
var uniquesFields = <List<String>>[
...?fieldsEntityAnnotations?.entries
.where((e) => e.value.hasUnique)
.map((e) => [e.key]),
for (var entityIndex in entityHandler.getEntityIndexes())
if (entityIndex.unique) entityIndex.fields,
];
if (uniquesFields.isEmpty) return;

// The entity's values in their stored form (normalized as an entry: e.g.
// an `EntityReference` as its referenced ID, not the reference object),
// so they are comparable with the stored entries. Normalized once for
// all the constraints.
var values = _normalizeEntityJSON(
{
for (var f in uniquesFields.expand((fields) => fields))
f: entityHandler.getField(o, f),
},
entityName: entityName,
table: table,
);

for (var e in uniques) {
var field = e.key;
var value = entityHandler.getField(o, field);
if (value == null) continue;
for (var fields in uniquesFields) {
// As the SQL databases: a `null` value never conflicts.
if (fields.any((f) => values[f] == null)) continue;

if (_containsEntryWithConflictFieldValue(
if (_containsEntryWithConflictFieldsValues(
map,
entityHandler,
entityId,
field,
value,
fields,
values,
)) {
var single = fields.length == 1;
throw EntityFieldInvalid(
'unique',
value,
fieldName: field,
entityType: entityHandler.type,
tableName: table,
);
}
}

// The composite unique constraints (`@EntityIndex(unique: true)`), as
// the SQL databases: a `null` value never conflicts.
for (var entityIndex in entityHandler.getEntityIndexes()) {
if (!entityIndex.unique) continue;

var fields = entityIndex.fields;

var values = _normalizeEntityJSON({
for (var f in fields) f: entityHandler.getField(o, f),
}, table: table);
if (values.values.any((v) => v == null)) continue;

var conflict = map.entries.any((e) {
if (entityId != null && entityId == e.key) return false;
var elem = e.value;
return fields.every(
(f) => _sameValue(_entryFieldValue(elem, f), values[f]),
);
});

if (conflict) {
throw EntityFieldInvalid(
'unique',
fields.map((f) => values[f]).toList(),
single ? values[fields.first] : fields.map((f) => values[f]).toList(),
fieldName: fields.join(', '),
fieldsNames: fields,
fieldsNames: single ? null : fields,
entityType: entityHandler.type,
tableName: table,
);
Expand All @@ -464,9 +451,15 @@ class DBSQLMemoryAdapter extends DBSQLAdapter<DBSQLMemoryAdapterContext>

/// Whether a stored value [a] and an entity's value [b] are the same, as
/// stored (e.g. an `enum` by its name).
///
/// The stored forms are compared only when the types differ (an entity's
/// `Enum` against its stored name): values of the same type are only the
/// same by `==` (two distinct values of a class without a distinctive
/// `toString` are not the same).
static bool _sameValue(Object? a, Object? b) {
if (a == b) return true;
if (a == null || b == null) return false;
if (a.runtimeType == b.runtimeType) return false;
return _storedForm(a) == _storedForm(b);
}

Expand All @@ -482,22 +475,24 @@ class DBSQLMemoryAdapter extends DBSQLAdapter<DBSQLMemoryAdapterContext>
? entry[field]
: entry[normalizeColumnName(field)];

bool _containsEntryWithConflictFieldValue<O>(
/// Whether a stored entry of [map], other than [entityId]'s own, has the
/// same [values] in all the [fields] (a unique constraint conflict).
///
/// Used by [checkEntityFields] for each unique constraint (single-field or
/// composite), with the entity's [values] already in their stored form:
/// each entry's field is read by name or column ([_entryFieldValue]) and
/// compared with [_sameValue].
bool _containsEntryWithConflictFieldsValues(
Map<Object, Map<String, dynamic>> map,
EntityHandler<O> entityHandler,
Object? entityId,
String field,
value,
List<String> fields,
Map<String, dynamic> values,
) => map.entries.any((e) {
if (entityId != null) {
var id = e.key;
if (entityId == id) return false;
}

if (entityId != null && entityId == e.key) return false;
var elem = e.value;
var elemValue = elem[field];
var conflict = elemValue == value;
return conflict;
return fields.every(
(f) => _sameValue(_entryFieldValue(elem, f), values[f]),
);
});

@override
Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: bones_api
description: Bones_API - A powerful API backend framework for Dart. It comes with a built-in HTTP Server, route handler, entity handler, SQL translator, and DB adapters.
version: 1.35.1
version: 1.35.2
homepage: https://github.com/Colossus-Services/bones_api

environment:
Expand Down
5 changes: 4 additions & 1 deletion test/bones_api_cov_root_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -605,11 +605,14 @@ void main() {
await root.ensureInitialized();
var zoneField = root.currentAPIRequest;

// The unsendable object is a `Zone`. The SDK names its class in the
// message: `_CustomZone` (Dart < 3.14) or `Zone` (Dart 3.14), so only
// `Zone` is matched (as a class name, not just the word "zone").
Matcher unsendable() => throwsA(
isA<ArgumentError>().having(
(e) => e.toString(),
'message',
contains('_CustomZone'),
matches(RegExp(r'Class: _?\w*Zone\b|_CustomZone')),
),
);

Expand Down
Loading
Loading