Question

I have a table called customer_transactions that contains a column named amount of type DECIMAL (not unsigned). In the customer table there is a column named account_balance which must always be equal to the sum of the customer's customer_transactions.amount rows.

Is there a way to enforce this equality by denying any other means of updating the amount column except via trigger (preferably a particularly named trigger)? Or maybe there's another way to enforce this that I'm unaware of?

Was it helpful?

Solution

Are you able to manage privileges on the server? I've never tried it, but I believe that in MySQL 5.1 and above, you could revoke any write privileges on the customer.amount column from your application's database user, while leaving the privilege to read the column and execute table triggers. Providing the user you use to create the trigger has permission to modify the amount column, less privileged users should then be able to still use the trigger.

Unless I have misunderstood the documentation... which is possible.

MySQL 5.1 Create Trigger documentation

OTHER TIPS

No, but you can create an effect like that.

If the account_balance column is not null and the application needs to insert rows, define a default value for the account_balance column.

Create a view that contains all the columns except account_balance and a calculated account_balance column:

create view customer_transactions_2 as -- call it whatever you want
select id, col1, col2, ..., account_balance + 0 as account_balance
from customer_transactions

Give your applications the view to work with. They will be able to do everything with the view that they can with the table, except update the account_balance value (you can't write to the database through views for non-raw columns).

Your trigger on the base table will be able to update the account_balance column.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top