import { sql } from "drizzle-orm";
import { createHash } from "node:crypto";

//#region src/dolt/advisory-lock.ts
function computeLockKey(prefix, identifier) {
	return createHash("sha256").update(`${prefix}${identifier}`).digest().readBigInt64BE(0);
}
const tryAdvisoryLock = (db) => async (prefix, identifier) => {
	const key = computeLockKey(prefix, identifier);
	return (await db.execute(sql`SELECT pg_try_advisory_lock(CAST(${key} AS bigint)) as acquired`)).rows[0]?.acquired === true;
};
const releaseAdvisoryLock = (db) => async (prefix, identifier) => {
	const key = computeLockKey(prefix, identifier);
	await db.execute(sql`SELECT pg_advisory_unlock(CAST(${key} AS bigint))`);
};

//#endregion
export { releaseAdvisoryLock, tryAdvisoryLock };