Skip to content

Commit

Permalink
Support UUID columns across more databases
Browse files Browse the repository at this point in the history
Postgres returns a concrete `java.util.UUID` where MySQL returns a
byte array. This should improve support for any databases that support
a native UUID column type.
  • Loading branch information
Gregg Hernandez committed Feb 23, 2017
1 parent da8217e commit 67df324
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
22 changes: 16 additions & 6 deletions relate/src/main/scala/com/lucidchart/relate/SqlRow.scala
Original file line number Diff line number Diff line change
Expand Up @@ -173,13 +173,23 @@ class SqlRow(val resultSet: java.sql.ResultSet) extends ResultSetWrapper {

def uuid(column: String): UUID = uuidOption(column).get
def uuidOption(column: String): Option[UUID] = {
byteArrayOption(column).map { bytes =>
require(bytes.length == 16)
extractOption(column) {
case u: UUID => u
case b => {
val bytes = b match {
case x: Array[Byte] => x
case x: Blob => x.getBytes(0, x.length.toInt)
case x: Clob => x.getSubString(1, x.length.asInstanceOf[Int]).getBytes
case x: String => x.toCharArray.map(_.toByte)
}

require(bytes.length == 16)

val bb = ByteBuffer.wrap(bytes)
val high = bb.getLong
val low = bb.getLong
new UUID(high, low)
val bb = ByteBuffer.wrap(bytes)
val high = bb.getLong
val low = bb.getLong
new UUID(high, low)
}
}
}

Expand Down
11 changes: 10 additions & 1 deletion relate/src/test/scala/SqlResultSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -874,14 +874,23 @@ class SqlResultSpec extends Specification with Mockito {
}

"uuid" should {
"return the correct value" in {
"return the correct value when stored as a byte array" in {
val (rs, row, _) = getMocks

val res = Array[Byte]('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')
rs.getObject("uuid") returns res
row.uuid("uuid") equals new UUID(3472611983179986487L, 4051376414998685030L)
row.uuidOption("uuid") must beSome(new UUID(3472611983179986487L, 4051376414998685030L))
}

"return the correct value when stored as UUID" in {
val (rs, row, _) = getMocks

val res = new UUID(3472611983179986487L, 4051376414998685030L)
rs.getObject("uuid") returns res
row.uuid("uuid") equals res
row.uuidOption("uuid") must beSome(res)
}
}

"uuidFromString" should {
Expand Down

0 comments on commit 67df324

Please sign in to comment.