How to write a Mysql transaction within a static JS-method?

64 views Asked by At

I have this static method that executes a SQL statement:

static save(habit){
    return db.execute(
        'INSERT INTO habits (name, repeatVal, notification, color, question, id) VALUES (?, ?, ?, ?, ?, ?)',
        [habit.name, habit.repeatVal, habit.notification, habit.color, habit.question, habit.id]
    );
}

Instead of this SQL statement I want to do the following SQL Transaction instead (this includes dummy data as of now):

START TRANSACTION;
SELECT @habitId:=MAX(habits.habitId)+1 FROM habits;
INSERT INTO habits(habits.habitId, habits.name, habits.repeatVal, habits.notification, habits.color, habits.question, habits.id) VALUES(@habitId, 'mysql test', 1, 1, '#786578', 'backend hello world', 14);
INSERT INTO habit_status(habit_status.habitId, habit_status.date, habit_status.status) VALUES(@habitId, "2021-04-01", 0), (@habitId, "2021-04-01", 0), (@habitId, "2021-04-01", 0), (@habitId, "2021-04-01", 0), (@habitId, "2021-04-01", 0), (@habitId, "2021-04-01", 0), (@habitId, "2021-04-01", 0), (@habitId, "2021-04-01", 0);
COMMIT;

What's the correct syntax to do this?

1

There are 1 answers

0
Luuk On

A couple of options:

  1. Try t search if anyone asked before: https://stackoverflow.com/search?q=javascript+include+transaction+

  2. Try to write a stored procedure which does do that job.

Which of above options did you try?