From d7890e1f258dcce0a55db968913ab595e96b02a5 Mon Sep 17 00:00:00 2001 From: Tim van Dam Date: Sat, 3 Dec 2022 16:11:00 +0100 Subject: [PATCH] fix(sqlite): fix off-by-one in max number of active connections (#392) --- packages/sqlite/src/sqlite-adapter.ts | 2 +- packages/sqlite/tests/sqlite.spec.ts | 30 ++++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/packages/sqlite/src/sqlite-adapter.ts b/packages/sqlite/src/sqlite-adapter.ts index c95fe3cc8..6c0c5ed9e 100644 --- a/packages/sqlite/src/sqlite-adapter.ts +++ b/packages/sqlite/src/sqlite-adapter.ts @@ -207,7 +207,7 @@ export class SQLiteConnectionPool extends SQLConnectionPool { } const connection = this.firstConnection && this.firstConnection.released ? this.firstConnection : - this.activeConnections > this.maxConnections + this.activeConnections >= this.maxConnections //we wait for the next query to be released and reuse it ? await asyncOperation((resolve) => { this.queue.push(resolve); diff --git a/packages/sqlite/tests/sqlite.spec.ts b/packages/sqlite/tests/sqlite.spec.ts index 7b94ba162..f8e838916 100644 --- a/packages/sqlite/tests/sqlite.spec.ts +++ b/packages/sqlite/tests/sqlite.spec.ts @@ -2,7 +2,7 @@ import { expect, test } from '@jest/globals'; import { SQLitePlatform } from '../src/sqlite-platform'; import { databaseFactory } from './factory'; import { User, UserCredentials } from '@deepkit/orm-integration'; -import { SQLiteDatabaseAdapter, SQLiteDatabaseTransaction } from '../src/sqlite-adapter'; +import { SQLiteConnection, SQLiteDatabaseAdapter, SQLiteDatabaseTransaction } from '../src/sqlite-adapter'; import { sleep } from '@deepkit/core'; import { AutoIncrement, cast, Entity, entity, PrimaryKey, Reference, ReflectionClass, serialize, typeOf, UUID, uuid } from '@deepkit/type'; import { Database, DatabaseEntityRegistry } from '@deepkit/orm'; @@ -229,6 +229,8 @@ test('connection pool', async () => { const c3 = await sqlite.connectionPool.getConnection(); expect(c3 === c1).toBe(true); + + c3.release(); } { @@ -265,6 +267,32 @@ test('connection pool', async () => { } }); +test(':memory: connection pool', async () => { + const sqlite = new SQLiteDatabaseAdapter(':memory:'); + + // create a connection, or return null if it takes longer than 100 ms + const createConnectionOrNull = () => Promise.race([ + sqlite.connectionPool.getConnection(), + sleep(0.1).then(() => null), + ]) + + { + const c1 = await sqlite.connectionPool.getConnection(); + const c2 = await createConnectionOrNull(); + const c3 = await createConnectionOrNull(); + + expect(sqlite.connectionPool.getActiveConnections()).toBeLessThanOrEqual(sqlite.connectionPool.maxConnections); + + expect(c1).toBeDefined(); + expect(c2).toBeNull(); + expect(c3).toBeNull(); + + c1.release(); + c2?.release(); + c3?.release(); + } +}); + test('optional', async () => { @entity.name('entity') class MyEntity {