Last active
June 5, 2018 12:02
-
-
Save psixdev/09d35df41e8dc9702c4d9c85e3092b87 to your computer and use it in GitHub Desktop.
Sequelize bug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Sequelize = require('sequelize'); | |
const config = require('./config')(); | |
const {DataTypes} = Sequelize; | |
const db = new Sequelize({ | |
database: config.postgres.database, | |
username: config.postgres.user, | |
password: config.postgres.password, | |
host: config.postgres.host, | |
port: config.postgres.port, | |
dialect: 'postgres', | |
logging: false | |
}); | |
db.parents = db.define('Parent', { | |
_id: { | |
type: DataTypes.INTEGER, | |
primaryKey: true, | |
autoIncrement: true | |
} | |
}, { | |
timestamps: false, | |
tableName: 'parents' | |
}); | |
db.somethings = db.define('Something', { | |
_id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true} | |
}, { | |
timestamps: false, | |
tableName: 'somethings' | |
}); | |
db.children = db.define('Child', { | |
_id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}, | |
parentId: DataTypes.INTEGER, | |
somethingId: DataTypes.INTEGER | |
}, { | |
timestamps: false, | |
tableName: 'children' | |
}); | |
db.parents.hasMany(db.children, { | |
as: 'children', | |
foreignKey: 'parentId' | |
}); | |
db.somethings.hasMany(db.children, { | |
as: 'children', | |
foreignKey: 'somethingId' | |
}); | |
db.children.belongsTo(db.parents, { | |
as: 'parent', | |
foreignKey: 'parentId', | |
targetKey: '_id' | |
}); | |
db.children.belongsTo(db.somethings, { | |
as: 'something', | |
foreignKey: 'somethingId' | |
}); | |
(async () => { | |
try { | |
await db.transaction(async (transaction) => { | |
await db.parents.truncate({transaction}); | |
await db.somethings.truncate({transaction}); | |
await db.children.truncate({transaction}); | |
const {_id: parentId} = await db.parents.create({}, {transaction}); | |
const {_id: somethingId} = await db.somethings.create({}, {transaction}); | |
await db.children.bulkCreate( | |
[{parentId, somethingId}, {parentId, somethingId}], | |
{transaction} | |
); | |
const parents = await db.parents.findAll({ | |
include: [{ | |
model: db.children, | |
as: 'children', | |
required: true, | |
include: [{ | |
model: db.somethings, | |
as: 'something', | |
required: true | |
}] | |
}], | |
limit: 5, | |
transaction, | |
logging: console.log | |
}); | |
console.log( | |
require('util').inspect( | |
parents.map((parent) => parent.toJSON()), | |
false, | |
null | |
) | |
); | |
}); | |
} catch (err) { | |
console.log(err.stack); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment