fix: find table sequence (#1101)

This commit is contained in:
ChengLei Shao 2022-11-17 20:16:03 +08:00 committed by GitHub
parent ba94dfaf6c
commit 395c441b21
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 15 deletions

View File

@ -387,6 +387,13 @@ pgOnly()('collection inherits', () => {
});
expect(a2.get('id')).toEqual(2);
db.collection({
name: 'd',
inherits: ['c'],
});
await db.sync();
});
it('should update inherit field when parent field update', async () => {

View File

@ -34,12 +34,22 @@ export class SyncRunner {
if (childAttributes.id && childAttributes.id.autoIncrement) {
for (const parent of parentTables) {
const sequenceNameResult = await queryInterface.sequelize.query(
`select pg_get_serial_sequence('"${parent}"', 'id')`,
`SELECT column_default FROM information_schema.columns WHERE
table_name='${parent}' and "column_name" = 'id';`,
{
transaction,
},
);
const sequenceName = sequenceNameResult[0][0]['pg_get_serial_sequence'];
const columnDefault = sequenceNameResult[0][0]['column_default'];
if (!columnDefault) {
throw new Error(`Can't find sequence name of ${parent}`);
}
const regex = new RegExp(/nextval\('(\w+)\'.*\)/);
const match = regex.exec(columnDefault);
const sequenceName = match[1];
const sequenceCurrentValResult = await queryInterface.sequelize.query(
`select last_value from ${sequenceName}`,
@ -47,7 +57,7 @@ export class SyncRunner {
transaction,
},
);
const sequenceCurrentVal = sequenceCurrentValResult[0][0]['last_value'];
const sequenceCurrentVal = parseInt(sequenceCurrentValResult[0][0]['last_value']);
if (sequenceCurrentVal > maxSequenceVal) {
maxSequenceName = sequenceName;
@ -58,19 +68,21 @@ export class SyncRunner {
await this.createTable(tableName, childAttributes, options, model, parentTables);
const parentsDeep = Array.from(db.inheritanceMap.getParents(inheritedCollection.name)).map(
(parent) => db.getCollection(parent).model.tableName,
);
const sequenceTables = [...parentsDeep, tableName];
for (const sequenceTable of sequenceTables) {
await queryInterface.sequelize.query(
`alter table "${sequenceTable}" alter column id set default nextval('${maxSequenceName}')`,
{
transaction,
},
if (maxSequenceName) {
const parentsDeep = Array.from(db.inheritanceMap.getParents(inheritedCollection.name)).map(
(parent) => db.getCollection(parent).model.tableName,
);
const sequenceTables = [...parentsDeep, tableName];
for (const sequenceTable of sequenceTables) {
await queryInterface.sequelize.query(
`alter table "${sequenceTable}" alter column id set default nextval('${maxSequenceName}')`,
{
transaction,
},
);
}
}
if (options.alter) {