diff --git a/packages/core/database/src/__tests__/fields/sort-field.test.ts b/packages/core/database/src/__tests__/fields/sort-field.test.ts index e53edf6a5..dbf0efffc 100644 --- a/packages/core/database/src/__tests__/fields/sort-field.test.ts +++ b/packages/core/database/src/__tests__/fields/sort-field.test.ts @@ -90,6 +90,41 @@ describe('string field', () => { console.log(end - begin); }); + it('should init sorted value with null scopeValue', async () => { + const Test = db.collection({ + name: 'tests', + fields: [ + { + type: 'string', + name: 'name', + }, + { + type: 'string', + name: 'group', + }, + ], + }); + + await db.sync(); + + await Test.repository.create({ + values: [ + { + group: null, + name: 'r5', + }, + { + group: null, + name: 'r6', + }, + ], + }); + + Test.setField('sort', { type: 'sort', scopeKey: 'group' }); + + await db.sync(); + }); + it('should init sorted value with scopeKey', async () => { const Test = db.collection({ name: 'tests', diff --git a/packages/core/database/src/fields/sort-field.ts b/packages/core/database/src/fields/sort-field.ts index 41cea73fc..30d9adae6 100644 --- a/packages/core/database/src/fields/sort-field.ts +++ b/packages/core/database/src/fields/sort-field.ts @@ -99,11 +99,19 @@ export class SortField extends Field { const whereClause = scopeKey && scopeValue - ? ` - WHERE ${queryInterface.quoteIdentifier(scopeKey)} IN (${scopeValue - .filter((v) => v !== null) - .map((v) => `'${v}'`) - .join(', ')})${scopeValue.includes(null) ? ` OR ${queryInterface.quoteIdentifier(scopeKey)} IS NULL` : ''}` + ? (() => { + const filteredScopeValue = scopeValue.filter((v) => v !== null); + if (filteredScopeValue.length === 0) { + return ''; + } + const initialClause = ` + WHERE ${queryInterface.quoteIdentifier(scopeKey)} IN (${filteredScopeValue.map((v) => `'${v}'`).join(', ')})`; + + const nullCheck = scopeValue.includes(null) + ? ` OR ${queryInterface.quoteIdentifier(scopeKey)} IS NULL` + : ''; + return initialClause + nullCheck; + })() : ''; if (this.collection.db.inDialect('postgres')) {