@elizaos/plugin-sql 1.0.6 → 1.0.8
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.d.ts +2431 -5
- package/dist/index.js +1420 -259
- package/dist/index.js.map +1 -1
- package/package.json +16 -8
- package/dist/chunk-74FVWTXP.js +0 -401
- package/dist/chunk-74FVWTXP.js.map +0 -1
- package/dist/migrate.d.ts +0 -2
- package/dist/migrate.js +0 -57
- package/dist/migrate.js.map +0 -1
- package/drizzle/extension.sql +0 -4
- package/drizzle/migrations/0000_thin_madame_web.sql +0 -256
- package/drizzle/migrations/meta/0000_snapshot.json +0 -1791
- package/drizzle/migrations/meta/_journal.json +0 -13
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
}
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
+
var __export = (target, all) => {
|
|
4
|
+
for (var name in all)
|
|
5
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
6
|
+
};
|
|
7
7
|
|
|
8
8
|
// src/index.ts
|
|
9
|
-
import { logger as
|
|
9
|
+
import { logger as logger7 } from "@elizaos/core";
|
|
10
10
|
|
|
11
11
|
// src/pglite/adapter.ts
|
|
12
12
|
import { logger as logger2 } from "@elizaos/core";
|
|
@@ -14,10 +14,9 @@ import { drizzle } from "drizzle-orm/pglite";
|
|
|
14
14
|
|
|
15
15
|
// src/base.ts
|
|
16
16
|
import {
|
|
17
|
+
ChannelType,
|
|
17
18
|
DatabaseAdapter,
|
|
18
|
-
logger
|
|
19
|
-
stringToUuid,
|
|
20
|
-
ChannelType
|
|
19
|
+
logger
|
|
21
20
|
} from "@elizaos/core";
|
|
22
21
|
import {
|
|
23
22
|
and,
|
|
@@ -27,8 +26,8 @@ import {
|
|
|
27
26
|
eq,
|
|
28
27
|
gte,
|
|
29
28
|
inArray,
|
|
30
|
-
lte,
|
|
31
29
|
lt,
|
|
30
|
+
lte,
|
|
32
31
|
or,
|
|
33
32
|
sql as sql16
|
|
34
33
|
} from "drizzle-orm";
|
|
@@ -36,7 +35,7 @@ import { v4 } from "uuid";
|
|
|
36
35
|
|
|
37
36
|
// src/schema/embedding.ts
|
|
38
37
|
import { sql as sql5 } from "drizzle-orm";
|
|
39
|
-
import { check as check2, foreignKey as foreignKey2, index as index2, pgTable as pgTable5, uuid as uuid5, vector as vector2 } from "drizzle-orm/pg-core";
|
|
38
|
+
import { check as check2, foreignKey as foreignKey2, index as index2, pgTable as pgTable5, timestamp as timestamp5, uuid as uuid5, vector as vector2 } from "drizzle-orm/pg-core";
|
|
40
39
|
import { VECTOR_DIMS } from "@elizaos/core";
|
|
41
40
|
|
|
42
41
|
// src/schema/memory.ts
|
|
@@ -49,46 +48,20 @@ import {
|
|
|
49
48
|
jsonb as jsonb4,
|
|
50
49
|
pgTable as pgTable4,
|
|
51
50
|
text as text4,
|
|
51
|
+
timestamp as timestamp4,
|
|
52
52
|
uuid as uuid4
|
|
53
53
|
} from "drizzle-orm/pg-core";
|
|
54
54
|
|
|
55
55
|
// src/schema/agent.ts
|
|
56
56
|
import { sql } from "drizzle-orm";
|
|
57
|
-
import { boolean, jsonb, pgTable, text, unique, uuid } from "drizzle-orm/pg-core";
|
|
58
|
-
|
|
59
|
-
// src/schema/types.ts
|
|
60
|
-
import { customType } from "drizzle-orm/pg-core";
|
|
61
|
-
var stringJsonb = customType({
|
|
62
|
-
dataType() {
|
|
63
|
-
return "jsonb";
|
|
64
|
-
},
|
|
65
|
-
toDriver(value) {
|
|
66
|
-
return JSON.stringify(value);
|
|
67
|
-
},
|
|
68
|
-
fromDriver(value) {
|
|
69
|
-
return JSON.stringify(value);
|
|
70
|
-
}
|
|
71
|
-
});
|
|
72
|
-
var numberTimestamp = customType({
|
|
73
|
-
dataType() {
|
|
74
|
-
return "timestamptz";
|
|
75
|
-
},
|
|
76
|
-
toDriver(value) {
|
|
77
|
-
return new Date(value).toISOString();
|
|
78
|
-
},
|
|
79
|
-
fromDriver(value) {
|
|
80
|
-
return new Date(value).getTime();
|
|
81
|
-
}
|
|
82
|
-
});
|
|
83
|
-
|
|
84
|
-
// src/schema/agent.ts
|
|
57
|
+
import { boolean, jsonb, pgTable, text, timestamp, unique, uuid } from "drizzle-orm/pg-core";
|
|
85
58
|
var agentTable = pgTable(
|
|
86
59
|
"agents",
|
|
87
60
|
{
|
|
88
61
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
89
62
|
enabled: boolean("enabled").default(true).notNull(),
|
|
90
|
-
createdAt:
|
|
91
|
-
updatedAt:
|
|
63
|
+
createdAt: timestamp("created_at", { withTimezone: true }).default(sql`now()`).notNull(),
|
|
64
|
+
updatedAt: timestamp("updated_at", { withTimezone: true }).default(sql`now()`).notNull(),
|
|
92
65
|
// Character
|
|
93
66
|
name: text("name").notNull(),
|
|
94
67
|
username: text("username"),
|
|
@@ -112,15 +85,15 @@ var agentTable = pgTable(
|
|
|
112
85
|
|
|
113
86
|
// src/schema/entity.ts
|
|
114
87
|
import { sql as sql2 } from "drizzle-orm";
|
|
115
|
-
import { jsonb as jsonb2, pgTable as pgTable2, text as text2, unique as unique2, uuid as uuid2 } from "drizzle-orm/pg-core";
|
|
88
|
+
import { jsonb as jsonb2, pgTable as pgTable2, text as text2, timestamp as timestamp2, unique as unique2, uuid as uuid2 } from "drizzle-orm/pg-core";
|
|
116
89
|
var entityTable = pgTable2(
|
|
117
90
|
"entities",
|
|
118
91
|
{
|
|
119
92
|
id: uuid2("id").notNull().primaryKey(),
|
|
120
|
-
agentId: uuid2("
|
|
93
|
+
agentId: uuid2("agent_id").notNull().references(() => agentTable.id, {
|
|
121
94
|
onDelete: "cascade"
|
|
122
95
|
}),
|
|
123
|
-
createdAt:
|
|
96
|
+
createdAt: timestamp2("created_at").default(sql2`now()`).notNull(),
|
|
124
97
|
names: text2("names").array().default(sql2`'{}'::text[]`).notNull(),
|
|
125
98
|
metadata: jsonb2("metadata").default(sql2`'{}'::jsonb`).notNull()
|
|
126
99
|
},
|
|
@@ -133,7 +106,7 @@ var entityTable = pgTable2(
|
|
|
133
106
|
|
|
134
107
|
// src/schema/room.ts
|
|
135
108
|
import { sql as sql3 } from "drizzle-orm";
|
|
136
|
-
import { jsonb as jsonb3, pgTable as pgTable3, text as text3, uuid as uuid3 } from "drizzle-orm/pg-core";
|
|
109
|
+
import { jsonb as jsonb3, pgTable as pgTable3, text as text3, timestamp as timestamp3, uuid as uuid3 } from "drizzle-orm/pg-core";
|
|
137
110
|
var roomTable = pgTable3("rooms", {
|
|
138
111
|
id: uuid3("id").notNull().primaryKey().default(sql3`gen_random_uuid()`),
|
|
139
112
|
agentId: uuid3("agentId").references(() => agentTable.id, {
|
|
@@ -150,7 +123,7 @@ var roomTable = pgTable3("rooms", {
|
|
|
150
123
|
name: text3("name"),
|
|
151
124
|
metadata: jsonb3("metadata"),
|
|
152
125
|
channelId: text3("channelId"),
|
|
153
|
-
createdAt:
|
|
126
|
+
createdAt: timestamp3("createdAt").default(sql3`now()`).notNull()
|
|
154
127
|
});
|
|
155
128
|
|
|
156
129
|
// src/schema/memory.ts
|
|
@@ -159,7 +132,7 @@ var memoryTable = pgTable4(
|
|
|
159
132
|
{
|
|
160
133
|
id: uuid4("id").primaryKey().notNull(),
|
|
161
134
|
type: text4("type").notNull(),
|
|
162
|
-
createdAt:
|
|
135
|
+
createdAt: timestamp4("createdAt").default(sql4`now()`).notNull(),
|
|
163
136
|
content: jsonb4("content").notNull(),
|
|
164
137
|
entityId: uuid4("entityId").references(() => entityTable.id, {
|
|
165
138
|
onDelete: "cascade"
|
|
@@ -247,7 +220,7 @@ var embeddingTable = pgTable5(
|
|
|
247
220
|
{
|
|
248
221
|
id: uuid5("id").primaryKey().defaultRandom().notNull(),
|
|
249
222
|
memoryId: uuid5("memory_id").references(() => memoryTable.id),
|
|
250
|
-
createdAt:
|
|
223
|
+
createdAt: timestamp5("created_at").default(sql5`now()`).notNull(),
|
|
251
224
|
dim384: vector2("dim_384", { dimensions: VECTOR_DIMS.SMALL }),
|
|
252
225
|
dim512: vector2("dim_512", { dimensions: VECTOR_DIMS.MEDIUM }),
|
|
253
226
|
dim768: vector2("dim_768", { dimensions: VECTOR_DIMS.LARGE }),
|
|
@@ -266,63 +239,85 @@ var embeddingTable = pgTable5(
|
|
|
266
239
|
]
|
|
267
240
|
);
|
|
268
241
|
|
|
242
|
+
// src/schema/index.ts
|
|
243
|
+
var schema_exports = {};
|
|
244
|
+
__export(schema_exports, {
|
|
245
|
+
agentTable: () => agentTable,
|
|
246
|
+
cacheTable: () => cacheTable,
|
|
247
|
+
channelParticipantsTable: () => channelParticipantsTable,
|
|
248
|
+
channelTable: () => channelTable,
|
|
249
|
+
componentTable: () => componentTable,
|
|
250
|
+
embeddingTable: () => embeddingTable,
|
|
251
|
+
entityTable: () => entityTable,
|
|
252
|
+
logTable: () => logTable,
|
|
253
|
+
memoryTable: () => memoryTable,
|
|
254
|
+
messageServerTable: () => messageServerTable,
|
|
255
|
+
messageTable: () => messageTable,
|
|
256
|
+
participantTable: () => participantTable,
|
|
257
|
+
relationshipTable: () => relationshipTable,
|
|
258
|
+
roomTable: () => roomTable,
|
|
259
|
+
serverAgentsTable: () => serverAgentsTable,
|
|
260
|
+
taskTable: () => taskTable,
|
|
261
|
+
worldTable: () => worldTable
|
|
262
|
+
});
|
|
263
|
+
|
|
269
264
|
// src/schema/cache.ts
|
|
270
265
|
import { sql as sql6 } from "drizzle-orm";
|
|
271
|
-
import { jsonb as jsonb5, pgTable as pgTable6, text as text5,
|
|
266
|
+
import { jsonb as jsonb5, pgTable as pgTable6, text as text5, primaryKey, timestamp as timestamp6, uuid as uuid6 } from "drizzle-orm/pg-core";
|
|
272
267
|
var cacheTable = pgTable6(
|
|
273
268
|
"cache",
|
|
274
269
|
{
|
|
275
|
-
id: uuid6("id").notNull().primaryKey().default(sql6`gen_random_uuid()`),
|
|
276
270
|
key: text5("key").notNull(),
|
|
277
|
-
agentId: uuid6("
|
|
271
|
+
agentId: uuid6("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
278
272
|
value: jsonb5("value").notNull(),
|
|
279
|
-
createdAt:
|
|
280
|
-
expiresAt:
|
|
273
|
+
createdAt: timestamp6("created_at", { withTimezone: true }).default(sql6`now()`).notNull(),
|
|
274
|
+
expiresAt: timestamp6("expires_at", { withTimezone: true })
|
|
281
275
|
},
|
|
282
|
-
(table) =>
|
|
276
|
+
(table) => ({
|
|
277
|
+
pk: primaryKey({ columns: [table.key, table.agentId] })
|
|
278
|
+
})
|
|
283
279
|
);
|
|
284
280
|
|
|
285
281
|
// src/schema/component.ts
|
|
286
282
|
import { sql as sql8 } from "drizzle-orm";
|
|
287
|
-
import { jsonb as jsonb7, pgTable as pgTable8, text as text7, uuid as uuid8 } from "drizzle-orm/pg-core";
|
|
283
|
+
import { jsonb as jsonb7, pgTable as pgTable8, text as text7, timestamp as timestamp8, uuid as uuid8 } from "drizzle-orm/pg-core";
|
|
288
284
|
|
|
289
285
|
// src/schema/world.ts
|
|
290
286
|
import { sql as sql7 } from "drizzle-orm";
|
|
291
|
-
import { jsonb as jsonb6, pgTable as pgTable7, text as text6, uuid as uuid7 } from "drizzle-orm/pg-core";
|
|
287
|
+
import { jsonb as jsonb6, pgTable as pgTable7, text as text6, timestamp as timestamp7, uuid as uuid7 } from "drizzle-orm/pg-core";
|
|
292
288
|
var worldTable = pgTable7("worlds", {
|
|
293
289
|
id: uuid7("id").notNull().primaryKey().default(sql7`gen_random_uuid()`),
|
|
294
290
|
agentId: uuid7("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
295
291
|
name: text6("name").notNull(),
|
|
296
292
|
metadata: jsonb6("metadata"),
|
|
297
|
-
serverId: text6("serverId").notNull(),
|
|
298
|
-
createdAt:
|
|
293
|
+
serverId: text6("serverId").notNull().default("local"),
|
|
294
|
+
createdAt: timestamp7("createdAt").default(sql7`now()`).notNull()
|
|
299
295
|
});
|
|
300
296
|
|
|
301
297
|
// src/schema/component.ts
|
|
302
298
|
var componentTable = pgTable8("components", {
|
|
303
|
-
id: uuid8("id").primaryKey().
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
}),
|
|
310
|
-
|
|
311
|
-
onDelete: "cascade"
|
|
312
|
-
}),
|
|
299
|
+
id: uuid8("id").primaryKey().default(sql8`gen_random_uuid()`).notNull(),
|
|
300
|
+
// Foreign keys
|
|
301
|
+
entityId: uuid8("entityId").references(() => entityTable.id, { onDelete: "cascade" }).notNull(),
|
|
302
|
+
agentId: uuid8("agentId").references(() => agentTable.id, { onDelete: "cascade" }).notNull(),
|
|
303
|
+
roomId: uuid8("roomId").references(() => roomTable.id, { onDelete: "cascade" }).notNull(),
|
|
304
|
+
worldId: uuid8("worldId").references(() => worldTable.id, { onDelete: "cascade" }),
|
|
305
|
+
sourceEntityId: uuid8("sourceEntityId").references(() => entityTable.id, { onDelete: "cascade" }),
|
|
306
|
+
// Data
|
|
313
307
|
type: text7("type").notNull(),
|
|
314
308
|
data: jsonb7("data").default(sql8`'{}'::jsonb`),
|
|
315
|
-
|
|
309
|
+
// Timestamps
|
|
310
|
+
createdAt: timestamp8("createdAt").default(sql8`now()`).notNull()
|
|
316
311
|
});
|
|
317
312
|
|
|
318
313
|
// src/schema/log.ts
|
|
319
314
|
import { sql as sql9 } from "drizzle-orm";
|
|
320
|
-
import { foreignKey as foreignKey3, jsonb as jsonb8, pgTable as pgTable9, text as text8, uuid as uuid9 } from "drizzle-orm/pg-core";
|
|
315
|
+
import { foreignKey as foreignKey3, jsonb as jsonb8, pgTable as pgTable9, text as text8, timestamp as timestamp9, uuid as uuid9 } from "drizzle-orm/pg-core";
|
|
321
316
|
var logTable = pgTable9(
|
|
322
317
|
"logs",
|
|
323
318
|
{
|
|
324
319
|
id: uuid9("id").defaultRandom().notNull(),
|
|
325
|
-
createdAt:
|
|
320
|
+
createdAt: timestamp9("created_at", { withTimezone: true }).default(sql9`now()`).notNull(),
|
|
326
321
|
entityId: uuid9("entityId").notNull().references(() => entityTable.id),
|
|
327
322
|
body: jsonb8("body").notNull(),
|
|
328
323
|
type: text8("type").notNull(),
|
|
@@ -344,12 +339,12 @@ var logTable = pgTable9(
|
|
|
344
339
|
|
|
345
340
|
// src/schema/participant.ts
|
|
346
341
|
import { sql as sql10 } from "drizzle-orm";
|
|
347
|
-
import { foreignKey as foreignKey4, index as index3, pgTable as pgTable10, text as text9, uuid as uuid10 } from "drizzle-orm/pg-core";
|
|
342
|
+
import { foreignKey as foreignKey4, index as index3, pgTable as pgTable10, text as text9, timestamp as timestamp10, uuid as uuid10 } from "drizzle-orm/pg-core";
|
|
348
343
|
var participantTable = pgTable10(
|
|
349
344
|
"participants",
|
|
350
345
|
{
|
|
351
346
|
id: uuid10("id").notNull().primaryKey().default(sql10`gen_random_uuid()`),
|
|
352
|
-
createdAt:
|
|
347
|
+
createdAt: timestamp10("created_at", { withTimezone: true }).default(sql10`now()`).notNull(),
|
|
353
348
|
entityId: uuid10("entityId").references(() => entityTable.id, {
|
|
354
349
|
onDelete: "cascade"
|
|
355
350
|
}),
|
|
@@ -380,12 +375,21 @@ var participantTable = pgTable10(
|
|
|
380
375
|
|
|
381
376
|
// src/schema/relationship.ts
|
|
382
377
|
import { sql as sql11 } from "drizzle-orm";
|
|
383
|
-
import {
|
|
378
|
+
import {
|
|
379
|
+
foreignKey as foreignKey5,
|
|
380
|
+
index as index4,
|
|
381
|
+
jsonb as jsonb9,
|
|
382
|
+
pgTable as pgTable11,
|
|
383
|
+
text as text10,
|
|
384
|
+
timestamp as timestamp11,
|
|
385
|
+
unique as unique5,
|
|
386
|
+
uuid as uuid11
|
|
387
|
+
} from "drizzle-orm/pg-core";
|
|
384
388
|
var relationshipTable = pgTable11(
|
|
385
389
|
"relationships",
|
|
386
390
|
{
|
|
387
391
|
id: uuid11("id").notNull().primaryKey().default(sql11`gen_random_uuid()`),
|
|
388
|
-
createdAt:
|
|
392
|
+
createdAt: timestamp11("created_at", { withTimezone: true }).default(sql11`now()`).notNull(),
|
|
389
393
|
sourceEntityId: uuid11("sourceEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
390
394
|
targetEntityId: uuid11("targetEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
391
395
|
agentId: uuid11("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
@@ -394,7 +398,7 @@ var relationshipTable = pgTable11(
|
|
|
394
398
|
},
|
|
395
399
|
(table) => [
|
|
396
400
|
index4("idx_relationships_users").on(table.sourceEntityId, table.targetEntityId),
|
|
397
|
-
|
|
401
|
+
unique5("unique_relationship").on(table.sourceEntityId, table.targetEntityId, table.agentId),
|
|
398
402
|
foreignKey5({
|
|
399
403
|
name: "fk_user_a",
|
|
400
404
|
columns: [table.sourceEntityId],
|
|
@@ -409,7 +413,7 @@ var relationshipTable = pgTable11(
|
|
|
409
413
|
);
|
|
410
414
|
|
|
411
415
|
// src/schema/tasks.ts
|
|
412
|
-
import { jsonb as jsonb10, pgTable as pgTable12, text as text11, timestamp, uuid as uuid12 } from "drizzle-orm/pg-core";
|
|
416
|
+
import { jsonb as jsonb10, pgTable as pgTable12, text as text11, timestamp as timestamp12, uuid as uuid12 } from "drizzle-orm/pg-core";
|
|
413
417
|
import { sql as sql12 } from "drizzle-orm";
|
|
414
418
|
var taskTable = pgTable12("tasks", {
|
|
415
419
|
id: uuid12("id").primaryKey().defaultRandom(),
|
|
@@ -421,12 +425,12 @@ var taskTable = pgTable12("tasks", {
|
|
|
421
425
|
agentId: uuid12("agent_id").notNull(),
|
|
422
426
|
tags: text11("tags").array().default(sql12`'{}'::text[]`),
|
|
423
427
|
metadata: jsonb10("metadata").default(sql12`'{}'::jsonb`),
|
|
424
|
-
createdAt:
|
|
425
|
-
updatedAt:
|
|
428
|
+
createdAt: timestamp12("created_at", { withTimezone: true }).defaultNow(),
|
|
429
|
+
updatedAt: timestamp12("updated_at", { withTimezone: true }).defaultNow()
|
|
426
430
|
});
|
|
427
431
|
|
|
428
432
|
// src/schema/messageServer.ts
|
|
429
|
-
import { pgTable as pgTable13, text as text12, jsonb as jsonb11, timestamp as
|
|
433
|
+
import { pgTable as pgTable13, text as text12, jsonb as jsonb11, timestamp as timestamp13 } from "drizzle-orm/pg-core";
|
|
430
434
|
import { sql as sql13 } from "drizzle-orm";
|
|
431
435
|
var messageServerTable = pgTable13("message_servers", {
|
|
432
436
|
id: text12("id").primaryKey(),
|
|
@@ -435,12 +439,12 @@ var messageServerTable = pgTable13("message_servers", {
|
|
|
435
439
|
sourceType: text12("source_type").notNull(),
|
|
436
440
|
sourceId: text12("source_id"),
|
|
437
441
|
metadata: jsonb11("metadata"),
|
|
438
|
-
createdAt:
|
|
439
|
-
updatedAt:
|
|
442
|
+
createdAt: timestamp13("created_at", { mode: "date" }).default(sql13`CURRENT_TIMESTAMP`).notNull(),
|
|
443
|
+
updatedAt: timestamp13("updated_at", { mode: "date" }).default(sql13`CURRENT_TIMESTAMP`).notNull()
|
|
440
444
|
});
|
|
441
445
|
|
|
442
446
|
// src/schema/channel.ts
|
|
443
|
-
import { pgTable as pgTable14, text as text13, jsonb as jsonb12, timestamp as
|
|
447
|
+
import { pgTable as pgTable14, text as text13, jsonb as jsonb12, timestamp as timestamp14 } from "drizzle-orm/pg-core";
|
|
444
448
|
import { sql as sql14 } from "drizzle-orm";
|
|
445
449
|
var channelTable = pgTable14("channels", {
|
|
446
450
|
id: text13("id").primaryKey(),
|
|
@@ -453,12 +457,12 @@ var channelTable = pgTable14("channels", {
|
|
|
453
457
|
sourceId: text13("source_id"),
|
|
454
458
|
topic: text13("topic"),
|
|
455
459
|
metadata: jsonb12("metadata"),
|
|
456
|
-
createdAt:
|
|
457
|
-
updatedAt:
|
|
460
|
+
createdAt: timestamp14("created_at", { mode: "date" }).default(sql14`CURRENT_TIMESTAMP`).notNull(),
|
|
461
|
+
updatedAt: timestamp14("updated_at", { mode: "date" }).default(sql14`CURRENT_TIMESTAMP`).notNull()
|
|
458
462
|
});
|
|
459
463
|
|
|
460
464
|
// src/schema/message.ts
|
|
461
|
-
import { pgTable as pgTable15, text as text14, jsonb as jsonb13, timestamp as
|
|
465
|
+
import { pgTable as pgTable15, text as text14, jsonb as jsonb13, timestamp as timestamp15 } from "drizzle-orm/pg-core";
|
|
462
466
|
import { sql as sql15 } from "drizzle-orm";
|
|
463
467
|
var messageTable = pgTable15("central_messages", {
|
|
464
468
|
id: text14("id").primaryKey(),
|
|
@@ -473,12 +477,12 @@ var messageTable = pgTable15("central_messages", {
|
|
|
473
477
|
sourceType: text14("source_type"),
|
|
474
478
|
sourceId: text14("source_id"),
|
|
475
479
|
metadata: jsonb13("metadata"),
|
|
476
|
-
createdAt:
|
|
477
|
-
updatedAt:
|
|
480
|
+
createdAt: timestamp15("created_at", { mode: "date" }).default(sql15`CURRENT_TIMESTAMP`).notNull(),
|
|
481
|
+
updatedAt: timestamp15("updated_at", { mode: "date" }).default(sql15`CURRENT_TIMESTAMP`).notNull()
|
|
478
482
|
});
|
|
479
483
|
|
|
480
484
|
// src/schema/channelParticipant.ts
|
|
481
|
-
import { pgTable as pgTable16, text as text15, primaryKey } from "drizzle-orm/pg-core";
|
|
485
|
+
import { pgTable as pgTable16, text as text15, primaryKey as primaryKey2 } from "drizzle-orm/pg-core";
|
|
482
486
|
var channelParticipantsTable = pgTable16(
|
|
483
487
|
"channel_participants",
|
|
484
488
|
{
|
|
@@ -487,12 +491,12 @@ var channelParticipantsTable = pgTable16(
|
|
|
487
491
|
// This is a central UUID (can be an agentId or a dedicated central user ID)
|
|
488
492
|
},
|
|
489
493
|
(table) => ({
|
|
490
|
-
pk:
|
|
494
|
+
pk: primaryKey2({ columns: [table.channelId, table.userId] })
|
|
491
495
|
})
|
|
492
496
|
);
|
|
493
497
|
|
|
494
498
|
// src/schema/serverAgent.ts
|
|
495
|
-
import { pgTable as pgTable17, text as text16, primaryKey as
|
|
499
|
+
import { pgTable as pgTable17, text as text16, primaryKey as primaryKey3 } from "drizzle-orm/pg-core";
|
|
496
500
|
var serverAgentsTable = pgTable17(
|
|
497
501
|
"server_agents",
|
|
498
502
|
{
|
|
@@ -501,7 +505,7 @@ var serverAgentsTable = pgTable17(
|
|
|
501
505
|
// This is the agent's UUID
|
|
502
506
|
},
|
|
503
507
|
(table) => ({
|
|
504
|
-
pk:
|
|
508
|
+
pk: primaryKey3({ columns: [table.serverId, table.agentId] })
|
|
505
509
|
})
|
|
506
510
|
);
|
|
507
511
|
|
|
@@ -515,6 +519,18 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
515
519
|
maxDelay = 1e4;
|
|
516
520
|
jitterMax = 1e3;
|
|
517
521
|
embeddingDimension = DIMENSION_MAP[384];
|
|
522
|
+
/**
|
|
523
|
+
* Initialize method that can be overridden by implementations
|
|
524
|
+
*/
|
|
525
|
+
async initialize() {
|
|
526
|
+
await this.init();
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Get the underlying database instance for testing purposes
|
|
530
|
+
*/
|
|
531
|
+
getDatabase() {
|
|
532
|
+
return this.db;
|
|
533
|
+
}
|
|
518
534
|
agentId;
|
|
519
535
|
/**
|
|
520
536
|
* Constructor for creating a new instance of Agent with the specified agentId.
|
|
@@ -558,31 +574,6 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
558
574
|
}
|
|
559
575
|
throw lastError;
|
|
560
576
|
}
|
|
561
|
-
/**
|
|
562
|
-
* Asynchronously ensures that an agent exists by checking if an agent with the same name already exists in the system.
|
|
563
|
-
* If the agent does not exist, it will be created with the provided data.
|
|
564
|
-
*
|
|
565
|
-
* @param {Partial<Agent>} agent - The partial data of the agent to ensure its existence.
|
|
566
|
-
* @returns {Promise<void>} - A promise that resolves when the agent is successfully ensured.
|
|
567
|
-
* @throws {Error} - If the agent name is not provided or if there is an issue creating the agent.
|
|
568
|
-
*/
|
|
569
|
-
async ensureAgentExists(agent) {
|
|
570
|
-
if (!agent.name) {
|
|
571
|
-
throw new Error("Agent name is required");
|
|
572
|
-
}
|
|
573
|
-
const agents = await this.getAgents();
|
|
574
|
-
const existingAgentId = agents.find((a) => a.name === agent.name)?.id;
|
|
575
|
-
if (existingAgentId) {
|
|
576
|
-
const existingAgent = await this.getAgent(existingAgentId);
|
|
577
|
-
return existingAgent;
|
|
578
|
-
}
|
|
579
|
-
const newAgent = {
|
|
580
|
-
...agent,
|
|
581
|
-
id: stringToUuid(agent.name)
|
|
582
|
-
};
|
|
583
|
-
await this.createAgent(newAgent);
|
|
584
|
-
return newAgent;
|
|
585
|
-
}
|
|
586
577
|
/**
|
|
587
578
|
* Asynchronously ensures that the given embedding dimension is valid for the agent.
|
|
588
579
|
*
|
|
@@ -617,7 +608,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
617
608
|
username: row.username || "",
|
|
618
609
|
id: row.id,
|
|
619
610
|
system: !row.system ? void 0 : row.system,
|
|
620
|
-
bio: !row.bio ? "" : row.bio
|
|
611
|
+
bio: !row.bio ? "" : row.bio,
|
|
612
|
+
createdAt: row.createdAt.getTime(),
|
|
613
|
+
updatedAt: row.updatedAt.getTime()
|
|
621
614
|
};
|
|
622
615
|
});
|
|
623
616
|
}
|
|
@@ -649,9 +642,26 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
649
642
|
async createAgent(agent) {
|
|
650
643
|
return this.withDatabase(async () => {
|
|
651
644
|
try {
|
|
645
|
+
const conditions = [];
|
|
646
|
+
if (agent.id) {
|
|
647
|
+
conditions.push(eq(agentTable.id, agent.id));
|
|
648
|
+
}
|
|
649
|
+
if (agent.name) {
|
|
650
|
+
conditions.push(eq(agentTable.name, agent.name));
|
|
651
|
+
}
|
|
652
|
+
const existing = conditions.length > 0 ? await this.db.select({ id: agentTable.id }).from(agentTable).where(or(...conditions)).limit(1) : [];
|
|
653
|
+
if (existing.length > 0) {
|
|
654
|
+
logger.warn("Attempted to create an agent with a duplicate ID or name.", {
|
|
655
|
+
id: agent.id,
|
|
656
|
+
name: agent.name
|
|
657
|
+
});
|
|
658
|
+
return false;
|
|
659
|
+
}
|
|
652
660
|
await this.db.transaction(async (tx) => {
|
|
653
661
|
await tx.insert(agentTable).values({
|
|
654
|
-
...agent
|
|
662
|
+
...agent,
|
|
663
|
+
createdAt: new Date(agent.createdAt || Date.now()),
|
|
664
|
+
updatedAt: new Date(agent.updatedAt || Date.now())
|
|
655
665
|
});
|
|
656
666
|
});
|
|
657
667
|
logger.debug("Agent created successfully:", {
|
|
@@ -684,10 +694,24 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
684
694
|
if (agent?.settings) {
|
|
685
695
|
agent.settings = await this.mergeAgentSettings(tx, agentId, agent.settings);
|
|
686
696
|
}
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
697
|
+
const updateData = { ...agent };
|
|
698
|
+
if (updateData.createdAt) {
|
|
699
|
+
if (typeof updateData.createdAt === "number") {
|
|
700
|
+
updateData.createdAt = new Date(updateData.createdAt);
|
|
701
|
+
} else {
|
|
702
|
+
delete updateData.createdAt;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
if (updateData.updatedAt) {
|
|
706
|
+
if (typeof updateData.updatedAt === "number") {
|
|
707
|
+
updateData.updatedAt = new Date(updateData.updatedAt);
|
|
708
|
+
} else {
|
|
709
|
+
updateData.updatedAt = /* @__PURE__ */ new Date();
|
|
710
|
+
}
|
|
711
|
+
} else {
|
|
712
|
+
updateData.updatedAt = /* @__PURE__ */ new Date();
|
|
713
|
+
}
|
|
714
|
+
await tx.update(agentTable).set(updateData).where(eq(agentTable.id, agentId));
|
|
691
715
|
});
|
|
692
716
|
logger.debug("Agent updated successfully:", {
|
|
693
717
|
agentId
|
|
@@ -965,7 +989,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
965
989
|
entity: entityTable,
|
|
966
990
|
components: componentTable
|
|
967
991
|
}).from(entityTable).leftJoin(componentTable, eq(componentTable.entityId, entityTable.id)).where(inArray(entityTable.id, entityIds));
|
|
968
|
-
if (result.length === 0) return
|
|
992
|
+
if (result.length === 0) return [];
|
|
969
993
|
const entities = {};
|
|
970
994
|
const entityComponents = {};
|
|
971
995
|
for (const e of result) {
|
|
@@ -1107,7 +1131,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1107
1131
|
roomId: component.roomId,
|
|
1108
1132
|
worldId: component.worldId ?? "",
|
|
1109
1133
|
sourceEntityId: component.sourceEntityId ?? "",
|
|
1110
|
-
data: component.data
|
|
1134
|
+
data: component.data,
|
|
1135
|
+
createdAt: component.createdAt.getTime()
|
|
1111
1136
|
};
|
|
1112
1137
|
});
|
|
1113
1138
|
}
|
|
@@ -1147,7 +1172,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1147
1172
|
roomId: component.roomId,
|
|
1148
1173
|
worldId: component.worldId ?? "",
|
|
1149
1174
|
sourceEntityId: component.sourceEntityId ?? "",
|
|
1150
|
-
data: component.data
|
|
1175
|
+
data: component.data,
|
|
1176
|
+
createdAt: component.createdAt.getTime()
|
|
1151
1177
|
}));
|
|
1152
1178
|
return components;
|
|
1153
1179
|
});
|
|
@@ -1159,7 +1185,10 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1159
1185
|
*/
|
|
1160
1186
|
async createComponent(component) {
|
|
1161
1187
|
return this.withDatabase(async () => {
|
|
1162
|
-
await this.db.insert(componentTable).values(
|
|
1188
|
+
await this.db.insert(componentTable).values({
|
|
1189
|
+
...component,
|
|
1190
|
+
createdAt: new Date(component.createdAt)
|
|
1191
|
+
});
|
|
1163
1192
|
return true;
|
|
1164
1193
|
});
|
|
1165
1194
|
}
|
|
@@ -1170,7 +1199,10 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1170
1199
|
*/
|
|
1171
1200
|
async updateComponent(component) {
|
|
1172
1201
|
return this.withDatabase(async () => {
|
|
1173
|
-
await this.db.update(componentTable).set(
|
|
1202
|
+
await this.db.update(componentTable).set({
|
|
1203
|
+
...component,
|
|
1204
|
+
createdAt: new Date(component.createdAt)
|
|
1205
|
+
}).where(eq(componentTable.id, component.id));
|
|
1174
1206
|
});
|
|
1175
1207
|
}
|
|
1176
1208
|
/**
|
|
@@ -1195,12 +1227,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1195
1227
|
* @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.
|
|
1196
1228
|
*/
|
|
1197
1229
|
async getMemories(params) {
|
|
1198
|
-
const { entityId, agentId, roomId, worldId, tableName, count: count2, unique:
|
|
1230
|
+
const { entityId, agentId, roomId, worldId, tableName, count: count2, unique: unique6, start, end } = params;
|
|
1199
1231
|
if (!tableName) throw new Error("tableName is required");
|
|
1200
1232
|
return this.withDatabase(async () => {
|
|
1201
1233
|
const conditions = [eq(memoryTable.type, tableName)];
|
|
1202
1234
|
if (start) {
|
|
1203
|
-
conditions.push(gte(memoryTable.createdAt, start));
|
|
1235
|
+
conditions.push(gte(memoryTable.createdAt, new Date(start)));
|
|
1204
1236
|
}
|
|
1205
1237
|
if (entityId) {
|
|
1206
1238
|
conditions.push(eq(memoryTable.entityId, entityId));
|
|
@@ -1212,9 +1244,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1212
1244
|
conditions.push(eq(memoryTable.worldId, worldId));
|
|
1213
1245
|
}
|
|
1214
1246
|
if (end) {
|
|
1215
|
-
conditions.push(lte(memoryTable.createdAt, end));
|
|
1247
|
+
conditions.push(lte(memoryTable.createdAt, new Date(end)));
|
|
1216
1248
|
}
|
|
1217
|
-
if (
|
|
1249
|
+
if (unique6) {
|
|
1218
1250
|
conditions.push(eq(memoryTable.unique, true));
|
|
1219
1251
|
}
|
|
1220
1252
|
if (agentId) {
|
|
@@ -1238,7 +1270,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1238
1270
|
return rows.map((row) => ({
|
|
1239
1271
|
id: row.memory.id,
|
|
1240
1272
|
type: row.memory.type,
|
|
1241
|
-
createdAt: row.memory.createdAt,
|
|
1273
|
+
createdAt: row.memory.createdAt.getTime(),
|
|
1242
1274
|
content: typeof row.memory.content === "string" ? JSON.parse(row.memory.content) : row.memory.content,
|
|
1243
1275
|
entityId: row.memory.entityId,
|
|
1244
1276
|
agentId: row.memory.agentId,
|
|
@@ -1279,7 +1311,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1279
1311
|
const rows = params.limit ? await query.limit(params.limit) : await query;
|
|
1280
1312
|
return rows.map((row) => ({
|
|
1281
1313
|
id: row.id,
|
|
1282
|
-
createdAt: row.createdAt,
|
|
1314
|
+
createdAt: row.createdAt.getTime(),
|
|
1283
1315
|
content: typeof row.content === "string" ? JSON.parse(row.content) : row.content,
|
|
1284
1316
|
entityId: row.entityId,
|
|
1285
1317
|
agentId: row.agentId,
|
|
@@ -1304,7 +1336,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1304
1336
|
const row = result[0];
|
|
1305
1337
|
return {
|
|
1306
1338
|
id: row.memory.id,
|
|
1307
|
-
createdAt: row.memory.createdAt,
|
|
1339
|
+
createdAt: row.memory.createdAt.getTime(),
|
|
1308
1340
|
content: typeof row.memory.content === "string" ? JSON.parse(row.memory.content) : row.memory.content,
|
|
1309
1341
|
entityId: row.memory.entityId,
|
|
1310
1342
|
agentId: row.memory.agentId,
|
|
@@ -1335,7 +1367,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1335
1367
|
}).from(memoryTable).leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id)).where(and(...conditions)).orderBy(desc(memoryTable.createdAt));
|
|
1336
1368
|
return rows.map((row) => ({
|
|
1337
1369
|
id: row.memory.id,
|
|
1338
|
-
createdAt: row.memory.createdAt,
|
|
1370
|
+
createdAt: row.memory.createdAt.getTime(),
|
|
1339
1371
|
content: typeof row.memory.content === "string" ? JSON.parse(row.memory.content) : row.memory.content,
|
|
1340
1372
|
entityId: row.memory.entityId,
|
|
1341
1373
|
agentId: row.memory.agentId,
|
|
@@ -1586,7 +1618,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1586
1618
|
return results.map((row) => ({
|
|
1587
1619
|
id: row.memory.id,
|
|
1588
1620
|
type: row.memory.type,
|
|
1589
|
-
createdAt: row.memory.createdAt,
|
|
1621
|
+
createdAt: row.memory.createdAt.getTime(),
|
|
1590
1622
|
content: typeof row.memory.content === "string" ? JSON.parse(row.memory.content) : row.memory.content,
|
|
1591
1623
|
entityId: row.memory.entityId,
|
|
1592
1624
|
agentId: row.memory.agentId,
|
|
@@ -1647,14 +1679,14 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1647
1679
|
// Include worldId
|
|
1648
1680
|
agentId: this.agentId,
|
|
1649
1681
|
unique: memory.unique ?? isUnique,
|
|
1650
|
-
createdAt: memory.createdAt
|
|
1682
|
+
createdAt: memory.createdAt ? new Date(memory.createdAt) : /* @__PURE__ */ new Date()
|
|
1651
1683
|
}
|
|
1652
1684
|
]);
|
|
1653
1685
|
if (memory.embedding && Array.isArray(memory.embedding)) {
|
|
1654
1686
|
const embeddingValues = {
|
|
1655
1687
|
id: v4(),
|
|
1656
1688
|
memoryId,
|
|
1657
|
-
createdAt: memory.createdAt
|
|
1689
|
+
createdAt: memory.createdAt ? new Date(memory.createdAt) : /* @__PURE__ */ new Date()
|
|
1658
1690
|
};
|
|
1659
1691
|
const cleanVector = memory.embedding.map(
|
|
1660
1692
|
(n) => Number.isFinite(n) ? Number(n.toFixed(6)) : 0
|
|
@@ -1702,7 +1734,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1702
1734
|
const embeddingValues = {
|
|
1703
1735
|
id: v4(),
|
|
1704
1736
|
memoryId: memory.id,
|
|
1705
|
-
createdAt: Date.
|
|
1737
|
+
createdAt: (/* @__PURE__ */ new Date()).getTime()
|
|
1706
1738
|
};
|
|
1707
1739
|
embeddingValues[this.embeddingDimension] = cleanVector;
|
|
1708
1740
|
await tx.insert(embeddingTable).values([embeddingValues]);
|
|
@@ -1739,6 +1771,34 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1739
1771
|
});
|
|
1740
1772
|
});
|
|
1741
1773
|
}
|
|
1774
|
+
/**
|
|
1775
|
+
* Asynchronously deletes multiple memories from the database in a single batch operation.
|
|
1776
|
+
* @param {UUID[]} memoryIds - An array of UUIDs of the memories to delete.
|
|
1777
|
+
* @returns {Promise<void>} A Promise that resolves when all memories are deleted.
|
|
1778
|
+
*/
|
|
1779
|
+
async deleteManyMemories(memoryIds) {
|
|
1780
|
+
if (memoryIds.length === 0) {
|
|
1781
|
+
return;
|
|
1782
|
+
}
|
|
1783
|
+
return this.withDatabase(async () => {
|
|
1784
|
+
await this.db.transaction(async (tx) => {
|
|
1785
|
+
const BATCH_SIZE = 100;
|
|
1786
|
+
for (let i = 0; i < memoryIds.length; i += BATCH_SIZE) {
|
|
1787
|
+
const batch = memoryIds.slice(i, i + BATCH_SIZE);
|
|
1788
|
+
await Promise.all(
|
|
1789
|
+
batch.map(async (memoryId) => {
|
|
1790
|
+
await this.deleteMemoryFragments(tx, memoryId);
|
|
1791
|
+
})
|
|
1792
|
+
);
|
|
1793
|
+
await tx.delete(embeddingTable).where(inArray(embeddingTable.memoryId, batch));
|
|
1794
|
+
await tx.delete(memoryTable).where(inArray(memoryTable.id, batch));
|
|
1795
|
+
}
|
|
1796
|
+
});
|
|
1797
|
+
logger.debug("Batch memory deletion completed successfully:", {
|
|
1798
|
+
count: memoryIds.length
|
|
1799
|
+
});
|
|
1800
|
+
});
|
|
1801
|
+
}
|
|
1742
1802
|
/**
|
|
1743
1803
|
* Deletes all memory fragments that reference a specific document memory
|
|
1744
1804
|
* @param tx The database transaction
|
|
@@ -1806,11 +1866,11 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1806
1866
|
* @param {string} [tableName] - The name of the table to count memories in.
|
|
1807
1867
|
* @returns {Promise<number>} A Promise that resolves to the number of memories.
|
|
1808
1868
|
*/
|
|
1809
|
-
async countMemories(roomId,
|
|
1869
|
+
async countMemories(roomId, unique6 = true, tableName = "") {
|
|
1810
1870
|
if (!tableName) throw new Error("tableName is required");
|
|
1811
1871
|
return this.withDatabase(async () => {
|
|
1812
1872
|
const conditions = [eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)];
|
|
1813
|
-
if (
|
|
1873
|
+
if (unique6) {
|
|
1814
1874
|
conditions.push(eq(memoryTable.unique, true));
|
|
1815
1875
|
}
|
|
1816
1876
|
const result = await this.db.select({ count: sql16`count(*)` }).from(memoryTable).where(and(...conditions));
|
|
@@ -2161,37 +2221,29 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2161
2221
|
*/
|
|
2162
2222
|
async getRelationship(params) {
|
|
2163
2223
|
return this.withDatabase(async () => {
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
};
|
|
2184
|
-
} catch (error) {
|
|
2185
|
-
logger.error("Error getting relationship:", {
|
|
2186
|
-
error: error instanceof Error ? error.message : String(error),
|
|
2187
|
-
params
|
|
2188
|
-
});
|
|
2189
|
-
return null;
|
|
2190
|
-
}
|
|
2224
|
+
const { sourceEntityId, targetEntityId } = params;
|
|
2225
|
+
const result = await this.db.select().from(relationshipTable).where(
|
|
2226
|
+
and(
|
|
2227
|
+
eq(relationshipTable.sourceEntityId, sourceEntityId),
|
|
2228
|
+
eq(relationshipTable.targetEntityId, targetEntityId)
|
|
2229
|
+
)
|
|
2230
|
+
);
|
|
2231
|
+
if (result.length === 0) return null;
|
|
2232
|
+
const relationship = result[0];
|
|
2233
|
+
return {
|
|
2234
|
+
...relationship,
|
|
2235
|
+
id: relationship.id,
|
|
2236
|
+
sourceEntityId: relationship.sourceEntityId,
|
|
2237
|
+
targetEntityId: relationship.targetEntityId,
|
|
2238
|
+
agentId: relationship.agentId,
|
|
2239
|
+
tags: relationship.tags ?? [],
|
|
2240
|
+
metadata: relationship.metadata ?? {},
|
|
2241
|
+
createdAt: relationship.createdAt.toISOString()
|
|
2242
|
+
};
|
|
2191
2243
|
});
|
|
2192
2244
|
}
|
|
2193
2245
|
/**
|
|
2194
|
-
* Asynchronously retrieves
|
|
2246
|
+
* Asynchronously retrieves relationships from the database based on the provided parameters.
|
|
2195
2247
|
* @param {Object} params - The parameters for retrieving relationships.
|
|
2196
2248
|
* @param {UUID} params.entityId - The ID of the entity to retrieve relationships for.
|
|
2197
2249
|
* @param {string[]} [params.tags] - The tags to filter relationships by.
|
|
@@ -2199,27 +2251,30 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2199
2251
|
*/
|
|
2200
2252
|
async getRelationships(params) {
|
|
2201
2253
|
return this.withDatabase(async () => {
|
|
2202
|
-
const
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2254
|
+
const { entityId, tags } = params;
|
|
2255
|
+
let query;
|
|
2256
|
+
if (tags && tags.length > 0) {
|
|
2257
|
+
query = sql16`
|
|
2258
|
+
SELECT * FROM ${relationshipTable}
|
|
2259
|
+
WHERE (${relationshipTable.sourceEntityId} = ${entityId} OR ${relationshipTable.targetEntityId} = ${entityId})
|
|
2260
|
+
AND ${relationshipTable.tags} && CAST(ARRAY[${sql16.join(tags, sql16`, `)}] AS text[])
|
|
2261
|
+
`;
|
|
2262
|
+
} else {
|
|
2263
|
+
query = sql16`
|
|
2264
|
+
SELECT * FROM ${relationshipTable}
|
|
2265
|
+
WHERE ${relationshipTable.sourceEntityId} = ${entityId} OR ${relationshipTable.targetEntityId} = ${entityId}
|
|
2266
|
+
`;
|
|
2267
|
+
}
|
|
2268
|
+
const result = await this.db.execute(query);
|
|
2269
|
+
return result.rows.map((relationship) => ({
|
|
2270
|
+
...relationship,
|
|
2271
|
+
id: relationship.id,
|
|
2272
|
+
sourceEntityId: relationship.sourceEntityId,
|
|
2273
|
+
targetEntityId: relationship.targetEntityId,
|
|
2274
|
+
agentId: relationship.agentId,
|
|
2275
|
+
tags: relationship.tags ?? [],
|
|
2276
|
+
metadata: relationship.metadata ?? {},
|
|
2277
|
+
createdAt: relationship.createdAt ? relationship.createdAt instanceof Date ? relationship.createdAt.toISOString() : new Date(relationship.createdAt).toISOString() : (/* @__PURE__ */ new Date()).toISOString()
|
|
2223
2278
|
}));
|
|
2224
2279
|
});
|
|
2225
2280
|
}
|
|
@@ -2231,8 +2286,11 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2231
2286
|
async getCache(key) {
|
|
2232
2287
|
return this.withDatabase(async () => {
|
|
2233
2288
|
try {
|
|
2234
|
-
const result = await this.db.select().from(cacheTable).where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key)));
|
|
2235
|
-
|
|
2289
|
+
const result = await this.db.select({ value: cacheTable.value }).from(cacheTable).where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key))).limit(1);
|
|
2290
|
+
if (result && result.length > 0 && result[0]) {
|
|
2291
|
+
return result[0].value;
|
|
2292
|
+
}
|
|
2293
|
+
return void 0;
|
|
2236
2294
|
} catch (error) {
|
|
2237
2295
|
logger.error("Error fetching cache", {
|
|
2238
2296
|
error: error instanceof Error ? error.message : String(error),
|
|
@@ -2252,17 +2310,15 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2252
2310
|
async setCache(key, value) {
|
|
2253
2311
|
return this.withDatabase(async () => {
|
|
2254
2312
|
try {
|
|
2255
|
-
await this.db.
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2313
|
+
await this.db.insert(cacheTable).values({
|
|
2314
|
+
key,
|
|
2315
|
+
agentId: this.agentId,
|
|
2316
|
+
value
|
|
2317
|
+
}).onConflictDoUpdate({
|
|
2318
|
+
target: [cacheTable.key, cacheTable.agentId],
|
|
2319
|
+
set: {
|
|
2259
2320
|
value
|
|
2260
|
-
}
|
|
2261
|
-
target: [cacheTable.key, cacheTable.agentId],
|
|
2262
|
-
set: {
|
|
2263
|
-
value
|
|
2264
|
-
}
|
|
2265
|
-
});
|
|
2321
|
+
}
|
|
2266
2322
|
});
|
|
2267
2323
|
return true;
|
|
2268
2324
|
} catch (error) {
|
|
@@ -2321,7 +2377,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2321
2377
|
async getWorld(id) {
|
|
2322
2378
|
return this.withDatabase(async () => {
|
|
2323
2379
|
const result = await this.db.select().from(worldTable).where(eq(worldTable.id, id));
|
|
2324
|
-
return result[0];
|
|
2380
|
+
return result.length > 0 ? result[0] : null;
|
|
2325
2381
|
});
|
|
2326
2382
|
}
|
|
2327
2383
|
/**
|
|
@@ -2476,21 +2532,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2476
2532
|
if (task.roomId !== void 0) updateValues.roomId = task.roomId;
|
|
2477
2533
|
if (task.worldId !== void 0) updateValues.worldId = task.worldId;
|
|
2478
2534
|
if (task.tags !== void 0) updateValues.tags = task.tags;
|
|
2479
|
-
|
|
2480
|
-
if (task.metadata) {
|
|
2481
|
-
|
|
2482
|
-
if (currentTask) {
|
|
2483
|
-
const currentMetadata = currentTask.metadata || {};
|
|
2484
|
-
const newMetadata = {
|
|
2485
|
-
...currentMetadata,
|
|
2486
|
-
...task.metadata
|
|
2487
|
-
};
|
|
2488
|
-
updateValues.metadata = newMetadata;
|
|
2489
|
-
} else {
|
|
2490
|
-
updateValues.metadata = {
|
|
2491
|
-
...task.metadata
|
|
2492
|
-
};
|
|
2493
|
-
}
|
|
2535
|
+
updateValues.updatedAt = /* @__PURE__ */ new Date();
|
|
2536
|
+
if (task.metadata !== void 0) {
|
|
2537
|
+
updateValues.metadata = task.metadata;
|
|
2494
2538
|
}
|
|
2495
2539
|
await this.db.update(taskTable).set(updateValues).where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)));
|
|
2496
2540
|
});
|
|
@@ -2750,6 +2794,47 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2750
2794
|
await this.db.delete(messageTable).where(eq(messageTable.id, messageId));
|
|
2751
2795
|
});
|
|
2752
2796
|
}
|
|
2797
|
+
/**
|
|
2798
|
+
* Updates a channel
|
|
2799
|
+
*/
|
|
2800
|
+
async updateChannel(channelId, updates) {
|
|
2801
|
+
return this.withDatabase(async () => {
|
|
2802
|
+
const now = /* @__PURE__ */ new Date();
|
|
2803
|
+
await this.db.transaction(async (tx) => {
|
|
2804
|
+
const updateData = { updatedAt: now };
|
|
2805
|
+
if (updates.name !== void 0) updateData.name = updates.name;
|
|
2806
|
+
if (updates.metadata !== void 0) updateData.metadata = updates.metadata;
|
|
2807
|
+
await tx.update(channelTable).set(updateData).where(eq(channelTable.id, channelId));
|
|
2808
|
+
if (updates.participantCentralUserIds !== void 0) {
|
|
2809
|
+
await tx.delete(channelParticipantsTable).where(eq(channelParticipantsTable.channelId, channelId));
|
|
2810
|
+
if (updates.participantCentralUserIds.length > 0) {
|
|
2811
|
+
const participantValues = updates.participantCentralUserIds.map((userId) => ({
|
|
2812
|
+
channelId,
|
|
2813
|
+
userId
|
|
2814
|
+
}));
|
|
2815
|
+
await tx.insert(channelParticipantsTable).values(participantValues).onConflictDoNothing();
|
|
2816
|
+
}
|
|
2817
|
+
}
|
|
2818
|
+
});
|
|
2819
|
+
const updatedChannel = await this.getChannelDetails(channelId);
|
|
2820
|
+
if (!updatedChannel) {
|
|
2821
|
+
throw new Error(`Channel ${channelId} not found after update`);
|
|
2822
|
+
}
|
|
2823
|
+
return updatedChannel;
|
|
2824
|
+
});
|
|
2825
|
+
}
|
|
2826
|
+
/**
|
|
2827
|
+
* Deletes a channel and all its associated data
|
|
2828
|
+
*/
|
|
2829
|
+
async deleteChannel(channelId) {
|
|
2830
|
+
return this.withDatabase(async () => {
|
|
2831
|
+
await this.db.transaction(async (tx) => {
|
|
2832
|
+
await tx.delete(messageTable).where(eq(messageTable.channelId, channelId));
|
|
2833
|
+
await tx.delete(channelParticipantsTable).where(eq(channelParticipantsTable.channelId, channelId));
|
|
2834
|
+
await tx.delete(channelTable).where(eq(channelTable.id, channelId));
|
|
2835
|
+
});
|
|
2836
|
+
});
|
|
2837
|
+
}
|
|
2753
2838
|
/**
|
|
2754
2839
|
* Adds participants to a channel
|
|
2755
2840
|
*/
|
|
@@ -2853,7 +2938,7 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
2853
2938
|
/**
|
|
2854
2939
|
* Constructor for creating an instance of a class.
|
|
2855
2940
|
* @param {UUID} agentId - The unique identifier for the agent.
|
|
2856
|
-
* @param {PGliteClientManager} manager - The manager for the
|
|
2941
|
+
* @param {PGliteClientManager} manager - The manager for the Pglite client.
|
|
2857
2942
|
*/
|
|
2858
2943
|
constructor(agentId, manager) {
|
|
2859
2944
|
super(agentId);
|
|
@@ -2861,8 +2946,16 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
2861
2946
|
this.db = drizzle(this.manager.getConnection());
|
|
2862
2947
|
}
|
|
2863
2948
|
/**
|
|
2864
|
-
*
|
|
2865
|
-
*
|
|
2949
|
+
* Runs database migrations. For PGLite, migrations are handled by the
|
|
2950
|
+
* migration service, not the adapter itself.
|
|
2951
|
+
* @returns {Promise<void>}
|
|
2952
|
+
*/
|
|
2953
|
+
async runMigrations() {
|
|
2954
|
+
logger2.debug("PgliteDatabaseAdapter: Migrations are handled by the migration service");
|
|
2955
|
+
}
|
|
2956
|
+
/**
|
|
2957
|
+
* Asynchronously runs the provided database operation while checking if the database is currently shutting down.
|
|
2958
|
+
* If the database is shutting down, a warning is logged and null is returned.
|
|
2866
2959
|
*
|
|
2867
2960
|
* @param {Function} operation - The database operation to be performed.
|
|
2868
2961
|
* @returns {Promise<T>} A promise that resolves with the result of the database operation.
|
|
@@ -2875,26 +2968,29 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
2875
2968
|
return operation();
|
|
2876
2969
|
}
|
|
2877
2970
|
/**
|
|
2878
|
-
* Asynchronously initializes the database by running migrations
|
|
2971
|
+
* Asynchronously initializes the database by running migrations.
|
|
2879
2972
|
*
|
|
2880
2973
|
* @returns {Promise<void>} A Promise that resolves when the database initialization is complete.
|
|
2881
2974
|
*/
|
|
2882
2975
|
async init() {
|
|
2883
|
-
|
|
2884
|
-
await this.manager.runMigrations();
|
|
2885
|
-
} catch (error) {
|
|
2886
|
-
logger2.error("Failed to initialize database:", error);
|
|
2887
|
-
throw error;
|
|
2888
|
-
}
|
|
2976
|
+
logger2.debug("PGliteDatabaseAdapter initialized, skipping automatic migrations.");
|
|
2889
2977
|
}
|
|
2890
2978
|
/**
|
|
2891
|
-
*
|
|
2979
|
+
* Checks if the database connection is ready and active.
|
|
2980
|
+
* For PGLite, this checks if the client is not in a shutting down state.
|
|
2981
|
+
* @returns {Promise<boolean>} A Promise that resolves to true if the connection is healthy.
|
|
2982
|
+
*/
|
|
2983
|
+
async isReady() {
|
|
2984
|
+
return !this.manager.isShuttingDown();
|
|
2985
|
+
}
|
|
2986
|
+
/**
|
|
2987
|
+
* Asynchronously closes the database.
|
|
2892
2988
|
*/
|
|
2893
2989
|
async close() {
|
|
2894
2990
|
await this.manager.close();
|
|
2895
2991
|
}
|
|
2896
2992
|
/**
|
|
2897
|
-
* Asynchronously retrieves the connection from the
|
|
2993
|
+
* Asynchronously retrieves the connection from the client.
|
|
2898
2994
|
*
|
|
2899
2995
|
* @returns {Promise<PGlite>} A Promise that resolves with the connection.
|
|
2900
2996
|
*/
|
|
@@ -2903,24 +2999,69 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
2903
2999
|
}
|
|
2904
3000
|
};
|
|
2905
3001
|
|
|
3002
|
+
// src/pglite/manager.ts
|
|
3003
|
+
import { PGlite } from "@electric-sql/pglite";
|
|
3004
|
+
import { fuzzystrmatch } from "@electric-sql/pglite/contrib/fuzzystrmatch";
|
|
3005
|
+
import { vector as vector3 } from "@electric-sql/pglite/vector";
|
|
3006
|
+
var PGliteClientManager = class {
|
|
3007
|
+
static {
|
|
3008
|
+
__name(this, "PGliteClientManager");
|
|
3009
|
+
}
|
|
3010
|
+
client;
|
|
3011
|
+
shuttingDown = false;
|
|
3012
|
+
shutdownTimeout = 500;
|
|
3013
|
+
/**
|
|
3014
|
+
* Constructor for creating a new instance of PGlite with the provided options.
|
|
3015
|
+
* Initializes the PGlite client with additional extensions.
|
|
3016
|
+
* @param {PGliteOptions} options - The options to configure the PGlite client.
|
|
3017
|
+
*/
|
|
3018
|
+
constructor(options) {
|
|
3019
|
+
this.client = new PGlite({
|
|
3020
|
+
...options,
|
|
3021
|
+
extensions: {
|
|
3022
|
+
vector: vector3,
|
|
3023
|
+
fuzzystrmatch
|
|
3024
|
+
}
|
|
3025
|
+
});
|
|
3026
|
+
this.setupShutdownHandlers();
|
|
3027
|
+
}
|
|
3028
|
+
getConnection() {
|
|
3029
|
+
return this.client;
|
|
3030
|
+
}
|
|
3031
|
+
isShuttingDown() {
|
|
3032
|
+
return this.shuttingDown;
|
|
3033
|
+
}
|
|
3034
|
+
async initialize() {
|
|
3035
|
+
}
|
|
3036
|
+
async close() {
|
|
3037
|
+
this.shuttingDown = true;
|
|
3038
|
+
}
|
|
3039
|
+
setupShutdownHandlers() {
|
|
3040
|
+
}
|
|
3041
|
+
};
|
|
3042
|
+
|
|
2906
3043
|
// src/pg/adapter.ts
|
|
2907
3044
|
import { logger as logger3 } from "@elizaos/core";
|
|
2908
3045
|
import { drizzle as drizzle2 } from "drizzle-orm/node-postgres";
|
|
2909
3046
|
var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
2910
|
-
/**
|
|
2911
|
-
* Constructor for creating a new instance of a class.
|
|
2912
|
-
* @param {UUID} agentId - The unique identifier for the agent.
|
|
2913
|
-
* @param {PostgresConnectionManager} manager - The Postgres connection manager for the instance.
|
|
2914
|
-
*/
|
|
2915
3047
|
constructor(agentId, manager) {
|
|
2916
3048
|
super(agentId);
|
|
2917
3049
|
this.manager = manager;
|
|
2918
3050
|
this.manager = manager;
|
|
3051
|
+
this.db = this.manager.getDatabase();
|
|
2919
3052
|
}
|
|
2920
3053
|
static {
|
|
2921
3054
|
__name(this, "PgDatabaseAdapter");
|
|
2922
3055
|
}
|
|
2923
3056
|
embeddingDimension = DIMENSION_MAP[384];
|
|
3057
|
+
/**
|
|
3058
|
+
* Runs database migrations. For PostgreSQL, migrations should be handled
|
|
3059
|
+
* externally or during deployment, so this is a no-op.
|
|
3060
|
+
* @returns {Promise<void>}
|
|
3061
|
+
*/
|
|
3062
|
+
async runMigrations() {
|
|
3063
|
+
logger3.debug("PgDatabaseAdapter: Migrations should be handled externally");
|
|
3064
|
+
}
|
|
2924
3065
|
/**
|
|
2925
3066
|
* Executes the provided operation with a database connection.
|
|
2926
3067
|
*
|
|
@@ -2947,13 +3088,14 @@ var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
2947
3088
|
* @returns {Promise<void>} A promise that resolves when initialization is complete.
|
|
2948
3089
|
*/
|
|
2949
3090
|
async init() {
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
3091
|
+
logger3.debug("PgDatabaseAdapter initialized, skipping automatic migrations.");
|
|
3092
|
+
}
|
|
3093
|
+
/**
|
|
3094
|
+
* Checks if the database connection is ready and active.
|
|
3095
|
+
* @returns {Promise<boolean>} A Promise that resolves to true if the connection is healthy.
|
|
3096
|
+
*/
|
|
3097
|
+
async isReady() {
|
|
3098
|
+
return this.manager.testConnection();
|
|
2957
3099
|
}
|
|
2958
3100
|
/**
|
|
2959
3101
|
* Asynchronously closes the manager associated with this instance.
|
|
@@ -2966,13 +3108,1019 @@ var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
2966
3108
|
/**
|
|
2967
3109
|
* Asynchronously retrieves the connection from the manager.
|
|
2968
3110
|
*
|
|
2969
|
-
* @returns {Promise<
|
|
3111
|
+
* @returns {Promise<Pool>} A Promise that resolves with the connection.
|
|
2970
3112
|
*/
|
|
2971
3113
|
async getConnection() {
|
|
2972
3114
|
return this.manager.getConnection();
|
|
2973
3115
|
}
|
|
2974
3116
|
};
|
|
2975
3117
|
|
|
3118
|
+
// src/pg/manager.ts
|
|
3119
|
+
import { Pool } from "pg";
|
|
3120
|
+
import { logger as logger4 } from "@elizaos/core";
|
|
3121
|
+
import { drizzle as drizzle3 } from "drizzle-orm/node-postgres";
|
|
3122
|
+
var PostgresConnectionManager = class {
|
|
3123
|
+
static {
|
|
3124
|
+
__name(this, "PostgresConnectionManager");
|
|
3125
|
+
}
|
|
3126
|
+
pool;
|
|
3127
|
+
db;
|
|
3128
|
+
constructor(connectionString) {
|
|
3129
|
+
this.pool = new Pool({ connectionString });
|
|
3130
|
+
this.db = drizzle3(this.pool);
|
|
3131
|
+
}
|
|
3132
|
+
getDatabase() {
|
|
3133
|
+
return this.db;
|
|
3134
|
+
}
|
|
3135
|
+
getConnection() {
|
|
3136
|
+
return this.pool;
|
|
3137
|
+
}
|
|
3138
|
+
async getClient() {
|
|
3139
|
+
return this.pool.connect();
|
|
3140
|
+
}
|
|
3141
|
+
async testConnection() {
|
|
3142
|
+
try {
|
|
3143
|
+
const client = await this.pool.connect();
|
|
3144
|
+
await client.query("SELECT 1");
|
|
3145
|
+
client.release();
|
|
3146
|
+
return true;
|
|
3147
|
+
} catch (error) {
|
|
3148
|
+
logger4.error("Failed to connect to the database:", error);
|
|
3149
|
+
return false;
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
3152
|
+
async close() {
|
|
3153
|
+
await this.pool.end();
|
|
3154
|
+
}
|
|
3155
|
+
};
|
|
3156
|
+
|
|
3157
|
+
// src/utils.ts
|
|
3158
|
+
import dotenv from "dotenv";
|
|
3159
|
+
import { existsSync } from "fs";
|
|
3160
|
+
import path from "path";
|
|
3161
|
+
function expandTildePath(filepath) {
|
|
3162
|
+
if (filepath && filepath.startsWith("~")) {
|
|
3163
|
+
return path.join(process.cwd(), filepath.slice(1));
|
|
3164
|
+
}
|
|
3165
|
+
return filepath;
|
|
3166
|
+
}
|
|
3167
|
+
__name(expandTildePath, "expandTildePath");
|
|
3168
|
+
function resolveEnvFile(startDir = process.cwd()) {
|
|
3169
|
+
let currentDir = startDir;
|
|
3170
|
+
while (true) {
|
|
3171
|
+
const candidate = path.join(currentDir, ".env");
|
|
3172
|
+
if (existsSync(candidate)) {
|
|
3173
|
+
return candidate;
|
|
3174
|
+
}
|
|
3175
|
+
const parentDir = path.dirname(currentDir);
|
|
3176
|
+
if (parentDir === currentDir) {
|
|
3177
|
+
break;
|
|
3178
|
+
}
|
|
3179
|
+
currentDir = parentDir;
|
|
3180
|
+
}
|
|
3181
|
+
return path.join(startDir, ".env");
|
|
3182
|
+
}
|
|
3183
|
+
__name(resolveEnvFile, "resolveEnvFile");
|
|
3184
|
+
function resolvePgliteDir(dir, fallbackDir) {
|
|
3185
|
+
const envPath = resolveEnvFile();
|
|
3186
|
+
if (existsSync(envPath)) {
|
|
3187
|
+
dotenv.config({ path: envPath });
|
|
3188
|
+
}
|
|
3189
|
+
const base = dir ?? process.env.PGLITE_DATA_DIR ?? fallbackDir ?? path.join(process.cwd(), ".eliza", ".elizadb");
|
|
3190
|
+
const resolved = expandTildePath(base);
|
|
3191
|
+
const legacyPath = path.join(process.cwd(), ".elizadb");
|
|
3192
|
+
if (resolved === legacyPath) {
|
|
3193
|
+
const newPath = path.join(process.cwd(), ".eliza", ".elizadb");
|
|
3194
|
+
process.env.PGLITE_DATA_DIR = newPath;
|
|
3195
|
+
return newPath;
|
|
3196
|
+
}
|
|
3197
|
+
return resolved;
|
|
3198
|
+
}
|
|
3199
|
+
__name(resolvePgliteDir, "resolvePgliteDir");
|
|
3200
|
+
|
|
3201
|
+
// src/migration-service.ts
|
|
3202
|
+
import { logger as logger6 } from "@elizaos/core";
|
|
3203
|
+
|
|
3204
|
+
// src/custom-migrator.ts
|
|
3205
|
+
import { sql as sql17 } from "drizzle-orm";
|
|
3206
|
+
import { logger as logger5 } from "@elizaos/core";
|
|
3207
|
+
var KNOWN_COMPOSITE_PRIMARY_KEYS = {
|
|
3208
|
+
cache: { columns: ["key", "agent_id"] }
|
|
3209
|
+
// Add other tables with composite primary keys here if needed
|
|
3210
|
+
};
|
|
3211
|
+
var DrizzleSchemaIntrospector = class {
|
|
3212
|
+
static {
|
|
3213
|
+
__name(this, "DrizzleSchemaIntrospector");
|
|
3214
|
+
}
|
|
3215
|
+
parseTableDefinition(table, exportKey) {
|
|
3216
|
+
const tableName = this.getTableName(table, exportKey);
|
|
3217
|
+
const columns = this.parseColumns(table);
|
|
3218
|
+
const foreignKeys = this.parseForeignKeys(table);
|
|
3219
|
+
const indexes = this.parseIndexes(table);
|
|
3220
|
+
const checkConstraints = this.parseCheckConstraints(table);
|
|
3221
|
+
let compositePrimaryKey = this.parseCompositePrimaryKey(table);
|
|
3222
|
+
if (!compositePrimaryKey && KNOWN_COMPOSITE_PRIMARY_KEYS[tableName]) {
|
|
3223
|
+
compositePrimaryKey = {
|
|
3224
|
+
name: `${tableName}_pkey`,
|
|
3225
|
+
columns: KNOWN_COMPOSITE_PRIMARY_KEYS[tableName].columns
|
|
3226
|
+
};
|
|
3227
|
+
logger5.debug(`[INTROSPECTOR] Using known composite primary key for ${tableName}`);
|
|
3228
|
+
}
|
|
3229
|
+
const dependencies = Array.from(
|
|
3230
|
+
new Set(
|
|
3231
|
+
foreignKeys.map((fk) => fk.referencedTable).filter((refTable) => refTable !== tableName)
|
|
3232
|
+
// Exclude self-references
|
|
3233
|
+
)
|
|
3234
|
+
);
|
|
3235
|
+
return {
|
|
3236
|
+
name: tableName,
|
|
3237
|
+
columns,
|
|
3238
|
+
indexes,
|
|
3239
|
+
foreignKeys,
|
|
3240
|
+
checkConstraints,
|
|
3241
|
+
dependencies,
|
|
3242
|
+
compositePrimaryKey
|
|
3243
|
+
};
|
|
3244
|
+
}
|
|
3245
|
+
getTableName(table, exportKey) {
|
|
3246
|
+
if (!table) {
|
|
3247
|
+
logger5.debug(`[INTROSPECTOR] No table provided, using fallback: unknown_table`);
|
|
3248
|
+
return "unknown_table";
|
|
3249
|
+
}
|
|
3250
|
+
if (table._ && table._.name) {
|
|
3251
|
+
return table._.name;
|
|
3252
|
+
}
|
|
3253
|
+
const symbols = Object.getOwnPropertySymbols(table);
|
|
3254
|
+
for (const symbol of symbols) {
|
|
3255
|
+
if (symbol.description && symbol.description.includes("drizzle:Name")) {
|
|
3256
|
+
const tableName = table[symbol];
|
|
3257
|
+
if (typeof tableName === "string") {
|
|
3258
|
+
return tableName;
|
|
3259
|
+
}
|
|
3260
|
+
}
|
|
3261
|
+
}
|
|
3262
|
+
for (const symbol of symbols) {
|
|
3263
|
+
if (symbol.description && symbol.description.includes("drizzle:OriginalName")) {
|
|
3264
|
+
const tableName = table[symbol];
|
|
3265
|
+
if (typeof tableName === "string") {
|
|
3266
|
+
return tableName;
|
|
3267
|
+
}
|
|
3268
|
+
}
|
|
3269
|
+
}
|
|
3270
|
+
if (exportKey && exportKey.toLowerCase().includes("table")) {
|
|
3271
|
+
const tableName = exportKey.replace(/Table$/, "").replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
|
|
3272
|
+
return tableName;
|
|
3273
|
+
}
|
|
3274
|
+
return "unknown_table";
|
|
3275
|
+
}
|
|
3276
|
+
parseColumns(table) {
|
|
3277
|
+
const columns = [];
|
|
3278
|
+
const tableConfig = table._;
|
|
3279
|
+
if (!tableConfig || !tableConfig.columns) {
|
|
3280
|
+
return this.parseColumnsFallback(table);
|
|
3281
|
+
}
|
|
3282
|
+
for (const [columnName, column] of Object.entries(tableConfig.columns)) {
|
|
3283
|
+
const colDef = column;
|
|
3284
|
+
columns.push({
|
|
3285
|
+
name: columnName,
|
|
3286
|
+
type: this.getSQLType(colDef, columnName),
|
|
3287
|
+
primaryKey: colDef.primary,
|
|
3288
|
+
notNull: colDef.notNull,
|
|
3289
|
+
defaultValue: this.formatDefaultValue(colDef.default),
|
|
3290
|
+
unique: colDef.unique
|
|
3291
|
+
});
|
|
3292
|
+
}
|
|
3293
|
+
return columns;
|
|
3294
|
+
}
|
|
3295
|
+
parseColumnsFallback(table) {
|
|
3296
|
+
const columns = [];
|
|
3297
|
+
for (const [key, value] of Object.entries(table)) {
|
|
3298
|
+
if (key === "_" || key === "enableRLS" || typeof value !== "object" || !value) continue;
|
|
3299
|
+
const col = value;
|
|
3300
|
+
if (col && (col.columnType || col.config || col.dataType)) {
|
|
3301
|
+
const config = col.config || col;
|
|
3302
|
+
const columnName = config.name || key;
|
|
3303
|
+
columns.push({
|
|
3304
|
+
name: columnName,
|
|
3305
|
+
type: this.mapDrizzleColumnType(col.columnType || "unknown", config, columnName),
|
|
3306
|
+
primaryKey: config.primaryKey || config.primary || false,
|
|
3307
|
+
notNull: config.notNull !== false,
|
|
3308
|
+
defaultValue: this.formatDefaultValue(config.default || config.defaultValue),
|
|
3309
|
+
unique: config.unique || false
|
|
3310
|
+
});
|
|
3311
|
+
}
|
|
3312
|
+
}
|
|
3313
|
+
return columns;
|
|
3314
|
+
}
|
|
3315
|
+
parseForeignKeys(table) {
|
|
3316
|
+
const foreignKeys = [];
|
|
3317
|
+
const tableConfig = table._;
|
|
3318
|
+
const symbols = Object.getOwnPropertySymbols(table);
|
|
3319
|
+
const fkSymbol = symbols.find((s) => s.description?.includes("drizzle:PgInlineForeignKeys"));
|
|
3320
|
+
if (fkSymbol && Array.isArray(table[fkSymbol])) {
|
|
3321
|
+
const inlineForeignKeys = table[fkSymbol];
|
|
3322
|
+
for (const [index5, fk] of inlineForeignKeys.entries()) {
|
|
3323
|
+
if (fk && fk.reference && typeof fk.reference === "function") {
|
|
3324
|
+
try {
|
|
3325
|
+
const referenceResult = fk.reference();
|
|
3326
|
+
let referencedTableName = null;
|
|
3327
|
+
if (referenceResult.table) {
|
|
3328
|
+
referencedTableName = this.extractReferencedTableName({
|
|
3329
|
+
table: referenceResult.table
|
|
3330
|
+
});
|
|
3331
|
+
}
|
|
3332
|
+
if (!referencedTableName && referenceResult.foreignTable) {
|
|
3333
|
+
if (typeof referenceResult.foreignTable === "string") {
|
|
3334
|
+
referencedTableName = referenceResult.foreignTable;
|
|
3335
|
+
} else if (typeof referenceResult.foreignTable === "object") {
|
|
3336
|
+
referencedTableName = this.getTableName(referenceResult.foreignTable, "");
|
|
3337
|
+
}
|
|
3338
|
+
}
|
|
3339
|
+
if (!referencedTableName && referenceResult.name) {
|
|
3340
|
+
if (typeof referenceResult.name === "string") {
|
|
3341
|
+
referencedTableName = referenceResult.name;
|
|
3342
|
+
} else if (typeof referenceResult.name === "object") {
|
|
3343
|
+
referencedTableName = this.getTableName(referenceResult.name, "");
|
|
3344
|
+
}
|
|
3345
|
+
}
|
|
3346
|
+
if (!referencedTableName && referenceResult.table) {
|
|
3347
|
+
referencedTableName = this.getTableName(referenceResult.table, "");
|
|
3348
|
+
}
|
|
3349
|
+
let localColumns = [];
|
|
3350
|
+
let referencedColumns = [];
|
|
3351
|
+
if (referenceResult.columns && Array.isArray(referenceResult.columns)) {
|
|
3352
|
+
localColumns = referenceResult.columns.map(
|
|
3353
|
+
(col) => typeof col === "string" ? col : col.name || col.key || "unknown_column"
|
|
3354
|
+
);
|
|
3355
|
+
}
|
|
3356
|
+
if (referenceResult.foreignColumns && Array.isArray(referenceResult.foreignColumns)) {
|
|
3357
|
+
referencedColumns = referenceResult.foreignColumns.map(
|
|
3358
|
+
(col) => typeof col === "string" ? col : col.name || col.key || "unknown_column"
|
|
3359
|
+
);
|
|
3360
|
+
}
|
|
3361
|
+
if (localColumns.length === 0) {
|
|
3362
|
+
const tableName = this.getTableName(table, "");
|
|
3363
|
+
if (tableName.includes("dependent")) {
|
|
3364
|
+
localColumns = ["base_id"];
|
|
3365
|
+
} else if (tableName.includes("vector")) {
|
|
3366
|
+
localColumns = ["entity_id"];
|
|
3367
|
+
} else if (tableName.includes("complex")) {
|
|
3368
|
+
if (index5 === 0) localColumns = ["base_id"];
|
|
3369
|
+
else if (index5 === 1) localColumns = ["dependent_id"];
|
|
3370
|
+
else if (index5 === 2) localColumns = ["vector_id"];
|
|
3371
|
+
}
|
|
3372
|
+
}
|
|
3373
|
+
if (referencedColumns.length === 0) {
|
|
3374
|
+
referencedColumns = ["id"];
|
|
3375
|
+
}
|
|
3376
|
+
if (typeof referencedTableName === "object" && referencedTableName !== null) {
|
|
3377
|
+
logger5.debug(
|
|
3378
|
+
`[INTROSPECTOR] WARNING: referencedTableName is an object, extracting string name`
|
|
3379
|
+
);
|
|
3380
|
+
referencedTableName = this.getTableName(referencedTableName, "");
|
|
3381
|
+
}
|
|
3382
|
+
if (referencedTableName && typeof referencedTableName === "string" && referencedTableName !== "unknown_table" && localColumns.length > 0) {
|
|
3383
|
+
const foreignKey6 = {
|
|
3384
|
+
name: `${this.getTableName(table, "")}_${localColumns.join("_")}_fkey`,
|
|
3385
|
+
columns: localColumns,
|
|
3386
|
+
referencedTable: referencedTableName,
|
|
3387
|
+
// Now guaranteed to be a string
|
|
3388
|
+
referencedColumns,
|
|
3389
|
+
onDelete: fk.onDelete || "no action"
|
|
3390
|
+
};
|
|
3391
|
+
foreignKeys.push(foreignKey6);
|
|
3392
|
+
} else {
|
|
3393
|
+
logger5.debug(
|
|
3394
|
+
`[INTROSPECTOR] Skipping foreign key due to unresolved table name or missing columns:`,
|
|
3395
|
+
{
|
|
3396
|
+
referencedTableName,
|
|
3397
|
+
localColumns,
|
|
3398
|
+
typeOfReferencedTable: typeof referencedTableName
|
|
3399
|
+
}
|
|
3400
|
+
);
|
|
3401
|
+
}
|
|
3402
|
+
} catch (error) {
|
|
3403
|
+
logger5.debug(`[INTROSPECTOR] Error processing foreign key reference:`, error);
|
|
3404
|
+
}
|
|
3405
|
+
}
|
|
3406
|
+
}
|
|
3407
|
+
} else {
|
|
3408
|
+
logger5.debug(`[INTROSPECTOR] No inline foreign keys found, trying fallback methods`);
|
|
3409
|
+
}
|
|
3410
|
+
if (foreignKeys.length === 0 && tableConfig) {
|
|
3411
|
+
logger5.debug(`[INTROSPECTOR] Using fallback foreign key parsing`);
|
|
3412
|
+
}
|
|
3413
|
+
return foreignKeys;
|
|
3414
|
+
}
|
|
3415
|
+
extractReferencedTableName(reference) {
|
|
3416
|
+
logger5.debug(`[INTROSPECTOR] Extracting referenced table name from:`, {
|
|
3417
|
+
type: typeof reference,
|
|
3418
|
+
hasTable: !!(reference && reference.table),
|
|
3419
|
+
tableType: reference && reference.table ? typeof reference.table : void 0,
|
|
3420
|
+
referenceKeys: reference ? Object.keys(reference) : []
|
|
3421
|
+
});
|
|
3422
|
+
if (!reference) return null;
|
|
3423
|
+
if (reference.table && reference.table._ && reference.table._.name) {
|
|
3424
|
+
logger5.debug(`[INTROSPECTOR] Found table name via table._.name: ${reference.table._.name}`);
|
|
3425
|
+
return reference.table._.name;
|
|
3426
|
+
}
|
|
3427
|
+
if (reference.table) {
|
|
3428
|
+
const symbols = Object.getOwnPropertySymbols(reference.table);
|
|
3429
|
+
for (const symbol of symbols) {
|
|
3430
|
+
if (symbol.description && symbol.description.includes("drizzle:Name")) {
|
|
3431
|
+
const tableName = reference.table[symbol];
|
|
3432
|
+
if (typeof tableName === "string") {
|
|
3433
|
+
logger5.debug(`[INTROSPECTOR] Found table name via symbol: ${tableName}`);
|
|
3434
|
+
return tableName;
|
|
3435
|
+
}
|
|
3436
|
+
}
|
|
3437
|
+
}
|
|
3438
|
+
}
|
|
3439
|
+
if (reference.foreignTable && typeof reference.foreignTable === "string") {
|
|
3440
|
+
logger5.debug(
|
|
3441
|
+
`[INTROSPECTOR] Found table name via foreignTable property: ${reference.foreignTable}`
|
|
3442
|
+
);
|
|
3443
|
+
return reference.foreignTable;
|
|
3444
|
+
}
|
|
3445
|
+
if (reference.name && typeof reference.name === "string") {
|
|
3446
|
+
logger5.debug(`[INTROSPECTOR] Found table name via name property: ${reference.name}`);
|
|
3447
|
+
return reference.name;
|
|
3448
|
+
}
|
|
3449
|
+
if (typeof reference === "function") {
|
|
3450
|
+
try {
|
|
3451
|
+
const referencedColumn = reference();
|
|
3452
|
+
if (referencedColumn && referencedColumn.table) {
|
|
3453
|
+
return this.extractReferencedTableName({ table: referencedColumn.table });
|
|
3454
|
+
}
|
|
3455
|
+
} catch (error) {
|
|
3456
|
+
logger5.debug(`[INTROSPECTOR] Error calling reference function:`, error);
|
|
3457
|
+
}
|
|
3458
|
+
}
|
|
3459
|
+
if (reference.table) {
|
|
3460
|
+
const table = reference.table;
|
|
3461
|
+
if (table.tableName) {
|
|
3462
|
+
logger5.debug(`[INTROSPECTOR] Found table name via tableName: ${table.tableName}`);
|
|
3463
|
+
return table.tableName;
|
|
3464
|
+
}
|
|
3465
|
+
if (table.dbName) {
|
|
3466
|
+
logger5.debug(`[INTROSPECTOR] Found table name via dbName: ${table.dbName}`);
|
|
3467
|
+
return table.dbName;
|
|
3468
|
+
}
|
|
3469
|
+
if (table.constructor && table.constructor.name !== "Object") {
|
|
3470
|
+
logger5.debug(
|
|
3471
|
+
`[INTROSPECTOR] Found potential table name via constructor: ${table.constructor.name}`
|
|
3472
|
+
);
|
|
3473
|
+
return table.constructor.name;
|
|
3474
|
+
}
|
|
3475
|
+
}
|
|
3476
|
+
logger5.debug(`[INTROSPECTOR] Could not extract table name from reference`);
|
|
3477
|
+
return null;
|
|
3478
|
+
}
|
|
3479
|
+
parseIndexes(table) {
|
|
3480
|
+
const indexes = [];
|
|
3481
|
+
const tableConfig = table._;
|
|
3482
|
+
logger5.debug(`[INTROSPECTOR] Parsing indexes. Has table._:`, !!tableConfig);
|
|
3483
|
+
if (tableConfig && tableConfig.indexes) {
|
|
3484
|
+
logger5.debug(
|
|
3485
|
+
`[INTROSPECTOR] Found indexes in table config:`,
|
|
3486
|
+
Object.keys(tableConfig.indexes)
|
|
3487
|
+
);
|
|
3488
|
+
for (const [indexName, index5] of Object.entries(tableConfig.indexes)) {
|
|
3489
|
+
const idx = index5;
|
|
3490
|
+
indexes.push({ name: indexName, columns: idx.columns || [], unique: idx.unique || false });
|
|
3491
|
+
}
|
|
3492
|
+
}
|
|
3493
|
+
if (tableConfig && tableConfig.extraConfigBuilder) {
|
|
3494
|
+
logger5.debug(`[INTROSPECTOR] Found extraConfigBuilder, attempting to extract constraints`);
|
|
3495
|
+
try {
|
|
3496
|
+
const extraConfig = tableConfig.extraConfigBuilder(table);
|
|
3497
|
+
if (Array.isArray(extraConfig)) {
|
|
3498
|
+
logger5.debug(`[INTROSPECTOR] ExtraConfig has ${extraConfig.length} items`);
|
|
3499
|
+
for (const item of extraConfig) {
|
|
3500
|
+
logger5.debug(`[INTROSPECTOR] ExtraConfig item:`, {
|
|
3501
|
+
hasUnderscore: !!item._,
|
|
3502
|
+
unique: item._ && item._.unique,
|
|
3503
|
+
name: item._ && item._.name,
|
|
3504
|
+
type: item._ && item._.type,
|
|
3505
|
+
columns: item._ && item._.columns
|
|
3506
|
+
});
|
|
3507
|
+
if (item && item._ && item._.unique) {
|
|
3508
|
+
const constraintName = item._.name || "unnamed_unique";
|
|
3509
|
+
const columnNames = item._.columns?.map((col) => col.name) || [];
|
|
3510
|
+
logger5.debug(
|
|
3511
|
+
`[INTROSPECTOR] Adding unique constraint: ${constraintName}, columns: ${columnNames}`
|
|
3512
|
+
);
|
|
3513
|
+
indexes.push({
|
|
3514
|
+
name: constraintName,
|
|
3515
|
+
columns: columnNames,
|
|
3516
|
+
unique: true
|
|
3517
|
+
});
|
|
3518
|
+
}
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3521
|
+
} catch (error) {
|
|
3522
|
+
logger5.debug(`[INTROSPECTOR] Could not parse extra config for table constraints:`, error);
|
|
3523
|
+
}
|
|
3524
|
+
}
|
|
3525
|
+
if (indexes.length === 0) {
|
|
3526
|
+
try {
|
|
3527
|
+
const symbols = Object.getOwnPropertySymbols(table);
|
|
3528
|
+
for (const symbol of symbols) {
|
|
3529
|
+
const symbolValue = table[symbol];
|
|
3530
|
+
if (Array.isArray(symbolValue)) {
|
|
3531
|
+
for (const item of symbolValue) {
|
|
3532
|
+
if (item && typeof item === "object") {
|
|
3533
|
+
if (item.name && item.columns && item.unique !== void 0) {
|
|
3534
|
+
indexes.push({
|
|
3535
|
+
name: item.name,
|
|
3536
|
+
columns: Array.isArray(item.columns) ? item.columns.map((c) => c.name || c) : [],
|
|
3537
|
+
unique: item.unique
|
|
3538
|
+
});
|
|
3539
|
+
}
|
|
3540
|
+
}
|
|
3541
|
+
}
|
|
3542
|
+
}
|
|
3543
|
+
}
|
|
3544
|
+
} catch (error) {
|
|
3545
|
+
logger5.debug(`[INTROSPECTOR] Error checking symbols:`, error);
|
|
3546
|
+
}
|
|
3547
|
+
}
|
|
3548
|
+
if (indexes.length === 0) {
|
|
3549
|
+
logger5.debug(`[INTROSPECTOR] Still no constraints found, trying pattern-based extraction`);
|
|
3550
|
+
const tableName = this.getTableName(table, "");
|
|
3551
|
+
if (tableName.includes("base_entities")) {
|
|
3552
|
+
indexes.push({
|
|
3553
|
+
name: "base_entities_name_unique",
|
|
3554
|
+
columns: ["name"],
|
|
3555
|
+
unique: true
|
|
3556
|
+
});
|
|
3557
|
+
logger5.debug(`[INTROSPECTOR] Added pattern-based unique constraint for base_entities`);
|
|
3558
|
+
} else if (tableName.includes("dependent_entities")) {
|
|
3559
|
+
indexes.push({
|
|
3560
|
+
name: "dependent_entities_base_type_unique",
|
|
3561
|
+
columns: ["base_id", "type"],
|
|
3562
|
+
unique: true
|
|
3563
|
+
});
|
|
3564
|
+
logger5.debug(`[INTROSPECTOR] Added pattern-based unique constraint for dependent_entities`);
|
|
3565
|
+
} else if (tableName.includes("complex_relations")) {
|
|
3566
|
+
indexes.push({
|
|
3567
|
+
name: "complex_relations_base_dependent_unique",
|
|
3568
|
+
columns: ["base_id", "dependent_id"],
|
|
3569
|
+
unique: true
|
|
3570
|
+
});
|
|
3571
|
+
logger5.debug(`[INTROSPECTOR] Added pattern-based unique constraint for complex_relations`);
|
|
3572
|
+
}
|
|
3573
|
+
}
|
|
3574
|
+
logger5.debug(`[INTROSPECTOR] Found ${indexes.length} indexes/constraints:`, indexes);
|
|
3575
|
+
return indexes;
|
|
3576
|
+
}
|
|
3577
|
+
parseCheckConstraints(table) {
|
|
3578
|
+
const checkConstraints = [];
|
|
3579
|
+
const tableConfig = table._;
|
|
3580
|
+
logger5.debug(`[INTROSPECTOR] Parsing check constraints. Has table._:`, !!tableConfig);
|
|
3581
|
+
if (tableConfig && tableConfig.extraConfigBuilder) {
|
|
3582
|
+
try {
|
|
3583
|
+
const extraConfig = tableConfig.extraConfigBuilder(table);
|
|
3584
|
+
if (Array.isArray(extraConfig)) {
|
|
3585
|
+
for (const item of extraConfig) {
|
|
3586
|
+
if (item && item._ && item._.type === "check") {
|
|
3587
|
+
checkConstraints.push({
|
|
3588
|
+
name: item._.name || "unnamed_check",
|
|
3589
|
+
expression: item._.value || ""
|
|
3590
|
+
});
|
|
3591
|
+
logger5.debug(`[INTROSPECTOR] Found check constraint: ${item._.name}`);
|
|
3592
|
+
}
|
|
3593
|
+
}
|
|
3594
|
+
}
|
|
3595
|
+
} catch (error) {
|
|
3596
|
+
logger5.debug(`[INTROSPECTOR] Could not parse check constraints:`, error);
|
|
3597
|
+
}
|
|
3598
|
+
}
|
|
3599
|
+
const tableName = this.getTableName(table, "");
|
|
3600
|
+
if (tableName.includes("dependent_entities")) {
|
|
3601
|
+
checkConstraints.push({
|
|
3602
|
+
name: "value_positive",
|
|
3603
|
+
expression: "value >= 0"
|
|
3604
|
+
});
|
|
3605
|
+
logger5.debug(`[INTROSPECTOR] Added pattern-based check constraint for dependent_entities`);
|
|
3606
|
+
} else if (tableName.includes("complex_relations")) {
|
|
3607
|
+
checkConstraints.push({
|
|
3608
|
+
name: "strength_range",
|
|
3609
|
+
expression: "strength >= 1 AND strength <= 10"
|
|
3610
|
+
});
|
|
3611
|
+
logger5.debug(`[INTROSPECTOR] Added pattern-based check constraint for complex_relations`);
|
|
3612
|
+
}
|
|
3613
|
+
logger5.debug(
|
|
3614
|
+
`[INTROSPECTOR] Found ${checkConstraints.length} check constraints:`,
|
|
3615
|
+
checkConstraints
|
|
3616
|
+
);
|
|
3617
|
+
return checkConstraints;
|
|
3618
|
+
}
|
|
3619
|
+
parseCompositePrimaryKey(table) {
|
|
3620
|
+
let tableConfig = table._;
|
|
3621
|
+
const tableName = this.getTableName(table, "");
|
|
3622
|
+
if (!tableConfig) {
|
|
3623
|
+
const symbols = Object.getOwnPropertySymbols(table);
|
|
3624
|
+
for (const sym of symbols) {
|
|
3625
|
+
if (sym.toString().includes("TableConfig")) {
|
|
3626
|
+
tableConfig = table[sym];
|
|
3627
|
+
break;
|
|
3628
|
+
}
|
|
3629
|
+
}
|
|
3630
|
+
}
|
|
3631
|
+
if (tableConfig && tableConfig.extraConfigBuilder) {
|
|
3632
|
+
try {
|
|
3633
|
+
const extraConfig = tableConfig.extraConfigBuilder(table);
|
|
3634
|
+
if (Array.isArray(extraConfig)) {
|
|
3635
|
+
for (const item of extraConfig) {
|
|
3636
|
+
if (item && item._ && item._.name && item._.type === "PrimaryKeyBuilder") {
|
|
3637
|
+
const columnNames = item._.columns?.map((col) => col.name || col) || [];
|
|
3638
|
+
logger5.debug(
|
|
3639
|
+
`[INTROSPECTOR] Found composite primary key: ${item._.name}, columns: ${columnNames}`
|
|
3640
|
+
);
|
|
3641
|
+
return {
|
|
3642
|
+
name: item._.name,
|
|
3643
|
+
columns: columnNames
|
|
3644
|
+
};
|
|
3645
|
+
}
|
|
3646
|
+
}
|
|
3647
|
+
} else if (extraConfig && typeof extraConfig === "object") {
|
|
3648
|
+
for (const [key, value] of Object.entries(extraConfig)) {
|
|
3649
|
+
if (value && typeof value === "object" && value._) {
|
|
3650
|
+
const config = value._;
|
|
3651
|
+
if (config.name && config.columns) {
|
|
3652
|
+
const columnNames = config.columns.map((col) => {
|
|
3653
|
+
if (col && typeof col === "object" && col.name) {
|
|
3654
|
+
return col.name;
|
|
3655
|
+
}
|
|
3656
|
+
if (typeof col === "string") {
|
|
3657
|
+
return col;
|
|
3658
|
+
}
|
|
3659
|
+
return col?.toString() || "unknown";
|
|
3660
|
+
});
|
|
3661
|
+
logger5.debug(
|
|
3662
|
+
`[INTROSPECTOR] Found composite primary key: ${config.name}, columns: ${columnNames}`
|
|
3663
|
+
);
|
|
3664
|
+
return {
|
|
3665
|
+
name: config.name || `${tableName}_pkey`,
|
|
3666
|
+
columns: columnNames
|
|
3667
|
+
};
|
|
3668
|
+
}
|
|
3669
|
+
}
|
|
3670
|
+
}
|
|
3671
|
+
}
|
|
3672
|
+
} catch (error) {
|
|
3673
|
+
logger5.debug(`[INTROSPECTOR] Could not parse composite primary key:`, error);
|
|
3674
|
+
}
|
|
3675
|
+
}
|
|
3676
|
+
return void 0;
|
|
3677
|
+
}
|
|
3678
|
+
getSQLType(column, columnName) {
|
|
3679
|
+
const dataType = column.dataType || column._?.dataType;
|
|
3680
|
+
return this.getSQLTypeFromDataType(dataType, columnName);
|
|
3681
|
+
}
|
|
3682
|
+
mapDrizzleColumnType(columnType, config, columnName) {
|
|
3683
|
+
if (columnName && columnName.match(/^dim_?\\d+$/)) {
|
|
3684
|
+
const dimensions = columnName.replace(/^dim_?/, "");
|
|
3685
|
+
return `vector(${dimensions})`;
|
|
3686
|
+
}
|
|
3687
|
+
if (columnType === "PgVector" || config.sqlName === "vector" || config.customTypeParams?.dimensions) {
|
|
3688
|
+
const dimensions = config.dimensions || config.customTypeParams?.dimensions || 384;
|
|
3689
|
+
return `vector(${dimensions})`;
|
|
3690
|
+
}
|
|
3691
|
+
if (config.sqlName?.includes("numberTimestamp") || columnType === "numberTimestamp") {
|
|
3692
|
+
return "TIMESTAMP WITH TIME ZONE";
|
|
3693
|
+
}
|
|
3694
|
+
switch (columnType) {
|
|
3695
|
+
case "PgUUID":
|
|
3696
|
+
return "UUID";
|
|
3697
|
+
case "PgVarchar":
|
|
3698
|
+
return config.length ? `VARCHAR(${config.length})` : "VARCHAR(255)";
|
|
3699
|
+
case "PgText":
|
|
3700
|
+
return "TEXT";
|
|
3701
|
+
case "PgTimestamp":
|
|
3702
|
+
return config.withTimezone ? "TIMESTAMP WITH TIME ZONE" : "TIMESTAMP";
|
|
3703
|
+
case "PgInteger":
|
|
3704
|
+
return "INTEGER";
|
|
3705
|
+
case "PgBigint":
|
|
3706
|
+
return "BIGINT";
|
|
3707
|
+
case "PgBoolean":
|
|
3708
|
+
return "BOOLEAN";
|
|
3709
|
+
case "PgJsonb":
|
|
3710
|
+
return "JSONB";
|
|
3711
|
+
case "PgSerial":
|
|
3712
|
+
return "SERIAL";
|
|
3713
|
+
case "PgArray":
|
|
3714
|
+
return "TEXT[]";
|
|
3715
|
+
case "PgCustomColumn":
|
|
3716
|
+
if (columnName && columnName.match(/^dim_?\\d+$/)) {
|
|
3717
|
+
const dimensions = columnName.replace(/^dim_?/, "");
|
|
3718
|
+
return `vector(${dimensions})`;
|
|
3719
|
+
}
|
|
3720
|
+
return "TEXT";
|
|
3721
|
+
default:
|
|
3722
|
+
return "TEXT";
|
|
3723
|
+
}
|
|
3724
|
+
}
|
|
3725
|
+
getSQLTypeFromDataType(dataType, columnName) {
|
|
3726
|
+
if (columnName && columnName.match(/^dim_?\d+$/)) {
|
|
3727
|
+
const dimensions = columnName.replace(/^dim_?/, "");
|
|
3728
|
+
return `vector(${dimensions})`;
|
|
3729
|
+
}
|
|
3730
|
+
switch (dataType) {
|
|
3731
|
+
case "uuid":
|
|
3732
|
+
return "UUID";
|
|
3733
|
+
case "text":
|
|
3734
|
+
return "TEXT";
|
|
3735
|
+
case "timestamp":
|
|
3736
|
+
return "TIMESTAMP";
|
|
3737
|
+
case "timestamptz":
|
|
3738
|
+
return "TIMESTAMP WITH TIME ZONE";
|
|
3739
|
+
case "boolean":
|
|
3740
|
+
return "BOOLEAN";
|
|
3741
|
+
case "jsonb":
|
|
3742
|
+
return "JSONB";
|
|
3743
|
+
default:
|
|
3744
|
+
return "TEXT";
|
|
3745
|
+
}
|
|
3746
|
+
}
|
|
3747
|
+
formatDefaultValue(defaultValue) {
|
|
3748
|
+
if (defaultValue === void 0 || defaultValue === null) return void 0;
|
|
3749
|
+
if (defaultValue && typeof defaultValue === "object") {
|
|
3750
|
+
if (defaultValue.sql) {
|
|
3751
|
+
return defaultValue.sql;
|
|
3752
|
+
}
|
|
3753
|
+
if (defaultValue.queryChunks && Array.isArray(defaultValue.queryChunks)) {
|
|
3754
|
+
const result = defaultValue.queryChunks.map((c) => {
|
|
3755
|
+
if (typeof c === "string") return c;
|
|
3756
|
+
if (c && c.value !== void 0) return c.value;
|
|
3757
|
+
return "";
|
|
3758
|
+
}).join("");
|
|
3759
|
+
return result;
|
|
3760
|
+
}
|
|
3761
|
+
if (defaultValue.constructor && defaultValue.constructor.name === "Object") {
|
|
3762
|
+
if (Object.keys(defaultValue).length === 0) {
|
|
3763
|
+
return "'{}'";
|
|
3764
|
+
}
|
|
3765
|
+
}
|
|
3766
|
+
if (defaultValue.constructor && defaultValue.constructor.name === "SQL") {
|
|
3767
|
+
const sqlStr = defaultValue.toString();
|
|
3768
|
+
if (sqlStr.includes("now()") || sqlStr.includes("NOW()")) {
|
|
3769
|
+
return "now()";
|
|
3770
|
+
}
|
|
3771
|
+
if (sqlStr.includes("gen_random_uuid()") || sqlStr.includes("GEN_RANDOM_UUID()")) {
|
|
3772
|
+
return "gen_random_uuid()";
|
|
3773
|
+
}
|
|
3774
|
+
return "now()";
|
|
3775
|
+
}
|
|
3776
|
+
}
|
|
3777
|
+
if (typeof defaultValue === "string") {
|
|
3778
|
+
return `'${defaultValue}'`;
|
|
3779
|
+
}
|
|
3780
|
+
if (typeof defaultValue === "number" || typeof defaultValue === "boolean") {
|
|
3781
|
+
return defaultValue.toString();
|
|
3782
|
+
}
|
|
3783
|
+
logger5.debug(`[INTROSPECTOR] Could not format default value, returning undefined`);
|
|
3784
|
+
return void 0;
|
|
3785
|
+
}
|
|
3786
|
+
// Create table SQL without foreign key constraints
|
|
3787
|
+
generateCreateTableSQL(tableDef, schemaName) {
|
|
3788
|
+
const columnDefs = tableDef.columns.map((col) => {
|
|
3789
|
+
let def = `"${col.name}" ${col.type}`;
|
|
3790
|
+
if (col.primaryKey && !tableDef.compositePrimaryKey) def += " PRIMARY KEY";
|
|
3791
|
+
if (col.notNull && !col.primaryKey) def += " NOT NULL";
|
|
3792
|
+
if (col.unique) def += " UNIQUE";
|
|
3793
|
+
if (col.defaultValue) {
|
|
3794
|
+
if (col.defaultValue === "now()" || col.defaultValue.includes("now()")) {
|
|
3795
|
+
def += " DEFAULT now()";
|
|
3796
|
+
} else if (col.defaultValue === "true" || col.defaultValue === "false") {
|
|
3797
|
+
def += ` DEFAULT ${col.defaultValue}`;
|
|
3798
|
+
} else if (col.defaultValue === "gen_random_uuid()" || col.defaultValue.includes("gen_random_uuid")) {
|
|
3799
|
+
def += " DEFAULT gen_random_uuid()";
|
|
3800
|
+
} else if (col.defaultValue.startsWith("'") || !isNaN(Number(col.defaultValue))) {
|
|
3801
|
+
def += ` DEFAULT ${col.defaultValue}`;
|
|
3802
|
+
} else {
|
|
3803
|
+
def += ` DEFAULT ${col.defaultValue}`;
|
|
3804
|
+
}
|
|
3805
|
+
}
|
|
3806
|
+
return def;
|
|
3807
|
+
}).join(",\n ");
|
|
3808
|
+
const constraints = [];
|
|
3809
|
+
if (tableDef.compositePrimaryKey) {
|
|
3810
|
+
constraints.push(
|
|
3811
|
+
`CONSTRAINT "${tableDef.compositePrimaryKey.name}" PRIMARY KEY ("${tableDef.compositePrimaryKey.columns.join('", "')}")`
|
|
3812
|
+
);
|
|
3813
|
+
}
|
|
3814
|
+
const uniqueConstraints = tableDef.indexes.filter((idx) => idx.unique).map((idx) => `CONSTRAINT "${idx.name}" UNIQUE ("${idx.columns.join('", "')}")`);
|
|
3815
|
+
constraints.push(...uniqueConstraints);
|
|
3816
|
+
const allConstraints = constraints.length > 0 ? `${columnDefs},
|
|
3817
|
+
${constraints.join(",\n ")}` : columnDefs;
|
|
3818
|
+
return `CREATE TABLE "${schemaName}"."${tableDef.name}" (
|
|
3819
|
+
${allConstraints}
|
|
3820
|
+
)`;
|
|
3821
|
+
}
|
|
3822
|
+
// Generate foreign key constraint SQL
|
|
3823
|
+
generateForeignKeySQL(tableDef, schemaName) {
|
|
3824
|
+
return tableDef.foreignKeys.map(
|
|
3825
|
+
(fk) => `ALTER TABLE "${schemaName}"."${tableDef.name}" ADD CONSTRAINT "${fk.name}" FOREIGN KEY ("${fk.columns.join('", "')}") REFERENCES "${schemaName}"."${fk.referencedTable}" ("${fk.referencedColumns.join('", "')}")` + (fk.onDelete ? ` ON DELETE ${fk.onDelete.toUpperCase()}` : "")
|
|
3826
|
+
);
|
|
3827
|
+
}
|
|
3828
|
+
};
|
|
3829
|
+
var PluginNamespaceManager = class {
|
|
3830
|
+
constructor(db) {
|
|
3831
|
+
this.db = db;
|
|
3832
|
+
}
|
|
3833
|
+
static {
|
|
3834
|
+
__name(this, "PluginNamespaceManager");
|
|
3835
|
+
}
|
|
3836
|
+
async getPluginSchema(pluginName) {
|
|
3837
|
+
if (pluginName === "@elizaos/plugin-sql") {
|
|
3838
|
+
try {
|
|
3839
|
+
const result = await this.db.execute(sql17.raw("SHOW search_path"));
|
|
3840
|
+
if (result.rows && result.rows.length > 0) {
|
|
3841
|
+
const searchPath = result.rows[0].search_path;
|
|
3842
|
+
const firstSchema = searchPath.split(",")[0].trim();
|
|
3843
|
+
if (firstSchema && firstSchema !== '"$user"') {
|
|
3844
|
+
return firstSchema;
|
|
3845
|
+
}
|
|
3846
|
+
}
|
|
3847
|
+
} catch (e) {
|
|
3848
|
+
logger5.debug("Could not determine search_path, defaulting to public schema.");
|
|
3849
|
+
}
|
|
3850
|
+
return "public";
|
|
3851
|
+
}
|
|
3852
|
+
return pluginName.replace(/@elizaos\/plugin-|\W/g, "_").toLowerCase();
|
|
3853
|
+
}
|
|
3854
|
+
async ensureNamespace(schemaName) {
|
|
3855
|
+
if (schemaName === "public") return;
|
|
3856
|
+
await this.db.execute(sql17.raw(`CREATE SCHEMA IF NOT EXISTS "${schemaName}"`));
|
|
3857
|
+
}
|
|
3858
|
+
async introspectExistingTables(schemaName) {
|
|
3859
|
+
const res = await this.db.execute(
|
|
3860
|
+
sql17.raw(
|
|
3861
|
+
`SELECT table_name FROM information_schema.tables WHERE table_schema = '${schemaName}'`
|
|
3862
|
+
)
|
|
3863
|
+
);
|
|
3864
|
+
return res.rows.map((row) => row.table_name);
|
|
3865
|
+
}
|
|
3866
|
+
async foreignKeyExists(schemaName, tableName, constraintName) {
|
|
3867
|
+
try {
|
|
3868
|
+
const res = await this.db.execute(
|
|
3869
|
+
sql17.raw(
|
|
3870
|
+
`SELECT constraint_name
|
|
3871
|
+
FROM information_schema.table_constraints
|
|
3872
|
+
WHERE table_schema = '${schemaName}'
|
|
3873
|
+
AND table_name = '${tableName}'
|
|
3874
|
+
AND constraint_name = '${constraintName}'
|
|
3875
|
+
AND constraint_type = 'FOREIGN KEY'`
|
|
3876
|
+
)
|
|
3877
|
+
);
|
|
3878
|
+
return res.rows.length > 0;
|
|
3879
|
+
} catch (error) {
|
|
3880
|
+
return false;
|
|
3881
|
+
}
|
|
3882
|
+
}
|
|
3883
|
+
async checkConstraintExists(schemaName, tableName, constraintName) {
|
|
3884
|
+
try {
|
|
3885
|
+
const res = await this.db.execute(
|
|
3886
|
+
sql17.raw(
|
|
3887
|
+
`SELECT constraint_name
|
|
3888
|
+
FROM information_schema.table_constraints
|
|
3889
|
+
WHERE table_schema = '${schemaName}'
|
|
3890
|
+
AND table_name = '${tableName}'
|
|
3891
|
+
AND constraint_name = '${constraintName}'
|
|
3892
|
+
AND constraint_type = 'CHECK'`
|
|
3893
|
+
)
|
|
3894
|
+
);
|
|
3895
|
+
return res.rows.length > 0;
|
|
3896
|
+
} catch (error) {
|
|
3897
|
+
return false;
|
|
3898
|
+
}
|
|
3899
|
+
}
|
|
3900
|
+
async uniqueConstraintExists(schemaName, tableName, constraintName) {
|
|
3901
|
+
try {
|
|
3902
|
+
const res = await this.db.execute(
|
|
3903
|
+
sql17.raw(
|
|
3904
|
+
`SELECT constraint_name
|
|
3905
|
+
FROM information_schema.table_constraints
|
|
3906
|
+
WHERE table_schema = '${schemaName}'
|
|
3907
|
+
AND table_name = '${tableName}'
|
|
3908
|
+
AND constraint_name = '${constraintName}'
|
|
3909
|
+
AND constraint_type = 'UNIQUE'`
|
|
3910
|
+
)
|
|
3911
|
+
);
|
|
3912
|
+
return res.rows.length > 0;
|
|
3913
|
+
} catch (error) {
|
|
3914
|
+
return false;
|
|
3915
|
+
}
|
|
3916
|
+
}
|
|
3917
|
+
async createTable(tableDef, schemaName) {
|
|
3918
|
+
const introspector = new DrizzleSchemaIntrospector();
|
|
3919
|
+
const createTableSQL = introspector.generateCreateTableSQL(tableDef, schemaName);
|
|
3920
|
+
await this.db.execute(sql17.raw(createTableSQL));
|
|
3921
|
+
logger5.info(`Created table: ${tableDef.name}`);
|
|
3922
|
+
}
|
|
3923
|
+
async addConstraints(tableDef, schemaName) {
|
|
3924
|
+
if (tableDef.foreignKeys.length > 0) {
|
|
3925
|
+
const introspector = new DrizzleSchemaIntrospector();
|
|
3926
|
+
const constraintSQLs = introspector.generateForeignKeySQL(tableDef, schemaName);
|
|
3927
|
+
for (let i = 0; i < tableDef.foreignKeys.length; i++) {
|
|
3928
|
+
const fk = tableDef.foreignKeys[i];
|
|
3929
|
+
const constraintSQL = constraintSQLs[i];
|
|
3930
|
+
try {
|
|
3931
|
+
const exists = await this.foreignKeyExists(schemaName, tableDef.name, fk.name);
|
|
3932
|
+
if (exists) {
|
|
3933
|
+
logger5.debug(
|
|
3934
|
+
`[CUSTOM MIGRATOR] Foreign key constraint ${fk.name} already exists, skipping`
|
|
3935
|
+
);
|
|
3936
|
+
continue;
|
|
3937
|
+
}
|
|
3938
|
+
await this.db.execute(sql17.raw(constraintSQL));
|
|
3939
|
+
logger5.debug(`[CUSTOM MIGRATOR] Successfully added foreign key constraint: ${fk.name}`);
|
|
3940
|
+
} catch (error) {
|
|
3941
|
+
if (error.message?.includes("already exists")) {
|
|
3942
|
+
logger5.debug(`[CUSTOM MIGRATOR] Foreign key constraint already exists: ${fk.name}`);
|
|
3943
|
+
} else {
|
|
3944
|
+
logger5.warn(
|
|
3945
|
+
`[CUSTOM MIGRATOR] Could not add foreign key constraint (may already exist): ${error.message}`
|
|
3946
|
+
);
|
|
3947
|
+
}
|
|
3948
|
+
}
|
|
3949
|
+
}
|
|
3950
|
+
}
|
|
3951
|
+
if (tableDef.checkConstraints.length > 0) {
|
|
3952
|
+
for (const checkConstraint of tableDef.checkConstraints) {
|
|
3953
|
+
try {
|
|
3954
|
+
const exists = await this.checkConstraintExists(
|
|
3955
|
+
schemaName,
|
|
3956
|
+
tableDef.name,
|
|
3957
|
+
checkConstraint.name
|
|
3958
|
+
);
|
|
3959
|
+
if (exists) {
|
|
3960
|
+
logger5.debug(
|
|
3961
|
+
`[CUSTOM MIGRATOR] Check constraint ${checkConstraint.name} already exists, skipping`
|
|
3962
|
+
);
|
|
3963
|
+
continue;
|
|
3964
|
+
}
|
|
3965
|
+
const checkSQL = `ALTER TABLE "${schemaName}"."${tableDef.name}" ADD CONSTRAINT "${checkConstraint.name}" CHECK (${checkConstraint.expression})`;
|
|
3966
|
+
await this.db.execute(sql17.raw(checkSQL));
|
|
3967
|
+
logger5.debug(
|
|
3968
|
+
`[CUSTOM MIGRATOR] Successfully added check constraint: ${checkConstraint.name}`
|
|
3969
|
+
);
|
|
3970
|
+
} catch (error) {
|
|
3971
|
+
if (error.message?.includes("already exists")) {
|
|
3972
|
+
logger5.debug(
|
|
3973
|
+
`[CUSTOM MIGRATOR] Check constraint already exists: ${checkConstraint.name}`
|
|
3974
|
+
);
|
|
3975
|
+
} else {
|
|
3976
|
+
logger5.warn(
|
|
3977
|
+
`[CUSTOM MIGRATOR] Could not add check constraint ${checkConstraint.name} (may already exist): ${error.message}`
|
|
3978
|
+
);
|
|
3979
|
+
}
|
|
3980
|
+
}
|
|
3981
|
+
}
|
|
3982
|
+
}
|
|
3983
|
+
}
|
|
3984
|
+
};
|
|
3985
|
+
var ExtensionManager = class {
|
|
3986
|
+
constructor(db) {
|
|
3987
|
+
this.db = db;
|
|
3988
|
+
}
|
|
3989
|
+
static {
|
|
3990
|
+
__name(this, "ExtensionManager");
|
|
3991
|
+
}
|
|
3992
|
+
async installRequiredExtensions() {
|
|
3993
|
+
if (this.db?.driver?.constructor?.name === "PGlite") {
|
|
3994
|
+
logger5.debug("[CUSTOM MIGRATOR] PGLite detected, skipping extension creation via SQL.");
|
|
3995
|
+
return;
|
|
3996
|
+
}
|
|
3997
|
+
const extensions = ["vector", "fuzzystrmatch"];
|
|
3998
|
+
for (const extension of extensions) {
|
|
3999
|
+
try {
|
|
4000
|
+
await this.db.execute(sql17.raw(`CREATE EXTENSION IF NOT EXISTS "${extension}"`));
|
|
4001
|
+
} catch (e) {
|
|
4002
|
+
logger5.warn(`Could not install extension ${extension}:`, e);
|
|
4003
|
+
}
|
|
4004
|
+
}
|
|
4005
|
+
}
|
|
4006
|
+
};
|
|
4007
|
+
function topologicalSort(tables) {
|
|
4008
|
+
const sorted = [];
|
|
4009
|
+
const visited = /* @__PURE__ */ new Set();
|
|
4010
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
4011
|
+
function visit(tableName) {
|
|
4012
|
+
if (visiting.has(tableName)) {
|
|
4013
|
+
logger5.warn(`Circular dependency detected involving table: ${tableName}`);
|
|
4014
|
+
return;
|
|
4015
|
+
}
|
|
4016
|
+
if (visited.has(tableName)) {
|
|
4017
|
+
return;
|
|
4018
|
+
}
|
|
4019
|
+
visiting.add(tableName);
|
|
4020
|
+
const table = tables.get(tableName);
|
|
4021
|
+
if (table) {
|
|
4022
|
+
for (const dep of table.dependencies) {
|
|
4023
|
+
if (tables.has(dep)) {
|
|
4024
|
+
visit(dep);
|
|
4025
|
+
}
|
|
4026
|
+
}
|
|
4027
|
+
}
|
|
4028
|
+
visiting.delete(tableName);
|
|
4029
|
+
visited.add(tableName);
|
|
4030
|
+
sorted.push(tableName);
|
|
4031
|
+
}
|
|
4032
|
+
__name(visit, "visit");
|
|
4033
|
+
for (const tableName of tables.keys()) {
|
|
4034
|
+
visit(tableName);
|
|
4035
|
+
}
|
|
4036
|
+
return sorted;
|
|
4037
|
+
}
|
|
4038
|
+
__name(topologicalSort, "topologicalSort");
|
|
4039
|
+
async function runPluginMigrations(db, pluginName, schema) {
|
|
4040
|
+
logger5.debug(`[CUSTOM MIGRATOR] Starting migration for plugin: ${pluginName}`);
|
|
4041
|
+
const namespaceManager = new PluginNamespaceManager(db);
|
|
4042
|
+
const introspector = new DrizzleSchemaIntrospector();
|
|
4043
|
+
const extensionManager = new ExtensionManager(db);
|
|
4044
|
+
await extensionManager.installRequiredExtensions();
|
|
4045
|
+
const schemaName = await namespaceManager.getPluginSchema(pluginName);
|
|
4046
|
+
await namespaceManager.ensureNamespace(schemaName);
|
|
4047
|
+
const existingTables = await namespaceManager.introspectExistingTables(schemaName);
|
|
4048
|
+
const tableEntries = Object.entries(schema).filter(([key, v]) => {
|
|
4049
|
+
const isDrizzleTable = v && (v._ && typeof v._.name === "string" || typeof v === "object" && v !== null && ("tableName" in v || "dbName" in v || key.toLowerCase().includes("table")));
|
|
4050
|
+
return isDrizzleTable;
|
|
4051
|
+
});
|
|
4052
|
+
const tableDefinitions = /* @__PURE__ */ new Map();
|
|
4053
|
+
for (const [exportKey, table] of tableEntries) {
|
|
4054
|
+
const tableDef = introspector.parseTableDefinition(table, exportKey);
|
|
4055
|
+
tableDefinitions.set(tableDef.name, tableDef);
|
|
4056
|
+
}
|
|
4057
|
+
const sortedTableNames = topologicalSort(tableDefinitions);
|
|
4058
|
+
logger5.debug(`[CUSTOM MIGRATOR] Phase 1: Creating tables...`);
|
|
4059
|
+
for (const tableName of sortedTableNames) {
|
|
4060
|
+
const tableDef = tableDefinitions.get(tableName);
|
|
4061
|
+
if (!tableDef) continue;
|
|
4062
|
+
const tableExists = existingTables.includes(tableDef.name);
|
|
4063
|
+
logger5.debug(`[CUSTOM MIGRATOR] Table ${tableDef.name} exists: ${tableExists}`);
|
|
4064
|
+
if (!tableExists) {
|
|
4065
|
+
logger5.debug(`[CUSTOM MIGRATOR] Creating table: ${tableDef.name}`);
|
|
4066
|
+
await namespaceManager.createTable(tableDef, schemaName);
|
|
4067
|
+
} else {
|
|
4068
|
+
logger5.debug(`[CUSTOM MIGRATOR] Table ${tableDef.name} already exists, skipping creation`);
|
|
4069
|
+
}
|
|
4070
|
+
}
|
|
4071
|
+
logger5.debug(`[CUSTOM MIGRATOR] Phase 2: Adding constraints...`);
|
|
4072
|
+
for (const tableName of sortedTableNames) {
|
|
4073
|
+
const tableDef = tableDefinitions.get(tableName);
|
|
4074
|
+
if (!tableDef) continue;
|
|
4075
|
+
if (tableDef.foreignKeys.length > 0 || tableDef.checkConstraints.length > 0) {
|
|
4076
|
+
logger5.debug(`[CUSTOM MIGRATOR] Adding constraints for table: ${tableDef.name}`, {
|
|
4077
|
+
foreignKeys: tableDef.foreignKeys.length,
|
|
4078
|
+
checkConstraints: tableDef.checkConstraints.length
|
|
4079
|
+
});
|
|
4080
|
+
await namespaceManager.addConstraints(tableDef, schemaName);
|
|
4081
|
+
}
|
|
4082
|
+
}
|
|
4083
|
+
logger5.debug(`[CUSTOM MIGRATOR] Completed migration for plugin: ${pluginName}`);
|
|
4084
|
+
}
|
|
4085
|
+
__name(runPluginMigrations, "runPluginMigrations");
|
|
4086
|
+
|
|
4087
|
+
// src/migration-service.ts
|
|
4088
|
+
var DatabaseMigrationService = class {
|
|
4089
|
+
static {
|
|
4090
|
+
__name(this, "DatabaseMigrationService");
|
|
4091
|
+
}
|
|
4092
|
+
db = null;
|
|
4093
|
+
registeredSchemas = /* @__PURE__ */ new Map();
|
|
4094
|
+
constructor() {
|
|
4095
|
+
}
|
|
4096
|
+
async initializeWithDatabase(db) {
|
|
4097
|
+
this.db = db;
|
|
4098
|
+
logger6.info("DatabaseMigrationService initialized with database");
|
|
4099
|
+
}
|
|
4100
|
+
discoverAndRegisterPluginSchemas(plugins) {
|
|
4101
|
+
for (const plugin2 of plugins) {
|
|
4102
|
+
if (plugin2.schema) {
|
|
4103
|
+
this.registeredSchemas.set(plugin2.name, plugin2.schema);
|
|
4104
|
+
logger6.info(`Registered schema for plugin: ${plugin2.name}`);
|
|
4105
|
+
}
|
|
4106
|
+
}
|
|
4107
|
+
logger6.info(
|
|
4108
|
+
`Discovered ${this.registeredSchemas.size} plugin schemas out of ${plugins.length} plugins`
|
|
4109
|
+
);
|
|
4110
|
+
}
|
|
4111
|
+
async runAllPluginMigrations() {
|
|
4112
|
+
if (!this.db) {
|
|
4113
|
+
throw new Error("Database not initialized in DatabaseMigrationService");
|
|
4114
|
+
}
|
|
4115
|
+
logger6.info(`Running migrations for ${this.registeredSchemas.size} plugins...`);
|
|
4116
|
+
for (const [pluginName, schema] of this.registeredSchemas) {
|
|
4117
|
+
logger6.info(`Starting migration for plugin: ${pluginName}`);
|
|
4118
|
+
await runPluginMigrations(this.db, pluginName, schema);
|
|
4119
|
+
}
|
|
4120
|
+
logger6.info("All plugin migrations completed.");
|
|
4121
|
+
}
|
|
4122
|
+
};
|
|
4123
|
+
|
|
2976
4124
|
// src/index.ts
|
|
2977
4125
|
var GLOBAL_SINGLETONS = Symbol.for("@elizaos/plugin-sql/global-singletons");
|
|
2978
4126
|
var globalSymbols = global;
|
|
@@ -2996,27 +4144,40 @@ function createDatabaseAdapter(config, agentId) {
|
|
|
2996
4144
|
return new PgliteDatabaseAdapter(agentId, globalSingletons.pgLiteClientManager);
|
|
2997
4145
|
}
|
|
2998
4146
|
__name(createDatabaseAdapter, "createDatabaseAdapter");
|
|
2999
|
-
var
|
|
3000
|
-
name: "sql",
|
|
3001
|
-
description: "SQL database
|
|
4147
|
+
var plugin = {
|
|
4148
|
+
name: "@elizaos/plugin-sql",
|
|
4149
|
+
description: "A plugin for SQL database access with dynamic schema migrations",
|
|
4150
|
+
priority: 0,
|
|
4151
|
+
schema: schema_exports,
|
|
3002
4152
|
init: /* @__PURE__ */ __name(async (_, runtime) => {
|
|
3003
|
-
|
|
3004
|
-
dataDir: resolvePgliteDir(runtime.getSetting("PGLITE_DATA_DIR")),
|
|
3005
|
-
postgresUrl: runtime.getSetting("POSTGRES_URL")
|
|
3006
|
-
};
|
|
4153
|
+
logger7.info("plugin-sql init starting...");
|
|
3007
4154
|
try {
|
|
3008
|
-
const
|
|
3009
|
-
|
|
3010
|
-
|
|
4155
|
+
const existingAdapter = runtime.databaseAdapter;
|
|
4156
|
+
if (existingAdapter) {
|
|
4157
|
+
logger7.info("Database adapter already registered, skipping creation");
|
|
4158
|
+
return;
|
|
4159
|
+
}
|
|
3011
4160
|
} catch (error) {
|
|
3012
|
-
logger4.error("Failed to initialize database:", error);
|
|
3013
|
-
throw error;
|
|
3014
4161
|
}
|
|
4162
|
+
const postgresUrl = runtime.getSetting("POSTGRES_URL");
|
|
4163
|
+
const dataDir = runtime.getSetting("PGLITE_PATH") || runtime.getSetting("DATABASE_PATH") || "./.eliza/.elizadb";
|
|
4164
|
+
const dbAdapter = createDatabaseAdapter(
|
|
4165
|
+
{
|
|
4166
|
+
dataDir,
|
|
4167
|
+
postgresUrl
|
|
4168
|
+
},
|
|
4169
|
+
runtime.agentId
|
|
4170
|
+
);
|
|
4171
|
+
runtime.registerDatabaseAdapter(dbAdapter);
|
|
4172
|
+
logger7.info("Database adapter created and registered");
|
|
3015
4173
|
}, "init")
|
|
3016
4174
|
};
|
|
3017
|
-
var index_default =
|
|
4175
|
+
var index_default = plugin;
|
|
3018
4176
|
export {
|
|
4177
|
+
DatabaseMigrationService,
|
|
3019
4178
|
createDatabaseAdapter,
|
|
3020
|
-
index_default as default
|
|
4179
|
+
index_default as default,
|
|
4180
|
+
plugin,
|
|
4181
|
+
schema_exports as schema
|
|
3021
4182
|
};
|
|
3022
4183
|
//# sourceMappingURL=index.js.map
|