Skip to content

Commit 0088e06

Browse files
committed
fix: sqlite bug do atomic reserve
1 parent 678fe09 commit 0088e06

1 file changed

Lines changed: 16 additions & 18 deletions

File tree

src/adapters/sqlite.ts

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,8 @@ export class SQLiteDatabaseAdapter implements DatabaseAdapter {
9595
`);
9696
recoverStmt.run(now);
9797

98-
// Atomically reserve a job using UPDATE with RETURNING (if supported) or UPDATE + SELECT
99-
// For SQLite, we'll use a subquery to atomically reserve the next available job
98+
// Atomically reserve a job using UPDATE with RETURNING
99+
// SQLite 3.35+ supports RETURNING clause
100100
const reserveStmt = this.db.prepare(`
101101
UPDATE jobs SET
102102
status = 'reserved',
@@ -109,28 +109,16 @@ export class SQLiteDatabaseAdapter implements DatabaseAdapter {
109109
ORDER BY priority DESC, push_time ASC
110110
LIMIT 1
111111
)
112+
RETURNING *
112113
`);
113114

114-
const result = reserveStmt.run(now, now + 300 * 1000, now); // Default 5 minute TTR for now
115+
const job = reserveStmt.get(now, now + 300 * 1000, now) as any;
115116

116-
// Check if we actually updated a row
117-
if (result.changes === 0) {
117+
// Check if we actually got a job
118+
if (!job) {
118119
return null;
119120
}
120121

121-
// Now get the job we just reserved
122-
const getJobStmt = this.db.prepare(`
123-
SELECT * FROM jobs
124-
WHERE status = 'reserved'
125-
AND reserve_time = ?
126-
ORDER BY reserve_time DESC
127-
LIMIT 1
128-
`);
129-
130-
const job = getJobStmt.get(now) as any;
131-
132-
if (!job) return null;
133-
134122
// Update with the correct TTR from the job
135123
const jobTtr = job.ttr || 300;
136124
const updateTtrStmt = this.db.prepare(`
@@ -222,6 +210,16 @@ export class SQLiteDatabaseAdapter implements DatabaseAdapter {
222210
stmt.run(Date.now(), parseInt(id));
223211
}
224212

213+
async clear(): Promise<void> {
214+
// Delete all jobs from the database and reset auto-increment
215+
const deleteStmt = this.db.prepare('DELETE FROM jobs');
216+
deleteStmt.run();
217+
218+
// Reset the auto-increment counter
219+
const resetStmt = this.db.prepare('DELETE FROM sqlite_sequence WHERE name = ?');
220+
resetStmt.run('jobs');
221+
}
222+
225223
close(): void {
226224
// Only close if the database has a close method (some implementations might not)
227225
if ('close' in this.db && typeof this.db.close === 'function') {

0 commit comments

Comments
 (0)