我正在尝试简单地将一个元素插入数据库而不在表上有一个autoinc标志。
这是表定义,我已经定义了所有适当的映射器:
class BlockHeaderTable(tag: Tag) extends Table[BlockHeader](tag,"block_headers") {
def hash = column[DoubleSha256Digest]("hash", O.PrimaryKey)
def version = column[UInt32]("version")
def previousBlockHash = column[DoubleSha256Digest]("previous_block_hash")
def merkleRootHash = column[DoubleSha256Digest]("merkle_root_hash")
def time = column[UInt32]("time")
def nBits = column[UInt32]("n_bits")
def nonce = column[UInt32]("nonce")
def * = (hash, version, previousBlockHash, merkleRootHash, time, nBits, nonce).<>[BlockHeader,
(DoubleSha256Digest, UInt32, DoubleSha256Digest, DoubleSha256Digest, UInt32, UInt32, UInt32)](blockHeaderApply,blockHeaderUnapply)
}
我正在尝试为此表创建一个简单的插入函数。这是我的尝试:
override val table = TableQuery[BlockHeaderTable]
def create(blockHeader: BlockHeader): Future[BlockHeader] = {
val insertAction = table += blockHeader
database.run(insertAction)
}
我收到类型的错误:
chris@chris-870Z5E-880Z5E-680Z5E:~/dev/bitcoins-spv-node$ sbt compile
[info] Loading project definition from /home/chris/dev/bitcoins-spv-node/project
[info] Set current project to bitcoins-spv-node (in build file:/home/chris/dev/bitcoins-spv-node/)
[info] Compiling 1 Scala source to /home/chris/dev/bitcoins-spv-node/target/scala-2.11/classes...
[error] /home/chris/dev/bitcoins-spv-node/src/main/scala/org/bitcoins/spvnode/models/BlockHeaderDAO.scala:30: type mismatch;
[error] found : slick.profile.FixedSqlAction[Boolean,slick.dbio.NoStream,slick.dbio.Effect.Write]
[error] required: slick.dbio.DBIOAction[org.bitcoins.core.protocol.blockchain.BlockHeader,slick.dbio.NoStream,Nothing]
[error] database.run(insertAction)
[error] ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 3 s, completed Sep 8, 2016 2:11:32 PM
答案 0 :(得分:1)
默认情况下,+=
会返回受影响的行数,通常为1.但是,为了满足create
函数的签名,您需要返回BlockHeader
。您只需链接一个返回“插入”值的DBIO.successful()
操作即可完成此操作:
def create(blockHeader: BlockHeader): Future[BlockHeader] = {
val insertion: DBIO[BlockHeader] = (table += blockHeader).andThen(DBIO.successful(blockHeader))
database.run(insertAction)
}
andThen
在第一个操作成功后执行,并将返回第二个操作的值。
不要与returning
混淆。使用returning
,您可以更改+=
和++=
返回的值。这样说,大多数DBMS只允许返回单个自动递增的主键。例如,如果hash
是一个自动递增的值,您可以这样返回:
val hash = (table returning table.map(_.hash)) += blockHeader
为了更进一步,您还可以使用BlockHeader
在into
对象中插入该值:
val blockHeaderWithHash = (table returning table.map(_.hash) into ((blockHeader, hash) => blockHeader.copy(hash = hash))) += blockHeader
答案 1 :(得分:0)
您的insertAction
会返回已插入的行数,因此您应该映射该值并检查操作是否成功:
def create(blockHeader: BlockHeader): Future[BlockHeader] = {
val insertAction = (table += blockHeader).flatMap {
case 0 => DBIO.failed(new Exception("Failed to insert `BlockHeader` object"))
case _ => DBIO.successful(blockHeader)
}
db.run(insertAction)
}