Repository navigation
Clean-code pass and fixes across bones_api (v1.35.0) - #209
Merged
Merged
Conversation
- condition: a private `_Ordering` enum (gt, gte, lt, lte; `mirrored`,
`test`) behind the ordering methods of `ConditionParameter` and
`Condition` (public methods kept as one-line delegates; the unused
`keyType` documented), and a private `_KeyConditionOrdering` base of the
four `KeyCondition{GreaterThan,...}` classes (constructors, `cast` and
symbols kept). `encodeValue` moved into `KeyCondition`.
- `ConditionParameter.matchesIn`: the parameters among the values are
resolved once, not once per element.
- `KeyConditionRegExp._literalRegExp` -> `_literalRegExpCache`, documented.
- encoder: `isReservedWord` by a const set; `TypeInfo.from(valueType)`
computed once; `EncodingContext.parameterValue`.
- condition SQL: `_encodeIDComparison`, `_requireTableScheme`,
`_writeEmptySetMatch`, `qualifiedColumnSQL`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- `SQLGenerator.uniqueConstraintName`, `indexName`, `foreignKeyName` and `relationshipTableName` (byte-identical names), also used by the scheme check and the in-memory adapter's relationship table. - Locals `constrain*Name` -> `constraint*Name`. - `SQLDialect.qualifiedColumnSQL` (used by `orderBySQL`). - `CreateTableSQL`/`AlterTableSQL` table caches named `*Cache`, documented. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
- `_checkDBTableScheme` split into helpers named after its sections (`_findMissingReferenceConstraints`, `_findMissingRelationshipIndexes`, `_findMissingEnumConstraints`, `_dedupeMissingEntityIndexes`, `_findEntityIndexesNameConflicts`, `_tableCheckErrorLine`), with `_sameManagerEntityTypes` for the identical to-one/to-many blocks, a local `columnsOf`, and the "No scheme" message written once. - Relationship generators: `_requireTableScheme`, `_requireRelationship`; `_generateConstrainRelationshipSQL` takes the resolved relationship; `_selectRelationshipSQLText` and `_executeSelectRelationshipSQL` shared by the single/multiple relationship selects. - JOINs: `SQLDialect.qualifiedColumnSQL` and `_joinKeyword` (same SQL). - `SQL`: `_positionalCache` declared before the method that fills it; the lazy positional fields documented. - Typo locals (`colum`, `constrainSQL`). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
- Server: one `_finishResponse` for both `_processAPIResponse` branches; helpers renamed to what they do (`_buildShelfResponse`, `_disposeAndCompressResponse`, `_startServersAndInitializeAPIRoot`, `_errorResponse`); CORS set once; payload reading shared (`_readPayloadBytes`, `_toUint8List`, one `maxPayloadLength` check); `_flattenSingleValues` for headers and query parameters; header names and the session cookie as constants; `normalizeHeaderValue` passes `k3`. - Security: one `resolveMapped` chain in `_resolveRequestCredentialsTokens`; dispose methods share `_disposeFromTokenStore`; `_setRequestCredential`. - Root/module: `_resolveModuleOrDefault`, `APIRoot.apiInfoRoute` and `APIRoot.defaultAuthenticationRoute`; `_routesHandlersPATCH`. - Response cache: an entry evicted once (not per alternative); `ifModifiedSince`; `void` 304 store; one `GET` check. - Cron: `_execute` split into `_runCalls`, `_storeRunResult`, `_runLabel`. - Mixin: `_findKeyByNormalized` for the lower-case and simple lookups. - Cache fields named `*Cache`, documented and declared before their users. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- `_selectEntries`: the two near-identical matching branches as one closure (references resolved only when needed, as before). - `_hasNoReferences` (select and delete) and `_deleteMatchedEntries` (the three delete branches). The parameters each passes are kept, and the difference documented (select: `namedParameters ?? parametersByPlaceholder`; delete: `parametersByPlaceholder`). - `_tablesVersions`/`_tablesIndexesVersions` -> `*Cache`, documented. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`_parseSelectDirectives` (with `_extractIntDirective` for the identical LIMIT/OFFSET/PAGE blocks), `_buildSelectTableHTML` and `_buildPaginationHTML`. Same HTML. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…unting - `_checkMaxMemorySize` sorted `_cachedResponses.values`, which holds a `List<_CachedResponse>` for an entry with compressed alternatives (not `Comparable`): a `TypeError` on eviction. It now sorts the entries (key + all alternatives), compared by their total usage and memory size (`_CachedResponse.compareEntries`, same order as `compareTo`). - `_expire` removed the entries (200 and its 304) from the map directly, so their memory size was never subtracted from `totalMemorySize`: now through `_remove`. Tests: eviction of JSON responses with gzip alternatives; total memory back to 0 after the cached entries expire. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`characterEscapeValue2` used `characterEscape`, whose pattern excludes
`'`, so `Condition.parse("name == 'a\\'b'")` failed (`"\'" expected`);
the unused `jsonEscapeCharsString2` was meant for it. Now
`characterEscape2`. Test in bones_api_condition_test.dart.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
It lacked a space after `name: $name,` and omitted `acceptsVarcharWithoutMaximumSize`, `intParameterTypeSuffix`, `maxIDsAsParameters`, `regExpSyntax` and `subqueryAsDerivedTable`. Tests in bones_api_cov_sql_builder_test.dart. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
- `_getUserDirectory` fell back to `Directory('~/')`, a literal `~`
directory (relative to the current one), not the home directory. The home
is now resolved only from `HOME`/`USERPROFILE` (Windows first tries
`USERPROFILE`, the others `HOME`, each with the other as fallback), in
the new `APIServerConfig.resolveUserDirectory` (`@visibleForTesting`).
The identical macOS and Linux branches are merged.
- `_resolvePayloadFromString`: `catch (e, s)` shadowed the payload `s`, so
the JSON-decode error log printed the stack trace in place of the
payload: now `catch (e, stackTrace)`.
Tests: `resolveUserDirectory` (incl. a literal `~` directory in the
current directory being ignored); the decode error log shows the payload.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
It bucketed elements by `hashCode`: an element whose `hashCode` changed after being added was looked up in another group, so `contains`, `add` and `remove` missed it. An identity set now uses `identityHashCode`. Test: an element with a changing `hashCode`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
It passed the caller's `fieldLC`/`fieldSimple` (the normalized forms of ONE field) to the lookup of every field, so all the fields after the first matched that same key. They are now computed per field; the two parameters are kept (public API) but ignored and `@Deprecated`. The `mapLC` and `mapSimple` indexes (per map) are still shared by all the fields. (No caller in the package passed them.) Test: two fields with `fieldLC`/`fieldSimple` and shared indexes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The values (and IDs in links) were written into the HTML as is: a value with `<` or `&` broke the page and could inject markup or scripts. Now escaped with `HtmlEscape` (element text; attribute for the links). Test in bones_api_cov_db_module_test.dart. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…0 branch Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # CHANGELOG.md
_compareUsageAndMemory (the eviction order) sorted the usage descending, so the most used responses were evicted first. Now the least used first (usage in buckets of 1000), and among equally used the largest first. Test: an entry used 1000+ times survives filling the cache. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- GenericEntityHandler.getFieldType: the entity instance is asked for the resolved field name (it was asked for the original key again). - EntityRepositoryProviderExtension.populateFromSource: forwards workingPath to resolveEntitiesSource (and resolveSource for variables). - EntityRepositoryProviderExtension.storeAllFromJson: uses transaction (forwarded to each repository) and resolves the variables placeholders (populateFromSource now lets it do so, once). - EntityReference.from / EntityReferenceList.from: forward entityHandlerProvider. - IterableEntityRepository.deleteEntity: forwards transaction. - EntityAccessRules ==/hashCode: entityFields compared/hashed element-wise (was identity). - EntityResolutionRules: allEager and allLazy both true is invalid (validate/merge throw ValidateEntityRulesError), and isEagerEntityType/isLazyEntityType no longer recurse forever on it. Tests: test/bones_api_entity_model_fixes_test.dart. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # CHANGELOG.md
…rater* names are deprecated) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…dapter The Directory, GCS and Memory adapters were copy-pasted: the table schemes, the transaction handling, the order/pagination, the ID/table names normalization, the entity JSON normalization and the operation execution. They now live in DBObjectAdapter<C>, with the hooks adapterLogger, createAdapterException (each adapter keeps its exception type and messages), encodeBytesAsDataURL (false for the memory adapter), and onTransactionContextCanceled/onTransactionContextClosed (the memory adapter's rollback and consolidation). Behavior-preserving. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…pter PostgreSQL, MySQL and SQLite had copy-pasted the tables names and fields references caches, their disposal, and the relationship tables lookup. They now live in DBSQLAdapter, over listTablesNamesImpl and findFieldsReferencedTablesImpl (the index names, only set by PostgreSQL, are passed through). The 30 s TTL of the fields references cache is named, every cache documented, and the unused idFieldName parameter of the PostgreSQL/MySQL relationship lookup dropped. Also adds to DBSQLAdapter the transaction defaults shared by the adapters whose driver runs a transaction around a callback (used by the next commit). Behavior-preserving. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ate auto-insert openTransaction of PostgreSQL, MySQL and SQLite only differed in the body run inside the driver's transaction: the rest (the pooled connection, the aborted check, the errors notification, the transaction result) is now DBSQLAdapter.openTransactionWithPool. Their identical transaction overrides are the DBSQLAdapter defaults (PostgreSQL keeps its cancelTransaction), and the auto-insert of an update that affected no row (MySQL, SQLite) is DBSQLAdapter.autoInsertAfterNoopUpdate. Behavior-preserving. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tion setup DBEntityRepository and DBRelationalEntityRepository had the same _ensureStoredImpl, and ensureStored only differed when the entity is already stored: now one implementation, with the hooks storeWithParentOperation and onEnsureStoredExisting (the relational one also ensures the references are stored). The repeated select operation setup is newSelectOperation. Also: _geAdapterEntityRepository renamed to _getAdapterEntityRepository; getEntityRepositoriesTables added (getEntityRepositoresTables kept, @deprecated); select uses its local keys; the cache fields _fieldsEntityRepositoriesCache, _relationshipFieldsCache and _nonPrimitiveFieldsCache are documented. Behavior-preserving. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
It used `.whereType<int>().first`, a StateError for a result without a row, while the SQLite and MySQL adapters return 0. The parsing is countFromResults (unit-tested, no database needed). Also the CHANGELOG notes of the adapters clean-up. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
After an update's auto-insert, _fixeTableSequence set the sequence of the ID column (idFieldName) from a literal max(id): a table whose ID column isn't `id` failed. Now max of the quoted ID column. The SQL is fixTableSequenceSQL (unit-tested, no database needed). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The schema introspection queries (columns, ID field, indexes, constraints, foreign keys, the ID sequence fix) interpolated the table (and MySQL database) names into SQL string literals unescaped: a `'` in a name broke or changed the query. They now use DBSQLAdapter.sqlStringLiteral (quotes doubled; the queries are otherwise the same). The foreign keys queries are findFieldsReferencedTablesSQL, unit-tested with the fixTableSequenceSQL escaping (no database needed). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Nov 8, 2026
The adapters have 64-bit integer literals, which don't compile to JavaScript (the Chrome CI shard failed to load it). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MySQL's default sql_mode treats a backslash as an escape in literals, so doubling `'` wasn't enough: `x\\' OR 1=1 -- ` still ended the literal. DBSQLAdapter.sqlStringLiteral gets escapeBackslashes; MySQL uses it via mysqlStringLiteral. Tests for both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…Lazy merge - Object adapters (Memory, Directory, GCS): openTransaction typed as their context again (synchronous), as before the shared DBObjectAdapter one. - DBSQLAdapter.cancelTransaction default typed bool (as the MySQL/SQLite overrides it replaced). - EntityResolutionRules.merge: an allEager/allLazy cross-flag conflict is dropped as a same-flag conflict (both tolerant: both flags dropped; one tolerant: it yields its flag); only an intolerant merge throws. Tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- _CachedResponse no longer Comparable (nothing sorts responses one by one; the eviction sorts whole entries). - APIRequest._lastPathPartCache named and documented; _describeSubTransaction documented; TransactionOperationType.name comment corrected (Enum.name is an SDK extension); the memory delete's parameters comment says why. - Tests use contextProviders (the deprecated alias is tested on purpose in one place). - CHANGELOG: k3 moved to Fixes; resolveUserDirectory's platforms; the adapters' new API and defaults; the tolerant allEager/allLazy merge; the MySQL backslash escaping; the payload wording. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
sqlite3 3.9.0's build hook rejects its native library download (a hash mismatch since 2026-11-08; master passed with it at 07:48 that day): every test job fails before running. A pubspec_overrides.yaml in the test jobs only; the package constraint stays ^3.8.0. Remove once fixed upstream. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
sqlite3 3.9.0's build hook rejects its native library download (a hash mismatch since 2026-11-08): every VM run fails before starting. The package skips 3.9.0 (also for its dependents) instead of a CI-only pin, which is reverted. Raise the bound once a fixed release is out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Skipping 3.9.0 didn't help: 3.8.0 fails the same way. The build hook's download gets GitHub's 504 page (its SHA-256 is the 'wrong hash' bef140a1...) for any version: a GitHub release-download outage, not a sqlite3 release defect (simolus3/sqlite3.dart#435). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #209 +/- ##
==========================================
+ Coverage 95.85% 95.91% +0.06%
==========================================
Files 75 75
Lines 26519 25953 -566
==========================================
- Hits 25419 24894 -525
+ Misses 1100 1059 -41
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
The identity sets (O(1) membership for bulk stores) were allocated with every Transaction: two empty sets per call, measurable on the cheapest operations (benchmark: SQLite count -4%, byId -1.3% vs 1.34.0). The lists stay the source of truth; a set is created from its list once it grows past 16 operations, and smaller transactions scan the list (identity, as before). Test: a 40-operation transaction (duplicate add, double execution, waitOperation on both sides of the threshold). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The 2026-11-08 progression column now shows 1.35.0 at 00e258c (the day's 1.34.0 runs stay in their entries); notes: same-session tables and A/Bs, memory remove 4.9x, the lazy Transaction sets, PostgreSQL drift. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
One PR with the whole clean-code pass. It was built from four parts, which were developed separately and merged into this branch. #206, #207 and #208 are closed in favour of this PR.
Parts
toAPIRequestand header constants;_executesplit,mixinlookup helper.matchesInresolves its parameters once;qualifiedColumnSQL;_checkDBTableSchemesplit, relationship SQL generators, memory adapter select/delete,APIDBModule.selectsplit.Transactionidentity sets (bulkstoreAllwas O(n²));storeAllFromJson, references, extensions,Time, pagination, collections.DBObjectAdapter;DBSQLAdapter;openTransactionWithPool;ensureStoredwith hooks;newSelectOperation.All of it is behavior-preserving, except the fixes below. Generated SQL is unchanged, and private cache fields now follow the convention (
*Cache, documented, declared before use).Fixes (each with a test)
TypeErroron entries with compressed alternatives;~folder;IdenticalSetgrouped byhashCode;getFieldsKeysInMapreused one field's normalization for all fields.\\'inside single quotes;SQLDialect.toStringwas incomplete;APIDBModuleHTML wasn't escaped.GenericEntityHandler.getFieldTypeignored the resolved field name;populateFromSourceignoredworkingPath;storeAllFromJsonignoredtransactionandvariables;EntityReference(List).fromdidn't forwardentityHandlerProvider;IterableEntityRepository.deleteEntitydroppedtransaction;EntityAccessRules ==comparedentityFieldsby identity;allEagerandallLazyset together recursed forever.doCountSQLthrew when there was no row;_fixeTableSequenceused a hard-codedmax(id);Deprecated (still working)
EntityHandler.graterThan*Value,EntityRulesResolver.cotextProviders,getEntityRepositoresTables, andgetFieldsKeysInMap'sfieldLC/fieldSimple.Version 1.35.0, with its CHANGELOG section.
🤖 Generated with Claude Code