How we use Kotlin with Exposed at TouK

Why Kotlin? At TouK, we try to early adopt technologies. We don’t have a starter project skeleton that is reused in every new project, we want to try something that fits the project needs, even if it’s not that popular yet. We tried Kotlin first it mid 2016, right after reaching 1.0.2 version

Why Kotlin?

At TouK, we try to early adopt technologies. We don’t have a starter project skeleton reused in every new project; we want to try something that fits the project’s needs, even if it’s not that popular yet. We tried Kotlin first in mid-2016, right after reaching the 1.0.2 version. It was getting really popular in Android development, but almost nobody used it on the backend, especially — with production deployment. After reading some “hello world” examples, including this great article by Sebastien Deleuze we decided to try Kotlin as main language for a new MVNO project. The project was mainly a backend for a mobile app, with some integrations with external services (chat, sms, payments) and background tasks regarding customer subscriptions. We felt that Kotlin would be something fresh and more pleasant for developers, but we also liked the “not reinventing the wheel” approach — reusing large parts of the Java/JVM ecosystem we were happy with for existing projects (Spring, Gradle, JUnit, Mockito).

Why Exposed?

We initially felt that Kotlin + JPA/Hibernate is not a perfect match. Kotlin’s functional nature with first-class immutability support was not something that could seemly integrate with full-blown ORM started in the pre-Java8 era. But Sebastien’s article led us to try Exposed — a SQL access library maintained by JetBrains. From the beginning, we really liked the main assumptions of Exposed:

  • not trying to be full ORM framework
  • two flavors — typesafe SQL DSL and DAO/ActiveRecord style
  • lightweight, no reflection
  • no code generation
  • Spring integration
  • no annotations on your domain classes (in SQL DSL flavor)
  • open for extension (e.g. PostGIS and new DB dialects)

TL;DR

If you want to see how we use Kotlin + Exposed duo in our projects, check out this Github repo. It’s a Spring Boot app exposing REST API with the implementation of Medium clone as specified in http://realworld.io (“The mother of all demo apps”).

Another nice example is this repo by Seb Schmidt.

SQL DSL

In our projects we decided to try the “typesafe SQL DSL” flavor of Exposed. In this approach you don’t have to add anything to your domain classes, just need to write a simple schema mapping using Kotlin in configuration-as-code manner:

data class User(
  val username: Username,
  val password: String,
  val email: String
)

object UserTable : Table("users") {
    val username = text("username")
    val email = text("email")
    val password = text("password")
}

And then you can write type/null-safe queries with direct mapping to your domain classes:

UserTable.select { UserTable.username eq username }?.toUser()

// or 

UserTable.select { UserTable.username like username }.map { it.toUser() }

fun ResultRow.toUser() = User(
       username = this[UserTable.username],
       email = this[UserTable.email],
       password = this[UserTable.password]
)

RefIds

We like type-safe RefIds in our domain code. This is particularly useful in DDD-ish architectures, where you can keep those RefIds in a shared domain and use them to communicate between contexts.

So we wrap plan ids (longs, strings) into simple wrapper classes (e.g. UserId, ArticleId, Username, Slug). Exposed allows to easily register your own column types or even generic WrapperColumnType implementation that you can find in our repo.

Using this technique you can rewrite this mapping to something like this:

sealed class UserId : RefId<Long>() {
  object New : UserId() {
    override val value: Long by IdNotPersistedDelegate<Long>()
  }
  data class Persisted(override val value: Long) : UserId() {
    override fun toString() = "UserId(value=$value)"
  }
}

data class User(
   val id: UserId = UserId.New,
   //...
)

fun Table.userId(name: String) = longWrapper<UserId>(name, UserId::Persisted, UserId::value)

object UserTable : Table("users") {
  val id = userId("id").primaryKey().autoIncrement()
//...
}

And now we can query by type-safe RefIds:

override fun findBy(userId: UserId) =
  UserTable.select { UserTable.id eq userId }?.toUser()

Relationship mapping

One of the most significant selling points of ORMs is how easy it is to deal with relations. You just annotate the related field/collection with OneToOne or OneToMany and then can fetch the whole graph of objects at once. In theory — quite a nice idea, but in practice, things often go wrong. I’m not going to dig into details, instead, I recommend you read e.g. these fragments of “Opinionated JPA with Querydsl” book:

