<?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>Software Warlock &#187; Database</title>
	<atom:link href="http://softwareblog.morlok.net/category/database/feed/" rel="self" type="application/rss+xml" />
	<link>http://softwareblog.morlok.net</link>
	<description></description>
	<lastBuildDate>Sat, 24 Dec 2011 16:06:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Mapping Enums to custom strings in NHibernate</title>
		<link>http://softwareblog.morlok.net/2009/07/02/mapping-enums-to-custom-strings-in-nhibernate/</link>
		<comments>http://softwareblog.morlok.net/2009/07/02/mapping-enums-to-custom-strings-in-nhibernate/#comments</comments>
		<pubDate>Fri, 03 Jul 2009 03:16:09 +0000</pubDate>
		<dc:creator>Warlock</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Enum]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Object-relational mapping]]></category>
		<category><![CDATA[ORM]]></category>

		<guid isPermaLink="false">http://softwareblog.morlok.net/?p=294</guid>
		<description><![CDATA[Many times when working with a legacy relation model and a newly developed C# object model that sits on top of the relational model, you may need to map enum values to/from arbitrary strings in the database using NHibernate. For &#8230;<p class="read-more"><a href="http://softwareblog.morlok.net/2009/07/02/mapping-enums-to-custom-strings-in-nhibernate/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>
Many times when working with a legacy relation model and a newly developed C# object model that sits on top of the relational model, you may need to map enum values to/from arbitrary strings in the database using NHibernate.
</p>
<p>
For example, suppose you have a a work order object that three possible states: request, approved, denied.  To represent this, you might use the following enum:
</p>
<pre name="code" class="c#">
enum WorkRequestState
{
    Request,
    Approved,
    Denied
};
</pre>
<p>But let&#8217;s assume that the legacy relational model has represented these values as strings: <tt>REQ</tt>, <tt>APR</tt>, <tt>DEN</tt>.  You can&#8217;t change the values for the relational model, and you certainly don&#8217;t want to use these values in your enum because they are not as readable as the values shown above.</p>
<p>By default, NHibernate will automatically convert you enum to a string value that matches the name of the enum values if the table field a string, or it will convert to the integer value for the enum options if the table field is an integer.</p>
<p>To do the above custom mapping we must implement a custom NHibernate type.</p>
<p>First, create a new class that inherits <tt>NHibernate.Type.EnumStringType</tt>.  In your constructor, pass the type of the enum you are handling, and the maximum number of characters that the enum values will be to the base class constructor:</p>
<pre name="code" class="c#">
class WorkRequestStateEnumStringType : NHibernate.Type.EnumStringType
{
    public WorkRequestStateEnumStringType()
        : base( typeof(WorkRequestState), 3)
    {
    }
    ...
}
</pre>
<p>Next, override the <tt>GetValue(...)</tt> method to map the enum value to the equivalent string.</p>
<pre name="code" class="c#">
public override object GetValue(object enm)
{
	if( null == enm )
		return String.Empty;

	switch( (WorkRequestState)enm )
	{
		case WorkRequestState.Request	: return "REQ";
		case WorkRequestState.Approved	: return "APR";
		case WorkRequestState.Denied	: return "DEN";
		default : throw new ArgumentException("Invalid WorkRequestState.");
	}
}
</pre>
<p>Override the <tt>GetInstance(...)</tt> method to map a string value to the equivalent enum value:</p>
<pre name="code" class="c#">
public override object GetInstance(object code)
{
	code = code.ToUpper();

	if( "REQ".Equals(code) )
		return WorkRequestState.Request;
	else if( "APR".Equals(code) )
		return WorkRequestState.Approved;
	else if( "DEN".Equals(code) )
		return WorkRequestState.Denied;

	throw new ArgumentException(
		"Cannot convert code '" + code + "' to WorkRequestState.");
}
</pre>
<p>Finally, in the NHibernate mapping file, specify the property&#8217;s type as the derived <tt>EnumStringType</tt> class.</p>
<pre name="code" class="xml">
&lt;class name="WorkRequest" table="work_request_table"&gt;
  &lt;property
    name="Status"
    column="status_field"
    type="my.namespace. WorkRequestStateEnumStringType, MyAssembly" /&gt;
  ...
&lt;class&gt;
</pre>
<p>Note that when specifying this type, you must use the <a href="http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx">assembly-qualified name</a> because the NHibernate code doing the mapping is in a separate assembly from the type you created.</p>
<p>This information has been derived from Jeremy Miller&#8217;s original post <a href="http://codebetter.com/blogs/jeremy.miller/archive/2006/02/20/138732.aspx">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://softwareblog.morlok.net/2009/07/02/mapping-enums-to-custom-strings-in-nhibernate/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>CoreData Development Techniques</title>
		<link>http://softwareblog.morlok.net/2009/04/01/coredata-development-techniques/</link>
		<comments>http://softwareblog.morlok.net/2009/04/01/coredata-development-techniques/#comments</comments>
		<pubDate>Thu, 02 Apr 2009 03:58:08 +0000</pubDate>
		<dc:creator>Warlock</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Software Development Tools]]></category>
		<category><![CDATA[Xcode]]></category>
		<category><![CDATA[CoreData]]></category>

		<guid isPermaLink="false">http://softwareblog.morlok.net/?p=145</guid>
		<description><![CDATA[I&#8217;m just getting started with CoreData, and I&#8217;ve been excited about about its nice graphical environment to define your model. CoreData&#8217;s approach to ORM is somewhat different than other tools, such as Hibernate, because it takes advantage of Objective-C&#8217;s dynamic &#8230;<p class="read-more"><a href="http://softwareblog.morlok.net/2009/04/01/coredata-development-techniques/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;m just getting started with CoreData, and I&#8217;ve been excited about about its nice graphical environment to define your model.
</p>
<p><a href="http://softwareblog.morlok.net/wp-content/uploads/2009/04/coredata-model.png"><img src="http://softwareblog.morlok.net/wp-content/uploads/2009/04/coredata-model-300x225.png" alt="" title="CoreData model" width="300" height="225" class="aligncenter size-medium wp-image-147" /></a></p>
<p>
CoreData&#8217;s approach to ORM is somewhat different than other tools, such as <a href="http://www.hibernate.org/">Hibernate</a>, because it takes advantage of Objective-C&#8217;s dynamic nature, and avoids some of the clutter problems you experience with more statically typed languages.  Instead of providing mapping information for classes that are defined elsewhere, all modeled objects are instances of <a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObject_Class/index.html">NSManagedObject</a> and the system customizes the accessors on the created objects based on the schema.
</p>
<p>
This is very nice when you are defining your model, and when you can use things like Cocoa Bindings to provide much of the system&#8217;s behavior based on state of the model, but when you need to start writing custom controller logic, it isn&#8217;t very readable to have everything going around as an NSManagedObject.  You can use the dynamically generated properties on these objects, but you will get compiler warnings.  Annoying.
</p>
<p>
You can certainly subclass NSManagedObject and tell the model to use your implementation.  This is necessarily if you are going to provide custom behavior on the model objects above the simple data oriented behavior CoreData provides for you.  Xcode will even <a href="http://developer.apple.com/DOCUMENTATION/DeveloperTools/Conceptual/XcodeCoreDataTools/Articles/xcdCodeGeneration.html#//apple_ref/doc/uid/TP40006872-SW1">generate source code</a> for you from your data model.
</p>
<p>While in the data model editor, do <em>File</em>, <em>New File&#8230;</em> and select <em>Managed Object Class</em> from the <em>Cocoa</em> category.</p>
<p><a href="http://softwareblog.morlok.net/wp-content/uploads/2009/04/picture-1.png"><img src="http://softwareblog.morlok.net/wp-content/uploads/2009/04/picture-1-300x283.png" alt="" title="select Managed Object Class" width="300" height="283" class="aligncenter size-medium wp-image-159" /></a></p>
<p>Choose the location where your files will be generated.</p>
<p>Select the model entities for which classes will be generated and click <em>Finish</em>.</p>
<p><a href="http://softwareblog.morlok.net/wp-content/uploads/2009/04/picture-2.png"><img src="http://softwareblog.morlok.net/wp-content/uploads/2009/04/picture-2-300x283.png" alt="" title="Select entities to generate" width="300" height="283" class="aligncenter size-medium wp-image-160" /></a></p>
<p>
The problem with this approach is that you are stuck manually keeping the model and the custom classes in sync.  You can certainly regenerate, but if you have made any changes to the files, they will be overwritten.
</p>
<p>One alternative to this manual update process is a tool, <a href="http://rentzsch.com/code/mogenerator">mogenerator</a>, that will automatically generate custom classes for you.  It even goes so far as two generate two classes for each model object:<br /> NSManagedObject&nbsp;<&mdash;&nbsp;GenClassA&nbsp;<&mdash;&nbsp;GenClassB (where <&mdash; represents inherits from).  This allows you to modify the code in GenClassB and leave GenClassA alone, which stores the core information from the model.  This way you can regenerate GenClassA as needed, without overwriting your custom behavior in GenClassB.  <a href="http://www.pyrusmalus.com/index.html">PyrusMalus</a> has an <a href="http://www.pyrusmalus.com/blog/archives/2006/11/06/getting_started_with_mogenerator.html">introduction</a> on how to get started with mogenerator, <a href="http://importantshock.wordpress.com/">Important Shock</a> has a discussion about the <a href="http://importantshock.wordpress.com/2006/12/19/mogenerator-or-how-i-nearly-abandoned-core-data/">approach used</a> by the tool, and <a href="http://guelich.net/blog/">Cocoa &amp; Medicine</a> has a <a href="http://guelich.net/blog/2007/01/01/running-mogenerator-from-xcode">description</a> of how to run mogerator from within Xcode using Apple Script.
</p>
<p>
There is some dissension about if the method of generating custom classes is a good thing.  On <a href="http://www.cocoabuilder.com/archive/message/cocoa/2008/10/5/219503">this thread</a> on <a href="http://www.cocoabuilder.com/">CocoaBuilder</a> Ben (who appears to be from Apple according to <a href="http://www.linkedin.com/profile?viewProfile=&#038;key=852945&#038;authToken=EW78&#038;authType=NAME_SEARCH&#038;pvs=ps">LinkedIn</a>) seems to be against the idea, though I his main objection is to the idea that the custom accessors generated by NSManagedObject are slower than those statically generated by mogenerator.
</p>
<p>
One of Apples <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CoreData/Articles/cdAccessorMethods.html#//apple_ref/doc/uid/TP40002154">recommended approaches</a> to avoid compiler warnings is to created categories for NSManagedObject so that the compiler accepts that the accessors you are using are actually there.  Xcode provides the ability to copy the attribute declarations for use in these categories (or in custom classes), but to cover everything, you need to copy two separate sets of declarations and paste them into the code.  You could use the Xcode custom class generation to get the signatures you need, but there is a still a bit of manual work in the process.
</p>
<p>
In my opinion, Apple needs to work more to help developers with this problem.  I like the approach taken by mogenerator, and I would like to see that same regenerative ability in the built-in Xcode tools, using the 2-class generation-gap design pattern to allow you to make changes to the generated classes without having the changes overwritten next time you re-generate.</p>
]]></content:encoded>
			<wfw:commentRss>http://softwareblog.morlok.net/2009/04/01/coredata-development-techniques/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ADO.NET parameters for use with the SQL &#8220;IN&#8221; Keyword</title>
		<link>http://softwareblog.morlok.net/2008/09/11/adonet-parameters-for-use-with-the-sql-in-keyword/</link>
		<comments>http://softwareblog.morlok.net/2008/09/11/adonet-parameters-for-use-with-the-sql-in-keyword/#comments</comments>
		<pubDate>Thu, 11 Sep 2008 16:39:01 +0000</pubDate>
		<dc:creator>Warlock</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Database]]></category>

		<guid isPermaLink="false">http://softwareblog.morlok.net/2008/09/11/adonet-parameters-for-use-with-the-sql-in-keyword/</guid>
		<description><![CDATA[Long of the short of it is there isn&#8217;t a good way to do it. A common example is that you might want select multiple rows from a table, using a list of IDs: SELECT * FROM room WHERE room_id &#8230;<p class="read-more"><a href="http://softwareblog.morlok.net/2008/09/11/adonet-parameters-for-use-with-the-sql-in-keyword/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>Long of the short of it is there isn&#8217;t a good way to do it.</p>
<p>A common example is that you might want select multiple rows from a table, using a list of IDs:
<p><code>SELECT * FROM room WHERE room_id IN (1,2,3,4);</code></p>
<p>What you&#8217;d like to do is have this list as an array parameter and set it appropriately on the command:</p>
<p><code><br />
int ids = new int[] { 1, 2, 3, 4 };<br />
string sql = "SELECT * FROM room WHERE room_id IN @IDS;";</p>
<p>SqlCommand cmd = new SqlCommand(sql, conn);</p>
<p>// DOES NOT WORK!<br />
cmd.Parameters.Add("@IDS", ids);<br />
</code></p>
<p>The problem is there is no array type in SQL server/ADO.NET. The only way to accomplish this is through dynamic sql, which is definitely not a best practice.</p>
<p>There are several articles discussing this problem.  The following are taken from this <a href="https://forums.microsoft.com/msdn/ShowPost.aspx?PostID=2405231&#038;SiteID=1">forum discussion</a> in which Arnie Rowland provided the links.</p>
<ul>
<li><a href="http://www.sommarskog.se/arrays-in-sql.html">http://www.sommarskog.se/arrays-in-sql.html</a></li>
<li><a href="http://databases.aspfaq.com/database/how-do-i-simulate-an-array-inside-a-stored-procedure.html">http://databases.aspfaq.com/database/how-do-i-simulate-an-array-inside-a-stored-procedure.html</a></li>
<li><a href="http://www.projectdmx.com/tsql/sqlarrays.aspx">http://www.projectdmx.com/tsql/sqlarrays.aspx</a></li>
<li><a href="http://omnibuzz-sql.blogspot.com/2006/06/interesting-queries-using-recursive.html">http://omnibuzz-sql.blogspot.com/2006/06/interesting-queries-using-recursive.html</a></li>
<li><a href="http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=419984&#038;SiteID=17">http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=419984&#038;SiteID=17</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms188332.aspx">http://msdn.microsoft.com/en-us/library/ms188332.aspx</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms175170.aspx">http://msdn.microsoft.com/en-us/library/ms175170.aspx</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://softwareblog.morlok.net/2008/09/11/adonet-parameters-for-use-with-the-sql-in-keyword/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Structuring your database update scripts</title>
		<link>http://softwareblog.morlok.net/2007/10/27/structuring-your-database-update-scripts/</link>
		<comments>http://softwareblog.morlok.net/2007/10/27/structuring-your-database-update-scripts/#comments</comments>
		<pubDate>Sat, 27 Oct 2007 17:01:27 +0000</pubDate>
		<dc:creator>Warlock</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[nant]]></category>

		<guid isPermaLink="false">http://softwareblog.morlok.net/2007/10/27/structuring-your-database-update-scripts/</guid>
		<description><![CDATA[I&#8217;m currently working on a project that will serve as the back-end for my adult hockey teams website (more on that to come). I&#8217;m also using this project as a test bed for some ideas I&#8217;d like to try at &#8230;<p class="read-more"><a href="http://softwareblog.morlok.net/2007/10/27/structuring-your-database-update-scripts/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently working on a project that will serve as the back-end for my adult hockey teams <a href="http://www.ahawarriors.com/">website</a> (more on that to come).  I&#8217;m also using this project as a test bed for some ideas I&#8217;d like to try at work for upcoming development.</p>
<p>One of the big problems we face with our current iteration of our product is that we need to manage the structure of the database.  We have a .NET app that has a database back-end powering some web services and a web based interface to the product.  The problem is we have many customers (well, I guess that&#8217;s not a problem) and they tend to be running different versions of the product, and hence different version of the database.  As part of customization services we offer, we may need to make minor alterations to the database structure that later get rolled into the next major product release.</p>
<p>Back to the hockey info manager.  I&#8217;ve been researching best practices on how to structure your development environment to help manage all these challenges, and I&#8217;ve been basing a lot of what I&#8217;m doing on <a href="p://www.jpboodhoo.com/blog/">Jean-Paul S. Boodhoo</a>&#8216;s work, as posted previously. For these database problems, I&#8217;m working with <a href="http://www.jpboodhoo.com/blog/AutomatingYourBuildsWithNAntPart6.aspx">this post</a> in particular.</p>
<p>Specifically, Jean-Paul advocates splitting database creation scripts into multiple templated files to handle creating the various aspects of the database.  I&#8217;ve generalized this a bit more so that there are multiple phases to the database, the initial phase and the update phase.</p>
<p>The database scripts are setup with the following naming convention:</p>
<pre>YYYYY.##.ZZZZZ.sql.template</pre>
<p>Where each of the sections means the following:</p>
<ul>
<li> YYYYY &#8211; The phase of the database creation this script applies to</li>
<li> ## &#8211; Within the phase, the order in which the script should be executed</li>
<li> ZZZZZ &#8211; A human friendly description of what the script addresses</li>
</ul>
<p>The database creation scripts are divided up into three phases: <em><font color="#000000">Initial</font></em>,<br />
<em><font color="#000000"> Update</font></em>, and <em><font color="#000000">Test</font></em>.</p>
<p>The <em><font color="#000000">Initial</font></em> phase create the database fresh for the current major release. These<br />
scripts deal with dropping the existing database if it exists, and creating<br />
everything from scratch.</p>
<p>The <font color="#000000"><em>Update</em></font> phase moves the database from it&#8217;s initial phase to the most current<br />
configuration.  Once the product has been released for use, the Initial phase<br />
scripts should no longer be updated, but rather the Update phase scripts should<br />
contain all changes to the database as part of patches, hotfixes, etc.<br />
Furthermore, scripts in the updates phase should assume that data already<br />
exists within the system and nothing should be broken by running the upgrade<br />
scripts.  This includes customers who may have previously had their database<br />
updated (inidicating the script is being run on a database that has been<br />
partially updated).  By combining (in order) the scripts in the update phase,<br />
a master database update script can be generated that will take the database<br />
from any state on or after the initial state to the most current phase.</p>
<p>When the product is being prepared for a major version release, a master upgrade<br />
package is created that combines all the updates from the previous version.<br />
This script is kept separately as part of a migration package, and all the<br />
changes in the updates are incorporated into the initial creation scripts. At<br />
this point the update scripts are wiped clean and the process begins again.</p>
<p>The <em><font color="#000000">Test</font></em> phase does not include any changes to the structure of the database<br />
but rather only adds data to the database that can be used in testing.</p>
<p>Below is the list of files currently in use in the project:</p>
<pre>Initial.00.Database.sql.template</pre>
<pre>Initial.01.Views.sql.template</pre>
<pre>Initial.02.StoredProcedures.sql.template</pre>
<pre>Initial.03.Security.sql.template</pre>
<pre>Initial.04.Data.sql.template</pre>
<pre>Update.00.Database.sql.template</pre>
<pre>Update.01.Views.sql.template</pre>
<pre>Update.02.StoredProcedures.sql.template</pre>
<pre>Update.03.Security.sql.template</pre>
<pre>Update.04.Data.sql.template</pre>
<pre>Test.00.Data.sql.template</pre>
<p>Obviously, I have yet to test this structure in practice, but I&#8217;ll keep the blog up to date with how well this structure ends up working.</p>
]]></content:encoded>
			<wfw:commentRss>http://softwareblog.morlok.net/2007/10/27/structuring-your-database-update-scripts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

