排序findOrCreate事务

时间:2019-08-23 15:26:04

标签: transactions sequelize.js

我正在将Sqlite 3 (4.0.6)与Sequalize (4.38.0)一起使用。模型是具有许多季节的比赛(唯一的索引年份和TournamentId)。这是冲洗类:

  async flush(tournamentJSON) {
    this.tournamentJSON = tournamentJSON
    const {sequelize} = await this.orm
    this.transaction = await sequelize.transaction()
    try {
      const tournament = await this.flushTournament()
      const season = await this.flushSeason(tournament)
      // commit
      await this.transaction.commit();

    } catch (err) {
      console.log(err)
      // Rollback transaction if any errors were encountered
      if (err) await this.transaction.rollback();
    }
  }

  async flushTournament() {
    const {tournamentJSON} = this
    const {models: {Tournament}} = await this.orm
    const [tournament, created] = await Tournament.findOrCreate({
      where: {
        country: tournamentJSON.country,
        type: tournamentJSON.type,
        identifier: tournamentJSON.identifier
      },
      transaction: this.transaction
    })
    return tournament

  }

  async flushSeason(tournament) {
    const {tournamentJSON} = this
    const {models: {Season}} = await this.orm
    const [season, created] = await Season.findOrCreate({
      where: {
        name: tournamentJSON.name,
        finCommit: tournamentJSON.finCommit,
        start: moment(tournamentJSON.start.replace(/\./g, '-')).toISOString(),
        year: Number(this.year),
        tournamentId: tournament.id
      },
      transaction: this.transaction
    })
    console.log(created)
    console.log(season)
    return season
  }

这是我在测试中使用它的方式:

  const flush = new Flush()
  const flush1 = new Flush()
  flush.year = 2011
  flush1.year = 2012
  let tournamentJSON = await Helper.loadJSON(`${t.context.fixtures}/someTournament.json`)
  await flush.flush(tournamentJSON)
  await flush1.flush(tournamentJSON)

我预计将创建一个锦标赛和两个赛季(分别为2011和2012年),但仅创建一个赛季(即2012年)。 flushSeason方法运行两次。在console.log的两行中,我看到在展位情况下created是正确的。

从日志中:

Executing (cb4f89f4-8e00-4fd0-b329-0c263f389922): 
INSERT INTO `season` (`id`,`name`,`year`,`start`,`finished`,`scraped`,`finCommit`,`createdAt`,`updatedAt`,`tournamentId`) 
VALUES (NULL,'Some name',2011,'2011-08-12 00:00:00.000 +00:00',0,0,'2000','2019-08-23 15:26:02.528 +00:00','2019-08-23 15:26:02.528 +00:00',1);
Executing (2ee2b03e-b127-491e-9da7-572e89d2ba70): 
INSERT INTO `season` (`id`,`name`,`year`,`start`,`finished`,`scraped`,`finCommit`,`createdAt`,`updatedAt`,`tournamentId`) 
VALUES (NULL,'Some name',2012,'2011-08-12 00:00:00.000 +00:00',0,0,'2000','2019-08-23 15:26:02.528 +00:00','2019-08-23 15:26:02.528 +00:00',1);

0 个答案:

没有答案