使用SQLite的Slick3 - 自动提交似乎无法正常工作

时间:2016-03-31 07:27:49

标签: scala sqlite slick

我正在尝试使用Slick for SQLite数据库编写一些基本查询

这是我的代码:

class MigrationLog(name: String) {

    val migrationEvents = TableQuery[MigrationEventTable]

    lazy val db: Future[SQLiteDriver.backend.DatabaseDef] = {
        val db = Database.forURL(s"jdbc:sqlite:$name.db", driver = "org.sqlite.JDBC")
        val setup = DBIO.seq(migrationEvents.schema.create)

        val createFuture = for {
          tables <- db.run(MTable.getTables)
          createResult <- if (tables.length  == 0) db.run(setup) else Future.successful()
        } yield createResult

        createFuture.map(_ => db)
    }

    val addEvent: (String, String) => Future[String] = (aggregateId, eventType) => {
        val id = java.util.UUID.randomUUID().toString
        val command = DBIO.seq(migrationEvents += (id, aggregateId, None, eventType, "CREATED", System.currentTimeMillis, None))
        db.flatMap(_.run(command).map(_ => id))
    }

    val eventSubmitted: (String, String) => Future[Unit] = (id, batchId) => {
       val q = for { e <- migrationEvents if e.id === id } yield (e.batchId, e.status, e.updatedAt)
       val updateAction = q.update(Some(batchId), "SUBMITTED", Some(System.currentTimeMillis))
       db.map(_.run(updateAction))
    }

    val eventMigrationCompleted: (String, String, String) => Future[Unit] = (batchId, id, status) => {
       val q = for { e <- migrationEvents if e.batchId === batchId && e.id === id} yield (e.status, e.updatedAt)
       val updateAction = q.update(status, Some(System.currentTimeMillis))
       db.map(_.run(updateAction))
    }

    val allEvents = () => {
        db.flatMap(_.run(migrationEvents.result))
    }
}

以下是我如何使用它:

val migrationLog = MigrationLog("test")
val events = for {
  id <- migrationLog.addEvent("aggregateUserId", "userAccessControl")
  _ <- migrationLog.eventSubmitted(id, "batchID_generated_from_idam")
  _ <- migrationLog.eventMigrationCompleted("batchID_generated_from_idam", id, "Successful")
  events <- migrationLog.allEvents()
} yield events

events.map(_.foreach(event => event match {
  case (id, aggregateId, batchId, eventType, status, submitted, updatedAt) => println(s"$id $aggregateId $batchId $eventType $status $submitted $updatedAt")
}))

我们的想法是首先添加事件,然后使用batchId(也会更新状态)更新事件,然后在作业完成时更新状态。 events应包含状态为Successful的事件。

运行此代码后,会打印状态为SUBMITTED的事件。如果我等待一段时间并执行相同的allEvents查询,或者只是使用sqlite3从命令行检查数据库,那么它会正确更新。 我正在等待在开始下一个操作之前解决期货,默认情况下应该启用自动提交。

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

原来问题是db.map(_.run(updateAction))返回Future[Future[Int]],这意味着当我尝试运行另一个查询时命令没有完成。

db.flatMap(_.run(updateAction))替换它解决了这个问题。