Logic Operation
Logic Architecture
Logic Bank operates as shown above:
-
Automatic Configuration
a. Declare logic in
logic/declare_logic.py
. Here is a summary of the rule typesb. The Admin App and JSON:API are already configured to load and execute this logic
-
Admin App and JSON:API operate as usual: makes calls on
SQLAlchemy
for inserts, updates and deletes and issuessession.commit()
-
The Logic Bank engine handles SQLAlchemy
before_flush
events onMapped Tables
, so executes on thissession.commit()
-
The logic engine operates in 2 phases:
a. Initial Loop - the logic engine operates much like a spreadsheet, executing the following on each inserted, updated or deleted row:
- watch for changes - at the attribute level
- react by running rules that referenced changed attributes, which can
- chain to still other attributes that refer to those changes. Note these might be in different tables, providing automation for multi-table logic
b. Commit Loop after all the rows have been initially processed, the engine executes commit constraints and events for each table that defines them
Logic does not apply to updates outside SQLAlchemy, nor to SQLAlchemy batch updates or unmapped sql updates.
Basic Idea - Like a Spreadsheet
Rules are spreadsheet-like expressions for multi-table derivations and constraints. For example (not actual syntax):
The Customer Balance is the sum of the unshipped Order AmountTotals
You can imagine that the spreadsheet watches for changes to referenced cells, reacts by recomputing the cell, which may chain to other cells.
Let's see how logic operates on a typical, multi-table transaction.
Watch, React, Chain
Let's consider a typical multi-table transaction. Here is the 5 rule solution for check credit:
As Order Details are inserted, the rule flow is shown below.
The add_order
example illustrates how
Watch / React / Chain operates to
check the Credit Limit as each Order Detail is inserted:
-
The
OrderDetail.UnitPrice
(copy, line 78) references Product, so inserts cause it to be copied -
Amount
(formula, line 75) watchesUnitPrice
, so its new value recomputesAmount
-
AmountTotal
(sum, line 72) watchesAmount
, soAmountTotal
is adjusted (more on adjustment, below) -
Balance
(sum, line 68) watchesAmountTotal
, so it is adjusted -
And the Credit Limit constraint (line 64) is checked (exceptions are raised if constraints are violated, and the transaction is rolled back)
All of the dependency management to see which attributes have changed, logic ordering, the SQL commands to read and adjust rows, and the chaining are fully automated by the engine, based solely on the rules above.
Creating New Rule Types
Not only can you define Python events, but you can add new rule types. This is an advanced topic, described here