GithubHelp home page GithubHelp logo

yonycalsin / nestjs-sequelize-seeder Goto Github PK

View Code? Open in Web Editor NEW
6.0 1.0 4.0 66 KB

๐ŸŒพ A simple extension library for nestjs sequelize to perform seeding.

Home Page: https://www.npmjs.com/package/nestjs-sequelize-seeder

License: MIT License

JavaScript 0.86% TypeScript 99.14%
nestjs sequelize seeder seeding nestjs-seeder sequelize-seeder

nestjs-sequelize-seeder's People

Contributors

dependabot-preview[bot] avatar renovate-bot avatar yonycalsin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

nestjs-sequelize-seeder's Issues

Sometimes get "Cannot add or update a child row" due to foreign key reference missing

Hi i'm getting this error from time to time when my nestjs project is reloading due to changes in the code. I run it in watch mode locally so it reloads the seeder everytime so I have data to debug.

Here is the error, made it more generic, but it basically says that the Foreign Key ID in the table I want to reference does not exist yet:
[Seeder] [ERROR...] Cannot add or update a child row: a foreign key constraint fails (database.Table1, CONSTRAINT Constraint_ibfk_1 FOREIGN KEY (ForeignKeyId) REFERENCES Table2 (id) ON DELETE NO ACTION ON UPDATE CASCADE)

E.g.:

Loading cat row into db before the row for breedId 2 has been loaded results in the error above.

First loaded
Cat: {
id = 1;
breedId = 2;
}

Loaded second
Breed: {
id = 2;
name = persian;
}

Sometimes get "Cannot add or update a child row" due to foreign key reference missing

It can also be the order, of the execution.

For example, when sequelize returns an error, when creating a new object for your model, there the id will increase, therefore the added associations will not match.

First you will have to execute the tables in their proper order, for example, if you create a breed and cat table, and associate it, then you will have to execute the breed table first and then cat, since the cat table depends on the breed table.

With nestjs it's easy to sort, the modules.

Module({
   imports: [
      // First
      BreedModule,
      // Second
      CatModule,
   ],
});
class AppModule {}

For the 'Breed' seed

const data = [
   {
      // Here don't forget to add the id
      id: 1,
      name: 'persian',
   },
];

For the 'Cat' seed

const data = [
   {
      // You'll also have to add an id, to save us some trouble
      id: 1,
      breedId: 1,
   },
];

I hope this helps you!

Originally posted by @yoicalsin in #12 (comment)

v1.0.9 issues with junction table, FK reference due to order of tables loaded, ValidationErrors...Etc

@yoicalsin

Junction table issue

I'd also like to point out i'm using a junction table for my CatBreed many-to-many relation. I'm having some issues with this as well. The db cant find the FK relation id's of the Cat & Breed models (example: catId, breedId).
This worked perfectly in v1.0.7 of "nestjs-sequelize-seeder"

At the moment those error logs have stopped appearing after playing around with the settings, not sure if it's still there or not. Just going to mention it anyway.

Here is my junction table seeder:

@Seeder({
    unique: [],
    model: CatBreed
})
export class SeedCatBreeds implements OnSeederInit {
    run() {
        return [
            {id: 1, catId: 1, breedId: 1},
            {id: 2, catId: 1, breedId: 4},
            {id: 3, catId: 2, breedId: 2},
            {id: 4, catId: 2, breedId: 3},
        ] as CatBreed[];
    }
}

my junction table model:

@Table
export class CatBreed extends Model<CatBreed> {
    @PrimaryKey
    @AutoIncrement
    @Column
    id: number;

    @ForeignKey(() => Breed)
    @Column
    breedId: number;
    @BelongsTo(() => Breed)
    breed: Breed;

    @ForeignKey(() => Cat)
    @Column
    catId: number;
    @BelongsTo(() => Cat)
    cat: Cat;
}

this is another error, which is a weird one, since CatBreed does not have a name column... why would it look for that

@Seeder({
    model: Cat,
    unique: ['name'], // -> this gives an error:
                        // Error: [SeederService] Unknown column 'CatBreed.name' in 'where clause'
})
export class SeedCats implements OnSeederInit {
    run() {
        return [
            {
                id: 1,
                name: 'Mr Mistofeles',
            },
        ]
    }
}

getting validationErrors often as well :

Unhandled rejection SequelizeUniqueConstraintError: Validation error
    at Query.formatError (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/sequelize/lib/dialects/mysql/query.js:223:16)
    at Execute.handler [as onResult] (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/sequelize/lib/dialects/mysql/query.js:51:23)
    at Execute.execute (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/mysql2/lib/commands/command.js:30:14)
    at Connection.handlePacket (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/mysql2/lib/connection.js:417:32)
    at PacketParser.onPacket (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/mysql2/lib/connection.js:75:12)
    at PacketParser.executeStart (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/mysql2/lib/packet_parser.js:75:16)
    at Socket.<anonymous> (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/mysql2/lib/connection.js:82:25)
    at Socket.emit (events.js:311:20)
    at addChunk (_stream_readable.js:294:12)
    at readableAddChunk (_stream_readable.js:275:11)
    at Socket.Readable.push (_stream_readable.js:209:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:186:23)

also still getting this error:

Unhandled rejection SequelizeForeignKeyConstraintError: Cannot add or update a child row: a foreign key constraint fails (`animals`.`CatBreeds`, CONSTRAINT `CatBreeds_ibfk_1` FOREIGN KEY (`catId`) REFERENCES `Cats` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)

I think this error is caused due to the "cat" that needs to be referenced isn't loaded yet.
I've kept an eye in terms of order of loading modules & seeders where the ones with FK's get loaded last.
So that's not the issue I think.

I've also deleted the database as well.

These are my settings for sequilize and the seeder module

SequelizeModule.forRootAsync({
        useFactory: () => {
            return {
                ...
                autoLoadModels: true,
                synchronize: true,
                sync: {
                    force: true,
                },
                ...
            };
        },
    }),

SeederModule.forRoot({
    isGlobal: true,
    logging: true,
    connection: 'animals',
}),

package.json

"nestjs-sequelize-seeder": "~1.0.9",
"sequelize": "^5.21.6",
"sequelize-cli": "^5.5.1",
"sequelize-typescript": "^1.1.0",
"@nestjs/sequelize": "^0.1.0",
"@types/sequelize": "^4.28.8",
"mysql2": "^2.1.0",

Undefined error logs postgreSQL dialect

image

I'm using v1.0.7 at the moment of this nestjs-sequelize-seeder library because the newest one is broken or something.
I've switched from MySQL to PostgreSQL and now i'm getting undefined errors in my logs without any further detailed explanation.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.