@elizaos/plugin-sql 1.0.0-alpha.1 → 1.0.0-alpha.16

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.
package/dist/index.js CHANGED
@@ -1,6 +1,12 @@
1
+ import {
2
+ PGliteClientManager,
3
+ PostgresConnectionManager,
4
+ __name
5
+ } from "./chunk-LLEN3JTK.js";
6
+
1
7
  // src/index.ts
2
8
  import {
3
- logger as logger6
9
+ logger as logger4
4
10
  } from "@elizaos/core";
5
11
 
6
12
  // src/pg-lite/adapter.ts
@@ -27,15 +33,39 @@ import {
27
33
  import { v4 } from "uuid";
28
34
 
29
35
  // src/schema/embedding.ts
36
+ import { sql as sql6 } from "drizzle-orm";
30
37
  import {
38
+ check as check2,
39
+ foreignKey as foreignKey2,
40
+ index as index2,
31
41
  pgTable as pgTable6,
32
42
  uuid as uuid6,
33
- vector as vector2,
34
- index as index2,
35
- foreignKey as foreignKey2,
36
- check as check2
43
+ vector as vector2
44
+ } from "drizzle-orm/pg-core";
45
+
46
+ // src/schema/memory.ts
47
+ import { relations, sql as sql5 } from "drizzle-orm";
48
+ import {
49
+ boolean as boolean2,
50
+ check,
51
+ foreignKey,
52
+ index,
53
+ jsonb as jsonb5,
54
+ pgTable as pgTable5,
55
+ text as text5,
56
+ uuid as uuid5
57
+ } from "drizzle-orm/pg-core";
58
+
59
+ // src/schema/agent.ts
60
+ import { sql } from "drizzle-orm";
61
+ import {
62
+ boolean,
63
+ jsonb,
64
+ pgTable,
65
+ text,
66
+ unique,
67
+ uuid
37
68
  } from "drizzle-orm/pg-core";
38
- import { sql as sql6 } from "drizzle-orm";
39
69
 
40
70
  // src/schema/types.ts
41
71
  import { customType } from "drizzle-orm/pg-core";
@@ -64,33 +94,7 @@ var numberTimestamp = customType(
64
94
  }
65
95
  );
66
96
 
67
- // src/schema/memory.ts
68
- import {
69
- pgTable as pgTable5,
70
- uuid as uuid5,
71
- text as text5,
72
- jsonb as jsonb5,
73
- index,
74
- boolean as boolean2,
75
- foreignKey,
76
- check
77
- } from "drizzle-orm/pg-core";
78
- import { relations, sql as sql5 } from "drizzle-orm";
79
-
80
- // src/schema/entity.ts
81
- import { sql as sql2 } from "drizzle-orm";
82
- import { jsonb as jsonb2, pgTable as pgTable2, text as text2, unique as unique2, uuid as uuid2 } from "drizzle-orm/pg-core";
83
-
84
97
  // src/schema/agent.ts
