Menu

DBScript: Transactions Without Noticing

A primary requirement of an database product is transactions: the safety mechanism that protects your data.

There a 2 mechanism for handling transactions in DBvolution: DBTransaction; and DBScript.

DBTransaction is a generic interface for creating a series of DBV statements and returning something back. The transaction is actually run using the DBDatabase's doTransaction() and doReadOnlyTransaction() methods:

    DBTable<Marque> transacted = database.doTransaction(
        new DBTransaction<DBTable<Marque>>() {
            @Override
            public DBTable<Marque> doTransaction(DBDatabase dbDatabase) throws SQLException{
                Marque myTableRow = new Marque();
                .
                .
                .
                return marques;
            }
        }
    );

This is all rather complicated and there is a lot of boilerplate code to be written correctly.

DBScript builds on the DBTransaction and makes it trivial to use.

The return type is already specified: it's a DBActionList, and DBScript provides test() and implement() methods to clearly indicate what the intention of the operation is.

All you need to do is subclass DBScript,implement the abstract method, and call test():

public class ChangeCurrentModel extends DBScript{

    @Override
    public DBActionList script(DBDatabase db) throws Exception {
        Vehicle vehicle = new Vehicle();
        ModelVariant mvar = new ModelVariant();
        ModelVersion mver = new ModelVersion();

        vehicle.unitNumber.permittedValues(1337);
        mvar.name.permittedValues("ZING");
        mver.name.permittedValuesIgnoreCase("XY2");

        return UsefulMethods.changeModelVersionOfVehicle(db, vehicle, mvar, mver);
    }
}

Inside your main method use something like:

    DBActionList actions = currentIncident.test(db);

or equivalently:

    DBActionList actions = db.test(currentIncident);

DBScript allows you to just write DBV code without worrying about transactions, in fact DBV works best if you don't.

Use the DBScript to collect all of your methods and actions together and let it handle all the transaction details internally.

As always any exception from the database will automatically rollback the transaction safely.

Posted by Gregory Graham 2014-01-28

Anonymous
Anonymous

Add attachments
Cancel





Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.