Something cool with 0.9.6

117 views
Skip to first unread message

David Whittaker

unread,
Oct 23, 2012, 3:15:43 PM10/23/12
to squ...@googlegroups.com
I'm just starting to play around with 0.9.6, and I found something I think is pretty nifty that I wanted to share.  Getting rid of the reliance on KeyedEntity is great, but I do use a field named id as a primary key in most of my entities.... Type constructors and structural types to the rescue!

  type WithId[A] = { def id: A }

 implicit def withIdDef[A, B <% WithId[A]] = new KeyedEntityDef[B,A] {
    
 def getId(b: B): A = b.id
 
 def idPropertyName: String = "id"
   
 def isPersisted(b: B): Boolean = bi.id > 0
    
  }

And just like that Squeryl knows that every entity that contains a val or var named "id" should use that field as it's primary key.  No trait to mix in or other change to the entity required.  

P.S. If you're wondering why it's B <% WithId[A] rather than B <: WithId[A] see here: http://stackoverflow.com/questions/10343244/why-doesnt-type-inference-work-here/10347307#10347307

John Ryan-Brown

unread,
Oct 25, 2012, 8:11:54 PM10/25/12
to squ...@googlegroups.com
Small point - the isPersisted implementation depends on A being a numeric type?

I'm still uncertain how isPersisted is meant to be implemented when primary key values are not auto-generated. For example. our primary keys are UUIDs that are generated by calling UUID.randomUUID.

David Whittaker

unread,
Oct 26, 2012, 9:13:13 AM10/26/12
to squ...@googlegroups.com
Hi John,

Good point.  That's actually not what I was using..... I had a sys.error("Unimplemented") as the body of my isPersisted and changed it after copy / pasting because I thought that might confuse people.  You're right though, it wouldn't compile.  As an alternative, you could use a pattern match on A checking for 0 on numeric AnyVal(s) and null for AnyRef.

Personally, I don't see much use for isPersisted right with KeyedEntityDef, given the current implementation.  It's only used by Squeryl in the insertOrUpdate method, which I don't use.  Eventually I'd like to see it reference a field so that Squeryl can properly set it for you.

Maxime Lévesque

unread,
Oct 26, 2012, 10:21:58 AM10/26/12
to squ...@googlegroups.com
You could have a canonical UUID to represent "the value was never
assigned", for example this :

java.util.UUID.fromString("00000000-0000-0000-0000-000000000000")


2012/10/26 David Whittaker <da...@iradix.com>:
Reply all
Reply to author
Forward
0 new messages