Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala & Play! & Slick & PostgreSQL auto increment

I have the following code in Scala:

case class Product(id: Option[Long] = None, name: String, price: BigDecimal, description: String)

object Products extends Table[Product]("product") {
  def id = column[Long]("id", O.AutoInc, O.PrimaryKey)
  def name = column[String]("name", O.NotNull)
  def price = column[BigDecimal]("price", O.NotNull)
  def description = column[String]("description", O.NotNull)

  def * = id.? ~ name ~ price ~ description <>(Product.apply _, Product.unapply _)

  def autoInc = * returning id

  def add(product: Product)(implicit s:Session): Long = {
    Products.autoInc.insert(product)
  }

  def all(implicit s:Session): List[Product] = {
    Query(Products).list
  }
}

Listing all products works great, however, I can't make adding method working.

After calling:

val myProduct = models.Product(id = None, name = "test2", price = BigDecimal(2.99), description = "test3")
models.Products.add(myProduct)

I constanty get an error message from PostgreSQL saying that id cannot be null. I totally agree with that, but why the id column is not being set by autoInc? Doesn't it work that way?

I use Play! 2.1.2, Scala 2.10.0, PostgreSQL 9.3 and play-slick 0.3.3.

Thanks in advance.

like image 328
oskario Avatar asked Jul 13 '13 20:07

oskario


People also ask

What is Scala used for?

Scala is used in Data processing, distributed computing, and web development. It powers the data engineering infrastructure of many companies.

Which is better Python or Scala?

Performance. When it comes to performance, Scala is the clear winner over Python. One reason Scala wins on performance is that it is a statically typed programming language and Python is a dynamically typed programming language. With statically typed languages, the compiler knows each variable or expression at runtime.

Is Scala frontend or backend?

Today, Scala is our language of choice for writing backend services.

Is Scala similar to Java or Python?

Unlike Python, Scala is based on JVM, so its source code is compiled to Java bytecode before being executed by JVM. Therefore Scala is available for all platforms that are supported by JVM, which includes the same platforms as listed for Python. You need the Python interpreter to run Python programs.


1 Answers

Here is a suggestion, rewrite your autoInc and add methods like this:

def autoInc = name ~ price ~ description returning id

def add(product: Product)(implicit s:Session): Long = {
    Products.autoInc.insert(p.name, p.price, p.description)
}

Some databases own't allow you to insert null in the auto increment column. Maybe it's the Postgres case.

like image 140
pedrofurla Avatar answered Sep 20 '22 13:09

pedrofurla