S
S
shamyyl2016-07-14 17:20:44
MySQL
shamyyl, 2016-07-14 17:20:44

What are the arguments in favor of using transactions in the database?

Moved to a new job. And then it turns out that the guys do not use transactions at all (!) When writing related data. And foreign keys are not placed anywhere (!!) in the database.
To my arguments that this threatens data integrity, the answer is that integrity should be controlled at the level of the application code itself.
I kind of understand with my soul that it’s impossible to write without transactions in such cases, but here’s the killer - I don’t have any more arguments on this topic.
I would like to hear arguments along with some cases that the approach "Fuck the transaction, you need to write the correct code" is not correct.

Answer the question

In order to leave comments, you need to log in

6 answer(s)
S
Saboteur, 2016-07-14
@shamyyl

"1) Add a transaction - just a few lines of code.
2) I would just like to hear what problem cases are possible here"
Write a few lines of code - developers' time and customer's money. "
Test a few lines of code - testers' time and customer's money.
Achieve creating a new task that the customer will pay for - the time of managers and the money of the customer
Using transactions is just a tool, not the truth.You need to give an example when in the current operation of your application a real error situation may arise due to the fact that you do not use transactions , and that it will be more profitable and cheaper to solve or prevent such a situation by introducing transactions than using code, as it is done now.
Look for an answer on a toaster, where they don’t know about your project, work conditions, or how easy it is to add a similar task to a sprint - it’s unlikely that you will get the right answer, there is even a chance that you will get several different answers, but you will only accept it as the correct one the one that you personally like, and not the one that is more adequate.

Дмитрий Энтелис, 2016-07-14
@DmitriyEntelis

Главный аргумент за использование транзакций, это не запись связанных данных, - а корректная обработка конкурентных запросов, в тех случаях когда это критично.
Условно писать без транзакций биллинг - показатель профнепригодности, а вот какой нибудь бложик - вполне нормально.

Александр Аксентьев, 2016-07-14
@Sanasol

Т.е. вы сами услышали где-то или "душой поняли" что транзакции МАСТХЕВ.
Начали об этом спорить с коллегами.
При этом у вас нет ни одного аргумента в их пользу?
А теперь просите чтобы мы за вас поспорили с вашими коллегами.
Вы прямо вылитый интернет-воен или диванный, не знаю есть ли разница.
По теме:
https://ru.wikipedia.org/wiki/ACID

Алексей Черемисин, 2016-07-14
@leahch

Ну как бы и без транзакций можно обходиться. Например использовать поле version, которое прибавляется каждый раз при при update.
Если вся работа с данными сводится к их добавлению, то транзакции и не нужны.
Но если присутствует цикл select/update, да еще и в несколько потоков, то рано или поздно данные повредятся.
Простой случай, возьмем поле debit. Попробуем его увеличивать в несколько потоков без транцакций в цикле - select debit from mytable where ID=10, программно прибавляем единичку к полученному debit, затем делаем update mytable set debit=11 where ID=10. Результат приятно удивит.
Также можно обойтись и без транзакций (точнее использовать так называемые "оптимистические блокировки"), если с полем debit считывать, например, поле version -

select debit, version as oldversion from mytable where ID=10
. Тогда update будет выглядеть примерно так
update mytable set debit =11, version=version+1 where ID=10 and version=oldversion
. Но при этом придется всегда проверять, изменили ли мы данные или нет.
ЗЫ. По просьбам трудящихся, про оптимистические блокировки - https://ru.wikipedia.org/wiki/Блокировка_(СУБД)

Алексей Уколов, 2016-07-14
@alexey-m-ukolov Куратор тега MySQL

The only thing that can be argued is that there is much less code when using the built-in features of the DB - why write something that is already well implemented in the DB?
And so, with full code coverage with tests and a normal architecture, there is not much difference. Unless writing transactions at the application level is some strange perversion. And here without foreign keys it is quite possible to manage. I always put them on, but I can understand those who give up on this.

L
lega, 2016-07-14
@lega

Make a correct sample that "breaks" the logic, for example, a competitive request for a double write-off of the same money.

integrity must be controlled at the level of the application code itself.
How do they control it?
It is possible, but not for complex transactions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question