85
- import {
86
- boolean,
87
- jsonb,
88
- pgTable,
89
- text,
90
- uuid,
91
- unique
92
- } from "drizzle-orm/pg-core";
93
- import { sql } from "drizzle-orm";
94
98
  var agentTable = pgTable(
95
99
  "agents",
96
100
  {
@@ -120,6 +124,8 @@ var agentTable = pgTable(
120
124
  );
121
125
 
122
126
  // src/schema/entity.ts
127
+ import { sql as sql2 } from "drizzle-orm";
128
+ import { jsonb as jsonb2, pgTable as pgTable2, text as text2, unique as unique2, uuid as uuid2 } from "drizzle-orm/pg-core";
123
129
  var entityTable = pgTable2(
124
130
  "entities",
125
131
  {
@@ -143,8 +149,8 @@ import { sql as sql4 } from "drizzle-orm";
143
149
  import { jsonb as jsonb4, pgTable as pgTable4, text as text4, uuid as uuid4 } from "drizzle-orm/pg-core";
144
150
 
145
151
  // src/schema/worldTable.ts
146
- import { jsonb as jsonb3, pgTable as pgTable3, text as text3, uuid as uuid3 } from "drizzle-orm/pg-core";
147
152
  import { sql as sql3 } from "drizzle-orm";
153
+ import { jsonb as jsonb3, pgTable as pgTable3, text as text3, uuid as uuid3 } from "drizzle-orm/pg-core";
148
154
  var worldTable = pgTable3("worlds", {
149
155
  id: uuid3("id").notNull().primaryKey().default(sql3`gen_random_uuid()`),
150
156
  agentId: uuid3("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
@@ -300,8 +306,8 @@ var cacheTable = pgTable7(
300
306
  );
301
307
 
302
308
  // src/schema/component.ts
303
- import { pgTable as pgTable8, uuid as uuid8, jsonb as jsonb7, text as text7 } from "drizzle-orm/pg-core";
304
309
  import { sql as sql8 } from "drizzle-orm";
310
+ import { jsonb as jsonb7, pgTable as pgTable8, text as text7, uuid as uuid8 } from "drizzle-orm/pg-core";
305
311
  var componentTable = pgTable8("components", {
306
312
  id: uuid8("id").primaryKey().defaultRandom(),
307
313
  entityId: uuid8("entityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
@@ -319,8 +325,8 @@ var componentTable = pgTable8("components", {
319
325
  });
320
326
 
321
327
  // src/schema/goal.ts
322
- import { pgTable as pgTable9, uuid as uuid9, text as text8, jsonb as jsonb8, foreignKey as foreignKey3 } from "drizzle-orm/pg-core";
323
328
  import { sql as sql9 } from "drizzle-orm";
329
+ import { foreignKey as foreignKey3, jsonb as jsonb8, pgTable as pgTable9, text as text8, uuid as uuid9 } from "drizzle-orm/pg-core";
324
330
  var goalTable = pgTable9(
325
331
  "goals",
326
332
  {
@@ -355,8 +361,8 @@ var goalTable = pgTable9(
355
361
  );
356
362
 
357
363
  // src/schema/log.ts
358
- import { pgTable as pgTable10, uuid as uuid10, text as text9, jsonb as jsonb9, foreignKey as foreignKey4 } from "drizzle-orm/pg-core";
359
364
  import { sql as sql10 } from "drizzle-orm";
365
+ import { foreignKey as foreignKey4, jsonb as jsonb9, pgTable as pgTable10, text as text9, uuid as uuid10 } from "drizzle-orm/pg-core";
360
366
  var logTable = pgTable10(
361
367
  "logs",
362
368
  {
@@ -382,14 +388,14 @@ var logTable = pgTable10(
382
388
  );
383
389
 
384
390
  // src/schema/participant.ts
391
+ import { sql as sql11 } from "drizzle-orm";
385
392
  import {
393
+ foreignKey as foreignKey5,
394
+ index as index3,
386
395
  pgTable as pgTable11,
387
- uuid as uuid11,
388
396
  text as text10,
389
- index as index3,
390
- foreignKey as foreignKey5
397
+ uuid as uuid11
391
398
  } from "drizzle-orm/pg-core";
392
- import { sql as sql11 } from "drizzle-orm";
393
399
  var participantTable = pgTable11(
394
400
  "participants",
395
401
  {
@@ -485,16 +491,30 @@ var taskTable = pgTable13("tasks", {
485
491
 
486
492
  // src/base.ts
487
493
  var BaseDrizzleAdapter = class extends DatabaseAdapter {
494
+ static {
495
+ __name(this, "BaseDrizzleAdapter");
496
+ }
488
497
  maxRetries = 3;
489
498
  baseDelay = 1e3;
490
499
  maxDelay = 1e4;
491
500
  jitterMax = 1e3;
492
501
  embeddingDimension = DIMENSION_MAP[384];
493
502
  agentId;
503
+ /**
504
+ * Constructor for creating a new instance of Agent with the specified agentId.
505
+ *
506
+ * @param {UUID} agentId - The unique identifier for the agent.
507
+ */
494
508
  constructor(agentId) {
495
509
  super();
496
510
  this.agentId = agentId;
497
511
  }
512
+ /**
513
+ * Executes the given operation with retry logic.
514
+ * @template T
515
+ * @param {() => Promise<T>} operation - The operation to be executed.
516
+ * @returns {Promise<T>} A promise that resolves with the result of the operation.
517
+ */
498
518
  async withRetry(operation) {
499
519
  let lastError = new Error("Unknown error");
500
520
  for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
@@ -516,7 +536,6 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
516
536
  nextRetryIn: `${(delay / 1e3).toFixed(1)}s`
517
537
  }
518
538
  );
519
- console.trace("****** Database operation failure source");
520
539
  await new Promise((resolve) => setTimeout(resolve, delay));
521
540
  } else {
522
541
  logger.error("Max retry attempts reached:", {
@@ -529,6 +548,14 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
529
548
  }
530
549
  throw lastError;
531
550
  }
551
+ /**
552
+ * Ensure that an agent exists by checking if an agent with the same name already exists in the system.
553
+ * If the agent does not exist, it will be created with the provided data.
554
+ *
555
+ * @param {Partial<Agent>} agent - The partial data of the agent to ensure its existence.
556
+ * @returns {Promise<void>} - A promise that resolves when the agent is successfully ensured.
557
+ * @throws {Error} - If the agent name is not provided or if there is an issue creating the agent.
558
+ */
532
559
  async ensureAgentExists(agent) {
533
560
  if (!agent.name) {
534
561
  throw new Error("Agent name is required");
@@ -541,6 +568,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
541
568
  await this.createAgent(agent);
542
569
  }
543
570
  }
571
+ /**
572
+ * Ensure that the given embedding dimension is valid for the agent.
573
+ *
574
+ * @param {number} dimension - The dimension to ensure for the embedding.
575
+ * @returns {Promise<void>} - Resolves once the embedding dimension is ensured.
576
+ */
544
577
  async ensureEmbeddingDimension(dimension) {
545
578
  const existingMemory = await this.db.select({
546
579
  embedding: embeddingTable
@@ -555,6 +588,11 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
555
588
  }
556
589
  this.embeddingDimension = DIMENSION_MAP[dimension];
557
590
  }
591
+ /**
592
+ * Asynchronously retrieves an agent by their ID from the database.
593
+ * @param {UUID} agentId - The ID of the agent to retrieve.
594
+ * @returns {Promise<Agent | null>} A promise that resolves to the retrieved agent or null if not found.
595
+ */
558
596
  async getAgent(agentId) {
559
597
  return this.withDatabase(async () => {
560
598
  const result = await this.db.select().from(agentTable).where(eq(agentTable.id, agentId)).limit(1);
@@ -562,12 +600,23 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
562
600
  return result[0];
563
601
  });
564
602
  }
603
+ /**
604
+ * Asynchronously retrieves a list of agents from the database.
605
+ *
606
+ * @returns {Promise<Agent[]>} A Promise that resolves to an array of Agent objects.
607
+ */
565
608
  async getAgents() {
566
609
  return this.withDatabase(async () => {
567
610
  const result = await this.db.select().from(agentTable);
568
611
  return result;
569
612
  });
570
613
  }
614
+ /**
615
+ * Asynchronously creates a new agent record in the database.
616
+ *
617
+ * @param {Partial<Agent>} agent The agent object to be created.
618
+ * @returns {Promise<boolean>} A promise that resolves to a boolean indicating the success of the operation.
619
+ */
571
620
  async createAgent(agent) {
572
621
  return this.withDatabase(async () => {
573
622
  try {
@@ -590,6 +639,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
590
639
  }
591
640
  });
592
641
  }
642
+ /**
643
+ * Updates an agent in the database with the provided agent ID and data.
644
+ * @param {UUID} agentId - The unique identifier of the agent to update.
645
+ * @param {Partial<Agent>} agent - The partial agent object containing the fields to update.
646
+ * @returns {Promise<boolean>} - A boolean indicating if the agent was successfully updated.
647
+ */
593
648
  async updateAgent(agentId, agent) {
594
649
  return this.withDatabase(async () => {
595
650
  try {
@@ -616,6 +671,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
616
671
  }
617
672
  });
618
673
  }
674
+ /**
675
+ * Asynchronously deletes an agent with the specified UUID and all related entries.
676
+ *
677
+ * @param {UUID} agentId - The UUID of the agent to be deleted.
678
+ * @returns {Promise<boolean>} - A boolean indicating if the deletion was successful.
679
+ */
619
680
  async deleteAgent(agentId) {
620
681
  return this.withDatabase(async () => {
621
682
  await this.db.transaction(async (tx) => {
@@ -628,6 +689,10 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
628
689
  * Count all agents in the database
629
690
  * Used primarily for maintenance and cleanup operations
630
691
  */
692
+ /**
693
+ * Asynchronously counts the number of agents in the database.
694
+ * @returns {Promise<number>} A Promise that resolves to the number of agents in the database.
695
+ */
631
696
  async countAgents() {
632
697
  return this.withDatabase(async () => {
633
698
  try {
@@ -730,11 +795,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
730
795
  return true;
731
796
  });
732
797
  } catch (error) {
733
- logger.error("Error creating account:", {
798
+ logger.error("Error creating entity:", {
734
799
  error: error instanceof Error ? error.message : String(error),
735
800
  entityId: entity.id,
736
801
  name: entity.metadata?.name
737
802
  });
803
+ console.trace(error);
738
804
  return false;
739
805
  }
740
806
  });
@@ -1566,7 +1632,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1566
1632
  if (params.tags && params.tags.length > 0) {
1567
1633
  const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ");
1568
1634
  query = query.where(
1569
- sql13`${relationshipTable.tags} @> ARRAY[${sql13.raw(tagParams)}]::text[]`
1635
+ sql13`${relationshipTable.tags} @> ARRAY[${sql13.raw(
1636
+ tagParams
1637
+ )}]::text[]`
1570
1638
  );
1571
1639
  }
1572
1640
  const results = await query;
@@ -1847,13 +1915,28 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1847
1915
 
1848
1916
  // src/pg-lite/adapter.ts
1849
1917
  var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
1918
+ static {
1919
+ __name(this, "PgliteDatabaseAdapter");
1920
+ }
1850
1921
  manager;
1851
1922
  embeddingDimension = DIMENSION_MAP[384];
1923
+ /**
1924
+ * Constructor for creating an instance of a class.
1925
+ * @param {UUID} agentId - The unique identifier for the agent.
1926
+ * @param {PGliteClientManager} manager - The manager for the PGlite client.
1927
+ */
1852
1928
  constructor(agentId, manager) {
1853
1929
  super(agentId);
1854
1930
  this.manager = manager;
1855
1931
  this.db = drizzle(this.manager.getConnection());
1856
1932
  }
1933
+ /**
1934
+ * Asynchronously runs the provided database operation while checking if the database manager is currently shutting down.
1935
+ * If the database manager is shutting down, a warning is logged and null is returned.
1936
+ *
1937
+ * @param {Function} operation - The database operation to be performed.
1938
+ * @returns {Promise<T>} A promise that resolves with the result of the database operation.
1939
+ */
1857
1940
  async withDatabase(operation) {
1858
1941
  if (this.manager.isShuttingDown()) {
1859
1942
  logger2.warn("Database is shutting down");
@@ -1861,6 +1944,11 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
1861
1944
  }
1862
1945
  return operation();
1863
1946
  }
1947
+ /**
1948
+ * Asynchronously initializes the database by running migrations using the manager.
1949
+ *
1950
+ * @returns {Promise<void>} A Promise that resolves when the database initialization is complete.
1951
+ */
1864
1952
  async init() {
1865
1953
  try {
1866
1954
  await this.manager.runMigrations();
@@ -1869,123 +1957,44 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
1869
1957
  throw error;
1870
1958
  }
1871
1959
  }
1960
+ /**
1961
+ * Asynchronously closes the manager.
1962
+ */
1872
1963
  async close() {
1873
1964
  await this.manager.close();
1874
1965
  }
1875
1966
  };
1876
1967
 
1877
- // src/pg-lite/manager.ts
1878
- import { PGlite } from "@electric-sql/pglite";
1879
- import { vector as vector3 } from "@electric-sql/pglite/vector";
1880
- import { fuzzystrmatch } from "@electric-sql/pglite/contrib/fuzzystrmatch";
1881
- import { logger as logger3 } from "@elizaos/core";
1882
- import { migrate } from "drizzle-orm/pglite/migrator";
1883
- import { fileURLToPath } from "node:url";
1884
- import path from "node:path";
1885
- import { drizzle as drizzle2 } from "drizzle-orm/pglite";
1886
- var __filename = fileURLToPath(import.meta.url);
1887
- var __dirname = path.dirname(__filename);
1888
- var PGliteClientManager = class {
1889
- client;
1890
- shuttingDown = false;
1891
- shutdownTimeout = 800;
1892
- constructor(options) {
1893
- this.client = new PGlite({
1894
- ...options,
1895
- extensions: {
1896
- vector: vector3,
1897
- fuzzystrmatch
1898
- }
1899
- });
1900
- this.setupShutdownHandlers();
1901
- }
1902
- getConnection() {
1903
- if (this.shuttingDown) {
1904
- throw new Error("Client manager is shutting down");
1905
- }
1906
- return this.client;
1907
- }
1908
- async gracefulShutdown() {
1909
- if (this.shuttingDown) {
1910
- return;
1911
- }
1912
- this.shuttingDown = true;
1913
- logger3.info("Starting graceful shutdown of PGlite client...");
1914
- const timeout = setTimeout(() => {
1915
- logger3.warn(
1916
- "Shutdown timeout reached, forcing database connection closure..."
1917
- );
1918
- this.client.close().finally(() => {
1919
- process.exit(1);
1920
- });
1921
- }, this.shutdownTimeout);
1922
- try {
1923
- await new Promise((resolve) => setTimeout(resolve, this.shutdownTimeout));
1924
- await this.client.close();
1925
- clearTimeout(timeout);
1926
- logger3.info("PGlite client shutdown completed successfully");
1927
- process.exit(0);
1928
- } catch (error) {
1929
- logger3.error("Error during graceful shutdown:", error);
1930
- process.exit(1);
1931
- }
1932
- }
1933
- setupShutdownHandlers() {
1934
- process.on("SIGINT", async () => {
1935
- await this.gracefulShutdown();
1936
- });
1937
- process.on("SIGTERM", async () => {
1938
- await this.gracefulShutdown();
1939
- });
1940
- process.on("beforeExit", async () => {
1941
- await this.gracefulShutdown();
1942
- });
1943
- }
1944
- async initialize() {
1945
- try {
1946
- await this.client.waitReady;
1947
- logger3.info("PGlite client initialized successfully");
1948
- } catch (error) {
1949
- logger3.error("Failed to initialize PGlite client:", error);
1950
- throw error;
1951
- }
1952
- }
1953
- async close() {
1954
- if (!this.shuttingDown) {
1955
- await this.gracefulShutdown();
1956
- }
1957
- }
1958
- isShuttingDown() {
1959
- return this.shuttingDown;
1960
- }
1961
- async runMigrations() {
1962
- try {
1963
- const db = drizzle2(this.client);
1964
- await migrate(db, {
1965
- migrationsFolder: path.resolve(__dirname, "../drizzle/migrations")
1966
- });
1967
- logger3.info("Migrations completed successfully!");
1968
- } catch (error) {
1969
- logger3.error("Failed to run database migrations:", error);
1970
- }
1971
- }
1972
- };
1973
-
1974
1968
  // src/pg/adapter.ts
1975
- import { logger as logger4 } from "@elizaos/core";
1976
- import { drizzle as drizzle3 } from "drizzle-orm/node-postgres";
1969
+ import { logger as logger3 } from "@elizaos/core";
1970
+ import { drizzle as drizzle2 } from "drizzle-orm/node-postgres";
1977
1971
  var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
1972
+ /**
1973
+ * Constructor for creating a new instance of a class.
1974
+ * @param {UUID} agentId - The unique identifier for the agent.
1975
+ * @param {PostgresConnectionManager} manager - The Postgres connection manager for the instance.
1976
+ */
1978
1977
  constructor(agentId, manager) {
1979
1978
  super(agentId);
1980
1979
  this.manager = manager;
1981
1980
  this.manager = manager;
1982
1981
  }
1982
+ static {
1983
+ __name(this, "PgDatabaseAdapter");
1984
+ }
1983
1985
  embeddingDimension = DIMENSION_MAP[384];
1986
+ /**
1987
+ * Executes the provided operation with a database connection.
1988
+ *
1989
+ * @template T
1990
+ * @param {() => Promise<T>} operation - The operation to be executed with the database connection.
1991
+ * @returns {Promise<T>} A promise that resolves with the result of the operation.
1992
+ */
1984
1993
  async withDatabase(operation) {
1985
1994
  return await this.withRetry(async () => {
1986
1995
  const client = await this.manager.getClient();
1987
1996
  try {
1988
- const db = drizzle3(client);
1997
+ const db = drizzle2(client);
1989
1998
  this.db = db;
1990
1999
  return await operation();
1991
2000
  } finally {
@@ -1993,181 +2002,67 @@ var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
1993
2002
  }
1994
2003
  });
1995
2004
  }
2005
+ /**
2006
+ * Asynchronously initializes the PgDatabaseAdapter by running migrations using the manager.
2007
+ * Logs a success message if initialization is successful, otherwise logs an error message.
2008
+ *
2009
+ * @returns {Promise<void>} A promise that resolves when initialization is complete.
2010
+ */
1996
2011
  async init() {
1997
2012
  try {
1998
2013
  await this.manager.runMigrations();
1999
- logger4.info("PgDatabaseAdapter initialized successfully");
2014
+ logger3.info("PgDatabaseAdapter initialized successfully");
2000
2015
  } catch (error) {
2001
- logger4.error("Failed to initialize PgDatabaseAdapter:", error);
2016
+ logger3.error("Failed to initialize PgDatabaseAdapter:", error);
2002
2017
  throw error;
2003
2018
  }
2004
2019
  }
2020
+ /**
2021
+ * Asynchronously closes the manager associated with this instance.
2022
+ *
2023
+ * @returns A Promise that resolves once the manager is closed.
2024
+ */
2005
2025
  async close() {
2006
2026
  await this.manager.close();
2007
2027
  }
2008
2028
  };
2009
2029
 
2010
- // src/pg/manager.ts
2011
- import pkg from "pg";
2012
- import { logger as logger5 } from "@elizaos/core";
2013
- import { migrate as migrate2 } from "drizzle-orm/node-postgres/migrator";
2014
- import { fileURLToPath as fileURLToPath2 } from "node:url";
2015
- import path2 from "node:path";
2016
- import { drizzle as drizzle4 } from "drizzle-orm/node-postgres";
2017
- var { Pool } = pkg;
2018
- var __filename2 = fileURLToPath2(import.meta.url);
2019
- var __dirname2 = path2.dirname(__filename2);
2020
- var PostgresConnectionManager = class {
2021
- pool;
2022
- isShuttingDown = false;
2023
- connectionTimeout = 5e3;
2024
- constructor(connectionString) {
2025
- const defaultConfig = {
2026
- max: 20,
2027
- idleTimeoutMillis: 3e4,
2028
- connectionTimeoutMillis: this.connectionTimeout
2029
- };
2030
- this.pool = new Pool({
2031
- ...defaultConfig,
2032
- connectionString
2033
- });
2034
- this.pool.on("error", (err) => {
2035
- logger5.error("Unexpected pool error", err);
2036
- this.handlePoolError(err);
2037
- });
2038
- this.setupPoolErrorHandling();
2039
- this.testConnection();
2040
- }
2041
- async handlePoolError(error) {
2042
- logger5.error("Pool error occurred, attempting to reconnect", {
2043
- error: error.message
2044
- });
2045
- try {
2046
- await this.pool.end();
2047
- this.pool = new Pool({
2048
- ...this.pool.options,
2049
- connectionTimeoutMillis: this.connectionTimeout
2050
- });
2051
- await this.testConnection();
2052
- logger5.success("Pool reconnection successful");
2053
- } catch (reconnectError) {
2054
- logger5.error("Failed to reconnect pool", {
2055
- error: reconnectError instanceof Error ? reconnectError.message : String(reconnectError)
2056
- });
2057
- throw reconnectError;
2058
- }
2059
- }
2060
- async testConnection() {
2061
- let client;
2062
- try {
2063
- client = await this.pool.connect();
2064
- const result = await client.query("SELECT NOW()");
2065
- logger5.success("Database connection test successful:", result.rows[0]);
2066
- return true;
2067
- } catch (error) {
2068
- logger5.error("Database connection test failed:", error);
2069
- throw new Error(
2070
- `Failed to connect to database: ${error.message}`
2071
- );
2072
- } finally {
2073
- if (client) client.release();
2074
- }
2075
- }
2076
- setupPoolErrorHandling() {
2077
- process.on("SIGINT", async () => {
2078
- await this.cleanup();
2079
- process.exit(0);
2080
- });
2081
- process.on("SIGTERM", async () => {
2082
- await this.cleanup();
2083
- process.exit(0);
2084
- });
2085
- process.on("beforeExit", async () => {
2086
- await this.cleanup();
2087
- });
2088
- }
2089
- getConnection() {
2090
- if (this.isShuttingDown) {
2091
- throw new Error("Connection manager is shutting down");
2092
- }
2093
- try {
2094
- return this.pool;
2095
- } catch (error) {
2096
- logger5.error("Failed to get connection from pool:", error);
2097
- throw error;
2098
- }
2099
- }
2100
- async getClient() {
2101
- try {
2102
- return await this.pool.connect();
2103
- } catch (error) {
2104
- logger5.error("Failed to acquire a database client:", error);
2105
- throw error;
2106
- }
2107
- }
2108
- async initialize() {
2109
- try {
2110
- await this.testConnection();
2111
- logger5.info("PostgreSQL connection manager initialized successfully");
2112
- } catch (error) {
2113
- logger5.error("Failed to initialize connection manager:", error);
2114
- throw error;
2115
- }
2116
- }
2117
- async close() {
2118
- await this.cleanup();
2119
- }
2120
- async cleanup() {
2121
- try {
2122
- await this.pool.end();
2123
- logger5.info("Database pool closed");
2124
- } catch (error) {
2125
- logger5.error("Error closing database pool:", error);
2126
- }
2127
- }
2128
- async runMigrations() {
2129
- try {
2130
- const db = drizzle4(this.pool);
2131
- await migrate2(db, {
2132
- migrationsFolder: path2.resolve(__dirname2, "../drizzle/migrations")
2133
- });
2134
- logger5.info("Migrations completed successfully!");
2135
- } catch (error) {
2136
- logger5.error("Failed to run database migrations:", error);
2137
- }
2138
- }
2139
- };
2140
-
2141
2030
  // src/index.ts
2142
2031
  var pgLiteClientManager;
2032
+ var postgresConnectionManager;
2143
2033
  function createDatabaseAdapter(config, agentId) {
2144
2034
  if (config.postgresUrl) {
2145
- const manager = new PostgresConnectionManager(config.postgresUrl);
2146
- return new PgDatabaseAdapter(agentId, manager);
2035
+ if (!postgresConnectionManager) {
2036
+ postgresConnectionManager = new PostgresConnectionManager(
2037
+ config.postgresUrl
2038
+ );
2039
+ }
2040
+ return new PgDatabaseAdapter(agentId, postgresConnectionManager);
2147
2041
  }
2148
- const dataDir = config.dataDir ?? "../../pgLite";
2042
+ const dataDir = config.dataDir ?? "./elizadb";
2149
2043
  if (!pgLiteClientManager) {
2150
2044
  pgLiteClientManager = new PGliteClientManager({ dataDir });
2151
2045
  }
2152
2046
  return new PgliteDatabaseAdapter(agentId, pgLiteClientManager);
2153
2047
  }
2048
+ __name(createDatabaseAdapter, "createDatabaseAdapter");
2154
2049
  var drizzlePlugin = {
2155
2050
  name: "drizzle",
2156
2051
  description: "Database adapter plugin using Drizzle ORM",
2157
- init: async (_, runtime) => {
2052
+ init: /* @__PURE__ */ __name(async (_, runtime) => {
2158
2053
  const config = {
2159
- dataDir: runtime.getSetting("PGLITE_DATA_DIR"),
2054
+ dataDir: runtime.getSetting("PGLITE_DATA_DIR") ?? "./pglite",
2160
2055
  postgresUrl: runtime.getSetting("POSTGRES_URL")
2161
2056
  };
2162
2057
  try {
2163
2058
  const db = createDatabaseAdapter(config, runtime.agentId);
2164
- logger6.success("Database connection established successfully");
2059
+ logger4.success("Database connection established successfully");
2165
2060
  runtime.registerDatabaseAdapter(db);
2166
2061
  } catch (error) {
2167
- logger6.error("Failed to initialize database:", error);
2062
+ logger4.error("Failed to initialize database:", error);
2168
2063
  throw error;
2169
2064
  }
2170
- }
2065
+ }, "init")
2171
2066
  };
2172
2067
  var index_default = drizzlePlugin;
2173
2068
  export {