From 3da2a8af920a7d106af03d4798d9c0fe858b4cbe Mon Sep 17 00:00:00 2001 From: ChengLei Shao Date: Mon, 11 Mar 2024 19:37:48 +0800 Subject: [PATCH] fix: init scope value when all data is null value (#3674) --- .../src/__tests__/fields/sort-field.test.ts | 35 +++++++++++++++++++ .../core/database/src/fields/sort-field.ts | 18 +++++++--- 2 files changed, 48 insertions(+), 5 deletions(-) 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')) {