Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle multiple sorts on records query #613

Merged
merged 3 commits into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions apps/core/src/__tests__/e2e/api/records/records.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ describe('Records', () => {
const sfTestLibTreeId = 'records_sort_filter_test_lib_tree';
const testTreeId = 'records_sf_test_tree';
const testSimpleAttrId = 'records_sort_filter_test_attr_simple';
const testSimpleAttrId2 = 'records_sort_filter_test_attr_simple2';
const testSimpleExtAttrId = 'records_sort_filter_test_attr_simple_extended';
const testSimpleLinkAttrId = 'records_sort_filter_test_attr_simple_link';
const testAdvAttrId = 'records_sort_filter_test_attr_adv';
Expand Down Expand Up @@ -315,6 +316,12 @@ describe('Records', () => {
label: 'test',
format: AttributeFormats.TEXT
});
await gqlSaveAttribute({
id: testSimpleAttrId2,
type: AttributeTypes.SIMPLE,
label: 'test 2',
format: AttributeFormats.TEXT
});
await gqlSaveAttribute({
id: testSimpleExtAttrId,
type: AttributeTypes.SIMPLE,
Expand Down Expand Up @@ -375,6 +382,7 @@ describe('Records', () => {
// Save attributes on libs
await gqlSaveLibrary(sfTestLibId, 'Test', [
testSimpleAttrId,
testSimpleAttrId2,
testSimpleExtAttrId,
testAdvAttrId,
testSimpleLinkAttrId,
Expand Down Expand Up @@ -484,6 +492,21 @@ describe('Records', () => {
recordId: "${sfRecord3}",
attribute: "${testSimpleAttrId}",
value: {payload: "B"}) { id_value }
v4: saveValue(
library: "${sfTestLibId}",
recordId: "${sfRecord1}",
attribute: "${testSimpleAttrId2}",
value: {payload: "1"}) { id_value }
v5: saveValue(
library: "${sfTestLibId}",
recordId: "${sfRecord2}",
attribute: "${testSimpleAttrId2}",
value: {payload: "1"}) { id_value }
v6: saveValue(
library: "${sfTestLibId}",
recordId: "${sfRecord3}",
attribute: "${testSimpleAttrId2}",
value: {payload: "2"}) { id_value }
}`);
});

Expand Down Expand Up @@ -517,6 +540,78 @@ describe('Records', () => {
expect(res.data.data.records.list[1].id).toBe(sfRecord3);
expect(res.data.data.records.list[2].id).toBe(sfRecord1);
});

describe('Multiple sorts', () => {
// +--------------+---------------------+--------------------+
// | | testSimpleAttribute | testSimpleAttrId2 |
// +--------------+---------------------+--------------------+
// | sfRecord1 | C | 1 |
// | sfRecord2 | A | 1 |
// | sfRecord3 | B | 2 |
// +--------------+---------------------+--------------------+

const _makeCall = async (
testSimpleAttrId2Order: 'asc' | 'desc',
testSimpleAttrIdOrder: 'asc' | 'desc'
) =>
makeGraphQlCall(`{
records(
library: "${sfTestLibId}",
multipleSort: [
{field: "${testSimpleAttrId2}", order: ${testSimpleAttrId2Order}},
{field: "${testSimpleAttrId}", order: ${testSimpleAttrIdOrder}}
]
) {
list {
id
}
}
}`);

test('Sort on multiple attributes asc / asc', async () => {
const res = await _makeCall('asc', 'asc');

expect(res.data.errors).toBeUndefined();
expect(res.data.data.records.list.map((record: {id: string}) => record.id)).toEqual([
sfRecord2,
sfRecord1,
sfRecord3
]);
});

test('Sort on multiple attributes desc / asc', async () => {
const res = await _makeCall('desc', 'asc');

expect(res.data.errors).toBeUndefined();
expect(res.data.data.records.list.map((record: {id: string}) => record.id)).toEqual([
sfRecord3,
sfRecord2,
sfRecord1
]);
});

test('Sort on multiple attributes asc / desc', async () => {
const res = await _makeCall('asc', 'desc');

expect(res.data.errors).toBeUndefined();
expect(res.data.data.records.list.map((record: {id: string}) => record.id)).toEqual([
sfRecord1,
sfRecord2,
sfRecord3
]);
});

test('Sort on multiple attributes desc / desc', async () => {
const res = await _makeCall('desc', 'desc');

expect(res.data.errors).toBeUndefined();
expect(res.data.data.records.list.map((record: {id: string}) => record.id)).toEqual([
sfRecord3,
sfRecord1,
sfRecord2
]);
});
});
P0ppoff marked this conversation as resolved.
Show resolved Hide resolved
});

describe('On simple extended attribute', () => {
Expand Down
2 changes: 2 additions & 0 deletions apps/core/src/app/core/recordApp/_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ export interface IRecordsQueryPagination {
export interface IRecordsQueryVariables {
library: string;
filters?: IRecordFilterLight[];
// @deprecated Should use multipleSort. They are both here for backward compatibility. Eventually, multipleSort will replace sort.
sort?: IRecordSortLight;
multipleSort?: IRecordSortLight[];
version?: IRecordsQueryVersion[];
pagination?: IRecordsQueryPagination;
retrieveInactive?: boolean;
Expand Down
6 changes: 4 additions & 2 deletions apps/core/src/app/core/recordApp/recordApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,8 @@ export default function ({
records(
library: ID!,
filters: [RecordFilterInput],
sort: RecordSortInput
sort: RecordSortInput @deprecated(reason: "Should use multipleSort. They are both here for backward compatibility. Eventually, multipleSort will replace sort."),
multipleSort: [RecordSortInput!]
version: [ValueVersionInput],
pagination: RecordsPagination,
retrieveInactive: Boolean,
Expand Down Expand Up @@ -274,6 +275,7 @@ export default function ({
library,
filters,
sort,
multipleSort,
version,
pagination,
retrieveInactive = false,
Expand Down Expand Up @@ -302,7 +304,7 @@ export default function ({
const params: IFindRecordParams = {
library,
filters,
sort,
sort: multipleSort ?? [sort],
pagination: pagination?.cursor
? (pagination as ICursorPaginationParams)
: (pagination as IPaginationParams),
Expand Down
2 changes: 1 addition & 1 deletion apps/core/src/domain/record/_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {IValue, IValuesOptions, IValueVersion} from '_types/value';
export interface IFindRecordParams {
library: string;
filters?: IRecordFilterLight[];
sort?: IRecordSortLight;
sort?: IRecordSortLight[];
options?: IValuesOptions;
pagination?: IPaginationParams | ICursorPaginationParams;
withCount?: boolean;
Expand Down
68 changes: 35 additions & 33 deletions apps/core/src/domain/record/recordDomain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1029,7 +1029,7 @@ export default function ({
const {library, sort, pagination, withCount, retrieveInactive = false} = params;
const {filters = [] as IRecordFilterLight[], fulltextSearch} = params;
const fullFilters: IRecordFilterOption[] = [];
let fullSort: IRecordSort;
let fullSort: IRecordSort[] = [];

await validateHelper.validateLibrary(library, ctx);

Expand Down Expand Up @@ -1123,39 +1123,43 @@ export default function ({
}

// Check sort fields
if (sort) {
const sortAttributes = await getAttributesFromField({
field: sort.field,
condition: null,
deps: {
'core.domain.attribute': attributeDomain,
'core.infra.library': libraryRepo,
'core.infra.tree': treeRepo
},
ctx
});
if (sort?.length) {
fullSort = await Promise.all(
sort.filter(Boolean).map(async s => {
const sortAttributes = await getAttributesFromField({
field: s.field,
condition: null,
deps: {
'core.domain.attribute': attributeDomain,
'core.infra.library': libraryRepo,
'core.infra.tree': treeRepo
},
ctx
});

const sortAttributesRepo = (await Promise.all(
sortAttributes.map(async a =>
!!a.reverse_link
? {
...a,
reverse_link: await attributeDomain.getAttributeProperties({
id: a.reverse_link as string,
ctx
})
}
: a
)
)) as IAttributeWithRevLink[];

fullSort = {
attributes: sortAttributesRepo,
order: sort.order
};
const sortAttributesRepo = (await Promise.all(
sortAttributes.map(async a =>
!!a.reverse_link
? {
...a,
reverse_link: await attributeDomain.getAttributeProperties({
id: a.reverse_link as string,
ctx
})
}
: a
)
)) as IAttributeWithRevLink[];

return {
attributes: sortAttributesRepo,
order: s.order
};
}, [])
);
}

const records = await recordRepo.find({
return recordRepo.find({
libraryId: library,
filters: fullFilters,
sort: fullSort,
Expand All @@ -1165,8 +1169,6 @@ export default function ({
fulltextSearch,
ctx
});

return records;
},
getRecordIdentity: _getRecordIdentity,
async getRecordFieldValue({library, record, attributeId, options, ctx}) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ exports[`AttributeAdvancedLinkRepo sortQueryPart Should return advanced link sor
"value2": "linked",
"value3": "ASC",
},
"query": "SORT FIRST(
"query": "FIRST(
FOR v, e IN 1 OUTBOUND r._id
@@value0
FILTER e.attribute == @value1 RETURN v.@value2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ exports[`AttributeStandardRepo sortQueryPart Should return advanced filter 1`] =
"value1": "label",
"value2": "ASC",
},
"query": "SORT FIRST(
"query": "FIRST(
FOR v, e IN 1 OUTBOUND r._id
@@value0
FILTER e.attribute == @value1 RETURN v.value
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ exports[`AttributeSimpleLinkRepo sortQueryPart Should return simple link sort 1`
"value2": "linked",
"value3": "ASC",
},
"query": "SORT
"query": "
FIRST(FOR l IN @value0
FILTER TO_STRING(r.@value1) == l._key
RETURN l.@value2)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,6 @@ exports[`AttributeSimpleRepo sortQueryPart Should return simple sort 1`] = `
"value0": "_key",
"value1": "ASC",
},
"query": "SORT r.@value0 @value1",
"query": "r.@value0 @value1",
}
`;
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ exports[`AttributeTreeRepo sortQueryPart Should return tree filter 1`] = `
"value3": "linked",
"value4": "ASC",
},
"query": "SORT FIRST(
"query": "FIRST(
FOR v, e IN 1 OUTBOUND r._id
@@value0, @@value1
FILTER e.attribute == @value2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1066,7 +1066,6 @@ describe('AttributeAdvancedLinkRepo', () => {
order: 'ASC'
});

expect(filter.query).toMatch(/^SORT/);
expect(filter).toMatchSnapshot();
});
});
Expand Down
15 changes: 6 additions & 9 deletions apps/core/src/infra/attributeTypes/attributeAdvancedLinkRepo.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright LEAV Solutions 2017 until 2023/11/05, Copyright Aristid from 2023/11/06
// This file is released under LGPL V3
// License text available at https://www.gnu.org/licenses/lgpl-3.0.txt
import {aql, AqlQuery, GeneratedAqlQuery, join, literal} from 'arangojs/aql';
import {aql, GeneratedAqlQuery, join, literal} from 'arangojs/aql';
import {IFilterTypesHelper} from 'infra/record/helpers/filterTypes';
import {IUtils} from 'utils/utils';
import {ILinkValue, IValueEdge} from '_types/value';
Expand All @@ -10,7 +10,7 @@ import {AttributeFormats, AttributeTypes, IAttribute} from '../../_types/attribu
import {IRecord} from '../../_types/record';
import {IDbService} from '../db/dbService';
import {IDbUtils} from '../db/dbUtils';
import {BASE_QUERY_IDENTIFIER, IAttributeTypeRepo, IAttributeWithRevLink} from './attributeTypesRepo';
import {BASE_QUERY_IDENTIFIER, IAttributeTypeRepo} from './attributeTypesRepo';
import {GetConditionPart} from './helpers/getConditionPart';

interface ISavedValueResult {
Expand Down Expand Up @@ -296,7 +296,7 @@ export default function ({

return _buildLinkValue(dbUtils.cleanup(res[0].linkedRecord), res[0].edge, !!attribute.reverse_link);
},
sortQueryPart({attributes, order}: {attributes: IAttributeWithRevLink[]; order: string}): AqlQuery {
sortQueryPart({attributes, order}) {
const collec = dbService.db.collection(VALUES_LINKS_COLLECTION);
const linked = !attributes[1]
? {id: '_key', format: AttributeFormats.TEXT}
Expand Down Expand Up @@ -324,12 +324,9 @@ export default function ({
`;
}

const query =
linked.format !== AttributeFormats.EXTENDED
? aql`SORT ${linkedValue} ${order}`
: aql`SORT ${_getExtendedFilterPart(attributes, linkedValue)} ${order}`;

return query;
return linked.format !== AttributeFormats.EXTENDED
? aql`${linkedValue} ${order}`
: aql`${_getExtendedFilterPart(attributes, linkedValue)} ${order}`;
},
filterValueQueryPart(attributes, filter, parentIdentifier = BASE_QUERY_IDENTIFIER) {
const collec = dbService.db.collection(VALUES_LINKS_COLLECTION);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -658,7 +658,6 @@ describe('AttributeStandardRepo', () => {
order: 'ASC'
});

expect(filter.query).toMatch(/^SORT/);
expect(filter).toMatchSnapshot();
});
});
Expand Down
Loading
Loading