Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can NHibernate check if the db schema has been generated?

So, newbie NHibernate user; trying to wrap my brain around it.

I'm contemplating how to handle deployment, and later injection of add-ons to a web app (which may require their own persistence classes).

I was thinking that using SchemaExport for the deployment would work pretty well, but I was wondering if there's a way too get NHibernate to tell me in a common, code-based way that a schema export has been done already, or not. Basically, I want to do smething like in this pseudocode:

  if(!_cfg.HasSchemaForType(typeof(MyType))
       ExportSchema(typeof(MyType));
  else
       UpdateSchema(typeof(MyType));

where the two functions would internally use SchemaExport or SchemaUpdate, respectively.


EDIT: Guys, I appreciate the answer so far, but they're missing the point a bit. What I'm trying to set up is a way for the application to allow for the addition and removal of add-ons which may require changes to the db. I'm not talking about versioning my own code or the like (at least, not as its primary function). So the question is less about when I deploy the app, and more about when I add or remove a plug-in. Has theis plugin (hence the pseudo-code type check) been deployed before? If so, run the update. If not, run the export. Make sense?

like image 285
Paul Avatar asked Jun 15 '09 19:06

Paul


1 Answers

Yes there is, in 3.0 at least

public static bool ValidateSchema()
{
    NHibernate.Tool.hbm2ddl.SchemaValidator myvalidator = new NHibernate.Tool.hbm2ddl.SchemaValidator(m_cfg);
    try
    {
        myvalidator.Validate();
        myvalidator = null;
        return true;
    }
    catch (Exception ex)
    {
        MsgBox(ex.Message, "Schema validation error");
    }
    finally
    {
        myvalidator = null;
    }

    return false;
}

For the update part, do.

public static void UpdateSchema()
{
    NHibernate.Tool.hbm2ddl.SchemaUpdate schema = new NHibernate.Tool.hbm2ddl.SchemaUpdate(m_cfg);
    schema.Execute(false, true);
    schema = null;
} // UpdateSchema
like image 76
Stefan Steiger Avatar answered Oct 08 '22 09:10

Stefan Steiger