In Exposed SQL DSL approach you have to do relationship mapping by yourself — if you need to. Let’s consider Article and Tag case from our project’s domain. We have a many-to-many relation here, so we need additional “article_tags” table:

object ArticleTagTable : Table("article_tags") {
   val tagId = tagId("tag_id").references(TagTable.id)
   val articleId = articleId("article_id").references(ArticleTable.id)
}

When creating an Article, we have to attach all the associated Tags by populating Article’s generated id into ArticleTabTable entries:

override fun create(article: Article): Article {
   val savedArticle = ArticleTable.insert { it.from(article) }
           .getOrThrow(ArticleTable.id)
           .let { article.copy(id = it) }
   savedArticle.tags.forEach { tag ->
       ArticleTagTable.insert {
           it[ArticleTagTable.tagId] = tag.id
           it[ArticleTagTable.articleId] = savedArticle.id
       }
   }
   return savedArticle
}

The funny part is the mapping of Article with Tags in query methods — in API specification Tags are always returned with the Article — so we need to eagerly fetch tags by using leftJoin:

val ArticleWithTags = (ArticleTable leftJoin ArticleTagTable leftJoin TagTable)

override fun findBy(articleId: ArticleId) =
  ArticleWithTags
    .select { ArticleTable.id eq articleId }
    .toArticles()
    .singleOrNull()

After joining, we have then one ResultRow per one Article-Tag pair, so we have to group them by ArticleId, and build the correct Article object by adding Tags for each matching resultRow:

fun Iterable<ResultRow>.toArticles(): List<ResultRow> {
   return fold(mutableMapOf<ArticleId, Article>()) { map, resultRow ->
       val article = resultRow.toArticle()
       val tagId = resultRow.tryGet(ArticleTagTable.tagId)
       val tag = tagId?.let { resultRow.toTag() }
       val current = map.getOrDefault(article.id, article)
       map[article.id] = current.copy(tags = current.tags + listOfNotNull(tag))
       map
   }.values.toList()
}

This implementation allows us to solve all the possible cases:

  • no articles (fold just returns empty map)
  • articles with no tags (tag is null, so listOfNotNull(tag) is empty)
  • articles with many tags (an article with a single tag is inserted into the map, then other tags are added in copy method)

However, consider when you need to fetch the dependent structure with the root object? For tags it makes sense since you always want the tags with the article, and the count of tags for any article should not be that huge. What about the comments? You definitely don’t want all the comments each time you fetch the article, instead you’ll need some kind of paging or even making a parent-child hierarchy for comments for the article. That’s why we recommend having this relationship mapped indirectly — every Comment should have ArticleId property, and the CommentRepository could have methods like:

fun findAllBy(articleId: ArticleId): List<Comment>
// or
fun findAllByPaged(articleId: ArticleId, pageRequest: PageRequest): Page<Comment>

Extendibility

Exposed is by design open for extension, making it even easier with Kotlin’s support for extension methods. You can define your own column type or expressions, e.g. for PostGIS point type support as Sebastian showed in his article. We used similar PostGIS extension in our project too. We were also able to implement a simple support for Java8 DateTime column type — for now, Exposed has Joda-time support, a generic approach for various date/time libraries is planned in the roadmap.

The bigger thing was Oracle DB dialect — we were forced to migrate to Oracle at some time in our project. We submitted a pull-request with foundations of Oracle 12 support, being tested in production for a while (then, we moved back to PostgreSQL…). The implementation was rather straightforward, with DataType- and FunctionProvider interfaces to provide and just a few tweaks in batch insert support.

Final thoughts

Our developer experience with Kotlin+Exposed duo was really pleasant. If you don’t plan to map many relations directly, just use simple data classes, connected by RefIds, it works really well. The Exposed library itself may need more exhaustive documentation and removing some annoying details (e.g. transaction management via thread-local — which is already on the roadmap), but we definitely recommend you give it a try in your project!

You May Also Like

Spock basics

