Bug: No longer able to specify the order of seeds as of 2.1.10
jjbell150 opened this issue · 4 comments
Versions
- Node: Node 16
- OS: Windows 10
Reproduction
In order to meet foreign key constraints when seeding, we need to guarantee that our seeds are run in a specific synchronous order. For example, each User must have an Account, so we have to seed Accounts before we can seed Users
We currently do this by listing seeds in the correct order within data-source.ts, but as of 2.1.10 this no longer works as expected
This appears to be caused by these changes, which cause our seeds to be run asynchronously: 3abb417
Steps to reproduce
Example data-source.ts:
import { DataSource, DataSourceOptions } from 'typeorm'
import { SeederOptions } from 'typeorm-extension'
const options: DataSourceOptions & SeederOptions = {
name: 'default',
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'admin',
password: 'password',
database: 'db',
synchronize: false,
logger: 'simple-console',
entities: [
'src/entities/*/**.ts'
],
seeds: [
'src/seeds/create-accounts.ts',
'src/seeds/create-users.ts',
'src/seeds/*.ts'
]
}
export const dataSource = new DataSource(options)
Example create-accounts.ts seeder:
import { DataSource } from 'typeorm'
import { Seeder } from 'typeorm-extension'
import { Accounts } from '../entities/accounts'
import { accounts } from '../fixtures/accounts'
export default class CreateAccounts implements Seeder {
public async run (dataSource: DataSource): Promise<void> {
await dataSource
.createQueryBuilder()
.insert()
.into(Accounts)
.values(accounts)
.orIgnore()
.execute()
}
}
Example create-users.ts seeder:
import { DataSource } from 'typeorm'
import { Seeder } from 'typeorm-extension'
import { Users } from '../entities/users'
import { users } from '../fixtures/users'
export default class CreateUsers implements Seeder {
public async run (dataSource: DataSource): Promise<void> {
await dataSource
.createQueryBuilder()
.insert()
.into(Users)
.values(users)
.orIgnore()
.execute()
}
}
Seeder command:
ts-node --swc ./node_modules/typeorm-extension/dist/cli/index.js seed
What is Expected?
Seeds are run synchronously in the order listed within data-source.ts. First create-accounts.ts is run, then create-users.ts, then all other seed files
What is actually happening?
create-users.ts runs without waiting for create-accounts.ts to finish, causing create-users.ts to fail with a foreign-key violation because there are no accounts
I'm very sorry
I will fix this today and publish a new release ✌️
How can I set the order of seeds in the new version?
How can I set the order of seeds in the new version?
Put a serial number in the seed file name like the migration generator do.