From db1b1771c23f487f61d07b8944652968df3a5b2f Mon Sep 17 00:00:00 2001 From: "Graciliano M. P." Date: Sun, 8 Nov 2026 05:16:44 -0300 Subject: [PATCH 1/6] Refactor entity rules: shared merge/flatten/scan helpers, cache naming - EntityResolutionRules.merge: the tri-state flag merge -> _mergeFlag; the tolerant/intolerant mirror arms -> _mergeTypesDroppingConflict. - fetchTypes: four near-identical lambdas -> _typesWhere. - EntityAccessRules: _flattenGroup, _conditionMatches, _lastDefined; the block arm returns fieldRule directly. - EntityAccessRulesCached: cache fields named *Cache and documented. - EntityRulesResolver.contextProviders (cotextProviders kept, deprecated). Co-Authored-By: Claude Opus 5.5 --- lib/src/bones_api_entity_rules.dart | 337 +++++++++++----------- test/bones_api_cov_entity_rules_test.dart | 5 +- 2 files changed, 175 insertions(+), 167 deletions(-) diff --git a/lib/src/bones_api_entity_rules.dart b/lib/src/bones_api_entity_rules.dart index ea2bde34..ce72beca 100644 --- a/lib/src/bones_api_entity_rules.dart +++ b/lib/src/bones_api_entity_rules.dart @@ -270,14 +270,9 @@ class EntityAccessRules extends EntityRules { final entityFields = this.entityFields; var fieldRule = entityFields != null && entityFields.isNotEmpty; - // If blocks a field it's not fully blocking a type: - if (fieldRule) { - return true; - } + // If blocks a field it's not fully blocking a type (allowed). // If there's NO field rule, the type is being blocked: - else { - return false; - } + return fieldRule; } case EntityAccessRuleType.mask: { @@ -291,17 +286,37 @@ class EntityAccessRules extends EntityRules { } } - final rules = this.rules; + return _lastDefined(rules, (r) => r.isAllowedEntityType(type)); + } + + /// Scans [rules] from the last to the first and returns the first + /// non-`null` [decision]: a later rule overrides an earlier one. Returns + /// `null` when no rule decides (or [rules] is `null`/empty). + /// + /// Used by [isAllowedEntityType], [isAllowedEntityTypeField] and + /// [isMaskedEntityTypeField] to delegate to the sub-rules. It's `static` + /// since [EntityAccessRules] is implemented by other classes. + static bool? _lastDefined( + List? rules, + bool? Function(EntityAccessRules rule) decision, + ) { if (rules == null || rules.isEmpty) return null; for (var r in rules.reversed) { - var allowed = r.isAllowedEntityType(type); - if (allowed != null) return allowed; + var decided = decision(r); + if (decided != null) return decided; } return null; } + /// Returns `true` if [condition] is absent (an unconditional rule) or + /// accepts [context]. Used by the field allow/block/mask checks. + static bool _conditionMatches( + EntityAccessRulesCondition? condition, + EntityAccessRulesContext? context, + ) => condition == null || condition(context); + bool hasRuleType(List ruleTypes) { if (ruleTypes.isEmpty) return false; @@ -341,7 +356,7 @@ class EntityAccessRules extends EntityRules { case EntityAccessRuleType.allow: { if (entityFields.anyIgnoreCase(field)) { - var allowed = condition == null || condition(context); + var allowed = _conditionMatches(condition, context); return allowed; } else { return null; @@ -350,7 +365,7 @@ class EntityAccessRules extends EntityRules { case EntityAccessRuleType.block: { if (entityFields.anyIgnoreCase(field)) { - var allowed = condition == null || condition(context); + var allowed = _conditionMatches(condition, context); var blocked = !allowed; return blocked; } else { @@ -368,15 +383,10 @@ class EntityAccessRules extends EntityRules { } } - final rules = this.rules; - if (rules == null || rules.isEmpty) return null; - - for (var r in rules.reversed) { - var allowed = r.isAllowedEntityTypeField(type, field, context: context); - if (allowed != null) return allowed; - } - - return null; + return _lastDefined( + rules, + (r) => r.isAllowedEntityTypeField(type, field, context: context), + ); } bool? isMaskedEntityTypeField( @@ -392,8 +402,7 @@ class EntityAccessRules extends EntityRules { if (entityType == type) { if (ruleType == EntityAccessRuleType.mask) { if (entityFields.anyIgnoreCase(field)) { - final condition = this.condition; - return (condition == null || condition(context)); + return _conditionMatches(condition, context); } else { return null; } @@ -402,15 +411,10 @@ class EntityAccessRules extends EntityRules { if (direct) return false; - final rules = this.rules; - if (rules == null || rules.isEmpty) return null; - - for (var r in rules.reversed) { - var masked = r.isMaskedEntityTypeField(type, field, context: context); - if (masked != null) return masked; - } - - return null; + return _lastDefined( + rules, + (r) => r.isMaskedEntityTypeField(type, field, context: context), + ); } V applyMask( @@ -575,12 +579,7 @@ class EntityAccessRules extends EntityRules { .where((r) => !r.isInnocuous) .map((r) => r.simplified()); - var rulesSimpleFlat = rulesSimple.expand((r) { - var rules = r.rules; - return rules != null && rules.isNotEmpty && r.entityType == null - ? rules - : [r]; - }).toList(); + var rulesSimpleFlat = rulesSimple.expand(_flattenGroup).toList(); if (entityType != null) { var r1 = copyWith(rules: []); @@ -607,25 +606,24 @@ class EntityAccessRules extends EntityRules { return other; } - var a = simplified(); - var b = other.simplified(); - - var rulesA = a.rules; - var rulesB = b.rules; - - var listA = rulesA != null && rulesA.isNotEmpty && a.entityType == null - ? rulesA - : [a]; - - var listB = rulesB != null && rulesB.isNotEmpty && b.entityType == null - ? rulesB - : [b]; - - var allRules = [...listA, ...listB]; + var allRules = [ + ..._flattenGroup(simplified()), + ..._flattenGroup(other.simplified()), + ]; return EntityAccessRules.group(allRules); } + /// Returns the sub-rules of [rule] when it's a pure group (sub-rules and + /// no [entityType]), otherwise `[rule]` itself. Used by [simplified] and + /// [merge] to avoid nesting groups inside groups. + static List _flattenGroup(EntityAccessRules rule) { + var rules = rule.rules; + return rules != null && rules.isNotEmpty && rule.entityType == null + ? rules + : [rule]; + } + static final _rulesListEquality = ListEquality(); @override @@ -777,10 +775,12 @@ class EntityAccessRulesCached implements EntityAccessRules { EntityAccessRulesCached(this.accessRules); - int? _totalRules; + /// Cache of [totalRules]: the rule tree is immutable, so the count is + /// computed (a full traversal) only once. + int? _totalRulesCache; @override - int totalRules() => _totalRules ??= accessRules.totalRules(); + int totalRules() => _totalRulesCache ??= accessRules.totalRules(); @override bool? get _innocuous => accessRules._innocuous; @@ -821,29 +821,33 @@ class EntityAccessRulesCached implements EntityAccessRules { @override bool get _simplified => accessRules._simplified; - final Map _hasRuleForEntityType = {}; + /// Cache of [hasRuleForEntityType] results by entity [Type]: called for + /// every object encoded to JSON, and each call walks the rule tree. + final Map _hasRuleForEntityTypeCache = {}; @override - bool hasRuleForEntityType(Type type) => _hasRuleForEntityType.putIfAbsent( - type, - () => accessRules.hasRuleForEntityType(type), - ); + bool hasRuleForEntityType(Type type) => _hasRuleForEntityTypeCache + .putIfAbsent(type, () => accessRules.hasRuleForEntityType(type)); - final Map<_CacheKey, bool> _hasRuleType = <_CacheKey, bool>{}; + /// Cache of [hasRuleType] results, keyed by the (element-wise compared) + /// list of rule types queried: each call walks the rule tree. + final Map<_CacheKey, bool> _hasRuleTypeCache = <_CacheKey, bool>{}; @override bool hasRuleType(List ruleTypes) { final cacheKey = _CacheKey(ruleTypes); - return _hasRuleType.putIfAbsent( + return _hasRuleTypeCache.putIfAbsent( cacheKey, () => accessRules.hasRuleType(ruleTypes), ); } - final Map _hasRuleForEntityTypeField = {}; + /// Cache of [hasRuleForEntityTypeField] results by entity [Type]: called + /// for every object encoded to JSON, and each call walks the rule tree. + final Map _hasRuleForEntityTypeFieldCache = {}; @override - bool hasRuleForEntityTypeField(Type type) => _hasRuleForEntityTypeField + bool hasRuleForEntityTypeField(Type type) => _hasRuleForEntityTypeFieldCache .putIfAbsent(type, () => accessRules.hasRuleForEntityTypeField(type)); @override @@ -1213,39 +1217,10 @@ class EntityResolutionRules extends EntityRules { Map? lazyTypes, bool mergeTolerant = false, }) { - var eagerTypesNotNull = eagerTypes?.entries.map((e) { - var eager = e.value; - return eager != null ? MapEntry(e.key, eager) : null; - }).nonNulls; - - var lazyTypesNotNull = lazyTypes?.entries.map((e) { - var lazy = e.value; - return lazy != null ? MapEntry(e.key, lazy) : null; - }).nonNulls; - - var fetchEager = eagerTypesNotNull?.map((e) { - var t = e.key; - var eager = e.value; - return eager ? t : null; - }); - - var fetchNotEager = eagerTypesNotNull?.map((e) { - var t = e.key; - var eager = e.value; - return !eager ? t : null; - }); - - var fetchLazy = lazyTypesNotNull?.map((e) { - var t = e.key; - var lazy = e.value; - return lazy ? t : null; - }); - - var fetchNotLazy = lazyTypesNotNull?.map((e) { - var t = e.key; - var lazy = e.value; - return !lazy ? t : null; - }); + var fetchEager = _typesWhere(eagerTypes, true); + var fetchNotEager = _typesWhere(eagerTypes, false); + var fetchLazy = _typesWhere(lazyTypes, true); + var fetchNotLazy = _typesWhere(lazyTypes, false); var eagerEntityTypes = [...?fetchEager, ...?fetchNotLazy].nonNulls .expand((e) => e is Iterable ? e : [e]) @@ -1282,6 +1257,15 @@ class EntityResolutionRules extends EntityRules { ); } + /// Returns the keys of [typesFlags] whose flag is [wanted], used by + /// [EntityResolutionRules.fetchTypes]. A `null` flag means "no rule" and + /// is never selected. A key can be a [Type] or an [Iterable] of [Type]s + /// (expanded by the caller). + static Iterable? _typesWhere( + Map? typesFlags, + bool wanted, + ) => typesFlags?.entries.where((e) => e.value == wanted).map((e) => e.key); + /// Returns `true` if this instance is equivalent to [innocuous] instance (no resolution rules to apply). @override bool get isInnocuous { @@ -1453,52 +1437,31 @@ class EntityResolutionRules extends EntityRules { var bothMergeTolerant = mergeTolerant && other.mergeTolerant; - var allowEntityFetch = _allowEntityFetch; - if (other._allowEntityFetch != null) { - if (allowEntityFetch == null) { - allowEntityFetch = other._allowEntityFetch; - } else if (allowEntityFetch != other._allowEntityFetch) { - if (bothMergeTolerant) { - allowEntityFetch = null; - } else if (mergeTolerant) { - allowEntityFetch = other._allowEntityFetch; - } else if (!other.mergeTolerant) { - throw MergeEntityRulesError(this, other, 'allowEntityFetch'); - } - } - } + var allowEntityFetch = _mergeFlag( + this, + other, + _allowEntityFetch, + other._allowEntityFetch, + 'allowEntityFetch', + ); var allowReadFile = this.allowReadFile || other.allowReadFile; - var allLazy = this.allLazy; - if (other.allLazy != null) { - if (allLazy == null) { - allLazy = other.allLazy; - } else if (allLazy != other.allLazy) { - if (bothMergeTolerant) { - allLazy = null; - } else if (mergeTolerant) { - allLazy = other.allLazy; - } else if (!other.mergeTolerant) { - throw MergeEntityRulesError(this, other, 'allLazy'); - } - } - } + var allLazy = _mergeFlag( + this, + other, + this.allLazy, + other.allLazy, + 'allLazy', + ); - var allEager = this.allEager; - if (other.allEager != null) { - if (allEager == null) { - allEager = other.allEager; - } else if (allEager != other.allEager) { - if (bothMergeTolerant) { - allEager = null; - } else if (mergeTolerant) { - allEager = other.allEager; - } else if (!other.mergeTolerant) { - throw MergeEntityRulesError(this, other, 'allEager'); - } - } - } + var allEager = _mergeFlag( + this, + other, + this.allEager, + other.allEager, + 'allEager', + ); var lazyEntityTypes = this.lazyEntityTypes .merge(other.lazyEntityTypes) @@ -1525,26 +1488,23 @@ class EntityResolutionRules extends EntityRules { if (bothMergeTolerant) { merge = merge.copyWith(conflictingEntityTypes: conflict); } else { - List? lazyEntityTypes; - List? eagerEntityTypes; - - if (mergeTolerant) { - lazyEntityTypes = this.lazyEntityTypes - .without(conflict) - .merge(other.lazyEntityTypes); - - eagerEntityTypes = this.eagerEntityTypes - .without(conflict) - .merge(other.eagerEntityTypes); - } else if (other.mergeTolerant) { - lazyEntityTypes = other.lazyEntityTypes - .without(conflict) - .merge(this.lazyEntityTypes); - - eagerEntityTypes = other.eagerEntityTypes - .without(conflict) - .merge(this.eagerEntityTypes); - } + // Exactly one side is tolerant: it yields the conflicting types to + // the intolerant side. + var (tolerant, intolerant) = mergeTolerant + ? (this, other) + : (other, this); + + var lazyEntityTypes = _mergeTypesDroppingConflict( + tolerant.lazyEntityTypes, + intolerant.lazyEntityTypes, + conflict, + ); + + var eagerEntityTypes = _mergeTypesDroppingConflict( + tolerant.eagerEntityTypes, + intolerant.eagerEntityTypes, + conflict, + ); merge = EntityResolutionRules( allowEntityFetch: allowEntityFetch, @@ -1563,6 +1523,46 @@ class EntityResolutionRules extends EntityRules { return merge; } + /// Merges one tri-state flag (`allowEntityFetch`, `allLazy`, `allEager`) + /// of [mine] and [theirs], used by [merge]: + /// - A `null` side yields to the other side. + /// - On a conflict: both [EntityResolutionRules.mergeTolerant] drop the + /// flag (`null`); a tolerant [mine] yields to [theirsValue]; an intolerant + /// [mine] facing an intolerant [theirs] throws a [MergeEntityRulesError] + /// naming [name]; otherwise [mineValue] is kept. + /// + /// It's `static` because [EntityResolutionRules] is implemented (not + /// extended) by other classes, which would otherwise have to forward it. + static bool? _mergeFlag( + EntityResolutionRules mine, + EntityResolutionRules theirs, + bool? mineValue, + bool? theirsValue, + String name, + ) { + if (theirsValue == null) return mineValue; + if (mineValue == null || mineValue == theirsValue) return theirsValue; + + if (mine.mergeTolerant && theirs.mergeTolerant) { + return null; + } else if (mine.mergeTolerant) { + return theirsValue; + } else if (!theirs.mergeTolerant) { + throw MergeEntityRulesError(mine, theirs, name); + } + + return mineValue; + } + + /// Merges [tolerantTypes] (without the [conflict] types) with + /// [intolerantTypes], used by [merge] when only one side is + /// [mergeTolerant]: the tolerant side gives up its conflicting types. + static List? _mergeTypesDroppingConflict( + List? tolerantTypes, + List? intolerantTypes, + List conflict, + ) => tolerantTypes.without(conflict).merge(intolerantTypes); + static final ListEquality _listEqualityType = ListEquality(); @override @@ -1870,23 +1870,28 @@ abstract class EntityRulesContextProvider { /// Mixin to resolve the [EntityResolutionRules] to apply. mixin EntityRulesResolver { - static final Set _cotextProviders = + static final Set _contextProviders = {}; static EntityRulesContextProvider? _singleContextProvider; static void _updateSingleContextProvider() => _singleContextProvider = - _cotextProviders.length == 1 ? _cotextProviders.first : null; + _contextProviders.length == 1 ? _contextProviders.first : null; /// Returns the current [EntityRulesContextProvider]s. + static List get contextProviders => + _contextProviders.toList(); + + /// Deprecated misspelling of [contextProviders]. + @Deprecated('Use `contextProviders`') static List get cotextProviders => - _cotextProviders.toList(); + contextProviders; /// Register an [EntityRulesContextProvider]. static bool registerContextProvider( EntityRulesContextProvider contextProvider, ) { - var added = _cotextProviders.add(contextProvider); + var added = _contextProviders.add(contextProvider); _updateSingleContextProvider(); return added; } @@ -1895,7 +1900,7 @@ mixin EntityRulesResolver { static bool unregisterContextProvider( EntityRulesContextProvider contextProvider, ) { - var removed = _cotextProviders.remove(contextProvider); + var removed = _contextProviders.remove(contextProvider); _updateSingleContextProvider(); return removed; } @@ -1908,7 +1913,7 @@ mixin EntityRulesResolver { var resolutionRules = singleContextProvider .getContextEntityResolutionRules(contextZone: Zone.current); return resolutionRules; - } else if (_cotextProviders.isEmpty) { + } else if (_contextProviders.isEmpty) { return null; } @@ -1916,7 +1921,7 @@ mixin EntityRulesResolver { EntityResolutionRules? contextRule; - for (var c in _cotextProviders) { + for (var c in _contextProviders) { var resolutionRules = c.getContextEntityResolutionRules( contextZone: zone, ); diff --git a/test/bones_api_cov_entity_rules_test.dart b/test/bones_api_cov_entity_rules_test.dart index 861d0656..83a4508d 100644 --- a/test/bones_api_cov_entity_rules_test.dart +++ b/test/bones_api_cov_entity_rules_test.dart @@ -689,6 +689,9 @@ void main() { expect(EntityRulesResolver.registerContextProvider(p3), isTrue); try { + expect(EntityRulesResolver.contextProviders.length, equals(3)); + // The deprecated misspelled alias still works: + // ignore: deprecated_member_use_from_same_package expect(EntityRulesResolver.cotextProviders.length, equals(3)); var context = resolver.getContextEntityResolutionRules()!; @@ -722,7 +725,7 @@ void main() { EntityRulesResolver.unregisterContextProvider(p3); } - expect(EntityRulesResolver.cotextProviders, isEmpty); + expect(EntityRulesResolver.contextProviders, isEmpty); }); test('resolved context provider', () { From e5d82b19df00b6b388bc7eff3afcaa798d469268 Mon Sep 17 00:00:00 2001 From: "Graciliano M. P." Date: Sun, 8 Nov 2026 05:19:35 -0300 Subject: [PATCH 2/6] Refactor entity model: shared helpers, cache naming, O(1) op lookups - Equality: _equalsValuesScalar (the DateTime/Time/DynamicNumber/primitive/ enum chain of equalsValues and equalsValuesBasic), _isCollectionLike, _entityHandlerForValue; comparisons via _compareAsNumbers. - greaterThanValue/greaterThanOrEqualValue; the misspelled graterThan* kept as @Deprecated forwarders. - Provider lookups: _asReiterable (documented), Iterable getEntityRepositoryByTypeInfo calls the Impl; _whereNotClosed without the redundant parameter; _openRepositoryOrNull; allRepositories uses traversed.add. - Transaction: identity-set caches beside _operations/_executedOperations for O(1) membership (bulk storeAll was O(n^2)). - Cascade delete: _addSubEntitiesDeleteCalls; _resolveRepositoryProvider renamed _resolveEntityRepository. - storeAllFromJson: _createAndStoreAll, named block-size constants; _logCreateFromMapError; _isFieldChanged; seed JSON _toEntitiesJson; resolveEntitySourceValueVariables flattened. - Handlers: _getCachedFieldType (shared by Generic/ClassReflection getFieldType), _inspectedOrThrow; list resolution hoisted; _resolveEntityHandler without always-true guards. - TransactionOperation: _describe() for the toString heads; TransactionOperationType.name is (this as Enum).name. - IterableEntityRepository: _relationshipFieldType, _matchesEntity, hasReferencedEntities explained. - Private cache fields named *Cache and documented (EntityHandler, GenericEntityHandler, ClassReflectionEntityHandler). Co-Authored-By: Claude Opus 5.5 --- lib/src/bones_api_entity.dart | 1487 ++++++++++--------- test/bones_api_cov_entity_handler_test.dart | 18 +- 2 files changed, 786 insertions(+), 719 deletions(-) diff --git a/lib/src/bones_api_entity.dart b/lib/src/bones_api_entity.dart index 0e684d8f..b51fe38e 100644 --- a/lib/src/bones_api_entity.dart +++ b/lib/src/bones_api_entity.dart @@ -13,8 +13,7 @@ import 'package:statistics/statistics.dart' DynamicInt, DynamicNumber, IterableMapEntryExtension, - NumericTypeExtension, - IterableExtension; + NumericTypeExtension; import 'package:swiss_knife/swiss_knife.dart' show EventStream, DataURLBase64; import 'bones_api_base.dart'; @@ -567,9 +566,11 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { entities.map((o) => MapEntry(getIDFromMap(o), o)), ); - Type? _idType; + /// Cache of [idType]: the [Type] of the ID field, fixed per entity type + /// and looked up on every ID parse/compare. + Type? _idTypeCache; - Type idType([O? o]) => _idType ??= getFieldType( + Type idType([O? o]) => _idTypeCache ??= getFieldType( o, idFieldName(o), resolveFiledName: false, @@ -581,15 +582,24 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { Map fieldsTypes([O? o]); - Map? _fieldsWithTypeList; + // The `fieldsWith*` caches below hold filtered views of [fieldsTypes]. + // The fields of an entity type are fixed, so each filter runs once. - Map fieldsWithTypeList([O? o]) => _fieldsWithTypeList ??= - fieldsWithType((_, fieldType) => fieldType.isList, o); + /// Cache of [fieldsWithTypeList]: the fields of a `List` type. + Map? _fieldsWithTypeListCache; - Map? _fieldsWithTypeEntity; + Map fieldsWithTypeList([O? o]) => + _fieldsWithTypeListCache ??= fieldsWithType( + (_, fieldType) => fieldType.isList, + o, + ); + + /// Cache of [fieldsWithTypeEntity]: the fields holding an entity + /// (not an [EntityReference]). + Map? _fieldsWithTypeEntityCache; Map fieldsWithTypeEntity([O? o]) => - _fieldsWithTypeEntity ??= fieldsWithType( + _fieldsWithTypeEntityCache ??= fieldsWithType( (_, fieldType) => !fieldType.isBasicType && !fieldType.isEntityReferenceListType && @@ -598,10 +608,12 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { o, ); - Map? _fieldsWithTypeEntityOrReference; + /// Cache of [fieldsWithTypeEntityOrReference]: the fields holding an + /// entity or an [EntityReference]. + Map? _fieldsWithTypeEntityOrReferenceCache; Map fieldsWithTypeEntityOrReference([O? o]) => - _fieldsWithTypeEntityOrReference ??= fieldsWithType( + _fieldsWithTypeEntityOrReferenceCache ??= fieldsWithType( (_, fieldType) => (!fieldType.isBasicType && !fieldType.isEntityReferenceListType && @@ -611,56 +623,68 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { o, ); - Map? _fieldsWithEntityReference; + /// Cache of [fieldsWithEntityReference]: the fields of an + /// [EntityReference] type. + Map? _fieldsWithEntityReferenceCache; Map fieldsWithEntityReference([O? o]) => - _fieldsWithEntityReference ??= Map.unmodifiable( + _fieldsWithEntityReferenceCache ??= Map.unmodifiable( fieldsWithTypeEntityOrReference(o).entries .where((e) => e.value.isEntityReferenceType) .toMapFromEntries(), ); - Map? _fieldsWithTypeListEntity; + /// Cache of [fieldsWithTypeListEntity]: the fields of a list of entities. + Map? _fieldsWithTypeListEntityCache; Map fieldsWithTypeListEntity([O? o]) => - _fieldsWithTypeListEntity ??= fieldsWithType( + _fieldsWithTypeListEntityCache ??= fieldsWithType( (_, fieldType) => fieldType.isValidListEntityType, o, ); - Map? _fieldsWithTypeListEntityReference; + /// Cache of [fieldsWithTypeListEntityOrReference]: the (non-hidden) fields + /// of a list of entities or an [EntityReferenceList]. + Map? _fieldsWithTypeListEntityOrReferenceCache; Map fieldsWithTypeListEntityOrReference([O? o]) => - _fieldsWithTypeListEntityReference ??= fieldsWithTypeAndAnnotations(( - fieldName, - fieldType, - fieldAnnotations, - ) { - if (!fieldType.isValidListEntityOrReferenceType) { - return false; - } + _fieldsWithTypeListEntityOrReferenceCache ??= + fieldsWithTypeAndAnnotations(( + fieldName, + fieldType, + fieldAnnotations, + ) { + if (!fieldType.isValidListEntityOrReferenceType) { + return false; + } - if (fieldAnnotations != null && fieldAnnotations.isNotEmpty) { - var hidden = fieldAnnotations.hasHidden; - return !hidden; - } + if (fieldAnnotations != null && fieldAnnotations.isNotEmpty) { + var hidden = fieldAnnotations.hasHidden; + return !hidden; + } - return true; - }, o); + return true; + }, o); - Map? _fieldsWithEntityReferenceList; + /// Cache of [fieldsWithEntityReferenceList]: the (non-hidden) fields of an + /// [EntityReferenceList] type. + Map? _fieldsWithEntityReferenceListCache; Map fieldsWithEntityReferenceList([O? o]) => - _fieldsWithEntityReferenceList ??= Map.unmodifiable( - fieldsWithTypeListEntityOrReference(o).entries - .where((e) => e.value.isEntityReferenceListType) - .toMapFromEntries(), - ); + _fieldsWithEntityReferenceListCache ??= + Map.unmodifiable( + fieldsWithTypeListEntityOrReference(o).entries + .where((e) => e.value.isEntityReferenceListType) + .toMapFromEntries(), + ); - Map>? _fieldsEntityAnnotations; + /// Cache of [fieldsEntityAnnotations] (also filled by subclasses): + /// field name -> its unmodifiable [EntityAnnotation]s. Built once (fixed + /// fields; a reflection lookup per field). + Map>? _fieldsEntityAnnotationsCache; Map> fieldsEntityAnnotations() => - _fieldsEntityAnnotations ??= + _fieldsEntityAnnotationsCache ??= Map>.unmodifiable( (getAllFieldsEntityAnnotations() ?? {}) .map>( @@ -1031,33 +1055,26 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { JsonEntityCache entityCache, EntityResolutionRulesResolved resolutionRulesResolved, ) { - if (type.isList && type.hasArguments) { - var elementType = type.arguments.first; - var valEntityHandler = _resolveEntityHandler( - elementType, - entityProvider, - entityHandlerProvider, - entityRepositoryProvider, - ); + final isTypedList = type.isList && type.hasArguments; - return _resolveListValueByType( - valEntityHandler, - value, - elementType, - entityProvider, - entityCache, - resolutionRulesResolved, - ); - } else if (type.isEntityReferenceListType) { - var elementType = type.arguments.first; + if (!isTypedList && !type.isEntityReferenceListType) { + return type.parseEntity(value); + } - var valEntityHandler = _resolveEntityHandler( - elementType, - entityProvider, - entityHandlerProvider, - entityRepositoryProvider, - ); + // A typed `List` or an `EntityReferenceList`: resolve the elements + // through `E`'s handler. + var elementType = type.arguments.first; + var valEntityHandler = _resolveEntityHandler( + elementType, + entityProvider, + entityHandlerProvider, + entityRepositoryProvider, + ); + + if (!isTypedList) { + // An `EntityReferenceList` of a lazy (not eager) type keeps the + // references, without loading the entities: var eagerEntityType = resolutionRulesResolved.isEagerEntityType( elementType.type, ); @@ -1069,18 +1086,16 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { entityCache: entityCache, ) as T; } - - return _resolveListValueByType( - valEntityHandler, - value, - elementType, - entityProvider, - entityCache, - resolutionRulesResolved, - ); - } else { - return type.parseEntity(value); } + + return _resolveListValueByType( + valEntityHandler, + value, + elementType, + entityProvider, + entityCache, + resolutionRulesResolved, + ); } FutureOr _resolveMapByType( @@ -1267,36 +1282,28 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { } } - if (valEntityHandler != null) { - var listFutures = TypeParser.parseList( - value, - elementParser: (e) => valEntityHandler.resolveValueByType( - elementType, - e, - entityProvider: entityProvider, - entityCache: entityCache, - resolutionRules: resolutionRulesResolved, - ), - ); + // Without the element type's handler, this handler resolves the + // elements (and the list isn't cast to the element type): + final EntityHandler resolver = valEntityHandler ?? this; - if (listFutures == null) return null; + var listFutures = TypeParser.parseList( + value, + elementParser: (e) => resolver.resolveValueByType( + elementType, + e, + entityProvider: entityProvider, + entityCache: entityCache, + resolutionRules: resolutionRulesResolved, + ), + ); + if (listFutures == null) return null; + + if (valEntityHandler != null) { return listFutures.resolveAll().resolveMapped((l) { return valEntityHandler.castList(l, elementType.type)! as T; }); } else { - var listFutures = TypeParser.parseList( - value, - elementParser: (e) => resolveValueByType( - elementType, - e, - entityProvider: entityProvider, - entityCache: entityCache, - resolutionRules: resolutionRulesResolved, - ), - ); - - if (listFutures == null) return null; return listFutures.resolveAll().resolveMapped((l) => l as T); } } @@ -1575,10 +1582,13 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { } } - EntityHandler? valEntityHandler = type == entityType ? this : null; - if (valEntityHandler != null) return valEntityHandler; + if (type == entityType) return this; + + // Each step below returns as soon as it resolves a handler, so the next + // step is reached only while the handler is still unresolved. + EntityHandler? valEntityHandler; - if (valEntityHandler == null && entityRepositoryProvider != null) { + if (entityRepositoryProvider != null) { var entityRepository = entityRepositoryProvider.getEntityRepositoryByType( entityType, ); @@ -1586,7 +1596,7 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { if (valEntityHandler != null) return valEntityHandler; } - if (valEntityHandler == null && entityHandlerProvider != null) { + if (entityHandlerProvider != null) { valEntityHandler = entityHandlerProvider.getEntityHandler( type: entityType, ); @@ -1602,42 +1612,60 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { return valEntityHandler; } - Map? _fieldsNamesIndexes; + /// Cache of [fieldsNamesIndexes]: field name -> index in [fieldsNames]. + /// The fields of an entity type are fixed, so it's built once. + Map? _fieldsNamesIndexesCache; - Map fieldsNamesIndexes([O? o]) { - if (_fieldsNamesIndexes == null) { - var fieldsNames = this.fieldsNames(o); - _fieldsNamesIndexes = buildFieldsNamesIndexes(fieldsNames); - } - return _fieldsNamesIndexes!; - } + Map fieldsNamesIndexes([O? o]) => + _fieldsNamesIndexesCache ??= buildFieldsNamesIndexes(fieldsNames(o)); - List? _fieldsNamesLC; + /// Cache of [fieldsNamesLC]: the [fieldsNames] in lower case, used for + /// case-insensitive field lookups. Built once (fixed fields). + List? _fieldsNamesLCCache; - List fieldsNamesLC([O? o]) { - if (_fieldsNamesLC == null) { - var fieldsNames = this.fieldsNames(o); - _fieldsNamesLC = buildFieldsNamesLC(fieldsNames); - } - return _fieldsNamesLC!; - } + List fieldsNamesLC([O? o]) => + _fieldsNamesLCCache ??= buildFieldsNamesLC(fieldsNames(o)); - List? _fieldsNamesSimple; + /// Cache of [fieldsNamesSimple]: the [fieldsNames] as simple keys + /// (`fieldToSimpleKey`), used for lenient field lookups. Built once (fixed + /// fields). + List? _fieldsNamesSimpleCache; - List fieldsNamesSimple([O? o]) { - if (_fieldsNamesSimple == null) { - var fieldsNames = this.fieldsNames(o); - _fieldsNamesSimple = buildFieldsNamesSimple(fieldsNames); - } - return _fieldsNamesSimple!; - } + List fieldsNamesSimple([O? o]) => + _fieldsNamesSimpleCache ??= buildFieldsNamesSimple(fieldsNames(o)); TypeInfo? getFieldType(O? o, String key, {bool resolveFiledName = false}); - Map? _fieldsTypes; + /// Returns the [TypeInfo] of field [key] from [_fieldsTypesCache] (`null` + /// if not cached yet or not found). With [resolveFiledName], a [key] not + /// found as is gets resolved against [fieldsNames] (case/format lenient). + /// + /// The first lookup step of [getFieldType] in [GenericEntityHandler] and + /// [ClassReflectionEntityHandler]; each one then falls back to its own + /// source (the entity instance, or the reflection). + TypeInfo? _getCachedFieldType(String key, bool resolveFiledName) { + final fieldsTypes = _fieldsTypesCache; + if (fieldsTypes == null) return null; + + var fieldType = fieldsTypes[key]; + + if (fieldType == null && resolveFiledName) { + var resolvedFieldName = this.resolveFiledName(fieldsNames(), key); + if (resolvedFieldName != null) { + fieldType = fieldsTypes[resolvedFieldName]; + } + } + + return fieldType; + } + + /// Cache of [getFieldsTypes] (also filled by subclasses' [fieldsTypes]): + /// field name -> [TypeInfo]. Resolving each field type can be expensive + /// (reflection), and the fields of an entity type are fixed. + Map? _fieldsTypesCache; Map getFieldsTypes([O? o]) { - return _fieldsTypes ??= Map.unmodifiable( + return _fieldsTypesCache ??= Map.unmodifiable( Map.fromEntries( fieldsNames(o).map( (key) => MapEntry( @@ -1649,10 +1677,12 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { ); } - Map? _fieldsEnumTypes; + /// Cache of [getFieldsEnumTypes]: the fields whose type is a registered + /// enum. Built once (fixed fields; a reflection lookup per field). + Map? _fieldsEnumTypesCache; Map getFieldsEnumTypes([O? o]) { - var enumFields = _fieldsEnumTypes; + var enumFields = _fieldsEnumTypesCache; if (enumFields != null) return enumFields; final reflectionFactory = ReflectionFactory(); @@ -1664,13 +1694,17 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { ) .toMapFromEntries(); - return _fieldsEnumTypes = Map.unmodifiable(mapEnumFields); + return _fieldsEnumTypesCache = Map.unmodifiable( + mapEnumFields, + ); } - Map? _fieldsEntityTypes; + /// Cache of [getFieldsEntityTypes]: the (non-enum) fields that hold a + /// single entity (or reference). Built once (fixed fields). + Map? _fieldsEntityTypesCache; Map getFieldsEntityTypes([O? o]) { - var entityFields = _fieldsEntityTypes; + var entityFields = _fieldsEntityTypesCache; if (entityFields != null) return entityFields; var enumFields = getFieldsEnumTypes(o); @@ -1692,15 +1726,17 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { .nonNulls .toMapFromEntries(); - return _fieldsEntityTypes = Map.unmodifiable( + return _fieldsEntityTypesCache = Map.unmodifiable( mapEntityFields, ); } - Map? _fieldsListEntityTypes; + /// Cache of [getFieldsListEntityTypes]: the (non-enum) fields that hold a + /// list of entities (or references). Built once (fixed fields). + Map? _fieldsListEntityTypesCache; Map getFieldsListEntityTypes([O? o]) { - var listEntityFields = _fieldsListEntityTypes; + var listEntityFields = _fieldsListEntityTypesCache; if (listEntityFields != null) return listEntityFields; var enumFields = getFieldsEnumTypes(o); @@ -1722,7 +1758,7 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { .nonNulls .toMapFromEntries(); - return _fieldsListEntityTypes = Map.unmodifiable( + return _fieldsListEntityTypesCache = Map.unmodifiable( mapListEntityFields, ); } @@ -2089,31 +2125,11 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { if (value1 == value2) return true; - equals = equalsValuesDateTime(value1, value2); - if (equals != null) return equals; - - equals = equalsValuesTime(value1, value2); - if (equals != null) return equals; - - equals = equalsValuesDynamicNumber(value1, value2); - if (equals != null) return equals; - - equals = equalsValuesPrimitive(value1, value2); + equals = _equalsValuesScalar(value1, value2); if (equals != null) return equals; - equals = equalsValuesEnum(value1, value2); - if (equals != null) return equals; - - var collection1 = - TypeParser.isCollectionValue(value1) || - value1.isEntityReferenceList || - value1 is Uint8List || - value1 is Int8List; - var collection2 = - TypeParser.isCollectionValue(value2) || - value2.isEntityReferenceList || - value2 is Uint8List || - value2 is Int8List; + var collection1 = _isCollectionLike(value1); + var collection2 = _isCollectionLike(value2); if (collection1 && collection2) { return isEqualsDeep(value1, value2, valueEquality: equalsValues); @@ -2152,6 +2168,27 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { return false; } + /// Compares [value1] and [value2] as scalar values, trying in order: + /// [DateTime], [Time], [DynamicNumber], primitive and [Enum] equality. + /// Returns the first decided result, or `null` if none applies. + /// + /// The shared chain of [equalsValues] and [equalsValuesBasic] (which run + /// their own checks before and after it). + static bool? _equalsValuesScalar(Object value1, Object value2) => + equalsValuesDateTime(value1, value2) ?? + equalsValuesTime(value1, value2) ?? + equalsValuesDynamicNumber(value1, value2) ?? + equalsValuesPrimitive(value1, value2) ?? + equalsValuesEnum(value1, value2); + + /// Returns `true` if [value] is compared element-wise by [equalsValues]: + /// a collection, an [EntityReferenceList] or a byte list. + static bool _isCollectionLike(Object value) => + TypeParser.isCollectionValue(value) || + value.isEntityReferenceList || + value is Uint8List || + value is Int8List; + static DynamicNumber valueToDynamicNumber( Object? value, { DynamicNumber? def, @@ -2182,48 +2219,59 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { // A `null` in a comparison (`>`, `>=`, `<`, `<=`) doesn't match (as SQL's // unknown, `NULL`): not an error. - static bool graterThanValue( + static bool greaterThanValue( Object? value1, Object? value2, { EntityHandler? entityHandler, - }) { - if (value1 == null || value2 == null) return false; - var n1 = valueToDynamicNumber(value1); - var n2 = valueToDynamicNumber(value2); - return n1 > n2; - } + }) => _compareAsNumbers(value1, value2, (n1, n2) => n1 > n2); - static bool graterThanOrEqualValue( + static bool greaterThanOrEqualValue( Object? value1, Object? value2, { EntityHandler? entityHandler, - }) { - if (value1 == null || value2 == null) return false; - var n1 = valueToDynamicNumber(value1); - var n2 = valueToDynamicNumber(value2); - return n1 >= n2; - } + }) => _compareAsNumbers(value1, value2, (n1, n2) => n1 >= n2); static bool lessThanValue( Object? value1, Object? value2, { EntityHandler? entityHandler, - }) { - if (value1 == null || value2 == null) return false; - var n1 = valueToDynamicNumber(value1); - var n2 = valueToDynamicNumber(value2); - return n1 < n2; - } + }) => _compareAsNumbers(value1, value2, (n1, n2) => n1 < n2); static bool lessThanOrEqualValue( Object? value1, Object? value2, { EntityHandler? entityHandler, - }) { + }) => _compareAsNumbers(value1, value2, (n1, n2) => n1 <= n2); + + /// Deprecated misspelling of [greaterThanValue]. + @Deprecated('Use `greaterThanValue`') + static bool graterThanValue( + Object? value1, + Object? value2, { + EntityHandler? entityHandler, + }) => greaterThanValue(value1, value2, entityHandler: entityHandler); + + /// Deprecated misspelling of [greaterThanOrEqualValue]. + @Deprecated('Use `greaterThanOrEqualValue`') + static bool graterThanOrEqualValue( + Object? value1, + Object? value2, { + EntityHandler? entityHandler, + }) => greaterThanOrEqualValue(value1, value2, entityHandler: entityHandler); + + /// Applies the comparison [op] to [value1] and [value2] converted to + /// [DynamicNumber] (see [valueToDynamicNumber]). A `null` side is `false` + /// (see above). Shared by [greaterThanValue], [greaterThanOrEqualValue], + /// [lessThanValue] and [lessThanOrEqualValue]. + static bool _compareAsNumbers( + Object? value1, + Object? value2, + bool Function(DynamicNumber n1, DynamicNumber n2) op, + ) { if (value1 == null || value2 == null) return false; var n1 = valueToDynamicNumber(value1); var n2 = valueToDynamicNumber(value2); - return n1 <= n2; + return op(n1, n2); } static bool equalsValuesBasic( @@ -2235,19 +2283,7 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { if (value2 == null) return false; if (identical(value1, value2) || value1 == value2) return true; - var equals = equalsValuesDateTime(value1, value2); - if (equals != null) return equals; - - equals = equalsValuesTime(value1, value2); - if (equals != null) return equals; - - equals = equalsValuesDynamicNumber(value1, value2); - if (equals != null) return equals; - - equals = equalsValuesPrimitive(value1, value2); - if (equals != null) return equals; - - equals = equalsValuesEnum(value1, value2); + var equals = _equalsValuesScalar(value1, value2); if (equals != null) return equals; equals = equalsValuesCollection( @@ -2274,25 +2310,8 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { return value2.equalsEntityID(value1); } - var reflectionFactory = ReflectionFactory(); - - EntityHandler? entityHandler1 = value1.isPrimitiveValue - ? null - : reflectionFactory - .getRegisterClassReflection(value1.runtimeType) - ?.entityHandler ?? - EntityHandlerProvider.globalProvider.getEntityHandler( - obj: value1, - ); - - EntityHandler? entityHandler2 = value2.isPrimitiveValue - ? null - : reflectionFactory - .getRegisterClassReflection(value2.runtimeType) - ?.entityHandler ?? - EntityHandlerProvider.globalProvider.getEntityHandler( - obj: value2, - ); + var entityHandler1 = _entityHandlerForValue(value1); + var entityHandler2 = _entityHandlerForValue(value2); if (entityHandler1 != null) { var id1 = entityHandler1.getID(value1); @@ -2318,6 +2337,18 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { return equalsValuesEntityMap(value1, value2, entityHandler: entityHandler); } + /// The [EntityHandler] of [value]'s type (its registered reflection's + /// handler, or the global provider's one), or `null` for a primitive value + /// (never an entity). Used by [equalsValuesEntity] for each side. + static EntityHandler? _entityHandlerForValue(Object value) { + if (value.isPrimitiveValue) return null; + + return ReflectionFactory() + .getRegisterClassReflection(value.runtimeType) + ?.entityHandler ?? + EntityHandlerProvider.globalProvider.getEntityHandler(obj: value); + } + /// Equals by ID: a `null` ID (no ID, or not resolved) is never equal (the /// values were not `==` already). See [equalsValuesEntity]. static bool _equalsIDs(Object? id1, Object? id2) => id1 != null && id1 == id2; @@ -2679,7 +2710,7 @@ abstract class EntityHandler with FieldsFromMap, EntityRulesResolver { entityCache: entityCache, resolutionRules: resolutionRules, ).resolveMapped((o) { - entityCache.cacheEntity(o, getID); + entityCache.cacheEntity(o, _getIDFunction); return o; }); }); @@ -2867,63 +2898,64 @@ class GenericEntityHandler extends EntityHandler { } } - String? _idFieldsName; - - @override - String idFieldName([O? o]) { - var idFieldsName = _idFieldsName; - - if (idFieldsName == null) { - inspectObject(o); - idFieldsName = _idFieldsName; + // A [GenericEntityHandler] can't reflect on [O]: the caches below are + // filled by [inspectObject] from the first entity instance seen (or one + // created by [createDefault]). - if (idFieldsName == null) { - throw StateError( - "`idFieldsName` Not populated yet for type `$type`! " - "No Entity instance presented to this EntityHandler yet.", - ); - } - } + /// Cache of [idFieldName] (the ID field's name), filled by + /// [inspectObject]. + String? _idFieldNameCache; - return idFieldsName; - } - - List? _fieldsNames; + /// Cache of [fieldsNames], filled by [inspectObject]. + List? _fieldsNamesCache; @override - List fieldsNames([O? o]) { - var fieldsNames = _fieldsNames; - - if (fieldsNames == null) { - inspectObject(o); - fieldsNames = _fieldsNames; - } + String idFieldName([O? o]) => _inspectedOrThrow( + o, + () => _idFieldNameCache, + () => + "`idFieldsName` Not populated yet for type `$type`! " + "No Entity instance presented to this EntityHandler yet.", + ); - if (fieldsNames == null) { - throw StateError( + @override + List fieldsNames([O? o]) => _inspectedOrThrow( + o, + () => _fieldsNamesCache, + () => "`fieldsNames` Not populated yet! No Entity instance presented to this EntityHandler yet. Type: $type", - ); - } - - return fieldsNames; - } + ); @override - Map fieldsTypes([O? o]) { - var fieldsTypes = _fieldsTypes; + Map fieldsTypes([O? o]) => _inspectedOrThrow( + o, + () => _fieldsTypesCache, + () => + "`fieldsTypes` Not populated yet! No Entity instance presented to this EntityHandler yet. Type: $type", + ); - if (fieldsTypes == null) { - inspectObject(o); - fieldsTypes = _fieldsTypes; - } + /// Returns the cached value read by [readCache], calling [inspectObject] + /// with [o] first when it's not cached yet. Throws a [StateError] with + /// [errorMessage] if it's still not available (no entity instance seen). + /// + /// Used by [idFieldName], [fieldsNames] and [fieldsTypes], whose values + /// only exist after an entity was inspected (see [inspectObject]). + T _inspectedOrThrow( + O? o, + T? Function() readCache, + String Function() errorMessage, + ) { + var value = readCache(); + if (value != null) return value; - if (fieldsTypes == null) { - throw StateError( - "`fieldsTypes` Not populated yet! No Entity instance presented to this EntityHandler yet. Type: $type", - ); + inspectObject(o); + + value = readCache(); + if (value == null) { + throw StateError(errorMessage()); } - return fieldsTypes; + return value; } @override @@ -2936,20 +2968,20 @@ class GenericEntityHandler extends EntityHandler { } } - if (o != null && _idFieldsName == null) { - _idFieldsName = o.idFieldName; + if (o != null && _idFieldNameCache == null) { + _idFieldNameCache = o.idFieldName; - final fieldsNames = _fieldsNames ??= List.unmodifiable( + final fieldsNames = _fieldsNamesCache ??= List.unmodifiable( o.fieldsNames, ); - _fieldsTypes ??= Map.unmodifiable( + _fieldsTypesCache ??= Map.unmodifiable( Map.fromEntries( fieldsNames.map((f) => MapEntry(f, o!.getFieldType(f)!)), ), ); - _fieldsEntityAnnotations ??= + _fieldsEntityAnnotationsCache ??= Map>.unmodifiable( Map>.fromEntries( fieldsNames.map((f) { @@ -3015,19 +3047,7 @@ class GenericEntityHandler extends EntityHandler { TypeInfo? getFieldType(O? o, String key, {bool resolveFiledName = false}) { inspectObject(o); - TypeInfo? fieldType; - - final fieldsTypes = _fieldsTypes; - if (fieldsTypes != null) { - fieldType = fieldsTypes[key]; - - if (fieldType == null && resolveFiledName) { - var resolvedFieldName = this.resolveFiledName(fieldsNames(), key); - if (resolvedFieldName != null) { - fieldType = fieldsTypes[resolvedFieldName]; - } - } - } + var fieldType = _getCachedFieldType(key, resolveFiledName); if (fieldType == null && o != null) { fieldType = o.getFieldType(key); @@ -3069,7 +3089,7 @@ class GenericEntityHandler extends EntityHandler { if (o != null) { return o.getFieldEntityAnnotations(key); } else { - return _fieldsEntityAnnotations?[key]; + return _fieldsEntityAnnotationsCache?[key]; } } @@ -3119,10 +3139,12 @@ class ClassReflectionEntityHandler extends EntityHandler { ClassReflection reflectionWithObject([O? o]) => o == null ? reflection : reflection.withObject(o); - List? _siblingsEntityHandlers; + /// Cache of [siblingsEntityHandlers]: the handlers of the sibling classes + /// (same reflection bundle), fixed after the reflection is registered. + List? _siblingsEntityHandlersCache; List siblingsEntityHandlers() => - _siblingsEntityHandlers ??= + _siblingsEntityHandlersCache ??= List.unmodifiable( reflection.siblingsClassReflection().map((c) => c.entityHandler), ); @@ -3172,15 +3194,16 @@ class ClassReflectionEntityHandler extends EntityHandler { @override V? getField(O o, String key) => reflection.getField(key, o); - /// The ID field (see [idFieldName]), without an object. - FieldReflection? _idField; + /// Cache of the ID field reflection (see [idFieldName]), without an + /// object: avoids a field lookup by name on every [getID]. + FieldReflection? _idFieldCache; /// The same value as `getField(o, idFieldName(o))`, read through the ID - /// field kept in [_idField]: an entity is cached by its ID each time one is - /// decoded or loaded. + /// field kept in [_idFieldCache]: an entity is cached by its ID each time + /// one is decoded or loaded. @override V? getID(O o) { - var idField = _idField ??= reflection.getStaticInstance().field( + var idField = _idFieldCache ??= reflection.getStaticInstance().field( idFieldName(o), ); if (idField == null) return super.getID(o); @@ -3193,19 +3216,7 @@ class ClassReflectionEntityHandler extends EntityHandler { @override TypeInfo? getFieldType(O? o, String key, {bool resolveFiledName = false}) { - TypeInfo? fieldType; - - final fieldsTypes = _fieldsTypes; - if (fieldsTypes != null) { - fieldType = fieldsTypes[key]; - - if (fieldType == null && resolveFiledName) { - var resolvedFieldName = this.resolveFiledName(fieldsNames(), key); - if (resolvedFieldName != null) { - fieldType = fieldsTypes[resolvedFieldName]; - } - } - } + var fieldType = _getCachedFieldType(key, resolveFiledName); if (fieldType == null) { var field = reflection.field(key, o); @@ -3236,12 +3247,13 @@ class ClassReflectionEntityHandler extends EntityHandler { List? getFieldEntityAnnotations(O? o, String key) => getFieldAnnotations(o, key)?.whereType().toList(); - List? _entityIndexes; + /// Cache of [getEntityIndexes]: the class annotations are fixed. + List? _entityIndexesCache; /// The [EntityIndex] annotations of the entity's class. @override List getEntityIndexes() => - _entityIndexes ??= List.unmodifiable( + _entityIndexesCache ??= List.unmodifiable( reflection.classAnnotations.whereType(), ); @@ -3321,20 +3333,21 @@ class ClassReflectionEntityHandler extends EntityHandler { return reflection.fromJson(json); } - String? _idFieldsName; + /// Cache of [idFieldName]: found once by [findIdFieldName] (a scan of the + /// class fields), defaulting to `id`. + String? _idFieldNameCache; @override String idFieldName([O? o]) { - if (_idFieldsName == null) { - // Just to populate: - if (_fieldsNames == null) { - fieldsNames(o); - } + var idFieldName = _idFieldNameCache; + if (idFieldName != null) return idFieldName; - var fieldName = findIdFieldName(o); - _idFieldsName = fieldName ?? 'id'; + // Just to populate: + if (_fieldsNamesCache == null) { + fieldsNames(o); } - return _idFieldsName!; + + return _idFieldNameCache = findIdFieldName(o) ?? 'id'; } String? findIdFieldName([O? o]) { @@ -3389,15 +3402,17 @@ class ClassReflectionEntityHandler extends EntityHandler { return null; } - List? _fieldsNames; + /// Cache of [fieldsNames]: the keys of [fieldsTypes] (fixed per class). + List? _fieldsNamesCache; @override List fieldsNames([O? o]) => - _fieldsNames ??= List.unmodifiable(fieldsTypes(o).keys); + _fieldsNamesCache ??= List.unmodifiable(fieldsTypes(o).keys); @override Map fieldsTypes([O? o]) { - return _fieldsTypes ??= Map.unmodifiable( + // Shares the base `_fieldsTypesCache` (also used by `getFieldsTypes`). + return _fieldsTypesCache ??= Map.unmodifiable( Map.fromEntries( reflectionWithObject(o).fieldsNames.map((f) { var field = reflection.field(f, o); @@ -3409,19 +3424,25 @@ class ClassReflectionEntityHandler extends EntityHandler { ); } - Map>? _constructors; + /// Cache of [constructors]: constructor name -> its parameters' types. + /// Fixed per class, and a full reflection scan to build. + Map>? _constructorsCache; @override Map>? constructors([O? o]) { - return _constructors ??= Map>.unmodifiable( - reflectionWithObject(o).allConstructors().map((c) { - var name = c.name; - var args = c.allParameters - .map((p) => MapEntry(p.jsonName, p.type.typeInfo)) - .toMapFromEntries(); - return MapEntry(name, Map.unmodifiable(args)); - }).toMapFromEntries(), - ); + return _constructorsCache ??= + Map>.unmodifiable( + reflectionWithObject(o).allConstructors().map((c) { + var name = c.name; + var args = c.allParameters + .map( + (p) => + MapEntry(p.jsonName, p.type.typeInfo), + ) + .toMapFromEntries(); + return MapEntry(name, Map.unmodifiable(args)); + }).toMapFromEntries(), + ); } @override @@ -4209,7 +4230,10 @@ abstract class EntityStorage extends EntityAccessor { repositoryProvider: EntityRepositoryProvider.globalProvider, ); - static EntityRepository? _resolveRepositoryProvider( + /// Resolves the [EntityRepository] of [O] (or [obj]/[type]) asking, in + /// order: [entityRepository]'s provider, [repositoryProvider] and + /// [entityHandler]. Used by the cascade delete. + static EntityRepository? _resolveEntityRepository( EntityHandler? entityHandler, EntityRepository? entityRepository, EntityRepositoryProvider? repositoryProvider, { @@ -4227,7 +4251,7 @@ abstract class EntityStorage extends EntityAccessor { EntityRepository? entityRepository, EntityRepositoryProvider? repositoryProvider, }) async { - entityRepository ??= _resolveRepositoryProvider( + entityRepository ??= _resolveEntityRepository( entityHandler, entityRepository, repositoryProvider, @@ -4277,7 +4301,7 @@ abstract class EntityStorage extends EntityAccessor { entityHandler?.getEntityHandler(obj: obj, type: type); if (eh != null && eh.type == obj.genericType) return eh; - var er = _resolveRepositoryProvider( + var er = _resolveEntityRepository( entityHandler, entityRepository, repositoryProvider, @@ -4364,37 +4388,16 @@ abstract class EntityStorage extends EntityAccessor { if (entities == null || entities.isEmpty) continue; - EntityRepository? tEntityRepository; - EntityHandler? tEntityHandler; - - for (var e in entities) { - tEntityRepository ??= _resolveRepositoryProvider( - entityHandler, - entityRepository, - repositoryProvider, - obj: e, - type: fieldType, - ); - - tEntityHandler ??= _resolveEntityHandler( - entityHandler, - tEntityRepository, - repositoryProvider, - obj: e, - type: fieldType, - ); - - preDeleteCalls.add( - () => _deleteCascadeGenericImpl( - e, - transaction, - tEntityHandler, - tEntityRepository, - repositoryProvider, - deleted, - ), - ); - } + _addSubEntitiesDeleteCalls( + entities, + fieldType, + entityHandler, + entityRepository, + repositoryProvider, + transaction, + deleted, + preDeleteCalls, + ); fieldValue.set(null); @@ -4415,37 +4418,17 @@ abstract class EntityStorage extends EntityAccessor { continue; } - EntityRepository? tEntityRepository; - EntityHandler? tEntityHandler; - - for (var e in fieldValues.nonNulls) { - tEntityRepository ??= _resolveRepositoryProvider( - entityHandler, - entityRepository, - repositoryProvider, - obj: e, - type: tType, - ); - - tEntityHandler ??= _resolveEntityHandler( - entityHandler, - tEntityRepository, - repositoryProvider, - obj: e, - type: tType, - ); - - preDeleteCalls.add( - () => _deleteCascadeGenericImpl( - e, - transaction, - tEntityHandler, - tEntityRepository, - repositoryProvider, - deleted, - ), - ); - } + _addSubEntitiesDeleteCalls( + // `whereType()`: the non-null values, typed. + fieldValues.whereType(), + tType, + entityHandler, + entityRepository, + repositoryProvider, + transaction, + deleted, + preDeleteCalls, + ); var fieldValuesEmpty = fieldValues.toList()..clear(); entityHandler.setField( @@ -4506,6 +4489,57 @@ abstract class EntityStorage extends EntityAccessor { return delOk; } + /// Adds to [preDeleteCalls] a cascade delete of each one of [entities] + /// (the elements of a list field of [entityType]), used by + /// [_deleteCascadeGenericImpl] for an [EntityReferenceList] field and for + /// a `List` of entities field. + /// + /// The sub-entities' repository and handler are resolved once (with the + /// first entity) and shared by all the calls: the locals below are + /// captured by the closures, in one scope. + static void _addSubEntitiesDeleteCalls( + Iterable entities, + Type entityType, + EntityHandler entityHandler, + EntityRepository entityRepository, + EntityRepositoryProvider? repositoryProvider, + Transaction transaction, + List deleted, + List Function()> preDeleteCalls, + ) { + EntityRepository? tEntityRepository; + EntityHandler? tEntityHandler; + + for (var e in entities) { + tEntityRepository ??= _resolveEntityRepository( + entityHandler, + entityRepository, + repositoryProvider, + obj: e, + type: entityType, + ); + + tEntityHandler ??= _resolveEntityHandler( + entityHandler, + tEntityRepository, + repositoryProvider, + obj: e, + type: entityType, + ); + + preDeleteCalls.add( + () => _deleteCascadeGenericImpl( + e, + transaction, + tEntityHandler, + tEntityRepository, + repositoryProvider, + deleted, + ), + ); + } + } + static bool _deleteSubEntityImpl( EntityHandler entityHandler, EntityRepository entityRepository, @@ -4519,7 +4553,7 @@ abstract class EntityStorage extends EntityAccessor { List Function()> preDeleteCalls, List Function()> posDeleteCalls, ) { - var tEntityRepository = _resolveRepositoryProvider( + var tEntityRepository = _resolveEntityRepository( entityHandler, entityRepository, repositoryProvider, @@ -4699,47 +4733,50 @@ class EntityRepositoryProvider Type? type, String? name, }) { - if (!isClosed) { - var entityRepository = _entityRepositories[O]; - if (entityRepository != null && !entityRepository.isClosed) { - return entityRepository as EntityRepository; - } + if (isClosed) return null; + + var entityRepository = _openRepositoryOrNull(_entityRepositories[O]); + if (entityRepository != null) return entityRepository; - Type? objType; + Type? objType; - if (obj != null) { - objType = obj.runtimeType; - if (objType != O) { - entityRepository = _entityRepositories[objType]; - if (entityRepository != null && !entityRepository.isClosed) { - return entityRepository as EntityRepository; - } - } + if (obj != null) { + objType = obj.runtimeType; + if (objType != O) { + entityRepository = _openRepositoryOrNull( + _entityRepositories[objType], + ); + if (entityRepository != null) return entityRepository; } + } - if (type != null && type != O && type != objType) { - entityRepository = _entityRepositories[type]; - if (entityRepository != null && !entityRepository.isClosed) { - return entityRepository as EntityRepository; - } - } + if (type != null && type != O && type != objType) { + entityRepository = _openRepositoryOrNull(_entityRepositories[type]); + if (entityRepository != null) return entityRepository; + } - if (name != null) { - var nameSimplified = EntityAccessor.simplifiedName(name); + if (name != null) { + var nameSimplified = EntityAccessor.simplifiedName(name); - entityRepository = _entityRepositories.values + return _openRepositoryOrNull( + _entityRepositories.values .where((e) => e.name == name || e.nameSimplified == nameSimplified) - .firstOrNull; - - if (entityRepository != null && !entityRepository.isClosed) { - return entityRepository as EntityRepository; - } - } + .firstOrNull, + ); } return null; } + /// Returns [entityRepository] as an [EntityRepository] of [O], or `null` + /// if it's `null` or closed. Used by the local lookups + /// ([_getLocalEntityRepository], [_getLocalEntityRepositoryByType]). + static EntityRepository? _openRepositoryOrNull( + EntityRepository? entityRepository, + ) => entityRepository != null && !entityRepository.isClosed + ? entityRepository as EntityRepository + : null; + EntityRepository? getEntityRepositoryByTypeInfo( TypeInfo typeInfo, ) { @@ -4773,12 +4810,7 @@ class EntityRepositoryProvider ) { if (isClosed) return null; - var entityRepository = _entityRepositories[type]; - if (entityRepository != null && !entityRepository.isClosed) { - return entityRepository as EntityRepository; - } - - return null; + return _openRepositoryOrNull(_entityRepositories[type]); } final Set _knownEntityRepositoryProviders = @@ -4825,11 +4857,8 @@ class EntityRepositoryProvider allRepositories ??= {}; traversedProviders ??= {}; - if (traversedProviders.contains(this)) { - return allRepositories; - } - - traversedProviders.add(this); + // Already traversed (a cycle among known providers): nothing to add. + if (!traversedProviders.add(this)) return allRepositories; for (var e in _entityRepositories.entries) { allRepositories.putIfAbsent(e.key, () => e.value); @@ -4864,23 +4893,15 @@ extension IterableEntityRepositoryProviderExtension EntityHandlerProvider? entityHandlerProvider, bool removeClosedProviders = false, Set? traversed, - }) { - var self = this; - if (self is! List && - self is! Set) { - self = self.toList(growable: false); - } - - return self._getEntityRepositoryImpl( - obj: obj, - type: type, - name: name, - entityRepositoryProvider: entityRepositoryProvider, - entityHandlerProvider: entityHandlerProvider, - removeClosedProviders: removeClosedProviders, - traversed: traversed, - ); - } + }) => _asReiterable()._getEntityRepositoryImpl( + obj: obj, + type: type, + name: name, + entityRepositoryProvider: entityRepositoryProvider, + entityHandlerProvider: entityHandlerProvider, + removeClosedProviders: removeClosedProviders, + traversed: traversed, + ); EntityRepository? getEntityRepositoryByTypeInfo( TypeInfo typeInfo, { @@ -4888,18 +4909,13 @@ extension IterableEntityRepositoryProviderExtension EntityHandlerProvider? entityHandlerProvider, bool removeClosedProviders = false, Set? traversed, - }) { - var entityType = typeInfo.entityType; - if (entityType == null) return null; - - return getEntityRepositoryByType( - entityType, - entityRepositoryProvider: entityRepositoryProvider, - entityHandlerProvider: entityHandlerProvider, - removeClosedProviders: removeClosedProviders, - traversed: traversed, - ); - } + }) => _asReiterable()._getEntityRepositoryByTypeInfoImpl( + typeInfo, + entityRepositoryProvider: entityRepositoryProvider, + entityHandlerProvider: entityHandlerProvider, + removeClosedProviders: removeClosedProviders, + traversed: traversed, + ); EntityRepository? getEntityRepositoryByType( Type type, { @@ -4907,36 +4923,36 @@ extension IterableEntityRepositoryProviderExtension EntityHandlerProvider? entityHandlerProvider, bool removeClosedProviders = false, Set? traversed, - }) { - var self = this; - if (self is! List && - self is! Set) { - self = self.toList(growable: false); - } - - return self._getEntityRepositoryByTypeImpl( - type, - entityRepositoryProvider: entityRepositoryProvider, - entityHandlerProvider: entityHandlerProvider, - removeClosedProviders: removeClosedProviders, - traversed: traversed, - ); - } + }) => _asReiterable()._getEntityRepositoryByTypeImpl( + type, + entityRepositoryProvider: entityRepositoryProvider, + entityHandlerProvider: entityHandlerProvider, + removeClosedProviders: removeClosedProviders, + traversed: traversed, + ); Map allRepositories({ Map? allRepositories, Set? traversedProviders, - }) { + }) => _asReiterable()._allRepositoriesImpl( + allRepositories: allRepositories, + traversedProviders: traversedProviders, + ); + + /// Returns this [Iterable] if it's a [List] or a [Set], otherwise a + /// (fixed-length) [List] copy of it. + /// + /// The lookups (`_lookupEntityRepository`, `_allRepositoriesImpl`) read + /// [length] and [first] and then iterate again: a lazy [Iterable] (e.g. a + /// `where`/`map` view) would be re-evaluated on each pass. A [List]/[Set] + /// is also kept as is so `removeClosedProviders` can remove from it. + Iterable _asReiterable() { var self = this; - if (self is! List && - self is! Set) { - self = self.toList(growable: false); + if (self is List || + self is Set) { + return self; } - - return self._allRepositoriesImpl( - allRepositories: allRepositories, - traversedProviders: traversedProviders, - ); + return self.toList(growable: false); } } @@ -5071,7 +5087,7 @@ extension _IterableEntityRepositoryProviderExtension return ask(first); } - var notClosed = _whereNotClosed(this, length, removeClosedProviders); + var notClosed = _whereNotClosed(length, removeClosedProviders); var entityRepositories = notClosed .map(ask) @@ -5107,12 +5123,14 @@ extension _IterableEntityRepositoryProviderExtension removeClosedProviders: removeClosedProviders, ); + /// The providers not closed. With [removeClosedProviders], the closed ones + /// are also removed from this [List]/[Set] (when any, comparing with the + /// original [length]). Used by [_lookupEntityRepository]. Iterable _whereNotClosed( - Iterable self, int length, bool removeClosedProviders, ) { - var notClosed = self.where((e) => !e.isClosed); + var notClosed = where((e) => !e.isClosed); if (removeClosedProviders) { notClosed = notClosed.toList(growable: false); @@ -5252,17 +5270,7 @@ extension EntityRepositoryProviderExtension on EntityRepositoryProvider { if (json == null) return >{}; var map = (json as Map).map((key, value) { - return MapEntry( - key.toString(), - (value as Iterable) - .map( - (e) => (e as Map).map( - (key, value) => - MapEntry(key.toString(), value as dynamic), - ), - ) - .toList(), - ); + return MapEntry(key.toString(), _toEntitiesJson(value as Iterable)); }); return storeAllFromJson( @@ -5438,35 +5446,35 @@ extension EntityRepositoryProviderExtension on EntityRepositoryProvider { } if (value is String) { + // A `%name%` placeholder: the variable value (the placeholder itself + // if the variable isn't defined). if (value.startsWith('%') && value.endsWith('%')) { var varName = value.substring(1, value.length - 1); - var varValue = variables[varName] ?? value; - return varValue; - } else { - return value; + return variables[varName] ?? value; } - } else if (value is num || value is bool) { - return value; + } else if (value is Map) { + // Kept apart from a generic `Map` so the result stays typed as a + // `Map`: + return value.map( + (k, v) => MapEntry( + k, + resolveEntitySourceValueVariables(k, v, variables), + ), + ); } else if (value is Map) { - if (value is Map) { - return value.map((k, v) { - var val = resolveEntitySourceValueVariables(k, v, variables); - return MapEntry(k, val); - }); - } else { - return value.map((k, v) { - var val = resolveEntitySourceValueVariables(k, v, variables); - return MapEntry(k, val); - }); - } + return value.map( + (k, v) => + MapEntry(k, resolveEntitySourceValueVariables(k, v, variables)), + ); } else if (value is List) { - return value.map((e) { - var val = resolveEntitySourceValueVariables(key, e, variables); - return val; - }).toList(); - } else { - return value; + return value + .map((e) => resolveEntitySourceValueVariables(key, e, variables)) + .toList(); } + + // Any other value (a plain `String`, a `num`, a `bool`...) has no + // variable to resolve: + return value; } FutureOr>>> resolveEntitiesSource( @@ -5476,20 +5484,23 @@ extension EntityRepositoryProviderExtension on EntityRepositoryProvider { return json.map((k, v) { var key = k.toString(); var values = v is Iterable ? v : [v]; - - var entities = values - .map( - (e) => (e as Map).map( - (key, value) => - MapEntry(key.toString(), value as dynamic), - ), - ) - .toList(); - - return MapEntry(key, entities); + return MapEntry(key, _toEntitiesJson(values)); }); }); + /// Converts each element of [values] (a decoded JSON object, a [Map]) to + /// a `Map` (keys as [String]s). Used to coerce the + /// decoded seed JSON by [storeAllFromJsonEncoded] and + /// [resolveEntitiesSource]. + static List> _toEntitiesJson(Iterable values) => values + .map( + (e) => (e as Map).map( + (key, value) => + MapEntry(key.toString(), value as dynamic), + ), + ) + .toList(); + FutureOr> resolveSource( Object? source, { String? workingPath, @@ -5799,30 +5810,27 @@ abstract class EntityRepository extends EntityAccessor parent: provider, ); + /// Up to this many JSON entries, [storeAllFromJson] creates and stores + /// them all at once; above it, in blocks of [_storeAllFromJsonBlockSize] + /// (logging the progress of a long population). + static const int _storeAllFromJsonSingleBlockMaxLength = 100; + + /// The block size of a [storeAllFromJson] above + /// [_storeAllFromJsonSingleBlockMaxLength] entries: bounds the entities + /// created (and held) before each `storeAll`. + static const int _storeAllFromJsonBlockSize = 50; + FutureOr> _storeAllFromJsonImpl( Iterable> entitiesJson, Transaction? transaction, EntityResolutionRules? resolutionRules, ) => Transaction.executeBlock((transaction) { - if (entitiesJson.length <= 100) { - var osAsync = entitiesJson - .map( - (e) => createFromMap( - e, - entityCache: transaction, - entityProvider: provider, - resolutionRules: resolutionRules, - ), - ) - .resolveAll(); - - return osAsync.resolveMapped((os) { - return storeAll(os, transaction: transaction).resolveWithValue(os); - }); + if (entitiesJson.length <= _storeAllFromJsonSingleBlockMaxLength) { + return _createAndStoreAll(entitiesJson, transaction, resolutionRules); } var entitiesJsonBlocks = entitiesJson - .splitBeforeIndexed((i, e) => i % 50 == 0) + .splitBeforeIndexed((i, e) => i % _storeAllFromJsonBlockSize == 0) .toList(); final entitiesJsonLength = entitiesJson.length; @@ -5849,26 +5857,41 @@ abstract class EntityRepository extends EntityAccessor 'Populating `$name`... $count / $entitiesJsonLength (${progress.toStringAsFixed(2)}%) -- ${elapsedTime.toHumanReadable()} / ${estimatedTime.toHumanReadable()}', ); - var osAsync = entitiesBlock - .map( - (e) => createFromMap( - e, - entityCache: transaction, - entityProvider: provider, - resolutionRules: resolutionRules, - ), - ) - .resolveAll(); - - return osAsync.resolveMapped((os) { - return storeAll(os, transaction: transaction).resolveWithValue(os); - }); + return _createAndStoreAll( + entitiesBlock, + transaction, + resolutionRules, + ); }) .resolveMapped((results) { return results.expand((l) => l).toList(); }); }, transaction: transaction); + /// Creates the entities of [entitiesJson] (see [createFromMap]) and then + /// stores them all in [transaction], returning them. Used by + /// [_storeAllFromJsonImpl] for all the entries at once, or for each block. + FutureOr> _createAndStoreAll( + Iterable> entitiesJson, + Transaction transaction, + EntityResolutionRules? resolutionRules, + ) { + var osAsync = entitiesJson + .map( + (e) => createFromMap( + e, + entityCache: transaction, + entityProvider: provider, + resolutionRules: resolutionRules, + ), + ) + .resolveAll(); + + return osAsync.resolveMapped((os) { + return storeAll(os, transaction: transaction).resolveWithValue(os); + }); + } + FutureOr storeFromJson( Map json, { Transaction? transaction, @@ -5911,25 +5934,27 @@ abstract class EntityRepository extends EntityAccessor return ret.then( (o) => o, onError: (e, s) { - _log.severe( - "Error creating `${entityHandler.type}` from fields Map: $fields", - e, - s, - ); - + _logCreateFromMapError(fields, e, s); throw e; }, ); } catch (e, s) { - _log.severe( - "Error creating `${entityHandler.type}` from fields Map: $fields", - e, - s, - ); + _logCreateFromMapError(fields, e, s); rethrow; } } + /// Logs an error of [createFromMap] (sync or async) with the [fields]. + void _logCreateFromMapError( + Map fields, + Object error, + StackTrace stackTrace, + ) => _log.severe( + "Error creating `${entityHandler.type}` from fields Map: $fields", + error, + stackTrace, + ); + @override Object? getEntityID(O o) => entityHandler.getID(o); @@ -6031,13 +6056,7 @@ abstract class EntityRepository extends EntityAccessor var fields = getEntityFields(o); - var changed = fields.entries.where((e) { - var key = e.key; - var val = e.value; - var prevVal = prevFields[key]; - var eq = entityHandler.equalsFieldValues(key, val, prevVal); - return !eq; - }); + var changed = fields.entries.where((e) => _isFieldChanged(e, prevFields)); var changedFields = changed.map((e) => e.key).toList(); return changedFields; @@ -6051,15 +6070,19 @@ abstract class EntityRepository extends EntityAccessor var fields = getEntityFields(o); - var changed = fields.entries.any((e) { - var key = e.key; - var val = e.value; - var prevVal = prevFields[key]; - var eq = entityHandler.equalsFieldValues(key, val, prevVal); - return !eq; - }); + return fields.entries.any((e) => _isFieldChanged(e, prevFields)); + } - return changed; + /// Returns `true` if the [field] value differs from its tracked value in + /// [prevFields] (see [EntityHandler.equalsFieldValues]). The per-field + /// predicate of [getEntityChangedFields] and [entityHasChangedFields]. + bool _isFieldChanged( + MapEntry field, + Map prevFields, + ) { + var key = field.key; + var prevVal = prevFields[key]; + return !entityHandler.equalsFieldValues(key, field.value, prevVal); } @override @@ -6527,8 +6550,19 @@ class Transaction extends JsonEntityCacheSimple implements EntityProvider { /// Returns the `Transaction` that are open. static List get openInstances => _openInstances.toList(); + /// The operations, in the order they were added (an operation's `id` is + /// its position). See [_operationsSetCache]. final List _operations = []; + /// Cache of the [_operations] as an identity set (kept in sync by + /// [addOperation] and [dispose]), for O(1) membership checks: + /// `_operations.contains` on every [addOperation] made a bulk store + /// (`storeAll`, thousands of operations) O(n²). + /// ([TransactionOperation] doesn't override `==`: identity is the same + /// equality `List.contains` used.) + final Set _operationsSetCache = + Set.identity(); + List get operations => UnmodifiableListView(_operations); @@ -6554,9 +6588,18 @@ class Transaction extends JsonEntityCacheSimple implements EntityProvider { /// Returns the executor of this transaction. Object? get executor => mainOperation?.executor; + /// The executed operations, in execution order. + /// See [_executedOperationsSetCache]. final List _executedOperations = []; + /// Cache of the [_executedOperations] as an identity set (kept in sync + /// by [_markOperationExecuted] and [dispose]), for O(1) membership + /// checks: `_executedOperations.contains` on every executed operation made + /// a bulk store O(n²). + final Set _executedOperationsSetCache = + Set.identity(); + /// Returns the list of [operations] that were fully executed. List get executedOperations => UnmodifiableListView(_executedOperations); @@ -6732,12 +6775,12 @@ class Transaction extends JsonEntityCacheSimple implements EntityProvider { return false; } - if (!_operations.contains(op)) { + if (!_operationsSetCache.contains(op)) { throw StateError("Operation not in transaction: $op"); } if (notExecuted == 1) { - return !_executedOperations.contains(op); + return !_executedOperationsSetCache.contains(op); } else { return _executedOperations.last == op; } @@ -6871,7 +6914,7 @@ class Transaction extends JsonEntityCacheSimple implements EntityProvider { Object? get result => _result; void addOperation(TransactionOperation op) { - if (_operations.contains(op)) { + if (_operationsSetCache.contains(op)) { throw StateError("Operation already in transaction: $op"); } @@ -6894,6 +6937,7 @@ class Transaction extends JsonEntityCacheSimple implements EntityProvider { } _operations.add(op); + _operationsSetCache.add(op); op.id = _operations.length; } @@ -6940,7 +6984,7 @@ class Transaction extends JsonEntityCacheSimple implements EntityProvider { Object? result, bool allowAutoCommit, ) { - if (_executedOperations.contains(op)) { + if (_executedOperationsSetCache.contains(op)) { throw StateError("Operation already executed in transaction: $op"); } @@ -6951,6 +6995,7 @@ class Transaction extends JsonEntityCacheSimple implements EntityProvider { op._endTime = DateTime.now(); _executedOperations.add(op); + _executedOperationsSetCache.add(op); if (!_aborted) { _lastResult = result; @@ -7001,13 +7046,13 @@ class Transaction extends JsonEntityCacheSimple implements EntityProvider { ); } - if (!_operations.contains(operation)) { + if (!_operationsSetCache.contains(operation)) { throw StateError( "Operation not in transaction:\n-- Operation> $operation\n-- $this", ); } - if (_executedOperations.contains(operation)) { + if (_executedOperationsSetCache.contains(operation)) { return true; } @@ -7039,12 +7084,12 @@ class Transaction extends JsonEntityCacheSimple implements EntityProvider { return true; } - if (_executedOperations.contains(operation)) { + if (_executedOperationsSetCache.contains(operation)) { return true; } } - return _executedOperations.contains(operation); + return _executedOperationsSetCache.contains(operation); } FutureOr _doAutoCommit() { @@ -7338,7 +7383,9 @@ class Transaction extends JsonEntityCacheSimple implements EntityProvider { _abortError = abortError; _aborted = true; - for (var op in _operations.whereNotIn(_executedOperations)) { + for (var op in _operations.where( + (op) => !_executedOperationsSetCache.contains(op), + )) { finishOperationVoid(op, null, allowAutoCommit: false); } @@ -7732,7 +7779,9 @@ class Transaction extends JsonEntityCacheSimple implements EntityProvider { _executionsFutures.clear(); _executedOperations.clear(); + _executedOperationsSetCache.clear(); _operations.clear(); + _operationsSetCache.clear(); clearCachedEntities(); @@ -7967,6 +8016,17 @@ abstract class TransactionOperation implements RecursiveToString { String get _executedStatus => isExecuted ? '(executed)' : ''; + /// The common head of the subclasses' [toStringSimple] and [toString]: + /// `[#@#:@]`. + /// - [className]: only [TransactionOperationSubTransaction] shows its own. + /// - [target]: a suffix after the repository name (e.g. the value + /// repository of [TransactionOperationSelectRelationships]). + String _describe({ + String className = 'TransactionOperation', + String target = '', + }) => + '$className$_executedStatus[#$id@#${transaction.id}:${type.name}@$repositoryName$target]'; + @override String toString({Set? processedObjects}); } @@ -7988,9 +8048,11 @@ class TransactionOperationSubTransaction extends TransactionOperation { transaction: parentTransaction, ); + String get _describeSubTransaction => + _describe(className: 'TransactionOperationSubTransaction'); + @override - String toStringSimple() => - 'TransactionOperationSubTransaction$_executedStatus[#$id@#${transaction.id}:subTransaction@$repositoryName]->$durationMsInfo'; + String toStringSimple() => '$_describeSubTransaction->$durationMsInfo'; @override String toString({ @@ -7999,7 +8061,7 @@ class TransactionOperationSubTransaction extends TransactionOperation { processedObjects, this, () => - 'TransactionOperationSubTransaction$_executedStatus[#$id@#${transaction.id}:subTransaction@$repositoryName]->${subTransaction.toString(compact: true)}$durationMsInfo', + '$_describeSubTransaction->${subTransaction.toString(compact: true)}$durationMsInfo', )!; } @@ -8021,18 +8083,16 @@ class TransactionOperationSelect extends TransactionOperation { ); @override - String toStringSimple() => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:select@$repositoryName]$durationMsInfo'; + String toStringSimple() => '${_describe()}$durationMsInfo'; @override - String toString({ - Set? processedObjects, - }) => RecursiveToString.recursiveToString( - processedObjects, - this, - () => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:select@$repositoryName]{matcher: $matcher$_commandToString}$durationMsInfo', - )!; + String toString({Set? processedObjects}) => + RecursiveToString.recursiveToString( + processedObjects, + this, + () => + '${_describe()}{matcher: $matcher$_commandToString}$durationMsInfo', + )!; } class TransactionOperationCount extends TransactionOperation { @@ -8047,18 +8107,16 @@ class TransactionOperationCount extends TransactionOperation { }) : super(TransactionOperationType.count, repositoryName, false, executor); @override - String toStringSimple() => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:count@$repositoryName]$durationMsInfo'; + String toStringSimple() => '${_describe()}$durationMsInfo'; @override - String toString({ - Set? processedObjects, - }) => RecursiveToString.recursiveToString( - processedObjects, - this, - () => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:count@$repositoryName]{matcher: $matcher$_commandToString}$durationMsInfo', - )!; + String toString({Set? processedObjects}) => + RecursiveToString.recursiveToString( + processedObjects, + this, + () => + '${_describe()}{matcher: $matcher$_commandToString}$durationMsInfo', + )!; } abstract class TransactionOperationWithEntity extends TransactionOperation { @@ -8105,18 +8163,15 @@ class TransactionOperationStore extends TransactionOperationSaveEntity { ); @override - String toStringSimple() => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:store@$repositoryName]$durationMsInfo'; + String toStringSimple() => '${_describe()}$durationMsInfo'; @override - String toString({ - Set? processedObjects, - }) => RecursiveToString.recursiveToString( - processedObjects, - this, - () => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:store@$repositoryName]{entity: $entity$_commandToString}$durationMsInfo', - )!; + String toString({Set? processedObjects}) => + RecursiveToString.recursiveToString( + processedObjects, + this, + () => '${_describe()}{entity: $entity$_commandToString}$durationMsInfo', + )!; } class TransactionOperationUpdate extends TransactionOperationSaveEntity { @@ -8136,18 +8191,15 @@ class TransactionOperationUpdate extends TransactionOperationSaveEntity { ); @override - String toStringSimple() => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:update@$repositoryName]$durationMsInfo'; + String toStringSimple() => '${_describe()}$durationMsInfo'; @override - String toString({ - Set? processedObjects, - }) => RecursiveToString.recursiveToString( - processedObjects, - this, - () => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:update@$repositoryName]{entity: $entity$_commandToString}$durationMsInfo', - )!; + String toString({Set? processedObjects}) => + RecursiveToString.recursiveToString( + processedObjects, + this, + () => '${_describe()}{entity: $entity$_commandToString}$durationMsInfo', + )!; } class TransactionOperationStoreRelationship @@ -8176,8 +8228,7 @@ class TransactionOperationStoreRelationship ); @override - String toStringSimple() => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:storeRelationship@$repositoryName]$durationMsInfo'; + String toStringSimple() => '${_describe()}$durationMsInfo'; @override String toString({ @@ -8186,7 +8237,7 @@ class TransactionOperationStoreRelationship processedObjects, this, () => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:storeRelationship@$repositoryName]{entity: $entity, other: $others$_commandToString}$durationMsInfo', + '${_describe()}{entity: $entity, other: $others$_commandToString}$durationMsInfo', )!; } @@ -8210,8 +8261,7 @@ class TransactionOperationConstrainRelationship ); @override - String toStringSimple() => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:constrainRelationship@$repositoryName]$durationMsInfo'; + String toStringSimple() => '${_describe()}$durationMsInfo'; @override String toString({ @@ -8220,7 +8270,7 @@ class TransactionOperationConstrainRelationship processedObjects, this, () => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:constrainRelationship@$repositoryName]{entity: $entity, other: $others$_commandToString}$durationMsInfo', + '${_describe()}{entity: $entity, other: $others$_commandToString}$durationMsInfo', )!; } @@ -8241,18 +8291,15 @@ class TransactionOperationSelectRelationship ); @override - String toStringSimple() => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:selectRelationship@$repositoryName]$durationMsInfo'; + String toStringSimple() => '${_describe()}$durationMsInfo'; @override - String toString({ - Set? processedObjects, - }) => RecursiveToString.recursiveToString( - processedObjects, - this, - () => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:selectRelationship@$repositoryName]{entity: $entity$_commandToString}$durationMsInfo', - )!; + String toString({Set? processedObjects}) => + RecursiveToString.recursiveToString( + processedObjects, + this, + () => '${_describe()}{entity: $entity$_commandToString}$durationMsInfo', + )!; } class TransactionOperationSelectRelationships extends TransactionOperation { @@ -8275,7 +8322,7 @@ class TransactionOperationSelectRelationships extends TransactionOperation { @override String toStringSimple() => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:selectRelationships@$repositoryName->$valueRepositoryName]$durationMsInfo'; + '${_describe(target: '->$valueRepositoryName')}$durationMsInfo'; @override String toString({ @@ -8284,7 +8331,7 @@ class TransactionOperationSelectRelationships extends TransactionOperation { processedObjects, this, () => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:selectRelationships@$repositoryName->$valueRepositoryName]{entities: $entities$_commandToString}$durationMsInfo', + '${_describe(target: '->$valueRepositoryName')}{entities: $entities$_commandToString}$durationMsInfo', )!; } @@ -8306,18 +8353,16 @@ class TransactionOperationDelete extends TransactionOperation { ); @override - String toStringSimple() => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:delete@$repositoryName]$durationMsInfo'; + String toStringSimple() => '${_describe()}$durationMsInfo'; @override - String toString({ - Set? processedObjects, - }) => RecursiveToString.recursiveToString( - processedObjects, - this, - () => - 'TransactionOperation$_executedStatus[#$id@#${transaction.id}:delete@$repositoryName]{matcher: $matcher$_commandToString}$durationMsInfo', - )!; + String toString({Set? processedObjects}) => + RecursiveToString.recursiveToString( + processedObjects, + this, + () => + '${_describe()}{matcher: $matcher$_commandToString}$durationMsInfo', + )!; } enum TransactionOperationType { @@ -8334,30 +8379,10 @@ enum TransactionOperationType { } extension TransactionOperationTypeExtension on TransactionOperationType { - String get name { - switch (this) { - case TransactionOperationType.subTransaction: - return 'subTransaction'; - case TransactionOperationType.select: - return 'select'; - case TransactionOperationType.count: - return 'count'; - case TransactionOperationType.store: - return 'store'; - case TransactionOperationType.storeRelationship: - return 'storeRelationship'; - case TransactionOperationType.constrainRelationship: - return 'constrainRelationship'; - case TransactionOperationType.selectRelationship: - return 'selectRelationship'; - case TransactionOperationType.selectRelationships: - return 'selectRelationships'; - case TransactionOperationType.update: - return 'update'; - case TransactionOperationType.delete: - return 'delete'; - } - } + /// The same as [Enum.name] (each value's name is its identifier). Kept as + /// public API; a call on a [TransactionOperationType] value resolves to + /// [Enum.name] anyway (an instance member wins over an extension's). + String get name => (this as Enum).name; /// `true` for an operation that only reads. bool get isRead => switch (this) { @@ -8482,6 +8507,11 @@ abstract class IterableEntityRepository fieldsListEntity.length - fieldsListEntityRef.length; if (fieldsListEntityNoRef > 0) return true; + // From here, every entity field is a reference field (`EntityReference` + // or `EntityReferenceList`), and there's at least one: + // - Only `EntityReferenceList` fields: `false` (the operation doesn't + // propagate for them). + // - Any `EntityReference` field: `true` (it can hold a loaded entity). if (fieldsEntityRef.isEmpty && fieldsListEntityRef.isNotEmpty) return false; return true; @@ -8501,17 +8531,36 @@ abstract class IterableEntityRepository return iterable().length; } - return iterable().where((o) { - return matcher.matchesEntity( - o, - entityHandler: entityHandler, - parameters: parameters, - positionalParameters: positionalParameters, - namedParameters: namedParameters, - ); - }).length; + return iterable() + .where( + (o) => _matchesEntity( + matcher, + o, + parameters, + positionalParameters, + namedParameters, + ), + ) + .length; } + /// [matcher].`matchesEntity` for [o] with this [entityHandler]: the + /// entity predicate of the [iterable] scans, shared by [count] and + /// [matches] (used by the selects and deletes). + bool _matchesEntity( + EntityMatcher matcher, + O o, + Object? parameters, + List? positionalParameters, + Map? namedParameters, + ) => matcher.matchesEntity( + o, + entityHandler: entityHandler, + parameters: parameters, + positionalParameters: positionalParameters, + namedParameters: namedParameters, + ); + @override Object? getEntityID(O o) => getID(o, entityHandler: entityHandler); @@ -8761,11 +8810,7 @@ abstract class IterableEntityRepository }) { checkNotClosed(); - fieldType ??= entityHandler.getFieldType(o, field, resolveFiledName: true)!; - - if (!fieldType.isListEntityOrReference) { - throw StateError("Field `$field` not a `List` entity type: $fieldType"); - } + fieldType = _relationshipFieldType(o, field, fieldType); var op = TransactionOperationStoreRelationship( name, @@ -8792,6 +8837,20 @@ abstract class IterableEntityRepository }); } + /// Returns [fieldType] (or [field]'s type, when `null`), which must be a + /// list of entities (or an [EntityReferenceList]): throws a [StateError] + /// otherwise. The shared validation of [setRelationship] and + /// [selectRelationship]. + TypeInfo _relationshipFieldType(O? o, String field, TypeInfo? fieldType) { + fieldType ??= entityHandler.getFieldType(o, field, resolveFiledName: true)!; + + if (!fieldType.isListEntityOrReference) { + throw StateError("Field `$field` not a `List` entity type: $fieldType"); + } + + return fieldType; + } + FutureOr putRelationship( Object oId, Type valuesType, @@ -8808,11 +8867,7 @@ abstract class IterableEntityRepository }) { checkNotClosed(); - fieldType ??= entityHandler.getFieldType(o, field, resolveFiledName: true)!; - - if (!fieldType.isListEntityOrReference) { - throw StateError("Field `$field` not a `List` entity type: $fieldType"); - } + fieldType = _relationshipFieldType(o, field, fieldType); oId ??= getID(o!, entityHandler: entityHandler)!; @@ -9043,15 +9098,15 @@ abstract class IterableEntityRepository bool? orderByID, OrderDirection? orderDirection, }) { - var itr = iterable().where((o) { - return matcher.matchesEntity( + var itr = iterable().where( + (o) => _matchesEntity( + matcher, o, - entityHandler: entityHandler, - parameters: parameters, - positionalParameters: positionalParameters, - namedParameters: namedParameters, - ); - }); + parameters, + positionalParameters, + namedParameters, + ), + ); return _applyOrderAndPagination( itr, diff --git a/test/bones_api_cov_entity_handler_test.dart b/test/bones_api_cov_entity_handler_test.dart index 27068e23..f064a8c2 100644 --- a/test/bones_api_cov_entity_handler_test.dart +++ b/test/bones_api_cov_entity_handler_test.dart @@ -862,11 +862,23 @@ void main() { var dn = DynamicInt.fromInt(5); expect(identical(EntityHandler.valueToDynamicNumber(dn), dn), isTrue); - expect(EntityHandler.graterThanValue(2, 1), isTrue); - expect(EntityHandler.graterThanValue(1, 2), isFalse); - expect(EntityHandler.graterThanOrEqualValue(2, 2), isTrue); + expect(EntityHandler.greaterThanValue(2, 1), isTrue); + expect(EntityHandler.greaterThanValue(1, 2), isFalse); + expect(EntityHandler.greaterThanOrEqualValue(2, 2), isTrue); + expect(EntityHandler.greaterThanOrEqualValue(1, 2), isFalse); expect(EntityHandler.lessThanValue(1, '2'), isTrue); expect(EntityHandler.lessThanOrEqualValue(2.5, 2), isFalse); + expect(EntityHandler.lessThanOrEqualValue(2, 2), isTrue); + + // A `null` side never matches: + expect(EntityHandler.greaterThanValue(null, 1), isFalse); + expect(EntityHandler.lessThanOrEqualValue(1, null), isFalse); + + // The deprecated misspelled aliases still work: + // ignore: deprecated_member_use_from_same_package + expect(EntityHandler.graterThanValue(2, 1), isTrue); + // ignore: deprecated_member_use_from_same_package + expect(EntityHandler.graterThanOrEqualValue(1, 2), isFalse); }); test('equalsValuesBasic', () { From 1d5cc08e6a5b252bb13236269c02fe5704fafacb Mon Sep 17 00:00:00 2001 From: "Graciliano M. P." Date: Sun, 8 Nov 2026 05:23:06 -0300 Subject: [PATCH 3/6] Refactor entity references and extensions: shared helpers, doc fixes - EntityReference.fromJson: _fromInstantiator for the two instantiator blocks; uses EntityInstantiatorHandler.resolveEntityMap (the private duplicate removed). - EntityReferenceBase: _toStringPrefix and _compareIDPresence shared by EntityReference and EntityReferenceList (the list-vs-list arm now tested); dead branch in _castListNullable removed. - TypeInfo extension: parseEntity/entityType merged branches; _castEntityHandler for the castCall of toEntityReference(List). - MapGetterExtension: _parseValue (getParsed/getMultiKeyParsed tail), one key loop, _scanKeyIgnoreCase shared by getIgnoreCase and matchKeyIgnoreCase; docs name defaultValue (not def), and getMultiKeyAsString parses as String. Co-Authored-By: Claude Opus 5.5 --- lib/src/bones_api_entity_reference.dart | 187 +++++++++--------- lib/src/bones_api_extension.dart | 150 +++++++------- test/bones_api_cov_entity_reference_test.dart | 25 +++ 3 files changed, 192 insertions(+), 170 deletions(-) diff --git a/lib/src/bones_api_entity_reference.dart b/lib/src/bones_api_entity_reference.dart index 975b46f1..22a5ccf8 100644 --- a/lib/src/bones_api_entity_reference.dart +++ b/lib/src/bones_api_entity_reference.dart @@ -461,6 +461,31 @@ abstract class EntityReferenceBase { @override String toString({bool withT = true}); + + /// The head of [toString]: ` className` (` ` only + /// [withT]), the type from the known [Type], else the type name, else `?`. + /// Shared by [EntityReference] and [EntityReferenceList]. + String _toStringPrefix(String className, bool withT) { + var typeStr = _type?.toString() ?? _typeName ?? '?'; + var prefix = '$className<$typeStr>'; + return withT ? ' $prefix' : prefix; + } + + /// The tail of `equalsEntityID`/`equalsEntitiesIDs` when comparing with + /// another reference: by ID(s) only when both sides have them + /// ([compareIDs]); `false` when only one side has them; `null` (unknown) + /// when neither has. + static bool? _compareIDPresence( + bool otherHasIDs, + bool thisHasIDs, + bool Function() compareIDs, + ) { + if (otherHasIDs) { + return thisHasIDs ? compareIDs() : false; + } else { + return thisHasIDs ? false : null; + } + } } /// Reference wrapper to an entity. @@ -638,30 +663,21 @@ class EntityReference extends EntityReferenceBase { ); if (entityHandler != null) { - var instantiator = EntityInstantiatorHandler( - entityHandler, + return _fromInstantiator( id, entity, - entityCache: entityCache, - entityHandlerProvider: entityHandlerProvider, + type, + typeName, + entityHandler, + entityProvider, + entityHandlerProvider, + entityFetcher, + entityCache, ); - - return EntityReference.fromEntityInstantiator( - id, - instantiator, - type: type, - typeName: typeName, - entityHandler: entityHandler, - entityProvider: entityProvider, - entityHandlerProvider: entityHandlerProvider, - entityFetcher: entityFetcher, - entityCache: entityCache, - checkGenericType: false, - )._autoCast(); } } - var entityMapCast = _resolveEntityMap(entity); + var entityMapCast = EntityInstantiatorHandler.resolveEntityMap(entity); return EntityReference.fromEntityMap( entityMapCast, @@ -709,26 +725,17 @@ class EntityReference extends EntityReferenceBase { if (entityHandler != null) { var id = entityHandler.getIDFromMap(json); if (id != null) { - var instantiator = EntityInstantiatorHandler( - entityHandler, + return _fromInstantiator( id, json, - entityCache: entityCache, - entityHandlerProvider: entityHandlerProvider, + type, + typeName, + entityHandler, + entityProvider, + entityHandlerProvider, + entityFetcher, + entityCache, ); - - return EntityReference.fromEntityInstantiator( - id, - instantiator, - type: type, - typeName: typeName, - entityHandler: entityHandler, - entityProvider: entityProvider, - entityHandlerProvider: entityHandlerProvider, - entityFetcher: entityFetcher, - entityCache: entityCache, - checkGenericType: false, - )._autoCast(); } } @@ -746,15 +753,42 @@ class EntityReference extends EntityReferenceBase { } } - static Map _resolveEntityMap(Object entity) { - var entityMap = entity is Map - ? entity - : TypeParser.parseMap(entity) ?? {}; + /// An [EntityReference] with [id] whose entity is instantiated (lazily) + /// from [entityMap] by an [EntityInstantiatorHandler] (which also caches + /// the instantiator in [entityCache]). Used by [EntityReference.fromJson] + /// when the entity handler and the ID are known: for an `EntityReference` + /// JSON with an `entity`, and for an entity JSON. + static EntityReference _fromInstantiator( + Object id, + Object entityMap, + Type? type, + String? typeName, + EntityHandler entityHandler, + EntityProvider? entityProvider, + EntityHandlerProvider? entityHandlerProvider, + EntityFetcher? entityFetcher, + EntityCache? entityCache, + ) { + var instantiator = EntityInstantiatorHandler( + entityHandler, + id, + entityMap, + entityCache: entityCache, + entityHandlerProvider: entityHandlerProvider, + ); - var entityMapCast = entityMap is Map - ? entityMap - : entityMap.map((key, value) => MapEntry('$key', value)); - return entityMapCast; + return EntityReference.fromEntityInstantiator( + id, + instantiator, + type: type, + typeName: typeName, + entityHandler: entityHandler, + entityProvider: entityProvider, + entityHandlerProvider: entityHandlerProvider, + entityFetcher: entityFetcher, + entityCache: entityCache, + checkGenericType: false, + )._autoCast(); } /// Creates an [EntityReference] from [o] trying to resolve it in the best way. @@ -1328,19 +1362,11 @@ class EntityReference extends EntityReferenceBase { return true; } - if (otherEntity.isIdSet) { - if (isIdSet) { - return id == otherEntity.id; - } else { - return false; - } - } else { - if (isIdSet) { - return false; - } else { - return null; - } - } + return EntityReferenceBase._compareIDPresence( + otherEntity.isIdSet, + isIdSet, + () => id == otherEntity.id, + ); } else if (otherEntity is T) { if (isEntitySet && identical(entity, otherEntity)) return true; @@ -1361,9 +1387,7 @@ class EntityReference extends EntityReferenceBase { @override String toString({bool withT = true}) { - var typeStr = _type?.toString() ?? _typeName ?? '?'; - var prefix = 'EntityReference<$typeStr>'; - if (withT) prefix = ' $prefix'; + var prefix = _toStringPrefix('EntityReference', withT); if (isNull) { return '$prefix{null}'; @@ -1928,14 +1952,11 @@ class EntityReferenceList extends EntityReferenceBase { static List? _castListNullable(List? l) { if (l == null) return null; + // (A `List` is also a `List`.) if (l is List) { return l; } - if (l is List) { - return l; - } - if (l.every((e) => e is E)) { return l.map((e) => e as E).toList(); } @@ -2568,19 +2589,11 @@ class EntityReferenceList extends EntityReferenceBase { return true; } - if (otherEntities.isIdSet) { - if (isIDsSet) { - return _idsEquality.equals(ids, [otherEntities.id]); - } else { - return false; - } - } else { - if (isIDsSet) { - return false; - } else { - return null; - } - } + return EntityReferenceBase._compareIDPresence( + otherEntities.isIdSet, + isIDsSet, + () => _idsEquality.equals(ids, [otherEntities.id]), + ); } else if (otherEntities is EntityReferenceList) { if (type != otherEntities.type) return false; @@ -2594,19 +2607,11 @@ class EntityReferenceList extends EntityReferenceBase { return true; } - if (otherEntities.isIDsSet) { - if (isIDsSet) { - return _idsEquality.equals(ids, otherEntities.ids); - } else { - return false; - } - } else { - if (isIDsSet) { - return false; - } else { - return null; - } - } + return EntityReferenceBase._compareIDPresence( + otherEntities.isIDsSet, + isIDsSet, + () => _idsEquality.equals(ids, otherEntities.ids), + ); } else if (otherEntities is T) { if (isEntitiesSet && _listIdenticalEquality.equals(entities, [otherEntities])) { @@ -2647,9 +2652,7 @@ class EntityReferenceList extends EntityReferenceBase { @override String toString({bool withT = true}) { - var typeStr = _type?.toString() ?? _typeName ?? '?'; - var prefix = 'EntityReferenceList<$typeStr>'; - if (withT) prefix = ' $prefix'; + var prefix = _toStringPrefix('EntityReferenceList', withT); if (isNull) { return '$prefix{null}'; diff --git a/lib/src/bones_api_extension.dart b/lib/src/bones_api_extension.dart index 0bf36f37..132f9603 100644 --- a/lib/src/bones_api_extension.dart +++ b/lib/src/bones_api_extension.dart @@ -241,27 +241,29 @@ extension MapGetterExtension on Map { return defaultValue; } - var keyStr = key.toString(); + var match = _scanKeyIgnoreCase(key); + if (match == null) return defaultValue; - for (var k in keys) { - if (equalsIgnoreAsciiCase(keyStr, k.toString())) { - var value = this[k]; - return value ?? defaultValue; - } - } - - return defaultValue; + return this[match.$1] ?? defaultValue; } /// Returns the existing key that matches [key] as case-insensitive. K? matchKeyIgnoreCase(K key) { if (containsKey(key)) return key; + return _scanKeyIgnoreCase(key)?.$1; + } + /// The first key (in [keys] order) whose `toString` equals [key]'s, + /// ignoring ASCII case, wrapped in a record (so a `null` key can be a + /// match), or `null` if none. The key scan of [getIgnoreCase] and + /// [matchKeyIgnoreCase] (each one checks the exact [key] its own way + /// first: by a non-null value, or by [containsKey]). + (K,)? _scanKeyIgnoreCase(K key) { var keyStr = key.toString(); for (var k in keys) { if (equalsIgnoreAsciiCase(keyStr, k.toString())) { - return k; + return (k,); } } @@ -276,7 +278,7 @@ extension MapGetterExtension on Map { /// Gets a [key] value parsing as [bool]. /// - /// - [def] is the default value if the value is invalid. + /// - [defaultValue] is the default value if the value is absent or invalid. bool? getAsBool(K key, {bool? defaultValue, bool ignoreCase = false}) => getParsed( key, @@ -287,7 +289,7 @@ extension MapGetterExtension on Map { /// Gets the value of the first matching [keys], parsing as [bool]. /// - /// - [def] is the default value if the value is invalid. + /// - [defaultValue] is the default value if the value is absent or invalid. bool? getMultiKeyAsBool( List keys, { bool? defaultValue, @@ -301,7 +303,7 @@ extension MapGetterExtension on Map { /// Gets a [key] value parsing as [int]. /// - /// - [def] is the default value if the value is invalid. + /// - [defaultValue] is the default value if the value is absent or invalid. int? getAsInt(K key, {int? defaultValue, bool ignoreCase = false}) => getParsed( key, @@ -312,7 +314,7 @@ extension MapGetterExtension on Map { /// Gets the value of the first matching [keys], parsing as [int]. /// - /// - [def] is the default value if the value is invalid. + /// - [defaultValue] is the default value if the value is absent or invalid. int? getMultiKeyAsInt( List keys, { int? defaultValue, @@ -326,7 +328,7 @@ extension MapGetterExtension on Map { /// Gets a [key] value parsing as [double]. /// - /// - [def] is the default value if the value is invalid. + /// - [defaultValue] is the default value if the value is absent or invalid. double? getAsDouble(K key, {double? defaultValue, bool ignoreCase = false}) => getParsed( key, @@ -337,7 +339,7 @@ extension MapGetterExtension on Map { /// Gets the value of the first matching [keys], parsing as [double]. /// - /// - [def] is the default value if the value is invalid. + /// - [defaultValue] is the default value if the value is absent or invalid. double? getMultiKeyAsDouble( List keys, { double? defaultValue, @@ -351,7 +353,7 @@ extension MapGetterExtension on Map { /// Gets a [key] value parsing to [num] type. /// - /// - [def] is the default value if the value is invalid. + /// - [defaultValue] is the default value if the value is absent or invalid. num? getAsNum(K key, {num? defaultValue, bool ignoreCase = false}) => getParsed( key, @@ -362,7 +364,7 @@ extension MapGetterExtension on Map { /// Gets the value of the first matching [keys], parsing as [num]. /// - /// - [def] is the default value if the value is invalid. + /// - [defaultValue] is the default value if the value is absent or invalid. num? getMultiKeyAsNum( List keys, { num? defaultValue, @@ -376,7 +378,7 @@ extension MapGetterExtension on Map { /// Gets a [key] value parsing as [String]. /// - /// - [def] is the default value if the value is invalid. + /// - [defaultValue] is the default value if the value is absent or invalid. String? getAsString(K key, {String? defaultValue, bool ignoreCase = false}) => getParsed( key, @@ -385,9 +387,9 @@ extension MapGetterExtension on Map { ignoreCase: ignoreCase, ); - /// Gets the value of the first matching [keys], parsing as [num]. + /// Gets the value of the first matching [keys], parsing as [String]. /// - /// - [def] is the default value if the value is invalid. + /// - [defaultValue] is the default value if the value is absent or invalid. String? getMultiKeyAsString( List keys, { String? defaultValue, @@ -401,7 +403,8 @@ extension MapGetterExtension on Map { /// Gets a [key] value parsing as [List]. /// - /// - [def] is the default value if the value is invalid. + /// - [defaultValue] is the default value if the value is absent or invalid. + /// - [def] is the [TypeParser.parseList] default (for a value it can't parse). /// - [elementParser] is the parser to use for each element in the [List]. List? getAsList( K key, { @@ -418,7 +421,8 @@ extension MapGetterExtension on Map { /// Gets a [key] value parsing as [Map]. /// - /// - [def] is the default value if the value is invalid. + /// - [defaultValue] is the default value if the value is absent or invalid. + /// - [def] is the [TypeParser.parseMap] default (for a value it can't parse). /// - [keyParser] is the parser to use for each key in the [Map]. /// - [valueParser] is the parser to use for each value in the [Map]. Map? getAsMap( @@ -442,7 +446,8 @@ extension MapGetterExtension on Map { /// Gets a [key] value parsing as [Set]. /// - /// - [def] is the default value if the value is invalid. + /// - [defaultValue] is the default value if the value is absent or invalid. + /// - [def] is the [TypeParser.parseSet] default (for a value it can't parse). /// - [elementParser] is the parser to use for each element in the [Set]. Set? getAsSet( K key, { @@ -467,18 +472,7 @@ extension MapGetterExtension on Map { bool ignoreCase = false, }) { var value = ignoreCase ? getIgnoreCase(key) : this[key]; - - T? v; - - if (parser != null) { - v = parser(value); - } else if (value is T?) { - v = value; - } else { - throw ArgumentError("Can't parse key('$key') value as `$T`: $value"); - } - - return v ?? defaultValue; + return _parseValue(value, parser, defaultValue, () => '$key'); } /// Same as [getParsed] but accepts multiple [keys]. @@ -488,27 +482,35 @@ extension MapGetterExtension on Map { T? defaultValue, bool ignoreCase = false, }) { + // The value of the first key with a (non-null) value: V? value; - if (ignoreCase) { - for (var k in keys) { - value = getIgnoreCase(k); - if (value != null) break; - } - } else { - for (var k in keys) { - value = this[k]; - if (value != null) break; - } + for (var k in keys) { + value = ignoreCase ? getIgnoreCase(k) : this[k]; + if (value != null) break; } + return _parseValue(value, parser, defaultValue, () => keys.join("','")); + } + + /// Parses [value] with [parser] (or, without a parser, accepts it if it's + /// already a [T]), returning [defaultValue] when the result is `null`. + /// Throws an [ArgumentError] (naming [keyDescription]) if [value] can't be + /// a [T]. The shared tail of [getParsed] and [getMultiKeyParsed]. + static T? _parseValue( + Object? value, + TypeElementParser? parser, + T? defaultValue, + String Function() keyDescription, + ) { T? v; + if (parser != null) { v = parser(value); } else if (value is T?) { v = value; } else { throw ArgumentError( - "Can't parse key('${keys.join("','")}') value as `$T`: $value", + "Can't parse key('${keyDescription()}') value as `$T`: $value", ); } @@ -672,15 +674,10 @@ extension TypeInfoEntityExtension on TypeInfo { Type? get entityType { var type = this.type; - Type? entityType; - - if (type.isEntityReferenceBaseType) { - entityType = arguments0?.type; - } else if (isList) { - entityType = arguments0?.type; - } else { - entityType = type; - } + // A reference or a `List`: the element (argument #0) type. + var entityType = type.isEntityReferenceBaseType || isList + ? arguments0?.type + : type; return EntityHandler.isValidEntityType(entityType) ? entityType : null; } @@ -717,12 +714,8 @@ extension TypeInfoEntityExtension on TypeInfo { } E? parseEntity(Object? value) { - if (isEntityReferenceType) { - var entityType = arguments0; - if (entityType != null) { - return entityType.parse(value); - } - } else if (isEntityReferenceListType) { + // A reference: parsed as its entity type (argument #0), when known. + if (isEntityReferenceType || isEntityReferenceListType) { var entityType = arguments0; if (entityType != null) { return entityType.parse(value); @@ -830,19 +823,12 @@ extension TypeInfoEntityExtension on TypeInfo { } EntityReference castCall() { - EntityHandler? oEntityHandler; - if (entityHandler != null) { - oEntityHandler = entityHandler is EntityHandler - ? (entityHandler as EntityHandler) - : entityHandler.getEntityHandler(type: type); - } - return _toEntityReferenceImpl( o, id, type, typeName, - oEntityHandler, + _castEntityHandler(entityHandler, type), entityProvider, entityHandlerProvider, entityFetcher as EntityFetcher?, @@ -853,6 +839,21 @@ extension TypeInfoEntityExtension on TypeInfo { return callCasted(castCall) as EntityReference; } + /// [entityHandler] as an [EntityHandler] of [E] (the type argument + /// [callCasted] resolves): itself if it already is one, otherwise the + /// one it provides for [E] ([type]). Used by the `castCall`s of + /// [toEntityReference] and [toEntityReferenceList]. + static EntityHandler? _castEntityHandler( + EntityHandler? entityHandler, + Type? type, + ) { + if (entityHandler == null) return null; + + return entityHandler is EntityHandler + ? entityHandler + : entityHandler.getEntityHandler(type: type); + } + EntityReference _toEntityReferenceImpl( Object? o, Object? id, @@ -971,18 +972,11 @@ extension TypeInfoEntityExtension on TypeInfo { } EntityReferenceList castCall() { - EntityHandler? oEntityHandler; - if (entityHandler != null) { - oEntityHandler = entityHandler is EntityHandler - ? (entityHandler as EntityHandler) - : entityHandler.getEntityHandler(type: type); - } - return _toEntityReferenceListImpl( o, type, typeName, - oEntityHandler, + _castEntityHandler(entityHandler, type), entityProvider, entityHandlerProvider, entitiesFetcher as EntitiesFetcher?, diff --git a/test/bones_api_cov_entity_reference_test.dart b/test/bones_api_cov_entity_reference_test.dart index 1642d5d0..41cecc1e 100644 --- a/test/bones_api_cov_entity_reference_test.dart +++ b/test/bones_api_cov_entity_reference_test.dart @@ -984,6 +984,31 @@ void main() { isFalse, ); + // `EntityReferenceList` compared by IDs (a non-null list always has + // IDs: resolved from its entities, `null` for an entity without ID): + var lNullID1 = EntityReferenceList<_Thing>.fromEntities([ + _Thing(null, 'x'), + ]); + var lNullID2 = EntityReferenceList<_Thing>.fromEntities([ + _Thing(null, 'y'), + ]); + expect( + lIDs.equalsEntitiesIDs(EntityReferenceList<_Thing>.fromIDs([1])), + isTrue, + ); + expect( + lIDs.equalsEntitiesIDs(EntityReferenceList<_Thing>.fromIDs([2])), + isFalse, + ); + expect(lIDs.equalsEntitiesIDs(lNullID1), isFalse); + expect(lNullID1.equalsEntitiesIDs(lIDs), isFalse); + expect(lNullID1.equalsEntitiesIDs(lNullID2), isTrue); + expect(lIDs.equalsEntitiesIDs(lNull), isFalse); + expect( + lNull.equalsEntitiesIDs(EntityReferenceList<_Thing>.asNull()), + isTrue, + ); + // With `T`: expect(l.equalsEntitiesIDs(t1), isTrue); expect(l.equalsEntitiesIDs(t2), isNull); From 33197036a5ec5f080164a3603b1281054bedd51d Mon Sep 17 00:00:00 2001 From: "Graciliano M. P." Date: Sun, 8 Nov 2026 05:24:35 -0300 Subject: [PATCH 4/6] Refactor Time, pagination and deep collection helpers - Time: +/- share _toOffsetDuration; _bytesInStringFormat uses _hasHmsPrefix. - EntityPagination: loadPage's sync/async success path -> _completePageLoad; _loadAllImpl's redundant final-page check removed (_isPageKnownEmpty). - isEqualsIterableDeep: paired iterators; intersectsIterableDeep iterates (materializing a lazy it2 once) instead of elementAt(i) (O(n^2) on a non-List Iterable). Co-Authored-By: Claude Opus 5.5 --- lib/src/bones_api_entity_pagination.dart | 34 ++++++------ lib/src/bones_api_types.dart | 68 +++++++++++------------- lib/src/bones_api_utils_collections.dart | 25 +++++---- 3 files changed, 67 insertions(+), 60 deletions(-) diff --git a/lib/src/bones_api_entity_pagination.dart b/lib/src/bones_api_entity_pagination.dart index 4a84f223..b169df9f 100644 --- a/lib/src/bones_api_entity_pagination.dart +++ b/lib/src/bones_api_entity_pagination.dart @@ -549,24 +549,14 @@ class EntityPagination { if (ret is! Future>) { var elapsedTime = stopwatch?.elapsed ?? Duration.zero; - var resolvedEnd = _setPage(page, ret); - var entries = _pages[page]!; - - _notifyLoaded(page, entries, elapsedTime, resolvedEnd); - - return entries; + return _completePageLoad(page, ret, elapsedTime); } var future = ret .then((pageEntries) { var elapsedTime = stopwatch?.elapsed ?? Duration.zero; _loadingPages.remove(page); - var resolvedEnd = _setPage(page, pageEntries); - var entries = _pages[page]!; - - _notifyLoaded(page, entries, elapsedTime, resolvedEnd); - - return entries; + return _completePageLoad(page, pageEntries, elapsedTime); }) .onError((e, s) { var elapsedTime = stopwatch?.elapsed ?? Duration.zero; @@ -581,6 +571,22 @@ class EntityPagination { return future; } + /// Stores the loaded [pageEntries] of [page] and notifies it (see + /// [_notifyLoaded]), returning the stored entries. The success path of + /// [loadPage], for a sync and for an async page loader. + List _completePageLoad( + int page, + List pageEntries, + Duration elapsedTime, + ) { + var resolvedEnd = _setPage(page, pageEntries); + var entries = _pages[page]!; + + _notifyLoaded(page, entries, elapsedTime, resolvedEnd); + + return entries; + } + void _notifySkipped(int page, EntityPaginationSkipReason reason) { if (onEvent == null) return; _notify(EntityPaginationPageSkipped(this, page, reason)); @@ -647,9 +653,7 @@ class EntityPagination { ++page; } - var finalPage = _finalPage; - if (finalPage != null && page > finalPage) return totalLength; - + // Past the final page or the first empty one (see `_isPageKnownEmpty`): if (_isPageKnownEmpty(page)) return totalLength; if (maxPages != null && fetchCount >= maxPages) return totalLength; diff --git a/lib/src/bones_api_types.dart b/lib/src/bones_api_types.dart index 1b1c4e04..620b2299 100644 --- a/lib/src/bones_api_types.dart +++ b/lib/src/bones_api_types.dart @@ -191,22 +191,14 @@ class Time implements Comparable