Spock (homepage) is like its authors say 'testing and specification framework'. Spock combines very elegant and natural syntax with the powerful capabilities. And what is most important it is easy to use.

One note at the very beginning: I assume that you are already familiar with principles of Test Driven Development and you know how to use testing framework like for example JUnit.

So how can I start?


Writing spock specifications is very easy. We need basic configuration of Spock and Groovy dependencies (if you are using mavenized project with Eclipse look to my previous post: Spock, Java and Maven). Once we have everything set up and running smooth we can write our first specs (spec or specification is equivalent for test class in other frameworks like JUnit of TestNG).

What is great with Spock is fact that we can use it to test both Groovy projects and pure Java projects or even mixed projects.


Let's go!


Every spec class must inherit from spock.lang.Specification class. Only then test runner will recognize it as test class and start tests. We will write few specs for this simple class: User class and few tests not connected with this particular class.

We start with defining our class:
import spock.lang.*

class UserSpec extends Specification {

}
Now we can proceed to defining test fixtures and test methods.

All activites we want to perform before each test method, are to be put in def setup() {...} method and everything we want to be run after each test should be put in def cleanup() {...} method (they are equivalents for JUnit methods with @Before and @After annotations).

It can look like this:
class UserSpec extends Specification {
User user
Document document

def setup() {
user = new User()
document = DocumentTestFactory.createDocumentWithTitle("doc1")
}

def cleanup() {

}
}
Of course we can use field initialization for instantiating test objects:
class UserSpec extends Specification {
User user = new User()
Document document = DocumentTestFactory.createDocumentWithTitle("doc1")

def setup() {

}

def cleanup() {

}
}

What is more readable or preferred? It is just a matter of taste because according to Spock docs behaviour is the same in these two cases.

It is worth mentioning that JUnit @BeforeClass/@AfterClass are also present in Spock as def setupSpec() {...} and def cleanupSpec() {...}. They will be runned before first test and after last test method.


First tests


In Spock every method in specification class, expect setup/cleanup, is treated by runner as a test method (unless you annotate it with @Ignore).

Very interesting feature of Spock and Groovy is ability to name methods with full sentences just like regular strings:
class UserSpec extends Specification {
// ...

def "should assign coment to user"() {
// ...
}
}
With such naming convention we can write real specification and include details about specified behaviour in method name, what is very convenient when reading test reports and analyzing errors.

Test method (also called feature method) is logically divided into few blocks, each with its own purpose. Blocks are defined like labels in Java (but they are transformed with Groovy AST transform features) and some of them must be put in code in specific order.

Most basic and common schema for Spock test is:
class UserSpec extends Specification {
// ...

def "should assign coment to user"() {
given:
// do initialization of test objects
when:
// perform actions to be tested
then:
// collect and analyze results
}
}

But there are more blocks like:
  • setup
  • expect
  • where
  • cleanup
In next section I am going to describe each block shortly with little examples.

given block

This block is used to setup test objects and their state. It has to be first block in test and cannot be repeated. Below is little example how can it be used:
class UserSpec extends Specification {
// ...

def "should add project to user and mark user as project's owner"() {
given:
User user = new User()
Project project = ProjectTestFactory.createProjectWithName("simple project")
// ...
}
}

In this code given block contains initialization of test objects and nothing more. We create simple user without any specified attributes and project with given name. In case when some of these objects could be reused in more feature methods, it could be worth putting initialization in setup method.

when and then blocks

When block contains action we want to test (Spock documentation calls it 'stimulus'). This block always occurs in pair with then block, where we are verifying response for satisfying certain conditions. Assume we have this simple test case:
class UserSpec extends Specification {
// ...

def "should assign user to comment when adding comment to user"() {
given:
User user = new User()
Comment comment = new Comment()
when:
user.addComment(comment)
then:
comment.getUserWhoCreatedComment().equals(user)
}

// ...
}

In when block there is a call of tested method and nothing more. After we are sure our action was performed, we can check for desired conditions in then block.

Then block is very well structured and its every line is treated by Spock as boolean statement. That means, Spock expects that we write instructions containing comparisons and expressions returning true or false, so we can create then block with such statements:
user.getName() == "John"
user.getAge() == 40
!user.isEnabled()
Each of lines will be treated as single assertion and will be evaluated by Spock.

