Cut down 90% on RDBMS costs switching from Oracle to EnterpriseDB


Now that’s an interesting story. Most Oracle users and customers will know that Oracle is not one of the most supportive suppliers when you don’t have the money. And by “the money”, I mean lots of money. It is a huge, and feature-rich database after all, but so is Postgres. There is a lot of innovation going on in the Postgres open source database, and it is enriched by EnterpriseDB to become an “enterprise-ready” RDBMS for 10% of the price that Oracle claims.

Read the full article here:

http://www.forbes.com/sites/petercohan/2011/12/27/enterprisedb-is-giving-oracle-a-run-for-its-money/

A neater way to use reflection in Java


Reflection in Java really feels awkward. The java.lang.reflect API is very powerful and complete, and in that sense also very verbose. Unlike in most scripting languages, there is no convenient way to access methods and fields dynamically using reflection. By convenient, I mean things like this

// PHP
$method = 'my_method';
$field  = 'my_field';

// Dynamically call a method
$object->$method();

// Dynamically access a field
$object->$field;

Or even better

// JavaScript
var method   = 'my_method';
var field    = 'my_field';

// Dynamically call a function
object[method]();

// Dynamically access a field
object[field];

For us Java guys, this is something we can only dream of. We would write this

String method = "my_method";
String field  = "my_field";

// Dynamically call a method
object.getClass().getMethod(method).invoke(object);

// Dynamically access a field
object.getClass().getField(field).get(object);

Obviously, this doesn’t take care of NullPointerExceptions, InvocationTargetExceptions, IllegalAccessExceptions, IllegalArgumentExceptions, SecurityExceptions, primitive types, etc. In an enterprise world, things need to be safe and secure, and the Java architects have thought of all possible problems that could arise when using reflection. But in many cases, we know what we’re doing and we don’t care about most of those features. We’d prefer the less verbose way.

That’s why I have created another sibling in the jOO* family: jOOR (Java Object Oriented Reflection). While this is not a killer libary, it might be useful for 1-2 developers out there looking for a simple and fluent solution. Here’s an example I have recently encountered on stack overflow, where jOOR might fit in just perfectly:

// Classic example of reflection usage
try {
  Method m1 = department.getClass().getMethod("getEmployees");
  Employee employees = (Employee[]) m1.invoke(department);

  for (Employee employee : employees) {
    Method m2 = employee.getClass().getMethod("getAddress");
    Address address = (Address) m2.invoke(employee);

    Method m3 = address.getClass().getMethod("getStreet");
    Street street = (Street) m3.invoke(address);

    System.out.println(street);
  }
}

// There are many checked exceptions that you are likely to ignore anyway 
catch (Exception ignore) {

  // ... or maybe just wrap in your preferred runtime exception:
  throw new RuntimeException(e);
}

And the same example using jOOR:

Employee[] employees = on(department).call("getEmployees").get();

for (Employee employee : employees) {
  Street street = on(employee).call("getAddress").call("getStreet").get();
  System.out.println(street);
}

See the full Stack Overflow question here:

http://stackoverflow.com/questions/4385003/java-reflection-open-source/8672186

Another example:

String world = 
on("java.lang.String")  // Like Class.forName()
 .create("Hello World") // Call the most specific matching constructor
 .call("substring", 6)  // Call the most specific matching method
 .call("toString")      // Call toString()
 .get()                 // Get the wrapped object, in this case a String

Get jOOR for free here:

http://code.google.com/p/joor/

A Brief, Incomplete, and Mostly Wrong History of Programming Languages


Found a fun read on the net, recently 😉

http://james-iry.blogspot.com/2009/05/brief-incomplete-and-mostly-wrong.html

SQL in Scala, where jOOQ could go


I have recently blogged about how simple it is to integrate jOOQ into Scala. See the full blog post here:

https://lukaseder.wordpress.com/2011/12/11/the-ultimate-sql-dsl-jooq-in-scala/

I’m more and more thrilled by that option, as Scala is one of the fastest emerging JVM languages nowadays. The plain integration of a Java library in Scala leaves some open questions. jOOQ knows the “val()” operator or method, to create bind values. See the manual here:

http://www.jooq.org/manual/JOOQ/BindValues/

