|
| 1 | +const Sequelize = require('sequelize'); |
| 2 | + |
| 3 | +const config = require('./config'); |
| 4 | + |
| 5 | +console.log('init sequelize...'); |
| 6 | + |
| 7 | +var sequelize = new Sequelize(config.database, config.username, config.password, { |
| 8 | + host: config.host, |
| 9 | + dialect: 'mysql', |
| 10 | + pool: { |
| 11 | + max: 5, |
| 12 | + min: 0, |
| 13 | + idle: 30000 |
| 14 | + } |
| 15 | +}); |
| 16 | + |
| 17 | +var Pet = sequelize.define('pet', { |
| 18 | + id: { |
| 19 | + type: Sequelize.STRING(50), |
| 20 | + primaryKey: true |
| 21 | + }, |
| 22 | + name: Sequelize.STRING(100), |
| 23 | + gender: Sequelize.BOOLEAN, |
| 24 | + birth: Sequelize.STRING(10), |
| 25 | + createdAt: Sequelize.BIGINT, |
| 26 | + updatedAt: Sequelize.BIGINT, |
| 27 | + version: Sequelize.BIGINT |
| 28 | +}, { |
| 29 | + timestamps: false |
| 30 | + }); |
| 31 | + |
| 32 | +var now = Date.now(); |
| 33 | + |
| 34 | +Pet.create({ |
| 35 | + id: 'g-' + now, |
| 36 | + name: 'Gaffey', |
| 37 | + gender: false, |
| 38 | + birth: '2007-07-07', |
| 39 | + createdAt: now, |
| 40 | + updatedAt: now, |
| 41 | + version: 0 |
| 42 | +}).then(function (p) { |
| 43 | + console.log('created.' + JSON.stringify(p)); |
| 44 | +}).catch(function (err) { |
| 45 | + console.log('failed: ' + err); |
| 46 | +}); |
| 47 | + |
| 48 | +(async () => { |
| 49 | + var dog = await Pet.create({ |
| 50 | + id: 'd-' + now, |
| 51 | + name: 'Odie', |
| 52 | + gender: false, |
| 53 | + birth: '2008-08-08', |
| 54 | + createdAt: now, |
| 55 | + updatedAt: now, |
| 56 | + version: 0 |
| 57 | + }); |
| 58 | + console.log('created: ' + JSON.stringify(dog)); |
| 59 | +})(); |
| 60 | + |
| 61 | +(async () => { |
| 62 | + var pets = await Pet.findAll({ |
| 63 | + where: { |
| 64 | + name: 'Gaffey' |
| 65 | + } |
| 66 | + }); |
| 67 | + console.log(`find ${pets.length} pets:`); |
| 68 | + for (let p of pets) { |
| 69 | + console.log(JSON.stringify(p)); |
| 70 | + console.log('update pet...'); |
| 71 | + p.gender = true; |
| 72 | + p.updatedAt = Date.now(); |
| 73 | + p.version ++; |
| 74 | + await p.save(); |
| 75 | + if (p.version === 3) { |
| 76 | + await p.destroy(); |
| 77 | + console.log(`${p.name} was destroyed.`); |
| 78 | + } |
| 79 | + } |
| 80 | +})(); |
0 commit comments