box.on_commit()
Define a trigger for execution when a transaction ends due to an event
such as
/reference/reference_lua/box_txn_management/commit.
The trigger function may take an iterator parameter, as described in an example for this section.
The trigger function should not access any database spaces.
If the trigger execution fails and raises an error, the effect is severe
and should be avoided – use Lua's pcall() mechanism around code
that might fail.
box.on_commit() must be invoked within a transaction, and the trigger
ceases to exist when the transaction ends.
Parameters:
-
trigger-function(function) — function which will become the trigger function -
old-trigger-function(function) — existing trigger function which will be replaced by trigger-function
Returns
nil or function pointer
If the parameters are (nil, old-trigger-function), then the old
trigger is deleted.
Details about trigger characteristics are in the triggers section.
Example 1
-- Insert test data --box.space.bands:insert { 1, 'Roxette', 1986 }box.space.bands:insert { 2, 'Scorpions', 1965 }box.space.bands:insert { 3, 'Ace of Base', 1987 }-- Define a function called on commit --function print_commit_result()print('Commit happened')end-- Commit the transaction --box.begin()box.space.bands:insert { 4, 'The Beatles', 1960 }box.on_commit(print_commit_result)box.commit()
Example 2
The function parameter can be an iterator. The iterator goes through the effects of every request that changed a space during the transaction.
The iterator has:
- an ordinal request number
- the old value of the tuple before the request (
nilfor aninsertrequest) - the new value of the tuple after the request (
nilfor adeleterequest) - the ID of the space
The example below displays the effects of two replace requests:
-- Insert test data --box.space.bands:insert { 1, 'Roxette', 1986 }box.space.bands:insert { 2, 'Scorpions', 1965 }box.space.bands:insert { 3, 'Ace of Base', 1987 }-- Define a function called on commit --function print_replace_details(iterator)for request_number, old_tuple, new_tuple, space_id in iterator() doprint('request_number: ' .. tostring(request_number))print('old_tuple: ' .. tostring(old_tuple))print('new_tuple: ' .. tostring(new_tuple))print('space_id: ' .. tostring(space_id))endend-- Commit the transaction --box.begin()box.space.bands:replace { 1, 'The Beatles', 1960 }box.space.bands:replace { 2, 'The Rolling Stones', 1965 }box.on_commit(print_replace_details)box.commit()
The output might look like this:
request_number: 1old_tuple: [1, 'Roxette', 1986]new_tuple: [1, 'The Beatles', 1960]space_id: 512request_number: 2old_tuple: [2, 'Scorpions', 1965]new_tuple: [2, 'The Rolling Stones', 1965]space_id: 512