openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
169 lines (168 loc) • 7.7 kB
JavaScript
import { b as publishSqliteDatabaseAdmission, f as invalidateLocalSqliteSchemaAdmissions, o as getSqliteDatabaseAdmission, x as publishSqliteDatabaseSchemaChange } from "./sqlite-database-admission-DQIqro3d.mjs";
import { s as stageSqliteTransactionState } from "./sqlite-post-commit-BrUVQObC.mjs";
import { A as postgresSchemaMetadataSql, C as admitPostgresPhysicalFacts, M as postgresStoreNamespace, O as admitPostgresCapabilities, R as admitPostgresSearch, k as getAdmittedPostgresSchema } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { a as runSqliteImmediateTransactionSync } from "./sqlite-transaction-BHHu6P5-.mjs";
import { t as beginUpdatePostgresMigration } from "./update-doctor-migration-attribution-Dp_N9vmd.mjs";
import { n as databaseEngineAdapters, s as observeConnection } from "./adapters-D8O-uubH.mjs";
import { randomUUID } from "node:crypto";
//#region src/infra/database-engine/open.ts
const admissionKey = { name: "database.engine" };
function readEngineAnchor(e, t = "identity", n = false) {
try {
return t === "schema" ? [e.prepare("SELECT schema FROM openclaw_engine_anchor LIMIT 1").get()] : e.prepare("SELECT store_id, engine, schema FROM openclaw_engine_anchor").all();
} catch (e) {
if (n || !(e instanceof Error) || e.message !== "no such table: openclaw_engine_anchor") throw e;
return;
}
}
function familySetting(e) {
return `database.families.${e.id === "team_reports" ? "team-reports" : e.id}.engine`;
}
function refusePostgresAnchor(e, t) {
const n = readEngineAnchor(e, "schema");
if (n) throw new Error(`This store lives in PostgreSQL schema ${String(n[0]?.schema ?? "unknown")}; set ${familySetting(t)} to postgres and configure database.postgres.connection.`);
}
/** Reuses the physical SQLite admission exchange across worker handles and idle reopen. */
function openEngineStore(e) {
const { anchor: t } = e;
let n = e.schema;
observeConnection(t);
const r = e.input !== void 0 && n.postgres !== void 0;
const i = getSqliteDatabaseAdmission(t, admissionKey);
if (!r) {
if (i?.engine === "postgres") throw new Error(`This store lives in PostgreSQL schema ${i.namespace}; set ${familySetting(n)} to postgres and configure database.postgres.connection.`);
if (!i && e.inspectSqlite().hasEngineAnchor) refusePostgresAnchor(t, n);
e.prepareAnchor();
databaseEngineAdapters.sqlite.schema.bootstrap({
...e,
input: e.input
}, t);
publishSqliteDatabaseAdmission(t, admissionKey, { engine: "sqlite" });
return databaseEngineAdapters.sqlite.openConnection({
...e,
input: e.input
});
}
if (i?.engine === "sqlite") throw new Error(`Existing SQLite ${n.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(n)}.`);
e.prepareAnchor();
const readOrCreateAnchor = () => {
const r = e.inspectSqlite();
if (r.hasExistingData) throw new Error(`Existing SQLite ${n.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(n)}.`);
if (!r.hasEngineAnchor && e.existingOnly) throw new Error("Missing PostgreSQL anchor; restore the matching PostgreSQL schema and anchor.");
if (!r.hasEngineAnchor) t.exec("CREATE TABLE IF NOT EXISTS openclaw_engine_anchor (store_id TEXT NOT NULL, engine TEXT NOT NULL CHECK (engine = 'postgres'), schema TEXT NOT NULL)");
const i = readEngineAnchor(t, "identity", true) ?? [];
if (i.length > 1 || r.hasEngineAnchor && i.length === 0) throw new Error("Invalid engine anchor: expected exactly one identity. Restore a matching backup.");
const a = i[0];
if (a) {
if (typeof a.store_id !== "string" || a.engine !== "postgres" || typeof a.schema !== "string") throw new Error("Invalid PostgreSQL anchor identity. Restore a matching backup.");
return {
storeId: a.store_id,
namespace: a.schema
};
}
const o = randomUUID();
const s = postgresStoreNamespace(e.input.schemaPrefix, n.id, o);
t.prepare("INSERT INTO openclaw_engine_anchor (store_id, engine, schema) VALUES (?, 'postgres', ?)").run(o, s);
e.onFreshAnchor?.(t);
return {
storeId: o,
namespace: s
};
};
const a = i?.engine === "postgres" ? i : e.existingOnly ? readOrCreateAnchor() : runSqliteImmediateTransactionSync(t, readOrCreateAnchor);
const o = {
...e,
input: e.input,
...a
};
const s = databaseEngineAdapters.postgres;
const c = s.openConnection(o);
const admit = (t) => {
admitPostgresPhysicalFacts({
db: c,
namespace: a.namespace,
storeId: a.storeId,
store: n.id,
version: n.version,
schema: n,
recordSchema: t,
preserveSchemaSeal: e.existingVersion
});
e.admitPostgres?.(c, t);
};
try {
const r = n.search ? admitPostgresSearch(c, n.search, a.namespace, e.existingVersion ? 1 : n.postgresVectorSearchVersion) : void 0;
if (!i || i.engine === "postgres" && i.version !== n.version) {
admitPostgresCapabilities(c);
let t;
let r;
c.runTransaction(() => {
const i = !c.prepare("SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ?").get(a.namespace);
if (i && !e.existingOnly) {
c.exec(`CREATE SCHEMA IF NOT EXISTS "${a.namespace.replaceAll("\"", "\"\"")}"`);
c.exec(postgresSchemaMetadataSql);
}
let l;
try {
l = c.prepare("SELECT version, store_id FROM openclaw_schema_meta WHERE store = ?").get(n.id);
} catch (e) {
throw new Error("Missing PostgreSQL metadata; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.", { cause: e });
}
if (!l) {
if (e.existingOnly || !i) throw new Error("Missing PostgreSQL metadata; restore the matching PostgreSQL schema and anchor.");
s.schema.bootstrap(o, c);
} else {
if (l.store_id !== a.storeId) throw new Error(`PostgreSQL database identity mismatch: expected ${a.storeId}, found ${String(l.store_id)}. Restore the matching anchor and PostgreSQL backup.`);
if (l.version !== n.version) {
if (e.existingVersion) {
const e = n.postgresMigrations?.find((e) => e.version === Number(l.version) + 1)?.fromSchema;
if (!e) throw new Error("Missing PostgreSQL source schema for inspection");
n = {
...n,
...e,
postgresVectorDecoderVersion: e.postgresVectorDecoderVersion,
postgresVectorSearchVersion: e.postgresVectorSearchVersion,
postgresTextSearchVersion: e.postgresTextSearchVersion,
version: Number(l.version)
};
} else {
r = e.assertMigrationCurrent;
r?.();
t = beginUpdatePostgresMigration(c, r);
invalidateLocalSqliteSchemaAdmissions(c);
stageSqliteTransactionState(c, {
stage: () => {},
rollback: () => {},
commit: () => publishSqliteDatabaseSchemaChange(c),
invalidate: () => publishSqliteDatabaseSchemaChange(c)
});
const migrate = () => s.schema.migrate(o, Number(l.version), c);
if (t) t.run(migrate);
else migrate();
}
}
}
admit(!l);
}, { withCommit(e) {
r?.();
t?.beforeCommit();
e();
} }, false);
t?.committed();
} else admit(false);
if (!i || i.engine === "postgres" && i.version !== n.version) publishSqliteDatabaseAdmission(t, admissionKey, {
engine: "postgres",
...a,
version: n.version
});
r?.();
for (const e of Object.values(getAdmittedPostgresSchema(c)?.searchExtensions ?? {})) admitPostgresSearch(c, e, a.namespace, n.postgresVectorSearchVersion)?.();
return c;
} catch (t) {
if (e.closeOnFailure) return e.closeOnFailure(c, t);
c.close();
throw t;
}
}
//#endregion
export { readEngineAnchor as n, openEngineStore as t };