How to initialize database from NAnt

You can’t live without unit testing. You develop professionally so your project needs professional, reliable and repeatable build process. You go further and integrate both for test automation and continuous integration.

A some point you realise that your functional/unit testing uses database that could be automatically initialized, every time a an automated tests are executed. It’s easy, yet advanced and professional:

  <target name="initdb">
    <property name="constr" value="Provider=SQLOLEDB;Data Source=BUILDSERVER;Initial Catalog=tempdb;Integrated Security=SSPI;"/>
    <property name="schema" value="${dir.misc}/db/MyDb.Schema.sql"/>
    <property name="content" value="${dir.misc}/db/MyDb.Content.sql"/>

    <echo message="====================================================================="/>
    <echo message="|  Re-Initializing database: ${constr} "/>
    <echo message="|  Schema:  ${schema}"/>
    <echo message="|  Content: ${content}"/>
    <echo message="====================================================================="/>

    <sql connstring="${constr}" transaction="true" print="true" delimiter="GO" delimstyle="Line">
      IF  EXISTS (SELECT name FROM sys.databases WHERE name = N'MyDb') DROP DATABASE [MyDb]
    <sql connstring="${constr}" batch="false" transaction="false" print="true" delimiter="GO" delimstyle="Line" source="${schema}" />
    <sql connstring="${constr}" batch="false" transaction="false" print="true" delimiter="GO" delimstyle="Line" source="${content}" />

Keep database schema and initial content in the version control along with your code. Verify database integration and currency within testing process.

Your development team will hate it because they no longer can leave schema/content scripts in SVN/CVS unsychronized. Soon, they will love it, when most of the problems connected with „master” database being out-of-date will be gone!

Leave a Reply

Back to Top