imageIn this mini-series of one post, I’ll show you how to generate SQL-script from an UML model.

First, you need a model. This can be any model, but here I use an UML model. The class diagram on the left shows a simple model consisting of a parent class and a related child class. Both are stereotyped <<table>> so you can see we are talking about a data model.

Both have some attributes. Note that their types have been declared explicitly.

The interesting part is their association. As you can see it is a traditional master-detail relationship. For clarity I have named the association and both association ends, but the latter is not strictly necessary.

This UML diagram can be represented in the following XML form:

Why that is interesting? That is because XML easily can be transformed into something useful.

For performing the actual transformation you can use, for example:

  1. XSLT stylesheet-driven transformation
  2. template-driven code generator
  3. code using XmlSerializer or XmlReader

Thus, it is transformed into a sql-script.

The keen eye will notice that in the final sql-script primary and foreign key columns are introduced, which are not present in the original model (diagram nor xml file). The other way around, specification of associations in the original model is much richer than the resulting foreign key constraint in the sql-script. These “mismatches” must be handled and are typically present when performing O/RM mapping.