Drools: storing rules in database

ghosttrain picture ghosttrain · Dec 8, 2010 · Viewed 17.4k times · Source

Currently I store all rules files on the file system (there are lots of versions of them) and load the different versions of them into memory at startup. I would like to change to storing my drools files in a database and was wondering if there is any solution or addon to Drools which facilitates this or should I craft my own?

Thanks.

Answer

andbi picture andbi · Jan 6, 2011

Yes, it can be done. All you need is the ability to get InputStream.In my case I use my own JPA class RulePackage to persist rule source as byte[], but you could use direct JDBC connection to access BLOB/CLOB fields in your DB schema. Important thing is to save also type of stored rule source, it will be needed when building rule packages:

switch(rulePackage.getRuleSourceType()) {
  case DRL:
    kbuilder.add( ResourceFactory.newByteArrayResource(rulePackage.getSource()), ResourceType.DRL);
    break;
  case EXCEL:
    kbuilder.add( ResourceFactory.newByteArrayResource(rulePackage.getSource()), ResourceType.DTABLE, excelConfig);
    break;
  case CSV:
    kbuilder.add( ResourceFactory.newByteArrayResource(rulePackage.getSource()), ResourceType.DTABLE, csvConfig);
    break;
  default:
    throw new Exception("Rule package '" + rulePackage.getName() + "' has unknown type");
}

You could consider using newInputStreamResource method if more applicable in your case:

   case DRL:
    kbuilder.add( ResourceFactory.newInputStreamResource(new StringInputStream(myDrlAsString)), ResourceType.DRL);
    break;

or

   case DRL:
    kbuilder.add( ResourceFactory.newInputStreamResource(new ByteArrayInputStream(myDrlAsByteArr)), ResourceType.DRL);
    break;

Something like that.