fix: sort field init (#2520)

* fix: sort field init

* chore: sort field name
This commit is contained in:
ChengLei Shao 2023-08-24 14:26:03 +08:00 committed by GitHub
parent b0630005d9
commit 0f9d946f09
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 45 additions and 4 deletions

View File

@ -17,6 +17,34 @@ describe('string field', () => {
await db.close();
});
it('should init with camelCase scope key', async () => {
const Test = db.collection({
name: 'tests',
fields: [
{
type: 'string',
name: 'name',
},
{
type: 'string',
name: 'scopeKey',
},
],
});
await db.sync();
await Test.repository.create({
values: {
name: 't1',
scopeKey: 'a',
},
});
Test.setField('scopeKeySort', { type: 'sort', scopeKey: 'scopeKey' });
await db.sync();
});
it('should init sorted value with thousand records', async () => {
const Test = db.collection({
name: 'tests',

View File

@ -44,9 +44,11 @@ export class SortField extends Field {
initRecordsSortValue = async ({ transaction }) => {
const orderField = (() => {
const model = this.collection.model;
if (model.primaryKeyAttribute) {
return model.primaryKeyAttribute;
}
if (model.rawAttributes['createdAt']) {
return model.rawAttributes['createdAt'].field;
}
@ -79,8 +81,19 @@ export class SortField extends Field {
const doInit = async (scopeKey = null, scopeValue = null) => {
const queryInterface = this.collection.db.sequelize.getQueryInterface();
if (scopeKey) {
const scopeField = this.collection.getField(scopeKey);
if (!scopeField) {
throw new Error(`can not find scope field ${scopeKey} for collection ${this.collection.name}`);
}
scopeKey = this.collection.model.rawAttributes[scopeKey].field;
}
const quotedOrderField = queryInterface.quoteIdentifier(orderField);
const sortColumnName = this.collection.model.rawAttributes[this.name].field;
const sql = `
WITH ordered_table AS (
SELECT *, ROW_NUMBER() OVER (${
@ -105,16 +118,16 @@ export class SortField extends Field {
this.collection.db.inDialect('mysql')
? `
UPDATE ${this.collection.quotedTableName()}, ordered_table
SET ${this.collection.quotedTableName()}.${this.name} = ordered_table.new_sequence_number
SET ${this.collection.quotedTableName()}.${sortColumnName} = ordered_table.new_sequence_number
WHERE ${this.collection.quotedTableName()}.${quotedOrderField} = ordered_table.${quotedOrderField}
`
: `
UPDATE ${this.collection.quotedTableName()}
SET ${queryInterface.quoteIdentifier(this.name)} = ordered_table.new_sequence_number
SET ${queryInterface.quoteIdentifier(sortColumnName)} = ordered_table.new_sequence_number
FROM ordered_table
WHERE ${this.collection.quotedTableName()}.${quotedOrderField} = ${queryInterface.quoteIdentifier(
'ordered_table',
)}.${quotedOrderField};
'ordered_table',
)}.${quotedOrderField};
`
}