Is it possible to listen for or be notified when an event occurs on a data table e.g. on row added?
I would like to create a background task that is triggered when a specific change occurs on a data table.
Is it possible to listen for or be notified when an event occurs on a data table e.g. on row added?
I would like to create a background task that is triggered when a specific change occurs on a data table.
You can create a scheduled task set to run periodically, (Maybe every once a minute?) and then have it launch your background task if various logic is true. This logic could include checking the state of a specific data table, recording it somewhere and then checking it again the next time it ran and comparing the two states. (This would tell you if the state changed.)
If you only want to know if the table contains a different number of rows than before, you can just use len(app_tables.your_table_name.search() )
to get the number of rows. The len()
function for the search operator is optimized to not iterate over every row, and just give you the number of results of a search very quickly.
To the best of my knowledge, Anvil’s database API does not have triggers. The most reliable way to do this is to
This is what we do, for example, to handle referential integrity (and other) constraints, e.g., when there is app-specific processing that needs to be done when attempting to delete a table row. We might decide, for example, to deny that deletion, if it would break cross-references from elsewhere in the database.
Simply counting rows can fail, for example, if you’re both adding and deleting rows. Moreover, it won’t tell you which rows were affected. With Anvil’s current database API, the only reliable way to tell, is to wrap those database operations in functions that you call, so that you can intercept those operations yourself.
Triggers might be possible with SQL-level access. A few people on the forum work at that level, and might know whether that’s feasible.