chore(database): set null value when field is unique and value is empty string (#3997)

* chore(database): set null value when field is unique and value is empty string

* fix: build
This commit is contained in:
ChengLei Shao 2024-04-10 08:49:19 +08:00 committed by GitHub
parent 6595fde713
commit 0bb5d5f5ee
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 125 additions and 0 deletions

View File

@ -0,0 +1,114 @@
import { Database, mockDatabase } from '@nocobase/database';
describe('unique field', () => {
let db: Database;
beforeEach(async () => {
db = mockDatabase({
logging: console.log,
});
await db.clean({ drop: true });
});
afterEach(async () => {
await db.close();
});
it('should not transform empty string to null when field is not unique', async () => {
const User = db.collection({
name: 'users',
fields: [
{
type: 'string',
name: 'name',
},
],
});
await db.sync();
await User.repository.create({
values: [
{},
{
name: '',
},
{
name: 'user3',
},
],
});
const u3 = await User.repository.findOne({
filter: {
name: 'user3',
},
});
await User.repository.update({
filter: {
id: u3.id,
},
values: {
name: '',
},
});
await u3.reload();
expect(u3.get('name')).toBe('');
});
it('should transform empty string to null when field is unique', async () => {
const User = db.collection({
name: 'users',
fields: [
{
type: 'string',
name: 'name',
unique: true,
},
],
});
await db.sync();
await User.repository.create({
values: [
{},
{
name: '',
},
{
name: 'user3',
},
],
});
const u3 = await User.repository.findOne({
filter: {
name: 'user3',
},
});
let error;
try {
await User.repository.update({
filter: {
id: u3.id,
},
values: {
name: '',
},
});
} catch (e) {
error = e;
}
expect(error).toBeUndefined();
await u3.reload();
expect(u3.get('name')).toBe(null);
});
});

View File

@ -406,6 +406,17 @@ export class Database extends EventEmitter implements AsyncEmitter {
instance?.toChangedWithAssociations?.();
});
this.on('beforeValidate', async (instance) => {
for (const [key, attribute] of Object.entries(instance.constructor.rawAttributes)) {
// @ts-ignore
if (attribute.unique && instance.changed(key)) {
if (instance.get(key) === '') {
instance.set(key, null);
}
}
}
});
this.on('afterUpdate', async (instance) => {
instance?.toChangedWithAssociations?.();
});