@elizaos/plugin-sql 1.0.7 → 1.0.9
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 +1423 -234
- 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 -1629
- 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,9 +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
|
-
ChannelType
|
|
19
|
+
logger
|
|
20
20
|
} from "@elizaos/core";
|
|
21
21
|
import {
|
|
22
22
|
and,
|
|
@@ -26,8 +26,8 @@ import {
|
|
|
26
26
|
eq,
|
|
27
27
|
gte,
|
|
28
28
|
inArray,
|
|
29
|
-
lte,
|
|
30
29
|
lt,
|
|
30
|
+
lte,
|
|
31
31
|
or,
|
|
32
32
|
sql as sql16
|
|
33
33
|
} from "drizzle-orm";
|
|
@@ -35,7 +35,7 @@ import { v4 } from "uuid";
|
|
|
35
35
|
|
|
36
36
|
// src/schema/embedding.ts
|
|
37
37
|
import { sql as sql5 } from "drizzle-orm";
|
|
38
|
-
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";
|
|
39
39
|
import { VECTOR_DIMS } from "@elizaos/core";
|
|
40
40
|
|
|
41
41
|
// src/schema/memory.ts
|
|
@@ -48,46 +48,20 @@ import {
|
|
|
48
48
|
jsonb as jsonb4,
|
|
49
49
|
pgTable as pgTable4,
|
|
50
50
|
text as text4,
|
|
51
|
+
timestamp as timestamp4,
|
|
51
52
|
uuid as uuid4
|
|
52
53
|
} from "drizzle-orm/pg-core";
|
|
53
54
|
|
|
54
55
|
// src/schema/agent.ts
|
|
55
56
|
import { sql } from "drizzle-orm";
|
|
56
|
-
import { boolean, jsonb, pgTable, text, unique, uuid } from "drizzle-orm/pg-core";
|
|
57
|
-
|
|
58
|
-
// src/schema/types.ts
|
|
59
|
-
import { customType } from "drizzle-orm/pg-core";
|
|
60
|
-
var stringJsonb = customType({
|
|
61
|
-
dataType() {
|
|
62
|
-
return "jsonb";
|
|
63
|
-
},
|
|
64
|
-
toDriver(value) {
|
|
65
|
-
return JSON.stringify(value);
|
|
66
|
-
},
|
|
67
|
-
fromDriver(value) {
|
|
68
|
-
return JSON.stringify(value);
|
|
69
|
-
}
|
|
70
|
-
});
|
|
71
|
-
var numberTimestamp = customType({
|
|
72
|
-
dataType() {
|
|
73
|
-
return "timestamptz";
|
|
74
|
-
},
|
|
75
|
-
toDriver(value) {
|
|
76
|
-
return new Date(value).toISOString();
|
|
77
|
-
},
|
|
78
|
-
fromDriver(value) {
|
|
79
|
-
return new Date(value).getTime();
|
|
80
|
-
}
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
// src/schema/agent.ts
|
|
57
|
+
import { boolean, jsonb, pgTable, text, timestamp, unique, uuid } from "drizzle-orm/pg-core";
|
|
84
58
|
var agentTable = pgTable(
|
|
85
59
|
"agents",
|
|
86
60
|
{
|
|
87
61
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
88
62
|
enabled: boolean("enabled").default(true).notNull(),
|
|
89
|
-
createdAt:
|
|
90
|
-
updatedAt:
|
|
63
|
+
createdAt: timestamp("created_at", { withTimezone: true }).default(sql`now()`).notNull(),
|
|
64
|
+
updatedAt: timestamp("updated_at", { withTimezone: true }).default(sql`now()`).notNull(),
|
|
91
65
|
// Character
|
|
92
66
|
name: text("name").notNull(),
|
|
93
67
|
username: text("username"),
|
|
@@ -111,15 +85,15 @@ var agentTable = pgTable(
|
|
|
111
85
|
|
|
112
86
|
// src/schema/entity.ts
|
|
113
87
|
import { sql as sql2 } from "drizzle-orm";
|
|
114
|
-
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";
|
|
115
89
|
var entityTable = pgTable2(
|
|
116
90
|
"entities",
|
|
117
91
|
{
|
|
118
92
|
id: uuid2("id").notNull().primaryKey(),
|
|
119
|
-
agentId: uuid2("
|
|
93
|
+
agentId: uuid2("agent_id").notNull().references(() => agentTable.id, {
|
|
120
94
|
onDelete: "cascade"
|
|
121
95
|
}),
|
|
122
|
-
createdAt:
|
|
96
|
+
createdAt: timestamp2("created_at").default(sql2`now()`).notNull(),
|
|
123
97
|
names: text2("names").array().default(sql2`'{}'::text[]`).notNull(),
|
|
124
98
|
metadata: jsonb2("metadata").default(sql2`'{}'::jsonb`).notNull()
|
|
125
99
|
},
|
|
@@ -132,7 +106,7 @@ var entityTable = pgTable2(
|
|
|
132
106
|
|
|
133
107
|
// src/schema/room.ts
|
|
134
108
|
import { sql as sql3 } from "drizzle-orm";
|
|
135
|
-
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";
|
|
136
110
|
var roomTable = pgTable3("rooms", {
|
|
137
111
|
id: uuid3("id").notNull().primaryKey().default(sql3`gen_random_uuid()`),
|
|
138
112
|
agentId: uuid3("agentId").references(() => agentTable.id, {
|
|
@@ -149,7 +123,7 @@ var roomTable = pgTable3("rooms", {
|
|
|
149
123
|
name: text3("name"),
|
|
150
124
|
metadata: jsonb3("metadata"),
|
|
151
125
|
channelId: text3("channelId"),
|
|
152
|
-
createdAt:
|
|
126
|
+
createdAt: timestamp3("createdAt").default(sql3`now()`).notNull()
|
|
153
127
|
});
|
|
154
128
|
|
|
155
129
|
// src/schema/memory.ts
|
|
@@ -158,7 +132,7 @@ var memoryTable = pgTable4(
|
|
|
158
132
|
{
|
|
159
133
|
id: uuid4("id").primaryKey().notNull(),
|
|
160
134
|
type: text4("type").notNull(),
|
|
161
|
-
createdAt:
|
|
135
|
+
createdAt: timestamp4("createdAt").default(sql4`now()`).notNull(),
|
|
162
136
|
content: jsonb4("content").notNull(),
|
|
163
137
|
entityId: uuid4("entityId").references(() => entityTable.id, {
|
|
164
138
|
onDelete: "cascade"
|
|
@@ -246,7 +220,7 @@ var embeddingTable = pgTable5(
|
|
|
246
220
|
{
|
|
247
221
|
id: uuid5("id").primaryKey().defaultRandom().notNull(),
|
|
248
222
|
memoryId: uuid5("memory_id").references(() => memoryTable.id),
|
|
249
|
-
createdAt:
|
|
223
|
+
createdAt: timestamp5("created_at").default(sql5`now()`).notNull(),
|
|
250
224
|
dim384: vector2("dim_384", { dimensions: VECTOR_DIMS.SMALL }),
|
|
251
225
|
dim512: vector2("dim_512", { dimensions: VECTOR_DIMS.MEDIUM }),
|
|
252
226
|
dim768: vector2("dim_768", { dimensions: VECTOR_DIMS.LARGE }),
|
|
@@ -265,63 +239,85 @@ var embeddingTable = pgTable5(
|
|
|
265
239
|
]
|
|
266
240
|
);
|
|
267
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
|
+
|
|
268
264
|
// src/schema/cache.ts
|
|
269
265
|
import { sql as sql6 } from "drizzle-orm";
|
|
270
|
-
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";
|
|
271
267
|
var cacheTable = pgTable6(
|
|
272
268
|
"cache",
|
|
273
269
|
{
|
|
274
|
-
id: uuid6("id").notNull().primaryKey().default(sql6`gen_random_uuid()`),
|
|
275
270
|
key: text5("key").notNull(),
|
|
276
|
-
agentId: uuid6("
|
|
271
|
+
agentId: uuid6("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
277
272
|
value: jsonb5("value").notNull(),
|
|
278
|
-
createdAt:
|
|
279
|
-
expiresAt:
|
|
273
|
+
createdAt: timestamp6("created_at", { withTimezone: true }).default(sql6`now()`).notNull(),
|
|
274
|
+
expiresAt: timestamp6("expires_at", { withTimezone: true })
|
|
280
275
|
},
|
|
281
|
-
(table) =>
|
|
276
|
+
(table) => ({
|
|
277
|
+
pk: primaryKey({ columns: [table.key, table.agentId] })
|
|
278
|
+
})
|
|
282
279
|
);
|
|
283
280
|
|
|
284
281
|
// src/schema/component.ts
|
|
285
282
|
import { sql as sql8 } from "drizzle-orm";
|
|
286
|
-
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";
|
|
287
284
|
|
|
288
285
|
// src/schema/world.ts
|
|
289
286
|
import { sql as sql7 } from "drizzle-orm";
|
|
290
|
-
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";
|
|
291
288
|
var worldTable = pgTable7("worlds", {
|
|
292
289
|
id: uuid7("id").notNull().primaryKey().default(sql7`gen_random_uuid()`),
|
|
293
290
|
agentId: uuid7("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
294
291
|
name: text6("name").notNull(),
|
|
295
292
|
metadata: jsonb6("metadata"),
|
|
296
|
-
serverId: text6("serverId").notNull(),
|
|
297
|
-
createdAt:
|
|
293
|
+
serverId: text6("serverId").notNull().default("local"),
|
|
294
|
+
createdAt: timestamp7("createdAt").default(sql7`now()`).notNull()
|
|
298
295
|
});
|
|
299
296
|
|
|
300
297
|
// src/schema/component.ts
|
|
301
298
|
var componentTable = pgTable8("components", {
|
|
302
|
-
id: uuid8("id").primaryKey().
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
}),
|
|
309
|
-
|
|
310
|
-
onDelete: "cascade"
|
|
311
|
-
}),
|
|
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
|
|
312
307
|
type: text7("type").notNull(),
|
|
313
308
|
data: jsonb7("data").default(sql8`'{}'::jsonb`),
|
|
314
|
-
|
|
309
|
+
// Timestamps
|
|
310
|
+
createdAt: timestamp8("createdAt").default(sql8`now()`).notNull()
|
|
315
311
|
});
|
|
316
312
|
|
|
317
313
|
// src/schema/log.ts
|
|
318
314
|
import { sql as sql9 } from "drizzle-orm";
|
|
319
|
-
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";
|
|
320
316
|
var logTable = pgTable9(
|
|
321
317
|
"logs",
|
|
322
318
|
{
|
|
323
319
|
id: uuid9("id").defaultRandom().notNull(),
|
|
324
|
-
createdAt:
|
|
320
|
+
createdAt: timestamp9("created_at", { withTimezone: true }).default(sql9`now()`).notNull(),
|
|
325
321
|
entityId: uuid9("entityId").notNull().references(() => entityTable.id),
|
|
326
322
|
body: jsonb8("body").notNull(),
|
|
327
323
|
type: text8("type").notNull(),
|
|
@@ -343,12 +339,12 @@ var logTable = pgTable9(
|
|
|
343
339
|
|
|
344
340
|
// src/schema/participant.ts
|
|
345
341
|
import { sql as sql10 } from "drizzle-orm";
|
|
346
|
-
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";
|
|
347
343
|
var participantTable = pgTable10(
|
|
348
344
|
"participants",
|
|
349
345
|
{
|
|
350
346
|
id: uuid10("id").notNull().primaryKey().default(sql10`gen_random_uuid()`),
|
|
351
|
-
createdAt:
|
|
347
|
+
createdAt: timestamp10("created_at", { withTimezone: true }).default(sql10`now()`).notNull(),
|
|
352
348
|
entityId: uuid10("entityId").references(() => entityTable.id, {
|
|
353
349
|
onDelete: "cascade"
|
|
354
350
|
}),
|
|
@@ -379,12 +375,21 @@ var participantTable = pgTable10(
|
|
|
379
375
|
|
|
380
376
|
// src/schema/relationship.ts
|
|
381
377
|
import { sql as sql11 } from "drizzle-orm";
|
|
382
|
-
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";
|
|
383
388
|
var relationshipTable = pgTable11(
|
|
384
389
|
"relationships",
|
|
385
390
|
{
|
|
386
391
|
id: uuid11("id").notNull().primaryKey().default(sql11`gen_random_uuid()`),
|
|
387
|
-
createdAt:
|
|
392
|
+
createdAt: timestamp11("created_at", { withTimezone: true }).default(sql11`now()`).notNull(),
|
|
388
393
|
sourceEntityId: uuid11("sourceEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
389
394
|
targetEntityId: uuid11("targetEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
390
395
|
agentId: uuid11("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
@@ -393,7 +398,7 @@ var relationshipTable = pgTable11(
|
|
|
393
398
|
},
|
|
394
399
|
(table) => [
|
|
395
400
|
index4("idx_relationships_users").on(table.sourceEntityId, table.targetEntityId),
|
|
396
|
-
|
|
401
|
+
unique5("unique_relationship").on(table.sourceEntityId, table.targetEntityId, table.agentId),
|
|
397
402
|
foreignKey5({
|
|
398
403
|
name: "fk_user_a",
|
|
399
404
|
columns: [table.sourceEntityId],
|
|
@@ -408,7 +413,7 @@ var relationshipTable = pgTable11(
|
|
|
408
413
|
);
|
|
409
414
|
|
|
410
415
|
// src/schema/tasks.ts
|
|
411
|
-
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";
|
|
412
417
|
import { sql as sql12 } from "drizzle-orm";
|
|
413
418
|
var taskTable = pgTable12("tasks", {
|
|
414
419
|
id: uuid12("id").primaryKey().defaultRandom(),
|
|
@@ -420,12 +425,12 @@ var taskTable = pgTable12("tasks", {
|
|
|
420
425
|
agentId: uuid12("agent_id").notNull(),
|
|
421
426
|
tags: text11("tags").array().default(sql12`'{}'::text[]`),
|
|
422
427
|
metadata: jsonb10("metadata").default(sql12`'{}'::jsonb`),
|
|
423
|
-
createdAt:
|
|
424
|
-
updatedAt:
|
|
428
|
+
createdAt: timestamp12("created_at", { withTimezone: true }).defaultNow(),
|
|
429
|
+
updatedAt: timestamp12("updated_at", { withTimezone: true }).defaultNow()
|
|
425
430
|
});
|
|
426
431
|
|
|
427
432
|
// src/schema/messageServer.ts
|
|
428
|
-
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";
|
|
429
434
|
import { sql as sql13 } from "drizzle-orm";
|
|
430
435
|
var messageServerTable = pgTable13("message_servers", {
|
|
431
436
|
id: text12("id").primaryKey(),
|
|
@@ -434,12 +439,12 @@ var messageServerTable = pgTable13("message_servers", {
|
|
|
434
439
|
sourceType: text12("source_type").notNull(),
|
|
435
440
|
sourceId: text12("source_id"),
|
|
436
441
|
metadata: jsonb11("metadata"),
|
|
437
|
-
createdAt:
|
|
438
|
-
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()
|
|
439
444
|
});
|
|
440
445
|
|
|
441
446
|
// src/schema/channel.ts
|
|
442
|
-
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";
|
|
443
448
|
import { sql as sql14 } from "drizzle-orm";
|
|
444
449
|
var channelTable = pgTable14("channels", {
|
|
445
450
|
id: text13("id").primaryKey(),
|
|
@@ -452,12 +457,12 @@ var channelTable = pgTable14("channels", {
|
|
|
452
457
|
sourceId: text13("source_id"),
|
|
453
458
|
topic: text13("topic"),
|
|
454
459
|
metadata: jsonb12("metadata"),
|
|
455
|
-
createdAt:
|
|
456
|
-
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()
|
|
457
462
|
});
|
|
458
463
|
|
|
459
464
|
// src/schema/message.ts
|
|
460
|
-
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";
|
|
461
466
|
import { sql as sql15 } from "drizzle-orm";
|
|
462
467
|
var messageTable = pgTable15("central_messages", {
|
|
463
468
|
id: text14("id").primaryKey(),
|
|
@@ -472,12 +477,12 @@ var messageTable = pgTable15("central_messages", {
|
|
|
472
477
|
sourceType: text14("source_type"),
|
|
473
478
|
sourceId: text14("source_id"),
|
|
474
479
|
metadata: jsonb13("metadata"),
|
|
475
|
-
createdAt:
|
|
476
|
-
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()
|
|
477
482
|
});
|
|
478
483
|
|
|
479
484
|
// src/schema/channelParticipant.ts
|
|
480
|
-
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";
|
|
481
486
|
var channelParticipantsTable = pgTable16(
|
|
482
487
|
"channel_participants",
|
|
483
488
|
{
|
|
@@ -486,12 +491,12 @@ var channelParticipantsTable = pgTable16(
|
|
|
486
491
|
// This is a central UUID (can be an agentId or a dedicated central user ID)
|
|
487
492
|
},
|
|
488
493
|
(table) => ({
|
|
489
|
-
pk:
|
|
494
|
+
pk: primaryKey2({ columns: [table.channelId, table.userId] })
|
|
490
495
|
})
|
|
491
496
|
);
|
|
492
497
|
|
|
493
498
|
// src/schema/serverAgent.ts
|
|
494
|
-
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";
|
|
495
500
|
var serverAgentsTable = pgTable17(
|
|
496
501
|
"server_agents",
|
|
497
502
|
{
|
|
@@ -500,7 +505,7 @@ var serverAgentsTable = pgTable17(
|
|
|
500
505
|
// This is the agent's UUID
|
|
501
506
|
},
|
|
502
507
|
(table) => ({
|
|
503
|
-
pk:
|
|
508
|
+
pk: primaryKey3({ columns: [table.serverId, table.agentId] })
|
|
504
509
|
})
|
|
505
510
|
);
|
|
506
511
|
|
|
@@ -514,6 +519,18 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
514
519
|
maxDelay = 1e4;
|
|
515
520
|
jitterMax = 1e3;
|
|
516
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
|
+
}
|
|
517
534
|
agentId;
|
|
518
535
|
/**
|
|
519
536
|
* Constructor for creating a new instance of Agent with the specified agentId.
|
|
@@ -591,7 +608,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
591
608
|
username: row.username || "",
|
|
592
609
|
id: row.id,
|
|
593
610
|
system: !row.system ? void 0 : row.system,
|
|
594
|
-
bio: !row.bio ? "" : row.bio
|
|
611
|
+
bio: !row.bio ? "" : row.bio,
|
|
612
|
+
createdAt: row.createdAt.getTime(),
|
|
613
|
+
updatedAt: row.updatedAt.getTime()
|
|
595
614
|
};
|
|
596
615
|
});
|
|
597
616
|
}
|
|
@@ -623,9 +642,26 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
623
642
|
async createAgent(agent) {
|
|
624
643
|
return this.withDatabase(async () => {
|
|
625
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
|
+
}
|
|
626
660
|
await this.db.transaction(async (tx) => {
|
|
627
661
|
await tx.insert(agentTable).values({
|
|
628
|
-
...agent
|
|
662
|
+
...agent,
|
|
663
|
+
createdAt: new Date(agent.createdAt || Date.now()),
|
|
664
|
+
updatedAt: new Date(agent.updatedAt || Date.now())
|
|
629
665
|
});
|
|
630
666
|
});
|
|
631
667
|
logger.debug("Agent created successfully:", {
|
|
@@ -658,10 +694,24 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
658
694
|
if (agent?.settings) {
|
|
659
695
|
agent.settings = await this.mergeAgentSettings(tx, agentId, agent.settings);
|
|
660
696
|
}
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
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));
|
|
665
715
|
});
|
|
666
716
|
logger.debug("Agent updated successfully:", {
|
|
667
717
|
agentId
|
|
@@ -939,7 +989,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
939
989
|
entity: entityTable,
|
|
940
990
|
components: componentTable
|
|
941
991
|
}).from(entityTable).leftJoin(componentTable, eq(componentTable.entityId, entityTable.id)).where(inArray(entityTable.id, entityIds));
|
|
942
|
-
if (result.length === 0) return
|
|
992
|
+
if (result.length === 0) return [];
|
|
943
993
|
const entities = {};
|
|
944
994
|
const entityComponents = {};
|
|
945
995
|
for (const e of result) {
|
|
@@ -1081,7 +1131,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1081
1131
|
roomId: component.roomId,
|
|
1082
1132
|
worldId: component.worldId ?? "",
|
|
1083
1133
|
sourceEntityId: component.sourceEntityId ?? "",
|
|
1084
|
-
data: component.data
|
|
1134
|
+
data: component.data,
|
|
1135
|
+
createdAt: component.createdAt.getTime()
|
|
1085
1136
|
};
|
|
1086
1137
|
});
|
|
1087
1138
|
}
|
|
@@ -1121,7 +1172,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1121
1172
|
roomId: component.roomId,
|
|
1122
1173
|
worldId: component.worldId ?? "",
|
|
1123
1174
|
sourceEntityId: component.sourceEntityId ?? "",
|
|
1124
|
-
data: component.data
|
|
1175
|
+
data: component.data,
|
|
1176
|
+
createdAt: component.createdAt.getTime()
|
|
1125
1177
|
}));
|
|
1126
1178
|
return components;
|
|
1127
1179
|
});
|
|
@@ -1133,7 +1185,10 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1133
1185
|
*/
|
|
1134
1186
|
async createComponent(component) {
|
|
1135
1187
|
return this.withDatabase(async () => {
|
|
1136
|
-
await this.db.insert(componentTable).values(
|
|
1188
|
+
await this.db.insert(componentTable).values({
|
|
1189
|
+
...component,
|
|
1190
|
+
createdAt: new Date(component.createdAt)
|
|
1191
|
+
});
|
|
1137
1192
|
return true;
|
|
1138
1193
|
});
|
|
1139
1194
|
}
|
|
@@ -1144,7 +1199,10 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1144
1199
|
*/
|
|
1145
1200
|
async updateComponent(component) {
|
|
1146
1201
|
return this.withDatabase(async () => {
|
|
1147
|
-
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));
|
|
1148
1206
|
});
|
|
1149
1207
|
}
|
|
1150
1208
|
/**
|
|
@@ -1169,12 +1227,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1169
1227
|
* @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.
|
|
1170
1228
|
*/
|
|
1171
1229
|
async getMemories(params) {
|
|
1172
|
-
const { entityId, agentId, roomId, worldId, tableName, count: count2, unique:
|
|
1230
|
+
const { entityId, agentId, roomId, worldId, tableName, count: count2, unique: unique6, start, end } = params;
|
|
1173
1231
|
if (!tableName) throw new Error("tableName is required");
|
|
1174
1232
|
return this.withDatabase(async () => {
|
|
1175
1233
|
const conditions = [eq(memoryTable.type, tableName)];
|
|
1176
1234
|
if (start) {
|
|
1177
|
-
conditions.push(gte(memoryTable.createdAt, start));
|
|
1235
|
+
conditions.push(gte(memoryTable.createdAt, new Date(start)));
|
|
1178
1236
|
}
|
|
1179
1237
|
if (entityId) {
|
|
1180
1238
|
conditions.push(eq(memoryTable.entityId, entityId));
|
|
@@ -1186,9 +1244,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1186
1244
|
conditions.push(eq(memoryTable.worldId, worldId));
|
|
1187
1245
|
}
|
|
1188
1246
|
if (end) {
|
|
1189
|
-
conditions.push(lte(memoryTable.createdAt, end));
|
|
1247
|
+
conditions.push(lte(memoryTable.createdAt, new Date(end)));
|
|
1190
1248
|
}
|
|
1191
|
-
if (
|
|
1249
|
+
if (unique6) {
|
|
1192
1250
|
conditions.push(eq(memoryTable.unique, true));
|
|
1193
1251
|
}
|
|
1194
1252
|
if (agentId) {
|
|
@@ -1212,7 +1270,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1212
1270
|
return rows.map((row) => ({
|
|
1213
1271
|
id: row.memory.id,
|
|
1214
1272
|
type: row.memory.type,
|
|
1215
|
-
createdAt: row.memory.createdAt,
|
|
1273
|
+
createdAt: row.memory.createdAt.getTime(),
|
|
1216
1274
|
content: typeof row.memory.content === "string" ? JSON.parse(row.memory.content) : row.memory.content,
|
|
1217
1275
|
entityId: row.memory.entityId,
|
|
1218
1276
|
agentId: row.memory.agentId,
|
|
@@ -1253,7 +1311,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1253
1311
|
const rows = params.limit ? await query.limit(params.limit) : await query;
|
|
1254
1312
|
return rows.map((row) => ({
|
|
1255
1313
|
id: row.id,
|
|
1256
|
-
createdAt: row.createdAt,
|
|
1314
|
+
createdAt: row.createdAt.getTime(),
|
|
1257
1315
|
content: typeof row.content === "string" ? JSON.parse(row.content) : row.content,
|
|
1258
1316
|
entityId: row.entityId,
|
|
1259
1317
|
agentId: row.agentId,
|
|
@@ -1278,7 +1336,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1278
1336
|
const row = result[0];
|
|
1279
1337
|
return {
|
|
1280
1338
|
id: row.memory.id,
|
|
1281
|
-
createdAt: row.memory.createdAt,
|
|
1339
|
+
createdAt: row.memory.createdAt.getTime(),
|
|
1282
1340
|
content: typeof row.memory.content === "string" ? JSON.parse(row.memory.content) : row.memory.content,
|
|
1283
1341
|
entityId: row.memory.entityId,
|
|
1284
1342
|
agentId: row.memory.agentId,
|
|
@@ -1309,7 +1367,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1309
1367
|
}).from(memoryTable).leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id)).where(and(...conditions)).orderBy(desc(memoryTable.createdAt));
|
|
1310
1368
|
return rows.map((row) => ({
|
|
1311
1369
|
id: row.memory.id,
|
|
1312
|
-
createdAt: row.memory.createdAt,
|
|
1370
|
+
createdAt: row.memory.createdAt.getTime(),
|
|
1313
1371
|
content: typeof row.memory.content === "string" ? JSON.parse(row.memory.content) : row.memory.content,
|
|
1314
1372
|
entityId: row.memory.entityId,
|
|
1315
1373
|
agentId: row.memory.agentId,
|
|
@@ -1560,7 +1618,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1560
1618
|
return results.map((row) => ({
|
|
1561
1619
|
id: row.memory.id,
|
|
1562
1620
|
type: row.memory.type,
|
|
1563
|
-
createdAt: row.memory.createdAt,
|
|
1621
|
+
createdAt: row.memory.createdAt.getTime(),
|
|
1564
1622
|
content: typeof row.memory.content === "string" ? JSON.parse(row.memory.content) : row.memory.content,
|
|
1565
1623
|
entityId: row.memory.entityId,
|
|
1566
1624
|
agentId: row.memory.agentId,
|
|
@@ -1619,16 +1677,16 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1619
1677
|
roomId: memory.roomId,
|
|
1620
1678
|
worldId: memory.worldId,
|
|
1621
1679
|
// Include worldId
|
|
1622
|
-
agentId: this.agentId,
|
|
1680
|
+
agentId: memory.agentId || this.agentId,
|
|
1623
1681
|
unique: memory.unique ?? isUnique,
|
|
1624
|
-
createdAt: memory.createdAt
|
|
1682
|
+
createdAt: memory.createdAt ? new Date(memory.createdAt) : /* @__PURE__ */ new Date()
|
|
1625
1683
|
}
|
|
1626
1684
|
]);
|
|
1627
1685
|
if (memory.embedding && Array.isArray(memory.embedding)) {
|
|
1628
1686
|
const embeddingValues = {
|
|
1629
1687
|
id: v4(),
|
|
1630
1688
|
memoryId,
|
|
1631
|
-
createdAt: memory.createdAt
|
|
1689
|
+
createdAt: memory.createdAt ? new Date(memory.createdAt) : /* @__PURE__ */ new Date()
|
|
1632
1690
|
};
|
|
1633
1691
|
const cleanVector = memory.embedding.map(
|
|
1634
1692
|
(n) => Number.isFinite(n) ? Number(n.toFixed(6)) : 0
|
|
@@ -1676,7 +1734,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1676
1734
|
const embeddingValues = {
|
|
1677
1735
|
id: v4(),
|
|
1678
1736
|
memoryId: memory.id,
|
|
1679
|
-
createdAt: Date.
|
|
1737
|
+
createdAt: (/* @__PURE__ */ new Date()).getTime()
|
|
1680
1738
|
};
|
|
1681
1739
|
embeddingValues[this.embeddingDimension] = cleanVector;
|
|
1682
1740
|
await tx.insert(embeddingTable).values([embeddingValues]);
|
|
@@ -1713,6 +1771,34 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1713
1771
|
});
|
|
1714
1772
|
});
|
|
1715
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
|
+
}
|
|
1716
1802
|
/**
|
|
1717
1803
|
* Deletes all memory fragments that reference a specific document memory
|
|
1718
1804
|
* @param tx The database transaction
|
|
@@ -1780,11 +1866,11 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1780
1866
|
* @param {string} [tableName] - The name of the table to count memories in.
|
|
1781
1867
|
* @returns {Promise<number>} A Promise that resolves to the number of memories.
|
|
1782
1868
|
*/
|
|
1783
|
-
async countMemories(roomId,
|
|
1869
|
+
async countMemories(roomId, unique6 = true, tableName = "") {
|
|
1784
1870
|
if (!tableName) throw new Error("tableName is required");
|
|
1785
1871
|
return this.withDatabase(async () => {
|
|
1786
1872
|
const conditions = [eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)];
|
|
1787
|
-
if (
|
|
1873
|
+
if (unique6) {
|
|
1788
1874
|
conditions.push(eq(memoryTable.unique, true));
|
|
1789
1875
|
}
|
|
1790
1876
|
const result = await this.db.select({ count: sql16`count(*)` }).from(memoryTable).where(and(...conditions));
|
|
@@ -2135,37 +2221,29 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2135
2221
|
*/
|
|
2136
2222
|
async getRelationship(params) {
|
|
2137
2223
|
return this.withDatabase(async () => {
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
};
|
|
2158
|
-
} catch (error) {
|
|
2159
|
-
logger.error("Error getting relationship:", {
|
|
2160
|
-
error: error instanceof Error ? error.message : String(error),
|
|
2161
|
-
params
|
|
2162
|
-
});
|
|
2163
|
-
return null;
|
|
2164
|
-
}
|
|
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
|
+
};
|
|
2165
2243
|
});
|
|
2166
2244
|
}
|
|
2167
2245
|
/**
|
|
2168
|
-
* Asynchronously retrieves
|
|
2246
|
+
* Asynchronously retrieves relationships from the database based on the provided parameters.
|
|
2169
2247
|
* @param {Object} params - The parameters for retrieving relationships.
|
|
2170
2248
|
* @param {UUID} params.entityId - The ID of the entity to retrieve relationships for.
|
|
2171
2249
|
* @param {string[]} [params.tags] - The tags to filter relationships by.
|
|
@@ -2173,27 +2251,30 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2173
2251
|
*/
|
|
2174
2252
|
async getRelationships(params) {
|
|
2175
2253
|
return this.withDatabase(async () => {
|
|
2176
|
-
const
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
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()
|
|
2197
2278
|
}));
|
|
2198
2279
|
});
|
|
2199
2280
|
}
|
|
@@ -2205,8 +2286,11 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2205
2286
|
async getCache(key) {
|
|
2206
2287
|
return this.withDatabase(async () => {
|
|
2207
2288
|
try {
|
|
2208
|
-
const result = await this.db.select().from(cacheTable).where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key)));
|
|
2209
|
-
|
|
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;
|
|
2210
2294
|
} catch (error) {
|
|
2211
2295
|
logger.error("Error fetching cache", {
|
|
2212
2296
|
error: error instanceof Error ? error.message : String(error),
|
|
@@ -2226,17 +2310,15 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2226
2310
|
async setCache(key, value) {
|
|
2227
2311
|
return this.withDatabase(async () => {
|
|
2228
2312
|
try {
|
|
2229
|
-
await this.db.
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
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: {
|
|
2233
2320
|
value
|
|
2234
|
-
}
|
|
2235
|
-
target: [cacheTable.key, cacheTable.agentId],
|
|
2236
|
-
set: {
|
|
2237
|
-
value
|
|
2238
|
-
}
|
|
2239
|
-
});
|
|
2321
|
+
}
|
|
2240
2322
|
});
|
|
2241
2323
|
return true;
|
|
2242
2324
|
} catch (error) {
|
|
@@ -2295,7 +2377,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2295
2377
|
async getWorld(id) {
|
|
2296
2378
|
return this.withDatabase(async () => {
|
|
2297
2379
|
const result = await this.db.select().from(worldTable).where(eq(worldTable.id, id));
|
|
2298
|
-
return result[0];
|
|
2380
|
+
return result.length > 0 ? result[0] : null;
|
|
2299
2381
|
});
|
|
2300
2382
|
}
|
|
2301
2383
|
/**
|
|
@@ -2450,21 +2532,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2450
2532
|
if (task.roomId !== void 0) updateValues.roomId = task.roomId;
|
|
2451
2533
|
if (task.worldId !== void 0) updateValues.worldId = task.worldId;
|
|
2452
2534
|
if (task.tags !== void 0) updateValues.tags = task.tags;
|
|
2453
|
-
|
|
2454
|
-
if (task.metadata) {
|
|
2455
|
-
|
|
2456
|
-
if (currentTask) {
|
|
2457
|
-
const currentMetadata = currentTask.metadata || {};
|
|
2458
|
-
const newMetadata = {
|
|
2459
|
-
...currentMetadata,
|
|
2460
|
-
...task.metadata
|
|
2461
|
-
};
|
|
2462
|
-
updateValues.metadata = newMetadata;
|
|
2463
|
-
} else {
|
|
2464
|
-
updateValues.metadata = {
|
|
2465
|
-
...task.metadata
|
|
2466
|
-
};
|
|
2467
|
-
}
|
|
2535
|
+
updateValues.updatedAt = /* @__PURE__ */ new Date();
|
|
2536
|
+
if (task.metadata !== void 0) {
|
|
2537
|
+
updateValues.metadata = task.metadata;
|
|
2468
2538
|
}
|
|
2469
2539
|
await this.db.update(taskTable).set(updateValues).where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)));
|
|
2470
2540
|
});
|
|
@@ -2724,6 +2794,47 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
2724
2794
|
await this.db.delete(messageTable).where(eq(messageTable.id, messageId));
|
|
2725
2795
|
});
|
|
2726
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
|
+
}
|
|
2727
2838
|
/**
|
|
2728
2839
|
* Adds participants to a channel
|
|
2729
2840
|
*/
|
|
@@ -2827,7 +2938,7 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
2827
2938
|
/**
|
|
2828
2939
|
* Constructor for creating an instance of a class.
|
|
2829
2940
|
* @param {UUID} agentId - The unique identifier for the agent.
|
|
2830
|
-
* @param {PGliteClientManager} manager - The manager for the
|
|
2941
|
+
* @param {PGliteClientManager} manager - The manager for the Pglite client.
|
|
2831
2942
|
*/
|
|
2832
2943
|
constructor(agentId, manager) {
|
|
2833
2944
|
super(agentId);
|
|
@@ -2835,8 +2946,16 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
2835
2946
|
this.db = drizzle(this.manager.getConnection());
|
|
2836
2947
|
}
|
|
2837
2948
|
/**
|
|
2838
|
-
*
|
|
2839
|
-
*
|
|
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.
|
|
2840
2959
|
*
|
|
2841
2960
|
* @param {Function} operation - The database operation to be performed.
|
|
2842
2961
|
* @returns {Promise<T>} A promise that resolves with the result of the database operation.
|
|
@@ -2849,26 +2968,29 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
2849
2968
|
return operation();
|
|
2850
2969
|
}
|
|
2851
2970
|
/**
|
|
2852
|
-
* Asynchronously initializes the database by running migrations
|
|
2971
|
+
* Asynchronously initializes the database by running migrations.
|
|
2853
2972
|
*
|
|
2854
2973
|
* @returns {Promise<void>} A Promise that resolves when the database initialization is complete.
|
|
2855
2974
|
*/
|
|
2856
2975
|
async init() {
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2976
|
+
logger2.debug("PGliteDatabaseAdapter initialized, skipping automatic migrations.");
|
|
2977
|
+
}
|
|
2978
|
+
/**
|
|
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();
|
|
2863
2985
|
}
|
|
2864
2986
|
/**
|
|
2865
|
-
* Asynchronously closes the
|
|
2987
|
+
* Asynchronously closes the database.
|
|
2866
2988
|
*/
|
|
2867
2989
|
async close() {
|
|
2868
2990
|
await this.manager.close();
|
|
2869
2991
|
}
|
|
2870
2992
|
/**
|
|
2871
|
-
* Asynchronously retrieves the connection from the
|
|
2993
|
+
* Asynchronously retrieves the connection from the client.
|
|
2872
2994
|
*
|
|
2873
2995
|
* @returns {Promise<PGlite>} A Promise that resolves with the connection.
|
|
2874
2996
|
*/
|
|
@@ -2877,24 +2999,69 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
2877
2999
|
}
|
|
2878
3000
|
};
|
|
2879
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
|
+
|
|
2880
3043
|
// src/pg/adapter.ts
|
|
2881
3044
|
import { logger as logger3 } from "@elizaos/core";
|
|
2882
3045
|
import { drizzle as drizzle2 } from "drizzle-orm/node-postgres";
|
|
2883
3046
|
var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
2884
|
-
/**
|
|
2885
|
-
* Constructor for creating a new instance of a class.
|
|
2886
|
-
* @param {UUID} agentId - The unique identifier for the agent.
|
|
2887
|
-
* @param {PostgresConnectionManager} manager - The Postgres connection manager for the instance.
|
|
2888
|
-
*/
|
|
2889
3047
|
constructor(agentId, manager) {
|
|
2890
3048
|
super(agentId);
|
|
2891
3049
|
this.manager = manager;
|
|
2892
3050
|
this.manager = manager;
|
|
3051
|
+
this.db = this.manager.getDatabase();
|
|
2893
3052
|
}
|
|
2894
3053
|
static {
|
|
2895
3054
|
__name(this, "PgDatabaseAdapter");
|
|
2896
3055
|
}
|
|
2897
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
|
+
}
|
|
2898
3065
|
/**
|
|
2899
3066
|
* Executes the provided operation with a database connection.
|
|
2900
3067
|
*
|
|
@@ -2921,13 +3088,14 @@ var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
2921
3088
|
* @returns {Promise<void>} A promise that resolves when initialization is complete.
|
|
2922
3089
|
*/
|
|
2923
3090
|
async init() {
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
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();
|
|
2931
3099
|
}
|
|
2932
3100
|
/**
|
|
2933
3101
|
* Asynchronously closes the manager associated with this instance.
|
|
@@ -2940,13 +3108,1021 @@ var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
2940
3108
|
/**
|
|
2941
3109
|
* Asynchronously retrieves the connection from the manager.
|
|
2942
3110
|
*
|
|
2943
|
-
* @returns {Promise<
|
|
3111
|
+
* @returns {Promise<Pool>} A Promise that resolves with the connection.
|
|
2944
3112
|
*/
|
|
2945
3113
|
async getConnection() {
|
|
2946
3114
|
return this.manager.getConnection();
|
|
2947
3115
|
}
|
|
2948
3116
|
};
|
|
2949
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 schemas = searchPath.split(",").map((s) => s.trim());
|
|
3843
|
+
for (const schema of schemas) {
|
|
3844
|
+
if (schema && !schema.includes("$user")) {
|
|
3845
|
+
return schema;
|
|
3846
|
+
}
|
|
3847
|
+
}
|
|
3848
|
+
}
|
|
3849
|
+
} catch (e) {
|
|
3850
|
+
logger5.debug("Could not determine search_path, defaulting to public schema.");
|
|
3851
|
+
}
|
|
3852
|
+
return "public";
|
|
3853
|
+
}
|
|
3854
|
+
return pluginName.replace(/@elizaos\/plugin-|\W/g, "_").toLowerCase();
|
|
3855
|
+
}
|
|
3856
|
+
async ensureNamespace(schemaName) {
|
|
3857
|
+
if (schemaName === "public") return;
|
|
3858
|
+
await this.db.execute(sql17.raw(`CREATE SCHEMA IF NOT EXISTS "${schemaName}"`));
|
|
3859
|
+
}
|
|
3860
|
+
async introspectExistingTables(schemaName) {
|
|
3861
|
+
const res = await this.db.execute(
|
|
3862
|
+
sql17.raw(
|
|
3863
|
+
`SELECT table_name FROM information_schema.tables WHERE table_schema = '${schemaName}'`
|
|
3864
|
+
)
|
|
3865
|
+
);
|
|
3866
|
+
return res.rows.map((row) => row.table_name);
|
|
3867
|
+
}
|
|
3868
|
+
async foreignKeyExists(schemaName, tableName, constraintName) {
|
|
3869
|
+
try {
|
|
3870
|
+
const res = await this.db.execute(
|
|
3871
|
+
sql17.raw(
|
|
3872
|
+
`SELECT constraint_name
|
|
3873
|
+
FROM information_schema.table_constraints
|
|
3874
|
+
WHERE table_schema = '${schemaName}'
|
|
3875
|
+
AND table_name = '${tableName}'
|
|
3876
|
+
AND constraint_name = '${constraintName}'
|
|
3877
|
+
AND constraint_type = 'FOREIGN KEY'`
|
|
3878
|
+
)
|
|
3879
|
+
);
|
|
3880
|
+
return res.rows.length > 0;
|
|
3881
|
+
} catch (error) {
|
|
3882
|
+
return false;
|
|
3883
|
+
}
|
|
3884
|
+
}
|
|
3885
|
+
async checkConstraintExists(schemaName, tableName, constraintName) {
|
|
3886
|
+
try {
|
|
3887
|
+
const res = await this.db.execute(
|
|
3888
|
+
sql17.raw(
|
|
3889
|
+
`SELECT constraint_name
|
|
3890
|
+
FROM information_schema.table_constraints
|
|
3891
|
+
WHERE table_schema = '${schemaName}'
|
|
3892
|
+
AND table_name = '${tableName}'
|
|
3893
|
+
AND constraint_name = '${constraintName}'
|
|
3894
|
+
AND constraint_type = 'CHECK'`
|
|
3895
|
+
)
|
|
3896
|
+
);
|
|
3897
|
+
return res.rows.length > 0;
|
|
3898
|
+
} catch (error) {
|
|
3899
|
+
return false;
|
|
3900
|
+
}
|
|
3901
|
+
}
|
|
3902
|
+
async uniqueConstraintExists(schemaName, tableName, constraintName) {
|
|
3903
|
+
try {
|
|
3904
|
+
const res = await this.db.execute(
|
|
3905
|
+
sql17.raw(
|
|
3906
|
+
`SELECT constraint_name
|
|
3907
|
+
FROM information_schema.table_constraints
|
|
3908
|
+
WHERE table_schema = '${schemaName}'
|
|
3909
|
+
AND table_name = '${tableName}'
|
|
3910
|
+
AND constraint_name = '${constraintName}'
|
|
3911
|
+
AND constraint_type = 'UNIQUE'`
|
|
3912
|
+
)
|
|
3913
|
+
);
|
|
3914
|
+
return res.rows.length > 0;
|
|
3915
|
+
} catch (error) {
|
|
3916
|
+
return false;
|
|
3917
|
+
}
|
|
3918
|
+
}
|
|
3919
|
+
async createTable(tableDef, schemaName) {
|
|
3920
|
+
const introspector = new DrizzleSchemaIntrospector();
|
|
3921
|
+
const createTableSQL = introspector.generateCreateTableSQL(tableDef, schemaName);
|
|
3922
|
+
await this.db.execute(sql17.raw(createTableSQL));
|
|
3923
|
+
logger5.info(`Created table: ${tableDef.name}`);
|
|
3924
|
+
}
|
|
3925
|
+
async addConstraints(tableDef, schemaName) {
|
|
3926
|
+
if (tableDef.foreignKeys.length > 0) {
|
|
3927
|
+
const introspector = new DrizzleSchemaIntrospector();
|
|
3928
|
+
const constraintSQLs = introspector.generateForeignKeySQL(tableDef, schemaName);
|
|
3929
|
+
for (let i = 0; i < tableDef.foreignKeys.length; i++) {
|
|
3930
|
+
const fk = tableDef.foreignKeys[i];
|
|
3931
|
+
const constraintSQL = constraintSQLs[i];
|
|
3932
|
+
try {
|
|
3933
|
+
const exists = await this.foreignKeyExists(schemaName, tableDef.name, fk.name);
|
|
3934
|
+
if (exists) {
|
|
3935
|
+
logger5.debug(
|
|
3936
|
+
`[CUSTOM MIGRATOR] Foreign key constraint ${fk.name} already exists, skipping`
|
|
3937
|
+
);
|
|
3938
|
+
continue;
|
|
3939
|
+
}
|
|
3940
|
+
await this.db.execute(sql17.raw(constraintSQL));
|
|
3941
|
+
logger5.debug(`[CUSTOM MIGRATOR] Successfully added foreign key constraint: ${fk.name}`);
|
|
3942
|
+
} catch (error) {
|
|
3943
|
+
if (error.message?.includes("already exists")) {
|
|
3944
|
+
logger5.debug(`[CUSTOM MIGRATOR] Foreign key constraint already exists: ${fk.name}`);
|
|
3945
|
+
} else {
|
|
3946
|
+
logger5.warn(
|
|
3947
|
+
`[CUSTOM MIGRATOR] Could not add foreign key constraint (may already exist): ${error.message}`
|
|
3948
|
+
);
|
|
3949
|
+
}
|
|
3950
|
+
}
|
|
3951
|
+
}
|
|
3952
|
+
}
|
|
3953
|
+
if (tableDef.checkConstraints.length > 0) {
|
|
3954
|
+
for (const checkConstraint of tableDef.checkConstraints) {
|
|
3955
|
+
try {
|
|
3956
|
+
const exists = await this.checkConstraintExists(
|
|
3957
|
+
schemaName,
|
|
3958
|
+
tableDef.name,
|
|
3959
|
+
checkConstraint.name
|
|
3960
|
+
);
|
|
3961
|
+
if (exists) {
|
|
3962
|
+
logger5.debug(
|
|
3963
|
+
`[CUSTOM MIGRATOR] Check constraint ${checkConstraint.name} already exists, skipping`
|
|
3964
|
+
);
|
|
3965
|
+
continue;
|
|
3966
|
+
}
|
|
3967
|
+
const checkSQL = `ALTER TABLE "${schemaName}"."${tableDef.name}" ADD CONSTRAINT "${checkConstraint.name}" CHECK (${checkConstraint.expression})`;
|
|
3968
|
+
await this.db.execute(sql17.raw(checkSQL));
|
|
3969
|
+
logger5.debug(
|
|
3970
|
+
`[CUSTOM MIGRATOR] Successfully added check constraint: ${checkConstraint.name}`
|
|
3971
|
+
);
|
|
3972
|
+
} catch (error) {
|
|
3973
|
+
if (error.message?.includes("already exists")) {
|
|
3974
|
+
logger5.debug(
|
|
3975
|
+
`[CUSTOM MIGRATOR] Check constraint already exists: ${checkConstraint.name}`
|
|
3976
|
+
);
|
|
3977
|
+
} else {
|
|
3978
|
+
logger5.warn(
|
|
3979
|
+
`[CUSTOM MIGRATOR] Could not add check constraint ${checkConstraint.name} (may already exist): ${error.message}`
|
|
3980
|
+
);
|
|
3981
|
+
}
|
|
3982
|
+
}
|
|
3983
|
+
}
|
|
3984
|
+
}
|
|
3985
|
+
}
|
|
3986
|
+
};
|
|
3987
|
+
var ExtensionManager = class {
|
|
3988
|
+
constructor(db) {
|
|
3989
|
+
this.db = db;
|
|
3990
|
+
}
|
|
3991
|
+
static {
|
|
3992
|
+
__name(this, "ExtensionManager");
|
|
3993
|
+
}
|
|
3994
|
+
async installRequiredExtensions() {
|
|
3995
|
+
if (this.db?.driver?.constructor?.name === "PGlite") {
|
|
3996
|
+
logger5.debug("[CUSTOM MIGRATOR] PGLite detected, skipping extension creation via SQL.");
|
|
3997
|
+
return;
|
|
3998
|
+
}
|
|
3999
|
+
const extensions = ["vector", "fuzzystrmatch"];
|
|
4000
|
+
for (const extension of extensions) {
|
|
4001
|
+
try {
|
|
4002
|
+
await this.db.execute(sql17.raw(`CREATE EXTENSION IF NOT EXISTS "${extension}"`));
|
|
4003
|
+
} catch (e) {
|
|
4004
|
+
logger5.warn(`Could not install extension ${extension}:`, e);
|
|
4005
|
+
}
|
|
4006
|
+
}
|
|
4007
|
+
}
|
|
4008
|
+
};
|
|
4009
|
+
function topologicalSort(tables) {
|
|
4010
|
+
const sorted = [];
|
|
4011
|
+
const visited = /* @__PURE__ */ new Set();
|
|
4012
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
4013
|
+
function visit(tableName) {
|
|
4014
|
+
if (visiting.has(tableName)) {
|
|
4015
|
+
logger5.warn(`Circular dependency detected involving table: ${tableName}`);
|
|
4016
|
+
return;
|
|
4017
|
+
}
|
|
4018
|
+
if (visited.has(tableName)) {
|
|
4019
|
+
return;
|
|
4020
|
+
}
|
|
4021
|
+
visiting.add(tableName);
|
|
4022
|
+
const table = tables.get(tableName);
|
|
4023
|
+
if (table) {
|
|
4024
|
+
for (const dep of table.dependencies) {
|
|
4025
|
+
if (tables.has(dep)) {
|
|
4026
|
+
visit(dep);
|
|
4027
|
+
}
|
|
4028
|
+
}
|
|
4029
|
+
}
|
|
4030
|
+
visiting.delete(tableName);
|
|
4031
|
+
visited.add(tableName);
|
|
4032
|
+
sorted.push(tableName);
|
|
4033
|
+
}
|
|
4034
|
+
__name(visit, "visit");
|
|
4035
|
+
for (const tableName of tables.keys()) {
|
|
4036
|
+
visit(tableName);
|
|
4037
|
+
}
|
|
4038
|
+
return sorted;
|
|
4039
|
+
}
|
|
4040
|
+
__name(topologicalSort, "topologicalSort");
|
|
4041
|
+
async function runPluginMigrations(db, pluginName, schema) {
|
|
4042
|
+
logger5.debug(`[CUSTOM MIGRATOR] Starting migration for plugin: ${pluginName}`);
|
|
4043
|
+
const namespaceManager = new PluginNamespaceManager(db);
|
|
4044
|
+
const introspector = new DrizzleSchemaIntrospector();
|
|
4045
|
+
const extensionManager = new ExtensionManager(db);
|
|
4046
|
+
await extensionManager.installRequiredExtensions();
|
|
4047
|
+
const schemaName = await namespaceManager.getPluginSchema(pluginName);
|
|
4048
|
+
await namespaceManager.ensureNamespace(schemaName);
|
|
4049
|
+
const existingTables = await namespaceManager.introspectExistingTables(schemaName);
|
|
4050
|
+
const tableEntries = Object.entries(schema).filter(([key, v]) => {
|
|
4051
|
+
const isDrizzleTable = v && (v._ && typeof v._.name === "string" || typeof v === "object" && v !== null && ("tableName" in v || "dbName" in v || key.toLowerCase().includes("table")));
|
|
4052
|
+
return isDrizzleTable;
|
|
4053
|
+
});
|
|
4054
|
+
const tableDefinitions = /* @__PURE__ */ new Map();
|
|
4055
|
+
for (const [exportKey, table] of tableEntries) {
|
|
4056
|
+
const tableDef = introspector.parseTableDefinition(table, exportKey);
|
|
4057
|
+
tableDefinitions.set(tableDef.name, tableDef);
|
|
4058
|
+
}
|
|
4059
|
+
const sortedTableNames = topologicalSort(tableDefinitions);
|
|
4060
|
+
logger5.debug(`[CUSTOM MIGRATOR] Phase 1: Creating tables...`);
|
|
4061
|
+
for (const tableName of sortedTableNames) {
|
|
4062
|
+
const tableDef = tableDefinitions.get(tableName);
|
|
4063
|
+
if (!tableDef) continue;
|
|
4064
|
+
const tableExists = existingTables.includes(tableDef.name);
|
|
4065
|
+
logger5.debug(`[CUSTOM MIGRATOR] Table ${tableDef.name} exists: ${tableExists}`);
|
|
4066
|
+
if (!tableExists) {
|
|
4067
|
+
logger5.debug(`[CUSTOM MIGRATOR] Creating table: ${tableDef.name}`);
|
|
4068
|
+
await namespaceManager.createTable(tableDef, schemaName);
|
|
4069
|
+
} else {
|
|
4070
|
+
logger5.debug(`[CUSTOM MIGRATOR] Table ${tableDef.name} already exists, skipping creation`);
|
|
4071
|
+
}
|
|
4072
|
+
}
|
|
4073
|
+
logger5.debug(`[CUSTOM MIGRATOR] Phase 2: Adding constraints...`);
|
|
4074
|
+
for (const tableName of sortedTableNames) {
|
|
4075
|
+
const tableDef = tableDefinitions.get(tableName);
|
|
4076
|
+
if (!tableDef) continue;
|
|
4077
|
+
if (tableDef.foreignKeys.length > 0 || tableDef.checkConstraints.length > 0) {
|
|
4078
|
+
logger5.debug(`[CUSTOM MIGRATOR] Adding constraints for table: ${tableDef.name}`, {
|
|
4079
|
+
foreignKeys: tableDef.foreignKeys.length,
|
|
4080
|
+
checkConstraints: tableDef.checkConstraints.length
|
|
4081
|
+
});
|
|
4082
|
+
await namespaceManager.addConstraints(tableDef, schemaName);
|
|
4083
|
+
}
|
|
4084
|
+
}
|
|
4085
|
+
logger5.debug(`[CUSTOM MIGRATOR] Completed migration for plugin: ${pluginName}`);
|
|
4086
|
+
}
|
|
4087
|
+
__name(runPluginMigrations, "runPluginMigrations");
|
|
4088
|
+
|
|
4089
|
+
// src/migration-service.ts
|
|
4090
|
+
var DatabaseMigrationService = class {
|
|
4091
|
+
static {
|
|
4092
|
+
__name(this, "DatabaseMigrationService");
|
|
4093
|
+
}
|
|
4094
|
+
db = null;
|
|
4095
|
+
registeredSchemas = /* @__PURE__ */ new Map();
|
|
4096
|
+
constructor() {
|
|
4097
|
+
}
|
|
4098
|
+
async initializeWithDatabase(db) {
|
|
4099
|
+
this.db = db;
|
|
4100
|
+
logger6.info("DatabaseMigrationService initialized with database");
|
|
4101
|
+
}
|
|
4102
|
+
discoverAndRegisterPluginSchemas(plugins) {
|
|
4103
|
+
for (const plugin2 of plugins) {
|
|
4104
|
+
if (plugin2.schema) {
|
|
4105
|
+
this.registeredSchemas.set(plugin2.name, plugin2.schema);
|
|
4106
|
+
logger6.info(`Registered schema for plugin: ${plugin2.name}`);
|
|
4107
|
+
}
|
|
4108
|
+
}
|
|
4109
|
+
logger6.info(
|
|
4110
|
+
`Discovered ${this.registeredSchemas.size} plugin schemas out of ${plugins.length} plugins`
|
|
4111
|
+
);
|
|
4112
|
+
}
|
|
4113
|
+
async runAllPluginMigrations() {
|
|
4114
|
+
if (!this.db) {
|
|
4115
|
+
throw new Error("Database not initialized in DatabaseMigrationService");
|
|
4116
|
+
}
|
|
4117
|
+
logger6.info(`Running migrations for ${this.registeredSchemas.size} plugins...`);
|
|
4118
|
+
for (const [pluginName, schema] of this.registeredSchemas) {
|
|
4119
|
+
logger6.info(`Starting migration for plugin: ${pluginName}`);
|
|
4120
|
+
await runPluginMigrations(this.db, pluginName, schema);
|
|
4121
|
+
}
|
|
4122
|
+
logger6.info("All plugin migrations completed.");
|
|
4123
|
+
}
|
|
4124
|
+
};
|
|
4125
|
+
|
|
2950
4126
|
// src/index.ts
|
|
2951
4127
|
var GLOBAL_SINGLETONS = Symbol.for("@elizaos/plugin-sql/global-singletons");
|
|
2952
4128
|
var globalSymbols = global;
|
|
@@ -2970,27 +4146,40 @@ function createDatabaseAdapter(config, agentId) {
|
|
|
2970
4146
|
return new PgliteDatabaseAdapter(agentId, globalSingletons.pgLiteClientManager);
|
|
2971
4147
|
}
|
|
2972
4148
|
__name(createDatabaseAdapter, "createDatabaseAdapter");
|
|
2973
|
-
var
|
|
2974
|
-
name: "sql",
|
|
2975
|
-
description: "SQL database
|
|
4149
|
+
var plugin = {
|
|
4150
|
+
name: "@elizaos/plugin-sql",
|
|
4151
|
+
description: "A plugin for SQL database access with dynamic schema migrations",
|
|
4152
|
+
priority: 0,
|
|
4153
|
+
schema: schema_exports,
|
|
2976
4154
|
init: /* @__PURE__ */ __name(async (_, runtime) => {
|
|
2977
|
-
|
|
2978
|
-
dataDir: resolvePgliteDir(runtime.getSetting("PGLITE_DATA_DIR")),
|
|
2979
|
-
postgresUrl: runtime.getSetting("POSTGRES_URL")
|
|
2980
|
-
};
|
|
4155
|
+
logger7.info("plugin-sql init starting...");
|
|
2981
4156
|
try {
|
|
2982
|
-
const
|
|
2983
|
-
|
|
2984
|
-
|
|
4157
|
+
const existingAdapter = runtime.databaseAdapter;
|
|
4158
|
+
if (existingAdapter) {
|
|
4159
|
+
logger7.info("Database adapter already registered, skipping creation");
|
|
4160
|
+
return;
|
|
4161
|
+
}
|
|
2985
4162
|
} catch (error) {
|
|
2986
|
-
logger4.error("Failed to initialize database:", error);
|
|
2987
|
-
throw error;
|
|
2988
4163
|
}
|
|
4164
|
+
const postgresUrl = runtime.getSetting("POSTGRES_URL");
|
|
4165
|
+
const dataDir = runtime.getSetting("PGLITE_PATH") || runtime.getSetting("DATABASE_PATH") || "./.eliza/.elizadb";
|
|
4166
|
+
const dbAdapter = createDatabaseAdapter(
|
|
4167
|
+
{
|
|
4168
|
+
dataDir,
|
|
4169
|
+
postgresUrl
|
|
4170
|
+
},
|
|
4171
|
+
runtime.agentId
|
|
4172
|
+
);
|
|
4173
|
+
runtime.registerDatabaseAdapter(dbAdapter);
|
|
4174
|
+
logger7.info("Database adapter created and registered");
|
|
2989
4175
|
}, "init")
|
|
2990
4176
|
};
|
|
2991
|
-
var index_default =
|
|
4177
|
+
var index_default = plugin;
|
|
2992
4178
|
export {
|
|
4179
|
+
DatabaseMigrationService,
|
|
2993
4180
|
createDatabaseAdapter,
|
|
2994
|
-
index_default as default
|
|
4181
|
+
index_default as default,
|
|
4182
|
+
plugin,
|
|
4183
|
+
schema_exports as schema
|
|
2995
4184
|
};
|
|
2996
4185
|
//# sourceMappingURL=index.js.map
|