@elizaos/plugin-sql 1.0.0-beta.51 → 1.0.0-beta.53
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/README.md +2 -2
- package/dist/{chunk-EYE2J2N6.js → chunk-C7MPSX4Y.js} +13 -4
- package/dist/chunk-C7MPSX4Y.js.map +1 -0
- package/dist/index.js +66 -38
- package/dist/index.js.map +1 -1
- package/dist/migrate.js +5 -9
- package/dist/migrate.js.map +1 -1
- package/package.json +5 -4
- package/dist/chunk-EYE2J2N6.js.map +0 -1
package/README.md
CHANGED
|
@@ -112,7 +112,7 @@ The plugin uses the following environment variables:
|
|
|
112
112
|
|
|
113
113
|
- `POSTGRES_URL`: Connection string for PostgreSQL database (e.g., `postgresql://user:password@localhost:5432/dbname`)
|
|
114
114
|
- If not provided, the plugin will use PGlite as a fallback
|
|
115
|
-
- `PGLITE_DATA_DIR`: (Optional) Directory for PGlite data storage (default:
|
|
115
|
+
- `PGLITE_DATA_DIR`: (Optional) Directory for PGlite data storage (default: `./pglite`)
|
|
116
116
|
|
|
117
117
|
These variables should be defined in a `.env` file at the root of your project.
|
|
118
118
|
|
|
@@ -225,7 +225,7 @@ export default defineConfig({
|
|
|
225
225
|
schema: './src/schema/index.ts',
|
|
226
226
|
out: './drizzle/migrations',
|
|
227
227
|
dbCredentials: {
|
|
228
|
-
url: process.env.POSTGRES_URL || 'file
|
|
228
|
+
url: process.env.POSTGRES_URL || 'file:../../.pglite',
|
|
229
229
|
},
|
|
230
230
|
breakpoints: true,
|
|
231
231
|
});
|
|
@@ -61,17 +61,26 @@ var PGliteClientManager = class {
|
|
|
61
61
|
const timeout = setTimeout(() => {
|
|
62
62
|
logger.warn("Shutdown timeout reached, forcing database connection closure...");
|
|
63
63
|
this.client.close().finally(() => {
|
|
64
|
-
|
|
64
|
+
logger.warn("Forced database connection closure complete.");
|
|
65
|
+
if (process.env.NODE_ENV !== "test") {
|
|
66
|
+
process.exit(1);
|
|
67
|
+
}
|
|
65
68
|
});
|
|
66
69
|
}, this.shutdownTimeout);
|
|
67
70
|
try {
|
|
68
71
|
await this.client.close();
|
|
69
72
|
clearTimeout(timeout);
|
|
70
73
|
logger.info("PGlite client shutdown completed successfully");
|
|
71
|
-
process.
|
|
74
|
+
if (process.env.NODE_ENV !== "test") {
|
|
75
|
+
process.exit(0);
|
|
76
|
+
}
|
|
72
77
|
} catch (error) {
|
|
73
78
|
logger.error("Error during graceful shutdown:", error);
|
|
74
|
-
process.
|
|
79
|
+
if (process.env.NODE_ENV !== "test") {
|
|
80
|
+
process.exit(1);
|
|
81
|
+
} else {
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
75
84
|
}
|
|
76
85
|
}
|
|
77
86
|
/**
|
|
@@ -343,4 +352,4 @@ export {
|
|
|
343
352
|
PGliteClientManager,
|
|
344
353
|
PostgresConnectionManager
|
|
345
354
|
};
|
|
346
|
-
//# sourceMappingURL=chunk-
|
|
355
|
+
//# sourceMappingURL=chunk-C7MPSX4Y.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 logger.warn('Forced database connection closure complete.');\n if (process.env.NODE_ENV !== 'test') {\n process.exit(1);\n }\n });\n }, this.shutdownTimeout);\n\n try {\n await this.client.close();\n clearTimeout(timeout);\n logger.info('PGlite client shutdown completed successfully');\n if (process.env.NODE_ENV !== 'test') {\n process.exit(0);\n }\n } catch (error) {\n logger.error('Error during graceful shutdown:', error);\n if (process.env.NODE_ENV !== 'test') {\n process.exit(1);\n } else {\n throw error;\n }\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 packageJsonUrl = await import.meta.resolve('@elizaos/plugin-sql/package.json');\n const packageJsonPath = fileURLToPath(packageJsonUrl);\n const packageRoot = pathDirname(packageJsonPath);\n const migrationsPath = pathResolve(packageRoot, 'drizzle/migrations');\n logger.debug(\n `Resolved migrations path (pglite) using import.meta.resolve: ${migrationsPath}`\n );\n\n await migrate(db, {\n migrationsFolder: migrationsPath,\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 packageJsonUrl = await import.meta.resolve('@elizaos/plugin-sql/package.json');\n const packageJsonPath = fileURLToPath(packageJsonUrl);\n const packageRoot = path.dirname(packageJsonPath);\n const migrationsPath = path.resolve(packageRoot, 'drizzle/migrations');\n logger.debug(`Resolved migrations path (pg) using import.meta.resolve: ${migrationsPath}`);\n\n await migrate(db, {\n migrationsFolder: migrationsPath,\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,YAAY;AAAA,QACV;AAAA,QACA;AAAA,MACF;AAAA,IACF,CAAC;AACD,SAAK,sBAAsB;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,gBAAwB;AAC7B,QAAI,KAAK,cAAc;AACrB,YAAM,IAAI,MAAM,iCAAiC;AAAA,IACnD;AACA,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAc,mBAAmB;AAC/B,QAAI,KAAK,cAAc;AACrB;AAAA,IACF;AAEA,SAAK,eAAe;AACpB,WAAO,KAAK,gDAAgD;AAE5D,UAAM,UAAU,WAAW,MAAM;AAC/B,aAAO,KAAK,kEAAkE;AAC9E,WAAK,OAAO,MAAM,EAAE,QAAQ,MAAM;AAChC,eAAO,KAAK,8CAA8C;AAC1D,YAAI,QAAQ,IAAI,aAAa,QAAQ;AACnC,kBAAQ,KAAK,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,IAAI;AAAA,QAChB,kBAAkB;AAAA,QAClB,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
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
PGliteClientManager,
|
|
3
3
|
PostgresConnectionManager,
|
|
4
4
|
__name
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-C7MPSX4Y.js";
|
|
6
6
|
|
|
7
7
|
// src/index.ts
|
|
8
8
|
import * as os from "node:os";
|
|
@@ -497,15 +497,17 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
497
497
|
* @returns {Promise<void>} - Resolves once the embedding dimension is ensured.
|
|
498
498
|
*/
|
|
499
499
|
async ensureEmbeddingDimension(dimension) {
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
500
|
+
return this.withDatabase(async () => {
|
|
501
|
+
const existingMemory = await this.db.select({
|
|
502
|
+
embedding: embeddingTable
|
|
503
|
+
}).from(memoryTable).innerJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id)).where(eq(memoryTable.agentId, this.agentId)).limit(1);
|
|
504
|
+
if (existingMemory.length > 0) {
|
|
505
|
+
const usedDimension = Object.entries(DIMENSION_MAP).find(
|
|
506
|
+
([_, colName]) => existingMemory[0].embedding[colName] !== null
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
this.embeddingDimension = DIMENSION_MAP[dimension];
|
|
510
|
+
});
|
|
509
511
|
}
|
|
510
512
|
/**
|
|
511
513
|
* Asynchronously retrieves an agent by their ID from the database.
|
|
@@ -520,7 +522,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
520
522
|
return {
|
|
521
523
|
...row,
|
|
522
524
|
username: row.username || "",
|
|
523
|
-
id: row.id
|
|
525
|
+
id: row.id,
|
|
526
|
+
system: !row.system ? void 0 : row.system,
|
|
527
|
+
bio: !row.bio ? "" : row.bio
|
|
524
528
|
};
|
|
525
529
|
});
|
|
526
530
|
}
|
|
@@ -538,7 +542,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
538
542
|
}).from(agentTable);
|
|
539
543
|
return rows.map((row) => ({
|
|
540
544
|
...row,
|
|
541
|
-
id: row.id
|
|
545
|
+
id: row.id,
|
|
546
|
+
bio: row.bio === null ? "" : row.bio
|
|
542
547
|
}));
|
|
543
548
|
});
|
|
544
549
|
}
|
|
@@ -616,27 +621,42 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
616
621
|
*/
|
|
617
622
|
async mergeAgentSettings(tx, agentId, updatedSettings) {
|
|
618
623
|
const currentAgent = await tx.select({ settings: agentTable.settings }).from(agentTable).where(eq(agentTable.id, agentId)).limit(1);
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
624
|
+
const currentSettings = currentAgent.length > 0 && currentAgent[0].settings ? currentAgent[0].settings : {};
|
|
625
|
+
const deepMerge = /* @__PURE__ */ __name((target, source) => {
|
|
626
|
+
if (source === null) {
|
|
627
|
+
return void 0;
|
|
628
|
+
}
|
|
629
|
+
if (Array.isArray(source) || typeof source !== "object") {
|
|
630
|
+
return source;
|
|
631
|
+
}
|
|
632
|
+
const output = typeof target === "object" && target !== null && !Array.isArray(target) ? { ...target } : {};
|
|
633
|
+
let isEmpty = true;
|
|
634
|
+
for (const key of Object.keys(source)) {
|
|
635
|
+
const sourceValue = source[key];
|
|
636
|
+
if (sourceValue === null) {
|
|
637
|
+
delete output[key];
|
|
638
|
+
} else if (typeof sourceValue === "object" && !Array.isArray(sourceValue)) {
|
|
639
|
+
const nestedMergeResult = deepMerge(output[key], sourceValue);
|
|
640
|
+
if (nestedMergeResult === void 0) {
|
|
641
|
+
delete output[key];
|
|
642
|
+
} else {
|
|
643
|
+
output[key] = nestedMergeResult;
|
|
644
|
+
isEmpty = false;
|
|
645
|
+
}
|
|
630
646
|
} else {
|
|
631
|
-
|
|
647
|
+
output[key] = sourceValue;
|
|
648
|
+
isEmpty = false;
|
|
632
649
|
}
|
|
633
650
|
}
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
651
|
+
if (Object.keys(output).length === 0) {
|
|
652
|
+
if (!(typeof source === "object" && source !== null && Object.keys(source).length === 0)) {
|
|
653
|
+
return void 0;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
return output;
|
|
657
|
+
}, "deepMerge");
|
|
658
|
+
const finalSettings = deepMerge(currentSettings, updatedSettings);
|
|
659
|
+
return finalSettings === void 0 ? {} : finalSettings;
|
|
640
660
|
}
|
|
641
661
|
/**
|
|
642
662
|
* Asynchronously deletes an agent with the specified UUID and all related entries.
|
|
@@ -1193,6 +1213,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1193
1213
|
agentId: row.memory.agentId,
|
|
1194
1214
|
roomId: row.memory.roomId,
|
|
1195
1215
|
unique: row.memory.unique,
|
|
1216
|
+
metadata: row.memory.metadata,
|
|
1196
1217
|
embedding: row.embedding ?? void 0
|
|
1197
1218
|
};
|
|
1198
1219
|
});
|
|
@@ -1708,23 +1729,31 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1708
1729
|
return this.withDatabase(async () => {
|
|
1709
1730
|
const result = await this.db.select({
|
|
1710
1731
|
id: roomTable.id,
|
|
1732
|
+
name: roomTable.name,
|
|
1733
|
+
// Added name
|
|
1711
1734
|
channelId: roomTable.channelId,
|
|
1712
1735
|
agentId: roomTable.agentId,
|
|
1713
1736
|
serverId: roomTable.serverId,
|
|
1714
1737
|
worldId: roomTable.worldId,
|
|
1715
1738
|
type: roomTable.type,
|
|
1716
|
-
source: roomTable.source
|
|
1739
|
+
source: roomTable.source,
|
|
1740
|
+
metadata: roomTable.metadata
|
|
1741
|
+
// Added metadata
|
|
1717
1742
|
}).from(roomTable).where(and(eq(roomTable.id, roomId), eq(roomTable.agentId, this.agentId))).limit(1);
|
|
1718
1743
|
if (result.length === 0) return null;
|
|
1719
1744
|
const room = result[0];
|
|
1720
1745
|
return {
|
|
1721
1746
|
...room,
|
|
1722
1747
|
id: room.id,
|
|
1748
|
+
name: room.name ?? void 0,
|
|
1749
|
+
// Corrected to handle null
|
|
1723
1750
|
agentId: room.agentId,
|
|
1724
1751
|
serverId: room.serverId,
|
|
1725
1752
|
worldId: room.worldId,
|
|
1726
1753
|
channelId: room.channelId,
|
|
1727
|
-
type: room.type
|
|
1754
|
+
type: room.type,
|
|
1755
|
+
metadata: room.metadata
|
|
1756
|
+
// Added metadata
|
|
1728
1757
|
};
|
|
1729
1758
|
});
|
|
1730
1759
|
}
|
|
@@ -2276,7 +2305,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2276
2305
|
return result.map((row) => ({
|
|
2277
2306
|
id: row.id,
|
|
2278
2307
|
name: row.name,
|
|
2279
|
-
description: row.description,
|
|
2308
|
+
description: row.description ?? "",
|
|
2280
2309
|
roomId: row.roomId,
|
|
2281
2310
|
worldId: row.worldId,
|
|
2282
2311
|
tags: row.tags || [],
|
|
@@ -2297,7 +2326,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2297
2326
|
return result.map((row) => ({
|
|
2298
2327
|
id: row.id,
|
|
2299
2328
|
name: row.name,
|
|
2300
|
-
description: row.description,
|
|
2329
|
+
description: row.description ?? "",
|
|
2301
2330
|
roomId: row.roomId,
|
|
2302
2331
|
worldId: row.worldId,
|
|
2303
2332
|
tags: row.tags || [],
|
|
@@ -2322,7 +2351,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2322
2351
|
return {
|
|
2323
2352
|
id: row.id,
|
|
2324
2353
|
name: row.name,
|
|
2325
|
-
description: row.description,
|
|
2354
|
+
description: row.description ?? "",
|
|
2326
2355
|
roomId: row.roomId,
|
|
2327
2356
|
worldId: row.worldId,
|
|
2328
2357
|
tags: row.tags || [],
|
|
@@ -2572,7 +2601,6 @@ var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
2572
2601
|
|
|
2573
2602
|
// src/index.ts
|
|
2574
2603
|
import path from "node:path";
|
|
2575
|
-
import { stringToUuid as stringToUuid2 } from "@elizaos/core";
|
|
2576
2604
|
var GLOBAL_SINGLETONS = Symbol.for("@elizaos/plugin-sql/global-singletons");
|
|
2577
2605
|
var globalSymbols = global;
|
|
2578
2606
|
if (!globalSymbols[GLOBAL_SINGLETONS]) {
|
|
@@ -2598,7 +2626,7 @@ function createDatabaseAdapter(config, agentId) {
|
|
|
2598
2626
|
}
|
|
2599
2627
|
return new PgDatabaseAdapter(agentId, globalSingletons.postgresConnectionManager);
|
|
2600
2628
|
}
|
|
2601
|
-
const dataDir = config.dataDir ?? path.join(
|
|
2629
|
+
const dataDir = config.dataDir ?? path.join(process.cwd(), ".pglite");
|
|
2602
2630
|
if (!globalSingletons.pgLiteClientManager) {
|
|
2603
2631
|
globalSingletons.pgLiteClientManager = new PGliteClientManager({ dataDir });
|
|
2604
2632
|
}
|
|
@@ -2610,7 +2638,7 @@ var sqlPlugin = {
|
|
|
2610
2638
|
description: "SQL database adapter plugin using Drizzle ORM",
|
|
2611
2639
|
init: /* @__PURE__ */ __name(async (_, runtime) => {
|
|
2612
2640
|
const config = {
|
|
2613
|
-
dataDir: runtime.getSetting("PGLITE_DATA_DIR") ?? path.join(
|
|
2641
|
+
dataDir: runtime.getSetting("PGLITE_DATA_DIR") ?? path.join(process.cwd(), ".pglite"),
|
|
2614
2642
|
postgresUrl: runtime.getSetting("POSTGRES_URL")
|
|
2615
2643
|
};
|
|
2616
2644
|
try {
|