Skip to content

Commit 3703ba8

Browse files
committed
fix: attempt to fix #15. race condition while creating the underlying table
1 parent 0454ccd commit 3703ba8

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

packages/verrou/src/drivers/knex.ts

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,23 @@ export class KnexAdapter implements DatabaseAdapter {
3232
}
3333

3434
async createTableIfNotExists() {
35-
const hasTable = await this.#connection.schema.hasTable(this.#tableName)
36-
if (hasTable) return
37-
38-
await this.#connection.schema.createTable(this.#tableName, (table) => {
39-
table.string('key', 255).notNullable().primary()
40-
table.string('owner').notNullable()
41-
table.bigint('expiration').unsigned().nullable()
42-
})
35+
try {
36+
await this.#connection.schema.createTable(this.#tableName, (table) => {
37+
table.string('key', 255).notNullable().primary()
38+
table.string('owner').notNullable()
39+
table.bigint('expiration').unsigned().nullable()
40+
})
41+
} catch {
42+
/**
43+
* If table creation fails, verify the table actually exists.
44+
* This handles weird race conditions where multiple instances try to create
45+
* the table simultaneously
46+
*
47+
* See https://github.com/Julien-R44/verrou/pull/15
48+
*/
49+
const hasTable = await this.#connection.schema.hasTable(this.#tableName)
50+
if (!hasTable) throw new Error(`Failed to create table "${this.#tableName}"`)
51+
}
4352
}
4453

4554
async insertLock(lock: { key: string; owner: string; expiration: number | null }) {

0 commit comments

Comments
 (0)