๐Ÿ”’ Core Concepts

Transactions in PikaORM

Transactions are handled very simplistically in PikaORM, utilizing Java Lambdas as the core function.

withTransaction() โ†’ Execute ops โ†’ Exception? โ†’ Rollback ๐Ÿ”™ or Commit โœ“

Basic Lambda Transactions

PikaORM wraps transactions inside the withTransaction() block. If an exception is thrown inside the lambda, the entire transaction (including nested transactions) is rolled back.

PikaORM orm = new PikaORM("jdbc:sqlite:test/web.db")
    .withLogLevel(TRACE)
    .makeDefaultORM()
    .withMigrations(new TransactionDemo())
    .applyMigrations();

TransactionDemo foo = new TransactionDemo("foo", 10);
TransactionDemo bar = new TransactionDemo("bar", -10); // bad value

try {
    orm.withTransaction(() -> {
        orm.insert(foo);

        // Nested transaction example
        orm.withTransaction(() -> {
            orm.insert(bar);
        });
    });
} catch (Exception e) {
    e.printStackTrace();
    // Transaction rolls back โ€” foo and bar are NOT saved.
}

Record Lifecycle Validation

We recommend using the PikaRecordLifecycle interface to ensure safety within transactions. This puts developers in the habit of validating data right before it hits the database.

public class TransactionDemo extends PikaORM.Migrations implements PikaRecordLifecycle {

    public long id;
    public String name;
    public Integer intValue;

    public TransactionDemo(String name, Integer intValue) {
        this.name = name;
        this.intValue = intValue;
    }

    // This lifecycle hook throws if the value is invalid
    @Override
    public boolean beforeInsert() {
        if (intValue < 0) {
            throw new IllegalStateException("Value cannot be less than zero");
        }
        return true;
    }

    @Override
    public void migrations() {
        add(this::addTransactionDemoTable);
    }
    // ... migration logic ...
}

By throwing an exception in beforeInsert(), the lambda transaction block automatically catches it and rolls back the database state seamlessly.