Sometimes we expect that our method throws an exception under given circumstances. We can write test for it with use of thrown method:
class CommentSpec extends Specification {
def "should throw exception when adding null document to comment"() {
given:
Comment comment = new Comment()
when:
comment.setCommentedDocument(null)
then:
thrown(RuntimeException)
}
}

In this test we want to make sure that passing incorrect parameters is correctly handled by tested method and that method throws an exception in response. In case you want to be certain that method does not throw particular exception, simply use notThrown method.


expect block

Expect block is primarily used when we do not want to separate when and then blocks because it is unnatural. It is especially useful for simple test (and according to TDD rules all test should be simple and short) with only one condition to check, like in this example (it is simple but should show the idea):
def "should create user with given name"() {
given:
User user = UserTestFactory.createUser("john doe")
expect:
user.getName() == "john doe"
}



More blocks!


That were very simple tests with standard Spock test layout and canonical divide into given/when/then parts. But Spock offers more possibilities in writing tests and provides more blocks.


setup/cleanup blocks

These two blocks have the very same functionality as the def setup and def cleanup methods in specification. They allow to perform some actions before test and after test. But unlike these methods (which are shared between all tests) blocks work only in methods they are defined in. 


where - easy way to create readable parameterized tests

Very often when we create unit tests there is a need to "feed" them with sample data to test various cases and border values. With Spock this task is very easy and straighforward. To provide test data to feature method, we need to use where block. Let's take a look at little the piece of code:

def "should successfully validate emails with valid syntax"() {
expect:
emailValidator.validate(email) == true
where:
email }

In this example, Spock creates variable called email which is used when calling method being tested. Internally feature method is called once, but framework iterates over given values and calls expect/when block as many times as there are values (however, if we use @Unroll annotation Spock can create separate run for each of given values, more about it in one of next examples).

Now, lets assume that we want our feature method to test both successful and failure validations. To achieve that goal we can create few 
parameterized variables for both input parameter and expected result. Here is a little example:

def "should perform validation of email addresses"() {
expect:
emailValidator.validate(email) == result
where:
email result }
Well, it looks nice, but Spock can do much better. It offers tabular format of defining parameters for test what is much more readable and natural. Lets take a look:
def "should perform validation of email addresses"() {
expect:
emailValidator.validate(email) == result
where:
email | result
"WTF" | false
"@domain" | false
"foo@bar.com" | true
"a@test" | false
}
In this code, each column of our "table" is treated as a separate variable and rows are values for subsequent test iterations.

Another useful feature of Spock during parameterizing test is its ability to "unroll" each parameterized test. Feature method from previous example could be defined as (the body stays the same, so I do not repeat it):
@Unroll("should validate email #email")
def "should perform validation of email addresses"() {
// ...
}
With that annotation, Spock generate few methods each with its own name and run them separately. We can use symbols from where blocks in @Unroll argument by preceding it with '#' sign what is a signal to Spock to use it in generated method name.


What next?


Well, that was just quick and short journey  through Spock and its capabilities. However, with that basic tutorial you are ready to write many unit tests. In one of my future posts I am going to describe more features of Spock focusing especially on its mocking abilities.

Micro services on the JVM part 1 – Clojure

Micro services could be a buzzword of 2014 for me. Few months ago I was curious to try Dropwizard framework as a separate backend, but didn’t get the whole idea yet. But then I watched a mind-blowing “Micro-Services Architecture” talk by Fred George. Also, the 4.0 release notes of Spring covers microservices as an important rising trend as well. After 10 years of having SOA in mind, but still developing monoliths, it’s a really tempting idea to try to decouple systems into a set of independently developed and deployed RESTful services.

Micro services could be a buzzword of 2014 for me. Few months ago I was curious to try Dropwizard framework as a separate backend, but didn’t get the whole idea yet. But then I watched a mind-blowing “Micro-Services Architecture” talk by Fred George. Also, the 4.0 release notes of Spring covers microservices as an important rising trend as well. After 10 years of having SOA in mind, but still developing monoliths, it’s a really tempting idea to try to decouple systems into a set of independently developed and deployed RESTful services.