@elizaos/plugin-sql 2.0.0-alpha.15 → 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 +711 -708
- package/dist/browser/index.browser.js.map +7 -7
- package/dist/cjs/index.node.cjs +760 -739
- package/dist/cjs/index.node.cjs.map +5 -5
- package/dist/node/index.node.js +718 -714
- package/dist/node/index.node.js.map +5 -5
- package/package.json +1 -2
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
2276
|
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}`;
|
|
2111
|
-
}
|
|
2112
|
-
return `${sql21};`;
|
|
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}";`;
|
|
2117
|
-
}
|
|
2118
|
-
function generateCreateUniqueConstraintSQL(constraint) {
|
|
2119
|
-
const table = constraint.table || "";
|
|
2120
|
-
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
2121
|
-
const name = constraint.name;
|
|
2122
|
-
const columns = constraint.columns.map((c) => `"${c}"`).join(", ");
|
|
2123
|
-
let sql21 = `ALTER TABLE "${schema}"."${tableName}" ADD CONSTRAINT "${name}" UNIQUE`;
|
|
2124
|
-
if (constraint.nullsNotDistinct) {
|
|
2125
|
-
sql21 += ` NULLS NOT DISTINCT`;
|
|
2277
|
+
sql22 += ` DEFAULT ${defaultValue}`;
|
|
2126
2278
|
}
|
|
2127
|
-
|
|
2128
|
-
return sql21;
|
|
2279
|
+
return sql22;
|
|
2129
2280
|
}
|
|
2130
|
-
function
|
|
2131
|
-
const table = constraint.table || "";
|
|
2281
|
+
function generateAddColumnSQL(table, column, definition) {
|
|
2132
2282
|
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
2133
|
-
|
|
2283
|
+
const tableNameWithSchema = `"${schema}"."${tableName}"`;
|
|
2284
|
+
const parts = [`"${column}"`];
|
|
2285
|
+
parts.push(definition.type);
|
|
2286
|
+
if (definition.primaryKey) {
|
|
2287
|
+
parts.push("PRIMARY KEY");
|
|
2288
|
+
}
|
|
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
|
-
}
|
|
2279
|
-
async getTables(schemaName) {
|
|
2280
|
-
const result = await this.db.execute(sql21`SELECT
|
|
2281
|
-
table_schema,
|
|
2282
|
-
table_name
|
|
2283
|
-
FROM information_schema.tables
|
|
2284
|
-
WHERE table_schema = ${schemaName}
|
|
2285
|
-
AND table_type = 'BASE TABLE'
|
|
2286
|
-
ORDER BY table_name`);
|
|
2287
|
-
return getRows2(result);
|
|
2288
|
-
}
|
|
2289
|
-
async getColumns(schemaName, tableName) {
|
|
2290
|
-
const result = await this.db.execute(sql21`SELECT
|
|
2291
|
-
a.attname AS column_name,
|
|
2292
|
-
CASE
|
|
2293
|
-
WHEN a.attnotnull THEN 'NO'
|
|
2294
|
-
ELSE 'YES'
|
|
2295
|
-
END AS is_nullable,
|
|
2296
|
-
CASE
|
|
2297
|
-
WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
|
|
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);
|
|
2331
2325
|
}
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
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);
|
|
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
|
+
}
|
|
2355
2334
|
}
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
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);
|
|
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
|
+
}
|
|
2390
2344
|
}
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
AND a.attnum = ANY(con.conkey)
|
|
2399
|
-
ORDER BY a.attnum
|
|
2400
|
-
) AS columns
|
|
2401
|
-
FROM pg_constraint con
|
|
2402
|
-
JOIN pg_class rel ON rel.oid = con.conrelid
|
|
2403
|
-
JOIN pg_namespace nsp ON nsp.oid = con.connamespace
|
|
2404
|
-
WHERE con.contype = 'p'
|
|
2405
|
-
AND nsp.nspname = ${schemaName}
|
|
2406
|
-
AND rel.relname = ${tableName}`);
|
|
2407
|
-
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;
|
|
2408
2352
|
}
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
SELECT a.attname
|
|
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);
|
|
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;
|
|
2426
2357
|
}
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
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
|
+
}
|
|
2438
2380
|
}
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
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);
|
|
2381
|
+
return false;
|
|
2382
|
+
}
|
|
2383
|
+
function formatDefaultValue(value, type) {
|
|
2384
|
+
if (value === null || value === "NULL") {
|
|
2385
|
+
return "NULL";
|
|
2451
2386
|
}
|
|
2452
|
-
|
|
2453
|
-
if (
|
|
2454
|
-
return;
|
|
2455
|
-
const match = defaultValue.match(/^'(.*)'::/);
|
|
2456
|
-
if (match) {
|
|
2457
|
-
return `'${match[1]}'`;
|
|
2387
|
+
if (type && (type.toLowerCase().includes("boolean") || type.toLowerCase() === "bool")) {
|
|
2388
|
+
if (value === true || value === "true" || value === "t" || value === 1) {
|
|
2389
|
+
return "true";
|
|
2458
2390
|
}
|
|
2459
|
-
if (
|
|
2460
|
-
return;
|
|
2391
|
+
if (value === false || value === "false" || value === "f" || value === 0) {
|
|
2392
|
+
return "false";
|
|
2461
2393
|
}
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2394
|
+
}
|
|
2395
|
+
if (type?.match(/^(integer|bigint|smallint|numeric|decimal|real|double)/i)) {
|
|
2396
|
+
return String(value);
|
|
2397
|
+
}
|
|
2398
|
+
if (typeof value === "string") {
|
|
2399
|
+
if (value.includes("::")) {
|
|
2400
|
+
return value;
|
|
2467
2401
|
}
|
|
2468
|
-
|
|
2402
|
+
if (value.startsWith("'") && value.endsWith("'")) {
|
|
2403
|
+
return value;
|
|
2404
|
+
}
|
|
2405
|
+
if (value.match(/^\w+\(\)/i) || value.includes("(") && value.includes(")")) {
|
|
2406
|
+
return value;
|
|
2407
|
+
}
|
|
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}`;
|
|
2482
2452
|
}
|
|
2453
|
+
return `${sql22};`;
|
|
2483
2454
|
}
|
|
2484
|
-
|
|
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`;
|
|
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});`;
|
|
2482
|
+
}
|
|
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";
|
|
@@ -7087,5 +7091,5 @@ export {
|
|
|
7087
7091
|
DatabaseMigrationService
|
|
7088
7092
|
};
|
|
7089
7093
|
|
|
7090
|
-
//# debugId=
|
|
7094
|
+
//# debugId=42019694876F4CEA64756E2164756E21
|
|
7091
7095
|
//# sourceMappingURL=index.node.js.map
|