@elizaos/plugin-sql 1.0.0-beta.0 → 1.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,5 @@
1
- import {
2
- __name
3
- } from "./chunk-I3JSTNED.js";
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4
3
 
5
4
  // src/pglite/manager.ts
6
5
  import { dirname as pathDirname, resolve as pathResolve } from "node:path";
@@ -138,7 +137,8 @@ var PGliteClientManager = class {
138
137
  const __filename = fileURLToPath(import.meta.url);
139
138
  const __dirname = pathDirname(__filename);
140
139
  await migrate(db, {
141
- migrationsFolder: pathResolve(__dirname, "../drizzle/migrations")
140
+ migrationsFolder: pathResolve(__dirname, "../drizzle/migrations"),
141
+ migrationsSchema: "public"
142
142
  });
143
143
  } catch (error) {
144
144
  logger.error("Failed to run database migrations (pglite):", error);
@@ -147,10 +147,11 @@ var PGliteClientManager = class {
147
147
  };
148
148
 
149
149
  // src/pg/manager.ts
150
+ import path from "node:path";
151
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
150
152
  import { logger as logger2 } from "@elizaos/core";
151
153
  import { drizzle as drizzle2 } from "drizzle-orm/node-postgres";
152
- import { dirname as pathDirname2, resolve as pathResolve2 } from "node:path";
153
- import { fileURLToPath as fileURLToPath2 } from "node:url";
154
+ import { migrate as migrate2 } from "drizzle-orm/node-postgres/migrator";
154
155
  import pkg from "pg";
155
156
  var { Pool } = pkg;
156
157
  var PostgresConnectionManager = class {
@@ -164,7 +165,7 @@ var PostgresConnectionManager = class {
164
165
  * Constructor for creating a connection pool.
165
166
  * @param {string} connectionString - The connection string used to connect to the database.
166
167
  */
167
- constructor(db, connectionString) {
168
+ constructor(connectionString) {
168
169
  const defaultConfig = {
169
170
  max: 20,
170
171
  idleTimeoutMillis: 3e4,
@@ -179,6 +180,7 @@ var PostgresConnectionManager = class {
179
180
  this.handlePoolError(err);
180
181
  });
181
182
  this.setupPoolErrorHandling();
183
+ this.testConnection();
182
184
  }
183
185
  /**
184
186
  * Handles a pool error by attempting to reconnect the pool.
@@ -278,6 +280,8 @@ var PostgresConnectionManager = class {
278
280
  */
279
281
  async initialize() {
280
282
  try {
283
+ await this.testConnection();
284
+ logger2.debug("PostgreSQL connection manager initialized successfully");
281
285
  } catch (error) {
282
286
  logger2.error("Failed to initialize connection manager:", error);
283
287
  throw error;
@@ -303,37 +307,32 @@ var PostgresConnectionManager = class {
303
307
  }
304
308
  }
305
309
  /**
306
- * Asynchronously runs database migrations using the Drizzle library and ensures
307
- * the database schema is always up to date with the current schema definition.
310
+ * Asynchronously runs database migrations using the Drizzle library.
308
311
  *
309
- * First applies existing migrations, then uses drizzle-kit push to ensure
310
- * the database schema matches the current schema definition.
312
+ * Drizzle will first check if the migrations are already applied.
313
+ * If there is a diff between database schema and migrations, it will apply the migrations.
314
+ * If they are already applied, it will skip them.
311
315
  *
312
- * @returns {Promise<void>} A Promise that resolves once the schema updates are completed successfully.
316
+ * @returns {Promise<void>} A Promise that resolves once the migrations are completed successfully.
313
317
  */
314
318
  async runMigrations() {
315
- const { existsSync } = await import("fs");
316
- const db = drizzle2(this.pool);
317
- const packagePath = (await import.meta.resolve("@elizaos/plugin-sql")).replace("file://", "");
318
- const packageMigrationsPath = pathResolve2(pathDirname2(packagePath), "../drizzle/migrations");
319
- console.log("packageMigrationsPath", packageMigrationsPath);
320
- const __filename = fileURLToPath2(import.meta.url);
321
- const __dirname = pathDirname2(__filename);
322
- const appMigrationPath = pathResolve2(__dirname, "../drizzle/migrations");
323
- console.log("appMigrationPath", appMigrationPath);
324
- const migrationsFolder = existsSync(packageMigrationsPath) ? packageMigrationsPath : appMigrationPath;
325
- console.log("migrationsFolder", migrationsFolder);
326
- const { execa } = await import("./execa-I2XBH3EI.js");
327
- await execa("npx", ["drizzle-kit", "push"], {
328
- cwd: migrationsFolder
329
- });
330
- console.log("migrated");
331
- await new Promise((resolve) => setTimeout(resolve, 2e3));
319
+ try {
320
+ const db = drizzle2(this.pool);
321
+ const __filename = fileURLToPath2(import.meta.url);
322
+ const __dirname = path.dirname(__filename);
323
+ await migrate2(db, {
324
+ migrationsFolder: path.resolve(__dirname, "../drizzle/migrations"),
325
+ migrationsSchema: "public"
326
+ });
327
+ } catch (error) {
328
+ logger2.error("Failed to run database migrations (pg):", error);
329
+ }
332
330
  }
333
331
  };
334
332
 
335
333
  export {
334
+ __name,
336
335
  PGliteClientManager,
337
336
  PostgresConnectionManager
338
337
  };
339
- //# sourceMappingURL=chunk-PSEXCDLP.js.map
338
+ //# sourceMappingURL=chunk-ROCRMD5N.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/pglite/manager.ts","../src/pg/manager.ts"],"sourceRoot":"./","sourcesContent":["import { dirname as pathDirname, resolve as pathResolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { PGlite, type PGliteOptions } from '@electric-sql/pglite';\nimport { fuzzystrmatch } from '@electric-sql/pglite/contrib/fuzzystrmatch';\nimport { vector } from '@electric-sql/pglite/vector';\nimport { logger } from '@elizaos/core';\nimport { drizzle } from 'drizzle-orm/pglite';\nimport { migrate } from 'drizzle-orm/pglite/migrator';\nimport type { IDatabaseClientManager } from '../types';\n\n/**\n * Class representing a database client manager for PGlite.\n * @implements { IDatabaseClientManager }\n */\nexport class PGliteClientManager implements IDatabaseClientManager<PGlite> {\n private client: PGlite;\n private shuttingDown = false;\n private readonly shutdownTimeout = 500;\n\n /**\n * Constructor for creating a new instance of PGlite with the provided options.\n * Initializes the PGlite client with additional extensions.\n * @param {PGliteOptions} options - The options to configure the PGlite client.\n */\n constructor(options: PGliteOptions) {\n this.client = new PGlite({\n ...options,\n extensions: {\n vector,\n fuzzystrmatch,\n },\n });\n this.setupShutdownHandlers();\n }\n\n /**\n * Retrieves the PostgreSQL lite connection.\n *\n * @returns {PGlite} The PostgreSQL lite connection.\n * @throws {Error} If the client manager is currently shutting down.\n */\n public getConnection(): PGlite {\n if (this.shuttingDown) {\n throw new Error('Client manager is shutting down');\n }\n return this.client;\n }\n\n /**\n * Initiates a graceful shutdown of the PGlite client.\n * Checks if the client is already in the process of shutting down.\n * Logs the start of shutdown process and sets shuttingDown flag to true.\n * Sets a timeout for the shutdown process and forces closure of database connection if timeout is reached.\n * Handles the shutdown process, closes the client connection, clears the timeout, and logs the completion of shutdown.\n * Logs any errors that occur during the shutdown process.\n */\n private async gracefulShutdown() {\n if (this.shuttingDown) {\n return;\n }\n\n this.shuttingDown = true;\n logger.info('Starting graceful shutdown of PGlite client...');\n\n const timeout = setTimeout(() => {\n logger.warn('Shutdown timeout reached, forcing database connection closure...');\n this.client.close().finally(() => {\n process.exit(1);\n });\n }, this.shutdownTimeout);\n\n try {\n await this.client.close();\n clearTimeout(timeout);\n logger.info('PGlite client shutdown completed successfully');\n process.exit(0);\n } catch (error) {\n logger.error('Error during graceful shutdown:', error);\n process.exit(1);\n }\n }\n\n /**\n * Sets up shutdown handlers for SIGINT, SIGTERM, and beforeExit events to gracefully shutdown the application.\n * @private\n */\n private setupShutdownHandlers() {\n process.on('SIGINT', async () => {\n await this.gracefulShutdown();\n });\n\n process.on('SIGTERM', async () => {\n await this.gracefulShutdown();\n });\n\n process.on('beforeExit', async () => {\n await this.gracefulShutdown();\n });\n }\n\n /**\n * Initializes the client for PGlite.\n *\n * @returns {Promise<void>} A Promise that resolves when the client is initialized successfully\n */\n public async initialize(): Promise<void> {\n try {\n await this.client.waitReady;\n logger.info('PGlite client initialized successfully');\n } catch (error) {\n logger.error('Failed to initialize PGlite client:', error);\n throw error;\n }\n }\n\n /**\n * Asynchronously closes the resource. If the resource is not already shutting down,\n * it performs a graceful shutdown before closing.\n *\n * @returns A promise that resolves once the resource has been closed.\n */\n public async close(): Promise<void> {\n if (!this.shuttingDown) {\n await this.gracefulShutdown();\n }\n }\n\n /**\n * Check if the system is currently shutting down.\n *\n * @returns {boolean} True if the system is shutting down, false otherwise.\n */\n public isShuttingDown(): boolean {\n return this.shuttingDown;\n }\n\n /**\n * Asynchronously runs database migrations using Drizzle.\n *\n * Drizzle will first check if the migrations are already applied.\n * If there is a diff between database schema and migrations, it will apply the migrations.\n * If they are already applied, it will skip them.\n *\n * @returns {Promise<void>} A Promise that resolves once the migrations are completed successfully.\n */\n async runMigrations(): Promise<void> {\n try {\n const db = drizzle(this.client);\n\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = pathDirname(__filename);\n\n await migrate(db, {\n migrationsFolder: pathResolve(__dirname, '../drizzle/migrations'),\n migrationsSchema: 'public',\n });\n } catch (error) {\n logger.error('Failed to run database migrations (pglite):', error);\n }\n }\n}\n","import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { logger } from '@elizaos/core';\nimport { drizzle } from 'drizzle-orm/node-postgres';\nimport { migrate } from 'drizzle-orm/node-postgres/migrator';\nimport pkg, { type Pool as PgPool } from 'pg';\nimport type { IDatabaseClientManager } from '../types';\n\nconst { Pool } = pkg;\n\n/**\n * Manages connections to a PostgreSQL database using a connection pool.\n * Implements IDatabaseClientManager interface.\n */\n\nexport class PostgresConnectionManager implements IDatabaseClientManager<PgPool> {\n private pool: PgPool;\n private isShuttingDown = false;\n private readonly connectionTimeout: number = 5000;\n\n /**\n * Constructor for creating a connection pool.\n * @param {string} connectionString - The connection string used to connect to the database.\n */\n constructor(connectionString: string) {\n const defaultConfig = {\n max: 20,\n idleTimeoutMillis: 30000,\n connectionTimeoutMillis: this.connectionTimeout,\n };\n\n this.pool = new Pool({\n ...defaultConfig,\n connectionString,\n });\n\n this.pool.on('error', (err) => {\n logger.error('Unexpected pool error', err);\n this.handlePoolError(err);\n });\n\n this.setupPoolErrorHandling();\n this.testConnection();\n }\n\n /**\n * Handles a pool error by attempting to reconnect the pool.\n *\n * @param {Error} error The error that occurred in the pool.\n * @throws {Error} If failed to reconnect the pool.\n */\n private async handlePoolError(error: Error) {\n logger.error('Pool error occurred, attempting to reconnect', {\n error: error.message,\n });\n\n try {\n await this.pool.end();\n\n this.pool = new Pool({\n ...this.pool.options,\n connectionTimeoutMillis: this.connectionTimeout,\n });\n\n await this.testConnection();\n logger.success('Pool reconnection successful');\n } catch (reconnectError) {\n logger.error('Failed to reconnect pool', {\n error: reconnectError instanceof Error ? reconnectError.message : String(reconnectError),\n });\n throw reconnectError;\n }\n }\n\n /**\n * Asynchronously tests the database connection by executing a query to get the current timestamp.\n *\n * @returns {Promise<boolean>} - A Promise that resolves to true if the database connection test is successful.\n */\n async testConnection(): Promise<boolean> {\n let client: pkg.PoolClient | null = null;\n try {\n client = await this.pool.connect();\n const result = await client.query('SELECT NOW()');\n logger.success('Database connection test successful:', result.rows[0]);\n return true;\n } catch (error) {\n logger.error('Database connection test failed:', error);\n throw new Error(`Failed to connect to database: ${(error as Error).message}`);\n } finally {\n if (client) client.release();\n }\n }\n\n /**\n * Sets up event listeners to handle pool cleanup on SIGINT, SIGTERM, and beforeExit events.\n */\n private setupPoolErrorHandling() {\n process.on('SIGINT', async () => {\n await this.cleanup();\n process.exit(0);\n });\n\n process.on('SIGTERM', async () => {\n await this.cleanup();\n process.exit(0);\n });\n\n process.on('beforeExit', async () => {\n await this.cleanup();\n });\n }\n\n /**\n * Get the connection pool.\n * @returns {PgPool} The connection pool\n * @throws {Error} If the connection manager is shutting down or an error occurs when trying to get the connection from the pool\n */\n public getConnection(): PgPool {\n if (this.isShuttingDown) {\n throw new Error('Connection manager is shutting down');\n }\n\n try {\n return this.pool;\n } catch (error) {\n logger.error('Failed to get connection from pool:', error);\n throw error;\n }\n }\n\n /**\n * Asynchronously acquires a database client from the connection pool.\n *\n * @returns {Promise<pkg.PoolClient>} A Promise that resolves with the acquired database client.\n * @throws {Error} If an error occurs while acquiring the database client.\n */\n public async getClient(): Promise<pkg.PoolClient> {\n try {\n return await this.pool.connect();\n } catch (error) {\n logger.error('Failed to acquire a database client:', error);\n throw error;\n }\n }\n\n /**\n * Initializes the PostgreSQL connection manager by testing the connection and logging the result.\n *\n * @returns {Promise<void>} A Promise that resolves once the manager is successfully initialized\n * @throws {Error} If there is an error initializing the connection manager\n */\n public async initialize(): Promise<void> {\n try {\n await this.testConnection();\n logger.debug('PostgreSQL connection manager initialized successfully');\n } catch (error) {\n logger.error('Failed to initialize connection manager:', error);\n throw error;\n }\n }\n\n /**\n * Asynchronously close the current process by executing a cleanup function.\n * @returns A promise that resolves once the cleanup is complete.\n */\n public async close(): Promise<void> {\n await this.cleanup();\n }\n\n /**\n * Cleans up and closes the database pool.\n * @returns {Promise<void>} A Promise that resolves when the database pool is closed.\n */\n async cleanup(): Promise<void> {\n try {\n await this.pool.end();\n logger.info('Database pool closed');\n } catch (error) {\n logger.error('Error closing database pool:', error);\n }\n }\n\n /**\n * Asynchronously runs database migrations using the Drizzle library.\n *\n * Drizzle will first check if the migrations are already applied.\n * If there is a diff between database schema and migrations, it will apply the migrations.\n * If they are already applied, it will skip them.\n *\n * @returns {Promise<void>} A Promise that resolves once the migrations are completed successfully.\n */\n async runMigrations(): Promise<void> {\n try {\n const db = drizzle(this.pool);\n\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n\n await migrate(db, {\n migrationsFolder: path.resolve(__dirname, '../drizzle/migrations'),\n migrationsSchema: 'public',\n });\n } catch (error) {\n logger.error('Failed to run database migrations (pg):', error);\n }\n }\n}\n"],"mappings":";;;;AAAA,SAAS,WAAW,aAAa,WAAW,mBAAmB;AAC/D,SAAS,qBAAqB;AAC9B,SAAS,cAAkC;AAC3C,SAAS,qBAAqB;AAC9B,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,eAAe;AACxB,SAAS,eAAe;AAOjB,IAAM,sBAAN,MAAoE;AAAA,EAd3E,OAc2E;AAAA;AAAA;AAAA,EACjE;AAAA,EACA,eAAe;AAAA,EACN,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnC,YAAY,SAAwB;AAClC,SAAK,SAAS,IAAI,OAAO;AAAA,MACvB,GAAG;AAAA,MACH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;AACF,YAAM,KAAKC,SAAQ,KAAK,IAAI;AAE5B,YAAM,aAAaC,eAAc,YAAY,GAAG;AAChD,YAAM,YAAY,KAAK,QAAQ,UAAU;AAEzC,YAAMC,SAAQ,IAAI;AAAA,QAChB,kBAAkB,KAAK,QAAQ,WAAW,uBAAuB;AAAA,QACjE,kBAAkB;AAAA,MACpB,CAAC;AAAA,IACH,SAAS,OAAO;AACd,MAAAH,QAAO,MAAM,2CAA2C,KAAK;AAAA,IAC/D;AAAA,EACF;AACF;","names":["fileURLToPath","logger","drizzle","migrate","logger","drizzle","fileURLToPath","migrate"]}
package/dist/index.js CHANGED
@@ -1,10 +1,8 @@
1
1
  import {
2
2
  PGliteClientManager,
3
- PostgresConnectionManager
4
- } from "./chunk-PSEXCDLP.js";
5
- import {
3
+ PostgresConnectionManager,
6
4
  __name
7
- } from "./chunk-I3JSTNED.js";
5
+ } from "./chunk-ROCRMD5N.js";
8
6
 
9
7
  // src/index.ts
10
8
  import * as os from "node:os";
@@ -1446,7 +1444,16 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1446
1444
  * @param {Room} room - The room object to create.
1447
1445
  * @returns {Promise<UUID>} A Promise that resolves to the ID of the created room.
1448
1446
  */
1449
- async createRoom({ id, name, source, type, channelId, serverId, worldId }) {
1447
+ async createRoom({
1448
+ id,
1449
+ name,
1450
+ source,
1451
+ type,
1452
+ channelId,
1453
+ serverId,
1454
+ worldId,
1455
+ metadata
1456
+ }) {
1450
1457
  return this.withDatabase(async () => {
1451
1458
  const newRoomId = id || v4();
1452
1459
  await this.db.insert(roomTable).values({
@@ -1457,7 +1464,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1457
1464
  type,
1458
1465
  channelId,
1459
1466
  serverId,
1460
- worldId
1467
+ worldId,
1468
+ metadata
1461
1469
  }).onConflictDoNothing({ target: roomTable.id });
1462
1470
  return newRoomId;
1463
1471
  });
@@ -1585,9 +1593,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1585
1593
  */
1586
1594
  async getParticipantsForRoom(roomId) {
1587
1595
  return this.withDatabase(async () => {
1588
- const result = await this.db.select({ entityId: participantTable.entityId }).from(participantTable).where(
1589
- and(eq(participantTable.roomId, roomId), eq(participantTable.agentId, this.agentId))
1590
- );
1596
+ const result = await this.db.select({ entityId: participantTable.entityId }).from(participantTable).where(eq(participantTable.roomId, roomId));
1591
1597
  return result.map((row) => row.entityId);
1592
1598
  });
1593
1599
  }
@@ -2053,6 +2059,66 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
2053
2059
  });
2054
2060
  });
2055
2061
  }
