@elizaos/plugin-sql 2.0.0-alpha.14 → 2.0.0-alpha.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index.browser.js +1252 -709
- package/dist/browser/index.browser.js.map +8 -8
- package/dist/cjs/index.node.cjs +1294 -733
- package/dist/cjs/index.node.cjs.map +6 -6
- package/dist/node/index.node.js +1256 -712
- package/dist/node/index.node.js.map +6 -6
- package/package.json +1 -1
package/dist/node/index.node.js
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
var __defProp = Object.defineProperty;
|
|
2
|
+
var __returnValue = (v) => v;
|
|
3
|
+
function __exportSetter(name, newValue) {
|
|
4
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
5
|
+
}
|
|
2
6
|
var __export = (target, all) => {
|
|
3
7
|
for (var name in all)
|
|
4
8
|
__defProp(target, name, {
|
|
5
9
|
get: all[name],
|
|
6
10
|
enumerable: true,
|
|
7
11
|
configurable: true,
|
|
8
|
-
set: (
|
|
12
|
+
set: __exportSetter.bind(all, name)
|
|
9
13
|
});
|
|
10
14
|
};
|
|
11
15
|
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
|
|
@@ -1032,169 +1036,532 @@ var init_rls = __esm(() => {
|
|
|
1032
1036
|
init_server();
|
|
1033
1037
|
});
|
|
1034
1038
|
|
|
1035
|
-
// runtime-migrator/
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
}
|
|
1048
|
-
if (normalized === "serial") {
|
|
1049
|
-
return "integer";
|
|
1050
|
-
}
|
|
1051
|
-
if (normalized === "bigserial") {
|
|
1052
|
-
return "bigint";
|
|
1053
|
-
}
|
|
1054
|
-
if (normalized === "smallserial") {
|
|
1055
|
-
return "smallint";
|
|
1056
|
-
}
|
|
1057
|
-
if (normalized.startsWith("numeric") || normalized.startsWith("decimal")) {
|
|
1058
|
-
const match = normalized.match(/\((\d+)(?:,\s*(\d+))?\)/);
|
|
1059
|
-
if (match) {
|
|
1060
|
-
return `numeric(${match[1]}${match[2] ? `,${match[2]}` : ""})`;
|
|
1061
|
-
}
|
|
1062
|
-
return "numeric";
|
|
1063
|
-
}
|
|
1064
|
-
if (normalized.startsWith("character varying")) {
|
|
1065
|
-
return normalized.replace("character varying", "varchar");
|
|
1066
|
-
}
|
|
1067
|
-
if (normalized === "text[]" || normalized === "_text") {
|
|
1068
|
-
return "text[]";
|
|
1039
|
+
// runtime-migrator/crypto-utils.ts
|
|
1040
|
+
function extendedHash(str) {
|
|
1041
|
+
const h1 = hashWithSeed(str, 5381);
|
|
1042
|
+
const h2 = hashWithSeed(str, 7919);
|
|
1043
|
+
const h3 = hashWithSeed(str, 104729);
|
|
1044
|
+
const h4 = hashWithSeed(str, 224737);
|
|
1045
|
+
return h1 + h2 + h3 + h4;
|
|
1046
|
+
}
|
|
1047
|
+
function hashWithSeed(str, seed) {
|
|
1048
|
+
let hash = seed;
|
|
1049
|
+
for (let i = 0;i < str.length; i++) {
|
|
1050
|
+
hash = hash * 33 ^ str.charCodeAt(i);
|
|
1069
1051
|
}
|
|
1070
|
-
return
|
|
1052
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
1071
1053
|
}
|
|
1072
|
-
function
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
if (
|
|
1078
|
-
|
|
1079
|
-
if (prevIndex.concurrently !== currIndex.concurrently)
|
|
1080
|
-
return true;
|
|
1081
|
-
const prevColumns = prevIndex.columns || [];
|
|
1082
|
-
const currColumns = currIndex.columns || [];
|
|
1083
|
-
if (prevColumns.length !== currColumns.length)
|
|
1084
|
-
return true;
|
|
1085
|
-
for (let i = 0;i < prevColumns.length; i++) {
|
|
1086
|
-
const prevCol = prevColumns[i];
|
|
1087
|
-
const currCol = currColumns[i];
|
|
1088
|
-
if (typeof prevCol === "string" && typeof currCol === "string") {
|
|
1089
|
-
if (prevCol !== currCol)
|
|
1090
|
-
return true;
|
|
1091
|
-
} else if (typeof prevCol === "object" && typeof currCol === "object") {
|
|
1092
|
-
if (prevCol.expression !== currCol.expression)
|
|
1093
|
-
return true;
|
|
1094
|
-
if (prevCol.isExpression !== currCol.isExpression)
|
|
1095
|
-
return true;
|
|
1096
|
-
if (prevCol.asc !== currCol.asc)
|
|
1097
|
-
return true;
|
|
1098
|
-
if (prevCol.nulls !== currCol.nulls)
|
|
1099
|
-
return true;
|
|
1100
|
-
} else {
|
|
1101
|
-
return true;
|
|
1102
|
-
}
|
|
1054
|
+
function stringToBigInt(str) {
|
|
1055
|
+
const hash = extendedHash(str);
|
|
1056
|
+
let lockId = BigInt(`0x${hash.slice(0, 16)}`);
|
|
1057
|
+
const mask63Bits = 0x7fffffffffffffffn;
|
|
1058
|
+
lockId = lockId & mask63Bits;
|
|
1059
|
+
if (lockId === 0n) {
|
|
1060
|
+
lockId = 1n;
|
|
1103
1061
|
}
|
|
1104
|
-
return
|
|
1062
|
+
return lockId;
|
|
1105
1063
|
}
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
}
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
const table = currentSnapshot.tables[tableName];
|
|
1141
|
-
if (table.indexes) {
|
|
1142
|
-
for (const indexName in table.indexes) {
|
|
1143
|
-
diff.indexes.created.push({
|
|
1144
|
-
...table.indexes[indexName],
|
|
1145
|
-
table: tableName
|
|
1146
|
-
});
|
|
1147
|
-
}
|
|
1064
|
+
|
|
1065
|
+
// runtime-migrator/drizzle-adapters/database-introspector.ts
|
|
1066
|
+
import { logger as logger3 } from "@elizaos/core";
|
|
1067
|
+
import { sql as sql21 } from "drizzle-orm";
|
|
1068
|
+
function getRows2(result) {
|
|
1069
|
+
return result.rows;
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
class DatabaseIntrospector {
|
|
1073
|
+
db;
|
|
1074
|
+
constructor(db) {
|
|
1075
|
+
this.db = db;
|
|
1076
|
+
}
|
|
1077
|
+
async introspectSchema(schemaName = "public") {
|
|
1078
|
+
logger3.info({ src: "plugin:sql", schemaName }, "Starting database introspection");
|
|
1079
|
+
const tables = {};
|
|
1080
|
+
const schemas = {};
|
|
1081
|
+
const enums = {};
|
|
1082
|
+
const allTables = await this.getTables(schemaName);
|
|
1083
|
+
for (const tableInfo of allTables) {
|
|
1084
|
+
const tableName = tableInfo.table_name;
|
|
1085
|
+
const tableSchema = tableInfo.table_schema || "public";
|
|
1086
|
+
logger3.debug({ src: "plugin:sql", tableSchema, tableName }, "Introspecting table");
|
|
1087
|
+
const columns = await this.getColumns(tableSchema, tableName);
|
|
1088
|
+
const columnsObject = {};
|
|
1089
|
+
const uniqueConstraintObject = {};
|
|
1090
|
+
for (const col of columns) {
|
|
1091
|
+
columnsObject[col.column_name] = {
|
|
1092
|
+
name: col.column_name,
|
|
1093
|
+
type: col.data_type,
|
|
1094
|
+
primaryKey: col.is_primary || false,
|
|
1095
|
+
notNull: col.is_nullable === "NO",
|
|
1096
|
+
default: col.column_default ? this.parseDefault(col.column_default, col.data_type) : undefined
|
|
1097
|
+
};
|
|
1148
1098
|
}
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1099
|
+
const indexes = await this.getIndexes(tableSchema, tableName);
|
|
1100
|
+
const indexesObject = {};
|
|
1101
|
+
for (const idx of indexes) {
|
|
1102
|
+
if (!idx.is_primary && !idx.is_unique_constraint) {
|
|
1103
|
+
if (idx.columns && Array.isArray(idx.columns) && idx.columns.length > 0) {
|
|
1104
|
+
indexesObject[idx.name] = {
|
|
1105
|
+
name: idx.name,
|
|
1106
|
+
columns: idx.columns.map((col) => ({
|
|
1107
|
+
expression: col,
|
|
1108
|
+
isExpression: false
|
|
1109
|
+
})),
|
|
1110
|
+
isUnique: idx.is_unique,
|
|
1111
|
+
method: idx.method || "btree"
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1152
1114
|
}
|
|
1153
1115
|
}
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
});
|
|
1169
|
-
}
|
|
1116
|
+
const foreignKeys = await this.getForeignKeys(tableSchema, tableName);
|
|
1117
|
+
const foreignKeysObject = {};
|
|
1118
|
+
for (const fk of foreignKeys) {
|
|
1119
|
+
foreignKeysObject[fk.name] = {
|
|
1120
|
+
name: fk.name,
|
|
1121
|
+
tableFrom: tableName,
|
|
1122
|
+
schemaFrom: tableSchema,
|
|
1123
|
+
tableTo: fk.foreign_table_name,
|
|
1124
|
+
schemaTo: fk.foreign_table_schema || "public",
|
|
1125
|
+
columnsFrom: [fk.column_name],
|
|
1126
|
+
columnsTo: [fk.foreign_column_name],
|
|
1127
|
+
onDelete: fk.delete_rule?.toLowerCase() || "no action",
|
|
1128
|
+
onUpdate: fk.update_rule?.toLowerCase() || "no action"
|
|
1129
|
+
};
|
|
1170
1130
|
}
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
}
|
|
1131
|
+
const primaryKeys = await this.getPrimaryKeys(tableSchema, tableName);
|
|
1132
|
+
const primaryKeysObject = {};
|
|
1133
|
+
for (const pk of primaryKeys) {
|
|
1134
|
+
primaryKeysObject[pk.name] = {
|
|
1135
|
+
name: pk.name,
|
|
1136
|
+
columns: pk.columns
|
|
1137
|
+
};
|
|
1178
1138
|
}
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
}
|
|
1139
|
+
const uniqueConstraints = await this.getUniqueConstraints(tableSchema, tableName);
|
|
1140
|
+
for (const unq of uniqueConstraints) {
|
|
1141
|
+
uniqueConstraintObject[unq.name] = {
|
|
1142
|
+
name: unq.name,
|
|
1143
|
+
columns: unq.columns,
|
|
1144
|
+
nullsNotDistinct: false
|
|
1145
|
+
};
|
|
1186
1146
|
}
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1147
|
+
const checkConstraints = await this.getCheckConstraints(tableSchema, tableName);
|
|
1148
|
+
const checksObject = {};
|
|
1149
|
+
for (const check3 of checkConstraints) {
|
|
1150
|
+
checksObject[check3.name] = {
|
|
1151
|
+
name: check3.name,
|
|
1152
|
+
value: check3.definition
|
|
1153
|
+
};
|
|
1191
1154
|
}
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1155
|
+
tables[`${tableSchema}.${tableName}`] = {
|
|
1156
|
+
name: tableName,
|
|
1157
|
+
schema: tableSchema,
|
|
1158
|
+
columns: columnsObject,
|
|
1159
|
+
indexes: indexesObject,
|
|
1160
|
+
foreignKeys: foreignKeysObject,
|
|
1161
|
+
compositePrimaryKeys: primaryKeysObject,
|
|
1162
|
+
uniqueConstraints: uniqueConstraintObject,
|
|
1163
|
+
checkConstraints: checksObject
|
|
1164
|
+
};
|
|
1165
|
+
if (tableSchema && tableSchema !== "public") {
|
|
1166
|
+
schemas[tableSchema] = tableSchema;
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
const enumsResult = await this.getEnums(schemaName);
|
|
1170
|
+
for (const enumInfo of enumsResult) {
|
|
1171
|
+
const key = `${enumInfo.schema}.${enumInfo.name}`;
|
|
1172
|
+
if (!enums[key]) {
|
|
1173
|
+
enums[key] = {
|
|
1174
|
+
name: enumInfo.name,
|
|
1175
|
+
schema: enumInfo.schema,
|
|
1176
|
+
values: []
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
enums[key].values.push(enumInfo.value);
|
|
1180
|
+
}
|
|
1181
|
+
logger3.info({ src: "plugin:sql", tableCount: Object.keys(tables).length }, "Database introspection complete");
|
|
1182
|
+
return {
|
|
1183
|
+
version: "7",
|
|
1184
|
+
dialect: "postgresql",
|
|
1185
|
+
tables,
|
|
1186
|
+
schemas,
|
|
1187
|
+
enums,
|
|
1188
|
+
_meta: {
|
|
1189
|
+
schemas: {},
|
|
1190
|
+
tables: {},
|
|
1191
|
+
columns: {}
|
|
1192
|
+
}
|
|
1193
|
+
};
|
|
1194
|
+
}
|
|
1195
|
+
async getTables(schemaName) {
|
|
1196
|
+
const result = await this.db.execute(sql21`SELECT
|
|
1197
|
+
table_schema,
|
|
1198
|
+
table_name
|
|
1199
|
+
FROM information_schema.tables
|
|
1200
|
+
WHERE table_schema = ${schemaName}
|
|
1201
|
+
AND table_type = 'BASE TABLE'
|
|
1202
|
+
ORDER BY table_name`);
|
|
1203
|
+
return getRows2(result);
|
|
1204
|
+
}
|
|
1205
|
+
async getColumns(schemaName, tableName) {
|
|
1206
|
+
const result = await this.db.execute(sql21`SELECT
|
|
1207
|
+
a.attname AS column_name,
|
|
1208
|
+
CASE
|
|
1209
|
+
WHEN a.attnotnull THEN 'NO'
|
|
1210
|
+
ELSE 'YES'
|
|
1211
|
+
END AS is_nullable,
|
|
1212
|
+
CASE
|
|
1213
|
+
WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
|
|
1214
|
+
AND EXISTS (
|
|
1215
|
+
SELECT FROM pg_attrdef ad
|
|
1216
|
+
WHERE ad.adrelid = a.attrelid
|
|
1217
|
+
AND ad.adnum = a.attnum
|
|
1218
|
+
AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval('''
|
|
1219
|
+
|| pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
|
|
1220
|
+
)
|
|
1221
|
+
THEN CASE a.atttypid
|
|
1222
|
+
WHEN 'int'::regtype THEN 'serial'
|
|
1223
|
+
WHEN 'int8'::regtype THEN 'bigserial'
|
|
1224
|
+
WHEN 'int2'::regtype THEN 'smallserial'
|
|
1225
|
+
END
|
|
1226
|
+
ELSE format_type(a.atttypid, a.atttypmod)
|
|
1227
|
+
END AS data_type,
|
|
1228
|
+
pg_get_expr(ad.adbin, ad.adrelid) AS column_default,
|
|
1229
|
+
CASE
|
|
1230
|
+
WHEN con.contype = 'p' THEN true
|
|
1231
|
+
ELSE false
|
|
1232
|
+
END AS is_primary
|
|
1233
|
+
FROM pg_attribute a
|
|
1234
|
+
JOIN pg_class cls ON cls.oid = a.attrelid
|
|
1235
|
+
JOIN pg_namespace ns ON ns.oid = cls.relnamespace
|
|
1236
|
+
LEFT JOIN pg_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum
|
|
1237
|
+
LEFT JOIN pg_constraint con ON con.conrelid = a.attrelid
|
|
1238
|
+
AND a.attnum = ANY(con.conkey)
|
|
1239
|
+
AND con.contype = 'p'
|
|
1240
|
+
WHERE
|
|
1241
|
+
a.attnum > 0
|
|
1242
|
+
AND NOT a.attisdropped
|
|
1243
|
+
AND ns.nspname = ${schemaName}
|
|
1244
|
+
AND cls.relname = ${tableName}
|
|
1245
|
+
ORDER BY a.attnum`);
|
|
1246
|
+
return getRows2(result);
|
|
1247
|
+
}
|
|
1248
|
+
async getIndexes(schemaName, tableName) {
|
|
1249
|
+
const result = await this.db.execute(sql21`SELECT
|
|
1250
|
+
i.relname AS name,
|
|
1251
|
+
idx.indisunique AS is_unique,
|
|
1252
|
+
idx.indisprimary AS is_primary,
|
|
1253
|
+
con.contype = 'u' AS is_unique_constraint,
|
|
1254
|
+
ARRAY(
|
|
1255
|
+
SELECT a.attname
|
|
1256
|
+
FROM pg_attribute a
|
|
1257
|
+
WHERE a.attrelid = idx.indrelid
|
|
1258
|
+
AND a.attnum = ANY(idx.indkey::int[])
|
|
1259
|
+
ORDER BY a.attnum
|
|
1260
|
+
) AS columns,
|
|
1261
|
+
am.amname AS method
|
|
1262
|
+
FROM pg_index idx
|
|
1263
|
+
JOIN pg_class i ON i.oid = idx.indexrelid
|
|
1264
|
+
JOIN pg_class c ON c.oid = idx.indrelid
|
|
1265
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
1266
|
+
JOIN pg_am am ON am.oid = i.relam
|
|
1267
|
+
LEFT JOIN pg_constraint con ON con.conindid = idx.indexrelid
|
|
1268
|
+
WHERE n.nspname = ${schemaName}
|
|
1269
|
+
AND c.relname = ${tableName}`);
|
|
1270
|
+
return getRows2(result);
|
|
1271
|
+
}
|
|
1272
|
+
async getForeignKeys(schemaName, tableName) {
|
|
1273
|
+
const result = await this.db.execute(sql21`SELECT
|
|
1274
|
+
con.conname AS name,
|
|
1275
|
+
att.attname AS column_name,
|
|
1276
|
+
fnsp.nspname AS foreign_table_schema,
|
|
1277
|
+
frel.relname AS foreign_table_name,
|
|
1278
|
+
fatt.attname AS foreign_column_name,
|
|
1279
|
+
CASE con.confupdtype
|
|
1280
|
+
WHEN 'a' THEN 'NO ACTION'
|
|
1281
|
+
WHEN 'r' THEN 'RESTRICT'
|
|
1282
|
+
WHEN 'n' THEN 'SET NULL'
|
|
1283
|
+
WHEN 'c' THEN 'CASCADE'
|
|
1284
|
+
WHEN 'd' THEN 'SET DEFAULT'
|
|
1285
|
+
END AS update_rule,
|
|
1286
|
+
CASE con.confdeltype
|
|
1287
|
+
WHEN 'a' THEN 'NO ACTION'
|
|
1288
|
+
WHEN 'r' THEN 'RESTRICT'
|
|
1289
|
+
WHEN 'n' THEN 'SET NULL'
|
|
1290
|
+
WHEN 'c' THEN 'CASCADE'
|
|
1291
|
+
WHEN 'd' THEN 'SET DEFAULT'
|
|
1292
|
+
END AS delete_rule
|
|
1293
|
+
FROM pg_catalog.pg_constraint con
|
|
1294
|
+
JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
|
|
1295
|
+
JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace
|
|
1296
|
+
LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey)
|
|
1297
|
+
AND att.attrelid = con.conrelid
|
|
1298
|
+
LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid
|
|
1299
|
+
LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace
|
|
1300
|
+
LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey)
|
|
1301
|
+
AND fatt.attrelid = con.confrelid
|
|
1302
|
+
WHERE con.contype = 'f'
|
|
1303
|
+
AND nsp.nspname = ${schemaName}
|
|
1304
|
+
AND rel.relname = ${tableName}`);
|
|
1305
|
+
return getRows2(result);
|
|
1306
|
+
}
|
|
1307
|
+
async getPrimaryKeys(schemaName, tableName) {
|
|
1308
|
+
const result = await this.db.execute(sql21`SELECT
|
|
1309
|
+
con.conname AS name,
|
|
1310
|
+
ARRAY(
|
|
1311
|
+
SELECT a.attname
|
|
1312
|
+
FROM pg_attribute a
|
|
1313
|
+
WHERE a.attrelid = con.conrelid
|
|
1314
|
+
AND a.attnum = ANY(con.conkey)
|
|
1315
|
+
ORDER BY a.attnum
|
|
1316
|
+
) AS columns
|
|
1317
|
+
FROM pg_constraint con
|
|
1318
|
+
JOIN pg_class rel ON rel.oid = con.conrelid
|
|
1319
|
+
JOIN pg_namespace nsp ON nsp.oid = con.connamespace
|
|
1320
|
+
WHERE con.contype = 'p'
|
|
1321
|
+
AND nsp.nspname = ${schemaName}
|
|
1322
|
+
AND rel.relname = ${tableName}`);
|
|
1323
|
+
return getRows2(result);
|
|
1324
|
+
}
|
|
1325
|
+
async getUniqueConstraints(schemaName, tableName) {
|
|
1326
|
+
const result = await this.db.execute(sql21`SELECT
|
|
1327
|
+
con.conname AS name,
|
|
1328
|
+
ARRAY(
|
|
1329
|
+
SELECT a.attname
|
|
1330
|
+
FROM pg_attribute a
|
|
1331
|
+
WHERE a.attrelid = con.conrelid
|
|
1332
|
+
AND a.attnum = ANY(con.conkey)
|
|
1333
|
+
ORDER BY a.attnum
|
|
1334
|
+
) AS columns
|
|
1335
|
+
FROM pg_constraint con
|
|
1336
|
+
JOIN pg_class rel ON rel.oid = con.conrelid
|
|
1337
|
+
JOIN pg_namespace nsp ON nsp.oid = con.connamespace
|
|
1338
|
+
WHERE con.contype = 'u'
|
|
1339
|
+
AND nsp.nspname = ${schemaName}
|
|
1340
|
+
AND rel.relname = ${tableName}`);
|
|
1341
|
+
return getRows2(result);
|
|
1342
|
+
}
|
|
1343
|
+
async getCheckConstraints(schemaName, tableName) {
|
|
1344
|
+
const result = await this.db.execute(sql21`SELECT
|
|
1345
|
+
con.conname AS name,
|
|
1346
|
+
pg_get_constraintdef(con.oid) AS definition
|
|
1347
|
+
FROM pg_constraint con
|
|
1348
|
+
JOIN pg_class rel ON rel.oid = con.conrelid
|
|
1349
|
+
JOIN pg_namespace nsp ON nsp.oid = con.connamespace
|
|
1350
|
+
WHERE con.contype = 'c'
|
|
1351
|
+
AND nsp.nspname = ${schemaName}
|
|
1352
|
+
AND rel.relname = ${tableName}`);
|
|
1353
|
+
return getRows2(result);
|
|
1354
|
+
}
|
|
1355
|
+
async getEnums(schemaName) {
|
|
1356
|
+
const result = await this.db.execute(sql21`SELECT
|
|
1357
|
+
n.nspname AS schema,
|
|
1358
|
+
t.typname AS name,
|
|
1359
|
+
e.enumlabel AS value,
|
|
1360
|
+
e.enumsortorder AS sort_order
|
|
1361
|
+
FROM pg_type t
|
|
1362
|
+
JOIN pg_enum e ON t.oid = e.enumtypid
|
|
1363
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
|
|
1364
|
+
WHERE n.nspname = ${schemaName}
|
|
1365
|
+
ORDER BY schema, name, sort_order`);
|
|
1366
|
+
return getRows2(result);
|
|
1367
|
+
}
|
|
1368
|
+
parseDefault(defaultValue, dataType) {
|
|
1369
|
+
if (!defaultValue)
|
|
1370
|
+
return;
|
|
1371
|
+
const match = defaultValue.match(/^'(.*)'::/);
|
|
1372
|
+
if (match) {
|
|
1373
|
+
return `'${match[1]}'`;
|
|
1374
|
+
}
|
|
1375
|
+
if (defaultValue.includes("nextval(")) {
|
|
1376
|
+
return;
|
|
1377
|
+
}
|
|
1378
|
+
if (dataType === "boolean") {
|
|
1379
|
+
if (defaultValue === "true")
|
|
1380
|
+
return "true";
|
|
1381
|
+
if (defaultValue === "false")
|
|
1382
|
+
return "false";
|
|
1383
|
+
}
|
|
1384
|
+
return defaultValue;
|
|
1385
|
+
}
|
|
1386
|
+
async hasExistingTables(pluginName) {
|
|
1387
|
+
const schemaName = pluginName === "@elizaos/plugin-sql" ? "public" : this.deriveSchemaName(pluginName);
|
|
1388
|
+
const result = await this.db.execute(sql21`SELECT COUNT(*) AS count
|
|
1389
|
+
FROM information_schema.tables
|
|
1390
|
+
WHERE table_schema = ${schemaName}
|
|
1391
|
+
AND table_type = 'BASE TABLE'`);
|
|
1392
|
+
const firstRow = result.rows?.[0];
|
|
1393
|
+
const count = parseInt(firstRow && firstRow.count || "0", 10);
|
|
1394
|
+
return count > 0;
|
|
1395
|
+
}
|
|
1396
|
+
deriveSchemaName(pluginName) {
|
|
1397
|
+
return pluginName.replace("@", "").replace("/", "_").replace(/-/g, "_").toLowerCase();
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
var init_database_introspector = () => {};
|
|
1401
|
+
|
|
1402
|
+
// runtime-migrator/drizzle-adapters/diff-calculator.ts
|
|
1403
|
+
var exports_diff_calculator = {};
|
|
1404
|
+
__export(exports_diff_calculator, {
|
|
1405
|
+
hasDiffChanges: () => hasDiffChanges,
|
|
1406
|
+
calculateDiff: () => calculateDiff
|
|
1407
|
+
});
|
|
1408
|
+
function normalizeType(type) {
|
|
1409
|
+
if (!type)
|
|
1410
|
+
return "";
|
|
1411
|
+
const normalized = type.toLowerCase().trim();
|
|
1412
|
+
if (normalized === "timestamp without time zone" || normalized === "timestamp with time zone") {
|
|
1413
|
+
return "timestamp";
|
|
1414
|
+
}
|
|
1415
|
+
if (normalized === "serial") {
|
|
1416
|
+
return "integer";
|
|
1417
|
+
}
|
|
1418
|
+
if (normalized === "bigserial") {
|
|
1419
|
+
return "bigint";
|
|
1420
|
+
}
|
|
1421
|
+
if (normalized === "smallserial") {
|
|
1422
|
+
return "smallint";
|
|
1423
|
+
}
|
|
1424
|
+
if (normalized.startsWith("numeric") || normalized.startsWith("decimal")) {
|
|
1425
|
+
const match = normalized.match(/\((\d+)(?:,\s*(\d+))?\)/);
|
|
1426
|
+
if (match) {
|
|
1427
|
+
return `numeric(${match[1]}${match[2] ? `,${match[2]}` : ""})`;
|
|
1428
|
+
}
|
|
1429
|
+
return "numeric";
|
|
1430
|
+
}
|
|
1431
|
+
if (normalized.startsWith("character varying")) {
|
|
1432
|
+
return normalized.replace("character varying", "varchar");
|
|
1433
|
+
}
|
|
1434
|
+
if (normalized === "text[]" || normalized === "_text") {
|
|
1435
|
+
return "text[]";
|
|
1436
|
+
}
|
|
1437
|
+
return normalized;
|
|
1438
|
+
}
|
|
1439
|
+
function isIndexChanged(prevIndex, currIndex) {
|
|
1440
|
+
if (prevIndex.isUnique !== currIndex.isUnique)
|
|
1441
|
+
return true;
|
|
1442
|
+
if (prevIndex.method !== currIndex.method)
|
|
1443
|
+
return true;
|
|
1444
|
+
if (prevIndex.where !== currIndex.where)
|
|
1445
|
+
return true;
|
|
1446
|
+
if (prevIndex.concurrently !== currIndex.concurrently)
|
|
1447
|
+
return true;
|
|
1448
|
+
const prevColumns = prevIndex.columns || [];
|
|
1449
|
+
const currColumns = currIndex.columns || [];
|
|
1450
|
+
if (prevColumns.length !== currColumns.length)
|
|
1451
|
+
return true;
|
|
1452
|
+
for (let i = 0;i < prevColumns.length; i++) {
|
|
1453
|
+
const prevCol = prevColumns[i];
|
|
1454
|
+
const currCol = currColumns[i];
|
|
1455
|
+
if (typeof prevCol === "string" && typeof currCol === "string") {
|
|
1456
|
+
if (prevCol !== currCol)
|
|
1457
|
+
return true;
|
|
1458
|
+
} else if (typeof prevCol === "object" && typeof currCol === "object") {
|
|
1459
|
+
if (prevCol.expression !== currCol.expression)
|
|
1460
|
+
return true;
|
|
1461
|
+
if (prevCol.isExpression !== currCol.isExpression)
|
|
1462
|
+
return true;
|
|
1463
|
+
if (prevCol.asc !== currCol.asc)
|
|
1464
|
+
return true;
|
|
1465
|
+
if (prevCol.nulls !== currCol.nulls)
|
|
1466
|
+
return true;
|
|
1467
|
+
} else {
|
|
1468
|
+
return true;
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
return false;
|
|
1472
|
+
}
|
|
1473
|
+
async function calculateDiff(previousSnapshot, currentSnapshot) {
|
|
1474
|
+
const diff = {
|
|
1475
|
+
tables: {
|
|
1476
|
+
created: [],
|
|
1477
|
+
deleted: [],
|
|
1478
|
+
modified: []
|
|
1479
|
+
},
|
|
1480
|
+
columns: {
|
|
1481
|
+
added: [],
|
|
1482
|
+
deleted: [],
|
|
1483
|
+
modified: []
|
|
1484
|
+
},
|
|
1485
|
+
indexes: {
|
|
1486
|
+
created: [],
|
|
1487
|
+
deleted: [],
|
|
1488
|
+
altered: []
|
|
1489
|
+
},
|
|
1490
|
+
foreignKeys: {
|
|
1491
|
+
created: [],
|
|
1492
|
+
deleted: [],
|
|
1493
|
+
altered: []
|
|
1494
|
+
},
|
|
1495
|
+
uniqueConstraints: {
|
|
1496
|
+
created: [],
|
|
1497
|
+
deleted: []
|
|
1498
|
+
},
|
|
1499
|
+
checkConstraints: {
|
|
1500
|
+
created: [],
|
|
1501
|
+
deleted: []
|
|
1502
|
+
}
|
|
1503
|
+
};
|
|
1504
|
+
if (!previousSnapshot) {
|
|
1505
|
+
diff.tables.created = Object.keys(currentSnapshot.tables);
|
|
1506
|
+
for (const tableName in currentSnapshot.tables) {
|
|
1507
|
+
const table = currentSnapshot.tables[tableName];
|
|
1508
|
+
if (table.indexes) {
|
|
1509
|
+
for (const indexName in table.indexes) {
|
|
1510
|
+
diff.indexes.created.push({
|
|
1511
|
+
...table.indexes[indexName],
|
|
1512
|
+
table: tableName
|
|
1513
|
+
});
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
if (table.foreignKeys) {
|
|
1517
|
+
for (const fkName in table.foreignKeys) {
|
|
1518
|
+
diff.foreignKeys.created.push(table.foreignKeys[fkName]);
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
return diff;
|
|
1523
|
+
}
|
|
1524
|
+
const prevTables = previousSnapshot.tables || {};
|
|
1525
|
+
const currTables = currentSnapshot.tables || {};
|
|
1526
|
+
for (const tableName in currTables) {
|
|
1527
|
+
if (!(tableName in prevTables)) {
|
|
1528
|
+
diff.tables.created.push(tableName);
|
|
1529
|
+
const table = currTables[tableName];
|
|
1530
|
+
if (table.indexes) {
|
|
1531
|
+
for (const indexName in table.indexes) {
|
|
1532
|
+
diff.indexes.created.push({
|
|
1533
|
+
...table.indexes[indexName],
|
|
1534
|
+
table: tableName
|
|
1535
|
+
});
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
if (table.uniqueConstraints) {
|
|
1539
|
+
for (const uqName in table.uniqueConstraints) {
|
|
1540
|
+
diff.uniqueConstraints.created.push({
|
|
1541
|
+
...table.uniqueConstraints[uqName],
|
|
1542
|
+
table: tableName
|
|
1543
|
+
});
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
if (table.checkConstraints) {
|
|
1547
|
+
for (const checkName in table.checkConstraints) {
|
|
1548
|
+
diff.checkConstraints.created.push({
|
|
1549
|
+
...table.checkConstraints[checkName],
|
|
1550
|
+
table: tableName
|
|
1551
|
+
});
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
if (table.foreignKeys) {
|
|
1555
|
+
for (const fkName in table.foreignKeys) {
|
|
1556
|
+
diff.foreignKeys.created.push(table.foreignKeys[fkName]);
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
for (const tableName in prevTables) {
|
|
1562
|
+
if (!(tableName in currTables)) {
|
|
1563
|
+
diff.tables.deleted.push(tableName);
|
|
1564
|
+
}
|
|
1198
1565
|
}
|
|
1199
1566
|
for (const tableName in currTables) {
|
|
1200
1567
|
if (tableName in prevTables) {
|
|
@@ -1363,32 +1730,6 @@ function hasDiffChanges(diff) {
|
|
|
1363
1730
|
return diff.tables.created.length > 0 || diff.tables.deleted.length > 0 || diff.tables.modified.length > 0 || diff.columns.added.length > 0 || diff.columns.deleted.length > 0 || diff.columns.modified.length > 0 || diff.indexes.created.length > 0 || diff.indexes.deleted.length > 0 || diff.indexes.altered.length > 0 || diff.foreignKeys.created.length > 0 || diff.foreignKeys.deleted.length > 0 || diff.foreignKeys.altered.length > 0 || diff.uniqueConstraints.created.length > 0 || diff.uniqueConstraints.deleted.length > 0 || diff.checkConstraints.created.length > 0 || diff.checkConstraints.deleted.length > 0;
|
|
1364
1731
|
}
|
|
1365
1732
|
|
|
1366
|
-
// runtime-migrator/crypto-utils.ts
|
|
1367
|
-
function extendedHash(str) {
|
|
1368
|
-
const h1 = hashWithSeed(str, 5381);
|
|
1369
|
-
const h2 = hashWithSeed(str, 7919);
|
|
1370
|
-
const h3 = hashWithSeed(str, 104729);
|
|
1371
|
-
const h4 = hashWithSeed(str, 224737);
|
|
1372
|
-
return h1 + h2 + h3 + h4;
|
|
1373
|
-
}
|
|
1374
|
-
function hashWithSeed(str, seed) {
|
|
1375
|
-
let hash = seed;
|
|
1376
|
-
for (let i = 0;i < str.length; i++) {
|
|
1377
|
-
hash = hash * 33 ^ str.charCodeAt(i);
|
|
1378
|
-
}
|
|
1379
|
-
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
1380
|
-
}
|
|
1381
|
-
function stringToBigInt(str) {
|
|
1382
|
-
const hash = extendedHash(str);
|
|
1383
|
-
let lockId = BigInt(`0x${hash.slice(0, 16)}`);
|
|
1384
|
-
const mask63Bits = 0x7fffffffffffffffn;
|
|
1385
|
-
lockId = lockId & mask63Bits;
|
|
1386
|
-
if (lockId === 0n) {
|
|
1387
|
-
lockId = 1n;
|
|
1388
|
-
}
|
|
1389
|
-
return lockId;
|
|
1390
|
-
}
|
|
1391
|
-
|
|
1392
1733
|
// runtime-migrator/drizzle-adapters/snapshot-generator.ts
|
|
1393
1734
|
import { is, SQL } from "drizzle-orm";
|
|
1394
1735
|
import { getTableConfig, PgDialect, PgTable } from "drizzle-orm/pg-core";
|
|
@@ -1617,7 +1958,7 @@ function hasChanges(previousSnapshot, currentSnapshot) {
|
|
|
1617
1958
|
const currHash = hashSnapshot(currentSnapshot);
|
|
1618
1959
|
return prevHash !== currHash;
|
|
1619
1960
|
}
|
|
1620
|
-
var sqlToStr = (
|
|
1961
|
+
var sqlToStr = (sql22, _casing) => {
|
|
1621
1962
|
const config = {
|
|
1622
1963
|
escapeName: () => {
|
|
1623
1964
|
throw new Error("we don't support params for `sql` default values");
|
|
@@ -1630,12 +1971,12 @@ var sqlToStr = (sql21, _casing) => {
|
|
|
1630
1971
|
},
|
|
1631
1972
|
casing: undefined
|
|
1632
1973
|
};
|
|
1633
|
-
return
|
|
1974
|
+
return sql22.toQuery(config).sql;
|
|
1634
1975
|
};
|
|
1635
1976
|
var init_snapshot_generator = () => {};
|
|
1636
1977
|
|
|
1637
1978
|
// runtime-migrator/drizzle-adapters/sql-generator.ts
|
|
1638
|
-
import { logger as
|
|
1979
|
+
import { logger as logger4 } from "@elizaos/core";
|
|
1639
1980
|
function checkForDataLoss(diff) {
|
|
1640
1981
|
const result = {
|
|
1641
1982
|
hasDataLoss: false,
|
|
@@ -1765,7 +2106,7 @@ async function generateMigrationSQL(previousSnapshot, currentSnapshot, diff) {
|
|
|
1765
2106
|
}
|
|
1766
2107
|
const dataLossCheck = checkForDataLoss(diff);
|
|
1767
2108
|
if (dataLossCheck.warnings.length > 0) {
|
|
1768
|
-
|
|
2109
|
+
logger4.warn({ src: "plugin:sql", warnings: dataLossCheck.warnings }, "Schema changes may cause data loss");
|
|
1769
2110
|
}
|
|
1770
2111
|
const schemasToCreate = new Set;
|
|
1771
2112
|
for (const tableName of diff.tables.created) {
|
|
@@ -1924,564 +2265,227 @@ function generateCreateTableSQL(fullTableName, table) {
|
|
|
1924
2265
|
return { tableSQL, fkSQLs };
|
|
1925
2266
|
}
|
|
1926
2267
|
function generateColumnDefinition(name, def) {
|
|
1927
|
-
let
|
|
2268
|
+
let sql22 = `"${name}" ${def.type}`;
|
|
1928
2269
|
if (def.primaryKey && !def.type.includes("SERIAL")) {
|
|
1929
|
-
|
|
2270
|
+
sql22 += " PRIMARY KEY";
|
|
1930
2271
|
}
|
|
1931
2272
|
if (def.notNull) {
|
|
1932
|
-
|
|
2273
|
+
sql22 += " NOT NULL";
|
|
1933
2274
|
}
|
|
1934
2275
|
if (def.default !== undefined) {
|
|
1935
|
-
const defaultValue = formatDefaultValue(def.default, def.type);
|
|
1936
|
-
|
|
1937
|
-
}
|
|
1938
|
-
return sql21;
|
|
1939
|
-
}
|
|
1940
|
-
function generateAddColumnSQL(table, column, definition) {
|
|
1941
|
-
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
1942
|
-
const tableNameWithSchema = `"${schema}"."${tableName}"`;
|
|
1943
|
-
const parts = [`"${column}"`];
|
|
1944
|
-
parts.push(definition.type);
|
|
1945
|
-
if (definition.primaryKey) {
|
|
1946
|
-
parts.push("PRIMARY KEY");
|
|
1947
|
-
}
|
|
1948
|
-
if (definition.default !== undefined) {
|
|
1949
|
-
const defaultValue = formatDefaultValue(definition.default, definition.type);
|
|
1950
|
-
if (defaultValue) {
|
|
1951
|
-
parts.push(`DEFAULT ${defaultValue}`);
|
|
1952
|
-
}
|
|
1953
|
-
}
|
|
1954
|
-
const definitionWithGenerated = definition;
|
|
1955
|
-
if (definitionWithGenerated.generated) {
|
|
1956
|
-
parts.push(`GENERATED ALWAYS AS (${definitionWithGenerated.generated}) STORED`);
|
|
1957
|
-
}
|
|
1958
|
-
if (definition.notNull) {
|
|
1959
|
-
parts.push("NOT NULL");
|
|
1960
|
-
}
|
|
1961
|
-
return `ALTER TABLE ${tableNameWithSchema} ADD COLUMN ${parts.join(" ")};`;
|
|
1962
|
-
}
|
|
1963
|
-
function generateDropColumnSQL(table, column) {
|
|
1964
|
-
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
1965
|
-
const tableNameWithSchema = `"${schema}"."${tableName}"`;
|
|
1966
|
-
return `ALTER TABLE ${tableNameWithSchema} DROP COLUMN "${column}" CASCADE;`;
|
|
1967
|
-
}
|
|
1968
|
-
function generateAlterColumnSQL(table, column, changes) {
|
|
1969
|
-
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
1970
|
-
const tableNameWithSchema = `"${schema}"."${tableName}"`;
|
|
1971
|
-
const statements = [];
|
|
1972
|
-
const changesTo = changes.to;
|
|
1973
|
-
const changesFrom = changes.from;
|
|
1974
|
-
const changesToType = changesTo?.type;
|
|
1975
|
-
const changesFromType = changesFrom?.type;
|
|
1976
|
-
if (changesToType !== changesFromType) {
|
|
1977
|
-
const newType = changesToType || "TEXT";
|
|
1978
|
-
const needsUsing = checkIfNeedsUsingClause(changesFromType || "", newType);
|
|
1979
|
-
if (needsUsing) {
|
|
1980
|
-
statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${column}" TYPE ${newType} USING "${column}"::text::${newType};`);
|
|
1981
|
-
} else {
|
|
1982
|
-
statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${column}" SET DATA TYPE ${newType};`);
|
|
1983
|
-
}
|
|
1984
|
-
}
|
|
1985
|
-
const changesToNotNull = changesTo?.notNull;
|
|
1986
|
-
const changesFromNotNull = changesFrom?.notNull;
|
|
1987
|
-
if (changesToNotNull !== changesFromNotNull) {
|
|
1988
|
-
if (changesToNotNull) {
|
|
1989
|
-
statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${column}" SET NOT NULL;`);
|
|
1990
|
-
} else {
|
|
1991
|
-
statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${column}" DROP NOT NULL;`);
|
|
1992
|
-
}
|
|
1993
|
-
}
|
|
1994
|
-
const changesToDefault = changesTo?.default;
|
|
1995
|
-
const changesFromDefault = changesFrom?.default;
|
|
1996
|
-
if (changesToDefault !== changesFromDefault) {
|
|
1997
|
-
if (changesToDefault !== undefined) {
|
|
1998
|
-
const defaultValue = formatDefaultValue(changesToDefault, changesToType || "");
|
|
1999
|
-
statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${column}" SET DEFAULT ${defaultValue};`);
|
|
2000
|
-
} else {
|
|
2001
|
-
statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${column}" DROP DEFAULT;`);
|
|
2002
|
-
}
|
|
2003
|
-
}
|
|
2004
|
-
return statements;
|
|
2005
|
-
}
|
|
2006
|
-
function checkIfNeedsUsingClause(fromType, toType) {
|
|
2007
|
-
if (!fromType || !toType)
|
|
2008
|
-
return false;
|
|
2009
|
-
if (fromType.includes("enum") || toType.includes("enum")) {
|
|
2010
|
-
return true;
|
|
2011
|
-
}
|
|
2012
|
-
const fromBase = fromType.split("(")[0].toLowerCase();
|
|
2013
|
-
const toBase = toType.split("(")[0].toLowerCase();
|
|
2014
|
-
if ((fromBase === "text" || fromBase === "varchar" || fromBase === "character varying") && (toBase === "jsonb" || toBase === "json")) {
|
|
2015
|
-
return true;
|
|
2016
|
-
}
|
|
2017
|
-
const needsUsingPairs = [
|
|
2018
|
-
["integer", "boolean"],
|
|
2019
|
-
["boolean", "integer"],
|
|
2020
|
-
["text", "integer"],
|
|
2021
|
-
["text", "numeric"],
|
|
2022
|
-
["text", "boolean"],
|
|
2023
|
-
["text", "uuid"],
|
|
2024
|
-
["text", "jsonb"],
|
|
2025
|
-
["text", "json"],
|
|
2026
|
-
["varchar", "integer"],
|
|
2027
|
-
["varchar", "numeric"],
|
|
2028
|
-
["varchar", "boolean"],
|
|
2029
|
-
["varchar", "uuid"],
|
|
2030
|
-
["varchar", "jsonb"],
|
|
2031
|
-
["varchar", "json"],
|
|
2032
|
-
["character varying", "jsonb"],
|
|
2033
|
-
["character varying", "json"]
|
|
2034
|
-
];
|
|
2035
|
-
for (const [from, to] of needsUsingPairs) {
|
|
2036
|
-
if (fromBase === from && toBase === to || fromBase === to && toBase === from) {
|
|
2037
|
-
return true;
|
|
2038
|
-
}
|
|
2039
|
-
}
|
|
2040
|
-
return false;
|
|
2041
|
-
}
|
|
2042
|
-
function formatDefaultValue(value, type) {
|
|
2043
|
-
if (value === null || value === "NULL") {
|
|
2044
|
-
return "NULL";
|
|
2045
|
-
}
|
|
2046
|
-
if (type && (type.toLowerCase().includes("boolean") || type.toLowerCase() === "bool")) {
|
|
2047
|
-
if (value === true || value === "true" || value === "t" || value === 1) {
|
|
2048
|
-
return "true";
|
|
2049
|
-
}
|
|
2050
|
-
if (value === false || value === "false" || value === "f" || value === 0) {
|
|
2051
|
-
return "false";
|
|
2052
|
-
}
|
|
2053
|
-
}
|
|
2054
|
-
if (type?.match(/^(integer|bigint|smallint|numeric|decimal|real|double)/i)) {
|
|
2055
|
-
return String(value);
|
|
2056
|
-
}
|
|
2057
|
-
if (typeof value === "string") {
|
|
2058
|
-
if (value.includes("::")) {
|
|
2059
|
-
return value;
|
|
2060
|
-
}
|
|
2061
|
-
if (value.startsWith("'") && value.endsWith("'")) {
|
|
2062
|
-
return value;
|
|
2063
|
-
}
|
|
2064
|
-
if (value.match(/^\w+\(\)/i) || value.includes("(") && value.includes(")")) {
|
|
2065
|
-
return value;
|
|
2066
|
-
}
|
|
2067
|
-
if (value.toUpperCase().startsWith("CURRENT_")) {
|
|
2068
|
-
return value;
|
|
2069
|
-
}
|
|
2070
|
-
return `'${value.replace(/'/g, "''")}'`;
|
|
2071
|
-
}
|
|
2072
|
-
return String(value);
|
|
2073
|
-
}
|
|
2074
|
-
function generateCreateIndexSQL(index7) {
|
|
2075
|
-
const unique3 = index7.isUnique ? "UNIQUE " : "";
|
|
2076
|
-
const method = index7.method || "btree";
|
|
2077
|
-
const columns = index7.columns.map((c) => {
|
|
2078
|
-
if (c.isExpression) {
|
|
2079
|
-
return c.expression;
|
|
2080
|
-
}
|
|
2081
|
-
return `"${c.expression}"${c.asc === false ? " DESC" : ""}`;
|
|
2082
|
-
}).join(", ");
|
|
2083
|
-
const indexName = index7.name.includes(".") ? index7.name.split(".")[1] : index7.name;
|
|
2084
|
-
let tableRef;
|
|
2085
|
-
const indexTable = index7.table;
|
|
2086
|
-
if (indexTable?.includes(".")) {
|
|
2087
|
-
const [schema, table] = indexTable.split(".");
|
|
2088
|
-
tableRef = `"${schema}"."${table}"`;
|
|
2089
|
-
} else {
|
|
2090
|
-
tableRef = `"${indexTable || ""}"`;
|
|
2091
|
-
}
|
|
2092
|
-
return `CREATE ${unique3}INDEX "${indexName}" ON ${tableRef} USING ${method} (${columns});`;
|
|
2093
|
-
}
|
|
2094
|
-
function generateDropIndexSQL(index7) {
|
|
2095
|
-
const indexNameFull = typeof index7 === "string" ? index7 : index7.name;
|
|
2096
|
-
const indexName = indexNameFull.includes(".") ? indexNameFull.split(".")[1] : indexNameFull;
|
|
2097
|
-
return `DROP INDEX IF EXISTS "${indexName}";`;
|
|
2098
|
-
}
|
|
2099
|
-
function generateCreateForeignKeySQL(fk) {
|
|
2100
|
-
const schemaFrom = fk.schemaFrom || "public";
|
|
2101
|
-
const schemaTo = fk.schemaTo || "public";
|
|
2102
|
-
const tableFrom = fk.tableFrom;
|
|
2103
|
-
const columnsFrom = fk.columnsFrom.map((c) => `"${c}"`).join(", ");
|
|
2104
|
-
const columnsTo = fk.columnsTo.map((c) => `"${c}"`).join(", ");
|
|
2105
|
-
let sql21 = `ALTER TABLE "${schemaFrom}"."${tableFrom}" ADD CONSTRAINT "${fk.name}" FOREIGN KEY (${columnsFrom}) REFERENCES "${schemaTo}"."${fk.tableTo}" (${columnsTo})`;
|
|
2106
|
-
if (fk.onDelete) {
|
|
2107
|
-
sql21 += ` ON DELETE ${fk.onDelete}`;
|
|
2108
|
-
}
|
|
2109
|
-
if (fk.onUpdate) {
|
|
2110
|
-
sql21 += ` ON UPDATE ${fk.onUpdate}`;
|
|
2276
|
+
const defaultValue = formatDefaultValue(def.default, def.type);
|
|
2277
|
+
sql22 += ` DEFAULT ${defaultValue}`;
|
|
2111
2278
|
}
|
|
2112
|
-
return
|
|
2113
|
-
}
|
|
2114
|
-
function generateDropForeignKeySQL(fk) {
|
|
2115
|
-
const [schema, tableName] = fk.tableFrom ? fk.tableFrom.includes(".") ? fk.tableFrom.split(".") : ["public", fk.tableFrom] : ["public", ""];
|
|
2116
|
-
return `ALTER TABLE "${schema}"."${tableName}" DROP CONSTRAINT "${fk.name}";`;
|
|
2279
|
+
return sql22;
|
|
2117
2280
|
}
|
|
2118
|
-
function
|
|
2119
|
-
const table = constraint.table || "";
|
|
2281
|
+
function generateAddColumnSQL(table, column, definition) {
|
|
2120
2282
|
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
2121
|
-
const
|
|
2122
|
-
const
|
|
2123
|
-
|
|
2124
|
-
if (
|
|
2125
|
-
|
|
2283
|
+
const tableNameWithSchema = `"${schema}"."${tableName}"`;
|
|
2284
|
+
const parts = [`"${column}"`];
|
|
2285
|
+
parts.push(definition.type);
|
|
2286
|
+
if (definition.primaryKey) {
|
|
2287
|
+
parts.push("PRIMARY KEY");
|
|
2126
2288
|
}
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2289
|
+
if (definition.default !== undefined) {
|
|
2290
|
+
const defaultValue = formatDefaultValue(definition.default, definition.type);
|
|
2291
|
+
if (defaultValue) {
|
|
2292
|
+
parts.push(`DEFAULT ${defaultValue}`);
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
const definitionWithGenerated = definition;
|
|
2296
|
+
if (definitionWithGenerated.generated) {
|
|
2297
|
+
parts.push(`GENERATED ALWAYS AS (${definitionWithGenerated.generated}) STORED`);
|
|
2298
|
+
}
|
|
2299
|
+
if (definition.notNull) {
|
|
2300
|
+
parts.push("NOT NULL");
|
|
2301
|
+
}
|
|
2302
|
+
return `ALTER TABLE ${tableNameWithSchema} ADD COLUMN ${parts.join(" ")};`;
|
|
2134
2303
|
}
|
|
2135
|
-
function
|
|
2136
|
-
const table = constraint.table || "";
|
|
2304
|
+
function generateDropColumnSQL(table, column) {
|
|
2137
2305
|
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
2138
|
-
const
|
|
2139
|
-
|
|
2140
|
-
return `ALTER TABLE "${schema}"."${tableName}" ADD CONSTRAINT "${name}" CHECK (${value});`;
|
|
2306
|
+
const tableNameWithSchema = `"${schema}"."${tableName}"`;
|
|
2307
|
+
return `ALTER TABLE ${tableNameWithSchema} DROP COLUMN "${column}" CASCADE;`;
|
|
2141
2308
|
}
|
|
2142
|
-
function
|
|
2143
|
-
const table = constraint.table || "";
|
|
2309
|
+
function generateAlterColumnSQL(table, column, changes) {
|
|
2144
2310
|
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
constructor(db) {
|
|
2159
|
-
this.db = db;
|
|
2160
|
-
}
|
|
2161
|
-
async introspectSchema(schemaName = "public") {
|
|
2162
|
-
logger4.info({ src: "plugin:sql", schemaName }, "Starting database introspection");
|
|
2163
|
-
const tables = {};
|
|
2164
|
-
const schemas = {};
|
|
2165
|
-
const enums = {};
|
|
2166
|
-
const allTables = await this.getTables(schemaName);
|
|
2167
|
-
for (const tableInfo of allTables) {
|
|
2168
|
-
const tableName = tableInfo.table_name;
|
|
2169
|
-
const tableSchema = tableInfo.table_schema || "public";
|
|
2170
|
-
logger4.debug({ src: "plugin:sql", tableSchema, tableName }, "Introspecting table");
|
|
2171
|
-
const columns = await this.getColumns(tableSchema, tableName);
|
|
2172
|
-
const columnsObject = {};
|
|
2173
|
-
const uniqueConstraintObject = {};
|
|
2174
|
-
for (const col of columns) {
|
|
2175
|
-
columnsObject[col.column_name] = {
|
|
2176
|
-
name: col.column_name,
|
|
2177
|
-
type: col.data_type,
|
|
2178
|
-
primaryKey: col.is_primary || false,
|
|
2179
|
-
notNull: col.is_nullable === "NO",
|
|
2180
|
-
default: col.column_default ? this.parseDefault(col.column_default, col.data_type) : undefined
|
|
2181
|
-
};
|
|
2182
|
-
}
|
|
2183
|
-
const indexes = await this.getIndexes(tableSchema, tableName);
|
|
2184
|
-
const indexesObject = {};
|
|
2185
|
-
for (const idx of indexes) {
|
|
2186
|
-
if (!idx.is_primary && !idx.is_unique_constraint) {
|
|
2187
|
-
if (idx.columns && Array.isArray(idx.columns) && idx.columns.length > 0) {
|
|
2188
|
-
indexesObject[idx.name] = {
|
|
2189
|
-
name: idx.name,
|
|
2190
|
-
columns: idx.columns.map((col) => ({
|
|
2191
|
-
expression: col,
|
|
2192
|
-
isExpression: false
|
|
2193
|
-
})),
|
|
2194
|
-
isUnique: idx.is_unique,
|
|
2195
|
-
method: idx.method || "btree"
|
|
2196
|
-
};
|
|
2197
|
-
}
|
|
2198
|
-
}
|
|
2199
|
-
}
|
|
2200
|
-
const foreignKeys = await this.getForeignKeys(tableSchema, tableName);
|
|
2201
|
-
const foreignKeysObject = {};
|
|
2202
|
-
for (const fk of foreignKeys) {
|
|
2203
|
-
foreignKeysObject[fk.name] = {
|
|
2204
|
-
name: fk.name,
|
|
2205
|
-
tableFrom: tableName,
|
|
2206
|
-
schemaFrom: tableSchema,
|
|
2207
|
-
tableTo: fk.foreign_table_name,
|
|
2208
|
-
schemaTo: fk.foreign_table_schema || "public",
|
|
2209
|
-
columnsFrom: [fk.column_name],
|
|
2210
|
-
columnsTo: [fk.foreign_column_name],
|
|
2211
|
-
onDelete: fk.delete_rule?.toLowerCase() || "no action",
|
|
2212
|
-
onUpdate: fk.update_rule?.toLowerCase() || "no action"
|
|
2213
|
-
};
|
|
2214
|
-
}
|
|
2215
|
-
const primaryKeys = await this.getPrimaryKeys(tableSchema, tableName);
|
|
2216
|
-
const primaryKeysObject = {};
|
|
2217
|
-
for (const pk of primaryKeys) {
|
|
2218
|
-
primaryKeysObject[pk.name] = {
|
|
2219
|
-
name: pk.name,
|
|
2220
|
-
columns: pk.columns
|
|
2221
|
-
};
|
|
2222
|
-
}
|
|
2223
|
-
const uniqueConstraints = await this.getUniqueConstraints(tableSchema, tableName);
|
|
2224
|
-
for (const unq of uniqueConstraints) {
|
|
2225
|
-
uniqueConstraintObject[unq.name] = {
|
|
2226
|
-
name: unq.name,
|
|
2227
|
-
columns: unq.columns,
|
|
2228
|
-
nullsNotDistinct: false
|
|
2229
|
-
};
|
|
2230
|
-
}
|
|
2231
|
-
const checkConstraints = await this.getCheckConstraints(tableSchema, tableName);
|
|
2232
|
-
const checksObject = {};
|
|
2233
|
-
for (const check3 of checkConstraints) {
|
|
2234
|
-
checksObject[check3.name] = {
|
|
2235
|
-
name: check3.name,
|
|
2236
|
-
value: check3.definition
|
|
2237
|
-
};
|
|
2238
|
-
}
|
|
2239
|
-
tables[`${tableSchema}.${tableName}`] = {
|
|
2240
|
-
name: tableName,
|
|
2241
|
-
schema: tableSchema,
|
|
2242
|
-
columns: columnsObject,
|
|
2243
|
-
indexes: indexesObject,
|
|
2244
|
-
foreignKeys: foreignKeysObject,
|
|
2245
|
-
compositePrimaryKeys: primaryKeysObject,
|
|
2246
|
-
uniqueConstraints: uniqueConstraintObject,
|
|
2247
|
-
checkConstraints: checksObject
|
|
2248
|
-
};
|
|
2249
|
-
if (tableSchema && tableSchema !== "public") {
|
|
2250
|
-
schemas[tableSchema] = tableSchema;
|
|
2251
|
-
}
|
|
2252
|
-
}
|
|
2253
|
-
const enumsResult = await this.getEnums(schemaName);
|
|
2254
|
-
for (const enumInfo of enumsResult) {
|
|
2255
|
-
const key = `${enumInfo.schema}.${enumInfo.name}`;
|
|
2256
|
-
if (!enums[key]) {
|
|
2257
|
-
enums[key] = {
|
|
2258
|
-
name: enumInfo.name,
|
|
2259
|
-
schema: enumInfo.schema,
|
|
2260
|
-
values: []
|
|
2261
|
-
};
|
|
2262
|
-
}
|
|
2263
|
-
enums[key].values.push(enumInfo.value);
|
|
2311
|
+
const tableNameWithSchema = `"${schema}"."${tableName}"`;
|
|
2312
|
+
const statements = [];
|
|
2313
|
+
const changesTo = changes.to;
|
|
2314
|
+
const changesFrom = changes.from;
|
|
2315
|
+
const changesToType = changesTo?.type;
|
|
2316
|
+
const changesFromType = changesFrom?.type;
|
|
2317
|
+
if (changesToType !== changesFromType) {
|
|
2318
|
+
const newType = changesToType || "TEXT";
|
|
2319
|
+
const needsUsing = checkIfNeedsUsingClause(changesFromType || "", newType);
|
|
2320
|
+
if (needsUsing) {
|
|
2321
|
+
statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${column}" TYPE ${newType} USING "${column}"::text::${newType};`);
|
|
2322
|
+
} else {
|
|
2323
|
+
statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${column}" SET DATA TYPE ${newType};`);
|
|
2264
2324
|
}
|
|
2265
|
-
logger4.info({ src: "plugin:sql", tableCount: Object.keys(tables).length }, "Database introspection complete");
|
|
2266
|
-
return {
|
|
2267
|
-
version: "7",
|
|
2268
|
-
dialect: "postgresql",
|
|
2269
|
-
tables,
|
|
2270
|
-
schemas,
|
|
2271
|
-
enums,
|
|
2272
|
-
_meta: {
|
|
2273
|
-
schemas: {},
|
|
2274
|
-
tables: {},
|
|
2275
|
-
columns: {}
|
|
2276
|
-
}
|
|
2277
|
-
};
|
|
2278
2325
|
}
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
return getRows2(result);
|
|
2326
|
+
const changesToNotNull = changesTo?.notNull;
|
|
2327
|
+
const changesFromNotNull = changesFrom?.notNull;
|
|
2328
|
+
if (changesToNotNull !== changesFromNotNull) {
|
|
2329
|
+
if (changesToNotNull) {
|
|
2330
|
+
statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${column}" SET NOT NULL;`);
|
|
2331
|
+
} else {
|
|
2332
|
+
statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${column}" DROP NOT NULL;`);
|
|
2333
|
+
}
|
|
2288
2334
|
}
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
AND EXISTS (
|
|
2299
|
-
SELECT FROM pg_attrdef ad
|
|
2300
|
-
WHERE ad.adrelid = a.attrelid
|
|
2301
|
-
AND ad.adnum = a.attnum
|
|
2302
|
-
AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval('''
|
|
2303
|
-
|| pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
|
|
2304
|
-
)
|
|
2305
|
-
THEN CASE a.atttypid
|
|
2306
|
-
WHEN 'int'::regtype THEN 'serial'
|
|
2307
|
-
WHEN 'int8'::regtype THEN 'bigserial'
|
|
2308
|
-
WHEN 'int2'::regtype THEN 'smallserial'
|
|
2309
|
-
END
|
|
2310
|
-
ELSE format_type(a.atttypid, a.atttypmod)
|
|
2311
|
-
END AS data_type,
|
|
2312
|
-
pg_get_expr(ad.adbin, ad.adrelid) AS column_default,
|
|
2313
|
-
CASE
|
|
2314
|
-
WHEN con.contype = 'p' THEN true
|
|
2315
|
-
ELSE false
|
|
2316
|
-
END AS is_primary
|
|
2317
|
-
FROM pg_attribute a
|
|
2318
|
-
JOIN pg_class cls ON cls.oid = a.attrelid
|
|
2319
|
-
JOIN pg_namespace ns ON ns.oid = cls.relnamespace
|
|
2320
|
-
LEFT JOIN pg_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum
|
|
2321
|
-
LEFT JOIN pg_constraint con ON con.conrelid = a.attrelid
|
|
2322
|
-
AND a.attnum = ANY(con.conkey)
|
|
2323
|
-
AND con.contype = 'p'
|
|
2324
|
-
WHERE
|
|
2325
|
-
a.attnum > 0
|
|
2326
|
-
AND NOT a.attisdropped
|
|
2327
|
-
AND ns.nspname = ${schemaName}
|
|
2328
|
-
AND cls.relname = ${tableName}
|
|
2329
|
-
ORDER BY a.attnum`);
|
|
2330
|
-
return getRows2(result);
|
|
2335
|
+
const changesToDefault = changesTo?.default;
|
|
2336
|
+
const changesFromDefault = changesFrom?.default;
|
|
2337
|
+
if (changesToDefault !== changesFromDefault) {
|
|
2338
|
+
if (changesToDefault !== undefined) {
|
|
2339
|
+
const defaultValue = formatDefaultValue(changesToDefault, changesToType || "");
|
|
2340
|
+
statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${column}" SET DEFAULT ${defaultValue};`);
|
|
2341
|
+
} else {
|
|
2342
|
+
statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${column}" DROP DEFAULT;`);
|
|
2343
|
+
}
|
|
2331
2344
|
}
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
SELECT a.attname
|
|
2340
|
-
FROM pg_attribute a
|
|
2341
|
-
WHERE a.attrelid = idx.indrelid
|
|
2342
|
-
AND a.attnum = ANY(idx.indkey::int[])
|
|
2343
|
-
ORDER BY a.attnum
|
|
2344
|
-
) AS columns,
|
|
2345
|
-
am.amname AS method
|
|
2346
|
-
FROM pg_index idx
|
|
2347
|
-
JOIN pg_class i ON i.oid = idx.indexrelid
|
|
2348
|
-
JOIN pg_class c ON c.oid = idx.indrelid
|
|
2349
|
-
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
2350
|
-
JOIN pg_am am ON am.oid = i.relam
|
|
2351
|
-
LEFT JOIN pg_constraint con ON con.conindid = idx.indexrelid
|
|
2352
|
-
WHERE n.nspname = ${schemaName}
|
|
2353
|
-
AND c.relname = ${tableName}`);
|
|
2354
|
-
return getRows2(result);
|
|
2345
|
+
return statements;
|
|
2346
|
+
}
|
|
2347
|
+
function checkIfNeedsUsingClause(fromType, toType) {
|
|
2348
|
+
if (!fromType || !toType)
|
|
2349
|
+
return false;
|
|
2350
|
+
if (fromType.includes("enum") || toType.includes("enum")) {
|
|
2351
|
+
return true;
|
|
2355
2352
|
}
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
fnsp.nspname AS foreign_table_schema,
|
|
2361
|
-
frel.relname AS foreign_table_name,
|
|
2362
|
-
fatt.attname AS foreign_column_name,
|
|
2363
|
-
CASE con.confupdtype
|
|
2364
|
-
WHEN 'a' THEN 'NO ACTION'
|
|
2365
|
-
WHEN 'r' THEN 'RESTRICT'
|
|
2366
|
-
WHEN 'n' THEN 'SET NULL'
|
|
2367
|
-
WHEN 'c' THEN 'CASCADE'
|
|
2368
|
-
WHEN 'd' THEN 'SET DEFAULT'
|
|
2369
|
-
END AS update_rule,
|
|
2370
|
-
CASE con.confdeltype
|
|
2371
|
-
WHEN 'a' THEN 'NO ACTION'
|
|
2372
|
-
WHEN 'r' THEN 'RESTRICT'
|
|
2373
|
-
WHEN 'n' THEN 'SET NULL'
|
|
2374
|
-
WHEN 'c' THEN 'CASCADE'
|
|
2375
|
-
WHEN 'd' THEN 'SET DEFAULT'
|
|
2376
|
-
END AS delete_rule
|
|
2377
|
-
FROM pg_catalog.pg_constraint con
|
|
2378
|
-
JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
|
|
2379
|
-
JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace
|
|
2380
|
-
LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey)
|
|
2381
|
-
AND att.attrelid = con.conrelid
|
|
2382
|
-
LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid
|
|
2383
|
-
LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace
|
|
2384
|
-
LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey)
|
|
2385
|
-
AND fatt.attrelid = con.confrelid
|
|
2386
|
-
WHERE con.contype = 'f'
|
|
2387
|
-
AND nsp.nspname = ${schemaName}
|
|
2388
|
-
AND rel.relname = ${tableName}`);
|
|
2389
|
-
return getRows2(result);
|
|
2353
|
+
const fromBase = fromType.split("(")[0].toLowerCase();
|
|
2354
|
+
const toBase = toType.split("(")[0].toLowerCase();
|
|
2355
|
+
if ((fromBase === "text" || fromBase === "varchar" || fromBase === "character varying") && (toBase === "jsonb" || toBase === "json")) {
|
|
2356
|
+
return true;
|
|
2390
2357
|
}
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2358
|
+
const needsUsingPairs = [
|
|
2359
|
+
["integer", "boolean"],
|
|
2360
|
+
["boolean", "integer"],
|
|
2361
|
+
["text", "integer"],
|
|
2362
|
+
["text", "numeric"],
|
|
2363
|
+
["text", "boolean"],
|
|
2364
|
+
["text", "uuid"],
|
|
2365
|
+
["text", "jsonb"],
|
|
2366
|
+
["text", "json"],
|
|
2367
|
+
["varchar", "integer"],
|
|
2368
|
+
["varchar", "numeric"],
|
|
2369
|
+
["varchar", "boolean"],
|
|
2370
|
+
["varchar", "uuid"],
|
|
2371
|
+
["varchar", "jsonb"],
|
|
2372
|
+
["varchar", "json"],
|
|
2373
|
+
["character varying", "jsonb"],
|
|
2374
|
+
["character varying", "json"]
|
|
2375
|
+
];
|
|
2376
|
+
for (const [from, to] of needsUsingPairs) {
|
|
2377
|
+
if (fromBase === from && toBase === to || fromBase === to && toBase === from) {
|
|
2378
|
+
return true;
|
|
2379
|
+
}
|
|
2408
2380
|
}
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
FROM pg_attribute a
|
|
2415
|
-
WHERE a.attrelid = con.conrelid
|
|
2416
|
-
AND a.attnum = ANY(con.conkey)
|
|
2417
|
-
ORDER BY a.attnum
|
|
2418
|
-
) AS columns
|
|
2419
|
-
FROM pg_constraint con
|
|
2420
|
-
JOIN pg_class rel ON rel.oid = con.conrelid
|
|
2421
|
-
JOIN pg_namespace nsp ON nsp.oid = con.connamespace
|
|
2422
|
-
WHERE con.contype = 'u'
|
|
2423
|
-
AND nsp.nspname = ${schemaName}
|
|
2424
|
-
AND rel.relname = ${tableName}`);
|
|
2425
|
-
return getRows2(result);
|
|
2381
|
+
return false;
|
|
2382
|
+
}
|
|
2383
|
+
function formatDefaultValue(value, type) {
|
|
2384
|
+
if (value === null || value === "NULL") {
|
|
2385
|
+
return "NULL";
|
|
2426
2386
|
}
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
WHERE con.contype = 'c'
|
|
2435
|
-
AND nsp.nspname = ${schemaName}
|
|
2436
|
-
AND rel.relname = ${tableName}`);
|
|
2437
|
-
return getRows2(result);
|
|
2387
|
+
if (type && (type.toLowerCase().includes("boolean") || type.toLowerCase() === "bool")) {
|
|
2388
|
+
if (value === true || value === "true" || value === "t" || value === 1) {
|
|
2389
|
+
return "true";
|
|
2390
|
+
}
|
|
2391
|
+
if (value === false || value === "false" || value === "f" || value === 0) {
|
|
2392
|
+
return "false";
|
|
2393
|
+
}
|
|
2438
2394
|
}
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
n.nspname AS schema,
|
|
2442
|
-
t.typname AS name,
|
|
2443
|
-
e.enumlabel AS value,
|
|
2444
|
-
e.enumsortorder AS sort_order
|
|
2445
|
-
FROM pg_type t
|
|
2446
|
-
JOIN pg_enum e ON t.oid = e.enumtypid
|
|
2447
|
-
JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
|
|
2448
|
-
WHERE n.nspname = ${schemaName}
|
|
2449
|
-
ORDER BY schema, name, sort_order`);
|
|
2450
|
-
return getRows2(result);
|
|
2395
|
+
if (type?.match(/^(integer|bigint|smallint|numeric|decimal|real|double)/i)) {
|
|
2396
|
+
return String(value);
|
|
2451
2397
|
}
|
|
2452
|
-
|
|
2453
|
-
if (
|
|
2454
|
-
return;
|
|
2455
|
-
const match = defaultValue.match(/^'(.*)'::/);
|
|
2456
|
-
if (match) {
|
|
2457
|
-
return `'${match[1]}'`;
|
|
2398
|
+
if (typeof value === "string") {
|
|
2399
|
+
if (value.includes("::")) {
|
|
2400
|
+
return value;
|
|
2458
2401
|
}
|
|
2459
|
-
if (
|
|
2460
|
-
return;
|
|
2402
|
+
if (value.startsWith("'") && value.endsWith("'")) {
|
|
2403
|
+
return value;
|
|
2461
2404
|
}
|
|
2462
|
-
if (
|
|
2463
|
-
|
|
2464
|
-
return "true";
|
|
2465
|
-
if (defaultValue === "false")
|
|
2466
|
-
return "false";
|
|
2405
|
+
if (value.match(/^\w+\(\)/i) || value.includes("(") && value.includes(")")) {
|
|
2406
|
+
return value;
|
|
2467
2407
|
}
|
|
2468
|
-
|
|
2408
|
+
if (value.toUpperCase().startsWith("CURRENT_")) {
|
|
2409
|
+
return value;
|
|
2410
|
+
}
|
|
2411
|
+
return `'${value.replace(/'/g, "''")}'`;
|
|
2469
2412
|
}
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2413
|
+
return String(value);
|
|
2414
|
+
}
|
|
2415
|
+
function generateCreateIndexSQL(index7) {
|
|
2416
|
+
const unique3 = index7.isUnique ? "UNIQUE " : "";
|
|
2417
|
+
const method = index7.method || "btree";
|
|
2418
|
+
const columns = index7.columns.map((c) => {
|
|
2419
|
+
if (c.isExpression) {
|
|
2420
|
+
return c.expression;
|
|
2421
|
+
}
|
|
2422
|
+
return `"${c.expression}"${c.asc === false ? " DESC" : ""}`;
|
|
2423
|
+
}).join(", ");
|
|
2424
|
+
const indexName = index7.name.includes(".") ? index7.name.split(".")[1] : index7.name;
|
|
2425
|
+
let tableRef;
|
|
2426
|
+
const indexTable = index7.table;
|
|
2427
|
+
if (indexTable?.includes(".")) {
|
|
2428
|
+
const [schema, table] = indexTable.split(".");
|
|
2429
|
+
tableRef = `"${schema}"."${table}"`;
|
|
2430
|
+
} else {
|
|
2431
|
+
tableRef = `"${indexTable || ""}"`;
|
|
2479
2432
|
}
|
|
2480
|
-
|
|
2481
|
-
|
|
2433
|
+
return `CREATE ${unique3}INDEX "${indexName}" ON ${tableRef} USING ${method} (${columns});`;
|
|
2434
|
+
}
|
|
2435
|
+
function generateDropIndexSQL(index7) {
|
|
2436
|
+
const indexNameFull = typeof index7 === "string" ? index7 : index7.name;
|
|
2437
|
+
const indexName = indexNameFull.includes(".") ? indexNameFull.split(".")[1] : indexNameFull;
|
|
2438
|
+
return `DROP INDEX IF EXISTS "${indexName}";`;
|
|
2439
|
+
}
|
|
2440
|
+
function generateCreateForeignKeySQL(fk) {
|
|
2441
|
+
const schemaFrom = fk.schemaFrom || "public";
|
|
2442
|
+
const schemaTo = fk.schemaTo || "public";
|
|
2443
|
+
const tableFrom = fk.tableFrom;
|
|
2444
|
+
const columnsFrom = fk.columnsFrom.map((c) => `"${c}"`).join(", ");
|
|
2445
|
+
const columnsTo = fk.columnsTo.map((c) => `"${c}"`).join(", ");
|
|
2446
|
+
let sql22 = `ALTER TABLE "${schemaFrom}"."${tableFrom}" ADD CONSTRAINT "${fk.name}" FOREIGN KEY (${columnsFrom}) REFERENCES "${schemaTo}"."${fk.tableTo}" (${columnsTo})`;
|
|
2447
|
+
if (fk.onDelete) {
|
|
2448
|
+
sql22 += ` ON DELETE ${fk.onDelete}`;
|
|
2449
|
+
}
|
|
2450
|
+
if (fk.onUpdate) {
|
|
2451
|
+
sql22 += ` ON UPDATE ${fk.onUpdate}`;
|
|
2452
|
+
}
|
|
2453
|
+
return `${sql22};`;
|
|
2454
|
+
}
|
|
2455
|
+
function generateDropForeignKeySQL(fk) {
|
|
2456
|
+
const [schema, tableName] = fk.tableFrom ? fk.tableFrom.includes(".") ? fk.tableFrom.split(".") : ["public", fk.tableFrom] : ["public", ""];
|
|
2457
|
+
return `ALTER TABLE "${schema}"."${tableName}" DROP CONSTRAINT "${fk.name}";`;
|
|
2458
|
+
}
|
|
2459
|
+
function generateCreateUniqueConstraintSQL(constraint) {
|
|
2460
|
+
const table = constraint.table || "";
|
|
2461
|
+
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
2462
|
+
const name = constraint.name;
|
|
2463
|
+
const columns = constraint.columns.map((c) => `"${c}"`).join(", ");
|
|
2464
|
+
let sql22 = `ALTER TABLE "${schema}"."${tableName}" ADD CONSTRAINT "${name}" UNIQUE`;
|
|
2465
|
+
if (constraint.nullsNotDistinct) {
|
|
2466
|
+
sql22 += ` NULLS NOT DISTINCT`;
|
|
2482
2467
|
}
|
|
2468
|
+
sql22 += ` (${columns});`;
|
|
2469
|
+
return sql22;
|
|
2470
|
+
}
|
|
2471
|
+
function generateDropUniqueConstraintSQL(constraint) {
|
|
2472
|
+
const table = constraint.table || "";
|
|
2473
|
+
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
2474
|
+
return `ALTER TABLE "${schema}"."${tableName}" DROP CONSTRAINT "${constraint.name}";`;
|
|
2475
|
+
}
|
|
2476
|
+
function generateCreateCheckConstraintSQL(constraint) {
|
|
2477
|
+
const table = constraint.table || "";
|
|
2478
|
+
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
2479
|
+
const name = constraint.name;
|
|
2480
|
+
const value = constraint.value;
|
|
2481
|
+
return `ALTER TABLE "${schema}"."${tableName}" ADD CONSTRAINT "${name}" CHECK (${value});`;
|
|
2483
2482
|
}
|
|
2484
|
-
|
|
2483
|
+
function generateDropCheckConstraintSQL(constraint) {
|
|
2484
|
+
const table = constraint.table || "";
|
|
2485
|
+
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
2486
|
+
return `ALTER TABLE "${schema}"."${tableName}" DROP CONSTRAINT "${constraint.name}";`;
|
|
2487
|
+
}
|
|
2488
|
+
var init_sql_generator = () => {};
|
|
2485
2489
|
|
|
2486
2490
|
// runtime-migrator/extension-manager.ts
|
|
2487
2491
|
import { logger as logger5 } from "@elizaos/core";
|
|
@@ -6032,6 +6036,546 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
6032
6036
|
await this.db.delete(pairingAllowlistTable).where(eq2(pairingAllowlistTable.id, id));
|
|
6033
6037
|
});
|
|
6034
6038
|
}
|
|
6039
|
+
async isReady() {
|
|
6040
|
+
try {
|
|
6041
|
+
await this.db.execute(sql27`SELECT 1`);
|
|
6042
|
+
return true;
|
|
6043
|
+
} catch {
|
|
6044
|
+
return false;
|
|
6045
|
+
}
|
|
6046
|
+
}
|
|
6047
|
+
async getConnection() {
|
|
6048
|
+
return this.db;
|
|
6049
|
+
}
|
|
6050
|
+
async transaction(callback, _options) {
|
|
6051
|
+
return callback(this);
|
|
6052
|
+
}
|
|
6053
|
+
async getComponentsByNaturalKeys(keys) {
|
|
6054
|
+
if (keys.length === 0)
|
|
6055
|
+
return [];
|
|
6056
|
+
const results = [];
|
|
6057
|
+
for (const key of keys) {
|
|
6058
|
+
const component = await this.getComponent(key.entityId, key.type, key.worldId, key.sourceEntityId);
|
|
6059
|
+
results.push(component);
|
|
6060
|
+
}
|
|
6061
|
+
return results;
|
|
6062
|
+
}
|
|
6063
|
+
async getComponentsForEntities(entityIds, worldId, sourceEntityId) {
|
|
6064
|
+
if (entityIds.length === 0)
|
|
6065
|
+
return [];
|
|
6066
|
+
return this.withDatabase(async () => {
|
|
6067
|
+
const conditions = [inArray(componentTable.entityId, entityIds)];
|
|
6068
|
+
if (worldId) {
|
|
6069
|
+
conditions.push(eq2(componentTable.worldId, worldId));
|
|
6070
|
+
}
|
|
6071
|
+
if (sourceEntityId) {
|
|
6072
|
+
conditions.push(eq2(componentTable.sourceEntityId, sourceEntityId));
|
|
6073
|
+
}
|
|
6074
|
+
const result = await this.db.select().from(componentTable).where(and(...conditions));
|
|
6075
|
+
return result.map((component) => ({
|
|
6076
|
+
...component,
|
|
6077
|
+
id: component.id,
|
|
6078
|
+
entityId: component.entityId,
|
|
6079
|
+
agentId: component.agentId,
|
|
6080
|
+
roomId: component.roomId,
|
|
6081
|
+
worldId: component.worldId ?? "",
|
|
6082
|
+
sourceEntityId: component.sourceEntityId ?? "",
|
|
6083
|
+
data: component.data,
|
|
6084
|
+
createdAt: component.createdAt.getTime()
|
|
6085
|
+
}));
|
|
6086
|
+
});
|
|
6087
|
+
}
|
|
6088
|
+
async createComponents(components) {
|
|
6089
|
+
if (components.length === 0)
|
|
6090
|
+
return [];
|
|
6091
|
+
return this.withDatabase(async () => {
|
|
6092
|
+
const ids = [];
|
|
6093
|
+
for (const component of components) {
|
|
6094
|
+
const success = await this.createComponent(component);
|
|
6095
|
+
if (success)
|
|
6096
|
+
ids.push(component.id);
|
|
6097
|
+
}
|
|
6098
|
+
return ids;
|
|
6099
|
+
});
|
|
6100
|
+
}
|
|
6101
|
+
async getComponentsByIds(componentIds) {
|
|
6102
|
+
if (componentIds.length === 0)
|
|
6103
|
+
return [];
|
|
6104
|
+
return this.withDatabase(async () => {
|
|
6105
|
+
const result = await this.db.select().from(componentTable).where(inArray(componentTable.id, componentIds));
|
|
6106
|
+
return result.map((component) => ({
|
|
6107
|
+
...component,
|
|
6108
|
+
id: component.id,
|
|
6109
|
+
entityId: component.entityId,
|
|
6110
|
+
agentId: component.agentId,
|
|
6111
|
+
roomId: component.roomId,
|
|
6112
|
+
worldId: component.worldId ?? "",
|
|
6113
|
+
sourceEntityId: component.sourceEntityId ?? "",
|
|
6114
|
+
data: component.data,
|
|
6115
|
+
createdAt: component.createdAt.getTime()
|
|
6116
|
+
}));
|
|
6117
|
+
});
|
|
6118
|
+
}
|
|
6119
|
+
async updateComponents(components) {
|
|
6120
|
+
for (const component of components) {
|
|
6121
|
+
await this.updateComponent(component);
|
|
6122
|
+
}
|
|
6123
|
+
}
|
|
6124
|
+
async deleteComponents(componentIds) {
|
|
6125
|
+
if (componentIds.length === 0)
|
|
6126
|
+
return;
|
|
6127
|
+
return this.withDatabase(async () => {
|
|
6128
|
+
await this.db.delete(componentTable).where(inArray(componentTable.id, componentIds));
|
|
6129
|
+
});
|
|
6130
|
+
}
|
|
6131
|
+
async upsertComponents(components, _options) {
|
|
6132
|
+
for (const component of components) {
|
|
6133
|
+
const existing = await this.getComponent(component.entityId, component.type, component.worldId, component.sourceEntityId);
|
|
6134
|
+
if (existing) {
|
|
6135
|
+
await this.updateComponent({ ...component, id: existing.id });
|
|
6136
|
+
} else {
|
|
6137
|
+
await this.createComponent(component);
|
|
6138
|
+
}
|
|
6139
|
+
}
|
|
6140
|
+
}
|
|
6141
|
+
async patchComponents(_updates, _options) {}
|
|
6142
|
+
async upsertEntities(entities) {
|
|
6143
|
+
for (const entity of entities) {
|
|
6144
|
+
const existing = await this.getEntitiesByIds([entity.id]);
|
|
6145
|
+
if (existing && existing.length > 0) {
|
|
6146
|
+
await this.updateEntity(entity);
|
|
6147
|
+
} else {
|
|
6148
|
+
await this.createEntities([entity]);
|
|
6149
|
+
}
|
|
6150
|
+
}
|
|
6151
|
+
}
|
|
6152
|
+
async queryEntities(params) {
|
|
6153
|
+
if (params.entityIds?.length) {
|
|
6154
|
+
const entities = await this.getEntitiesByIds(params.entityIds);
|
|
6155
|
+
return entities || [];
|
|
6156
|
+
}
|
|
6157
|
+
return this.withDatabase(async () => {
|
|
6158
|
+
const conditions = [];
|
|
6159
|
+
if (params.agentId) {
|
|
6160
|
+
conditions.push(eq2(entityTable.agentId, params.agentId));
|
|
6161
|
+
}
|
|
6162
|
+
if (params.componentType) {
|
|
6163
|
+
const subquery = sql27`EXISTS (
|
|
6164
|
+
SELECT 1 FROM ${componentTable}
|
|
6165
|
+
WHERE ${componentTable.entityId} = ${entityTable.id}
|
|
6166
|
+
AND ${componentTable.type} = ${params.componentType}
|
|
6167
|
+
)`;
|
|
6168
|
+
conditions.push(subquery);
|
|
6169
|
+
}
|
|
6170
|
+
let query = this.db.select().from(entityTable).where(conditions.length > 0 ? and(...conditions) : undefined);
|
|
6171
|
+
if (params.limit) {
|
|
6172
|
+
query = query.limit(params.limit);
|
|
6173
|
+
}
|
|
6174
|
+
if (params.offset) {
|
|
6175
|
+
query = query.offset(params.offset);
|
|
6176
|
+
}
|
|
6177
|
+
const result = await query;
|
|
6178
|
+
return result.map((row) => ({
|
|
6179
|
+
...row,
|
|
6180
|
+
id: row.id,
|
|
6181
|
+
agentId: row.agentId,
|
|
6182
|
+
names: row.names || [],
|
|
6183
|
+
metadata: row.metadata || {}
|
|
6184
|
+
}));
|
|
6185
|
+
});
|
|
6186
|
+
}
|
|
6187
|
+
async updateEntities(entities) {
|
|
6188
|
+
for (const entity of entities) {
|
|
6189
|
+
await this.updateEntity(entity);
|
|
6190
|
+
}
|
|
6191
|
+
}
|
|
6192
|
+
async deleteEntities(entityIds) {
|
|
6193
|
+
for (const entityId of entityIds) {
|
|
6194
|
+
await this.deleteEntity(entityId);
|
|
6195
|
+
}
|
|
6196
|
+
}
|
|
6197
|
+
async getEntitiesForRooms(roomIds, includeComponents) {
|
|
6198
|
+
const result = [];
|
|
6199
|
+
for (const roomId of roomIds) {
|
|
6200
|
+
const entities = await this.getEntitiesForRoom(roomId, includeComponents);
|
|
6201
|
+
result.push({ roomId, entities });
|
|
6202
|
+
}
|
|
6203
|
+
return result;
|
|
6204
|
+
}
|
|
6205
|
+
async createLogs(params) {
|
|
6206
|
+
for (const param of params) {
|
|
6207
|
+
await this.log(param);
|
|
6208
|
+
}
|
|
6209
|
+
}
|
|
6210
|
+
async getLogsByIds(logIds) {
|
|
6211
|
+
if (logIds.length === 0)
|
|
6212
|
+
return [];
|
|
6213
|
+
return this.withDatabase(async () => {
|
|
6214
|
+
const result = await this.db.select().from(logTable).where(inArray(logTable.id, logIds));
|
|
6215
|
+
return result.map((log) => ({
|
|
6216
|
+
...log,
|
|
6217
|
+
id: log.id,
|
|
6218
|
+
entityId: log.entityId,
|
|
6219
|
+
roomId: log.roomId,
|
|
6220
|
+
type: log.type,
|
|
6221
|
+
body: log.body,
|
|
6222
|
+
createdAt: new Date(log.createdAt)
|
|
6223
|
+
}));
|
|
6224
|
+
});
|
|
6225
|
+
}
|
|
6226
|
+
async updateLogs(logs) {
|
|
6227
|
+
return this.withDatabase(async () => {
|
|
6228
|
+
for (const { id, updates } of logs) {
|
|
6229
|
+
const setValues = {};
|
|
6230
|
+
if (updates.body !== undefined)
|
|
6231
|
+
setValues.body = updates.body;
|
|
6232
|
+
if (updates.type !== undefined)
|
|
6233
|
+
setValues.type = updates.type;
|
|
6234
|
+
if (Object.keys(setValues).length > 0) {
|
|
6235
|
+
await this.db.update(logTable).set(setValues).where(eq2(logTable.id, id));
|
|
6236
|
+
}
|
|
6237
|
+
}
|
|
6238
|
+
});
|
|
6239
|
+
}
|
|
6240
|
+
async deleteLogs(logIds) {
|
|
6241
|
+
if (logIds.length === 0)
|
|
6242
|
+
return;
|
|
6243
|
+
return this.withDatabase(async () => {
|
|
6244
|
+
await this.db.delete(logTable).where(inArray(logTable.id, logIds));
|
|
6245
|
+
});
|
|
6246
|
+
}
|
|
6247
|
+
async createMemories(memories) {
|
|
6248
|
+
const ids = [];
|
|
6249
|
+
for (const { memory, tableName, unique: unique3 } of memories) {
|
|
6250
|
+
const memoryWithUnique = unique3 !== undefined ? { ...memory, unique: unique3 } : memory;
|
|
6251
|
+
const id = await this.createMemory(memoryWithUnique, tableName);
|
|
6252
|
+
ids.push(id);
|
|
6253
|
+
}
|
|
6254
|
+
return ids;
|
|
6255
|
+
}
|
|
6256
|
+
async updateMemories(memories) {
|
|
6257
|
+
for (const memory of memories) {
|
|
6258
|
+
await this.updateMemory(memory);
|
|
6259
|
+
}
|
|
6260
|
+
}
|
|
6261
|
+
async upsertMemories(memories, _options) {
|
|
6262
|
+
for (const { memory, tableName } of memories) {
|
|
6263
|
+
if (memory.id) {
|
|
6264
|
+
const existing = await this.getMemoryById(memory.id);
|
|
6265
|
+
if (existing) {
|
|
6266
|
+
await this.updateMemory(memory);
|
|
6267
|
+
continue;
|
|
6268
|
+
}
|
|
6269
|
+
}
|
|
6270
|
+
await this.createMemory(memory, tableName);
|
|
6271
|
+
}
|
|
6272
|
+
}
|
|
6273
|
+
async deleteMemories(memoryIds) {
|
|
6274
|
+
await this.deleteManyMemories(memoryIds);
|
|
6275
|
+
}
|
|
6276
|
+
async getWorldsByIds(worldIds) {
|
|
6277
|
+
if (worldIds.length === 0)
|
|
6278
|
+
return [];
|
|
6279
|
+
return this.withDatabase(async () => {
|
|
6280
|
+
const result = await this.db.select().from(worldTable).where(inArray(worldTable.id, worldIds));
|
|
6281
|
+
return result.map((world) => this.mapWorldResult(world));
|
|
6282
|
+
});
|
|
6283
|
+
}
|
|
6284
|
+
async createWorlds(worlds) {
|
|
6285
|
+
const ids = [];
|
|
6286
|
+
for (const world of worlds) {
|
|
6287
|
+
const id = await this.createWorld(world);
|
|
6288
|
+
ids.push(id);
|
|
6289
|
+
}
|
|
6290
|
+
return ids;
|
|
6291
|
+
}
|
|
6292
|
+
async deleteWorlds(worldIds) {
|
|
6293
|
+
for (const id of worldIds) {
|
|
6294
|
+
await this.removeWorld(id);
|
|
6295
|
+
}
|
|
6296
|
+
}
|
|
6297
|
+
async updateWorlds(worlds) {
|
|
6298
|
+
for (const world of worlds) {
|
|
6299
|
+
await this.updateWorld(world);
|
|
6300
|
+
}
|
|
6301
|
+
}
|
|
6302
|
+
async upsertWorlds(worlds) {
|
|
6303
|
+
for (const world of worlds) {
|
|
6304
|
+
const existing = await this.getWorld(world.id);
|
|
6305
|
+
if (existing) {
|
|
6306
|
+
await this.updateWorld(world);
|
|
6307
|
+
} else {
|
|
6308
|
+
await this.createWorld(world);
|
|
6309
|
+
}
|
|
6310
|
+
}
|
|
6311
|
+
}
|
|
6312
|
+
async deleteRoomsByWorldIds(worldIds) {
|
|
6313
|
+
for (const worldId of worldIds) {
|
|
6314
|
+
await this.deleteRoomsByWorldId(worldId);
|
|
6315
|
+
}
|
|
6316
|
+
}
|
|
6317
|
+
async getRoomsByWorlds(worldIds, limit, offset) {
|
|
6318
|
+
if (worldIds.length === 0)
|
|
6319
|
+
return [];
|
|
6320
|
+
return this.withDatabase(async () => {
|
|
6321
|
+
const conditions = [
|
|
6322
|
+
inArray(roomTable.worldId, worldIds),
|
|
6323
|
+
eq2(roomTable.agentId, this.agentId)
|
|
6324
|
+
];
|
|
6325
|
+
let query = this.db.select().from(roomTable).where(and(...conditions));
|
|
6326
|
+
if (offset) {
|
|
6327
|
+
query = query.offset(offset);
|
|
6328
|
+
}
|
|
6329
|
+
if (limit) {
|
|
6330
|
+
query = query.limit(limit);
|
|
6331
|
+
}
|
|
6332
|
+
const result = await query;
|
|
6333
|
+
return result.map((room) => ({
|
|
6334
|
+
...room,
|
|
6335
|
+
id: room.id,
|
|
6336
|
+
name: room.name ?? undefined,
|
|
6337
|
+
agentId: room.agentId,
|
|
6338
|
+
messageServerId: room.messageServerId,
|
|
6339
|
+
serverId: room.messageServerId,
|
|
6340
|
+
worldId: room.worldId,
|
|
6341
|
+
channelId: room.channelId,
|
|
6342
|
+
type: room.type,
|
|
6343
|
+
metadata: room.metadata
|
|
6344
|
+
}));
|
|
6345
|
+
});
|
|
6346
|
+
}
|
|
6347
|
+
async upsertRooms(rooms) {
|
|
6348
|
+
for (const room of rooms) {
|
|
6349
|
+
const existing = await this.getRoomsByIds([room.id]);
|
|
6350
|
+
if (existing && existing.length > 0) {
|
|
6351
|
+
await this.updateRoom(room);
|
|
6352
|
+
} else {
|
|
6353
|
+
await this.createRooms([room]);
|
|
6354
|
+
}
|
|
6355
|
+
}
|
|
6356
|
+
}
|
|
6357
|
+
async createRoomParticipants(entityIds, roomId) {
|
|
6358
|
+
const ids = [];
|
|
6359
|
+
for (const entityId of entityIds) {
|
|
6360
|
+
const success = await this.addParticipant(entityId, roomId);
|
|
6361
|
+
if (success) {
|
|
6362
|
+
ids.push(`${roomId}:${entityId}`);
|
|
6363
|
+
}
|
|
6364
|
+
}
|
|
6365
|
+
return ids;
|
|
6366
|
+
}
|
|
6367
|
+
async deleteParticipants(participants) {
|
|
6368
|
+
for (const { entityId, roomId } of participants) {
|
|
6369
|
+
const success = await this.removeParticipant(entityId, roomId);
|
|
6370
|
+
if (!success)
|
|
6371
|
+
return false;
|
|
6372
|
+
}
|
|
6373
|
+
return true;
|
|
6374
|
+
}
|
|
6375
|
+
async updateParticipants(participants) {
|
|
6376
|
+
for (const { entityId, roomId, updates } of participants) {
|
|
6377
|
+
if (updates.roomState !== undefined) {
|
|
6378
|
+
await this.setParticipantUserState(roomId, entityId, updates.roomState);
|
|
6379
|
+
}
|
|
6380
|
+
}
|
|
6381
|
+
}
|
|
6382
|
+
async updateRooms(rooms) {
|
|
6383
|
+
for (const room of rooms) {
|
|
6384
|
+
await this.updateRoom(room);
|
|
6385
|
+
}
|
|
6386
|
+
}
|
|
6387
|
+
async deleteRooms(roomIds) {
|
|
6388
|
+
for (const roomId of roomIds) {
|
|
6389
|
+
await this.deleteRoom(roomId);
|
|
6390
|
+
}
|
|
6391
|
+
}
|
|
6392
|
+
async getParticipantsForEntities(entityIds) {
|
|
6393
|
+
const result = [];
|
|
6394
|
+
for (const entityId of entityIds) {
|
|
6395
|
+
const participants = await this.getParticipantsForEntity(entityId);
|
|
6396
|
+
result.push(...participants);
|
|
6397
|
+
}
|
|
6398
|
+
return result;
|
|
6399
|
+
}
|
|
6400
|
+
async getParticipantsForRooms(roomIds) {
|
|
6401
|
+
const result = [];
|
|
6402
|
+
for (const roomId of roomIds) {
|
|
6403
|
+
const entityIds = await this.getParticipantsForRoom(roomId);
|
|
6404
|
+
result.push({ roomId, entityIds });
|
|
6405
|
+
}
|
|
6406
|
+
return result;
|
|
6407
|
+
}
|
|
6408
|
+
async areRoomParticipants(pairs) {
|
|
6409
|
+
const results = [];
|
|
6410
|
+
for (const { roomId, entityId } of pairs) {
|
|
6411
|
+
const isParticipant = await this.isRoomParticipant(roomId, entityId);
|
|
6412
|
+
results.push(isParticipant);
|
|
6413
|
+
}
|
|
6414
|
+
return results;
|
|
6415
|
+
}
|
|
6416
|
+
async getParticipantUserStates(pairs) {
|
|
6417
|
+
const results = [];
|
|
6418
|
+
for (const { roomId, entityId } of pairs) {
|
|
6419
|
+
const state = await this.getParticipantUserState(roomId, entityId);
|
|
6420
|
+
results.push(state);
|
|
6421
|
+
}
|
|
6422
|
+
return results;
|
|
6423
|
+
}
|
|
6424
|
+
async updateParticipantUserStates(updates) {
|
|
6425
|
+
for (const { roomId, entityId, state } of updates) {
|
|
6426
|
+
await this.setParticipantUserState(roomId, entityId, state);
|
|
6427
|
+
}
|
|
6428
|
+
}
|
|
6429
|
+
async getRelationshipsByPairs(pairs) {
|
|
6430
|
+
const results = [];
|
|
6431
|
+
for (const pair of pairs) {
|
|
6432
|
+
const rel = await this.getRelationship(pair);
|
|
6433
|
+
results.push(rel);
|
|
6434
|
+
}
|
|
6435
|
+
return results;
|
|
6436
|
+
}
|
|
6437
|
+
async createRelationships(relationships) {
|
|
6438
|
+
const ids = [];
|
|
6439
|
+
for (const rel of relationships) {
|
|
6440
|
+
const id = v4();
|
|
6441
|
+
const success = await this.createRelationship(rel);
|
|
6442
|
+
if (success)
|
|
6443
|
+
ids.push(id);
|
|
6444
|
+
}
|
|
6445
|
+
return ids;
|
|
6446
|
+
}
|
|
6447
|
+
async getRelationshipsByIds(relationshipIds) {
|
|
6448
|
+
if (relationshipIds.length === 0)
|
|
6449
|
+
return [];
|
|
6450
|
+
return this.withDatabase(async () => {
|
|
6451
|
+
const result = await this.db.select().from(relationshipTable).where(inArray(relationshipTable.id, relationshipIds));
|
|
6452
|
+
return result.map((relationship) => ({
|
|
6453
|
+
...relationship,
|
|
6454
|
+
id: relationship.id,
|
|
6455
|
+
sourceEntityId: relationship.sourceEntityId,
|
|
6456
|
+
targetEntityId: relationship.targetEntityId,
|
|
6457
|
+
agentId: relationship.agentId,
|
|
6458
|
+
tags: relationship.tags ?? [],
|
|
6459
|
+
metadata: relationship.metadata ?? {},
|
|
6460
|
+
createdAt: relationship.createdAt.toISOString()
|
|
6461
|
+
}));
|
|
6462
|
+
});
|
|
6463
|
+
}
|
|
6464
|
+
async updateRelationships(relationships) {
|
|
6465
|
+
for (const relationship of relationships) {
|
|
6466
|
+
await this.updateRelationship(relationship);
|
|
6467
|
+
}
|
|
6468
|
+
}
|
|
6469
|
+
async deleteRelationships(relationshipIds) {
|
|
6470
|
+
if (relationshipIds.length === 0)
|
|
6471
|
+
return;
|
|
6472
|
+
return this.withDatabase(async () => {
|
|
6473
|
+
await this.db.delete(relationshipTable).where(inArray(relationshipTable.id, relationshipIds));
|
|
6474
|
+
});
|
|
6475
|
+
}
|
|
6476
|
+
async getCaches(keys) {
|
|
6477
|
+
const result = new Map;
|
|
6478
|
+
for (const key of keys) {
|
|
6479
|
+
const value = await this.getCache(key);
|
|
6480
|
+
if (value !== undefined) {
|
|
6481
|
+
result.set(key, value);
|
|
6482
|
+
}
|
|
6483
|
+
}
|
|
6484
|
+
return result;
|
|
6485
|
+
}
|
|
6486
|
+
async setCaches(entries) {
|
|
6487
|
+
for (const { key, value } of entries) {
|
|
6488
|
+
const success = await this.setCache(key, value);
|
|
6489
|
+
if (!success)
|
|
6490
|
+
return false;
|
|
6491
|
+
}
|
|
6492
|
+
return true;
|
|
6493
|
+
}
|
|
6494
|
+
async deleteCaches(keys) {
|
|
6495
|
+
for (const key of keys) {
|
|
6496
|
+
const success = await this.deleteCache(key);
|
|
6497
|
+
if (!success)
|
|
6498
|
+
return false;
|
|
6499
|
+
}
|
|
6500
|
+
return true;
|
|
6501
|
+
}
|
|
6502
|
+
async createTasks(tasks) {
|
|
6503
|
+
const ids = [];
|
|
6504
|
+
for (const task of tasks) {
|
|
6505
|
+
const id = await this.createTask(task);
|
|
6506
|
+
ids.push(id);
|
|
6507
|
+
}
|
|
6508
|
+
return ids;
|
|
6509
|
+
}
|
|
6510
|
+
async getTasksByIds(taskIds) {
|
|
6511
|
+
const tasks = [];
|
|
6512
|
+
for (const taskId of taskIds) {
|
|
6513
|
+
const task = await this.getTask(taskId);
|
|
6514
|
+
if (task)
|
|
6515
|
+
tasks.push(task);
|
|
6516
|
+
}
|
|
6517
|
+
return tasks;
|
|
6518
|
+
}
|
|
6519
|
+
async updateTasks(updates) {
|
|
6520
|
+
for (const { id, task } of updates) {
|
|
6521
|
+
await this.updateTask(id, task);
|
|
6522
|
+
}
|
|
6523
|
+
}
|
|
6524
|
+
async deleteTasks(taskIds) {
|
|
6525
|
+
for (const taskId of taskIds) {
|
|
6526
|
+
await this.deleteTask(taskId);
|
|
6527
|
+
}
|
|
6528
|
+
}
|
|
6529
|
+
async getPairingAllowlists(queries) {
|
|
6530
|
+
const result = [];
|
|
6531
|
+
for (const { channel, agentId } of queries) {
|
|
6532
|
+
const entries = await this.getPairingAllowlist(channel, agentId);
|
|
6533
|
+
result.push({ channel, agentId, entries });
|
|
6534
|
+
}
|
|
6535
|
+
return result;
|
|
6536
|
+
}
|
|
6537
|
+
async createPairingRequests(requests) {
|
|
6538
|
+
const ids = [];
|
|
6539
|
+
for (const request of requests) {
|
|
6540
|
+
const id = await this.createPairingRequest(request);
|
|
6541
|
+
ids.push(id);
|
|
6542
|
+
}
|
|
6543
|
+
return ids;
|
|
6544
|
+
}
|
|
6545
|
+
async updatePairingRequests(requests) {
|
|
6546
|
+
for (const request of requests) {
|
|
6547
|
+
await this.updatePairingRequest(request);
|
|
6548
|
+
}
|
|
6549
|
+
}
|
|
6550
|
+
async deletePairingRequests(ids) {
|
|
6551
|
+
for (const id of ids) {
|
|
6552
|
+
await this.deletePairingRequest(id);
|
|
6553
|
+
}
|
|
6554
|
+
}
|
|
6555
|
+
async createPairingAllowlistEntries(entries) {
|
|
6556
|
+
const ids = [];
|
|
6557
|
+
for (const entry of entries) {
|
|
6558
|
+
const id = await this.createPairingAllowlistEntry(entry);
|
|
6559
|
+
ids.push(id);
|
|
6560
|
+
}
|
|
6561
|
+
return ids;
|
|
6562
|
+
}
|
|
6563
|
+
async updatePairingAllowlistEntries(entries) {
|
|
6564
|
+
return this.withDatabase(async () => {
|
|
6565
|
+
for (const entry of entries) {
|
|
6566
|
+
if (!entry.id)
|
|
6567
|
+
continue;
|
|
6568
|
+
await this.db.update(pairingAllowlistTable).set({
|
|
6569
|
+
metadata: entry.metadata || {}
|
|
6570
|
+
}).where(eq2(pairingAllowlistTable.id, entry.id));
|
|
6571
|
+
}
|
|
6572
|
+
});
|
|
6573
|
+
}
|
|
6574
|
+
async deletePairingAllowlistEntries(ids) {
|
|
6575
|
+
for (const id of ids) {
|
|
6576
|
+
await this.deletePairingAllowlistEntry(id);
|
|
6577
|
+
}
|
|
6578
|
+
}
|
|
6035
6579
|
}
|
|
6036
6580
|
|
|
6037
6581
|
// pg/adapter.ts
|
|
@@ -6547,5 +7091,5 @@ export {
|
|
|
6547
7091
|
DatabaseMigrationService
|
|
6548
7092
|
};
|
|
6549
7093
|
|
|
6550
|
-
//# debugId=
|
|
7094
|
+
//# debugId=42019694876F4CEA64756E2164756E21
|
|
6551
7095
|
//# sourceMappingURL=index.node.js.map
|