Can I exclude certain tables when building my database schema using Castle ActiveRecord
-
12-01-2021 - |
Question
We are using Castle ActiveRecord as a helper layer on top of NHibernate. To generate our database, we use:
ActiveRecordStarter.CreateSchema();
To generate the sql for building our database we use:
ActiveRecordStarter.GenerateCreationScripts(filename);
They work like a charm. However we sometimes don't want to generate a table for every one of our entities. I believe nhibernate has a mechanism for excluding certain tables from a schema build (see here) - does anyone know whether ActiveRecord can do the same thing?
La solution
For posterity, here's what I ended up doing:
1) Grabbed the NHibernate SchemaExporter source code and renamed the class to "OurSchemaExporter".
2) Added a new constructor:
public OurSchemaExporter(Configuration cfg, Func<string, bool> shouldScriptBeIncluded)
: this(cfg, cfg.Properties)
{
this.shouldScriptBeIncluded = shouldScriptBeIncluded ?? (s => true);
}
3) Modified the initialize method to call out to find out whether a script should be included:
private void Initialize()
{
if (this.wasInitialized)
return;
if (PropertiesHelper.GetString("hbm2ddl.keywords", this.configProperties, "not-defined").ToLowerInvariant() == Hbm2DDLKeyWords.AutoQuote)
SchemaMetadataUpdater.QuoteTableAndColumns(this.cfg);
this.dialect = Dialect.GetDialect(this.configProperties);
this.dropSQL = this.cfg.GenerateDropSchemaScript(this.dialect);
this.createSQL = this.cfg.GenerateSchemaCreationScript(this.dialect);
// ** our modification to exclude certain scripts **
this.dropSQL = new string[0]; // we handle the drops ourselves, as NH doesn't know the names of all our FKs
this.createSQL = this.createSQL.Where(s => shouldScriptBeIncluded(s)).ToArray();
this.formatter = (PropertiesHelper.GetBoolean("format_sql", this.configProperties, true) ? FormatStyle.Ddl : FormatStyle.None).Formatter;
this.wasInitialized = true;
}
4) When using OurSchemaExporter, check whether we want to include certain tables by looking at the contents of each SQL create script:
var ourSchemaExport = new TpsSchemaExporter(configuration, ShouldScriptBeIncluded);
...
private bool ShouldScriptBeIncluded(string script)
{
return !tablesToSkip.Any(t => ShouldSkip(script, t));
}
private static bool ShouldSkip(string script, string tableName)
{
string s = script.ToLower();
string t = tableName.ToLower();
return
s.Contains(string.Format("create table dbo.{0} ", t))
|| s.Contains(string.Format("alter table dbo.{0} ", t))
|| s.EndsWith(string.Format("drop table dbo.{0}", t));
}
A hack, but it does the job.