2062
+ /**
2063
+ * Asynchronously retrieves group chat memories from all rooms under a given server.
2064
+ * It fetches all room IDs associated with the `serverId`, then retrieves memories
2065
+ * from those rooms in descending order (latest to oldest), with an optional count limit.
2066
+ *
2067
+ * @param {Object} params - Parameters for fetching memories.
2068
+ * @param {UUID} params.serverId - The server ID to fetch memories for.
2069
+ * @param {number} [params.count] - The maximum number of memories to retrieve.
2070
+ * @returns {Promise<Memory[]>} - A promise that resolves to an array of memory objects.
2071
+ */
2072
+ async getMemoriesByServerId(params) {
2073
+ return this.withDatabase(async () => {
2074
+ const roomIdsResult = await this.db.select({ roomId: roomTable.id }).from(roomTable).where(eq(roomTable.serverId, params.serverId));
2075
+ if (roomIdsResult.length === 0) return [];
2076
+ const roomIds = roomIdsResult.map((row) => row.roomId);
2077
+ const query = this.db.select({
2078
+ memory: memoryTable,
2079
+ embedding: embeddingTable[this.embeddingDimension]
2080
+ }).from(memoryTable).leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id)).where(inArray(memoryTable.roomId, roomIds)).orderBy(desc(memoryTable.createdAt));
2081
+ const rows = params.count ? await query.limit(params.count) : await query;
2082
+ return rows.map((row) => ({
2083
+ id: row.memory.id,
2084
+ type: row.memory.type,
2085
+ createdAt: row.memory.createdAt,
2086
+ content: typeof row.memory.content === "string" ? JSON.parse(row.memory.content) : row.memory.content,
2087
+ entityId: row.memory.entityId,
2088
+ agentId: row.memory.agentId,
2089
+ roomId: row.memory.roomId,
2090
+ unique: row.memory.unique,
2091
+ embedding: row.embedding ?? void 0
2092
+ }));
2093
+ });
2094
+ }
2095
+ /**
2096
+ * Asynchronously deletes all rooms associated with a specific serverId.
2097
+ * @param {UUID} serverId - The server ID to delete rooms for.
2098
+ * @returns {Promise<void>} A Promise that resolves when the rooms are deleted.
2099
+ */
2100
+ async deleteRoomsByServerId(serverId) {
2101
+ return this.withDatabase(async () => {
2102
+ await this.db.transaction(async (tx) => {
2103
+ const roomIdsResult = await tx.select({ roomId: roomTable.id }).from(roomTable).where(eq(roomTable.serverId, serverId));
2104
+ if (roomIdsResult.length === 0) return;
2105
+ const roomIds = roomIdsResult.map((row) => row.roomId);
2106
+ await tx.delete(embeddingTable).where(
2107
+ inArray(
2108
+ embeddingTable.memoryId,
2109
+ tx.select({ id: memoryTable.id }).from(memoryTable).where(inArray(memoryTable.roomId, roomIds))
2110
+ )
2111
+ );
2112
+ await tx.delete(memoryTable).where(inArray(memoryTable.roomId, roomIds));
2113
+ await tx.delete(participantTable).where(inArray(participantTable.roomId, roomIds));
2114
+ await tx.delete(logTable).where(inArray(logTable.roomId, roomIds));
2115
+ await tx.delete(roomTable).where(inArray(roomTable.id, roomIds));
2116
+ });
2117
+ logger.debug("Rooms and related logs deleted successfully for server:", {
2118
+ serverId
2119
+ });
2120
+ });
2121
+ }
2056
2122
  };
2057
2123
 
2058
2124
  // src/pglite/adapter.ts
@@ -2170,7 +2236,6 @@ var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
2170
2236
  };
2171
2237
 
2172
2238
  // src/index.ts
2173
- import { Pool } from "pg";
2174
2239
  var GLOBAL_SINGLETONS = Symbol.for("@elizaos/plugin-sql/global-singletons");
2175
2240
  var globalSymbols = global;
2176
2241
  if (!globalSymbols[GLOBAL_SINGLETONS]) {
@@ -2189,10 +2254,8 @@ function createDatabaseAdapter(config, agentId) {
2189
2254
  config.dataDir = expandTildePath(config.dataDir);
2190
2255
  }
2191
2256
  if (config.postgresUrl) {
2192
- const pool = new Pool({ connectionString: config.postgresUrl });
2193
2257
  if (!globalSingletons.postgresConnectionManager) {
2194
2258
  globalSingletons.postgresConnectionManager = new PostgresConnectionManager(
2195
- pool,
2196
2259
  config.postgresUrl
2197
2260
  );
2198
2261
  }