Slick postgres function as primary key for insertOrUpdate

33 views
Skip to first unread message

Stefaan Delanghe

unread,
Apr 3, 2017, 8:26:24 AM4/3/17
to Slick / ScalaQuery
Hey,

I have been trying for half a day to use a POSTGRES function as primary key. Here is my setup of database.

CREATE OR REPLACE FUNCTION make_uid() RETURNS text AS $$
DECLARE
new_uid text;
done bool;
BEGIN
done := false;
WHILE NOT done LOOP
new_uid := md5(''||now()::text||random()::text);
done := NOT exists(SELECT 1 FROM masterdata.company WHERE idKey=new_uid);
END LOOP;
RETURN new_uid;
END;
$$ LANGUAGE PLPGSQL VOLATILE;

CREATE TABLE company(
idKey TEXT PRIMARY KEY DEFAULT make_uid(),
companyNumber VARCHAR(254),
name VARCHAR(254),
synonyms VARCHAR(254),
tl_ref BIGINT
);

class Companies(tag : Tag) extends Table[Company](tag, Some("xxxx"), "company") {
val idKey : Rep[Option[String]] = column[Option[String]]("idkey", O.PrimaryKey, O.AutoInc, O.Default(None))
val companyNumber : Rep[Option[String]] = column[Option[String]]("companynumber")
val name: Rep[String] = column[String]("name")
val synonyms: Rep[Option[String]] = column[Option[String]]("synonyms", O.Default(None))
val tlRef: Rep[Option[Int]] = column[Option[Int]]("tl_ref", O.Default(None))
def * = (idKey, companyNumber, name, synonyms, tlRef) <> (Company.tupled, Company.unapply)
}


The following query is not working due to error Message org.postgresql.util.PSQLException: ERROR: null value in column "idkey" violates not-null constraint

val result = companies.filter(_.tlRef === companyDB.teamleaderId).result.headOption.map { existing =>
val row: Company = existing.map({ _.copy(companyNumber = companyDB.companyNumber,
name = companyDB.name,
synonyms = companyDB.synonyms,
teamleaderId = companyDB.teamleaderId
)}) getOrElse companyDB
row
}.flatMap { row => companies.insertOrUpdate(row).map(_ => ()) }


The idKey is not filled in which is normall as i want it to be generated by the function in postgres.
Any indication as to what my misunderstanding is?

Thank you


Reply all
Reply to author
Forward
0 new messages