我正在一个 Scala 项目中尝试使用 Slick 来访问关系(PostgreSQL)数据库。该项目使用 Scala 2.12.14、Slick 3.3.3 和 Slick Codegen 3.3.3。
我首先创建了一个非常简单的数据库表:
create table example (
id uuid not null primary key,
name varchar
);
接下来,我运行了 Slick 代码生成器来为我生成Table
和TableRow
类。它们产生了这个 Scala 文件:
object Tables extends {
val profile = slick.jdbc.PostgresProfile
} with Tables
/** Slick data model trait for extension, choice of backend or usage in the cake pattern. (Make sure to initialize this late.) */
trait Tables {
val profile: slick.jdbc.JdbcProfile
import profile.api._
import slick.model.ForeignKeyAction
// NOTE: GetResult mappers for plain SQL are only generated for tables where Slick knows how to map the types of all columns.
import slick.jdbc.{GetResult => GR}
/** DDL for all tables. Call .create to execute. */
lazy val schema: profile.SchemaDescription = Example.schema
@deprecated("Use .schema instead of .ddl", "3.0")
def ddl = schema
/** Entity class storing rows of table Example
* @param id Database column id SqlType(uuid), PrimaryKey
* @param name Database column name SqlType(varchar), Default(None) */
case class ExampleRow(id: java.util.UUID, name: Option[String] = None)
/** GetResult implicit for fetching ExampleRow objects using plain SQL queries */
implicit def GetResultExampleRow(implicit e0: GR[java.util.UUID], e1: GR[Option[String]]): GR[ExampleRow] = GR{
prs => import prs._
ExampleRow.tupled((<<[java.util.UUID], <<?[String]))
}
/** Table description of table example. Objects of this class serve as prototypes for rows in queries. */
class Example(_tableTag: Tag) extends profile.api.Table[ExampleRow](_tableTag, "example") {
def * = (id, name) <> (ExampleRow.tupled, ExampleRow.unapply)
/** Maps whole row to an option. Useful for outer joins. */
def ? = ((Rep.Some(id), name)).shaped.<>({r=>import r._; _1.map(_=> ExampleRow.tupled((_1.get, _2)))}, (_:Any) => throw new Exception("Inserting into ? projection not supported."))
/** Database column id SqlType(uuid), PrimaryKey */
val id: Rep[java.util.UUID] = column[java.util.UUID]("id", O.PrimaryKey)
/** Database column name SqlType(varchar), Default(None) */
val name: Rep[Option[String]] = column[Option[String]]("name", O.Default(None))
}
/** Collection-like TableQuery object for table Example */
lazy val Example = new TableQuery(tag => new Example(tag))
}
据我所知,这似乎是有道理的。
然后我尝试实际使用此模式将记录插入“示例”表:
val config = DatabaseConfig.forURI[JdbcProfile](URI.create("...not relevant..."))
config.db.run(DBIO.seq(
Tables.Example += (UUID.randomUUID(), "Whatever"),
))
编译此代码失败:
方法 += 的参数过多 (2): (value: Tables.ExampleRow)slick.sql.FixedSqlAction[Int,slick.dbio.NoStream,slick.dbio.Effect.Write]
有任何想法吗?