|
| 1 | +import { beforeEach, describe, expect, test } from '@sqlite-js/driver-tests'; |
| 2 | +import { waSqliteSingleWorker, waSqliteWorkerPool } from '../../lib/index.js'; |
| 3 | + |
| 4 | +describe('concurrency tests', () => { |
| 5 | + let dbPath: string; |
| 6 | + |
| 7 | + const open = async () => { |
| 8 | + const db = await waSqliteWorkerPool(dbPath); |
| 9 | + return db; |
| 10 | + }; |
| 11 | + |
| 12 | + beforeEach((context) => { |
| 13 | + let testNameSanitized = context.fullName.replaceAll( |
| 14 | + /[\s\/\\>\.\-\:]+/g, |
| 15 | + '_' |
| 16 | + ); |
| 17 | + |
| 18 | + if (testNameSanitized.length > 10) { |
| 19 | + testNameSanitized = |
| 20 | + testNameSanitized.substring(testNameSanitized.length - 7) + |
| 21 | + String(Math.random()).substring(1, 4); |
| 22 | + } |
| 23 | + dbPath = `test-db/${testNameSanitized}.db`; |
| 24 | + }); |
| 25 | + |
| 26 | + test('concurrent select', async () => { |
| 27 | + await using driver = await open(); |
| 28 | + { |
| 29 | + await using connection = await driver.reserveConnection(); |
| 30 | + using s1 = connection.prepare( |
| 31 | + 'create table test_data(id integer primary key, data text)' |
| 32 | + ); |
| 33 | + await s1.step(); |
| 34 | + using s2 = connection.prepare( |
| 35 | + "insert into test_data(data) values('test')" |
| 36 | + ); |
| 37 | + await s2.step(); |
| 38 | + } |
| 39 | + |
| 40 | + let promises: Promise<void>[] = []; |
| 41 | + |
| 42 | + for (let i = 0; i < 5; i++) { |
| 43 | + const p = (async () => { |
| 44 | + const start = Date.now(); |
| 45 | + await using connection = await driver.reserveConnection(); |
| 46 | + |
| 47 | + using b = connection.prepare('begin immediate'); |
| 48 | + await b.step(); |
| 49 | + using s = connection.prepare('select * from test_data'); |
| 50 | + const { rows } = await s.step(); |
| 51 | + |
| 52 | + expect(rows).toEqual([{ id: 1, data: 'test' }]); |
| 53 | + await new Promise((resolve) => setTimeout(resolve, 500)); |
| 54 | + |
| 55 | + using e = connection.prepare('commit'); |
| 56 | + await e.step(); |
| 57 | + console.log('tx done in', Date.now() - start); |
| 58 | + })(); |
| 59 | + promises.push(p); |
| 60 | + } |
| 61 | + await Promise.all(promises); |
| 62 | + }); |
| 63 | +}); |
0 commit comments