This operator cannot be used in Scala, as Scala declares “val” as a reserved word. I’ve had similar issues in Java before, when trying to use “case” or “else” in the API, which is not possible either. The path of least resistance is to overload or re-name those methods. “val” was overloaded as “value” in jOOQ 2.0.1. “case” and “else” were re-named a long time ago as “decode” (from Oracle’s DECODE function), and “otherwise” (as in XSL).

So for a full-fledged integration in Scala, jOOQ should be wrapped in a new API called scOOQ ;-). This new API should take Scala’s language features into account in order to make working with jOOQ a lot easier. This could be the chance to re-engineer some of the API and make all API methods uppercase, as is usual with SQL. With Scala’s ability of omitting syntax elements, such as “.” and “()”, the API could then declare one-word methods, such as in this Java example:

MERGE().INTO(MY_TABLE)
       .USING(SOURCE_TABLE)
       .ON(MY_TABLE.ID.equal(SOURCE_TABLE.ID))
       .WHEN().MATCHED().THEN().UPDATE()
         .SET(ID, 1)
         .SET(DATA, "Data")
       .WHEN().NOT().MATCHED().THEN().INSERT(MY_TABLE.ID, MY_TABLE.DATA)
       .VALUES(1, "Data")

While in Java, this looks quite nasty and verbose, in Scala it could be very nice! The below statement should compile in Scala if the API was declared as such:

MERGE INTO MY_TABLE
      USING (SOURCE_TABLE)
      ON (MY_TABLE.ID equal SOURCE_TABLE.ID)
      WHEN MATCHED THEN UPDATE
        SET (ID, 1)
        SET (DATA, "Data")
      WHEN NOT MATCHED THEN INSERT (MY_TABLE.ID, MY_TABLE.DATA)
      VALUES (1, "Data")

Convinced? Contributions very welcome! 🙂

Java 8 virtual extension methods


I’ve been following the evolution of the Java 8 Lambda expressions project for a while now, and I’m really thrilled by its current state of progress. The latest “easy-to-understand” presentation I’ve found is this one:
http://blogs.oracle.com/briangoetz/resource/devoxx-lang-lib-vm-co-evol.pdf

Now, as an API designer, I’m particularly interested in the concept of virtual extension methods and I was wondering whether it was also considered to introduce “final” extension methods as opposed to “default” ones. For example:

interface A {
  void a();
  void b() default { System.out.println("b"); };
  void c() final { System.out.println("c"); };
}

When implementing the above interface A, one…

  • MUST also implement a()
  • MAY implement / override b()
  • CANNOT override c()

Advantages:

  • API designers can create convenience methods more easily without risking client code “illegally” overriding default implementations. That’s one of the main purposes of “final”.
  • Lambda expressions wouldn’t need to be limited to pure “functional interfaces” (single-method interfaces), as a functional interface would still be “functional” if it also had any number of final extension methods. For example, the above interface A would become a functional interface, if b() was removed or if b() was made final as well.
  • Extension methods would have more features in common with regular methods, which can be final as well. I guess for the reflection API and for the JVM, that’s a plus.
  • The JVM is modified anyway to support extension methods. Java 8’s momentum could be used for this feature as well, i.e. now is the right time to think about this

Disadvantages:

  • A class could inherit multiple colliding final method implementations in the case of “diamond interface inheritance“. This could lead to new compilation errors in existing code. I guess this lack of backwards compatibility is the biggest drawback.

As with multiple inheritance itself, careful API designers could
further improve their API’s when using final extension methods,
whereas less careful API designers might break client code. But this
is the case with previous usage of “final” as well, so I think final
extension methods would be a very nice addition to Java 8.

See the full mail and follow-up on the lambda-dev mailing list here:
http://mail.openjdk.java.net/pipermail/lambda-dev/2011-December/004426.html

The ultimate SQL-DSL: jOOQ in Scala


I’ve recently come across some advertising for the new upcoming version of Scala IDE for Eclipse, which made me remember my college programming lessons at the EPFL Laboratoire des Méthodes de Programmation (LAMP), the origin of the Scala language. Back then, Scala appeared quite freaky. Very elegant, a bit inefficient, somewhat dogmatic. It was much more functional than object oriented, from what I recall, and Martin Odersky had a hard time agreeing that the key to success is to combine the two paradigms. But Scala has come a long way in the last 8 years. So I was wondering if jOOQ was portable to Scala. The answer amazes me:

