<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jakob Külzer &#187; Database</title>
	<atom:link href="http://www.jakusys.de/blog/tag/database/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jakusys.de/blog</link>
	<description>Ninja Coding Monkey goes Canada</description>
	<lastBuildDate>Sun, 02 Jan 2011 20:12:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.3</generator>
		<item>
		<title>Liquibase Incremental DB Diff</title>
		<link>http://www.jakusys.de/blog/2009/12/liquibase-incremental-db-diff/</link>
		<comments>http://www.jakusys.de/blog/2009/12/liquibase-incremental-db-diff/#comments</comments>
		<pubDate>Sat, 12 Dec 2009 15:14:24 +0000</pubDate>
		<dc:creator>Jakob Külzer</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[#ggx]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Groovy & Grails Exchange]]></category>
		<category><![CDATA[LiquiBase]]></category>
		<category><![CDATA[Migration]]></category>
		<category><![CDATA[Schema]]></category>

		<guid isPermaLink="false">http://www.jakusys.de/blog/?p=1112</guid>
		<description><![CDATA[After discussing this on the Groovy and Grails Exchange, I finally put together a new version of the db diff script that I've mentioned in an earlier post. I couldn't find the original version that I've written a couple of months ago, so I hacked together a new one. It's far from perfect, efficient or [...]]]></description>
			<content:encoded><![CDATA[<p>After discussing this on the Groovy and Grails Exchange, I finally put together a new version of the db diff script that I've mentioned in an earlier post. I couldn't find the original version that I've written a couple of months ago, so I hacked together a new one. It's far from perfect, efficient or beautiful, but it does what it is supposed to.</p>
<p>So, what's the idea behind this script? Everybody that uses Liquibase (if you are not, check out my blog post about <a title="Liqiubase and Grails - How to use it" href="http://www.jakusys.de/blog/2008/09/grails-and-liquibase-how-to-use/" target="_blank">what Liquibase is and how to use it</a>) knows how painful it is to update your changelog.xml. Liquibase already gives you a great tool to start with, the db-diff command. However, it is hardcoded to diff the current environment's database against the test database. This is annoying as you'll have to modify your datasources and keep the database schema updated manually. But fear not, here is my (surprisingly) easy solution.</p>
<p>I've created a simple script (or rather, I took the db-diff script and hacked it), which I've called incremental DB diff (all the other cool names are already taken...) and what it does is the following:</p>
<ol>
<li> update the schema in the db-diff (or whatever you call it) database using the changelog.xml</li>
<li>diff the database of the current environment against this database and output the diff as Liquibase XML</li>
</ol>
<p>So, how is this a good thing? Easy: this little script will automatically create a target database to diff against using the changelog.xml which is good, as the changelog.xml represents your last migration status. And as it uses a separate database it doesn't influence the test database.</p>
<p>After running the script just put the output in the changelog.xml and you're done.</p>
<p>All you have to do to use this is to drop the file into your /scripts/ directory, create a new database and an according datasource entry for the environment "dbdiff" like this:</p>
<pre>	dbdiff {
		dataSource {
			driverClassName = "com.mysql.jdbc.Driver"
			dbCreate = "create-drop"
			url = "jdbc:mysql://localhost/foo_dbdiff"
			username = "foo"
			password = "bar"
		}
	}</pre>
<p>Download <a href="http://www.jakusys.de/files/DbDiffIncremental.groovy" target="_blank">DbDiffIncremental.groovy</a>. Drop me a mail or a comment if you have questions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jakusys.de/blog/2009/12/liquibase-incremental-db-diff/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>LiquiBase, addForeignKeyConstraint and Column Types do not Match</title>
		<link>http://www.jakusys.de/blog/2008/09/liquibase-addforeignkeyconstraint-column-types-do-not-match/</link>
		<comments>http://www.jakusys.de/blog/2008/09/liquibase-addforeignkeyconstraint-column-types-do-not-match/#comments</comments>
		<pubDate>Thu, 25 Sep 2008 02:49:50 +0000</pubDate>
		<dc:creator>Jakob Külzer</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[LiquiBase]]></category>
		<category><![CDATA[Database]]></category>

		<guid isPermaLink="false">http://www.jakusys.de/blog/?p=367</guid>
		<description><![CDATA[Today I encountered some weird errors while migrating my database using LiquiBase. It took me quite some time to figure out what was wrong as no one has encountered this error before. So, here's the problem and the solution. Ugly but simple example: I have two domain classes, say Book and Author and a Book [...]]]></description>
			<content:encoded><![CDATA[<p>Today I encountered some weird errors while migrating my database using <a title="LiquiBase" href="http://www.liquibase.org/" target="_blank">LiquiBase</a>. It took me quite some time to figure out what was wrong as no one has encountered this error before. So, here's the problem and the solution. <img src='http://www.jakusys.de/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Ugly but simple example: I have two domain classes, say Book and Author and a Book has an Author. How Author looks like is not important. Book looks like this</p>
<pre>class Book {
  Author author
}</pre>
<p>Due to changes in the requirements the author needs to be optional thus nullable. With updated constraints the Book class looks like this:</p>
<pre>class Book {
  Author author
  static constraints = { author(nullable:true) }
}</pre>
<p>So upgrading the database with LiquiBase should be as easy as adding a couple of lines to the changelog file:</p>
<pre>&lt;changeSet author="jakob" id="foo-1"&gt;
  &lt;dropForeignKeyConstraint baseTableName="BOOK" constraintName="FK2E3AE9CD85EDFA"/&gt;
  &lt;dropNotNullConstraint tableName="BOOK" columnName="AUTHOR_ID"/&gt;
  &lt;addForeignKeyConstraint baseColumnNames="AUTHOR_ID"
    baseTableName="BOOK" constraintName="FK2E3AE9CD85EDFA"
    deferrable="false" initiallyDeferred="false"
    referencedColumnNames="ID" referencedTableName="AUTHOR"/&gt;
&lt;/changeSet&gt;</pre>
<p>Basically this changeset drops the foreign key constraint on AUTHOR_ID, drops the not-null-constraints and re-adds the foreign key constraint which is required to handle the association between the Book and the Author class.</p>
<p>Unfortunately the <a title="LiquiBase: addForeignKeyConstraint" href="http://www.liquibase.org/manual/add_foreign_key_constraint" target="_blank">addForeignKeyConstraint</a> will cause an error, something like this:</p>
<pre>Caused by: java.sql.SQLException: Column types do not match in statement [ALTER TABLE...</pre>
<p>The reason why this happens is that: when dropping the not-null constraint the type of the AUTHOR_ID column is re-set to something unusable. Inspecting the database with the HSQLDB Databasemanager showed that the type of the is set to NULL which is weird. The solution to this is easy however. All you need to do is to provide LiquiBase the type with the columnDataType attribute of the column in the <a title="LiquiBase: dropNotNullConstraint" href="http://www.liquibase.org/manual/remove_not-null_constraint" target="_blank">dropNotNullConstraint</a> element:</p>
<pre>&lt;changeSet author="jakob" id="foo-1"&gt;
  &lt;dropForeignKeyConstraint baseTableName="BOOK" constraintName="FK2E3AE9CD85EDFA"/&gt;
  &lt;dropNotNullConstraint tableName="BOOK" columnName="AUTHOR_ID"/&gt;
  &lt;addForeignKeyConstraint baseColumnNames="AUTHOR_ID" <strong>columnDataType="BIGINT" </strong>
    baseTableName="BOOK" constraintName="FK2E3AE9CD85EDFA"
    deferrable="false" initiallyDeferred="false"
    referencedColumnNames="ID" referencedTableName="AUTHOR"/&gt;
&lt;/changeSet&gt;</pre>
<p>With this in place it will work like a charm.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jakusys.de/blog/2008/09/liquibase-addforeignkeyconstraint-column-types-do-not-match/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Grails and LiquiBase &#8211; How to use</title>
		<link>http://www.jakusys.de/blog/2008/09/grails-and-liquibase-how-to-use/</link>
		<comments>http://www.jakusys.de/blog/2008/09/grails-and-liquibase-how-to-use/#comments</comments>
		<pubDate>Fri, 19 Sep 2008 03:07:51 +0000</pubDate>
		<dc:creator>Jakob Külzer</dc:creator>
				<category><![CDATA[Cool Tech]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[LiquiBase]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Guide]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.jakusys.de/blog/?p=313</guid>
		<description><![CDATA[In my current project I'm now at a point where the application has come pretty far but is still far from finished. The domain model is not perfect, but very stable at this point -- changes however, are still possible. To get going with the application we are planning to perform tests with some real [...]]]></description>
			<content:encoded><![CDATA[<p>In my current project I'm now at a point where the application has come pretty far but is still far from finished. The domain model is not perfect, but very stable at this point -- changes however, are still possible.</p>
<p>To get going with the application we are planning to perform tests with some real data. The problem at this point is that entering real data into a database that might be wiped due to changes in the domain model is a very tedious task, at least for the person responsible for entering the data. And the reason for running such a test is to find problems with the domain model which lead to the dreaded changes in the domain model. This cat bites her own tail...</p>
<p>As wiping out the database and re-entering the data is not an option at this point, I decided to look into <a title="LiquiBase" href="http://www.liquibase.org/home" target="_blank">LiquiBase</a> which as been sitting on my delicious list for quite a while.</p>
<p>This post is an attempt to write down my experiences and learned lessons with LiquiBase. The <a title="LiquiBase Manual" href="http://www.liquibase.org/manual/home" target="_blank">documentation of LiquiBase</a> is technically complete and extensive but lacks more information about how to use it in a real project. This is an attempt to create a guide on how to leverage LiquiBase in a real world project.</p>
<p><span id="more-313"></span></p>
<h2>What is this LiquiBase anyways?</h2>
<p>For starters LiquiBase is a tool that helps developers to track and apply changes to database schemas. Basically what it does is storing all changes that are made to a database in a special XML file, called a database changelog file. This changelog file can be used to determine if there are any changes between the schema in the changelog file and the schema found in a database. The nice thing about LiquiBase is that it is database neutral so you can use with any database Java is able to connect to, and that are a lot...</p>
<p>But there is more to LiquiBase that just tracking changes. The outstanding feature of LiquiBase is that it is able to migrate data using the information stored in the database changelog file. This doesn't sound like very much when you are starting a project from scratch, but as soon as you start entering data in your evolving application, you'll understand. And as every application evolves, this is a feature handy for every developer, especially for Grails developers as Hibernate as ORM basically supports only two modes of operation to handle the database schema (configured via the <tt class="literal"><a title="Hibernate Configuration" href="http://www.hibernate.org/hib_docs/v3/reference/en-US/html/configuration-optional.html" target="_blank">hibernate.hbm2ddl.auto</a> option</tt>): wiping out the database and applying a new schema (called create or create-drop) or attempting to update the schema (simply called update). The update option looks like a good way to go at first but as it turns out it has its drawbacks, especially if there is data in the database.</p>
<h2>How does it work?</h2>
<p>The hub of all activity in LiquiBase is the changelog file. Basically there are two possible ways to create and maintain the changelogs, the first is to use the generated changelogs as far as possible and the other is to write changelogs by hand. I'm sticking mostly to the first one as the generated changelogs are sufficient most of the time and writing changelogs manually is way to tedious though easy as there is a complete XSD.</p>
<p>Each entry in the changelog file is called a changeset and has a unique id. The id is used to refer to specific datasets. But how does LiquiBase know which changesets have been applied to the database? The answer is simple, it creates a table called DATABASECHANGELOG into which it will insert a row for each applied changeset. So make sure you start using LiquiBase early because you really want to have these tables in your database when changes have been incorporated into a running system.</p>
<p>Applying changesets against the database is called migration but more on this later.</p>
<h2>Setting the Scene</h2>
<p>The work flow to push in changes may depend on your project. The work flow I'm describing can be applied to team of couple of Grails developers and has been tested on a real world project.</p>
<p>As an example for the rest of the post let's assume a project that is developed by a couple of code monkeys. The change the domain classes and to monkey stuff. On the other hand there is a data entry system deployed so real data can be inserted into the database and the software can be demoed. I will refer to this system as the demo system. The demo system and the data entered into it has several purposes. First to see if the domain model is adequate for real data and second to provide the developers with real testing data.</p>
<p>Problems arise quickly in this scenario, for example changes are made to the domain model and the database schema of the demo system must be updated, preferably without wiping out all the data that has been entered. At this point LiquiBase comes in.</p>
<h2>Grails and LiquiBase - Getting Started</h2>
<p>Ok, now how to use LiquiBase in a Grails Project? Easy: there is a <a title="Grails LiquiBase Plugin" href="http://www.liquibase.org/manual/grails" target="_blank">LiquiBase grails plugin</a> for grails which can easily be installed using the following command:</p>
<pre>grails install-plugin liquibase</pre>
<p>This will install a copy of LiquiBase in your application and set up a <a title="Grails LiquiBase Commands" href="http://www.liquibase.org/manual/grails" target="_blank">couple of new commands</a> for the grails command line interface. Before you can do anything useful with LiquiBase you have to create a database changelog file for your current database, preferably using the generate-changelog command:</p>
<pre>grails generate-changelog grails-app/migrations/changelog.xml</pre>
<p>Note: if you omit the filename the changelog will be dumped to the console. You can dump the changelog into any file but grails-app/migrations/changelog.xml is the default and LiquiBase will keep looking for this file. With the changelog file in place you should add it to your version control system.</p>
<h2>Tracking Changes</h2>
<p>So the next step is to make some changes to the domain model which result in a change of the database schema. You now have two possibilities for updating your changelog file. Either manually or using some of the neat tools LiquiBase offers. I won't go into the details for creating the files manually, the LiquiBase manual does a good job at this. So let's talk about the tools.</p>
<p>LiquiBase ships with a very powerful command: diff. What this does is it looks at the current database and at <span style="text-decoration: line-through;">the changelog</span> (<strong>I have to correct myself here, see next section! Sorry about this!</strong>) another database and outputs the difference between them. As LiquiBase changelog XML! So this is awesome because you can make changes to your Grails domain model, run it against a database and pull out the changes. All that is then to do is to add the newly generated changesets to your database changelog file.</p>
<h2>The db-diff Tool</h2>
<p>The db-diff tool in the Grails plugin is kind of mysterious. The LiquiBase documentation for the Grails plugin does not even mention it and I got it wrong in the first run. I had to reading the <a title="DB DIFF " href="http://www.liquibase.org/manual/diff" target="_blank">section about the database diff</a> provided by LiquiBase and dig through the Groovy scripts of the LiquiBase Grails plugin to understand what it does.</p>
<p>The diff utility of LiquiBase compares two databases with each other, which kind of explains its name (doh). When using the LiquiBase command line interface you have to provide two different connection strings for two databases. When using the Grails plugin however, you cannot specify two databases (not yet?); so what happens is that: the database for the current environment ist compared to the database of the test environment. This behaviour is hardcoded into plugins/liquibase-1.8.0.0/scripts/DbDiff.groovy and limits the usefulness of the tool. So what I did is every time a database has been migrated the new schema gets propagated to the testing database. If the domain model changes the schema of the dev database, the changes can easily be determined by diff'ing it against the testing database.</p>
<p>This is not exactly a perfect solution as you manually have to keep the testing database in sync with the changelog. So I am currently playing around with a modification of the Grails LiquiBase plugin which adds a compareToChangelog command which populates a separate database from the current changelog and then compares this to the database of the currently used environment. Using this tool makes updating the changelog really easy as you get the changesets just for those changes you made to the domain model. If there is interest I will publish this to the LiquiBase plugin.</p>
<h2>Migrating a Database</h2>
<p>Finally your changelog has been updated and you now need to update your demo database. The first thing you should do: <strong><span style="color: #ff0000;">Make a backup of your database</span></strong>! Although LiquiBase has matured to some extent, migrating a database full of data is a risky endeavor. So make sure you are on the safe side before touching a database with real data.</p>
<p>The easiest way to migrate the database is to set up a copy of your project and modify the datasource to point at the demo database. The first thing you might want to do is to check which changesets have to be executed by running the following command:</p>
<pre>grails status</pre>
<p>This will generate a list of changesets which have to be applied, assuming there is a DATABASECHANGELOG table in the database. If you are happy with what you see, you can either migrate the database directly or do a dry run. I prefer to do a dry run before touching the database by running:</p>
<pre>grails migrate-sql</pre>
<p>This will output a sequence of SQL statements that LiquiBase will issue to migrate the database. This is quite handy as you can see what will happen. Then, finally the database is migrated by issuing the following command:</p>
<pre>grails migrate</pre>
<p>When everything goes fine your database has just been updated. If something goes wrong, you can either use the rollback commands provided or fall back to the backup of your database.</p>
<h2>Gotchas</h2>
<p>The following points present pitfalls you want to avoid (its enough that I hit them <img src='http://www.jakusys.de/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> . Please note that this is a living section, I keep adding new points I encounter.</p>
<h3>Use LiquiBase early!</h3>
<p>Make sure you start using LiquiBase early. Insert the DATABASECHANGELOG table as soon as possible and ensure that changesets are run against the databases.</p>
<h3>Backups, Backups, Backups...</h3>
<p>Backup your database before migrating! Really, do it!</p>
<h3>Stick to one Database Flavor</h3>
<p>Do not switch database flavors, e.g. from HSQLDB to MySQL. I tried this and I've encountered  a couple of issues with this. For example a changelog created from a HSQLDB may not run on a MySQL and vice versa due to different named datatypes (e.g. MySQL MEDIUMBLOB vs. HSQLDB VARBINARY). Further the changelog generated from a MySQL can cause problems on other databases as it names all primary keys "PRIMARY" per default. This leads to erroneous SQL that cannot be run.</p>
<p>Those problemes are nothing that couldn't be solved with a little bit of search and replace and even might be necessary to create the schema for a production database; but it is definitively nothing you want to do very often.</p>
<h3>How to Start Using LiquiBase in the Middle of a Project</h3>
<p>When you start to use LiquiBase in the middle of a project where there already is a database filled with precious production data, things can easily become complicated. The key to success here is to freeze the project or at least the part which affects the database schema for some time, generate a database changelog file from the current state and propagate this to all database instances. The reason why this is so important is that you need the DATABASECHANGELOG table on those databases; without this table and its entries  LiquiBase does not know which changes to apply. You could use the db-diff tool here, but the far more elegant approach is to simply propagate those changes to all databases once.</p>
<p>As soon as you have the DATABASECHANGELOG on all database instances, updating the schema becomes so easy that you will almost get addicted to it!</p>
<p>So, step by step:</p>
<ul>
<li>freeze your project for half an hour, maybe you can do this in the evening</li>
<li>create a new changelog file from the current schema with the <em>grails generate-changelog</em> command</li>
<li>mark all those changesets as imported with the <em>grails changelog-sync</em> command</li>
<li>push those changes to ALL databases associated with the project. If you fail to do so, migrating the schema of a database without those tables is almost impossible. Depending on the size of your database this requires a massive amount of time.</li>
<li>With the DATABASECHANGELOG table in place, migrating LiquiBase to the next version is as simple as entering grails migrate.</li>
</ul>
<h2>Conclusion</h2>
<p>LiquiBase is a great addition to Grails and you should really really think about using it. Otherwise managing changes to the database can easily become a big problem and im talking out of experience here. Hopefuly this post helps you to get started with LiquiBase. As always if you have any comments please feel to post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jakusys.de/blog/2008/09/grails-and-liquibase-how-to-use/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
	</channel>
</rss>

