Skip to content

Commit 28a63e1

Browse files
committed
db.d: make privilege operations atomic
1 parent 8824f5d commit 28a63e1

File tree

1 file changed

+17
-23
lines changed

1 file changed

+17
-23
lines changed

src/db.d

Lines changed: 17 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -684,15 +684,15 @@ final class Database
684684
bool add_user_privileges(string username, Duration duration)
685685
{
686686
enum sql = text(
687-
"UPDATE ", users_table, " SET privileges = ? WHERE username = ?;"
687+
"UPDATE ", users_table,
688+
" SET privileges = CASE",
689+
" WHEN CAST(privileges AS INTEGER) > ? THEN privileges ELSE ?",
690+
" END + ?",
691+
" WHERE username = ?;"
688692
);
689-
auto privileged_until = user_privileged_until(username).toUnixTime;
690-
const now = Clock.currTime.toUnixTime;
691-
692-
if (privileged_until < now) privileged_until = now;
693-
privileged_until += duration.total!"seconds";
694-
695-
query(sql, [privileged_until.text, username]);
693+
const now = Clock.currTime.toUnixTime.text;
694+
const seconds = duration.total!"seconds".text;
695+
query(sql, [now, now, seconds, username]);
696696

697697
if (changes() == 0)
698698
return false;
@@ -705,22 +705,16 @@ final class Database
705705

706706
bool remove_user_privileges(string username, Duration duration)
707707
{
708-
const now = Clock.currTime.toUnixTime;
709-
auto privileged_until = user_privileged_until(username).toUnixTime;
710-
if (privileged_until <= now)
711-
return false;
712-
713708
enum sql = text(
714-
"UPDATE ", users_table, " SET privileges = ? WHERE username = ?;"
715-
);
716-
const seconds = duration.total!"seconds";
717-
718-
if (privileged_until > now + seconds)
719-
privileged_until -= seconds;
720-
else
721-
privileged_until = now;
722-
723-
query(sql, [privileged_until.text, username]);
709+
"UPDATE ", users_table,
710+
" SET privileges = CASE",
711+
" WHEN privileges > ? + ? THEN privileges - ? ELSE ?",
712+
" END ",
713+
" WHERE username = ? AND CAST(privileges AS INTEGER) > ?;"
714+
);
715+
const now = Clock.currTime.toUnixTime.text;
716+
const seconds = duration.total!"seconds".text;
717+
query(sql, [now, seconds, seconds, now, username, now]);
724718

725719
if (changes() == 0)
726720
return false;

0 commit comments

Comments
 (0)