jOOQ is 100% Scala-ready !!

Obviously, this is not due to jOOQ’s fluent API alone. It’s mostly because of how Scala was built on top of Java. Check out this piece of sample code:

package org.jooq.scala

import java.sql.Connection
import java.sql.DriverManager

// This makes integration of Java into Scala easier
import scala.collection.JavaConversions._

// Import all relevant things from jOOQ
import org.jooq.impl.Factory._
import org.jooq.util.maven.example.mysql.Test2Factory
import org.jooq.util.maven.example.mysql.Tables._

object Test {
  def main(args: Array[String]) {

    // This is business as usual. I guess there's
    // also a "Scala way" to do this...?
    Class.forName("com.mysql.jdbc.Driver");
    val connection = DriverManager.getConnection(
      "jdbc:mysql://localhost/test", "root", "");
    val create = new Test2Factory(connection);

    // Fetch book titles and their respective authors into
    // a result, and print the result to the console. Wow!
    // If this doesn't feel like SQL to you...?
    val result = (create
      select (
          T_BOOK.TITLE as "book title",
          T_AUTHOR.FIRST_NAME as "author's first name",
          T_AUTHOR.LAST_NAME as "author's last name")
      from T_AUTHOR
      join T_BOOK on (T_AUTHOR.ID equal T_BOOK.AUTHOR_ID)
      where (T_AUTHOR.ID in (1, 2, 3))
      orderBy (T_AUTHOR.LAST_NAME asc) fetch)

    // Print the result to the console
    println(result)

    // Iterate over authors and the number of books they've written
    // Print each value to the console
    for (r <- (create
               select (T_AUTHOR.FIRST_NAME, T_AUTHOR.LAST_NAME, count)
               from T_AUTHOR
               join T_BOOK on (T_AUTHOR.ID equal T_BOOK.AUTHOR_ID)
               where (T_AUTHOR.ID in (1, 2, 3))
               groupBy (T_AUTHOR.FIRST_NAME, T_AUTHOR.LAST_NAME)
               orderBy (T_AUTHOR.LAST_NAME asc)
               fetch)) {

      // Accessing record data is just like in Java
      print(r.getValue(T_AUTHOR.FIRST_NAME))
      print(" ")
      print(r.getValue(T_AUTHOR.LAST_NAME))
      print(" wrote ")
      print(r.getValue(count))
      println(" books ")
    }
  }
}

As expected, the console contains this data

+------------+-------------------+------------------+
|book title  |author's first name|author's last name|
+------------+-------------------+------------------+
|O Alquimista|Paulo              |Coelho            |
|Brida       |Paulo              |Coelho            |
|1984        |George             |Orwell            |
|Animal Farm |George             |Orwell            |
+------------+-------------------+------------------+

Paulo Coelho wrote 2 books 
George Orwell wrote 2 books 

You get 2 in 1

With Scala, jOOQ’s fluent API looks even more like SQL than in Java. And you get 2 in 1:

  1. Typesafe querying, meaning that your SQL syntax is compiled
  2. Typesafe querying, meaning that your database schema is part of the code

The biggest drawback I can see so far is that Scala ships with new reserved words, such as val, a very important method in jOOQ. I guess that could be sorted out somehow. So Scala users and SQL enthusiasts! Please! Feedback 🙂

Subtle SQL differences: Constraint names


The various SQL product vendors implement subtle differences in the way they interpret SQL. In this case, I’ve been examining the reuse of constraint names within a schema / database (which is yet another story: what’s a schema, what’s a database?). Here’s the summary:

Constraint names are unique within a schema

  • Derby
  • H2
  • HSQLDB
  • Ingres
  • MySQL
  • Oracle
  • SQL Server

Constraint names are unique within a table

  • DB2
  • SQLite
  • Sybase SQL Anywhere

The “weird ones”

  • Postgres: Foreign Key names can be reused. Unique / Primary Key names cannot
  • Sybase ASE: Unique / Primary Key names can be reused. Foreign Key names cannot

For most compatibility across databases, it is never a good idea to re-use names. Keep your constraint names unique across a schema.