Files
YMS/webgui/lib/db.inc
T

58 lines
1.7 KiB
PHP

<?php
/******************************************************************************
* YMS - Yacht Management Software
* Copyright (C) 2024-2026 Thomas Hooge
*
* SPDX-License-Identifier: WTFPL
******************************************************************************
*/
function db_lock_acquire($table, $key, $userid) {
global $pdo;
$token = bin2hex(random_bytes(8));
// first try new lock
$sql = "INSERT INTO recordlock (lock_table, lock_key, token, userid) "
. "VALUES (?, ?, ?, ?)";
try {
$sth = $pdo->prepare($sql);
$sth->execute([$table, $key, $token, $userid]);
return $token;
} catch (PDOException $e) {
if ($e->errorInfo[1] != 1062) {
throw $e;
}
}
// lazy locking: lock exists but is old, so we use it
$sql = "UPDATE recordlock "
. "SET token=?, userid=?, "
. "created_at=CURRENT_TIMESTAMP, last_seen=CURRENT_TIMESTAMP "
. "WHERE lock_table=? AND lock_key=? "
. "AND last_seen<CURRENT_TIMESTAMP-INTERVAL 5 MINUTE";
$sth = $pdo->prepare($sql);
$sth->execute([$token, $userid, $table, $key]);
if ($stmt->rowCount() === 1) {
return $token;
}
return null;
}
function db_lock_refresh($token) {
global $pdo;
$sql = "UPDATE recordlock "
. "SET last_seen=CURRENT_TIMESTAMP "
. "WHERE token=?";
$sth = $pdo->prepare($sql);
$sth->execute([$token]);
return $sth->rowCount() === 1;
}
function db_lock_release($token) {
global $pdo;
$sql = "DELETE FROM recordlock WHERE token=?";
$sth = $pdo->prepare($sql);
$sth->execute([$token]);
return $sth->rowCount() === 1;
}