Knex seed for postgres
See original GitHub issueI was playing around with different databases for this kit since we are mentioning over here that any database can be plugged into the kit in the same way as SQLite.
So, I tried plugging postgres
and faced an issue with the knex seed provided in this kit. The problem is we are using truncate()
for seed migration and comment
table is referencing post
table to populate the comments for a particular post_id
.
Since postgres
does not allow truncating tables if the table has any foreign key reference making the script yarn seed
fails.
However, using raw queries from knex does push the seed to completion, but it does not insert the post_id
reference in comment
table.
From this (in seeds/post.js)
await Promise.all([
knex('post').truncate(),
knex('comment').truncate()
]);
to this
await Promise.all([
knex.raw('TRUNCATE TABLE post CASCADE'),
knex.raw('TRUNCATE TABLE comment CASCADE')
]);
However, it returns null
for post_id
This is the final seed function in case of postgres
export async function seed(knex, Promise) {
await Promise.all([
knex.raw('TRUNCATE TABLE post CASCADE'),
knex.raw('TRUNCATE TABLE comment CASCADE')
]);
await Promise.all([...Array(20).keys()].map(async ii => {
const post = await knex('post').insert({
title: `Post title ${ii + 1}`,
content: `Post content ${ii + 1}`
});
await Promise.all([...Array(2).keys()].map(async jj => {
return knex('comment').insert({
post_id: post[0],
content: `Comment title ${jj + 1} for post ${post[0]}`
});
}));
}));
}
P.S -> Just in case you want to see my modified knexdata.js file
export const development = {
client: 'pg',
debug: true,
connection: {
host: '127.0.0.1',
user: 'postgres',
password: '*****',
database: 'dev_db'
},
seeds: {
directory: './src/server/database/seeds'
},
migrations: {
directory: './src/server/database/migrations'
},
useNullAsDefault: true
};
Another problem is the primary key (autoincrement) for post
and comment
table is not resetting back to 1
after running the seed every time.
Is there any workaround for this?
Issue Analytics
- State:
- Created 6 years ago
- Comments:11 (8 by maintainers)
Top GitHub Comments
This issue can be closed once https://github.com/sysgears/apollo-fullstack-starter-kit/pull/188 is merged.
Undefined binding(s)
error when adding post should be fixed via: https://github.com/sysgears/apollo-fullstack-starter-kit/commit/e3406ae46dc18774b41121151a99bd023a03cc23