Skip to content

Commit

Permalink
Forbid circular mappings in auto mapper
Browse files Browse the repository at this point in the history
Fixes #888
  • Loading branch information
maxpatiiuk committed Mar 17, 2023
1 parent 6a32f0b commit f4cd803
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import { theories } from '../../../tests/utils';
import type { RA } from '../../../utils/types';
import type { AutoMapperResults } from '../autoMapper';
import {
type AutoMapperConstructorParameters,
AutoMapper as AutoMapperConstructor,
type AutoMapperConstructorParameters,
circularTables,
} from '../autoMapper';

requireContext();
Expand Down Expand Up @@ -198,3 +199,22 @@ theories(
},
]
);

test('circular tables are calculated correctly', () =>
expect(circularTables()).toMatchInlineSnapshot(`
[
"[table Agent]",
"[table Container]",
"[table Geography]",
"[table GeographyTreeDefItem]",
"[table GeologicTimePeriod]",
"[table GeologicTimePeriodTreeDefItem]",
"[table LithoStrat]",
"[table LithoStratTreeDefItem]",
"[table ReferenceWork]",
"[table Storage]",
"[table StorageTreeDefItem]",
"[table Taxon]",
"[table TaxonTreeDefItem]",
]
`));
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type { IR, R, RA, Writable, WritableArray } from '../../utils/types';
import { filterArray } from '../../utils/types';
import { findArrayDivergencePoint } from '../../utils/utils';
import type { AnyTree } from '../DataModel/helperTypes';
import { getModel, strictGetModel } from '../DataModel/schema';
import { getModel, schema, strictGetModel } from '../DataModel/schema';
import type { Relationship } from '../DataModel/specifyField';
import type { SpecifyModel } from '../DataModel/specifyModel';
import type { Tables } from '../DataModel/types';
Expand Down Expand Up @@ -602,6 +602,10 @@ export class AutoMapper {
if (
// Don't iterate over the same table again
this.searchedTables.includes(tableName) ||
// Don't allow circular mappings
(mappingPath.length > 0 &&
tableName === this.baseTable.name &&
!circularTables().includes(this.baseTable)) ||
// Don't go beyond the depth limit
mappingPath.length > depthLimit
)
Expand Down Expand Up @@ -989,3 +993,12 @@ export class AutoMapper {
return !pathContainsToManyReferences && !this.allowMultipleMappings;
}
}

/**
* Tables that have relationships to themself
*/
export const circularTables = f.store<RA<SpecifyModel>>(() =>
Object.values(schema.models).filter(({ relationships, name }) =>
relationships.some(({ relatedModel }) => relatedModel.name === name)
)
);

0 comments on commit f4cd803

Please sign in to comment.