fix: belongs to many through table with custom schema (#1539)

This commit is contained in:
ChengLei Shao 2023-03-05 17:43:04 +08:00 committed by GitHub
parent d380c94c52
commit a214c7b2aa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 32 additions and 2 deletions

View File

@ -55,9 +55,15 @@ export class BelongsToManyField extends RelationField {
if (database.hasCollection(through)) { if (database.hasCollection(through)) {
Through = database.getCollection(through); Through = database.getCollection(through);
} else { } else {
Through = database.collection({ const throughCollectionOptions = {
name: through, name: through,
}); };
if (this.collection.collectionSchema()) {
throughCollectionOptions['schema'] = this.collection.collectionSchema();
}
Through = database.collection(throughCollectionOptions);
Object.defineProperty(Through.model, 'isThrough', { value: true }); Object.defineProperty(Through.model, 'isThrough', { value: true });
} }

View File

@ -51,5 +51,29 @@ describe('belongsToMany', () => {
}); });
expect(throughCollection.get('sortable')).toEqual(false); expect(throughCollection.get('sortable')).toEqual(false);
const collectionManagerSchema = process.env.COLLECTION_MANAGER_SCHEMA;
const mainSchema = process.env.DB_SCHEMA || 'public';
if (collectionManagerSchema && mainSchema != collectionManagerSchema && db.inDialect('postgres')) {
expect(throughCollection.get('schema')).toEqual(collectionManagerSchema);
const tableName = db.getCollection('post_tags').model.tableName;
const mainSchema = process.env.DB_SCHEMA || 'public';
const tableExists = async (tableName: string, schema: string) => {
const sql = `SELECT EXISTS(SELECT 1 FROM information_schema.tables
WHERE table_schema = '${schema}'
AND table_name = '${tableName}')`;
const results = await db.sequelize.query(sql, { type: 'SELECT' });
const exists = results[0]['exists'];
return exists;
};
expect(await tableExists(tableName, collectionManagerSchema)).toBe(true);
expect(await tableExists(tableName, mainSchema)).toBe(false);
}
}); });
}); });