Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: sqlite bun compat patch, fix race condition #81

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 20 additions & 25 deletions db/sqlite.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,34 +31,29 @@ function getAll(name) {
})
}

function setNum(name, num) {
return new Promise((resolve, reject) => {
db.exec(`INSERT INTO tb_count(\`name\`, \`num\`)
VALUES($name, $num)
ON CONFLICT(name) DO
UPDATE SET \`num\` = $num;`
,
{ $name: name, $num: num }
)

resolve()
})
async function setNum(name, num) {
const stmt = db.prepare(
`INSERT INTO tb_count(name, num)
VALUES(?, ?)
ON CONFLICT(name) DO
UPDATE SET num = excluded.num;`
);
stmt.run(name, num);
}

function setNumMulti(counters) {
return new Promise((resolve, reject) => {
const stmt = db.prepare(`INSERT INTO tb_count(\`name\`, \`num\`)
VALUES($name, $num)
ON CONFLICT(name) DO
UPDATE SET \`num\` = $num;`)

const setMany = db.transaction((counters) => {
for (const counter of counters) stmt.run(counter)
})
async function setNumMulti(counters) {
const stmt = db.prepare(
`INSERT INTO tb_count(name, num)
VALUES(?, ?)
ON CONFLICT(name) DO
UPDATE SET num = excluded.num;`
);

setMany(counters)
resolve()
})
db.transaction((counters) => {
counters.forEach((counter) => {
stmt.run(counter.name, counter.num);
});
})(counters);
}

module.exports = {
Expand Down
11 changes: 4 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,16 +145,13 @@ async function getCountByName(name, num) {
if (num > 0) { return { name, num } };

try {
if (!(name in __cache_counter)) {
const counter = (await db.getNum(name)) || defaultCount;
__cache_counter[name] = counter.num + 1;
} else {
__cache_counter[name]++;
}
// Try to first get counter for this name from cache, then from db, then use default value
const count = (__cache_counter[name] || (db.getNum(name) || defaultCount).num) + 1
__cache_counter[name] = count;

pushDB();

return { name, num: __cache_counter[name] };
return { name, num: count };
} catch (error) {
logger.error("get count by name is error: ", error);
return defaultCount;
Expand Down