Search code examples
javadatabase-schemaderby

Determine Derby Database Schema Version With Java?


I have found this article which describes how to get the Derby database schema version from the command line with derbyrun.jar.

How can I determine the schema version from within my Java program?

EDIT: I answered my own question but I think it is not the best solution. When someone proposes a better solution I will accept that as an answer.


Solution

  • I've come up with something to get the schema version in Java, but it's ugly (and not quite complete). I hope somebody out there has something better:

    
    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        String strConnectionURL = "jdbc:derby:c:\data\tomcat7\active\LearnyErnie\data\derby;create=false";
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        Connection connection = DriverManager.getConnection(strConnectionURL);
        String strCommand = "values syscs_util.syscs_get_database_property( 'DataDictionaryVersion' );";
        InputStream inputStream = new ByteArrayInputStream(strCommand.getBytes("UTF-8"));
        ij.runScript(connection, inputStream, "UTF-8", outputStream, "UTF-8");
        String strOutput = new String(outputStream.toByteArray());
        System.out.println("Output = " + strOutput);
    }
    

    strOutput will contain the following text:

    
    Output = CONNECTION0* -     jdbc:derby:c:\data\tomcat7\active\LearnyErnie\data\derby
    * = current connection
    ij> values syscs_util.syscs_get_database_property( 'DataDictionaryVersion' );
    1
    (long line of dashes taken out because it squirrels up the SO output)
    10.9
    1 row selected
    ij>
    

    The schema version is "10.9" in the output above. It is up to you to parse it out. (I'm not bothering with that today. This is just for extra info in a Help -> About dialog and I will just write the whole ugly mess to the screen.)

    We certainly can't count on that parsing logic to work in future versions, or even the call to syscs_get_database_property() itself.

    I am hoping someone out there has a more resilient way to do this.

    Edit: It occurred to me later that perhaps the JDBC DatabaseMetaData object would contain info on the database schema in one of its properties, but I've examined them all and it doesn't. They give info on the driver version only (which can be different than the database schema).